@popmelt.com/core 0.8.7 → 0.8.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -18
- package/dist/bridge-entry.mjs +47 -107
- package/dist/{chunk-ETDSTV4E.mjs → chunk-AX3C7GUE.mjs} +1 -1
- package/dist/cli.mjs +47 -107
- package/dist/index.d.mts +10 -1
- package/dist/index.mjs +68 -47
- package/dist/memory-legacy.d.mts +5 -1
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +6 -94
- package/dist/memory-store.mjs +3 -3
- package/dist/memory.d.mts +5 -10
- package/dist/memory.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-6UNEV3DE.mjs +182 -0
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +48 -108
- package/package.json +1 -1
- package/dist/server-FZ2YAIA5.mjs +0 -242
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as
|
|
1
|
+
import{mkdir as od,unlink as id,writeFile as rd}from"fs/promises";import{join as Ir}from"path";import{execFileSync as jc,spawn as lr}from"child_process";import{randomUUID as Ct}from"crypto";import{mkdir as Ac,readFile as pr,readdir as Mc,realpath as Ec,stat as _c,unlink as Cc,writeFile as Hn}from"fs/promises";import{createServer as $c}from"http";import{tmpdir as Oc}from"os";import{basename as Vn,dirname as Dc,isAbsolute as gr,join as $e,relative as Jc,resolve as Nc}from"path";import{fileURLToPath as Bc}from"url";function No(o,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -25,68 +25,12 @@ import{mkdir as Ad,unlink as Ed,writeFile as Md}from"fs/promises";import{join as
|
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}var
|
|
29
|
-
\u2026[truncated]`:t}function
|
|
30
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let i=t.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function
|
|
31
|
-
`)[0].slice(0,80)}`:"Bash";y.push(
|
|
32
|
-
`)}`)),
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${t.split("/").pop()}`,file:t}}}function js(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&qt(o).toLowerCase().includes("error"))return o.message}function Ut(o,e,n=[]){for(let t of e){let i=o[t];if(typeof i=="string")return i}for(let[t,i]of Object.entries(o)){if(!i||typeof i!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let r=Ut(i,e);if(r)return r}}function ao(o){let e=qt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as As,readFile as Es}from"fs/promises";import{join as co}from"path";var yn=class{constructor(e){let n=co(e,".popmelt");this.decisionsDir=co(n,"decisions")}async listDecisionIds(){try{return(await As(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Es(co(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};function ci(o,e){let n=o.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),i=Ns(t.assertionResults,e),r=Bs(i);return{status:r,summary:ot(t.summary)||ui(r),assertionResults:i,tooling:Fs(t.tooling)}}catch{}return{status:"needs_review",summary:Ls(o.trim()||"The evaluator did not return a structured result.",1e3),assertionResults:e.map(t=>({assertion:t,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]})),tooling:{chromeDevtools:"unknown",evidenceTypes:["screenshot"]}}}function di(o,e){let n=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length?[f.path]:[]),t=o.changes??[],i=n.length>0?n:t.map(f=>f.path),r=[...new Set(i.map(f=>f.map(String).join(".")).filter(Boolean))].map(f=>({kind:"model_path",value:f}));if(r.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(r.map(f=>f.value)),d=e.cases.find(f=>f.status!=="rejected"&&(f.sourceDecisionIds.some(u=>s.has(u))||(f.dependencies??[]).some(u=>u.kind==="model_path"&&c.has(u.value)))),l=(o.selectedChanges??[]).find(f=>f.label?.trim())?.label?.trim()??t.find(f=>f.label?.trim())?.label?.trim()??o.title,b=d?.id.startsWith("eval-model-")??!1,j=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length>0?[{path:f.path,value:f.value,label:f.label,detail:f.detail}]:[]),x=(j.length>0?j:t.map(f=>({path:f.path,value:f.value,label:f.label,detail:f.rationale}))).flatMap(f=>Ms(f,o.decisionIds)),m=In(o.underlyingClaim??o.summary),p=[...new Set([...d&&!b?d.assertions:[],...x,...x.length===0&&m?[m]:[]])],y=r[0].value,h=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!b?d.title:l,status:"pending",category:d?.category??h,prompt:d&&!b?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!b?d.rationale:$s(y),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...r].map(f=>[`${f.kind}:${f.value}`,f])).values()]}]}function Ms(o,e){let n=String(o.path[0]??"");if(n==="rules")return _s(o.value,e);if(n==="components"){let s=li(String(o.path[1]??o.label??"component")),c=vn(o.value),d=c?Gt(c.usage):[];if(d.length>0){let b=Ds(d),j=d.length===1?"uses":"use";return[`The ${b} ${j} the same shared implementation for the ${s} pattern.`]}if(c?.shared===!0)return[`The product uses a shared implementation for the ${s} pattern.`];let l=c?ot(c.constraint):"";if(l){let b=Cs(l,s);if(b)return[b]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=vn(o.value),d=c&&"value"in c?c.value:o.value,l=Os(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=vn(o.value),i=t?ot(t.text)||ot(t.constraint):typeof o.value=="string"?o.value:"",r=In(i||o.detail||"");return r?[r]:[]}function _s(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=vn(s),d=c?ot(c.text):"";return d?[{text:d,sources:c?Gt(c.sources):[]}]:[]}),i=t.filter(s=>s.sources.some(c=>n.has(c)));return(i.length>0?i:t.length===1?t:[]).map(s=>In(s.text)).filter(s=>!!s)}function Cs(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?kt(`Wherever ${Wt(n[1])}, the shared ${e} implementation is used instead of ${Wt(n[2])}`):In(o)}function lo(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return kt(`${ai(n[1])} is ${Wt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return kt(ai(t[1]));let i=e.match(/^Use (.+?)\.?$/i);if(i)return kt(`The product uses ${Wt(i[1])}`);let r=e.match(/^Do not (.+?)\.?$/i);return r?kt(`The product does not ${Wt(r[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":kt(e)}var In=lo;function $s(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${li(e[1]??"component")} contract across its declared product surfaces.`:e[0]==="tokens"?`Protects the ${e.slice(1).join(".")} token from implementation drift.`:e[0]==="rules"?"Protects an enforceable product rule across its declared scope.":"Protects an enforceable product expectation across its declared scope."}function vn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function li(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function Ds(o){return o.length<=1?o[0]??"":o.length===2?`${o[0]} and ${o[1]}`:`${o.slice(0,-1).join(", ")}, and ${o.at(-1)}`}function Os(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function kt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function ai(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Wt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function pi(o){return`You are running a Popmelt design eval against the current page. This is an evaluation-only task: do not edit files, do not write code, and do not create annotations.
|
|
34
|
-
|
|
35
|
-
## Eval
|
|
36
|
-
\`\`\`json
|
|
37
|
-
${JSON.stringify(o.evalCase,null,2)}
|
|
38
|
-
\`\`\`
|
|
39
|
-
|
|
40
|
-
## Scope
|
|
41
|
-
\`\`\`json
|
|
42
|
-
${JSON.stringify(o.scope,null,2)}
|
|
43
|
-
\`\`\`
|
|
44
|
-
|
|
45
|
-
## Current Design Model
|
|
46
|
-
\`\`\`json
|
|
47
|
-
${JSON.stringify(o.model??null,null,2)}
|
|
48
|
-
\`\`\`
|
|
49
|
-
|
|
50
|
-
## Evidence
|
|
51
|
-
- Current page screenshot: ${o.screenshotPath}
|
|
52
|
-
- Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
|
|
53
|
-
|
|
54
|
-
## Instructions
|
|
55
|
-
1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
|
|
56
|
-
2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
|
|
57
|
-
3. Use the screenshot as baseline evidence.
|
|
58
|
-
4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
|
|
59
|
-
5. Judge each assertion independently as "pass", "fail", or "needs_review".
|
|
60
|
-
6. Keep failures actionable and grounded in observed evidence.
|
|
61
|
-
7. Do not propose visual markers yet.
|
|
62
|
-
8. End with exactly one machine-readable <eval_run_result> block.
|
|
63
|
-
9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
|
|
64
|
-
10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
|
|
65
|
-
|
|
66
|
-
The block must be valid JSON with this shape:
|
|
67
|
-
|
|
68
|
-
\`\`\`json
|
|
69
|
-
{
|
|
70
|
-
"status": "pass",
|
|
71
|
-
"summary": "Short run summary.",
|
|
72
|
-
"assertionResults": [
|
|
73
|
-
{
|
|
74
|
-
"assertion": "Original assertion text",
|
|
75
|
-
"status": "pass",
|
|
76
|
-
"summary": "What was observed.",
|
|
77
|
-
"evidence": ["Screenshot shows ...", "DOM selector ..."]
|
|
78
|
-
}
|
|
79
|
-
],
|
|
80
|
-
"tooling": {
|
|
81
|
-
"chromeDevtools": "available",
|
|
82
|
-
"evidenceTypes": ["screenshot", "dom", "computed_styles"]
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
\`\`\`
|
|
87
|
-
|
|
88
|
-
Allowed statuses: pass, fail, needs_review.
|
|
89
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function ot(o){return typeof o=="string"?o.trim():""}function Gt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Js(o){let e=ot(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ns(o,e){let t=(Array.isArray(o)?o:[]).map(i=>{if(!i||typeof i!="object")return null;let r=i,s=ot(r.assertion);return s?{assertion:s,status:Js(r.status)??"needs_review",summary:ot(r.summary)||ui("needs_review"),evidence:Gt(r.evidence)}:null}).filter(i=>i!==null);return t.length>0?t:e.map(i=>({assertion:i,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Bs(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Fs(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=ot(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Gt(e.evidenceTypes).length>0?Gt(e.evidenceTypes):["screenshot"]}}function ui(o){return o==="pass"?"The current page appears to satisfy this eval.":o==="fail"?"The current page appears to violate this eval.":"The current page needs human review for this eval."}function Ls(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as zs}from"crypto";import{mkdir as Us,writeFile as qs}from"fs/promises";import{join as po}from"path";var wn=class{constructor(e){this.root=po(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=po(this.root,"eval-screenshots"),t=zs("sha256").update(e).digest("hex"),i=po(n,`${t}.webp`);return await Us(n,{recursive:!0}),await qs(i,e,{flag:"wx"}).catch(r=>{if(r.code!=="EEXIST")throw r}),i}};import{randomUUID as mi}from"crypto";import{mkdir as uo,readFile as mo,writeFile as bn}from"fs/promises";import{dirname as fo,join as Pt}from"path";var We="[ProjectionWorker]",Ws={version:1,runs:[]},Gs={version:1,updatedAt:0,proposals:[]},Hs=12;function Vs(o){return Array.isArray(o)?o.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function fi(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Ks(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Qs(o,e,n){let t=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let m of r){if(!m||typeof m!="object")continue;let p=m.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&i.add(y)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=r.filter(m=>{if(!m||typeof m!="object")return!1;let p=m.id,y=typeof p=="string"?d.find(h=>h&&typeof h=="object"&&h.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(m)}).length,b=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},j=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(m=>JSON.stringify(s[m])!==JSON.stringify(b[m])).length,x=Object.keys(c).filter(m=>JSON.stringify(c[m])!==JSON.stringify(j[m])).length;return{ruleCount:l,tokenSectionCount:T,componentCount:x,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(m=>!i.has(m))}}function Xs(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ys(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let i=typeof n=="number"?[]:{};return o[String(e)]=i,i}function xn(o,e,n){let t=o;for(let r=0;r<e.length-1;r++)t=Ys(t,e[r],e[r+1]);let i=e[e.length-1];t[String(i)]=Xs(n)}function hi(o,e){let n=o;for(let i=0;i<e.length-1;i++){let r=n[String(e[i])];if(!r||typeof r!="object")return;n=r}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Zs(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function ea(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function gi(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Zs(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?ea(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Sn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Pt(e,".popmelt");this.runsPath=Pt(t,"projection-runs.json"),this.legacyRunsPath=Pt(t,"materialization-runs.json"),this.proposalsPath=Pt(t,"projection-queue.json"),this.legacyProposalsPath=Pt(t,"model-proposals.json"),this.modelPath=Pt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await mo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Vs(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let i=t.key.split(".");t.value===null?hi(n,i):xn(n,i,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Hs),n=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!n.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),i=t.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(m=>m.id);console.log(`${We} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=ia(i,s),d=Ks(i,t.totalCandidateDecisionCount,c);n=mi().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let b=!0,j,T,x;try{let m=`projection-${Date.now()}`,{provider:p,result:y}=this.spawnModelAgent(m,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let h=await y;if(!h.success)b=!1,j=h.error,console.error(`${We} ${p} spawn error:`,j);else{let f=oa(h.text,r);if(f){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let R of f)xn(u,R.path,R.value);Array.isArray(u.rules)&&(u.rules=fi(u.rules));let A=Qs(u,r,s);if(f){let R=[...new Set(f.flatMap(C=>C.decisionIds))];A.coveredDecisionIds=R,A.uncoveredDecisionIds=r.filter(C=>!R.includes(C))}T=A;let D=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:T,changes:f});x=D.id,console.log(`${We} Created model proposal ${D.id} for ${r.length} decision(s)`)}else b=!1,j="No valid bounded <model-changes> block found in response",console.error(`${We} ${j}`)}}catch(m){b=!1,j=m instanceof Error?m.message:String(m),console.error(`${We} Error:`,j)}return await this.persistRun({...l,status:b?"proposed":"failed",completedAt:Date.now(),error:j,outputStats:T,proposalId:x}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:b,error:j}),{processedIds:r,success:b,error:j,runId:n,proposalId:x}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=fi(e.rules)),await bn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await uo(fo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2)),n):{...Ws,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Gs,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(t);for(let s of i.changes??[])xn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>i.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>t.createdAt-i.createdAt||t.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,n,t,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?hi(s,d.path):xn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let i=new Set(t.generatedEvalIds??[]),r=new Map((t.evalProjections??[]).map(s=>[s.evalId,s]));for(let s of n){let c=typeof s=="string"?{evalId:s,title:s,action:"created"}:s;i.add(c.evalId),r.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...i],evalProjections:[...r.values()]})}async createModelProposal(e){let n={id:mi().slice(0,8),status:"pending",title:ta(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:na(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(i=>i.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),i=null;return t.proposals=t.proposals.map(r=>r.id!==e?r:(i={...r,...n,updatedAt:Date.now()},i)),i?(t.updatedAt=Date.now(),await this.persistModelProposals(t),i):null}async persistModelProposals(e){try{await uo(fo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...i})=>i)};await bn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(i=>i.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await uo(fo(this.runsPath),{recursive:!0}),await bn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await mo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await mo(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,i){let r=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...gn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:mn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...fn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function ta(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function na(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function oa(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let i=new Set(e),r=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(j=>typeof j=="string"||typeof j=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let b=Array.isArray(d.decisionIds)?d.decisionIds.filter(j=>typeof j=="string"&&i.has(j)):[];return b.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:b,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===t.length?r:null}catch{return null}}function ia(o,e){let n=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
28
|
+
</html>`}var _r=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Cr=new Set(["default","flex","fast","priority"]);function It(o){let e=typeof o.reasoningEffort=="string"&&_r.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&Cr.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function cn(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 $r}from"child_process";import{createInterface as Or}from"readline";var Dr=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),Bo=1e5;function Jr(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Dr.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>Bo?t.slice(0,Bo)+`
|
|
29
|
+
\u2026[truncated]`:t}function dn(o,e){let{prompt:n,projectRoot:t,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:p,reasoningEffort:x,timeoutMs:j=3e5,onEvent:T}=e,b=[];d?b.push("--resume",d,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),p&&b.push("--model",p),x&&b.push("--effort",x);for(let y of s)b.push("--allowedTools",y);let f=$r(c,b,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),l=new Promise(y=>{let m,I=[],u=[],k=[],M=!1,g="",_,$,h=!1,A=setTimeout(()=>{h=!0,f.kill("SIGTERM"),setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},5e3)},j),D=Or({input:f.stdout}),B=new Set;D.on("line",V=>{if(V.trim())try{let Y=JSON.parse(V);Y.session_id&&!m&&(m=Y.session_id);let ie=Y.type??(Y.event?.type?`event.${Y.event.type}`:"unknown");if(B.add(ie),Y.type==="result"&&Y.result&&I.length===0){let N=typeof Y.result=="string"?Y.result:"";N&&(I.push(N),T?.({type:"delta",jobId:o,text:N},o))}if(Y.type==="assistant"&&Array.isArray(Y.message?.content)){typeof Y.error=="string"&&(_=Y.error);for(let N of Y.message.content){if(N.type==="text"&&N.text&&(I.push(N.text),T?.({type:"delta",jobId:o,text:N.text},o)),N.type==="tool_use"&&N.name){let pe=N.input?.file_path||N.input?.path||void 0,Z=Jr(N);if(T?.({type:"tool_use",jobId:o,tool:N.name,...pe?{file:pe}:{},...Z?{content:Z}:{}},o),N.name==="Edit"&&N.input?.file_path){let J={tool:"Edit",file_path:N.input.file_path,old_string:N.input.old_string,new_string:N.input.new_string,replace_all:N.input.replace_all};u.push(J),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:J.file_path,oldString:typeof J.old_string=="string"?J.old_string:void 0,newString:typeof J.new_string=="string"?J.new_string:void 0,replaceAll:typeof J.replace_all=="boolean"?J.replace_all:void 0})}else N.name==="Write"&&N.input?.file_path&&(u.push({tool:"Write",file_path:N.input.file_path,content:N.input.content}),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:N.input.file_path,content:typeof N.input.content=="string"?N.input.content:void 0}))}N.type==="thinking"&&N.thinking&&T?.({type:"thinking",jobId:o,text:N.thinking},o)}}Y.type==="result"&&Y.is_error===!0&&(M=!0,typeof Y.error=="string"&&(_=Y.error),typeof Y.result=="string"&&($=Y.result)),Y.type==="user"&&Y.tool_use_result?.file?.filePath&&T?.({type:"tool_use",jobId:o,tool:"Read",file:Y.tool_use_result.file.filePath},o)}catch{}});let U=[];f.stderr?.on("data",V=>{U.push(V.toString())}),f.on("close",V=>{if(clearTimeout(A),D.close(),I.length===0&&B.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...B].join(", ")}`),h)M=!0,g=`Timed out after ${Math.round(j/6e4)} minutes`;else if(V!==0&&V!==null){M=!0;let ie=U.join("").trim(),N=I.join("").trim(),pe=I.length===0&&B.size>0?` (no text captured, event types: ${[...B].join(", ")})`:"";g=ie||$||N||`Claude process exited with code ${V}${pe}`}M&&!g&&$&&(g=$);let Y=Nr(g,_);y({sessionId:m,text:I.join(""),success:!M,error:M?Y.message:void 0,errorCode:M?Y.code:void 0,recoverableError:M?Y.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:k.length>0?k:void 0})}),f.on("error",V=>{clearTimeout(A),M=!0,g=V.message,y({sessionId:m,text:I.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:k.length>0?k:void 0})})});return{process:f,result:l}}function Nr(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 Br,spawnSync as Go}from"child_process";import{readFileSync as Lr,statSync as Fr}from"fs";import{basename as qr,extname as zr,isAbsolute as Ur,relative as Wo,resolve as Gr}from"path";import{createInterface as Wr}from"readline";function Lo(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Fo=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"]),Zn=2e5,Hr=1e5,Ho=2e5;function Vo(o){let e=qr(o).toLowerCase(),n=zr(o).toLowerCase();return Fo.has(n)||Fo.has(e)}function Nt(o,e){let n=Ur(e)?e:Gr(o,e),t=Wo(o,n);return t===""||t.startsWith("..")?null:n}function ln(o,e){if(!Vo(e))return;let n=Nt(o,e);if(n)try{let t=Fr(n);return t.isFile()?t.size>Zn?{exists:!0,truncated:!0}:{exists:!0,content:Lr(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Vr(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function Kr(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 Vr(o,["patch","diff","unifiedDiff","unified_diff"])}function eo(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function zo(o,e){let n=Go("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Ho+65536});return n.status!==0?null:n.stdout??""}function Qr(o){let e=new Set;for(let n of o.split(`
|
|
30
|
+
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let i=t.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function Uo(o){let e=zo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=zo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=eo(n,Ho);return{status:e,changedFiles:Qr(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Xr(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function Yr(o,e){if(!Vo(e))return;let n=Nt(o,e);if(!n)return;let t=Wo(o,n);if(t===""||t.startsWith(".."))return;let i=Go("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Zn+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=eo(r,Zn);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Zr(o,e,n){return e.map(t=>{let i=n.has(t)?n.get(t):Yr(o,t),r=ln(o,t);return{filePath:t,...i?{before:i}:{},...r?{after:r}:{}}})}function pn(o,e){let{prompt:n,projectRoot:t,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:p=[]}=e,x=[];if(r){x.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let b of p)x.push("-c",b);s&&x.push("-m",s),x.push(r),x.push(n),i&&x.push("--image",i)}else{x.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let b of p)x.push("-c",b);s&&x.push("-m",s),x.push(n),i&&x.push("--image",i)}let j=Br("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),T=new Promise(b=>{let f,l=[],y=[],m=[],I=new Map,u=new Map,k=!1,M="",g=Wr({input:j.stdout}),_=new Set;g.on("line",h=>{if(h.trim())try{let A=JSON.parse(h),D=A.type??"unknown";if(_.add(D),D==="thread.started"&&A.thread_id&&!f&&(f=A.thread_id),(D==="item.agentMessage.delta"||D==="item/agentMessage/delta")&&A.delta?.text&&(l.push(A.delta.text),c?.({type:"delta",jobId:o,text:A.delta.text},o)),(D==="item.reasoning.delta"||D==="item/reasoning/delta")&&A.delta?.text&&c?.({type:"thinking",jobId:o,text:A.delta.text},o),(D==="item.started"||D==="item/started")&&A.item){let B=A.item.type;if(B==="command_execution"){let U=A.item.command,V=U?Lo(U):void 0,Y=Uo(t),ie=new Map;for(let pe of Y?.changedFiles??[])ie.set(pe,ln(t,pe));typeof A.item.id=="string"&&u.set(A.item.id,{...U?{rawCommand:U}:{},...V?{command:V}:{},...Y?{beforeWorktree:Y}:{},beforeSnapshots:ie});let N=V?`Bash: ${V.split(`
|
|
31
|
+
`)[0].slice(0,80)}`:"Bash";y.push(N),c?.({type:"tool_use",jobId:o,tool:"Bash",...V?{content:V}:{}},o)}else if(B==="file_change"){let U=A.item.filename||A.item.path;U&&!I.has(U)&&I.set(U,ln(t,U)),y.push(U?`Edit ${U.split("/").pop()}`:"Edit");let V=U?Nt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...V?{file:V}:{}},o)}else if(B==="file_read"){let U=A.item.filename||A.item.path;y.push(U?`Read ${U.split("/").pop()}`:"Read");let V=U?Nt(t,U)??U:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...V?{file:V}:{}},o)}else if(B==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(B==="mcp_tool_call"){let U=A.item.tool_name||A.item.name||"MCP";y.push(U),c?.({type:"tool_use",jobId:o,tool:U},o)}}if((D==="item.completed"||D==="item/completed")&&A.item){if(A.item.type==="agent_message"){let B=A.item.text;typeof B=="string"&&B&&(l.push(B),c?.({type:"delta",jobId:o,text:B},o))}else if(A.item.type==="reasoning"){let B=A.item.text;typeof B=="string"&&B&&c?.({type:"thinking",jobId:o,text:B},o)}else if(A.item.type==="file_change"&&Array.isArray(A.item.changes))for(let B of A.item.changes){let U=B.path||B.filename,V=B.kind==="add"?"Write":"Edit";if(U){y.push(`${V} ${U.split("/").pop()}`);let Y=Nt(t,U)??U;c?.({type:"tool_use",jobId:o,tool:V,file:Y},o);let ie=B,N=typeof ie.kind=="string"?ie.kind:void 0,pe=Kr(N),Z=I.get(U),J=ln(t,U);m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:pe,filePath:U,...Z?{before:Z}:{},...J?{after:J}:{},...qo(ie)?{patch:qo(ie)}:{},...N?{rawKind:N}:{}}),I.set(U,J)}}else if(A.item.type==="command_execution"){let B=typeof A.item.id=="string"?A.item.id:void 0,U=B?u.get(B):void 0,V=typeof A.item.command=="string"?A.item.command:U?.rawCommand,Y=V?Lo(V):U?.command,ie=Uo(t);if(Xr(U?.beforeWorktree,ie)){let N=[...new Set([...U?.beforeWorktree?.changedFiles??[],...ie?.changedFiles??[]])],pe=typeof A.item.aggregated_output=="string"?eo(A.item.aggregated_output,Hr):void 0,Z=typeof A.item.exit_code=="number"?A.item.exit_code:A.item.exit_code===null?null:void 0,J=typeof A.item.status=="string"?A.item.status:void 0;m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...V?{rawCommand:V}:{},...Y?{command:Y}:{},...Z!==void 0?{exitCode:Z}:{},...J?{status:J}:{},...pe?{output:pe.text}:{},...pe?.truncated?{outputTruncated:!0}:{},...U?.beforeWorktree?{beforeWorktree:U.beforeWorktree}:{},...ie?{afterWorktree:ie}:{},...N.length>0?{touchedFiles:Zr(t,N,U?.beforeSnapshots??new Map)}:{}})}B&&u.delete(B)}}D==="turn.failed"&&(k=!0,M=A.error?.message||A.message||"Turn failed")}catch{}});let $=[];j.stderr?.on("data",h=>{$.push(h.toString())}),j.on("close",h=>{g.close(),l.length===0&&_.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[..._].join(", ")}`),h!==0&&h!==null&&(k=!0,M=$.join("")||`Codex process exited with code ${h}`),b({sessionId:f,text:l.join(""),success:!k,error:k?M:void 0,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})}),j.on("error",h=>{k=!0,M=h.message,b({sessionId:f,text:l.join(""),success:!1,error:M,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:j,result:T}}import{spawn as es}from"child_process";import{createInterface as ts}from"readline";function Ko(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 Qo(o,e){let{prompt:n,projectRoot:t,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,p=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];i&&p.push(`--resume=${i}`),r&&p.push("--model",r),p.push("-p",n);let x=es(d,p,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),j=new Promise(T=>{let b,f=[],l=[],y=!1,m="",I=!1,u=setTimeout(()=>{I=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},s),k=ts({input:x.stdout}),M=new Set,g=[];k.on("line",$=>{if($.trim())try{let h=JSON.parse($),A=Lt(h);M.add(A),g.length<5&&os(A)&&g.push($.slice(0,800));let D=Bt(h,["sessionId","session_id","id"],["session","conversation","thread"]);D&&!b&&(b=D);let B=ns(h,f.length===0);B&&(f.push(B),c?.({type:"delta",jobId:o,text:B},o));let U=is(h);U&&c?.({type:"thinking",jobId:o,text:U},o);let V=rs(h);V&&(l.push(V.label),c?.({type:"tool_use",jobId:o,tool:V.tool,...V.file?{file:V.file}:{},...V.content?{content:V.content}:{}},o));let Y=ss(h);Y&&(y=!0,m=Y)}catch{}});let _=[];x.stderr?.on("data",$=>{_.push($.toString())}),x.on("close",$=>{clearTimeout(u),k.close(),f.length===0&&M.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...M].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
|
|
32
|
+
`)}`)),I?(y=!0,m=`Timed out after ${Math.round(s/6e4)} minutes`):$!==0&&$!==null&&(y=!0,m=_.join("").trim()||m||`Copilot process exited with code ${$}`);let h=y?Ko(m,r):null;T({sessionId:b,text:f.join(""),success:!y,error:h?.message,errorCode:h?.code,recoverableError:h?.recoverable,provider:"copilot",toolsUsed:l.length>0?l:void 0})}),x.on("error",$=>{clearTimeout(u);let h=Ko($.message,r);T({sessionId:b,text:f.join(""),success:!1,error:h.message,errorCode:h.code,recoverableError:h.recoverable,provider:"copilot",toolsUsed:l.length>0?l:void 0})})});return{process:x,result:j}}function Lt(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 ns(o,e=!1){let n=Lt(o).toLowerCase(),t=o.update,i=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Be(o.delta)??Be(o.content)??Be(o.message);if(n==="assistant.message"&&e)return Be(o.message)??Be(o.content)??Be(o);if(n==="result"&&e)return Be(o.result)??Be(o.output)??Be(o.message)??Be(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&to(o))return o.text;if(typeof o.message=="string"&&to(o))return o.message;if(typeof o.delta=="string"&&to(o))return o.delta}function Be(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Be).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=Be(e[n]);if(t)return t}}function os(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function is(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 rs(o){let e=Bt(o,["tool","toolName","tool_name","name"]),n=Bt(o,["command","cmd"]),t=Bt(o,["file","path","filename","filePath"]),i=Lt(o);if(n||i.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
33
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${t.split("/").pop()}`,file:t}}}function ss(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"&&Lt(o).toLowerCase().includes("error"))return o.message}function Bt(o,e,n=[]){for(let t of e){let i=o[t];if(typeof i=="string")return i}for(let[t,i]of Object.entries(o)){if(!i||typeof i!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let r=Bt(i,e);if(r)return r}}function to(o){let e=Lt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as as,readFile as cs}from"fs/promises";import{join as no}from"path";var un=class{constructor(e){let n=no(e,".popmelt");this.decisionsDir=no(n,"decisions")}async listDecisionIds(){try{return(await as(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await cs(no(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};import{createHash as ds,randomUUID as ls}from"crypto";import{mkdir as oo,readFile as Xo,readdir as Yo,rename as mn,stat as Zo,unlink as fn,writeFile as hn}from"fs/promises";import{extname as ps,join as Ue}from"path";var us=10080*60*1e3,ms=600*1e3,fs=3600*1e3;function hs(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function gs(o,e){return[...o.trim()].map(t=>t==="/"||t==="\\"||t.charCodeAt(0)<32?"-":t).join("").slice(0,120)||e}var gn=class{constructor(e){this.draftsDir=Ue(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ue(e,".popmelt","artifacts","thread-media")}async stage(e){let n=ls(),t=hs(e.mimeType),i=`${n}${t}`,r=Date.now(),s={id:n,annotationId:e.annotationId,name:gs(e.name,`pasted-context${t}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await oo(this.draftsDir,{recursive:!0});let c=Ue(this.draftsDir,i),d=Ue(this.draftsDir,`${n}.json`),p=`${c}.part`,x=`${d}.part`;return await hn(p,e.data),await mn(p,c),await hn(x,JSON.stringify(s,null,2)),await mn(x,d),s}async claim(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(delete t.releasedAt,t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async release(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(t.releasedAt=Date.now(),t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async promote(e){let n={};for(let t of e){let i=await this.readManifest(t.id);if(!i)throw new Error(`Draft attachment ${t.id} is unavailable or expired.`);if(i.annotationId!==t.annotationId)throw new Error(`Draft attachment ${t.id} does not belong to annotation ${t.annotationId}.`);let r=Ue(this.draftsDir,i.contentFile),s=await Xo(r),c=ds("sha256").update(s).digest("hex"),d=Ue(this.mediaDir,`${c}${ps(i.contentFile)||".bin"}`);await oo(this.mediaDir,{recursive:!0});try{await Zo(d)}catch{let p=`${d}.part`;await hn(p,s),await mn(p,d)}(n[t.annotationId]??=[]).push({id:i.id,name:i.name,mimeType:i.mimeType,size:i.size,kind:i.kind,path:d}),i.releasedAt=Date.now(),i.lastSeenAt=Date.now(),await this.writeManifest(i)}return n}async sweep(e=Date.now()){let n;try{n=await Yo(this.draftsDir)}catch{return}await Promise.all(n.map(async t=>{let i=Ue(this.draftsDir,t);if(t.endsWith(".part")){let c=await Zo(i).catch(()=>null);c&&e-c.mtimeMs>fs&&await fn(i).catch(()=>{});return}if(!t.endsWith(".json"))return;let r=await this.readManifest(t.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>ms:e-r.lastSeenAt>us)||await Promise.all([fn(i).catch(()=>{}),fn(Ue(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Yo(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>fn(Ue(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Xo(Ue(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await oo(this.draftsDir,{recursive:!0});let n=Ue(this.draftsDir,`${e.id}.json`),t=`${n}.part`;await hn(t,JSON.stringify(e,null,2)),await mn(t,n)}};import{randomUUID as ei}from"crypto";import{mkdir as io,readFile as ro,writeFile as yn}from"fs/promises";import{dirname as so,join as wt}from"path";var Ge="[ProjectionWorker]",ys={version:1,runs:[]},vs={version:1,updatedAt:0,proposals:[]},Is=12;function ws(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 ti(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(`${Ge} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${Ge} Rule count ${e.length} exceeds cap of 30`),e}function bs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function xs(o,e,n){let t=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let f of r){if(!f||typeof f!="object")continue;let l=f.sources;if(Array.isArray(l))for(let y of l)typeof y=="string"&&t.has(y)&&i.add(y)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],p=r.filter(f=>{if(!f||typeof f!="object")return!1;let l=f.id,y=typeof l=="string"?d.find(m=>m&&typeof m=="object"&&m.id===l):void 0;return JSON.stringify(y)!==JSON.stringify(f)}).length,x=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},j=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(f=>JSON.stringify(s[f])!==JSON.stringify(x[f])).length,b=Object.keys(c).filter(f=>JSON.stringify(c[f])!==JSON.stringify(j[f])).length;return{ruleCount:p,tokenSectionCount:T,componentCount:b,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(f=>!i.has(f))}}function Ss(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ks(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let i=typeof n=="number"?[]:{};return o[String(e)]=i,i}function vn(o,e,n){let t=o;for(let r=0;r<e.length-1;r++)t=ks(t,e[r],e[r+1]);let i=e[e.length-1];t[String(i)]=Ss(n)}function ni(o,e){let n=o;for(let i=0;i<e.length-1;i++){let r=n[String(e[i])];if(!r||typeof r!="object")return;n=r}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Ps(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 Rs(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 oi(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Ps(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Rs(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var In=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=wt(e,".popmelt");this.runsPath=wt(t,"projection-runs.json"),this.legacyRunsPath=wt(t,"materialization-runs.json"),this.proposalsPath=wt(t,"projection-queue.json"),this.legacyProposalsPath=wt(t,"model-proposals.json"),this.modelPath=wt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ro(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=ws(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let i=t.key.split(".");t.value===null?ni(n,i):vn(n,i,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Is),n=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!n.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),i=t.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(f=>f.id);console.log(`${Ge} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=Ms(i,s),d=bs(i,t.totalCandidateDecisionCount,c);n=ei().slice(0,8);let p={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(p);let x=!0,j,T,b;try{let f=`projection-${Date.now()}`,{provider:l,result:y}=this.spawnModelAgent(f,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});p={...p,provider:l},await this.persistRun(p);let m=await y;if(!m.success)x=!1,j=m.error,console.error(`${Ge} ${l} spawn error:`,j);else{let I=As(m.text,r);if(I){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of I)vn(u,g.path,g.value);Array.isArray(u.rules)&&(u.rules=ti(u.rules));let k=xs(u,r,s);if(I){let g=[...new Set(I.flatMap(_=>_.decisionIds))];k.coveredDecisionIds=g,k.uncoveredDecisionIds=r.filter(_=>!g.includes(_))}T=k;let M=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:l,model:e.model??this.options.model,outputStats:T,changes:I});b=M.id,console.log(`${Ge} Created model proposal ${M.id} for ${r.length} decision(s)`)}else x=!1,j="No valid bounded <model-changes> block found in response",console.error(`${Ge} ${j}`)}}catch(f){x=!1,j=f instanceof Error?f.message:String(f),console.error(`${Ge} Error:`,j)}return await this.persistRun({...p,status:x?"proposed":"failed",completedAt:Date.now(),error:j,outputStats:T,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:x,error:j}),{processedIds:r,success:x,error:j,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ti(e.rules)),await yn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ge} 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 io(so(this.runsPath),{recursive:!0}),await yn(this.runsPath,JSON.stringify(n,null,2)),n):{...ys,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...vs,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(t);for(let s of i.changes??[])vn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>i.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>t.createdAt-i.createdAt||t.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,n,t,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?ni(s,d.path):vn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:ei().slice(0,8),status:"pending",title:Ts(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"}.`:js(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(i=>i.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),i=null;return t.proposals=t.proposals.map(r=>r.id!==e?r:(i={...r,...n,updatedAt:Date.now()},i)),i?(t.updatedAt=Date.now(),await this.persistModelProposals(t),i):null}async persistModelProposals(e){try{await io(so(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...i})=>i)};await yn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ge} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(i=>i.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await io(so(this.runsPath),{recursive:!0}),await yn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ge} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ro(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ro(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,i){let r=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...pn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:cn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ge} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...dn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Ts(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function js(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function As(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let i=new Set(e),r=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(j=>typeof j=="string"||typeof j=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let p=d.path[0];if(p!=="tokens"&&p!=="components"&&p!=="rules")return[];if(p==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(j=>typeof j=="string"&&i.has(j)):[];return x.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:x,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===t.length?r:null}catch{return null}}function Ms(o,e){let n=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
90
34
|
Kind: ${r.kind}
|
|
91
35
|
Claim: ${r.claim}
|
|
92
36
|
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
@@ -165,75 +109,71 @@ Example:
|
|
|
165
109
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
166
110
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
167
111
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
168
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
169
|
-
`),n=[],t=null;for(let i of e){let r=i.match(
|
|
112
|
+
Include property and bindings when the decision context has class-level evidence.`}var wn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let i of this.listeners)i(e,n,t)}cancelJob(e){let n=this.queue.findIndex(i=>i.id===e);if(n>=0){let[i]=this.queue.splice(n,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as Es}from"child_process";import{readFile as si}from"fs/promises";import{homedir as co}from"os";import{join as Ke}from"path";var lo=/popmelt/i;function mt(){return{found:!1,name:null,scope:null,disabled:!1}}function bt(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Ft(o){for(let e of Object.keys(o))if(lo.test(e))return e;return null}async function bn(o){try{let e=await si(o,"utf-8");return JSON.parse(e)}catch{return null}}async function po(o){let e=co(),n=await bn(Ke(e,".claude.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=Ft(i.mcpServers);if(r)return bt(r,"user")}if(i.projects&&typeof i.projects=="object"){let s=i.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Ft(c.mcpServers);if(d){let p=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(x=>lo.test(x));return bt(d,"project",p)}}}}}let t=await bn(Ke(o,".mcp.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=Ft(i.mcpServers);if(s){let c=await ii(o,s);return bt(s,"mcp.json",c)}}let r=Ft(i);if(r&&r!=="mcpServers"){let s=await ii(o,r);return bt(r,"mcp.json",s)}}return mt()}async function ii(o,e){let n=Ke(o,".claude","settings.local.json"),t=await bn(n);if(t&&typeof t=="object"){let i=t;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var _s=/^\[mcp_servers\.([^\]]+)\]/;function Cs(o){let e=o.split(`
|
|
113
|
+
`),n=[],t=null;for(let i of e){let r=i.match(_s);r?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
170
114
|
`)}),t={name:r[1],bodyLines:[]}):i.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
115
|
`)}),t=null):t&&t.bodyLines.push(i)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
|
-
`)}),n}function
|
|
173
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
116
|
+
`)}),n}function $s(o){return/enabled\s*=\s*false/i.test(o)}async function uo(o){let e=process.env.CODEX_HOME||Ke(co(),".codex"),n=await ri(Ke(e,"config.toml"),"user");if(n.found)return n;let t=await ri(Ke(o,".codex","config.toml"),"project");return t.found?t:mt()}async function mo(o,e="copilot"){let n=await Os(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Ke(co(),".copilot"),i=await ao(Ke(t,"mcp-config.json"),"user");if(i.found)return i;let r=await ao(Ke(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await ao(Ke(o,".github","mcp.json"),"mcp.json");return s.found?s:mt()}async function Os(o){try{let e=await new Promise((n,t)=>{Es(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return ai(JSON.parse(e),"user")}catch{return mt()}}async function ao(o,e){let n=await bn(o);return ai(n,e)}function ai(o,e){if(!o||typeof o!="object")return mt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,i=Ft(t);return i?bt(i,e):mt()}async function ri(o,e){try{let n=await si(o,"utf-8"),t=Cs(n);for(let i of t)if(lo.test(i.name)){let r=$s(i.body);return bt(i.name,e,r)}}catch{}return mt()}import{execFile as ci}from"child_process";import{mkdir as Ds,readFile as di,writeFile as li}from"fs/promises";import{homedir as pi}from"os";import{dirname as Js,join as fo}from"path";var ho="https://mcp.popmelt.com/mcp";async function ui(o=ho){let e=fo(pi(),".claude.json"),n;try{let i=await di(e,"utf-8");n=JSON.parse(i)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let i of Object.keys(t))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await li(e,JSON.stringify(n,null,2)+`
|
|
117
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function mi(o=ho){let e=process.env.CODEX_HOME||fo(pi(),".codex"),n=fo(e,"config.toml"),t;try{t=await di(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ds(Js(n),{recursive:!0});let i=`
|
|
174
118
|
[mcp_servers.popmelt]
|
|
175
119
|
url = "${o}"
|
|
176
|
-
`;return await ki(n,t+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ai(o=xo,e="copilot"){let n=await fa(e);if(ha(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,i)=>{Si(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function fa(o){try{let e=await new Promise((n,t)=>{Si(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return JSON.parse(e)}catch{return null}}function ha(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Tn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:n,createdAt:i?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,i]of this.leases)i.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as Mo,readFile as pt,writeFile as _o}from"fs/promises";import{join as Xe}from"path";var ga=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function So(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(So(o).split(" ").filter(e=>e.length>2&&!ga.has(e)))}function Ei(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ya(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function va(o,e){let n=new Map,t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(So).filter(Boolean),r=jn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of ya(s)){let l=So(d.value);for(let T of i){let x=l===T?95:l.includes(T)||T.includes(l)?75:0;x>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:d.by,score:x})}let j=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(Ei(jn(l),r)*55);j>=30&&j>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:j>=45?"strong":"weak",matchedBy:"query_text",score:j})}c&&n.set(s.id,c)}return n}function Ia(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function wa(o){return Math.ceil(JSON.stringify(o).length/4)}function Ro(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(y=>{if(y.recordType!=="proposal"||i&&!i.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let h=[...o.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===y.id&&f.toState==="deferred"&&f.transitionContext?.kind==="proposal_deferral")?.transitionContext;return h?h.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||h.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||h.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||h.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||h.resurfaceWhen.includes("after_date")&&!!(h.revisitAfter&&Date.parse(t)>=Date.parse(h.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=va(n,e),d=[...c.values()].sort((y,h)=>h.score-y.score),l=jn([e.action,e.text].filter(Boolean).join(" ")),b=r.flatMap(y=>{let h=y.subjects.map(D=>c.get(D.subjectId)).filter(D=>!!D),f=Math.max(0,...h.map(D=>D.score)),u=Math.round(Ei(jn(y.claim),l)*35),A=f+u;return A>=50?[{proposal:y,proposalMatches:h,score:A}]:[]}).sort((y,h)=>h.score-y.score||y.proposal.id.localeCompare(h.proposal.id)),j=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),x=[],m=0;for(let y of b){if(x.length>=j)break;let h=y.proposal.sourceRefs.slice(0,4),f={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(A=>A.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:A,...D})=>D)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(A=>A.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ia(y.proposal,s),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:h},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...h]},u={...f,estimatedTokens:wa(f)};if(m+u.estimatedTokens>T)break;x.push(u),m+=u.estimatedTokens}let p=Math.max(0,b.length-x.length);return{packets:x,subjectMatches:d.map(({score:y,...h})=>h),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:b.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:m},uncertainty:c.size===0?"subject_unresolved":b.length===0?"no_relevant_pending_proposal":void 0}}var ba=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ko(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function An(o){return new Set(ko(o).split(" ").filter(e=>e.length>2&&!ba.has(e)))}function Mi(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function xa(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(ko).filter(Boolean),i=An([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(n.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let b=ko(l.value);for(let x of t){let m=b===x?95:b.includes(x)||x.includes(b)?75:0;m>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:m>=90?"exact":"strong",matchedBy:l.by,score:m})}let T=["/","#","[","]","="].some(x=>l.value.includes(x))?0:Math.round(Mi(An(b),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Sa(o){return Math.ceil(JSON.stringify(o).length/4)}function jt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ra(o,e){let n=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(r=>r.state==="completed"),i=t.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":t.length?"partial":"unknown",attemptIds:n.map(r=>r.id)}}function ka(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),i=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=t[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function _i(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),i=o.records.filter(C=>C.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(C=>C.recordType==="decision"&&C.state==="active"),c=r?s.filter(C=>r.has(C.id)):s,d=o.records.filter(C=>C.recordType==="implementation_attempt"),l=o.records.filter(C=>C.recordType==="verification_attempt"),b=o.records.filter(C=>C.recordType==="freshness_signal"&&C.state==="open"),j=o.records.filter(C=>C.recordType==="evidence"),T=o.records.filter(C=>C.recordType==="model_entry"),x=[...o.records].reverse().filter(C=>C.recordType==="eval_spec").filter((C,I,w)=>w.findIndex(M=>M.legacyId===C.legacyId)===I),m=xa(i,e),p=new Map(m.map(C=>[C.subjectId,C.score])),y=An([e.action,e.text].filter(Boolean).join(" ")),h=c.flatMap(C=>{let I=Math.max(0,...C.subjects.map(F=>p.get(F.subjectId)??0)),w=Math.round(Mi(An(C.claim),y)*35),M=I+w;return M>=50?[{decision:C,score:M}]:[]}).sort((C,I)=>I.score-C.score||C.decision.id.localeCompare(I.decision.id)),f=new Map;for(let C of h.slice(0,t))f.set(C.decision.id,C.decision);for(let C of o.relationships){if(!jt(C,"excepts")&&!jt(C,"contradicts"))continue;let I=s.find(M=>M.id===C.from.entityId),w=s.find(M=>M.id===C.to.entityId);!I||!w||!f.has(I.id)&&!f.has(w.id)||(f.size<t&&f.set(I.id,I),f.size<t&&f.set(w.id,w))}let u=[...f.values()],A=C=>C.from.entityType==="decision"&&C.to.entityType==="decision"&&f.has(C.from.entityId)&&f.has(C.to.entityId),D=(C,I=!1)=>{let w=new Set(C.map($=>$.id)),M=b.filter($=>$.target.entityType==="decision"&&w.has($.target.entityId)),F=new Set(o.relationships.filter($=>jt($,"excepts")&&w.has($.from.entityId)&&w.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),U=o.relationships.filter($=>jt($,"contradicts")&&w.has($.from.entityId)&&w.has($.to.entityId)).map($=>({id:$.id,decisionIds:[$.from.entityId,$.to.entityId],unresolvedQuestion:$.reason,expansionRefs:[{kind:"record",id:$.id}]})),ne=new Set(U.flatMap($=>$.decisionIds)),oe=j.filter($=>$.sourceRefs.some(Z=>Z.kind==="record"&&w.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===$.id&&Z.to.entityType==="decision"&&w.has(Z.to.entityId))),ye=Math.max(0,h.length-C.length),Y=o.relationships.some($=>jt($,"contradicts")&&A($)&&(!w.has($.from.entityId)||!w.has($.to.entityId))),V=I||ye>0||Y,q=[];m.length===0&&(e.subjectHints?.length??0)>0?q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):C.length===0&&q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),U.length&&q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:U.flatMap($=>$.expansionRefs)}),oe.some($=>$.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map($=>({kind:"record",id:$.id}))}),V&&q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let ge={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:m.map(({score:$,...Z})=>Z),modelEntries:T.filter($=>$.decisionIds.some(Z=>w.has(Z))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),evalSpecs:x.filter($=>$.decisionIds.some(Z=>w.has(Z))).map($=>({id:$.id,legacyId:$.legacyId,state:$.state,title:$.title,assertionCount:$.assertions.length,decisionIds:$.decisionIds,expansionRef:{kind:"record",id:$.id}})),decisions:C.map($=>({id:$.id,kind:$.kind,claim:$.claim,subjectIds:$.subjects.map(Z=>Z.subjectId),authority:$.authority,effectiveState:ne.has($.id)?"conflicted":F.has($.id)?"excepted":"active",freshness:M.filter(Z=>Z.target.entityId===$.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:$.id}})),conflicts:U,uncertainties:q,implementation:C.map($=>Ra($.id,d)),verification:C.map($=>ka($.id,l,M)),evidence:oe.map($=>({evidenceId:$.id,summary:$.summary,availability:$.availability,sourceRefs:$.sourceRefs})),completeness:{status:V?"truncated":"complete",omittedDecisionCount:ye,omittedEvidenceCount:0,conflictsComplete:!Y}};return ge.budget.estimatedTokens=Sa(ge),ge},R=D(u);for(;R.budget.estimatedTokens>n&&u.length>0;){let C=u.pop(),I=o.relationships.filter(w=>jt(w,"contradicts")&&(w.from.entityId===C.id||w.to.entityId===C.id)).flatMap(w=>[w.from.entityId,w.to.entityId]);u=u.filter(w=>!I.includes(w.id)),R=D(u,!0)}return R}var Pa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function At(o){return Pa.test(o)}function Ta(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ae(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function Po(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){At(n)||ae(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Ge(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ae(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function It(o,e,n,t=!1){t&&n.level==="contributor"&&ae(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ae(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ja={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},Aa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ea(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),Ge(o,`${n}.createdAt`,e.createdAt),It(o,`${n}.authority`,e.authority);let t=ja[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(i)&&ae(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Aa.has(r)&&(It(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ae(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&ae(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ae(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Ge(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ma(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Ge(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ae(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ae(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ae(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ae(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(It(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ae(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Po(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&ae(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Ge(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ae(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&ae(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&ae(o,`${n}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Ge(o,`${n}.concreteBindings[${r}].createdAt`,i.createdAt),Ge(o,`${n}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ae(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Ge(o,`${n}.appliedAt`,e.appliedAt),It(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ae(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ae(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&ae(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Po(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Po(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function _a(o,e,n){if(Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),Ge(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ae(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&ae(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?ae(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&It(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ae(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ae(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ae(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ae(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function wt(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),Ge(e,"manifest.createdAt",o.manifest.createdAt),Ge(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let h=n.get(p);h?ae(e,y,"duplicate_id",`ID is already used at ${h}.`):n.set(p,y)};o.records.forEach((p,y)=>{let h=`records[${y}]`;t(p.id,h),Ma(e,p,h,o.manifest.projectId)}),o.events.forEach((p,y)=>{let h=`events[${y}]`;t(p.id,h),Ea(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,y)=>{let h=`relationships[${y}]`;t(p.id,h),_a(e,p,h),p.projectId!==o.manifest.projectId&&ae(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,y)=>{t(p.id,`artifacts[${y}]`),Te(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let h=`tombstones[${y}]`;t(p.id,h),Te(e,`${h}.id`,p.id),Te(e,`${h}.objectId`,p.objectId),Te(e,`${h}.deletedById`,p.deletedById),Ge(e,`${h}.deletedAt`,p.deletedAt),It(e,`${h}.authority`,p.authority,!0)});let i=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),r=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,y)=>{let h=`${p.entityType}:${p.entityId}`;!i.has(h)&&!r.has(h)&&ae(e,y,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};o.events.forEach((p,y)=>s(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{s(p.from,`relationships[${y}].from`),s(p.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,y)=>{c.has(p)||ae(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,h)=>{!i.has(`${p}:${y}`)&&!r.has(`${p}:${y}`)&&ae(e,h,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let h=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${h}.granteeId`),l("participant",p.grantedById,`${h}.grantedById`),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`));break;case"observation":p.captureContext.subjectIds.forEach((f,u)=>l("subject",f,`${h}.captureContext.subjectIds[${u}]`)),p.captureContext.artifactIds.forEach((f,u)=>d(f,`${h}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":p.subjects.forEach((f,u)=>l("subject",f.subjectId,`${h}.subjects[${u}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((f,u)=>d(f,`${h}.messageArtifactIds[${u}]`)),p.resultRefs.forEach((f,u)=>s(f,`${h}.resultRefs[${u}]`));break;case"iteration":p.threadIds.forEach((f,u)=>l("thread",f,`${h}.threadIds[${u}]`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"evidence":p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"advisory_explanation":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`)),p.supersededById&&l("advisory_explanation",p.supersededById,`${h}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((f,u)=>l("iteration",f,`${h}.iterationIds[${u}]`)),p.coverageClaims.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverageClaims[${u}].decisionId`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${h}.replacesSpecId`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),(p.dependencies??[]).forEach((f,u)=>{f.kind==="subject"&&f.subjectId&&l("subject",f.subjectId,`${h}.dependencies[${u}].subjectId`)}),(p.scenarios??[]).forEach((f,u)=>{f.subjectIds?.forEach((A,D)=>l("subject",A,`${h}.scenarios[${u}].subjectIds[${D}]`))}),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${h}.evalSpecId`),p.targets.forEach((f,u)=>l(f.entityType,f.entityId,`${h}.targets[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;case"model_entry":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`));break;case"model_projection":It(e,`${h}.authority`,p.authority,!0),l("participant",p.appliedById,`${h}.appliedById`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.entryIds.forEach((f,u)=>l("model_entry",f,`${h}.entryIds[${u}]`)),p.coverage.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverage[${u}].decisionId`));break;case"freshness_signal":s(p.target,`${h}.target`),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;default:break}});let b=new Map(o.events.map(p=>[p.id,p])),j=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),T=new Map;o.events.forEach((p,y)=>{let h=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,f=T.get(h)??new Set;f.add(p.toState),T.set(h,f),f.size>1&&ae(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let x=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),m=(p,y,h,f,u)=>{if(p.level!=="delegate"||!p.grantId)return;let A=x.get(p.grantId);if(!A){ae(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(A.granteeId!==y||A.level!=="delegate")&&ae(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let D=Date.parse(h);(D<Date.parse(A.startsAt)||A.endsAt&&D>Date.parse(A.endsAt)||A.revokedAt&&D>=Date.parse(A.revokedAt))&&ae(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),A.subjectIds.length&&f.length&&!f.every(R=>A.subjectIds.includes(R))&&ae(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&m(p.authority,p.acceptedById,p.createdAt,p.subjects.map(y=>y.subjectId),`records:${p.id}.authority`);o.events.forEach((p,y)=>{let h=j.get(`${p.entity.entityType}:${p.entity.entityId}`),f=h&&"subjects"in h?h.subjects.map(u=>u.subjectId):[];m(p.authority,p.participantId,p.createdAt,f,`events[${y}].authority`)}),o.relationships.forEach((p,y)=>{if(!p.authority)return;let h=[p.from,p.to].flatMap(f=>{let u=j.get(`${f.entityType}:${f.entityId}`);return u&&"subjects"in u?u.subjects.map(A=>A.subjectId):[]});m(p.authority,p.participantId,p.createdAt,h,`relationships[${y}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let y=b.get(p.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==p.proposalId||y.toState!=="accepted")&&ae(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==p.acceptedById&&ae(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),j.has(`proposal:${p.proposalId}`)||ae(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(f=>f.relationshipType==="supersedes"&&f.to.entityType==="decision"&&f.to.entityId===p.id)||ae(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(f=>f.entity.entityType==="decision"&&f.entity.entityId===p.id&&f.toState==="revoked"&&!!f.reason?.trim())||ae(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(h=>h.recordType==="decision"&&h.proposalId===p.id)||ae(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ta(e)}function Vt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Ci(o,e,n,t,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ca(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function En(o,e){let n=[],t=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),At(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Ca(e))At(r)||n.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Ci(o,t,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Vt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Vt(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Ci(o,r,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[r,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let i={...Vt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as $a}from"crypto";import{readFile as Da,readdir as Oa,realpath as Ja}from"fs/promises";import{join as Kt,relative as Na}from"path";var Ba=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Et(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function $i(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,n,t){let r=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=$a("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function To(o,e){try{return JSON.parse(await Da(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Fa(o){let e=Et(o);if(!e)return 0;let n=0,t=i=>{let r=Et(i);if(!r){n+=1;return}for(let s of Object.values(r))t(s)};for(let i of Object.values(e))t(i);return n}function La(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Qt(o){let e=[],n=await Ja(o.projectRoot).catch(()=>o.projectRoot),t=Kt(n,".popmelt"),i=await To(Kt(t,"threads.json"),e),r=await To(Kt(t,"model.json"),e),s=Et(i),c=Et(s?.threads)??{},d=Object.entries(c).map(([$,Z])=>({key:$,value:Et(Z)})).filter($=>!!$.value),l=Kt(t,"decisions"),b=await Oa(l).catch(()=>[]),j=[];for(let $ of b.filter(Z=>Z.endsWith(".json")).sort()){let Z=Et(await To(Kt(l,$),e));Z&&j.push({file:$,value:Z})}let T=d.flatMap(({value:$})=>[$.createdAt,$.updatedAt]).filter($=>typeof $=="number"&&Number.isFinite($)),x=T.length?Math.min(...T):0,m=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=le(m,"project",m,x),y=le(m,"participant","legacy-owner",x),h=le(m,"participant","legacy-agent",x),f=le(m,"subject","project",x),u=Le(Math.max(x,...T)),A=[],D=[],R=new Map,C=new Map,I=new Map(j.map($=>[$.value.id??$.file.replace(/^d-|\.json$/g,""),$.value])),w=new Map,M=($,Z,ue,se,Oe)=>{let Je=R.get(ue);if(Je)return Je;let Re=le(m,"artifact",$,se);return D.push({id:Re,kind:Z,mediaType:Oe,location:ue,availability:"available"}),R.set(ue,Re),Re};for(let{file:$,value:Z}of j){let ue=Z.id??$.replace(/^d-|\.json$/g,""),se=Z.createdAt??x,Oe=[M(`${ue}:envelope`,"other",`.popmelt/decisions/${$}`,se,"application/json")];Z.screenshotPath&&Oe.push(M(`${ue}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,se,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Je,Re]of(Z.pastedImagePaths??[]).entries())Oe.push(M(`${ue}:image:${Je}`,"image",Re,se));w.set(ue,Oe)}let F=($,Z,ue)=>({id:$,schemaVersion:1,projectId:p,createdAt:u,participantId:Z,sourceRefs:ue}),H=($,Z)=>{A.push(Z);let ue=C.get($)??[];ue.push(Z.id),C.set($,ue)},U=[{...F(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...F(h,h,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];A.push(...U),A.push({...F(f,y,[]),recordType:"subject",subjectType:"project",label:Na(process.cwd(),n)||n,aliases:[],locators:[{id:le(m,"locator",n,x),kind:"project_root",value:n,status:"current",validFrom:Le(x),sourceRefs:[]}]});let ne=new Map,oe=($,Z)=>{let ue=ne.get($);if(ue)return ue;let se=le(m,"subject",$,Z),Oe={...F(se,y,[{kind:"external",id:$}]),createdAt:Le(Z),recordType:"subject",subjectType:"element",label:$,aliases:[],locators:[{id:le(m,"locator",$,Z),kind:"dom_selector",value:$,status:"current",validFrom:Le(Z),sourceRefs:[{kind:"external",id:$}]}]};return A.push(Oe),ne.set($,se),se};for(let{key:$,value:Z}of d){let ue=Z.id??$,se=Z.createdAt??x,Oe=le(m,"thread",ue,se),Je={kind:"thread",id:ue},Re=[],Ue=[],Ve=Array.isArray(Z.messages)?Z.messages:[],et,st,mt=0;Ve.forEach((we,at)=>{let Me=we.timestamp??se,tt=le(m,"artifact",`${ue}:message:${at}`,Me);if(Re.push(tt),D.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${at}`,availability:"available"}),R.set(`.popmelt/threads.json#/threads/${ue}/messages/${at}`,tt),we.screenshotPath&&M(`${ue}:message:${at}:screenshot`,"screenshot",we.screenshotPath,Me),we.role==="human"){et=we;let Ae=we.feedbackSummary??we.replyToQuestion;if(Ae?.trim()){let Ne=le(m,"observation",`${ue}:${at}`,Me),lt=Z.elementIdentifiers??[],Rt={...F(Ne,y,[Je,{kind:"message",id:tt}]),createdAt:Le(Me),recordType:"observation",state:"open",statement:Ae,captureContext:{subjectIds:lt.map(ht=>oe(ht,se)),artifactIds:[tt]},resolvedByIds:[]};H(ue,Rt),st=Ne,Ue.push({entityType:"observation",entityId:Ne})}return}if(we.role!=="assistant")return;let ct=we.jobId??`${ue}:${at}`,dt=le(m,"iteration",ct,Me),ft=I.get(ct),no=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",oo={...F(dt,h,[Je,{kind:"message",id:tt},...(w.get(ct)??[]).map(Ae=>({kind:"artifact",id:Ae}))]),createdAt:Le(Me),recordType:"iteration",threadIds:[Oe],startedAt:Le(et?.timestamp,Me),completedAt:Le(Me),requestSummary:$i(et?.feedbackSummary,et?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:no,execution:{provider:we.provider??ft?.provider,model:we.model??ft?.model,sessionId:we.sessionId??ft?.sessionId},artifactIds:[tt,...w.get(ct)??[]]};H(ue,oo),Ue.push({entityType:"iteration",entityId:dt});let Ft=we.resolutions??ft?.resolutions??[];for(let[Ae,Ne]of Ft.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let lt=Z.elementIdentifiers??[],Rt=(lt.length?lt:[n]).map(pn=>({subjectId:pn===n?f:oe(pn,se),role:"governed"})),ht=le(m,"proposal",`${ct}:${Ne.annotationId??"resolution"}:${Ae}`,Me),io={...F(ht,h,[Je,{kind:"iteration",id:dt}]),createdAt:Le(Me),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:Rt,subjectSemantics:Rt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$i(et?.feedbackSummary,et?.replyToQuestion,Ne.summary),iterationId:dt,inferredById:h}};H(ue,io),Ue.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ft.some(Ae=>Ae.status==="resolved")||ft?.gitDiff){let Ae=le(m,"implementation",ct,Me),Ne={...F(Ae,h,[Je,{kind:"iteration",id:dt}]),createdAt:Le(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[dt],coverageClaims:[],summary:Ft.map(lt=>lt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};H(ue,Ne),Ue.push({entityType:"implementation_attempt",entityId:Ae}),mt+=1}st&&(st=void 0)});let Nt=Ve.at(-1),Bt={...F(Oe,y,[Je]),createdAt:Le(se),recordType:"thread",state:Nt?.question?"open":"resolved",messageArtifactIds:Re,outcome:Nt?.question?"question_unresolved":mt?"implementation_only":"no_outcome",resultRefs:Ue};A.push(Bt),C.set(ue,[Oe,...C.get(ue)??[]])}let ye=Fa(r);ye&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ye} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:Le(x),updatedAt:u,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:A,events:[],relationships:[],artifacts:D,tombstones:[]},V=wt(Y),ge=(o.proofCaseIds??Ba).map($=>({legacyId:$,threadFound:d.some(({key:Z,value:ue})=>(ue.id??Z)===$),decisionEnvelopeFound:I.has($),recordIds:C.get($)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce(($,Z)=>$+(Z.value.messages?.length??0),0),decisionEnvelopes:j.length,modelEntries:ye,artifactsReferenced:D.length},imported:La(A),unresolvedAcceptance:e.filter($=>$.code==="acceptance_unresolved").length,deferredModelEntries:ye,proofCases:ge,issues:e,schemaIssues:V.issues}}}import{createHash as za}from"crypto";import{mkdir as Di,open as jo,readFile as Ao,readdir as Ua,rename as qa,unlink as Eo}from"fs/promises";import{join as it}from"path";var Wa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function _n(o){return za("sha256").update(JSON.stringify(o)).digest("hex")}function Oi(o){return _n(o)}function Ji(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let i=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(i<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let r=o.records[i];if(r.projectId!==t.projectId||r.createdAt!==t.createdAt||r.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[i]=structuredClone(t)}for(let t of e.projectionUpdates){let i=o.records.find(r=>r.recordType===t.entityType&&r.id===t.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(i.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${i.state}`);i.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ga(o,e,n){return Ji(structuredClone(o),e,n)}async function bt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await jo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
177
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await qa(n,o)}catch(i){throw await Eo(n).catch(()=>{}),i}}async function Mn(o){return JSON.parse(await Ao(o,"utf8"))}var Cn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=it(e,".popmelt","memory"),this.journalDir=it(this.memoryDir,"journal"),this.manifestPath=it(this.memoryDir,"manifest.json"),this.checkpointPath=it(this.memoryDir,"checkpoint.json"),this.lockPath=it(this.memoryDir,"writer.lock")}async initialize(e){let n=wt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Di(this.journalDir,{recursive:!0});try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Ao(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=_n(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await bt(this.checkpointPath,i),await bt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await bt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=_n(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await bt(it(this.memoryDir,t),i),e.manifest.checkpoint={file:t,sequence:i.sequence,hash:n},await bt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!At(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let i=t.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...r,hash:Oi(r)},c=Ga(t.bundle,e,n.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(i).padStart(12,"0")}-${n.transactionId}.json`;return await bt(it(this.journalDir,l),s),t.manifest.head={sequence:i,hash:s.hash},t.manifest.updatedAt=n.committedAt,await bt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Wa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Mn(this.manifestPath),n=await Mn(it(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==_n(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Ua(this.journalDir),i=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,b=new Set;for(let T of s){let x=await Mn(it(this.journalDir,T)),{hash:m,...p}=x;if(m!==Oi(p))throw new Error(`Journal hash mismatch: ${T}`);if(x.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(x.previousHash!==l)throw new Error(`Journal chain mismatch at ${T}`);if(x.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(b.has(x.transactionId))throw new Error(`Duplicate transaction ID: ${x.transactionId}`);Ji(c,x.mutation,x.committedAt),d=x.sequence,l=x.hash,b.add(x.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let j=wt(c);if(!j.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(j.issues)}`);return{bundle:c,manifest:e,transactionIds:b,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Di(this.memoryDir,{recursive:!0});let n;try{n=await jo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let i=await Mn(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await Eo(this.lockPath),n=await jo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Eo(this.lockPath).catch(()=>{})}}};import{randomBytes as Ha}from"crypto";function fe(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ha(10).toString("hex"),i=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${i}${t.slice(4,7)}-${t.slice(7,19)}`}var Va=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Ni(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Va(),l=d.records,b=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(A=>A.kind==="thread"&&A.id===e.threadId));b||(b={id:le(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(b));let j=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let A=o.records.find(D=>D.recordType==="subject"&&D.locators.some(R=>R.value===u&&R.status==="current"));A||(A={id:le(i,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(i,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(A)),j.push(A)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let A=o.records.find(D=>D.recordType==="subject"&&D.locators.some(R=>R.kind==="source_file"&&R.value===u&&R.status==="current"));A||(A={id:le(i,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(i,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(A)),j.push(A)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),x;if(T.length>0){x=le(i,"live-observation",r,e.createdAt);let u={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(A=>A.claim.trim()).join(" "),captureContext:{subjectIds:j.map(A=>A.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let m=le(i,"live-iteration",r,e.completedAt),p={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...x?[{kind:"record",id:x}]:[]],recordType:"iteration",threadIds:[b.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};l.push(p);let y=[],h=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),f=j.length>0?j:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(T.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,A]of T.entries()){let D=le(i,"live-proposal",`${r}:${u}`,e.completedAt),R=f.map(I=>({subjectId:I.id,role:"governed"})),C={id:D,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:A.claim.trim(),rationale:A.rationale?.trim()||void 0,proposedKind:A.proposedKind,subjects:R,subjectSemantics:R.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:A.sourceText?.trim()||e.requestSummary,iterationId:m,inferredById:t.id}};l.push(C),y.push(D)}if(h.length>0){let u=new Set(e.governingDecisionIds??[]),A=o.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&u.has(R.id)),D={id:le(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m}],recordType:"implementation_attempt",state:"completed",iterationIds:[m],coverageClaims:A.map(R=>({decisionId:R.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map(C=>C.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:m}]})),summary:h.map(R=>R.summary).join(" "),artifactIds:[]};l.push(D)}return{mutation:d,iterationId:m,proposalIds:y,observationId:x}}import{createHash as Ka}from"crypto";import{mkdir as Qa,open as Xa,readFile as Ya,rename as Za,unlink as ec}from"fs/promises";import{join as Bi}from"path";function Fi(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Li(o){return Ka("sha256").update(JSON.stringify(o)).digest("hex")}async function tc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Xa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Za(n,o)}catch(i){throw await ec(n).catch(()=>{}),i}}function nc(o,e,n=new Date().toISOString()){let t={},i={},r={},s=(d,l,b)=>{let j=d[l]??=[];j.includes(b)||j.push(b)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let b of[l.label,...l.aliases,...l.locators.filter(j=>j.status==="current").map(j=>j.value)]){let j=Fi(b);j&&s(t,j,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(i,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(r,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:Li(c)}}function zi(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Fi(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var $n=class{constructor(e){this.indexDir=Bi(e,".popmelt","memory","indexes"),this.indexPath=Bi(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let i=JSON.parse(await Ya(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===n.sequence&&i.journalHead.hash===n.hash&&r===Li(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let t=nc(e,n);return await Qa(this.indexDir,{recursive:!0}),await tc(this.indexPath,t),t}};var Xt="popmelt:imprint",Ui="popmelt:imprint-evidence",Mt="popmelt:imprint-relation";function Dn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Xt)?.id}function Co(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function On(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="instantiates"&&t.fromId===e?[t.toId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}var Jn=class{constructor(e){this.projectRoot=e;this.store=new Cn(e),this.indexStore=new $n(e),this.manifestPath=Xe(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await pt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let t=await Qt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Qt({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"legacy-evals-v1.json");try{let r=JSON.parse(await pt(n,"utf8"));return{migrated:!1,specs:r.specs??0,runs:r.runs??0}}catch{}let t=[],i=[];try{let r=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(r.cases)?r.cases:[]}catch{}try{let r=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));i=Array.isArray(r.runs)?r.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,i)),await Mo(e,{recursive:!0}),await _o(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:i.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:i.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Xe(this.projectRoot,".popmelt","memory","migrations"),n=Xe(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await pt(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Mo(e,{recursive:!0}),await _o(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,d=i.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=i.bundle.manifest.projectId,b=new Set(i.bundle.records.map(u=>u.id)),j=new Set(i.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(A=>A.kind==="external"&&A.uri===Mt?[A.id]:[]))),T=new Map,x=i.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let A=x.find(D=>Dn(D)===u.id);T.set(u.id,A?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let m=[],p=[],y=[],h=0;for(let u of t.explanations){let A=T.get(u.id),D=x.find(w=>w.id===A),R=[],C=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let w of C){let M=le(l,"imprint-evidence-record",w.id,Date.parse(w.createdAt));R.push(M),!b.has(M)&&(m.push({id:M,schemaVersion:1,projectId:l,createdAt:w.createdAt,participantId:c.id,sourceRefs:Co([{kind:"external",id:w.id,uri:Ui},{kind:"external",id:u.id,uri:Xt},{kind:"thread",id:w.threadId},{kind:"message",id:w.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(w.kind)?"user_feedback":"judgment",summary:w.summary,availability:"available",artifactIds:[]}),y.push({id:le(l,"imprint-evidence-link",`${u.id}:${w.id}`,Date.parse(w.createdAt)),schemaVersion:1,projectId:l,createdAt:w.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:w.id,uri:Ui}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),h+=1)}let I={id:A,schemaVersion:1,projectId:l,createdAt:D?.createdAt??u.createdAt,participantId:D?.participantId??c.id,sourceRefs:Co([...D?.sourceRefs??[],{kind:"external",id:u.id,uri:Xt}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...D?.evidenceIds??[],...R])],concreteBindings:On(t,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};D?p.push(I):m.push(I)}for(let u of t.relations){let A=T.get(u.fromId),D=T.get(u.toId);!A||!D||j.has(u.id)||y.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:Mt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"advisory_explanation",entityId:D},reason:u.rationale||"The Imprint graph connected these explanations."})}let f=new Date().toISOString();if(m.length||p.length||y.length)try{let u=await this.store.commit({records:m,recordReplacements:p,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:f});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Mo(e,{recursive:!0}),await _o(n,JSON.stringify({version:2,migratedAt:f,explanations:t.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:h}}async review(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Ro(t.bundle,i)}}async contextualize(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:_i(t.bundle,i),reviewSelection:Ro(t.bundle,i)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:En(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Qt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),i=En(t.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,n);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:t.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:fe(r),decisionId:fe(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:fe(r),replacementProposalId:fe(r),acceptanceEventId:fe(r),decisionId:fe(r),relationshipId:fe(r),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:fe(r),reason:e.reason}:{...c,action:"defer",eventId:fe(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=En(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(T=>T.message).join(" ")};let b=await this.store.commitReviewPlan(l.plan,{transactionId:fe(r),committedAt:s});await this.refreshIndex(b);let j=l.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:j,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:b.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Ni(n.bundle,e),i=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(t.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),i=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),r=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?i:r??i,c=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),b=t.bundle.manifest.projectId,j=[],T=[],x=[],m=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),p=new Map(m.flatMap(f=>{let u=Dn(f);return u?[[u,f.id]]:[]}));for(let f of e.summary.changes)if(!p.has(f.explanationId)){let u=n?.explanations.find(A=>A.id===f.explanationId);p.set(f.explanationId,le(b,"imprint-explanation",f.explanationId,Date.parse(u?.createdAt??d)))}for(let f of e.summary.changes){let u={kind:"external",id:f.explanationId,uri:Xt},A=p.get(f.explanationId),D=m.find(w=>w.id===A),R=n?.explanations.find(w=>w.id===f.explanationId),C={id:le(b,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};j.push(C);let I={id:A,schemaVersion:1,projectId:b,createdAt:D?.createdAt??R?.createdAt??d,participantId:D?.participantId??s.id,sourceRefs:Co([...D?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:R?.kind??D?.kind??"pattern",state:R?.state??f.state,statement:R?.statement??f.statement,rationale:R?.rationale??D?.rationale??e.summary.detail,scope:structuredClone(R?.scope??D?.scope??{kind:"project",values:[]}),subjectIds:D?.subjectIds??[c.id],evidenceIds:[...new Set([...D?.evidenceIds??[],C.id])],concreteBindings:R?On(n,f.explanationId):D?.concreteBindings??[],supersededById:R?.supersededBy?p.get(R.supersededBy):D?.supersededById,updatedAt:R?.updatedAt??d};D?T.push(I):j.push(I),x.push({id:le(b,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:I.id},to:{entityType:"evidence",entityId:C.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let y=new Set(t.bundle.relationships.flatMap(f=>f.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Mt?[u.id]:[])));for(let f of n?.relations??[]){let u=p.get(f.fromId),A=p.get(f.toId);!u||!A||y.has(f.id)||x.push({id:le(b,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:b,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:Mt}],recordType:"relationship",relationshipType:f.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:A},reason:f.rationale||"The Imprint graph connected these explanations."})}let h=le(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let f=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:h,committedAt:d});await this.refreshIndex(f)}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=JSON.parse(await pt(Xe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),r=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="ai"&&R.status==="active")??t;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(R=>R.recordType==="advisory_explanation"),l=new Map(d.flatMap(R=>{let C=Dn(R);return C?[[C,R]]:[]})),b=new Map([...[...l].map(([R,C])=>[R,C.id]),...e.explanations.filter(R=>!l.has(R.id)).map(R=>[R.id,le(c,"imprint-explanation",R.id,Date.parse(R.createdAt))])]),j=[],T=[],x=new Set(e.explanations.map(R=>R.id));for(let R of e.explanations){let C=l.get(R.id);if(!C){j.push({id:b.get(R.id),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:R.id,uri:Xt}],recordType:"advisory_explanation",kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:On(e,R.id),supersededById:R.supersededBy?b.get(R.supersededBy):void 0,updatedAt:R.updatedAt});continue}let I={...structuredClone(C),kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),concreteBindings:On(e,R.id),supersededById:R.supersededBy?b.get(R.supersededBy):void 0,updatedAt:R.updatedAt},w=M=>JSON.stringify({kind:M.kind,state:M.state,statement:M.statement,rationale:M.rationale,scope:M.scope,concreteBindings:M.concreteBindings,supersededById:M.supersededById,updatedAt:M.updatedAt});w(C)!==w(I)&&T.push(I)}for(let[R,C]of l)x.has(R)||C.state==="retired"||T.push({...structuredClone(C),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let m=new Set(n.bundle.tombstones.flatMap(R=>R.objectType==="relationship"?[R.objectId]:[])),p=new Map(n.bundle.relationships.flatMap(R=>{if(m.has(R.id))return[];let C=R.sourceRefs.find(I=>I.kind==="external"&&I.uri===Mt)?.id;return C?[[C,R]]:[]})),y=new Set(p.keys()),h=[];for(let R of e.relations){let C=b.get(R.fromId),I=b.get(R.toId);!C||!I||y.has(R.id)||h.push({id:le(c,"imprint-relation",R.id,Date.parse(R.createdAt)),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:R.id,uri:Mt}],recordType:"relationship",relationshipType:R.type,from:{entityType:"advisory_explanation",entityId:C},to:{entityType:"advisory_explanation",entityId:I},reason:R.rationale||"The Imprint graph connected these explanations."})}let f=new Set(e.relations.map(R=>R.id)),u=t?[...p].filter(([R])=>!f.has(R)).map(([,R])=>({id:le(c,"imprint-relationship-tombstone",R.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:R.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!j.length&&!T.length&&!h.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let A=e.updatedAt,D=le(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(A));try{let R=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:h,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:D,committedAt:A});return await this.refreshIndex(R),{status:"synced",relationships:h.length+u.length,explanations:j.length+T.length,headSequence:R.report.headSequence}}catch(R){if(!(R instanceof Error)||!R.message.includes("Transaction already exists"))throw R;return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let i of n.bundle.records)t[i.recordType]=(t[i.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:n.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!i.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),t=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>n.has(r))&&t.set(i.key,i);return[...t.values()]}async getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),i=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),r=new Map(i.map(p=>[p.id,p])),s=new Map(i.flatMap(p=>{let y=Dn(p);return y?[[y,p.id]]:[]})),c=new Set(e.map(p=>s.get(p)??p)),d=new Map(t.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),l=new Map(t.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),b=new Set(t.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),j=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),T={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=i.map(p=>{let y=p.evidenceIds.flatMap(u=>{let A=l.get(u);if(!A)return[];let D=A.sourceRefs.find(w=>w.kind==="thread")?.id,R=A.sourceRefs.find(w=>w.kind==="message")?.id,C=A.kind==="judgment"||A.kind==="user_feedback"||A.kind==="project_state"?A.kind:"other",I=d.get(A.participantId)??"unknown";return[{id:A.id,kind:C,summary:A.summary,createdAt:A.createdAt,participantKind:I,threadId:D,jobId:R}]}).sort((u,A)=>A.createdAt.localeCompare(u.createdAt)),h=t.bundle.relationships.flatMap(u=>{if(b.has(u.id))return[];if(!j.has(u.relationshipType))return[];let A=u.from.entityType==="advisory_explanation"&&u.from.entityId===p.id&&u.to.entityType==="advisory_explanation",D=u.to.entityType==="advisory_explanation"&&u.to.entityId===p.id&&u.from.entityType==="advisory_explanation";if(!A&&!D)return[];let R=A?u.to.entityId:u.from.entityId,C=r.get(R);return C?[{id:u.id,type:u.relationshipType,direction:A?"outgoing":"incoming",explanationId:C.id,statement:C.statement,rationale:u.reason}]:[]}),f=[...new Set([...p.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...y.flatMap(u=>u.threadId?[u.threadId]:[])])];return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:p.concreteBindings.map(u=>({...structuredClone(u)})),relations:h,sourceThreadIds:f,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,y)=>Number(y.needsGrounding)-Number(p.needsGrounding)||T[p.state]-T[y.state]||y.updatedAt.localeCompare(p.updatedAt)),m={total:x.filter(p=>p.state!=="retired").length,emerging:x.filter(p=>p.state==="emerging").length,testing:x.filter(p=>p.state==="testing").length,grounded:x.filter(p=>p.state==="grounded").length,challenged:x.filter(p=>p.state==="challenged").length,retired:x.filter(p=>p.state==="retired").length,needsGrounding:x.filter(p=>p.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:m,explanations:x}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let i=[...t.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(l=>l.targets.some(b=>b.entityType==="decision"&&b.entityId===c.id)).sort((l,b)=>b.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(r=>r.recordType==="decision"&&e.includes(r.id)?r.subjects.map(s=>s.subjectId):[])),i=[];for(let r of n.records)if(!(r.recordType!=="subject"||!t.has(r.id)))for(let s of r.locators.filter(c=>c.status==="current"))s.kind==="source_file"?i.push({kind:"source_file",value:s.value,subjectId:r.id}):s.kind==="route_pattern"?i.push({kind:"route",value:s.value,subjectId:r.id}):s.kind==="token_path"?i.push({kind:"model_path",value:s.value,subjectId:r.id}):(s.kind==="dom_selector"||s.kind==="file_export"||s.kind==="source_span")&&i.push({kind:"subject",value:s.value,subjectId:r.id});return[...new Map(i.map(r=>[`${r.kind}:${r.value}:${r.subjectId??""}`,r])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),i=n.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!t||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=fe(r),d=fe(r),l=fe(r),b=fe(r),j=fe(r),T=new Set(n.bundle.records.flatMap(w=>w.recordType==="model_entry"&&w.key===e.key?w.decisionIds:[])),x=n.bundle.records.filter(w=>w.recordType==="decision"&&w.state==="active"&&T.has(w.id)),m={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:i.id,role:"governed"}],y={...m,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},h={...m,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},f={...m,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},u={...m,id:b,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[l],value:e.value},A={...m,id:j,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[b],coverage:[{decisionId:l,status:"projected"}]},D={...m,id:fe(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},R=x.map(w=>({...m,id:fe(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:w.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),C=x.map(w=>({...m,id:fe(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:w.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),I=await this.store.commit({records:[y,f,u,A],events:[h,...R],relationships:[D,...C],artifacts:[],tombstones:[],projectionUpdates:x.map(w=>({entityType:"decision",entityId:w.id,fromState:"active",state:"superseded"}))},{transactionId:fe(r),committedAt:s});return await this.refreshIndex(I),{decisionId:l,entryId:b}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let i=this.latestEvalSpec(n.bundle,t.id),r=n.bundle.records.flatMap(m=>m.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===m.id||m.sourceRefs.some(y=>y.id===p))?[m.id]:[]),s=[...new Set(n.bundle.records.flatMap(m=>m.recordType==="decision"&&r.includes(m.id)?m.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:r,subjectIds:s,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(i&&JSON.stringify({state:i.state,title:i.title,category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,decisionIds:i.decisionIds,subjectIds:i.subjectIds,threadRefs:i.threadRefs,dependencies:i.dependencies??[],scenarios:i.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!l)throw new Error("No active local owner participant is available.");let b=Date.now(),j=new Date(b).toISOString(),T={id:fe(b),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:j,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...r.map(m=>({kind:"record",id:m}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:i?.id,...d,targets:r.map(m=>({entityType:"decision",entityId:m})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},x=i?[{id:fe(b),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:j,participantId:l.id,sourceRefs:[{kind:"record",id:T.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:T.id},to:{entityType:"eval_spec",entityId:i.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];n=await this.store.commit({records:[T],events:[],relationships:x,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(b),committedAt:j})}return await this.refreshIndex(n),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.tombstones.filter(s=>s.objectType==="eval_spec").map(s=>s.objectId)),t=e.records.filter(s=>s.recordType==="eval_spec").reverse().filter((s,c,d)=>d.findIndex(l=>l.legacyId===s.legacyId)===c).filter(s=>!n.has(s.id)),i=e.records.filter(s=>s.recordType==="verification_attempt"),r=e.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.targetKind==="verification_result");return t.map(s=>{let c=i.filter(b=>b.evalSpecId===s.id).sort((b,j)=>j.createdAt.localeCompare(b.createdAt))[0],d=c&&r.some(b=>b.target.entityType==="verification_attempt"&&b.target.entityId===c.id),l=s.state==="draft"?"draft":s.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:s.legacyId,canonicalSpecId:s.id,verificationState:l,title:s.title,status:s.state==="draft"?"pending":s.state==="active"?"approved":"rejected",category:s.category,prompt:s.prompt,assertions:s.assertions,rationale:s.rationale,sourceDecisionIds:s.decisionIds,sourceThreadIds:s.threadRefs,dependencies:s.dependencies??[],scenarios:s.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[i]=await this.syncEvalSpecs([{...t,...n}]);return i??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let i=n.get(t.evalSpecId);if(!i)return[];let r=t.evalRun,s=Date.parse(t.createdAt);return[{id:r?.id??t.id,evalId:i.legacyId,threadId:r?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:r?.createdAt??s,completedAt:r?.completedAt??s,durationMs:r?.durationMs??0,scope:r?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:r?.assertionResults??i.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:r?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:r?.provider,model:r?.model,screenshotPath:r?.screenshotPath,codeFingerprint:r?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,i)=>t.completedAt-i.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(T=>T.recordType==="verification_attempt"&&T.evalRun?.id===n.id))return;let i=this.latestEvalSpec(t.bundle,e.id);if(!i)return;let r=t.bundle.records.find(T=>T.recordType==="participant"&&T.status==="active"&&T.kind==="ai")??t.bundle.records.find(T=>T.recordType==="participant"&&T.status==="active");if(!r)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:i.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:i.id}],recordType:"verification_attempt",evalSpecId:i.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:r.id,name:n.model??n.provider??"Popmelt eval runner"},targets:i.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},b=i.targets.map(T=>({id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:T,reason:n.summary})),j=await this.store.commit({records:[d,l],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});await this.refreshIndex(j)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(i=>[i.id,i]));for(let i of[...n].sort((r,s)=>r.completedAt-s.completedAt)){let r=t.get(i.evalId);r&&await this.recordEvalVerification(r,i)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),i=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!i)return;let r=Date.now(),s=new Date(r).toISOString(),c={id:fe(r),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:i.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(r),committedAt:s});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),i=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),r=e.filter(d=>!i.includes(d)).map(d=>d.id);if(r.length===0)return{valid:i,discardedIds:r};let s=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!s)return{valid:i,discardedIds:r};let c=r.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(b=>({id:fe(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:b.id,objectType:"eval_spec",deletedAt:l,deletedById:s.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:fe(d),committedAt:l}),await this.refreshIndex(n)}return{valid:i,discardedIds:r}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(m=>m.recordType==="model_projection"&&m.state==="applied"&&m.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let i=n.bundle.records.filter(m=>m.recordType==="decision"&&e.decisionIds.includes(m.id)&&m.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=fe(s),l=e.changes.map(m=>{let p=m.decisionIds?.filter(f=>e.decisionIds.includes(f)),y=p?.length?p:e.decisionIds,h=[...new Set(i.filter(f=>y.includes(f.id)).flatMap(f=>f.subjects.map(u=>u.subjectId)))];return{id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:y.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:m.path.map(String).join("."),subjectIds:h,decisionIds:y,value:m.value}}),b=new Set(l.flatMap(m=>m.decisionIds)),j={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(m=>({kind:"record",id:m})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(m=>m.id),coverage:e.decisionIds.map(m=>e.coverage?.find(p=>p.decisionId===m)??{decisionId:m,status:b.has(m)?"projected":"unprojected"})},T=l.flatMap(m=>m.decisionIds.map(p=>({id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:j.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:m.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),x=await this.store.commit({records:[...l,j],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});return await this.refreshIndex(x),{projectionId:d,entryIds:l.map(m=>m.id),headSequence:x.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Qt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=zi(t,n.subjectHints??[]);return i?{...n,subjectIds:[...new Set([...n.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Ct(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function _t(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function $o(o){let e=Ct(o),n=Ct(e.authority),t=n.level,i=n.mode,r=_t(t,"authority.level",["owner","delegate","contributor"]),s=_t(i,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=Ct(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Se(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Se(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>_t(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:_t(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Ct(d);return{subjectId:Se(l.subjectId,"subjectId"),role:_t(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Do(o){let e=Ct(o),n=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Se(c,s))}},t=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Ct(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Nn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
179
|
-
`)}async function
|
|
180
|
-
`)}function
|
|
120
|
+
`;return await li(n,t+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function fi(o=ho,e="copilot"){let n=await Ns(e);if(Bs(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,i)=>{ci(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function Ns(o){try{let e=await new Promise((n,t)=>{ci(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return JSON.parse(e)}catch{return null}}function Bs(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 xn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:n,createdAt:i?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,i]of this.leases)i.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as ji,readFile as Gt,writeFile as Ai}from"fs/promises";import{join as Pt}from"path";var Ls=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function go(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Sn(o){return new Set(go(o).split(" ").filter(e=>e.length>2&&!Ls.has(e)))}function hi(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 Fs(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 qs(o,e){let n=new Map,t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(go).filter(Boolean),r=Sn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of Fs(s)){let p=go(d.value);for(let T of i){let b=p===T?95:p.includes(T)||T.includes(p)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let j=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(hi(Sn(p),r)*55);j>=30&&j>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:j>=45?"strong":"weak",matchedBy:"query_text",score:j})}c&&n.set(s.id,c)}return n}function zs(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function Us(o){return Math.ceil(JSON.stringify(o).length/4)}function yo(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(y=>{if(y.recordType!=="proposal"||i&&!i.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let m=[...o.events].reverse().find(I=>I.entity.entityType==="proposal"&&I.entity.entityId===y.id&&I.toState==="deferred"&&I.transitionContext?.kind==="proposal_deferral")?.transitionContext;return m?m.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||m.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||m.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||m.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||m.resurfaceWhen.includes("after_date")&&!!(m.revisitAfter&&Date.parse(t)>=Date.parse(m.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=qs(n,e),d=[...c.values()].sort((y,m)=>m.score-y.score),p=Sn([e.action,e.text].filter(Boolean).join(" ")),x=r.flatMap(y=>{let m=y.subjects.map(M=>c.get(M.subjectId)).filter(M=>!!M),I=Math.max(0,...m.map(M=>M.score)),u=Math.round(hi(Sn(y.claim),p)*35),k=I+u;return k>=50?[{proposal:y,proposalMatches:m,score:k}]:[]}).sort((y,m)=>m.score-y.score||y.proposal.id.localeCompare(m.proposal.id)),j=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),b=[],f=0;for(let y of x){if(b.length>=j)break;let m=y.proposal.sourceRefs.slice(0,4),I={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(k=>k.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:k,...M})=>M)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(k=>k.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:zs(y.proposal,s),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:m},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...m]},u={...I,estimatedTokens:Us(I)};if(f+u.estimatedTokens>T)break;b.push(u),f+=u.estimatedTokens}let l=Math.max(0,x.length-b.length);return{packets:b,subjectMatches:d.map(({score:y,...m})=>m),completeness:{status:l>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:l,maxEstimatedTokens:T,estimatedTokens:f},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var Gs=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function vo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function kn(o){return new Set(vo(o).split(" ").filter(e=>e.length>2&&!Gs.has(e)))}function gi(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Ws(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(vo).filter(Boolean),i=kn([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(n.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of d){let x=vo(p.value);for(let b of t){let f=x===b?95:x.includes(b)||b.includes(x)?75:0;f>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:f>=90?"exact":"strong",matchedBy:p.by,score:f})}let T=["/","#","[","]","="].some(b=>p.value.includes(b))?0:Math.round(gi(kn(x),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Hs(o){return Math.ceil(JSON.stringify(o).length/4)}function xt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Vs(o,e){let n=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(r=>r.state==="completed"),i=t.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":t.length?"partial":"unknown",attemptIds:n.map(r=>r.id)}}function Ks(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),i=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=t[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function yi(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),i=o.records.filter(g=>g.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=r?s.filter(g=>r.has(g.id)):s,d=o.records.filter(g=>g.recordType==="implementation_attempt"),p=o.records.filter(g=>g.recordType==="verification_attempt"),x=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),j=o.records.filter(g=>g.recordType==="evidence"),T=o.records.filter(g=>g.recordType==="model_entry"),b=Ws(i,e),f=new Map(b.map(g=>[g.subjectId,g.score])),l=kn([e.action,e.text].filter(Boolean).join(" ")),y=c.flatMap(g=>{let _=Math.max(0,...g.subjects.map(A=>f.get(A.subjectId)??0)),$=Math.round(gi(kn(g.claim),l)*35),h=_+$;return h>=50?[{decision:g,score:h}]:[]}).sort((g,_)=>_.score-g.score||g.decision.id.localeCompare(_.decision.id)),m=new Map;for(let g of y.slice(0,t))m.set(g.decision.id,g.decision);for(let g of o.relationships){if(!xt(g,"excepts")&&!xt(g,"contradicts"))continue;let _=s.find(h=>h.id===g.from.entityId),$=s.find(h=>h.id===g.to.entityId);!_||!$||!m.has(_.id)&&!m.has($.id)||(m.size<t&&m.set(_.id,_),m.size<t&&m.set($.id,$))}let I=[...m.values()],u=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&m.has(g.from.entityId)&&m.has(g.to.entityId),k=(g,_=!1)=>{let $=new Set(g.map(J=>J.id)),h=x.filter(J=>J.target.entityType==="decision"&&$.has(J.target.entityId)),A=new Set(o.relationships.filter(J=>xt(J,"excepts")&&$.has(J.from.entityId)&&$.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),B=o.relationships.filter(J=>xt(J,"contradicts")&&$.has(J.from.entityId)&&$.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),U=new Set(B.flatMap(J=>J.decisionIds)),V=j.filter(J=>J.sourceRefs.some(W=>W.kind==="record"&&$.has(W.id))||o.relationships.some(W=>W.relationshipType==="supports"&&W.from.entityType==="evidence"&&W.from.entityId===J.id&&W.to.entityType==="decision"&&$.has(W.to.entityId))),Y=Math.max(0,y.length-g.length),ie=o.relationships.some(J=>xt(J,"contradicts")&&u(J)&&(!$.has(J.from.entityId)||!$.has(J.to.entityId))),N=_||Y>0||ie,pe=[];b.length===0&&(e.subjectHints?.length??0)>0?pe.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&pe.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),B.length&&pe.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:B.flatMap(J=>J.expansionRefs)}),V.some(J=>J.availability!=="available")&&pe.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:V.map(J=>({kind:"record",id:J.id}))}),N&&pe.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let Z={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:b.map(({score:J,...W})=>W),modelEntries:T.filter(J=>J.decisionIds.some(W=>$.has(W))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:g.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(W=>W.subjectId),authority:J.authority,effectiveState:U.has(J.id)?"conflicted":A.has(J.id)?"excepted":"active",freshness:h.filter(W=>W.target.entityId===J.id).map(W=>W.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:B,uncertainties:pe,implementation:g.map(J=>Vs(J.id,d)),verification:g.map(J=>Ks(J.id,p,h)),evidence:V.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:N?"truncated":"complete",omittedDecisionCount:Y,omittedEvidenceCount:0,conflictsComplete:!ie}};return Z.budget.estimatedTokens=Hs(Z),Z},M=k(I);for(;M.budget.estimatedTokens>n&&I.length>0;){let g=I.pop(),_=o.relationships.filter($=>xt($,"contradicts")&&($.from.entityId===g.id||$.to.entityId===g.id)).flatMap($=>[$.from.entityId,$.to.entityId]);I=I.filter($=>!_.includes($.id)),M=k(I,!0)}return M}var Qs=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function St(o){return Qs.test(o)}function Xs(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function ee(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function Io(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Pe(o,e,n){St(n)||ee(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function We(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ee(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function ft(o,e,n,t=!1){t&&n.level==="contributor"&&ee(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ee(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Ys={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},Zs=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ea(o,e,n){Pe(o,`${n}.id`,e.id),Pe(o,`${n}.projectId`,e.projectId),Pe(o,`${n}.participantId`,e.participantId),Pe(o,`${n}.entity.entityId`,e.entity.entityId),We(o,`${n}.createdAt`,e.createdAt),ft(o,`${n}.authority`,e.authority);let t=Ys[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(i)&&ee(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Zs.has(r)&&(ft(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ee(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&ee(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ee(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&We(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function ta(o,e,n,t){Pe(o,`${n}.id`,e.id),Pe(o,`${n}.projectId`,e.projectId),Pe(o,`${n}.participantId`,e.participantId),We(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ee(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ee(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ee(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)&&ee(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(ft(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ee(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Io(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&ee(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),We(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ee(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&ee(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&ee(o,`${n}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),We(o,`${n}.concreteBindings[${r}].createdAt`,i.createdAt),We(o,`${n}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ee(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(We(o,`${n}.appliedAt`,e.appliedAt),ft(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ee(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())&&ee(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&ee(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Io(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Io(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function na(o,e,n){if(Pe(o,`${n}.id`,e.id),Pe(o,`${n}.projectId`,e.projectId),Pe(o,`${n}.participantId`,e.participantId),Pe(o,`${n}.from.entityId`,e.from.entityId),Pe(o,`${n}.to.entityId`,e.to.entityId),We(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ee(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&ee(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?ee(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&ft(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ee(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ee(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))&&ee(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ee(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function ht(o){let e=[];Pe(e,"manifest.projectId",o.manifest.projectId),We(e,"manifest.createdAt",o.manifest.createdAt),We(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(l,y)=>{let m=n.get(l);m?ee(e,y,"duplicate_id",`ID is already used at ${m}.`):n.set(l,y)};o.records.forEach((l,y)=>{let m=`records[${y}]`;t(l.id,m),ta(e,l,m,o.manifest.projectId)}),o.events.forEach((l,y)=>{let m=`events[${y}]`;t(l.id,m),ea(e,l,m),l.projectId!==o.manifest.projectId&&ee(e,`${m}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((l,y)=>{let m=`relationships[${y}]`;t(l.id,m),na(e,l,m),l.projectId!==o.manifest.projectId&&ee(e,`${m}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((l,y)=>{t(l.id,`artifacts[${y}]`),Pe(e,`artifacts[${y}].id`,l.id)}),o.tombstones.forEach((l,y)=>{let m=`tombstones[${y}]`;t(l.id,m),Pe(e,`${m}.id`,l.id),Pe(e,`${m}.objectId`,l.objectId),Pe(e,`${m}.deletedById`,l.deletedById),We(e,`${m}.deletedAt`,l.deletedAt),ft(e,`${m}.authority`,l.authority,!0)});let i=new Set(o.records.map(l=>`${l.recordType}:${l.id}`)),r=new Set(o.tombstones.map(l=>`${l.objectType}:${l.objectId}`)),s=(l,y)=>{let m=`${l.entityType}:${l.entityId}`;!i.has(m)&&!r.has(m)&&ee(e,y,"dangling_entity_reference",`No record or tombstone exists for ${m}.`)};o.events.forEach((l,y)=>s(l.entity,`events[${y}].entity`)),o.relationships.forEach((l,y)=>{s(l.from,`relationships[${y}].from`),s(l.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(l=>l.id)),d=(l,y)=>{c.has(l)||ee(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},p=(l,y,m)=>{!i.has(`${l}:${y}`)&&!r.has(`${l}:${y}`)&&ee(e,m,"dangling_entity_reference",`No ${l} record or tombstone exists.`)};o.records.forEach((l,y)=>{let m=`records[${y}]`;switch(l.recordType){case"authority_grant":p("participant",l.granteeId,`${m}.granteeId`),p("participant",l.grantedById,`${m}.grantedById`),l.subjectIds.forEach((I,u)=>p("subject",I,`${m}.subjectIds[${u}]`));break;case"observation":l.captureContext.subjectIds.forEach((I,u)=>p("subject",I,`${m}.captureContext.subjectIds[${u}]`)),l.captureContext.artifactIds.forEach((I,u)=>d(I,`${m}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":l.subjects.forEach((I,u)=>p("subject",I.subjectId,`${m}.subjects[${u}].subjectId`));break;case"thread":l.messageArtifactIds.forEach((I,u)=>d(I,`${m}.messageArtifactIds[${u}]`)),l.resultRefs.forEach((I,u)=>s(I,`${m}.resultRefs[${u}]`));break;case"iteration":l.threadIds.forEach((I,u)=>p("thread",I,`${m}.threadIds[${u}]`)),l.artifactIds.forEach((I,u)=>d(I,`${m}.artifactIds[${u}]`));break;case"evidence":l.artifactIds.forEach((I,u)=>d(I,`${m}.artifactIds[${u}]`));break;case"advisory_explanation":l.subjectIds.forEach((I,u)=>p("subject",I,`${m}.subjectIds[${u}]`)),l.evidenceIds.forEach((I,u)=>p("evidence",I,`${m}.evidenceIds[${u}]`)),l.supersededById&&p("advisory_explanation",l.supersededById,`${m}.supersededById`);break;case"implementation_attempt":l.iterationIds.forEach((I,u)=>p("iteration",I,`${m}.iterationIds[${u}]`)),l.coverageClaims.forEach((I,u)=>p("decision",I.decisionId,`${m}.coverageClaims[${u}].decisionId`)),l.artifactIds.forEach((I,u)=>d(I,`${m}.artifactIds[${u}]`));break;case"eval_spec":l.replacesSpecId&&p("eval_spec",l.replacesSpecId,`${m}.replacesSpecId`),l.decisionIds.forEach((I,u)=>p("decision",I,`${m}.decisionIds[${u}]`)),l.subjectIds.forEach((I,u)=>p("subject",I,`${m}.subjectIds[${u}]`)),(l.dependencies??[]).forEach((I,u)=>{I.kind==="subject"&&I.subjectId&&p("subject",I.subjectId,`${m}.dependencies[${u}].subjectId`)}),(l.scenarios??[]).forEach((I,u)=>{I.subjectIds?.forEach((k,M)=>p("subject",k,`${m}.scenarios[${u}].subjectIds[${M}]`))}),l.targets.forEach((I,u)=>p(I.entityType,I.entityId,`${m}.targets[${u}]`));break;case"verification_attempt":l.evalSpecId&&p("eval_spec",l.evalSpecId,`${m}.evalSpecId`),l.targets.forEach((I,u)=>p(I.entityType,I.entityId,`${m}.targets[${u}]`)),l.evidenceIds.forEach((I,u)=>p("evidence",I,`${m}.evidenceIds[${u}]`));break;case"model_entry":l.subjectIds.forEach((I,u)=>p("subject",I,`${m}.subjectIds[${u}]`)),l.decisionIds.forEach((I,u)=>p("decision",I,`${m}.decisionIds[${u}]`));break;case"model_projection":ft(e,`${m}.authority`,l.authority,!0),p("participant",l.appliedById,`${m}.appliedById`),l.decisionIds.forEach((I,u)=>p("decision",I,`${m}.decisionIds[${u}]`)),l.entryIds.forEach((I,u)=>p("model_entry",I,`${m}.entryIds[${u}]`)),l.coverage.forEach((I,u)=>p("decision",I.decisionId,`${m}.coverage[${u}].decisionId`));break;case"freshness_signal":s(l.target,`${m}.target`),l.evidenceIds.forEach((I,u)=>p("evidence",I,`${m}.evidenceIds[${u}]`));break;default:break}});let x=new Map(o.events.map(l=>[l.id,l])),j=new Map(o.records.map(l=>[`${l.recordType}:${l.id}`,l])),T=new Map;o.events.forEach((l,y)=>{let m=`${l.entity.entityType}:${l.entity.entityId}:${l.fromState??"null"}`,I=T.get(m)??new Set;I.add(l.toState),T.set(m,I),I.size>1&&ee(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(l=>l.recordType==="authority_grant"?[[l.id,l]]:[])),f=(l,y,m,I,u)=>{if(l.level!=="delegate"||!l.grantId)return;let k=b.get(l.grantId);if(!k){ee(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(k.granteeId!==y||k.level!=="delegate")&&ee(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let M=Date.parse(m);(M<Date.parse(k.startsAt)||k.endsAt&&M>Date.parse(k.endsAt)||k.revokedAt&&M>=Date.parse(k.revokedAt))&&ee(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),k.subjectIds.length&&I.length&&!I.every(g=>k.subjectIds.includes(g))&&ee(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let l of o.records)l.recordType==="decision"&&f(l.authority,l.acceptedById,l.createdAt,l.subjects.map(y=>y.subjectId),`records:${l.id}.authority`);o.events.forEach((l,y)=>{let m=j.get(`${l.entity.entityType}:${l.entity.entityId}`),I=m&&"subjects"in m?m.subjects.map(u=>u.subjectId):[];f(l.authority,l.participantId,l.createdAt,I,`events[${y}].authority`)}),o.relationships.forEach((l,y)=>{if(!l.authority)return;let m=[l.from,l.to].flatMap(I=>{let u=j.get(`${I.entityType}:${I.entityId}`);return u&&"subjects"in u?u.subjects.map(k=>k.subjectId):[]});f(l.authority,l.participantId,l.createdAt,m,`relationships[${y}].authority`)});for(let l of o.records){if(l.recordType!=="decision")continue;let y=x.get(l.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==l.proposalId||y.toState!=="accepted")&&ee(e,`records:${l.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==l.acceptedById&&ee(e,`records:${l.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),j.has(`proposal:${l.proposalId}`)||ee(e,`records:${l.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),l.state==="superseded"&&(o.relationships.some(I=>I.relationshipType==="supersedes"&&I.to.entityType==="decision"&&I.to.entityId===l.id)||ee(e,`records:${l.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),l.state==="revoked"&&(o.events.some(I=>I.entity.entityType==="decision"&&I.entity.entityId===l.id&&I.toState==="revoked"&&!!I.reason?.trim())||ee(e,`records:${l.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let l of o.records){if(l.recordType!=="proposal"||l.state!=="accepted")continue;o.records.some(m=>m.recordType==="decision"&&m.proposalId===l.id)||ee(e,`records:${l.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Xs(e)}function qt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function vi(o,e,n,t,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function oa(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 Pn(o,e){let n=[],t=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),St(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of oa(e))St(r)||n.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=vi(o,t,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...qt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...qt(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=vi(o,r,e,c.id,e.decisionId),p={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[r,d],events:[s,c],relationships:[p]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let i={...qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as ia}from"crypto";import{readFile as ra,readdir as sa,realpath as aa}from"fs/promises";import{join as zt,relative as ca}from"path";var da=["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 kt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Ii(...o){return o.find(e=>!!e?.trim())?.trim()}function oe(o,e,n,t){let r=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=ia("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function wo(o,e){try{return JSON.parse(await ra(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function la(o){let e=kt(o);if(!e)return 0;let n=0,t=i=>{let r=kt(i);if(!r){n+=1;return}for(let s of Object.values(r))t(s)};for(let i of Object.values(e))t(i);return n}function pa(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Ut(o){let e=[],n=await aa(o.projectRoot).catch(()=>o.projectRoot),t=zt(n,".popmelt"),i=await wo(zt(t,"threads.json"),e),r=await wo(zt(t,"model.json"),e),s=kt(i),c=kt(s?.threads)??{},d=Object.entries(c).map(([W,re])=>({key:W,value:kt(re)})).filter(W=>!!W.value),p=zt(t,"decisions"),x=await sa(p).catch(()=>[]),j=[];for(let W of x.filter(re=>re.endsWith(".json")).sort()){let re=kt(await wo(zt(p,W),e));re&&j.push({file:W,value:re})}let T=d.flatMap(({value:W})=>[W.createdAt,W.updatedAt]).filter(W=>typeof W=="number"&&Number.isFinite(W)),b=T.length?Math.min(...T):0,f=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 l=oe(f,"project",f,b),y=oe(f,"participant","legacy-owner",b),m=oe(f,"participant","legacy-agent",b),I=oe(f,"subject","project",b),u=Le(Math.max(b,...T)),k=[],M=[],g=new Map,_=new Map,$=new Map(j.map(W=>[W.value.id??W.file.replace(/^d-|\.json$/g,""),W.value])),h=new Map,A=(W,re,K,Se,Ae)=>{let Ie=g.get(K);if(Ie)return Ie;let Me=oe(f,"artifact",W,Se);return M.push({id:Me,kind:re,mediaType:Ae,location:K,availability:"available"}),g.set(K,Me),Me};for(let{file:W,value:re}of j){let K=re.id??W.replace(/^d-|\.json$/g,""),Se=re.createdAt??b,Ae=[A(`${K}:envelope`,"other",`.popmelt/decisions/${W}`,Se,"application/json")];re.screenshotPath&&Ae.push(A(`${K}:screenshot`,"screenshot",`.popmelt/${re.screenshotPath.replace(/^\.popmelt\//,"")}`,Se,re.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ie,Me]of(re.pastedImagePaths??[]).entries())Ae.push(A(`${K}:image:${Ie}`,"image",Me,Se));h.set(K,Ae)}let D=(W,re,K)=>({id:W,schemaVersion:1,projectId:l,createdAt:u,participantId:re,sourceRefs:K}),B=(W,re)=>{k.push(re);let K=_.get(W)??[];K.push(re.id),_.set(W,K)},U=[{...D(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...D(m,m,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];k.push(...U),k.push({...D(I,y,[]),recordType:"subject",subjectType:"project",label:ca(process.cwd(),n)||n,aliases:[],locators:[{id:oe(f,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Le(b),sourceRefs:[]}]});let V=new Map,Y=(W,re)=>{let K=V.get(W);if(K)return K;let Se=oe(f,"subject",W,re),Ae={...D(Se,y,[{kind:"external",id:W}]),createdAt:Le(re),recordType:"subject",subjectType:"element",label:W,aliases:[],locators:[{id:oe(f,"locator",W,re),kind:"dom_selector",value:W,status:"current",validFrom:Le(re),sourceRefs:[{kind:"external",id:W}]}]};return k.push(Ae),V.set(W,Se),Se};for(let{key:W,value:re}of d){let K=re.id??W,Se=re.createdAt??b,Ae=oe(f,"thread",K,Se),Ie={kind:"thread",id:K},Me=[],Ve=[],st=Array.isArray(re.messages)?re.messages:[],Ye,at,rn=0;st.forEach((ve,nt)=>{let Ee=ve.timestamp??Se,Ze=oe(f,"artifact",`${K}:message:${nt}`,Ee);if(Me.push(Ze),M.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${K}/messages/${nt}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${K}/messages/${nt}`,Ze),ve.screenshotPath&&A(`${K}:message:${nt}:screenshot`,"screenshot",ve.screenshotPath,Ee),ve.role==="human"){Ye=ve;let Oe=ve.feedbackSummary??ve.replyToQuestion;if(Oe?.trim()){let De=oe(f,"observation",`${K}:${nt}`,Ee),rt=re.elementIdentifiers??[],vt={...D(De,y,[Ie,{kind:"message",id:Ze}]),createdAt:Le(Ee),recordType:"observation",state:"open",statement:Oe,captureContext:{subjectIds:rt.map(dt=>Y(dt,Se)),artifactIds:[Ze]},resolvedByIds:[]};B(K,vt),at=De,Ve.push({entityType:"observation",entityId:De})}return}if(ve.role!=="assistant")return;let ot=ve.jobId??`${K}:${nt}`,it=oe(f,"iteration",ot,Ee),ct=$.get(ot),Ot=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",Xn={...D(it,m,[Ie,{kind:"message",id:Ze},...(h.get(ot)??[]).map(Oe=>({kind:"artifact",id:Oe}))]),createdAt:Le(Ee),recordType:"iteration",threadIds:[Ae],startedAt:Le(Ye?.timestamp,Ee),completedAt:Le(Ee),requestSummary:Ii(Ye?.feedbackSummary,Ye?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:Ot,execution:{provider:ve.provider??ct?.provider,model:ve.model??ct?.model,sessionId:ve.sessionId??ct?.sessionId},artifactIds:[Ze,...h.get(ot)??[]]};B(K,Xn),Ve.push({entityType:"iteration",entityId:it});let Dt=ve.resolutions??ct?.resolutions??[];for(let[Oe,De]of Dt.entries()){if(De.status!=="resolved"||!De.summary?.trim())continue;let rt=re.elementIdentifiers??[],vt=(rt.length?rt:[n]).map(an=>({subjectId:an===n?I:Y(an,Se),role:"governed"})),dt=oe(f,"proposal",`${ot}:${De.annotationId??"resolution"}:${Oe}`,Ee),Yn={...D(dt,m,[Ie,{kind:"iteration",id:it}]),createdAt:Le(Ee),recordType:"proposal",state:"pending",claim:De.summary,subjects:vt,subjectSemantics:vt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Ii(Ye?.feedbackSummary,Ye?.replyToQuestion,De.summary),iterationId:it,inferredById:m}};B(K,Yn),Ve.push({entityType:"proposal",entityId:dt}),e.push({severity:"warning",code:"acceptance_unresolved",source:K,message:`Proposal ${dt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Dt.some(Oe=>Oe.status==="resolved")||ct?.gitDiff){let Oe=oe(f,"implementation",ot,Ee),De={...D(Oe,m,[Ie,{kind:"iteration",id:it}]),createdAt:Le(Ee),recordType:"implementation_attempt",state:"completed",iterationIds:[it],coverageClaims:[],summary:Dt.map(rt=>rt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};B(K,De),Ve.push({entityType:"implementation_attempt",entityId:Oe}),rn+=1}at&&(at=void 0)});let sn=st.at(-1),Qn={...D(Ae,y,[Ie]),createdAt:Le(Se),recordType:"thread",state:sn?.question?"open":"resolved",messageArtifactIds:Me,outcome:sn?.question?"question_unresolved":rn?"implementation_only":"no_outcome",resultRefs:Ve};k.push(Qn),_.set(K,[Ae,..._.get(K)??[]])}let ie=la(r);ie&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ie} model values were not promoted because their accepted decision provenance is unresolved.`});let N={manifest:{formatVersion:1,projectId:l,createdAt:Le(b),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:k,events:[],relationships:[],artifacts:M,tombstones:[]},pe=ht(N),J=(o.proofCaseIds??da).map(W=>({legacyId:W,threadFound:d.some(({key:re,value:K})=>(K.id??re)===W),decisionEnvelopeFound:$.has(W),recordIds:_.get(W)??[]}));return{bundle:N,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((W,re)=>W+(re.value.messages?.length??0),0),decisionEnvelopes:j.length,modelEntries:ie,artifactsReferenced:M.length},imported:pa(k),unresolvedAcceptance:e.filter(W=>W.code==="acceptance_unresolved").length,deferredModelEntries:ie,proofCases:J,issues:e,schemaIssues:pe.issues}}}import{createHash as ua}from"crypto";import{mkdir as wi,open as bo,readFile as xo,readdir as ma,rename as fa,unlink as So}from"fs/promises";import{join as et}from"path";var ha={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Tn(o){return ua("sha256").update(JSON.stringify(o)).digest("hex")}function bi(o){return Tn(o)}function xi(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let i=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(i<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let r=o.records[i];if(r.projectId!==t.projectId||r.createdAt!==t.createdAt||r.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[i]=structuredClone(t)}for(let t of e.projectionUpdates){let i=o.records.find(r=>r.recordType===t.entityType&&r.id===t.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(i.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${i.state}`);i.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function ga(o,e,n){return xi(structuredClone(o),e,n)}async function gt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await bo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
121
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await fa(n,o)}catch(i){throw await So(n).catch(()=>{}),i}}async function Rn(o){return JSON.parse(await xo(o,"utf8"))}var jn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=et(e,".popmelt","memory"),this.journalDir=et(this.memoryDir,"journal"),this.manifestPath=et(this.memoryDir,"manifest.json"),this.checkpointPath=et(this.memoryDir,"checkpoint.json"),this.lockPath=et(this.memoryDir,"writer.lock")}async initialize(e){let n=ht(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await wi(this.journalDir,{recursive:!0});try{throw await xo(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 xo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=Tn(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await gt(this.checkpointPath,i),await gt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await gt(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=Tn(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await gt(et(this.memoryDir,t),i),e.manifest.checkpoint={file:t,sequence:i.sequence,hash:n},await gt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!St(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let i=t.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...r,hash:bi(r)},c=ga(t.bundle,e,n.committedAt),d=ht(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let p=`${String(i).padStart(12,"0")}-${n.transactionId}.json`;return await gt(et(this.journalDir,p),s),t.manifest.head={sequence:i,hash:s.hash},t.manifest.updatedAt=n.committedAt,await gt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...ha,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Rn(this.manifestPath),n=await Rn(et(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!==Tn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await ma(this.journalDir),i=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,p=n.journalHash??null,x=new Set;for(let T of s){let b=await Rn(et(this.journalDir,T)),{hash:f,...l}=b;if(f!==bi(l))throw new Error(`Journal hash mismatch: ${T}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(b.previousHash!==p)throw new Error(`Journal chain mismatch at ${T}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(x.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);xi(c,b.mutation,b.committedAt),d=b.sequence,p=b.hash,x.add(b.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==p)throw new Error("Journal manifest head hash mismatch.");let j=ht(c);if(!j.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(j.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:p}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await wi(this.memoryDir,{recursive:!0});let n;try{n=await bo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let i=await Rn(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await So(this.lockPath),n=await bo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await So(this.lockPath).catch(()=>{})}}};import{randomBytes as ya}from"crypto";function ye(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=ya(10).toString("hex"),i=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${i}${t.slice(4,7)}-${t.slice(7,19)}`}var va=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Si(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=va(),p=d.records,x=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(k=>k.kind==="thread"&&k.id===e.threadId));x||(x={id:oe(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(x));let j=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let k=o.records.find(M=>M.recordType==="subject"&&M.locators.some(g=>g.value===u&&g.status==="current"));k||(k={id:oe(i,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:oe(i,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},p.push(k)),j.push(k)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let k=o.records.find(M=>M.recordType==="subject"&&M.locators.some(g=>g.kind==="source_file"&&g.value===u&&g.status==="current"));k||(k={id:oe(i,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:oe(i,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},p.push(k)),j.push(k)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),b;if(T.length>0){b=oe(i,"live-observation",r,e.createdAt);let u={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(k=>k.claim.trim()).join(" "),captureContext:{subjectIds:j.map(k=>k.id),artifactIds:[]},resolvedByIds:[]};p.push(u)}let f=oe(i,"live-iteration",r,e.completedAt),l={id:f,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],recordType:"iteration",threadIds:[x.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};p.push(l);let y=[],m=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),I=j.length>0?j:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(T.length>0&&I.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,k]of T.entries()){let M=oe(i,"live-proposal",`${r}:${u}`,e.completedAt),g=I.map($=>({subjectId:$.id,role:"governed"})),_={id:M,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:f},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:k.claim.trim(),rationale:k.rationale?.trim()||void 0,proposedKind:k.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:k.sourceText?.trim()||e.requestSummary,iterationId:f,inferredById:t.id}};p.push(_),y.push(M)}if(m.length>0){let u=new Set(e.governingDecisionIds??[]),k=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&u.has(g.id)),M={id:oe(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:f}],recordType:"implementation_attempt",state:"completed",iterationIds:[f],coverageClaims:k.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${m.map(_=>_.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:f}]})),summary:m.map(g=>g.summary).join(" "),artifactIds:[]};p.push(M)}return{mutation:d,iterationId:f,proposalIds:y,observationId:b}}import{createHash as Ia}from"crypto";import{mkdir as wa,open as ba,readFile as xa,rename as Sa,unlink as ka}from"fs/promises";import{join as ki}from"path";function Pi(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ri(o){return Ia("sha256").update(JSON.stringify(o)).digest("hex")}async function Pa(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await ba(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
122
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Sa(n,o)}catch(i){throw await ka(n).catch(()=>{}),i}}function Ra(o,e,n=new Date().toISOString()){let t={},i={},r={},s=(d,p,x)=>{let j=d[p]??=[];j.includes(x)||j.push(x)};for(let d of o.records)if(d.recordType==="subject"){let p=d;for(let x of[p.label,...p.aliases,...p.locators.filter(j=>j.status==="current").map(j=>j.value)]){let j=Pi(x);j&&s(t,j,p.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let p of d.subjects)s(i,p.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let p of d.subjects)s(r,p.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:Ri(c)}}function Ti(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Pi(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var An=class{constructor(e){this.indexDir=ki(e,".popmelt","memory","indexes"),this.indexPath=ki(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let i=JSON.parse(await xa(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===n.sequence&&i.journalHead.hash===n.hash&&r===Ri(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let t=Ra(e,n);return await wa(this.indexDir,{recursive:!0}),await Pa(this.indexPath,t),t}};var Wt="popmelt:imprint",Mi="popmelt:imprint-evidence",Rt="popmelt:imprint-relation";function Mn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Wt)?.id}function ko(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function En(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="instantiates"&&t.fromId===e?[t.toId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}var _n=class{constructor(e){this.projectRoot=e;this.store=new jn(e),this.indexStore=new An(e),this.manifestPath=Pt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Gt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let t=await Ut({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Ut({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Pt(this.projectRoot,".popmelt","memory","migrations"),n=Pt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await Gt(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await Gt(Pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await ji(e,{recursive:!0}),await Ai(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,d=i.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let p=i.bundle.manifest.projectId,x=new Set(i.bundle.records.map(u=>u.id)),j=new Set(i.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(k=>k.kind==="external"&&k.uri===Rt?[k.id]:[]))),T=new Map,b=i.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let k=b.find(M=>Mn(M)===u.id);T.set(u.id,k?.id??oe(p,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let f=[],l=[],y=[],m=0;for(let u of t.explanations){let k=T.get(u.id),M=b.find(h=>h.id===k),g=[],_=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let h of _){let A=oe(p,"imprint-evidence-record",h.id,Date.parse(h.createdAt));g.push(A),!x.has(A)&&(f.push({id:A,schemaVersion:1,projectId:p,createdAt:h.createdAt,participantId:c.id,sourceRefs:ko([{kind:"external",id:h.id,uri:Mi},{kind:"external",id:u.id,uri:Wt},{kind:"thread",id:h.threadId},{kind:"message",id:h.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(h.kind)?"user_feedback":"judgment",summary:h.summary,availability:"available",artifactIds:[]}),y.push({id:oe(p,"imprint-evidence-link",`${u.id}:${h.id}`,Date.parse(h.createdAt)),schemaVersion:1,projectId:p,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:Mi}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"evidence",entityId:A},reason:"This advisory explanation was derived from collaboration evidence."}),m+=1)}let $={id:k,schemaVersion:1,projectId:p,createdAt:M?.createdAt??u.createdAt,participantId:M?.participantId??c.id,sourceRefs:ko([...M?.sourceRefs??[],{kind:"external",id:u.id,uri:Wt}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...M?.evidenceIds??[],...g])],concreteBindings:En(t,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};M?l.push($):f.push($)}for(let u of t.relations){let k=T.get(u.fromId),M=T.get(u.toId);!k||!M||j.has(u.id)||y.push({id:oe(p,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:p,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:Rt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"advisory_explanation",entityId:M},reason:u.rationale||"The Imprint graph connected these explanations."})}let I=new Date().toISOString();if(f.length||l.length||y.length)try{let u=await this.store.commit({records:f,recordReplacements:l,events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:oe(p,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:I});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await ji(e,{recursive:!0}),await Ai(n,JSON.stringify({version:2,migratedAt:I,explanations:t.explanations.length,evidence:m,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:m}}async review(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,selection:yo(t.bundle,i)}}async contextualize(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:yi(t.bundle,i),reviewSelection:yo(t.bundle,i)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Pn(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 Ut({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),i=Pn(t.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,n);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:t.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:ye(r),decisionId:ye(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:ye(r),replacementProposalId:ye(r),acceptanceEventId:ye(r),decisionId:ye(r),relationshipId:ye(r),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:ye(r),reason:e.reason}:{...c,action:"defer",eventId:ye(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=Pn(n.bundle,d);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(T=>T.message).join(" ")};let x=await this.store.commitReviewPlan(p.plan,{transactionId:ye(r),committedAt:s});await this.refreshIndex(x);let j=p.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:j,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:x.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=Si(n.bundle,e),i=oe(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(t.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await Gt(Pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),i=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),r=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?i:r??i,c=t.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),p=Date.parse(d),x=t.bundle.manifest.projectId,j=[],T=[],b=[],f=t.bundle.records.filter(I=>I.recordType==="advisory_explanation"),l=new Map(f.flatMap(I=>{let u=Mn(I);return u?[[u,I.id]]:[]}));for(let I of e.summary.changes)if(!l.has(I.explanationId)){let u=n?.explanations.find(k=>k.id===I.explanationId);l.set(I.explanationId,oe(x,"imprint-explanation",I.explanationId,Date.parse(u?.createdAt??d)))}for(let I of e.summary.changes){let u={kind:"external",id:I.explanationId,uri:Wt},k=l.get(I.explanationId),M=f.find(h=>h.id===k),g=n?.explanations.find(h=>h.id===I.explanationId),_={id:oe(x,"imprint-live-evidence",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};j.push(_);let $={id:k,schemaVersion:1,projectId:x,createdAt:M?.createdAt??g?.createdAt??d,participantId:M?.participantId??s.id,sourceRefs:ko([...M?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??M?.kind??"pattern",state:g?.state??I.state,statement:g?.statement??I.statement,rationale:g?.rationale??M?.rationale??e.summary.detail,scope:structuredClone(g?.scope??M?.scope??{kind:"project",values:[]}),subjectIds:M?.subjectIds??[c.id],evidenceIds:[...new Set([...M?.evidenceIds??[],_.id])],concreteBindings:g?En(n,I.explanationId):M?.concreteBindings??[],supersededById:g?.supersededBy?l.get(g.supersededBy):M?.supersededById,updatedAt:g?.updatedAt??d};M?T.push($):j.push($),b.push({id:oe(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:$.id},to:{entityType:"evidence",entityId:_.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let y=new Set(t.bundle.relationships.flatMap(I=>I.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Rt?[u.id]:[])));for(let I of n?.relations??[]){let u=l.get(I.fromId),k=l.get(I.toId);!u||!k||y.has(I.id)||b.push({id:oe(x,"imprint-relation",I.id,Date.parse(I.createdAt)),schemaVersion:1,projectId:x,createdAt:I.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:I.id,uri:Rt}],recordType:"relationship",relationshipType:I.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:k},reason:I.rationale||"The Imprint graph connected these explanations."})}let m=oe(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let I=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:m,committedAt:d});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=JSON.parse(await Gt(Pt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),r=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??t;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(g=>g.recordType==="advisory_explanation"),p=new Map(d.flatMap(g=>{let _=Mn(g);return _?[[_,g]]:[]})),x=new Map([...[...p].map(([g,_])=>[g,_.id]),...e.explanations.filter(g=>!p.has(g.id)).map(g=>[g.id,oe(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),j=[],T=[],b=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let _=p.get(g.id);if(!_){j.push({id:x.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Wt}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:En(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let $={...structuredClone(_),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:En(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt},h=A=>JSON.stringify({kind:A.kind,state:A.state,statement:A.statement,rationale:A.rationale,scope:A.scope,concreteBindings:A.concreteBindings,supersededById:A.supersededById,updatedAt:A.updatedAt});h(_)!==h($)&&T.push($)}for(let[g,_]of p)b.has(g)||_.state==="retired"||T.push({...structuredClone(_),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let f=new Set(n.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),l=new Map(n.bundle.relationships.flatMap(g=>{if(f.has(g.id))return[];let _=g.sourceRefs.find($=>$.kind==="external"&&$.uri===Rt)?.id;return _?[[_,g]]:[]})),y=new Set(l.keys()),m=[];for(let g of e.relations){let _=x.get(g.fromId),$=x.get(g.toId);!_||!$||y.has(g.id)||m.push({id:oe(c,"imprint-relation",g.id,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Rt}],recordType:"relationship",relationshipType:g.type,from:{entityType:"advisory_explanation",entityId:_},to:{entityType:"advisory_explanation",entityId:$},reason:g.rationale||"The Imprint graph connected these explanations."})}let I=new Set(e.relations.map(g=>g.id)),u=t?[...l].filter(([g])=>!I.has(g)).map(([,g])=>({id:oe(c,"imprint-relationship-tombstone",g.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:g.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!j.length&&!T.length&&!m.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let k=e.updatedAt,M=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(k));try{let g=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:m,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:M,committedAt:k});return await this.refreshIndex(g),{status:"synced",relationships:m.length+u.length,explanations:j.length+T.length,headSequence:g.report.headSequence}}catch(g){if(!(g instanceof Error)||!g.message.includes("Transaction already exists"))throw g;return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let i of n.bundle.records)t[i.recordType]=(t[i.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:n.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!i.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),t=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>n.has(r))&&t.set(i.key,i);return[...t.values()]}async getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),i=t.bundle.records.filter(l=>l.recordType==="advisory_explanation"),r=new Map(i.map(l=>[l.id,l])),s=new Map(i.flatMap(l=>{let y=Mn(l);return y?[[y,l.id]]:[]})),c=new Set(e.map(l=>s.get(l)??l)),d=new Map(t.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),p=new Map(t.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),x=new Set(t.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),j=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),T={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=i.map(l=>{let y=l.evidenceIds.flatMap(u=>{let k=p.get(u);if(!k)return[];let M=k.sourceRefs.find(h=>h.kind==="thread")?.id,g=k.sourceRefs.find(h=>h.kind==="message")?.id,_=k.kind==="judgment"||k.kind==="user_feedback"||k.kind==="project_state"?k.kind:"other",$=d.get(k.participantId)??"unknown";return[{id:k.id,kind:_,summary:k.summary,createdAt:k.createdAt,participantKind:$,threadId:M,jobId:g}]}).sort((u,k)=>k.createdAt.localeCompare(u.createdAt)),m=t.bundle.relationships.flatMap(u=>{if(x.has(u.id))return[];if(!j.has(u.relationshipType))return[];let k=u.from.entityType==="advisory_explanation"&&u.from.entityId===l.id&&u.to.entityType==="advisory_explanation",M=u.to.entityType==="advisory_explanation"&&u.to.entityId===l.id&&u.from.entityType==="advisory_explanation";if(!k&&!M)return[];let g=k?u.to.entityId:u.from.entityId,_=r.get(g);return _?[{id:u.id,type:u.relationshipType,direction:k?"outgoing":"incoming",explanationId:_.id,statement:_.statement,rationale:u.reason}]:[]}),I=[...new Set([...l.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...y.flatMap(u=>u.threadId?[u.threadId]:[])])];return{id:l.id,kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),createdAt:l.createdAt,updatedAt:l.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:l.concreteBindings.map(u=>({...structuredClone(u)})),relations:m,sourceThreadIds:I,needsGrounding:l.state==="testing"&&c.has(l.id)}}).sort((l,y)=>Number(y.needsGrounding)-Number(l.needsGrounding)||T[l.state]-T[y.state]||y.updatedAt.localeCompare(l.updatedAt)),f={total:b.filter(l=>l.state!=="retired").length,emerging:b.filter(l=>l.state==="emerging").length,testing:b.filter(l=>l.state==="testing").length,grounded:b.filter(l=>l.state==="grounded").length,challenged:b.filter(l=>l.state==="challenged").length,retired:b.filter(l=>l.state==="retired").length,needsGrounding:b.filter(l=>l.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:f,explanations:b}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,p)=>d.createdAt.localeCompare(p.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let i=[...t.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(p=>p.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((p,x)=>x.createdAt.localeCompare(p.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(p=>p.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),i=n.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!t||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=ye(r),d=ye(r),p=ye(r),x=ye(r),j=ye(r),T=new Set(n.bundle.records.flatMap(h=>h.recordType==="model_entry"&&h.key===e.key?h.decisionIds:[])),b=n.bundle.records.filter(h=>h.recordType==="decision"&&h.state==="active"&&T.has(h.id)),f={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},l=[{subjectId:i.id,role:"governed"}],y={...f,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:l,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},m={...f,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."},I={...f,id:p,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:l,noChange:!1,effectiveAt:s},u={...f,id:x,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[p],value:e.value},k={...f,id:j,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[p],entryIds:[x],coverage:[{decisionId:p,status:"projected"}]},M={...f,id:ye(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},g=b.map(h=>({...f,id:ye(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:h.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),_=b.map(h=>({...f,id:ye(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:I.id},to:{entityType:"decision",entityId:h.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),$=await this.store.commit({records:[y,I,u,k],events:[m,...g],relationships:[M,..._],artifacts:[],tombstones:[],projectionUpdates:b.map(h=>({entityType:"decision",entityId:h.id,fromState:"active",state:"superseded"}))},{transactionId:ye(r),committedAt:s});return await this.refreshIndex($),{decisionId:p,entryId:x}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(f=>f.recordType==="model_projection"&&f.state==="applied"&&f.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let i=n.bundle.records.filter(f=>f.recordType==="decision"&&e.decisionIds.includes(f.id)&&f.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=n.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=ye(s),p=e.changes.map(f=>{let l=f.decisionIds?.filter(I=>e.decisionIds.includes(I)),y=l?.length?l:e.decisionIds,m=[...new Set(i.filter(I=>y.includes(I.id)).flatMap(I=>I.subjects.map(u=>u.subjectId)))];return{id:ye(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:y.map(I=>({kind:"record",id:I})),recordType:"model_entry",key:f.path.map(String).join("."),subjectIds:m,decisionIds:y,value:f.value}}),x=new Set(p.flatMap(f=>f.decisionIds)),j={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(f=>({kind:"record",id:f})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:p.map(f=>f.id),coverage:e.decisionIds.map(f=>e.coverage?.find(l=>l.decisionId===f)??{decisionId:f,status:x.has(f)?"projected":"unprojected"})},T=p.flatMap(f=>f.decisionIds.map(l=>({id:ye(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:j.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:f.id},to:{entityType:"decision",entityId:l},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...p,j],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ye(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:p.map(f=>f.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Ut({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=Ti(t,n.subjectHints??[]);return i?{...n,subjectIds:[...new Set([...n.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function jt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function we(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Tt(o,e,n){let t=we(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Po(o){let e=jt(o),n=jt(e.authority),t=n.level,i=n.mode,r=Tt(t,"authority.level",["owner","delegate","contributor"]),s=Tt(i,"authority.mode",["local_trusted","hosted"]),c={proposalId:we(e.proposalId,"proposalId"),participantId:we(e.participantId,"participantId"),occurredAt:we(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:we(e.eventId,"eventId"),decisionId:we(e.decisionId,"decisionId"),kind:Tt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:we(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:we(e.eventId,"eventId"),reason:we(e.reason,"reason")};case"defer":{let d=jt(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:we(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(p=>we(p,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(p=>Tt(p,"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:we(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:we(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:we(e.acceptanceEventId,"acceptanceEventId"),decisionId:we(e.decisionId,"decisionId"),relationshipId:we(e.relationshipId,"relationshipId"),claim:we(e.claim,"claim"),kind:Tt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let p=jt(d);return{subjectId:we(p.subjectId,"subjectId"),role:Tt(p.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:we(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Ro(o){let e=jt(o),n=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>we(c,s))}},t=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:jt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Cn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
123
|
+
`)}async function Ei(o,e,n,t){let i=Cn(e);if(!(!i&&n.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(p=>p.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){t?.(r);return}}function _i(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,i)=>["",`${i+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,i)=>["",`${i+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
124
|
+
`)}function Ci(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,i=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!i||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:i,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function $i(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 To(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],i=await Ta(o),r=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,p,x,j,T,b,f,l,y,m,I,u,k,M=[],g=[],_=0,$=[];for(;_<i.length;){let h=i.indexOf(r,_);if(h===-1)break;let A=h+r.length;if(i.slice(h,h+s.length).equals(s))break;let D=A;i[D]===13&&i[D+1]===10&&(D+=2);let B=i.indexOf(`\r
|
|
181
125
|
\r
|
|
182
|
-
`,
|
|
126
|
+
`,D);if(B===-1)break;let U=i.slice(D,B).toString("utf-8"),V=B+4,Y=i.indexOf(r,V),ie=Y!==-1?Y-2:i.length;$.push({headers:U,body:i.slice(V,ie)}),_=Y!==-1?Y:i.length}for(let h of $){let A=h.headers.match(/name="([^"]+)"/);if(!A)continue;let D=A[1];if(D==="screenshot")c=h.body;else if(D==="feedback")d=h.body.toString("utf-8");else if(D==="color")p=h.body.toString("utf-8");else if(D==="provider")x=h.body.toString("utf-8");else if(D==="model")j=h.body.toString("utf-8");else if(D==="reasoningEffort")T=h.body.toString("utf-8");else if(D==="serviceTier")b=h.body.toString("utf-8");else if(D==="goal")f=h.body.toString("utf-8");else if(D==="pageUrl")l=h.body.toString("utf-8");else if(D==="viewport")y=h.body.toString("utf-8");else if(D==="planId")m=h.body.toString("utf-8");else if(D==="manifest")I=h.body.toString("utf-8");else if(D==="tasks")u=h.body.toString("utf-8");else if(D==="sourceId")k=h.body.toString("utf-8");else if(D.startsWith("screenshot-")){let B=D.slice(11);try{let U=decodeURIComponent(B);g.push({pathname:U,data:h.body})}catch{}}else if(D.startsWith("image-")){let B=D.split("-"),U=parseInt(B[B.length-1],10),V=B.slice(1,-1).join("-");V&&!isNaN(U)&&M.push({annotationId:V,index:U,data:h.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:p,provider:x,model:j,reasoningEffort:T,serviceTier:b,goal:f,pageUrl:l,viewport:y,planId:m,manifest:I,tasks:u,sourceId:k,pastedImages:M,pageScreenshots:g}}function Ta(o){return new Promise((e,n)=>{let t=[];o.on("data",i=>t.push(i)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as ja}from"crypto";var Aa=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,Ma=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Ea=new Set(["strengthened","weakened","mixed","unknown"]);function Ht(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 _a(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Oi(o,e,n,t=Date.now()){let i=_a(o);if(!i)return null;let r=typeof i.transition=="string"&&Ma.has(i.transition)?i.transition:null,s=Ht(i.focus);if(!r||!s)return null;let c=typeof i.evidencePosture=="string"&&Ea.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:ja(),jobId:e,sequence:n,timestamp:t,transition:r,snapshot:{focus:s,seeking:Ht(i.seeking),workingHypothesis:Ht(i.workingHypothesis),evidencePosture:c,update:Ht(i.update),nextObservation:Ht(i.nextObservation)},contextPolicy:"exclude"}}function jo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Ca(o,e,n=0){let t=[],i=new Set,r=n;return{visibleText:o.replace(Aa,(c,d)=>{try{let p=Oi(JSON.parse(d),e,r);if(!p)return"";let x=jo(p);if(i.has(x))return"";i.add(x),t.push(p),r++}catch{}return""}).replace(/\n{3,}/g,`
|
|
183
127
|
|
|
184
|
-
`).trim(),orientations:t}}function
|
|
128
|
+
`).trim(),orientations:t}}function $a(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 $n=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let i=this.buffer.indexOf("<orientation>");if(i<0){let c=$a(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,i);let r=this.buffer.indexOf("</orientation>",i+13);if(r<0){this.buffer=this.buffer.slice(i);break}let s=this.buffer.slice(i+13,r).trim();this.buffer=this.buffer.slice(r+14);try{let c=Oi(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=jo(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=Ca(e,this.jobId,this.sequence),t=n.orientations.filter(i=>{let r=jo(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Di=`## Public orientation updates
|
|
185
129
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
186
130
|
<orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
|
|
187
131
|
|
|
188
132
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
189
133
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
190
134
|
|
|
191
|
-
These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function
|
|
192
|
-
### ${
|
|
193
|
-
`)}function
|
|
194
|
-
`)}function
|
|
195
|
-
`)}function
|
|
196
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let i=t.match(
|
|
197
|
-
`));return
|
|
198
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ac(n,o)}catch(i){throw await Ec(n).catch(()=>{}),i}}function _c(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Cc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=$e(e):o.explanations.push($e(e))}function No(o,e){let n=$e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(i=>i.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push($e(t.explanation))}else if(t.op==="replace_explanation")Cc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(i=>i.id!==t.explanationId),n.relations=n.relations.filter(i=>i.fromId!==t.explanationId&&i.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(i=>i.id===t.concrete.id)||n.concrete.push($e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(i=>i.id!==t.concreteId),n.relations=n.relations.filter(i=>i.fromId!==t.concreteId&&i.toId!==t.concreteId);else if(t.op==="add_evidence"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);i.evidence.some(r=>r.id===t.evidence.id)||(i.evidence.push($e(t.evidence)),i.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(i,$e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let i=n.explanations.some(s=>s.id===t.relation.fromId),r=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!i||!r)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push($e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(i=>i.id!==t.relationId));return n}function $c(o,e){let n=[],t=$e(o);for(let i of e){if(i.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=t.explanations.find(s=>s.id===i.explanationId);r&&n.unshift({op:"add_explanation",explanation:$e(r)})}else if(i.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=t.concrete.find(s=>s.id===i.concreteId);r&&n.unshift({op:"add_concrete",concrete:$e(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=t.explanations.find(c=>c.id===r);s&&n.unshift({op:"replace_explanation",explanation:$e(s)})}else if(i.op==="add_relation")n.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=t.relations.find(s=>s.id===i.relationId);r&&n.unshift({op:"add_relation",relation:$e(r)})}t=No(t,[i])}return n}function dr(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Wn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=$t(e,".popmelt","imprint"),this.manifestPath=$t(this.imprintDir,"manifest.json"),this.graphPath=$t(this.imprintDir,"graph.json"),this.journalDir=$t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ar(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await jc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=_c(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ar($t(this.journalDir,t[c]),"utf8")),{hash:l,...b}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==cr(b))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=No(i,d.mutations),i.updatedAt=d.committedAt,i.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(j=>j.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=t.graph.head.sequence+1,r=$c(t.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:$e(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:cr(s)},d=No(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let l=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await on($t(this.journalDir,l),c);let b={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await on(this.graphPath,d),await on(this.manifestPath,b),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,i){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(dr));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(b=>dr(b).some(j=>c.has(j)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await on(this.graphPath,e.graph),await on(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Dc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Oc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Jc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Gn(o){return new Set(Jc(o).split(" ").filter(e=>e.length>2&&!Oc.has(e)))}function Hn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function rt(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function lr(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function pr(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let i=Number(t);if(!Number.isInteger(i)||i<0||i>=n.length)return{found:!1};n=n[i]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Fo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let i=JSON.parse(t);if(i.decision==="none"){let T=String(i.reason);if(!Dc.has(T))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:T},visibleText:n}}if(i.decision!==void 0&&i.decision!=="mutate")throw new Error("imprint decision is invalid");let r=i.summary,s=r?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:je(r?.title,120),detail:je(r?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(i.appliedExplanationIds)?i.appliedExplanationIds.filter(T=>typeof T=="string"&&!!T.trim()):[],l=[];for(let T of Array.isArray(i.mutations)?i.mutations:[]){if(!T||typeof T!="object")continue;let x=T;if(x.op==="add"&&["intention","principle","pattern"].includes(String(x.kind))){let m=je(x.statement),p=je(x.rationale);if(!m||!p)continue;l.push({op:"add",clientId:je(x.clientId,100)||void 0,kind:x.kind,statement:m,rationale:p,scope:lr(x.scope),rootReason:je(x.rootReason,300)||void 0})}else if(x.op==="revise"&&typeof x.explanationId=="string"){let m={op:"revise",explanationId:x.explanationId,statement:je(x.statement)||void 0,rationale:je(x.rationale)||void 0,scope:lr(x.scope),reopenGrounding:x.reopenGrounding===!0};(m.statement||m.rationale||m.scope||m.reopenGrounding)&&l.push(m)}else if(x.op==="evidence"&&typeof x.explanationId=="string"&&["supports","challenges","excepts"].includes(String(x.stance))){let m=je(x.summary);m&&l.push({op:"evidence",explanationId:x.explanationId,stance:x.stance,summary:m})}else if(x.op==="relation"&&typeof x.fromId=="string"&&typeof x.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(x.type))){let m=je(x.rationale);if(!m)continue;l.push({op:"relation",type:x.type,fromId:x.fromId,toId:x.toId,rationale:m})}else if(x.op==="supersede"&&typeof x.explanationId=="string"&&typeof x.replacementId=="string"){let m=je(x.reason);m&&l.push({op:"supersede",explanationId:x.explanationId,replacementId:x.replacementId,reason:m})}else if(x.op==="bind_concrete"&&typeof x.explanationId=="string"){let m=je(x.modelPath,300);m&&l.push({op:"bind_concrete",explanationId:x.explanationId,modelPath:m,rationale:je(x.rationale)})}else x.op==="retire"&&typeof x.explanationId=="string"&&l.push({op:"retire",explanationId:x.explanationId,reason:je(x.reason)})}let b=i.grounding,j=b&&typeof b.explanationId=="string"&&je(b.question)?{explanationId:b.explanationId,question:je(b.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:j},visibleText:n}}catch(i){return{visibleText:n,error:i instanceof Error?i.message:String(i)}}}function Lo(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,i)=>[`${i+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(r=>` - Concrete terminal: ${r.modelPath} = ${JSON.stringify(r.value)}`)].join(`
|
|
199
|
-
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(t=>`- ${t.fromId} --${t.type}--> ${t.toId}: ${t.rationale}`)]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Topology assessment is mandatory for every add mutation. Connect the new clientId with relation or supersede mutations whenever it overlaps, specializes, operationalizes, supports, contradicts, or excepts another surfaced or newly-added explanation. If it is genuinely a new root with no meaningful relative, include rootReason on the add mutation explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
|
|
200
|
-
`)}var rn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Wn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Gn(e.text??""),t=Gn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!i.size)return;let{graph:r}=await this.store.load(),s=r.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let p=Gn([m.statement,m.rationale].join(" ")),y=Gn(m.scope.values.join(" ")),h=Hn(p,n),f=Hn(y,n),u=Hn(y,t),A=Hn(p,t),D=h+f*.2+u*.25+A*.1+(m.state==="grounded"?.08:0)+(i.has(m.id)?1:0),R=i.has(m.id)||(n.size?h>=.12||f>=.5:u>=.2||A>=.2);return{item:m,score:D,relevant:R}}).filter(m=>m.relevant&&m.score>=.18).sort((m,p)=>p.score-m.score||p.item.updatedAt.localeCompare(m.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:m})=>m),l=new Set(d.map(m=>m.id)),b=new Set(r.relations.flatMap(m=>l.has(m.fromId)?[m.toId]:l.has(m.toId)?[m.fromId]:[])),j=new Set(r.explanations.flatMap(m=>b.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),T=r.explanations.filter(m=>j.has(m.id)&&!l.has(m.id)).sort((m,p)=>p.updatedAt.localeCompare(m.updatedAt)).slice(0,4),x=[...d,...T];for(let m of T)l.add(m.id);return{explanations:x.map(m=>{let p=new Set(r.relations.filter(y=>y.fromId===m.id&&y.type==="instantiates").map(y=>y.toId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:r.concrete.filter(y=>p.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||T.length<j.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},relations:r.relations.filter(m=>l.has(m.fromId)&&l.has(m.toId)&&m.type!=="instantiates").map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),i=await this.store.load(),r=new Map(i.graph.explanations.map(I=>[I.id,I])),s=new Map,c=new Map,d=[],l=new Set,b=new Set(n.pendingGroundingExplanationIds??[]),j=new Set(e.mutations.flatMap(I=>I.op==="add"&&I.clientId?[I.clientId]:[])),T=I=>r.has(I)||j.has(I),x=new Set;for(let I of e.mutations)I.op==="relation"&&I.fromId!==I.toId&&T(I.fromId)&&T(I.toId)?(x.add(I.fromId),x.add(I.toId)):I.op==="supersede"&&I.explanationId!==I.replacementId&&T(I.explanationId)&&T(I.replacementId)?(x.add(I.explanationId),x.add(I.replacementId)):I.op==="bind_concrete"&&T(I.explanationId)&&pr(n.concreteModel,I.modelPath).found&&x.add(I.explanationId);let m=i.graph.explanations.length===0;for(let I of e.mutations){if(I.op!=="add")continue;let w=!!(I.clientId&&x.has(I.clientId)),M=!!I.rootReason?.trim()||m;if(!w&&!M)continue;m&&(m=!1);let F=He();I.clientId&&s.set(I.clientId,F);let H=I.clientId?e.appliedExplanationIds.includes(I.clientId):!1,U={id:F,kind:I.kind,statement:I.statement,rationale:I.rationale,scope:Bo(I.scope),state:H?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};r.set(F,U),l.add(F),d.push({op:"add_explanation",explanation:U})}let p=I=>s.get(I)??I;for(let I of e.mutations){if(I.op!=="revise")continue;let w=p(I.explanationId),M=r.get(w);if(M?.state!=="grounded")continue;let F=He(),H={id:F,kind:M.kind,statement:I.statement??M.statement,rationale:I.rationale??M.rationale,scope:I.scope?Bo(I.scope):M.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[rt(n,"supports",e.summary.detail)]};r.set(F,H),c.set(w,F),l.add(F),d.push({op:"add_explanation",explanation:H}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:F,toId:w,rationale:I.rationale??e.summary.detail,createdAt:t}})}let y=I=>{let w=p(I);return c.get(w)??w};for(let I of e.mutations){if(I.op==="add")continue;if(I.op==="bind_concrete"){let M=y(I.explanationId);if(!r.has(M))continue;let F=pr(n.concreteModel,I.modelPath);if(!F.found)continue;let H=i.graph.concrete.find(U=>U.modelPath===I.modelPath&&JSON.stringify(U.value)===JSON.stringify(F.value));H||(H={id:He(),modelPath:I.modelPath,value:structuredClone(F.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:H})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:M,toId:H.id,rationale:I.rationale,createdAt:t}}),l.add(M);continue}if(I.op==="relation"){let M=y(I.fromId),F=y(I.toId);if(!r.has(M)||!r.has(F)||M===F)continue;d.push({op:"add_relation",relation:{id:He(),type:I.type,fromId:M,toId:F,rationale:I.rationale,createdAt:t}}),l.add(M),l.add(F);continue}if(I.op==="supersede"){let M=y(I.explanationId),F=y(I.replacementId);if(!r.has(M)||!r.has(F)||M===F)continue;d.push({op:"add_evidence",explanationId:M,evidence:rt(n,"challenges",I.reason)}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged",supersededBy:F},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"contradicts",fromId:F,toId:M,rationale:I.reason,createdAt:t}}),l.add(M),l.add(F);continue}let w=y(I.explanationId);if(r.has(w))if(l.add(w),I.op==="revise"){if(c.has(p(I.explanationId)))continue;let M={...I.statement?{statement:I.statement}:{},...I.rationale?{rationale:I.rationale}:{},...I.scope?{scope:Bo(I.scope)}:{},...I.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:w,patch:M,updatedAt:t})}else I.op==="evidence"?(d.push({op:"add_evidence",explanationId:w,evidence:rt(n,I.stance,I.summary)}),I.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:w,patch:{state:"challenged"},updatedAt:t})):I.op==="retire"&&(d.push({op:"add_evidence",explanationId:w,evidence:rt(n,"challenges",I.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:w,patch:{state:"retired"},updatedAt:t}))}for(let I of e.appliedExplanationIds){let w=y(I),M=r.get(w);!M||M.state==="grounded"||M.state==="retired"||b.has(w)&&!l.has(w)||(l.has(w)||(l.add(w),d.push({op:"add_evidence",explanationId:w,evidence:{...rt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),M.state==="emerging"&&d.push({op:"revise_explanation",explanationId:w,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let h=He(),f=await this.store.commit({transactionId:h,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),u=new Map(f.graph.explanations.map(I=>[I.id,I])),A=[...l].flatMap(I=>{let w=u.get(I);if(!w)return[];let M=!i.graph.explanations.some(H=>H.id===I),F=w.state==="challenged"||w.state==="retired";return[{explanationId:I,action:M?"added":F?"challenged":"revised",statement:w.statement,state:w.state}]}),D=e.grounding?y(e.grounding.explanationId):void 0,R=D?u.get(D):void 0,C=R?.state==="testing"&&!b.has(R.id)?{explanationId:R.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:h,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:A,...C?{grounding:C}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let b of l)await this.store.undo(b,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${r.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${r.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(b=>b.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:r.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${r.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...rt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${r.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:s,summary:d,mutations:c})}};function ur(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Vn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function zo(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function mr(o){let e=zo(Vn(o.origin));if(e)return e;let n=zo(Vn(o.referer));if(n)return n;let t=Vn(o["x-forwarded-host"]);if(!t)return null;let i=Vn(o["x-forwarded-proto"])==="https"?"https":"http";return zo(`${i}://${t}`)}function fr(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(t).slice(0,n),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Kn}from"crypto";import{mkdir as sn,readFile as xt,unlink as Fc,writeFile as Ot}from"fs/promises";import{dirname as Qn,extname as Lc,join as De}from"path";var Nc={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Bc(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function hr(o,e){let n=e??Bc(o);return{kind:n,...Nc[n]}}function Dt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function gr(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var zc={version:1,threads:{}},yr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],an={version:2,updatedAt:0,files:{}};function Uc(o){return JSON.stringify(o,null,2)}function qc(o){return Object.fromEntries(yr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Wc(o){let e={...o};for(let n of yr)delete e[n];return e}function Jt(o){let e=o;if(o.error){let n=hr(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=Dt(e.result,!1),t=Dt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Xn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=De(e,".popmelt");this.legacyFilePath=De(n,"threads.json"),this.threadsDir=De(n,"threads"),this.indexPath=De(this.threadsDir,"index.json"),this.artifactsDir=De(n,"artifacts","thread-messages"),this.mediaDir=De(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await xt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,i]of Object.entries(e.files)){let r=await this.readThread(De(this.threadsDir,i));r&&(n[t]=r)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await xt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Jt)}]))},this.index={...an,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...zc,threads:{}},this.index={...an,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let i of Object.values(n.threads))if(i.elementIdentifiers.some(s=>t.has(s)))return i;return null}async createThread(e,n){let t=await this.load(),i={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,n){let i=(await this.load()).threads[e];i&&(i.messages.push(Jt(n)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Jt(n)):i.messages.push(Jt(n)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Jt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of n)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((i,r)=>r.updatedAt-i.updatedAt),t.slice(0,e).map(i=>{let s=i.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=i.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let h=y.imprintSummary?.grounding;if(h?.question&&!y.imprintSummary?.resolvedAction)return h.question},l=i.messages.findLastIndex(y=>!!d(y)),b=i.messages.findLastIndex(y=>y.role==="human"),j=l>b?d(i.messages[l]):void 0,T=i.messages.at(-1)?.role,x=Array.from(new Set(i.messages.slice(0,Math.max(0,b)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),m=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=c.some(y=>!!y.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:m,hasError:p,lastMessageRole:T,pendingQuestion:j,acknowledgedJobIds:x,elementIdentifiers:i.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await xt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await xt(De(Qn(this.legacyFilePath),i.path),"utf8");Kn("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Jt({...r,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=qc(e),t=Wc(e);if(Object.keys(n).length===0)return t;let i=Uc(n),r=Kn("sha256").update(i).digest("hex"),s=De("artifacts","thread-messages",`${r}.json`);await sn(this.artifactsDir,{recursive:!0});try{await xt(De(Qn(this.legacyFilePath),s),"utf8")}catch{await Ot(De(Qn(this.legacyFilePath),s),i)}return{...t,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let n=async t=>{if(Qn(t)===this.mediaDir)return t;try{let i=await xt(t),r=Kn("sha256").update(i).digest("hex"),s=De(this.mediaDir,`${r}${Lc(t)||".bin"}`);await sn(this.mediaDir,{recursive:!0});try{await xt(s)}catch{await Ot(s,i)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,i])=>[t,await n(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,i])=>[t,await Promise.all(i.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await sn(this.threadsDir,{recursive:!0});let n=this.index??{...an,files:{}},t=n.files[e.id]??`${Kn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Ot(De(this.threadsDir,t),JSON.stringify(r,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await sn(this.threadsDir,{recursive:!0}),this.index=this.index??{...an,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...an,files:{}},t=n.files[e];t&&await Fc(De(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await sn(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Gc,open as Hc,readFile as Vc,rename as Kc,unlink as Qc}from"fs/promises";import{dirname as Xc,join as Yc}from"path";var vr={schemaVersion:1,theme:"auto",updatedAt:null};function Ir(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Zc(o,e){await Gc(Xc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Hc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
201
|
-
`,"utf8"),await t.sync()}finally{await t.close()}await
|
|
202
|
-
`)}function
|
|
203
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=i?`Using ${i}`:"tool";break}let
|
|
204
|
-
`)}function
|
|
135
|
+
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 Vt(o,e,n){let t=[];if(o.annotations.length>0){t.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(p=>{let x=[p.selector];return p.reactComponent&&x.push(`(${p.reactComponent})`),x.join(" ")}).join(", "),s=i.instruction||"No text";t.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[i.id];if(c&&c.length>0)for(let p of c)t.push(` Attached image: use the Read tool to view ${p}`);let d=n?.[i.id];if(d?.length)for(let p of d)t.push(` Attached context (${p.name}, ${p.mimeType}): use the Read tool to inspect ${p.path}`)}}if(o.styleModifications.length>0){t.push(""),t.push("## Style Changes (make permanent in source)"),t.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let i of o.styleModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"";for(let s of i.changes)t.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){t.push(""),t.push("## Text Changes (make permanent in source)"),t.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let i of o.textModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=JSON.stringify(i.original),c=JSON.stringify(i.modified),d=i.textNodePath.length>0?` textNodePath=${i.textNodePath.join(".")}`:"";t.push(`- ${i.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(o.domModifications?.length){t.push(""),t.push("## DOM Structure Changes (make permanent in source)"),t.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let i of o.domModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=i.sourceElement?.reactComponent?` from ${i.sourceSelector} (${i.sourceElement.reactComponent})`:i.sourceSelector?` from ${i.sourceSelector}`:"",c=i.referenceSelector?` ${i.placement} ${i.referenceSelector}`:` at index ${i.targetIndex}`;t.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${c}`)}}if(o.spacingTokenChanges?.length){t.push(""),t.push("## Spacing Token Changes"),t.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let i of o.spacingTokenChanges){t.push(`
|
|
136
|
+
### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let r of i.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?t.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):t.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),t.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;t.push(""),t.push("## Inspected Element"),t.push("The developer has this element selected in the inspector:");let r=[i.selector];i.reactComponent&&r.push(`(${i.reactComponent})`),i.context&&r.push(`in ${i.context}`),i.textContent&&r.push(`"${i.textContent.slice(0,80)}"`),t.push(`- ${r.join(" ")}`)}return t.join(`
|
|
137
|
+
`)}function Ji(o,e,n){let t=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!r&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let p=d.finalScope??d.inferredScope,x=p?` [${p.breadth} ${p.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${x} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(t.push(""),t.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let x=new Map;for(let j of s)if(typeof j=="object"&&j!==null&&"text"in j){let T=j,b=T.scope||"general";x.has(b)||x.set(b,[]),x.get(b).push(T.text)}for(let[j,T]of x){t.push(`**${j.charAt(0).toUpperCase()+j.slice(1)}**`);for(let b of T)t.push(`- ${b}`)}}else for(let x of s)typeof x=="string"&&t.push(`- ${x}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let p=d.pathname||new URL(e.url).pathname;c.has(p)||c.set(p,[]),c.get(p).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,p]of c){t.push(""),t.push(`## Page: ${d}`);let x=s[d];x&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${x}`):!x&&n?.provider!=="codex"&&(Object.keys(s).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let j={...e,annotations:p,styleModifications:e.styleModifications},T=Vt(j,n?.imagePaths,n?.attachmentFiles);T&&(t.push(""),t.push(T))}}else{let s=Vt(e,n?.imagePaths,n?.attachmentFiles);s&&(t.push(""),t.push(s))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output 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(`
|
|
138
|
+
`)}function Ni(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Bi(o,e,n,t){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),n!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${c.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),c.feedbackSummary&&i.push(`Annotations: ${c.feedbackSummary}`))):c.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${c.question}"`)):(i.push(`### Round ${s} (assistant)`),c.responseText&&i.push(`Response: ${c.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of t)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output a resolution block listing what you did for each annotation:"),i.push("<resolution>"),i.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),i.push("</resolution>"),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
|
|
139
|
+
`)}function Oa(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 Da(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&&!Oa(e[n]))return!1;return!0}function Li(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(Da):[]}catch{return[]}}function Fi(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let i=t;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}import{execFile as Ja}from"child_process";import{readdir as Na,readFile as Ba,stat as La}from"fs/promises";import{homedir as Kt}from"os";import{join as Qe}from"path";var Dn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:qi()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:qi()}],Qt=[{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"}],Xt={id:"",label:"Default",source:"cli"},Fa=/^\s*-\s+"([^"]+)"/;function qa(o){let e=[],n=!1;for(let t of o.split(`
|
|
140
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let i=t.match(Fa);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Ao(r),source:"cli"})}return Jn([Xt,...e])}function za(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,i)=>{let r=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(t=>{let i=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!i)return[];let r=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Ao(i),s=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let p=d;return typeof p.effort!="string"?[]:[{effort:p.effort,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let p=d;return typeof p.id!="string"?[]:[{id:p.id,label:typeof p.name=="string"?p.name:p.id,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0;return[{id:i,label:r,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function qi(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Ua(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Jn(e.map(n=>({id:n,label:Ao(n),source:"cli"})))}function Ao(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let r=t[1]==="sonnet"?"Sonn":Va(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${r}${s}${t[4]?" Fast":""}`}let i=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return n}async function zi(o="copilot"){let e=await On(o,["help","config"]),n=qa(e);return n.length>1?n:[Xt]}async function Ui(o="codex"){let e=await On(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Qe(Kt(),".codex");return Wi(Qe(t,"models_cache.json"))}),n=za(e);return n.length>0?Jn([...n,...Qt]):Qt}async function Gi(o="claude"){let e=Qe(Kt(),".claude"),n=[Qe(Kt(),".claude","stats-cache.json"),Qe(Kt(),".claude","settings.json"),Qe(Kt(),".claude.json"),Qe(e,"cache","changelog.md")],[t,i,r]=await Promise.all([On(o,["--help"]).catch(()=>""),On(o,["--version"]).catch(()=>""),Ga(e).catch(()=>[])]),s=Ha([...n,...r]),c=await Promise.all(s.map(p=>Wi(p).catch(()=>""))),d=Ua([t,i,...c].join(`
|
|
141
|
+
`));return Jn([...Dn,...d])}function On(o,e,n=5e3){return new Promise((t,i)=>{Ja(o,e,{encoding:"utf-8",timeout:n},(r,s)=>{if(r){i(r);return}t(s)})})}async function Wi(o){return Ba(o,"utf-8")}async function Ga(o){let e=[Qe(o,"projects"),Qe(o,"telemetry")],n=[];for(let t of e)await Hi(t,n,4);return n.sort((t,i)=>i.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Hi(o,e,n){if(n<0)return;let t;try{t=await Na(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async i=>{let r=Qe(o,i.name);if(i.isDirectory()){await Hi(r,e,n-1);return}if(!(!i.isFile()||!Wa(i.name)))try{let s=await La(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function Wa(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Jn(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 Ha(o){return[...new Set(o)]}function Va(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Nn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){n=r;break}}let t=n>=0?n+1:0,i=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),i}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let i=this.bufferEvent(n,e);for(let r of this.listeners)r(i,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let i={...n,seq:t.nextSeq++};return t.events.push(i),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),i}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,n,t){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(i=>{let r=!1,s=()=>{r||(r=!0,i())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!r){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as He}from"crypto";import{createHash as Ka}from"crypto";import{mkdir as Qa,open as Xa,readFile as Vi,readdir as Ya,rename as Za,unlink as ec}from"fs/promises";import{dirname as tc,join as At}from"path";function _e(o){return structuredClone(o)}function Ki(o){return Ka("sha256").update(JSON.stringify(o)).digest("hex")}async function Yt(o,e){await Qa(tc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Xa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
142
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Za(n,o)}catch(i){throw await ec(n).catch(()=>{}),i}}function nc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function oc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=_e(e):o.explanations.push(_e(e))}function Mo(o,e){let n=_e(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(i=>i.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(_e(t.explanation))}else if(t.op==="replace_explanation")oc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(i=>i.id!==t.explanationId),n.relations=n.relations.filter(i=>i.fromId!==t.explanationId&&i.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(i=>i.id===t.concrete.id)||n.concrete.push(_e(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(i=>i.id!==t.concreteId),n.relations=n.relations.filter(i=>i.fromId!==t.concreteId&&i.toId!==t.concreteId);else if(t.op==="add_evidence"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);i.evidence.some(r=>r.id===t.evidence.id)||(i.evidence.push(_e(t.evidence)),i.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(i,_e(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let i=n.explanations.some(s=>s.id===t.relation.fromId),r=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!i||!r)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push(_e(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(i=>i.id!==t.relationId));return n}function ic(o,e){let n=[],t=_e(o);for(let i of e){if(i.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=t.explanations.find(s=>s.id===i.explanationId);r&&n.unshift({op:"add_explanation",explanation:_e(r)})}else if(i.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=t.concrete.find(s=>s.id===i.concreteId);r&&n.unshift({op:"add_concrete",concrete:_e(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=t.explanations.find(c=>c.id===r);s&&n.unshift({op:"replace_explanation",explanation:_e(s)})}else if(i.op==="add_relation")n.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=t.relations.find(s=>s.id===i.relationId);r&&n.unshift({op:"add_relation",relation:_e(r)})}t=Mo(t,[i])}return n}function Qi(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 Bn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=At(e,".popmelt","imprint"),this.manifestPath=At(this.imprintDir,"manifest.json"),this.graphPath=At(this.imprintDir,"graph.json"),this.journalDir=At(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Vi(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 Ya(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=nc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await Vi(At(this.journalDir,t[c]),"utf8")),{hash:p,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||p!==Ki(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=Mo(i,d.mutations),i.updatedAt=d.committedAt,i.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(j=>j.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=t.graph.head.sequence+1,r=ic(t.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:_e(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Ki(s)},d=Mo(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let p=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await Yt(At(this.journalDir,p),c);let x={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Yt(this.graphPath,d),await Yt(this.manifestPath,x),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,i){let r=await this.load(),s=r.transactions.find(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(Qi));if(r.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(x=>Qi(x).some(j=>c.has(j)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Yt(this.graphPath,e.graph),await Yt(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var rc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),sc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ac(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ln(o){return new Set(ac(o).split(" ").filter(e=>e.length>2&&!sc.has(e)))}function Fn(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 Eo(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 tt(o,e,n){return{id:He(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function Te(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Xi(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function Yi(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let i=Number(t);if(!Number.isInteger(i)||i<0||i>=n.length)return{found:!1};n=n[i]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function _o(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let i=JSON.parse(t);if(i.decision==="none"){let T=String(i.reason);if(!rc.has(T))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:T},visibleText:n}}if(i.decision!==void 0&&i.decision!=="mutate")throw new Error("imprint decision is invalid");let r=i.summary,s=r?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:Te(r?.title,120),detail:Te(r?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(i.appliedExplanationIds)?i.appliedExplanationIds.filter(T=>typeof T=="string"&&!!T.trim()):[],p=[];for(let T of Array.isArray(i.mutations)?i.mutations:[]){if(!T||typeof T!="object")continue;let b=T;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let f=Te(b.statement),l=Te(b.rationale);if(!f||!l)continue;p.push({op:"add",clientId:Te(b.clientId,100)||void 0,kind:b.kind,statement:f,rationale:l,scope:Xi(b.scope),rootReason:Te(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let f={op:"revise",explanationId:b.explanationId,statement:Te(b.statement)||void 0,rationale:Te(b.rationale)||void 0,scope:Xi(b.scope),reopenGrounding:b.reopenGrounding===!0};(f.statement||f.rationale||f.scope||f.reopenGrounding)&&p.push(f)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let f=Te(b.summary);f&&p.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:f})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type))){let f=Te(b.rationale);if(!f)continue;p.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:f})}else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let f=Te(b.reason);f&&p.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:f})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let f=Te(b.modelPath,300);f&&p.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:f,rationale:Te(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&p.push({op:"retire",explanationId:b.explanationId,reason:Te(b.reason)})}let x=i.grounding,j=x&&typeof x.explanationId=="string"&&Te(x.question)?{explanationId:x.explanationId,question:Te(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:p,grounding:j},visibleText:n}}catch(i){return{visibleText:n,error:i instanceof Error?i.message:String(i)}}}function Co(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,i)=>[`${i+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(r=>` - Concrete terminal: ${r.modelPath} = ${JSON.stringify(r.value)}`)].join(`
|
|
143
|
+
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(t=>`- ${t.fromId} --${t.type}--> ${t.toId}: ${t.rationale}`)]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation, not merely acceptance of completed work.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. A task-specific edit becomes learning only if the human establishes a reusable dependency or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","Topology assessment is mandatory for every add mutation. Connect the new clientId with relation or supersede mutations whenever it overlaps, specializes, operationalizes, supports, contradicts, or excepts another surfaced or newly-added explanation. If it is genuinely a new root with no meaningful relative, include rootReason on the add mutation explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked to the grounded parent with a refines, operationalizes, or excepts relation.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding only when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<imprint>{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
|
|
144
|
+
`)}var Zt=class{constructor(e,n){this.noopCounts=new Map;this.store=new Bn(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=Ln(e.text??""),t=Ln((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!i.size)return;let{graph:r}=await this.store.load(),s=r.explanations.filter(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let l=Ln([f.statement,f.rationale].join(" ")),y=Ln(f.scope.values.join(" ")),m=Fn(l,n),I=Fn(y,n),u=Fn(y,t),k=Fn(l,t),M=m+I*.2+u*.25+k*.1+(f.state==="grounded"?.08:0)+(i.has(f.id)?1:0),g=i.has(f.id)||(n.size?m>=.12||I>=.5:u>=.2||k>=.2);return{item:f,score:M,relevant:g}}).filter(f=>f.relevant&&f.score>=.18).sort((f,l)=>l.score-f.score||l.item.updatedAt.localeCompare(f.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:f})=>f),p=new Set(d.map(f=>f.id)),x=new Set(r.relations.flatMap(f=>p.has(f.fromId)?[f.toId]:p.has(f.toId)?[f.fromId]:[])),j=new Set(r.explanations.flatMap(f=>x.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),T=r.explanations.filter(f=>j.has(f.id)&&!p.has(f.id)).sort((f,l)=>l.updatedAt.localeCompare(f.updatedAt)).slice(0,4),b=[...d,...T];for(let f of T)p.add(f.id);return{explanations:b.map(f=>{let l=new Set(r.relations.filter(y=>y.fromId===f.id&&y.type==="instantiates").map(y=>y.toId));return{id:f.id,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:f.scope,state:f.state,concrete:r.concrete.filter(y=>l.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||T.length<j.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},relations:r.relations.filter(f=>p.has(f.fromId)&&p.has(f.toId)&&f.type!=="instantiates").map(f=>({id:f.id,type:f.type,fromId:f.fromId,toId:f.toId,rationale:f.rationale}))}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),i=await this.store.load(),r=new Map(i.graph.explanations.map(h=>[h.id,h])),s=new Map,c=new Map,d=[],p=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),j=new Set(e.mutations.flatMap(h=>h.op==="revise"&&e.mutations.some(A=>A.op==="evidence"&&A.stance==="challenges"&&A.explanationId===h.explanationId)?[h.explanationId]:[])),T=new Set(e.mutations.flatMap(h=>h.op==="add"&&h.clientId?[h.clientId]:[])),b=h=>r.has(h)||T.has(h),f=new Set;for(let h of e.mutations)h.op==="relation"&&h.fromId!==h.toId&&b(h.fromId)&&b(h.toId)?(f.add(h.fromId),f.add(h.toId)):h.op==="supersede"&&h.explanationId!==h.replacementId&&b(h.explanationId)&&b(h.replacementId)?(f.add(h.explanationId),f.add(h.replacementId)):h.op==="bind_concrete"&&b(h.explanationId)&&Yi(n.concreteModel,h.modelPath).found&&f.add(h.explanationId);let l=i.graph.explanations.length===0;for(let h of e.mutations){if(h.op!=="add")continue;let A=!!(h.clientId&&f.has(h.clientId)),D=!!h.rootReason?.trim()||l;if(!A&&!D)continue;l&&(l=!1);let B=He();h.clientId&&s.set(h.clientId,B);let U=h.clientId?e.appliedExplanationIds.includes(h.clientId):!1,V={id:B,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:Eo(h.scope),state:U?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};r.set(B,V),p.add(B),d.push({op:"add_explanation",explanation:V})}let y=h=>s.get(h)??h;for(let h of e.mutations){if(h.op!=="revise")continue;let A=y(h.explanationId),D=r.get(A);if(D?.state!=="grounded")continue;let B=He(),U={id:B,kind:D.kind,statement:h.statement??D.statement,rationale:h.rationale??D.rationale,scope:h.scope?Eo(h.scope):D.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};r.set(B,U),c.set(A,B),p.add(B),d.push({op:"add_explanation",explanation:U}),d.push({op:"add_relation",relation:{id:He(),type:"refines",fromId:B,toId:A,rationale:h.rationale??e.summary.detail,createdAt:t}})}let m=h=>{let A=y(h);return c.get(A)??A};for(let h of e.mutations){if(h.op==="add")continue;if(h.op==="bind_concrete"){let D=m(h.explanationId);if(!r.has(D))continue;let B=Yi(n.concreteModel,h.modelPath);if(!B.found)continue;let U=i.graph.concrete.find(V=>V.modelPath===h.modelPath&&JSON.stringify(V.value)===JSON.stringify(B.value));U||(U={id:He(),modelPath:h.modelPath,value:structuredClone(B.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:U})),d.push({op:"add_relation",relation:{id:He(),type:"instantiates",fromId:D,toId:U.id,rationale:h.rationale,createdAt:t}}),p.add(D);continue}if(h.op==="relation"){let D=m(h.fromId),B=m(h.toId);if(!r.has(D)||!r.has(B)||D===B)continue;d.push({op:"add_relation",relation:{id:He(),type:h.type,fromId:D,toId:B,rationale:h.rationale,createdAt:t}}),p.add(D),p.add(B);continue}if(h.op==="supersede"){let D=m(h.explanationId),B=m(h.replacementId);if(!r.has(D)||!r.has(B)||D===B)continue;d.push({op:"add_evidence",explanationId:D,evidence:tt(n,"challenges",h.reason)}),d.push({op:"revise_explanation",explanationId:D,patch:{state:"challenged",supersededBy:B},updatedAt:t}),d.push({op:"add_relation",relation:{id:He(),type:"supersedes",fromId:B,toId:D,rationale:h.reason,createdAt:t}}),p.add(D),p.add(B);continue}let A=m(h.explanationId);if(r.has(A))if(p.add(A),h.op==="revise"){if(c.has(y(h.explanationId)))continue;let D=r.get(A);if(!D||D.state!=="emerging"&&D.state!=="testing")continue;let B={...h.statement?{statement:h.statement}:{},...h.rationale?{rationale:h.rationale}:{},...h.scope?{scope:Eo(h.scope)}:{},...h.reopenGrounding||j.has(h.explanationId)?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:A,patch:B,updatedAt:t})}else if(h.op==="evidence"){if(h.stance==="challenges"&&j.has(h.explanationId))continue;d.push({op:"add_evidence",explanationId:A,evidence:tt(n,h.stance,h.summary)}),h.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"challenged"},updatedAt:t})}else h.op==="retire"&&(d.push({op:"add_evidence",explanationId:A,evidence:tt(n,"challenges",h.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:A,patch:{state:"retired"},updatedAt:t}))}for(let h of e.appliedExplanationIds){let A=m(h),D=r.get(A);!D||D.state==="grounded"||D.state==="retired"||x.has(A)&&!p.has(A)||(p.has(A)||(p.add(A),d.push({op:"add_evidence",explanationId:A,evidence:{...tt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),D.state==="emerging"&&d.push({op:"revise_explanation",explanationId:A,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=He(),u=await this.store.commit({transactionId:I,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),k=new Map(u.graph.explanations.map(h=>[h.id,h])),M=[...p].flatMap(h=>{let A=k.get(h);if(!A)return[];let D=!i.graph.explanations.some(U=>U.id===h),B=A.state==="challenged"||A.state==="retired";return[{explanationId:h,action:D?"added":B?"challenged":"revised",statement:A.statement,state:A.state}]}),g=e.grounding?m(e.grounding.explanationId):void 0,_=g?k.get(g):void 0,$=_?.state==="testing"&&!x.has(_.id)?{explanationId:_.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:M,...$?{grounding:$}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let p=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let x of p)await this.store.undo(x,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,He());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(p=>p.id===t);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${r.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${r.statement}`;else if(e.action==="narrow"){let p=(e.value??"").split(",").map(x=>x.trim()).filter(Boolean);if(!p.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:r.scope.kind,values:p},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${r.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${r.statement}`;else if(e.action==="edit"){let p=e.value?.trim();if(!p)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:p,state:"testing"},updatedAt:n}),d=`Edited: ${p}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:He(),committedAt:n,source:s,summary:d,mutations:c})}};function Zi(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function qn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function $o(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 er(o){let e=$o(qn(o.origin));if(e)return e;let n=$o(qn(o.referer));if(n)return n;let t=qn(o["x-forwarded-host"]);if(!t)return null;let i=qn(o["x-forwarded-proto"])==="https"?"https":"http";return $o(`${i}://${t}`)}function tr(o,e,n=5){let t=(d,p)=>(p.completedAt??p.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(t).slice(0,n),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,p)=>p.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,p)=>(d[p.status]=(d[p.status]??0)+1,d),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as zn}from"crypto";import{mkdir as en,readFile as yt,unlink as lc,writeFile as Et}from"fs/promises";import{dirname as Un,extname as pc,join as Ce}from"path";var cc={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 dc(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 nr(o,e){let n=e??dc(o);return{kind:n,...cc[n]}}function Mt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function or(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var uc={version:1,threads:{}},ir=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],tn={version:2,updatedAt:0,files:{}};function mc(o){return JSON.stringify(o,null,2)}function fc(o){return Object.fromEntries(ir.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function hc(o){let e={...o};for(let n of ir)delete e[n];return e}function _t(o){let e=o;if(o.error){let n=nr(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=Mt(e.result,!1),t=Mt(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 Gn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Ce(e,".popmelt");this.legacyFilePath=Ce(n,"threads.json"),this.threadsDir=Ce(n,"threads"),this.indexPath=Ce(this.threadsDir,"index.json"),this.artifactsDir=Ce(n,"artifacts","thread-messages"),this.mediaDir=Ce(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await yt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,i]of Object.entries(e.files)){let r=await this.readThread(Ce(this.threadsDir,i));r&&(n[t]=r)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await yt(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(_t)}]))},this.index={...tn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...uc,threads:{}},this.index={...tn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let i of Object.values(n.threads))if(i.elementIdentifiers.some(s=>t.has(s)))return i;return null}async createThread(e,n){let t=await this.load(),i={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,n){let i=(await this.load()).threads[e];i&&(i.messages.push(_t(n)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,_t(n)):i.messages.push(_t(n)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=_t(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of n)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((i,r)=>r.updatedAt-i.updatedAt),t.slice(0,e).map(i=>{let s=i.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=i.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let m=y.imprintSummary?.grounding;if(m?.question&&!y.imprintSummary?.resolvedAction)return m.question},p=i.messages.findLastIndex(y=>!!d(y)),x=i.messages.findLastIndex(y=>y.role==="human"),j=p>x?d(i.messages[p]):void 0,T=i.messages.at(-1)?.role,b=Array.from(new Set(i.messages.slice(0,Math.max(0,x)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),f=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),l=c.some(y=>!!y.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:f,hasError:l,lastMessageRole:T,pendingQuestion:j,acknowledgedJobIds:b,elementIdentifiers:i.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await yt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await yt(Ce(Un(this.legacyFilePath),i.path),"utf8");zn("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return _t({...r,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=fc(e),t=hc(e);if(Object.keys(n).length===0)return t;let i=mc(n),r=zn("sha256").update(i).digest("hex"),s=Ce("artifacts","thread-messages",`${r}.json`);await en(this.artifactsDir,{recursive:!0});try{await yt(Ce(Un(this.legacyFilePath),s),"utf8")}catch{await Et(Ce(Un(this.legacyFilePath),s),i)}return{...t,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let n=async t=>{if(Un(t)===this.mediaDir)return t;try{let i=await yt(t),r=zn("sha256").update(i).digest("hex"),s=Ce(this.mediaDir,`${r}${pc(t)||".bin"}`);await en(this.mediaDir,{recursive:!0});try{await yt(s)}catch{await Et(s,i)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,i])=>[t,await n(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,i])=>[t,await Promise.all(i.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([t,i])=>[t,await Promise.all(i.map(async r=>({...r,path:await n(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await en(this.threadsDir,{recursive:!0});let n=this.index??{...tn,files:{}},t=n.files[e.id]??`${zn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Et(Ce(this.threadsDir,t),JSON.stringify(r,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Et(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 en(this.threadsDir,{recursive:!0}),this.index=this.index??{...tn,files:{}},await Et(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...tn,files:{}},t=n.files[e];t&&await lc(Ce(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await en(this.threadsDir,{recursive:!0}),await Et(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as gc,open as yc,readFile as vc,rename as Ic,unlink as wc}from"fs/promises";import{dirname as bc,join as xc}from"path";var rr={schemaVersion:1,theme:"auto",updatedAt:null};function sr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Sc(o,e){await gc(bc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await yc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
145
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await Ic(n,o)}catch(t){throw await wc(n).catch(()=>{}),t}}var Wn=class{constructor(e){this.path=xc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await vc(this.path,"utf8")),n=sr(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...rr}}}catch{return{exists:!1,preferences:{...rr}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Sc(this.path,n),n}};function ar(o){return sr(o)!==null}function cr(o){return Pc(o).slice(0,12)}var kc=[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 Pc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Rc(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let T=7;T>=0;T--)e.push(n/Math.pow(2,T*8)&255);let t=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,p=528734635,x=1541459225,j=new Array(64);for(let T=0;T<e.length;T+=64){for(let M=0;M<16;M++){let g=T+M*4;j[M]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let M=16;M<64;M++){let g=Xe(j[M-15],7)^Xe(j[M-15],18)^j[M-15]>>>3,_=Xe(j[M-2],17)^Xe(j[M-2],19)^j[M-2]>>>10;j[M]=j[M-16]+g+j[M-7]+_>>>0}let b=t,f=i,l=r,y=s,m=c,I=d,u=p,k=x;for(let M=0;M<64;M++){let g=Xe(m,6)^Xe(m,11)^Xe(m,25),_=m&I^~m&u,$=k+g+_+kc[M]+j[M]>>>0,h=Xe(b,2)^Xe(b,13)^Xe(b,22),A=b&f^b&l^f&l,D=h+A>>>0;k=u,u=I,I=m,m=y+$>>>0,y=l,l=f,f=b,b=$+D>>>0}t=t+b>>>0,i=i+f>>>0,r=r+l>>>0,s=s+y>>>0,c=c+m>>>0,d=d+I>>>0,p=p+u>>>0,x=x+k>>>0}return[t,i,r,s,c,d,p,x].map(T=>T.toString(16).padStart(8,"0")).join("")}function Xe(o,e){return o>>>e|o<<32-e}function Rc(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 dr={name:"@popmelt.com/core",version:"0.8.9",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 nn=dr.version;var Lc=1111,Fc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],qc=1800*1e3,zc=3600*1e3,ur=45e3,Uc=5e3,Gc=1e4,Wc=2*1024*1024;function mr(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(`
|
|
146
|
+
`)}function on(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Hc(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 yr(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 Vc(o,e){let n=[];for(let t of o)if(t.type==="delta"){let i=t.text;if(!i)continue;let r=n[n.length-1];r&&r.kind==="text"?r.text+=i:n.push({kind:"text",text:i})}else if(t.type==="tool_use"){let i=t.tool||"",r=t.file??void 0,s=t.content??void 0,c=r?r.split("/").pop()??r:void 0,d;switch(i){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=s?s.split(`
|
|
147
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=i?`Using ${i}`:"tool";break}let p=r??s??void 0,x=r?gr(r)?r:Nc(e,r):void 0,j=n[n.length-1];j&&j.kind==="tool_group"&&j.tool===i?j.items.push({label:d,detail:p,...x?{filePath:x}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:d,detail:p,...x?{filePath:x}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function Kc(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(`
|
|
148
|
+
`)}function Qc(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function fr(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),i=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),r=[...e,...t,...n,...i].map(s=>Qc(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Xc(o,e){let n=o.headers.origin;yr(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 Je(o){let e=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}async function Yc(o,e){let n=[],t=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(t+=r.length,t>e)throw new Error("Request body too large");n.push(r)}return Buffer.concat(n)}function Zc(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function ed(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,i,r]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function Kn(o,e){try{o.res.write(`event: ${e.type}
|
|
205
149
|
data: ${JSON.stringify(e)}
|
|
206
150
|
|
|
207
|
-
`)}catch{}}function
|
|
208
|
-
${t}
|
|
209
|
-
${i}`).digest("hex").slice(0,16)}catch{return}}function jd(o,e){let n=o;for(let t of e.split(".").filter(Boolean)){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[t]}return n}async function Ar(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let i=[["scenarios",e.scenarios??[]]];for(let r of[...t].sort((s,c)=>`${s.kind}:${s.value}`.localeCompare(`${c.kind}:${c.value}`)))if(r.kind==="model_path")i.push([r.kind,r.value,jd(n,r.value)]);else if(r.kind==="source_file"){let s=_r(o,r.value),d=s===o||s.startsWith(`${o}/`)?await Uo(s,"utf8").catch(()=>"[missing]"):"[outside-project]";i.push([r.kind,r.value,d])}else i.push([r.kind,r.value]);return Mr("sha256").update(JSON.stringify(i)).digest("hex").slice(0,16)}async function $r(o={}){let e=new Date().toISOString(),n=o.port??md,t=o.projectRoot??process.cwd(),i=await sd(t).catch(()=>t),r=br(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ee(ld(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,b=[...o.allowedTools??fd],j=o.claudePath??"claude",T=o.copilotPath??"copilot",x=o.provider??"claude",m=o.timeoutMs,p=o.restartMode??"embedded",y=n,h={},f={claude:j,codex:"codex",copilot:T};for(let[a,g]of Object.entries(f))try{let P=g.includes("/")?g:to("which",[g],{encoding:"utf-8"}).trim();h[a]={available:!0,path:P}}catch{h[a]={available:!1,path:null}}function u(a,g){return new Promise(P=>{let v=Sr(g,["--version"],{stdio:["ignore","ignore","ignore"]}),k=!1,S=J=>{k||(k=!0,P(J))},E=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout(E),S(!1)}),v.on("close",J=>{clearTimeout(E),S(J===0)})})}await Promise.all([(async()=>{h.claude&&(h.claude.models=h.claude.available&&h.claude.path?await ir(h.claude.path).catch(()=>zn):zn)})(),(async()=>{h.codex&&(h.codex.models=h.codex.available&&h.codex.path?await or(h.codex.path).catch(()=>tn):tn)})(),(async()=>{h.copilot&&(h.copilot.models=h.copilot.available&&h.copilot.path?await nr(h.copilot.path).catch(()=>[nn]):[nn])})()]);let[A,D,R]=await Promise.all([vo(i),Io(i),wo(i,h.copilot?.path??T)]),C=await bi(i);h.claude&&(h.claude.mcp=A),h.codex&&(h.codex.mcp=D),h.copilot&&(h.copilot.mcp=R),A.found&&A.name&&b.push(`mcp__${A.name}__*`),await id(c,{recursive:!0}),Er(c).catch(()=>{});let I=new qn(1),w=new Rn,M=new Tn(kr),F=null,H=0,U=!1,ne=()=>{H+=1,U=!1,F&&clearTimeout(F),F=null},oe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},ye=()=>{if(p!=="detached"||M.size>0||U)return;U=!0;let a=++H,g=Date.now()+vd,P=()=>{if(a!==H)return;if(M.size>0){ne();return}if(!(I.isRunning||I.depth>0||w.isRunning||w.depth>0)||Date.now()>=g){U=!1,F=setTimeout(oe,50),F.unref?.();return}F=setTimeout(P,250),F.unref?.()};P()},Y=new Set,V=new Xn(i),q=new Jn(i),ge=new rn(i,r),$=new Yn(i),Z=new yn(i),ue=new wn(i),se=new Sn(i,{claudePath:j,provider:x,timeoutMs:m,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let g of Y)eo(g,a)}});q.beginAutomaticInitialization({writerVersion:cn}).then(async a=>{a.state==="ready"?(await q.migrateLegacyEvals(),await q.migrateImprintSnapshot(),await q.syncImprintGraph(),await se.applyCanonicalEntries(await q.getCanonicalModelEntries()),x!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Ae({provider:x,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Oe=20,Je=300*1e3,Re=[];function Ue(){let a=Date.now()-Je;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>Oe);)Re.shift()}let Ve=new Map;async function et(a){if(a.status!=="applied")return[];let g={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},P=di(a,g);if(P.length===0)return[];let v=await q.getEvalDependenciesForDecisions(a.decisionIds),k=a.threadId?await V.getThread(a.threadId):null,S=[...new Set((k?.messages??[]).flatMap(B=>(B.editEvents??[]).flatMap(z=>z.filePath?[z.filePath]:[])).map(B=>qo(B)?Rr(i,B):B))].map(B=>({kind:"source_file",value:B})),E=P.map(B=>{let z=[...new Map([...B.dependencies??[],...v,...S].map(G=>[`${G.kind}:${G.value}:${"subjectId"in G?G.subjectId??"":""}`,G])).values()],L=z.filter(G=>G.kind==="route"),O=z.flatMap(G=>G.kind==="model_path"&&G.value.startsWith("components.")?[G.value.slice(11).split(".")[0]]:[]),N=[...new Set(z.flatMap(G=>"subjectId"in G&&G.subjectId?[G.subjectId]:[]))],Q=L.length>0?L.map((G,re)=>({id:`route-${re+1}`,...G.value.includes("*")?{routePattern:G.value}:{route:G.value},components:O.map(ce=>({name:ce})),subjectIds:N})):[{id:O.length>0?`component-${O[0]}`:"current-page",components:O.map(G=>({name:G})),subjectIds:N}];return{...B,dependencies:z,scenarios:B.scenarios?.length?B.scenarios:Q}}),J=new Set(g.cases.map(B=>B.id));return await q.syncEvalSpecs(E),await se.attachGeneratedEvals(a.id,E.map(B=>({evalId:B.id,title:B.title,action:J.has(B.id)&&(a.evalProjections?.some(z=>z.evalId===B.id)||!a.generatedEvalIds?.includes(B.id))?"extended":"created"}))),E.map(B=>B.id)}async function st(a){let g=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",P=lo(a.claim)||"The product satisfies the declared model constraint.",v={id:`eval-decision-${a.decisionId}`,title:g.charAt(0).toUpperCase()+g.slice(1),status:"pending",category:a.modelPath.startsWith("components.")?"component":a.modelPath.startsWith("tokens.")?"visual":"workflow",prompt:"Verify this product expectation across the declared scenarios.",assertions:[P],rationale:`Protects the ${a.modelPath} constraint from implementation drift.`,sourceDecisionIds:[a.decisionId],sourceThreadIds:[],dependencies:[{kind:"model_path",value:a.modelPath}],scenarios:[{id:a.modelPath.startsWith("components.")?`component-${g.replace(/\s+/g,"-")}`:"current-page",components:a.modelPath.startsWith("components.")?[{name:a.modelPath.slice(11).split(".")[0]}]:void 0}]};return await q.syncEvalSpecs([v]),v.id}let mt=null,Nt;I.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&eo(v,a)}),w.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&eo(v,a)}),w.setProcessor(async a=>{let g=a.provider??x;try{let P=await se.run({provider:g,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),k=P.runId?v.runs.find(E=>E.id===P.runId):void 0;if(P.success&&P.proposalId){let E=await se.findModelProposal(P.proposalId),J=await se.loadModel(),B=E?gi(E,J):null;if(E&&B){let z=E.decisionIds.map(O=>({decisionId:O,status:"projected"}));await q.applyModelProjection({runId:E.runId??E.id,presentationJobId:E.presentationJobId,decisionIds:E.decisionIds,changes:B.map(O=>({path:O.path,value:O.value,decisionIds:O.decisionIds})),coverage:z});let L=await se.applySelectedModelProposal(E.id,B.map(O=>({path:O.path,value:O.value})),B.map(O=>({group:O.path[0]==="rules"||O.path[0]==="components"||O.path[0]==="tokens"?O.path[0]:"model",label:O.label??O.id,detail:O.rationale,path:O.path,value:O.value})),"automatic");L&&await et(L)}}let S=bd(P,k);if(a.threadId&&(await V.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})||await V.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:g})),P.success)a.status="done",a.result=S,w.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ue();else{if(a.status="error",a.error=P.error??"Projection failed",a.threadId){let E=`Model projection failed.
|
|
151
|
+
`)}catch{}}function $t(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function td(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 nd(o,e){return new Promise((n,t)=>{let i=s=>{o.removeListener("listening",r),t(s)},r=()=>{o.removeListener("error",i),n()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function vr(o={}){let e=new Date().toISOString(),n=o.port??Lc,t=o.projectRoot??process.cwd(),i=await Ec(t).catch(()=>t),r=cr(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??$e(Oc(),"popmelt-bridge"),d=o.maxTurns??40,p=o.maxBudgetUsd??1,x=[...o.allowedTools??Fc],j=o.claudePath??"claude",T=o.copilotPath??"copilot",b=o.provider??"claude",f=o.timeoutMs,l=o.restartMode??"embedded",y=n,m={},I={claude:j,codex:"codex",copilot:T};for(let[a,v]of Object.entries(I))try{let R=v.includes("/")?v:jc("which",[v],{encoding:"utf-8"}).trim();m[a]={available:!0,path:R}}catch{m[a]={available:!1,path:null}}function u(a,v){return new Promise(R=>{let w=lr(v,["--version"],{stdio:["ignore","ignore","ignore"]}),P=!1,S=O=>{P||(P=!0,R(O))},C=setTimeout(()=>{w.kill("SIGTERM"),S(!0)},5e3);w.on("error",()=>{clearTimeout(C),S(!1)}),w.on("close",O=>{clearTimeout(C),S(O===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Gi(m.claude.path).catch(()=>Dn):Dn)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Ui(m.codex.path).catch(()=>Qt):Qt)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await zi(m.copilot.path).catch(()=>[Xt]):[Xt])})()]);let[k,M,g]=await Promise.all([po(i),uo(i),mo(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=k),m.codex&&(m.codex.mcp=M),m.copilot&&(m.copilot.mcp=g),k.found&&k.name&&x.push(`mcp__${k.name}__*`),await Ac(c,{recursive:!0}),hr(c).catch(()=>{});let _=new Nn(1),$=new wn,h=new xn(ur),A=null,D=0,B=!1,U=()=>{D+=1,B=!1,A&&clearTimeout(A),A=null},V=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},Y=()=>{if(l!=="detached"||h.size>0||B)return;B=!0;let a=++D,v=Date.now()+Gc,R=()=>{if(a!==D)return;if(h.size>0){U();return}if(!(_.isRunning||_.depth>0||$.isRunning||$.depth>0)||Date.now()>=v){B=!1,A=setTimeout(V,50),A.unref?.();return}A=setTimeout(R,250),A.unref?.()};R()},ie=new Set,N=new Gn(i),pe=new gn(i);pe.sweep();let Z=new _n(i),J=new Zt(i,r),W=new Wn(i),re=new un(i),K=new In(i,{claudePath:j,provider:b,timeoutMs:f,loadProjectableDecisions:a=>Z.getProjectableDecisions(a),onEvent:a=>{for(let v of ie)Kn(v,a)}});Z.beginAutomaticInitialization({writerVersion:nn}).then(async a=>{a.state==="ready"?(await Z.migrateImprintSnapshot(),await Z.syncImprintGraph(),await K.applyCanonicalEntries(await Z.getCanonicalModelEntries()),b!=="copilot"&&(await K.getUnprojectedPatternDecisions()).length>0&&await Ot({provider:b,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Se=20,Ae=300*1e3,Ie=[];function Me(){let a=Date.now()-Ae;for(;Ie.length>0&&(Ie[0].completedAt<a||Ie.length>Se);)Ie.shift()}let Ve=new Map,st=null,Ye;_.addListener((a,v,R)=>{for(let w of ie)(!R||!w.sourceId||w.sourceId===R)&&Kn(w,a)}),$.addListener((a,v,R)=>{for(let w of ie)(!R||!w.sourceId||w.sourceId===R)&&Kn(w,a)}),$.setProcessor(async a=>{let v=a.provider??b;try{let R=await K.run({provider:v,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let w=await K.loadRuns(),P=R.runId?w.runs.find(C=>C.id===R.runId):void 0;if(R.success&&R.proposalId){let C=await K.findModelProposal(R.proposalId),O=await K.loadModel(),L=C?oi(C,O):null;if(C&&L){let G=C.decisionIds.map(F=>({decisionId:F,status:"projected"}));await Z.applyModelProjection({runId:C.runId??C.id,presentationJobId:C.presentationJobId,decisionIds:C.decisionIds,changes:L.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:G}),await K.applySelectedModelProposal(C.id,L.map(F=>({path:F.path,value:F.value})),L.map(F=>({group:F.path[0]==="rules"||F.path[0]==="components"||F.path[0]==="tokens"?F.path[0]:"model",label:F.label??F.id,detail:F.rationale,path:F.path,value:F.value})),"automatic")}}let S=Kc(R,P);if(a.threadId&&(await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:v})),R.success)a.status="done",a.result=S,$.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),Ie.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Me();else{if(a.status="error",a.error=R.error??"Projection failed",a.threadId){let C=`Model projection failed.
|
|
210
152
|
|
|
211
|
-
${a.error}`;await
|
|
153
|
+
${a.error}`;await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:v})}$.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Me()}}catch(R){if(a.status==="cancelled")return;if(a.status="error",a.error=R instanceof Error?R.message:String(R),a.threadId){let w=`Model projection failed.
|
|
212
154
|
|
|
213
|
-
${a.error}`;await
|
|
155
|
+
${a.error}`;await N.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})||await N.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})}$.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Me()}}),_.setProcessor(async a=>{let v=a,R=v._replyPrompt,w=v._replyText,P=v._replyImagePaths,S=a.provider??b,C=!!(a.surfacedProposalIds?.length&&R),O=!C&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&w!==void 0&&await N.updateMessage(a.threadId,a.id,{queued:!1});let L;if(a.threadId){let z=await N.getThread(a.threadId);if(z){for(let ae=z.messages.length-1;ae>=0;ae--)if(z.messages[ae].sessionId){L=z.messages[ae].sessionId;break}}}C&&(L=void 0);let G;if(L&&R){if(G=w??R,P&&P.length>0){G+=`
|
|
214
156
|
|
|
215
|
-
The developer attached reference images with their reply:`;for(let
|
|
216
|
-
Attached image: use the Read tool to view the image at: ${
|
|
157
|
+
The developer attached reference images with their reply:`;for(let z of P)G+=`
|
|
158
|
+
Attached image: use the Read tool to view the image at: ${z}`}a.kind==="synthesize"?G+=`
|
|
217
159
|
|
|
218
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
160
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:G+=`
|
|
219
161
|
|
|
220
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(
|
|
162
|
+
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)G=Vt(a.feedback,a.imagePaths,a.attachmentFiles)+`
|
|
221
163
|
|
|
222
164
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
223
165
|
|
|
224
166
|
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
225
167
|
|
|
226
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let
|
|
168
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let z=!R&&a.threadId?await N.getThreadHistory(a.threadId):void 0,ae=R?null:await K.loadModel();G=R??Ji(a.screenshotPath,a.feedback,{threadHistory:z&&z.length>0?z:void 0,provider:S,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:ae??void 0,screenshotPaths:a.screenshotPaths})}G+=_i(a.memoryReview),O&&(G+=Co(a.imprintContext)),G+=`
|
|
227
169
|
|
|
228
|
-
${Ki}`;let O=kd(a.color,`[\u22B9 ${y}:${a.id}]`),N=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${O} Reviewing ${N} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let Q=new Fn(a.id),G=(de,pe)=>{if(de.type==="delta"&&"text"in de){let _e=Q.push(de.text);_e.visibleText&&(I.accumulateText(pe,"response",_e.visibleText),I.broadcast({...de,text:_e.visibleText},pe,a.sourceId));for(let Ce of _e.orientations)I.broadcast({type:"orientation",jobId:pe,orientation:Ce},pe,a.sourceId);return}else de.type==="thinking"&&"text"in de&&I.accumulateText(pe,"thinking",de.text);I.broadcast(de,pe,a.sourceId)},{process:re,result:ce}=S==="codex"?gn(a.id,{prompt:L,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:z,model:a.model,sandboxMode:E?"read-only":void 0,configOverrides:mn(a.agentSettings),onEvent:G}):S==="copilot"?si(a.id,{prompt:L,projectRoot:i,resumeSessionId:z,model:a.model,timeoutMs:m,copilotPath:h.copilot?.path??T,onEvent:G}):fn(a.id,{prompt:L,projectRoot:i,maxTurns:d,maxBudgetUsd:l,allowedTools:E?["Read"]:b,claudePath:j,resumeSessionId:z,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:m,onEvent:G});I.setActiveProcess(a.id,re);let te=await ce,be=Q.finalize(te.text),Ie=be.visibleText,ve=B?Fo(Ie):{visibleText:Ie,draft:void 0,error:void 0},K=ve.visibleText;for(let de of be.orientations)I.broadcast({type:"orientation",jobId:a.id,orientation:de},a.id,a.sourceId);if(a.result=K,te.success){console.log(`${O} Iteration complete`),te.fileEdits&&te.fileEdits.length>0&&console.log(`${O} Captured ${te.fileEdits.length} file edit(s): ${te.fileEdits.map(W=>`${W.tool} ${W.file_path}`).join(", ")}`),te.editEvents&&te.editEvents.length>0&&console.log(`${O} Captured ${te.editEvents.length} edit event(s): ${te.editEvents.map(W=>`${W.operation} ${W.filePath}`).join(", ")}`),a.status="done";let de=Xi(Ie),pe=Zi(Ie);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let W=new Set(a.annotationIds);pe.every(Ke=>W.has(Ke.annotationId))||(pe=pe.map((Ke,Qe)=>({...Ke,annotationId:a.annotationIds[Qe%a.annotationIds.length]})))}let _e=te.fileEdits&&te.fileEdits.length>0?te.fileEdits.map(W=>`${W.tool} ${W.file_path.split("/").pop()}`):te.toolsUsed,Ce=I.getBufferedEvents(a.id),nt=Ce?wd(Ce.events,i):void 0,ke,ee=Hi(Ie),he=Gi(Ie);if(he)if(!(a.memoryReview?.packets.some(ie=>ie.proposalId===he.proposalId)||a.surfacedProposalIds?.includes(he.proposalId)))ke={status:"rejected",action:he.action,proposalId:he.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{ke=await q.commitConversationalReview(he)}catch(ie){ke={status:"rejected",action:he.action,proposalId:he.proposalId,message:ie instanceof Error?ie.message:String(ie)}}let Pe=[...(te.fileEdits??[]).map(W=>W.file_path),...(te.editEvents??[]).flatMap(W=>W.filePath?[W.filePath]:[])],xe,gt=a.imprintContext?.pendingGroundingExplanationIds??[];if(ve.draft?.decision==="none"&&ge.recordNoop(ve.draft.reason),a.threadId&&ve.draft?.decision==="mutate"&&!he&&!ee)try{xe=await ge.capture(ve.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:gt}),xe&&await q.recordImprintEvidence({summary:xe,threadId:a.threadId,jobId:a.id}).catch(W=>console.warn(`${O} Canonical Imprint evidence linkage failed:`,W))}catch(W){console.warn(`${O} Continuous imprint update failed; the thread result remains available:`,W instanceof Error?W.message:String(W))}else ve.error&&console.warn(`${O} Ignored invalid imprint block: ${ve.error}`);let qe=xe?.transactionId;if(a.threadId&&xe&&!xe.grounding){let W=await V.getThread(a.threadId),ie=new Set(xe.changes.map(Qe=>Qe.explanationId)),Ke=W?Id(W.messages,ie):void 0;if(Ke?.imprintSummary){let Qe=Ke.imprintSummary;await V.updateAssistantMessage(a.threadId,Ke.jobId,{imprintSummary:{...Qe,detail:xe.detail,changes:xe.changes,additionalObservationCount:(Qe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Qe.coalescedTransactionIds??[],xe.transactionId]}}),xe=void 0}}let Lt=gr({question:de,resolutions:pe,changedFiles:Pe,decisionRequired:!!ee,imprintTransactionId:qe,groundingRequired:!!xe?.grounding}),X=nt?.flatMap(W=>W.kind==="orientation"?[W.orientation]:[])??[];if(a.threadId){let W=E?ee?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":K;await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:W,resolutions:!E&&pe.length>0?pe:void 0,question:E?void 0:de??void 0,sessionId:te.sessionId,toolsUsed:E?void 0:_e,editEvents:!E&&te.editEvents&&te.editEvents.length>0?te.editEvents:void 0,segments:!E&&nt&&nt.length>0?nt:void 0,turn:{phase:"complete",orientation:X,result:Lt},result:Lt,memoryReviewCard:ee??void 0,memoryReceipt:ke,imprintSummary:xe,model:a.model,provider:S})}if(a.threadId&&!he&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let W=a.feedback.annotations.flatMap(ie=>ie.linkedSelector?[ie.pathname?`${ie.pathname}:${ie.linkedSelector}`:ie.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Nn(a.feedback)||"[request unavailable]"),responseSummary:de??K,outcome:de?"question_asked":pe.some(ie=>ie.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:te.sessionId},subjectHints:W,filePaths:[...(te.fileEdits??[]).map(ie=>ie.file_path),...(te.editEvents??[]).flatMap(ie=>ie.filePath?[ie.filePath]:[])].map(ie=>qo(ie)?Rr(i,ie):ie),resolutions:pe.map(ie=>({status:ie.status,summary:ie.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ie=>ie.id)})}catch(ie){console.warn(`${O} Canonical memory capture failed; iteration remains available in legacy history:`,ie instanceof Error?ie.message:String(ie))}}if(ke?.status==="committed"&&ke.decisionId&&S!=="copilot"&&await Ae({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${ke.decisionId}`}),a.kind==="run_eval"&&K&&a.evalId&&a.evalRunId){let W=await q.findJournalEvalCase(a.evalId),ie=a._evalRunScope;if(W&&ie){let Ke=ci(Ie,W.assertions),Qe=Date.now(),Zr={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Qe,durationMs:Qe-a.createdAt,scope:ie,provider:S,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:jr(i),rawResponse:Ie,scopeFingerprint:a._evalScopeFingerprint,...Ke};await q.recordEvalVerification(W,Zr),console.log(`${O} Eval run: ${W.title} \u2192 ${Ke.status}`)}}de&&(console.log(`${O} \u{1F4AC} Question detected: "${de.slice(0,120)}" \u2192 broadcasting to ${Y.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),I.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:de,annotationIds:a.annotationIds},a.id,a.sourceId));let me=er(Ie);me.length>0&&(console.log(`${O} Novel pattern(s): ${me.map(W=>`${W.category}/${W.element}`).join(", ")}`),I.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),I.broadcast({type:"done",jobId:a.id,success:!0,resolutions:pe.length>0?pe:void 0,responseText:K,threadId:a.threadId,annotationIds:a.annotationIds,result:Lt},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${O} Error: ${te.error}`),a.status="error",a.error=te.error,a.threadId&&await V.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:te.error||"Unknown error",model:a.model,provider:S}),I.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:te.error||"Unknown error",provider:S,model:a.model,recoverable:te.recoverableError,code:te.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:te.error,threadId:a.threadId,annotationIds:a.annotationIds});Ue()});let Bt=dd(async(a,g)=>{if(Sd(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let P=a.url||"/",v=P.split("?")[0],k=new URL(P,`http://127.0.0.1:${y}`),S=k.pathname,E=Rd(a,k);if(E&&E!==r){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:E,projectName:Zn(i)});return}if(a.headers.origin){if(!Cr(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(E!==r){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:E,projectName:Zn(i)});return}}try{if(a.method==="POST"&&S==="/send")await Me(a,g);else if(a.method==="GET"&&S==="/events")ct(a,g);else if(a.method==="GET"&&S==="/status")await dt(a,g,E);else if(a.method==="GET"&&S==="/ui-preferences")await no(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await oo(a,g);else if(a.method==="PATCH"&&S==="/config")await ft(a,g);else if(a.method==="POST"&&S==="/leases"){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await ze(a),B=typeof J.leaseId=="string"?J.leaseId.trim():"",z=typeof J.ownerPid=="number"&&Number.isInteger(J.ownerPid)&&J.ownerPid>0?J.ownerPid:void 0;if(!B||B.length>128){_(g,400,{error:"A valid leaseId is required."});return}ne();let L=M.acquire(B,z);_(g,201,{ok:!0,lease:L,ttlMs:kr})}catch{_(g,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!J){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=M.heartbeat(J);if(!B){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:B})}else{let B=M.release(J);_(g,B.found?200:404,{ok:B.found}),B.becameEmpty&&ye()}}else if(a.method==="POST"&&S==="/shutdown"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&S==="/restart"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of Y)try{J.res.end()}catch{}Bt.close(()=>{Sr(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(g,200,{providers:h});else if(S.startsWith("/imprint/"))await at(a,g,S);else if(S.startsWith("/memory/"))await we(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await Lr(a,g);else if(a.method==="POST"&&S==="/reply")await tt(a,g);else if(a.method==="POST"&&S==="/cancel")Ft(a,g);else if(a.method==="POST"&&S==="/materialize")_(g,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(g,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let J=await se.loadRuns();_(g,200,J)}else if(a.method==="GET"&&S==="/projection/proposals"){let J=await se.loadModelProposals();_(g,200,J)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let J=S.slice(22,-15);await lt(J,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let J=S.slice(22,-6);await Ne(J,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let J=S.slice(22,-8);await Rt(J,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await zr(a,g);else if(a.method==="DELETE"&&S==="/model/component")await Ur(a,g);else if(a.method==="PATCH"&&S==="/model/token")await qr(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Wr(a,g);else if(a.method==="POST"&&S==="/model/consolidate")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/evals/synthesize")_(g,410,{error:"Standalone eval synthesis was removed. Evals are projected from accepted decisions."});else if(a.method==="GET"&&S==="/evals"){let J=await se.loadModel(),B=await Promise.all((await q.getJournalEvalCases()).map(async O=>{let N=await Ar(i,O,J);return O.verificationState==="passing"&&(!O.verifiedScopeFingerprint||!N||O.verifiedScopeFingerprint!==N)?{...O,verificationState:"stale"}:O})),z=jr(i),L=(await q.getJournalEvalRuns()).filter(O=>!O.codeFingerprint||O.codeFingerprint===z);_(g,200,{version:1,updatedAt:Date.now(),cases:B,runs:L,authority:"journal",legacyMirror:!1})}else if(a.method==="POST"&&S.startsWith("/evals/")&&S.endsWith("/run")){let J=S.slice(7,-4);await io(J,a,g)}else if(a.method==="PATCH"&&S.startsWith("/evals/"))await pn(S.slice(7),a,g);else if(a.method==="GET"&&S==="/model"){let J=await se.loadModel();_(g,200,{model:J})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let J=S.slice(6,S.length-7),B=parseInt(k.searchParams.get("afterSeq")??"-1",10),z=I.getBufferedEvents(J,isNaN(B)?-1:B);z?_(g,200,z):_(g,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await Kr(v.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let J=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),B=await V.listRecent(J);_(g,200,B)}else if(a.method==="GET"&&S.startsWith("/decision/")){let J=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))_(g,400,{error:"Invalid decision id"});else{let B=await V.getThread(J),z=[...B?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(B&&z?.annotationSnapshot){let L=[...B.messages].reverse().find(O=>O.resolutions?.length);_(g,200,{decision:{id:B.id,createdAt:z.timestamp,url:z.annotationSnapshot.url,viewport:z.annotationSnapshot.viewport,color:z.annotationSnapshot.color,annotations:z.annotationSnapshot.annotations,resolutions:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await Z.loadDecision(J);L?_(g,200,{decision:L,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let J=S.slice(8);await Qr(J,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await Xr(J,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Gr(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Hr(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Vr(g):_(g,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),_(g,500,{error:J instanceof Error?J.message:"Internal error"})}});async function we(a,g,P){try{if(a.method==="GET"&&P==="/memory/status"){_(g,200,await q.status());return}if(a.method==="GET"&&P==="/memory/diagnostics"){_(g,200,await q.diagnostics());return}if(a.method==="GET"&&P==="/memory/model-view"){_(g,200,await q.getModelView());return}if(a.method==="GET"&&P==="/memory/imprint-view"){let v=await V.load(),k=[...new Set(Object.values(v.threads).flatMap(S=>ln(S.messages)))];_(g,200,await q.getImprintView(k));return}if(a.method==="POST"&&P==="/memory/constraints"){let v=await ze(a),k=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=typeof v.pathname=="string"?v.pathname.trim():"",E=typeof v.selector=="string"?v.selector.trim():"",J=await q.getModelView(),B=k?J.entries.filter(O=>O.key===`components.${k}`||O.key.startsWith(`components.${k}.`)):[],z=(O,N)=>{if(!N)return!1;if(!O.includes("*"))return O===N;let Q=O.split("*").map(G=>G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${Q}$`).test(N)},L=(await q.getJournalEvalCases()).filter(O=>{if(O.status==="rejected")return!1;let N=(O.dependencies??[]).some(G=>G.kind==="route"&&z(G.value,S)||G.kind==="subject"&&G.value===E),Q=(O.scenarios??[]).some(G=>!!k&&(G.components??[]).some(re=>re.name===k||re.exportName===k)||!!S&&!!G.route&&G.route===S||!!S&&!!G.routePattern&&z(G.routePattern,S));return N||Q}).map(O=>({id:O.id,title:O.title,verificationState:O.verificationState,assertions:O.assertions}));_(g,200,{modelEntries:B,evals:L});return}if(a.method==="POST"&&P==="/memory/conversation-action"){let v=await ze(a),k=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",E=String(v.action);if(!k||!S||!["accept","edit_and_accept","reject","defer"].includes(E)){_(g,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await V.getThread(k),B=J?.messages.find(ce=>ce.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!J||!B){_(g,409,{error:"This decision review card is not available in the thread."});return}let z=await se.findModelProposalsByThread(k),L=(await Promise.all(z.map(async ce=>({proposal:ce,matches:(await Promise.all(ce.decisionIds.map(te=>q.findPendingProposalForLegacyDecision(te)))).some(te=>te?.proposalId===S)})))).find(ce=>ce.matches)?.proposal,O={proposalId:S,action:E,kind:B.kind,claim:E==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:E==="defer"?void 0:`The owner explicitly chose ${E.replaceAll("_"," ")} from the decision review card.`,taskContext:E==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:E==="defer"?["different_action","owner_request"]:void 0};if(O.action==="edit_and_accept"&&!O.claim){_(g,400,{error:"Edited decision wording is required."});return}let N=await q.commitConversationalReview(O),Q=`memory-${ut().slice(0,8)}`,G=E==="accept"?"> Accepted decision":E==="edit_and_accept"?"> Edited and accepted decision":E==="reject"?"> Rejected decision":"> Deferred decision";await V.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:Q,replyToQuestion:G}),await V.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:Q,responseText:"",memoryReceipt:N,provider:St(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),N.status==="committed"&&L&&await se.dismissModelProposal(L.id);let re=St(typeof v.provider=="string"?v.provider:void 0);N.status==="committed"&&N.decisionId&&re!=="copilot"&&await Ae({provider:re,model:typeof v.model=="string"?v.model:void 0,agentSettings:yt(v),threadId:k,reason:`Project accepted decision ${N.decisionId}`}),_(g,N.status==="committed"?200:409,{receipt:N});return}if(a.method==="POST"&&P==="/memory/analyze"){let v=await ze(a),k=await q.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(k.issues.map(E=>E.code))].map(E=>[E,k.issues.filter(J=>J.code===E).length]));_(g,200,{...k,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&P==="/memory/review"){let v=await ze(a),k=await q.review(Do(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&P==="/memory/context"){let v=await ze(a),k=await q.contextualize(Do(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&P==="/memory/initialize"){let v=await ze(a),k=await q.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:cn});_(g,201,{status:k.status,report:{source:k.report.source,imported:k.report.imported,unresolvedAcceptance:k.report.unresolvedAcceptance,deferredModelEntries:k.report.deferredModelEntries,proofCases:k.report.proofCases,schemaIssues:k.report.schemaIssues}});return}if(a.method==="POST"&&P==="/memory/plan"){let v=await ze(a),k=await q.planReview($o(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(g,k.result.ok?200:422,k);return}if(a.method==="POST"&&P==="/memory/commit"){let v=await ze(a),k=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await q.commitReview($o(v.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});_(g,200,{status:await q.status(),journal:S.report});return}if(a.method==="POST"&&P==="/memory/recover"){let v=await ze(a),k=await q.recover(v.confirm===!0);_(g,200,{status:await q.status(),journal:k.report});return}_(g,404,{error:"Memory endpoint not found."})}catch(v){let k=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(k),E=/required|invalid|unsupported|expected|must be|confirmation/i.test(k);if(S||E){_(g,S?409:400,{error:k});return}throw v}}async function at(a,g,P){if(a.method==="GET"&&P==="/imprint/status"){let[v,k]=await Promise.all([ge.store.load(),V.load()]),S=[...new Set(Object.values(k.threads).flatMap(E=>ln(E.messages)))].filter(E=>v.graph.explanations.some(J=>J.id===E&&J.state==="testing"));_(g,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(E=>E.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:v.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&P==="/imprint/action"){let v=await ze(a),k=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",E=String(v.action);if(!k||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(E)){_(g,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await V.getThread(k),z=[...B?.messages??[]].reverse().find(re=>re.role==="assistant"&&re.imprintSummary?.transactionId===S),L=z?.imprintSummary;if(!B||!z||!L){_(g,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){_(g,409,{error:"This imprint summary has already been resolved."});return}let O=`imprint-${ut().slice(0,8)}`;await ge.applyGroundingAction({summary:L,action:E,value:typeof v.value=="string"?v.value:void 0,threadId:k,jobId:O}),await q.recordImprintEvidence({summary:L,action:E,threadId:k,jobId:O}).catch(re=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",re));let N=Dt(z.result,!!z.question),Q=z.turn?{...z.turn,result:Dt(z.turn.result,!!z.question)}:void 0;await V.updateAssistantMessage(k,z.jobId,{imprintSummary:{...L,resolvedAction:E},...N?{result:N}:{},...Q?{turn:Q}:{}});let G={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await V.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:O,replyToQuestion:G[E]}),_(g,200,{ok:!0,action:E});return}_(g,404,{error:"Imprint endpoint not found."})}async function Me(a,g){let{screenshot:P,feedback:v,color:k,provider:S,model:E,reasoningEffort:J,serviceTier:B,sourceId:z,pastedImages:L,pageScreenshots:O}=await Bn(a),N;try{N=JSON.parse(v)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let Q=ut().slice(0,8),G={};if(O.length>0)for(let ee of O){let he=encodeURIComponent(ee.pathname),Pe=Ee(c,`screenshot-${Q}-${he}.webp`);await dn(Pe,ee.data),G[ee.pathname]=Pe}let re=Ee(c,`screenshot-${Q}.webp`);await dn(re,P);let ce={};if(L.length>0)for(let ee of L){let he=Ee(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await dn(he,ee.data),ce[ee.annotationId]||(ce[ee.annotationId]=[]),ce[ee.annotationId].push(he)}let te=N.annotations.map(ee=>ee.linkedSelector?ee.pathname?`${ee.pathname}:${ee.linkedSelector}`:ee.linkedSelector:null).filter(ee=>!!ee),be;if(te.length>0){let ee=await V.findContinuationThread(te);ee?(be=ee.id,await V.addElementIdentifiers(be,te)):be=(await V.createThread(Q,te)).id}else be=(await V.createThread(Q,[])).id;let Ie=N.annotations.map(ee=>ee.id),ve=Object.keys(G).length>0,K=await qi(q,N,te,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await ge.contextualize({text:Nn(N),subjectHints:[...te,...N.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(he=>!!he))],pendingGroundingExplanationIds:ln((await V.getThread(be))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:re,feedback:N,createdAt:Date.now(),color:k,threadId:be,annotationIds:Ie,provider:St(S),model:E||void 0,agentSettings:yt({reasoningEffort:J,serviceTier:B}),...Object.keys(ce).length>0?{imagePaths:ce}:{},sourceId:z||void 0,...ve?{screenshotPaths:G}:{},...K?{memoryReview:K}:{},...de?{imprintContext:de}:{}},_e=new Set(N.annotations.map(ee=>ee.pathname).filter(Boolean)),Ce;if(_e.size>1){let ee=new Map;for(let he of N.annotations){let Pe=he.pathname||"(unknown)";ee.has(Pe)||ee.set(Pe,[]),ee.get(Pe).push(he.instruction||Tr({...N,annotations:[he]}))}Ce=[...ee.entries()].map(([he,Pe])=>`\`${he}\`
|
|
229
|
-
${
|
|
170
|
+
${Di}`;let F=ed(a.color,`[\u22B9 ${y}:${a.id}]`),ce=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${F} Reviewing ${ce} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${L?` (resuming: ${L.slice(0,8)})`:""}`);let q=new $n(a.id),le=(z,ae)=>{if(z.type==="delta"&&"text"in z){let je=q.push(z.text);je.visibleText&&(_.accumulateText(ae,"response",je.visibleText),_.broadcast({...z,text:je.visibleText},ae,a.sourceId));for(let Fe of je.orientations)_.broadcast({type:"orientation",jobId:ae,orientation:Fe},ae,a.sourceId);return}else z.type==="thinking"&&"text"in z&&_.accumulateText(ae,"thinking",z.text);_.broadcast(z,ae,a.sourceId)},{process:se,result:ne}=S==="codex"?pn(a.id,{prompt:G,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:L,model:a.model,sandboxMode:C?"read-only":void 0,configOverrides:cn(a.agentSettings),onEvent:le}):S==="copilot"?Qo(a.id,{prompt:G,projectRoot:i,resumeSessionId:L,model:a.model,timeoutMs:f,copilotPath:m.copilot?.path??T,onEvent:le}):dn(a.id,{prompt:G,projectRoot:i,maxTurns:d,maxBudgetUsd:p,allowedTools:C?["Read"]:x,claudePath:j,resumeSessionId:L,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:le});_.setActiveProcess(a.id,se);let X=await ne,be=q.finalize(X.text),ue=be.visibleText,he=O?_o(ue):{visibleText:ue,draft:void 0,error:void 0},ke=he.visibleText;for(let z of be.orientations)_.broadcast({type:"orientation",jobId:a.id,orientation:z},a.id,a.sourceId);if(a.result=ke,X.success){console.log(`${F} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${F} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(te=>`${te.tool} ${te.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${F} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(te=>`${te.operation} ${te.filePath}`).join(", ")}`),a.status="done";let z=Ni(ue),ae=Li(ue);if(ae.length>0&&a.annotationIds&&a.annotationIds.length>0){let te=new Set(a.annotationIds);ae.every(pt=>te.has(pt.annotationId))||(ae=ae.map((pt,ut)=>({...pt,annotationId:a.annotationIds[ut%a.annotationIds.length]})))}let je=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(te=>`${te.tool} ${te.file_path.split("/").pop()}`):X.toolsUsed,Fe=_.getBufferedEvents(a.id),qe=Fe?Vc(Fe.events,i):void 0,Re,ze=$i(ue),xe=Ci(ue);if(xe)if(!(a.memoryReview?.packets.some(de=>de.proposalId===xe.proposalId)||a.surfacedProposalIds?.includes(xe.proposalId)))Re={status:"rejected",action:xe.action,proposalId:xe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Re=await Z.commitConversationalReview(xe)}catch(de){Re={status:"rejected",action:xe.action,proposalId:xe.proposalId,message:de instanceof Error?de.message:String(de)}}let lt=[...(X.fileEdits??[]).map(te=>te.file_path),...(X.editEvents??[]).flatMap(te=>te.filePath?[te.filePath]:[])],H,ge=a.imprintContext?.pendingGroundingExplanationIds??[];if(he.draft?.decision==="none"&&J.recordNoop(he.draft.reason),a.threadId&&he.draft?.decision==="mutate"&&!xe&&!ze)try{H=await J.capture(he.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await K.loadModel(),pendingGroundingExplanationIds:ge}),H&&await Z.recordImprintEvidence({summary:H,threadId:a.threadId,jobId:a.id}).catch(te=>console.warn(`${F} Canonical Imprint evidence linkage failed:`,te))}catch(te){console.warn(`${F} Continuous imprint update failed; the thread result remains available:`,te instanceof Error?te.message:String(te))}else he.error&&console.warn(`${F} Ignored invalid imprint block: ${he.error}`);let Ne=H?.transactionId;if(a.threadId&&H&&!H.grounding){let te=await N.getThread(a.threadId),de=new Set(H.changes.map(ut=>ut.explanationId)),pt=te?Hc(te.messages,de):void 0;if(pt?.imprintSummary){let ut=pt.imprintSummary;await N.updateAssistantMessage(a.threadId,pt.jobId,{imprintSummary:{...ut,detail:H.detail,changes:H.changes,additionalObservationCount:(ut.additionalObservationCount??0)+1,coalescedTransactionIds:[...ut.coalescedTransactionIds??[],H.transactionId]}}),H=void 0}}let Q=or({question:z,resolutions:ae,changedFiles:lt,decisionRequired:!!ze,imprintTransactionId:Ne,groundingRequired:!!H?.grounding}),me=qe?.flatMap(te=>te.kind==="orientation"?[te.orientation]:[])??[];if(a.threadId){let te=C?ze?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":ke;await N.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:te,resolutions:!C&&ae.length>0?ae:void 0,question:C?void 0:z??void 0,sessionId:X.sessionId,toolsUsed:C?void 0:je,editEvents:!C&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!C&&qe&&qe.length>0?qe:void 0,turn:{phase:"complete",orientation:me,result:Q},result:Q,memoryReviewCard:ze??void 0,memoryReceipt:Re,imprintSummary:H,model:a.model,provider:S})}if(a.threadId&&!xe&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let te=a.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await Z.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:w??(Cn(a.feedback)||"[request unavailable]"),responseSummary:z??ke,outcome:z?"question_asked":ae.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:te,filePaths:[...(X.fileEdits??[]).map(de=>de.file_path),...(X.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>gr(de)?Jc(i,de):de),resolutions:ae.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(de=>de.id)})}catch(de){console.warn(`${F} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}Re?.status==="committed"&&Re.decisionId&&S!=="copilot"&&await Ot({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Re.decisionId}`}),z&&(console.log(`${F} \u{1F4AC} Question detected: "${z.slice(0,120)}" \u2192 broadcasting to ${ie.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),_.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:z,annotationIds:a.annotationIds},a.id,a.sourceId));let fe=Fi(ue);fe.length>0&&(console.log(`${F} Novel pattern(s): ${fe.map(te=>`${te.category}/${te.element}`).join(", ")}`),_.broadcast({type:"novel_patterns",jobId:a.id,patterns:fe,threadId:a.threadId},a.id,a.sourceId)),_.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ae.length>0?ae:void 0,responseText:ke,threadId:a.threadId,annotationIds:a.annotationIds,result:Q},a.id,a.sourceId),Ie.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${F} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await N.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:S}),_.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:S,model:a.model,recoverable:X.recoverableError,code:X.errorCode},a.id,a.sourceId),Ie.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});Me()});let at=$c(async(a,v)=>{if(Xc(a,v),a.method==="OPTIONS"){v.writeHead(204),v.end();return}let R=a.url||"/",w=R.split("?")[0],P=new URL(R,`http://127.0.0.1:${y}`),S=P.pathname,C=Zc(a,P);if(C&&C!==r){E(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:Vn(i)});return}if(a.headers.origin){if(!yr(a.headers.origin)){E(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(C!==r){E(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:Vn(i)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let O=P.searchParams.get("annotationId")?.trim()??"",L=P.searchParams.get("name")?.trim()??"",G=P.searchParams.get("kind"),F=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!O||O.length>128||!/^[a-z0-9_-]+$/i.test(O)){E(v,400,{error:"A valid annotationId is required."});return}if(G!=="svg"&&G!=="text"||G==="svg"&&F!=="image/svg+xml"||G==="text"&&F!=="text/plain"){E(v,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ce=await Yc(a,Wc);if(ce.length===0){E(v,400,{error:"Attachment is empty."});return}let q=await pe.stage({annotationId:O,name:L,mimeType:F,kind:G,data:ce});E(v,201,{attachment:{id:q.id,name:q.name,mimeType:q.mimeType,size:q.size,kind:q.kind}})}else if(a.method==="POST"&&S==="/draft-attachments/claim"){let O=await Je(a),L=Array.isArray(O.ids)?O.ids.filter(G=>typeof G=="string").slice(0,100):[];await pe.claim(L),E(v,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await pe.release([S.slice(19)]),E(v,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await Qn(a,v);else if(a.method==="GET"&&S==="/events")nt(a,v);else if(a.method==="GET"&&S==="/status")await Ee(a,v,C);else if(a.method==="GET"&&S==="/ui-preferences")await ot(v);else if(a.method==="PATCH"&&S==="/ui-preferences")await it(a,v);else if(a.method==="PATCH"&&S==="/config")await Ze(a,v);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){E(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let O=await Je(a),L=typeof O.leaseId=="string"?O.leaseId.trim():"",G=typeof O.ownerPid=="number"&&Number.isInteger(O.ownerPid)&&O.ownerPid>0?O.ownerPid:void 0;if(!L||L.length>128){E(v,400,{error:"A valid leaseId is required."});return}U();let F=h.acquire(L,G);E(v,201,{ok:!0,lease:F,ttlMs:ur})}catch{E(v,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){E(v,409,{error:"Bridge leases are only available for detached bridges."});return}let O="";try{O=decodeURIComponent(S.slice(8))}catch{E(v,400,{error:"Invalid lease id."});return}if(!O){E(v,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let L=h.heartbeat(O);if(!L){E(v,404,{error:"Lease not found."});return}E(v,200,{ok:!0,lease:L})}else{let L=h.release(O);E(v,L.found?200:404,{ok:L.found}),L.becameEmpty&&Y()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){E(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}E(v,200,{ok:!0}),setTimeout(V,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){E(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}E(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let O of ie)try{O.res.end()}catch{}at.close(()=>{lr(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")E(v,200,{providers:m});else if(S.startsWith("/imprint/"))await sn(a,v,S);else if(S.startsWith("/memory/"))await rn(a,v,S);else if(a.method==="POST"&&S==="/mcp/install")await vt(a,v);else if(a.method==="POST"&&S==="/reply")await ve(a,v);else if(a.method==="POST"&&S==="/cancel")ct(a,v);else if(a.method==="POST"&&S==="/materialize")E(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")E(v,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let O=await K.loadRuns();E(v,200,O)}else if(a.method==="GET"&&S==="/projection/proposals"){let O=await K.loadModelProposals();E(v,200,O)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let O=S.slice(22,-15);await Dt(O,a,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let O=S.slice(22,-6);await Xn(O,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let O=S.slice(22,-8);await Oe(O,a,v)}else if(S.startsWith("/model/proposals/"))E(v,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await dt(a,v);else if(a.method==="DELETE"&&S==="/model/component")await Yn(a,v);else if(a.method==="PATCH"&&S==="/model/token")await an(a,v);else if(a.method==="DELETE"&&S==="/model/token")await kr(a,v);else if(a.method==="POST"&&S==="/model/consolidate")E(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")E(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let O=await K.loadModel();E(v,200,{model:O})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let O=S.slice(6,S.length-7),L=parseInt(P.searchParams.get("afterSeq")??"-1",10),G=_.getBufferedEvents(O,isNaN(L)?-1:L);G?E(v,200,G):E(v,404,{error:"Unknown job"})}else if(a.method==="GET"&&w.startsWith("/files/"))await jr(w.slice(7),v);else if(a.method==="GET"&&S==="/threads/recent"){let O=Math.min(Math.max(parseInt(P.searchParams.get("limit")??"5",10)||5,1),20),L=await N.listRecent(O);E(v,200,L)}else if(a.method==="GET"&&S.startsWith("/decision/")){let O=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(O))E(v,400,{error:"Invalid decision id"});else{let L=await N.getThread(O),G=[...L?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(L&&G?.annotationSnapshot){let F=[...L.messages].reverse().find(ce=>ce.resolutions?.length);E(v,200,{decision:{id:L.id,createdAt:G.timestamp,url:G.annotationSnapshot.url,viewport:G.annotationSnapshot.viewport,color:G.annotationSnapshot.color,annotations:G.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await re.loadDecision(O);F?E(v,200,{decision:F,authority:"legacy_archive"}):E(v,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let O=S.slice(8);await Ar(O,v)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let O=S.slice(8);await Mr(O,v)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Pr(a,v):a.method==="GET"&&S==="/canvas/manifest"?await Rr(v):a.method==="GET"&&S==="/canvas/app.mjs"?await Tr(v):E(v,404,{error:"Not found"})}catch(O){console.error("[Bridge] Request error:",O),E(v,500,{error:O instanceof Error?O.message:"Internal error"})}});async function rn(a,v,R){try{if(a.method==="GET"&&R==="/memory/status"){E(v,200,await Z.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){E(v,200,await Z.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){E(v,200,await Z.getModelView());return}if(a.method==="GET"&&R==="/memory/imprint-view"){let w=await N.load(),P=[...new Set(Object.values(w.threads).flatMap(S=>on(S.messages)))];E(v,200,await Z.getImprintView(P));return}if(a.method==="POST"&&R==="/memory/constraints"){let w=await Je(a),P=typeof w.reactComponent=="string"?w.reactComponent.trim():"",S=await Z.getModelView(),C=P?S.entries.filter(O=>O.key===`components.${P}`||O.key.startsWith(`components.${P}.`)):[];E(v,200,{modelEntries:C});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let w=await Je(a),P=typeof w.threadId=="string"?w.threadId:"",S=typeof w.proposalId=="string"?w.proposalId:"",C=String(w.action);if(!P||!S||!["accept","edit_and_accept","reject","defer"].includes(C)){E(v,400,{error:"A valid thread, proposal, and review action are required."});return}let O=await N.getThread(P),L=O?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!O||!L){E(v,409,{error:"This decision review card is not available in the thread."});return}let G=await K.findModelProposalsByThread(P),F=(await Promise.all(G.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(be=>Z.findPendingProposalForLegacyDecision(be)))).some(be=>be?.proposalId===S)})))).find(X=>X.matches)?.proposal,ce={proposalId:S,action:C,kind:L.kind,claim:C==="edit_and_accept"&&typeof w.claim=="string"?w.claim.trim():void 0,reason:C==="defer"?void 0:`The owner explicitly chose ${C.replaceAll("_"," ")} from the decision review card.`,taskContext:C==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:C==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){E(v,400,{error:"Edited decision wording is required."});return}let q=await Z.commitConversationalReview(ce),le=`memory-${Ct().slice(0,8)}`,se=C==="accept"?"> Accepted decision":C==="edit_and_accept"?"> Edited and accepted decision":C==="reject"?"> Rejected decision":"> Deferred decision";await N.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:le,replyToQuestion:se}),await N.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:le,responseText:"",memoryReceipt:q,provider:$t(typeof w.provider=="string"?w.provider:void 0),model:typeof w.model=="string"?w.model:void 0}),q.status==="committed"&&F&&await K.dismissModelProposal(F.id);let ne=$t(typeof w.provider=="string"?w.provider:void 0);q.status==="committed"&&q.decisionId&&ne!=="copilot"&&await Ot({provider:ne,model:typeof w.model=="string"?w.model:void 0,agentSettings:It(w),threadId:P,reason:`Project accepted decision ${q.decisionId}`}),E(v,q.status==="committed"?200:409,{receipt:q});return}if(a.method==="POST"&&R==="/memory/analyze"){let w=await Je(a),P=await Z.analyzeLegacy({projectKey:typeof w.projectKey=="string"?w.projectKey:void 0}),S=Object.fromEntries([...new Set(P.issues.map(C=>C.code))].map(C=>[C,P.issues.filter(O=>O.code===C).length]));E(v,200,{...P,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&R==="/memory/review"){let w=await Je(a),P=await Z.review(Ro(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});E(v,200,P);return}if(a.method==="POST"&&R==="/memory/context"){let w=await Je(a),P=await Z.contextualize(Ro(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});E(v,200,P);return}if(a.method==="POST"&&R==="/memory/initialize"){let w=await Je(a),P=await Z.initializeFromLegacy({confirmed:w.confirm===!0,projectKey:typeof w.projectKey=="string"?w.projectKey:void 0,writerVersion:nn});E(v,201,{status:P.status,report:{source:P.report.source,imported:P.report.imported,unresolvedAcceptance:P.report.unresolvedAcceptance,deferredModelEntries:P.report.deferredModelEntries,proofCases:P.report.proofCases,schemaIssues:P.report.schemaIssues}});return}if(a.method==="POST"&&R==="/memory/plan"){let w=await Je(a),P=await Z.planReview(Po(w.command),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});E(v,P.result.ok?200:422,P);return}if(a.method==="POST"&&R==="/memory/commit"){let w=await Je(a),P=w.transaction&&typeof w.transaction=="object"&&!Array.isArray(w.transaction)?w.transaction:{},S=await Z.commitReview(Po(w.command),{transactionId:typeof P.transactionId=="string"?P.transactionId:"",committedAt:typeof P.committedAt=="string"?P.committedAt:""});E(v,200,{status:await Z.status(),journal:S.report});return}if(a.method==="POST"&&R==="/memory/recover"){let w=await Je(a),P=await Z.recover(w.confirm===!0);E(v,200,{status:await Z.status(),journal:P.report});return}E(v,404,{error:"Memory endpoint not found."})}catch(w){let P=w instanceof Error?w.message:String(w),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(P),C=/required|invalid|unsupported|expected|must be|confirmation/i.test(P);if(S||C){E(v,S?409:400,{error:P});return}throw w}}async function sn(a,v,R){if(a.method==="GET"&&R==="/imprint/status"){let[w,P]=await Promise.all([J.store.load(),N.load()]),S=[...new Set(Object.values(P.threads).flatMap(C=>on(C.messages)))].filter(C=>w.graph.explanations.some(O=>O.id===C&&O.state==="testing"));E(v,200,{state:"ready",head:w.graph.head,updatedAt:w.graph.updatedAt,explanationCount:w.graph.explanations.filter(C=>C.state!=="retired").length,concreteCount:w.graph.concrete.length,relationCount:w.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:w.recoveredTransactions,admission:J.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let w=await Je(a),P=typeof w.threadId=="string"?w.threadId:"",S=typeof w.transactionId=="string"?w.transactionId:"",C=String(w.action);if(!P||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(C)){E(v,400,{error:"A valid thread, imprint update, and action are required."});return}let L=await N.getThread(P),G=[...L?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),F=G?.imprintSummary;if(!L||!G||!F){E(v,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){E(v,409,{error:"This imprint summary has already been resolved."});return}let ce=`imprint-${Ct().slice(0,8)}`;await J.applyGroundingAction({summary:F,action:C,value:typeof w.value=="string"?w.value:void 0,threadId:P,jobId:ce}),await Z.recordImprintEvidence({summary:F,action:C,threadId:P,jobId:ce}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let q=Mt(G.result,!!G.question),le=G.turn?{...G.turn,result:Mt(G.turn.result,!!G.question)}:void 0;await N.updateAssistantMessage(P,G.jobId,{imprintSummary:{...F,resolvedAction:C},...q?{result:q}:{},...le?{turn:le}:{}});let se={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 N.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:ce,replyToQuestion:se[C]}),E(v,200,{ok:!0,action:C});return}E(v,404,{error:"Imprint endpoint not found."})}async function Qn(a,v){let{screenshot:R,feedback:w,color:P,provider:S,model:C,reasoningEffort:O,serviceTier:L,sourceId:G,pastedImages:F,pageScreenshots:ce}=await To(a),q;try{q=JSON.parse(w)}catch{E(v,400,{error:"Invalid feedback JSON"});return}let le=q.annotations.flatMap(H=>(H.attachments??[]).map(ge=>({id:ge.id,annotationId:H.id}))),se;try{se=le.length>0?await pe.promote(le):void 0}catch(H){E(v,409,{error:H instanceof Error?H.message:"Draft attachment unavailable."});return}let ne=Ct().slice(0,8),X={};if(ce.length>0)for(let H of ce){let ge=encodeURIComponent(H.pathname),Ne=$e(c,`screenshot-${ne}-${ge}.webp`);await Hn(Ne,H.data),X[H.pathname]=Ne}let be=$e(c,`screenshot-${ne}.webp`);await Hn(be,R);let ue={};if(F.length>0)for(let H of F){let ge=$e(c,`pasted-${ne}-${H.annotationId}-${H.index}.webp`);await Hn(ge,H.data),ue[H.annotationId]||(ue[H.annotationId]=[]),ue[H.annotationId].push(ge)}let he=q.annotations.map(H=>H.linkedSelector?H.pathname?`${H.pathname}:${H.linkedSelector}`:H.linkedSelector:null).filter(H=>!!H),ke;if(he.length>0){let H=await N.findContinuationThread(he);H?(ke=H.id,await N.addElementIdentifiers(ke,he)):ke=(await N.createThread(ne,he)).id}else ke=(await N.createThread(ne,[])).id;let z=q.annotations.map(H=>H.id),ae=Object.keys(X).length>0,je=await Ei(Z,q,he,H=>console.warn(`[\u22B9 ${y}:${ne}] Contextual memory unavailable; continuing without it:`,H instanceof Error?H.message:String(H))),Fe=await J.contextualize({text:Cn(q),subjectHints:[...he,...q.annotations.flatMap(H=>[H.pathname,H.elements?.[0]?.reactComponent].filter(ge=>!!ge))],pendingGroundingExplanationIds:on((await N.getThread(ke))?.messages??[])}).catch(H=>{console.warn(`[\u22B9 ${y}:${ne}] Imprint context unavailable; continuing without it:`,H instanceof Error?H.message:String(H))}),qe={id:ne,status:"queued",screenshotPath:be,feedback:q,createdAt:Date.now(),color:P,threadId:ke,annotationIds:z,provider:$t(S),model:C||void 0,agentSettings:It({reasoningEffort:O,serviceTier:L}),...Object.keys(ue).length>0?{imagePaths:ue}:{},...se&&Object.keys(se).length>0?{attachmentFiles:se}:{},sourceId:G||void 0,...ae?{screenshotPaths:X}:{},...je?{memoryReview:je}:{},...Fe?{imprintContext:Fe}:{}},Re=new Set(q.annotations.map(H=>H.pathname).filter(Boolean)),ze;if(Re.size>1){let H=new Map;for(let ge of q.annotations){let Ne=ge.pathname||"(unknown)";H.has(Ne)||H.set(Ne,[]),H.get(Ne).push(ge.instruction||fr({...q,annotations:[ge]}))}ze=[...H.entries()].map(([ge,Ne])=>`\`${ge}\`
|
|
171
|
+
${Ne.map(Q=>`- ${Q}`).join(`
|
|
230
172
|
`)}`).join(`
|
|
231
|
-
`)}else
|
|
232
|
-
`):
|
|
233
|
-
`)
|
|
234
|
-
`)),Ie){let X=Ie,W=[...X._replyTexts??(X._replyText?[X._replyText]:[]),k],ie=[...X._replyImagePaths??[],...K];X._replyTexts=W,X._replyText=Pr(W),X._replyImagePaths=ie.length>0?ie:void 0,X._replyPrompt=gt,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=_e??X.memoryReview,X.imprintContext=Ce??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...xe])],_(g,200,{jobId:ve,position:1,threadId:v,bundled:!0});return}let qe={id:ve,status:"queued",screenshotPath:ce,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:v,annotationIds:ee.length>0?ee:void 0,provider:he,model:J||void 0,agentSettings:B,sourceId:z||void 0,..._e?{memoryReview:_e}:{},...Ce?{imprintContext:Ce}:{},...xe.length?{surfacedProposalIds:xe}:{}};re?qe.kind="resolve_eval":te&&(qe.kind=te),qe._replyPrompt=gt,qe._evalRemediation=!!re,qe._replyTexts=[k],qe._replyText=Pr([k]),K.length>0&&(qe._replyImagePaths=K);let Lt=be?I.enqueueNext(qe):I.enqueue(qe);_(g,200,{jobId:ve,position:Lt,threadId:v})}function ct(a,g){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),g.write(`event: connected
|
|
173
|
+
`)}else ze=fr(q);let xe=Vt(q,Object.keys(ue).length>0?ue:void 0,se);await N.appendMessage(ke,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:be,...ae?{screenshotPaths:X}:{},...Object.keys(ue).length>0?{imagePaths:ue}:{},...se&&Object.keys(se).length>0?{attachmentFiles:se}:{},annotationIds:z,annotationSnapshot:{url:q.url,viewport:q.viewport,annotations:q.annotations,color:P||void 0},feedbackSummary:ze,feedbackContext:xe||void 0,...je?{memoryReview:je}:{},...Fe?{imprintContext:Fe}:{}});let lt=_.enqueue(qe);E(v,200,{jobId:ne,position:lt,threadId:ke})}async function ve(a,v){let R=a.headers["content-type"]||"",w,P,S,C,O,L,G,F,ce=[];if(R.includes("multipart/form-data")){let Q=await To(a),me=Q.feedback?JSON.parse(Q.feedback):{};w=me.threadId,P=me.reply,S=me.color,C=me.provider,O=me.model,L=It(me),G=me.sourceId||Q.sourceId,F=typeof me.memoryReviewProposalId=="string"?me.memoryReviewProposalId:void 0;for(let fe of Q.pastedImages)ce.push(fe.data)}else{let Q=[];for await(let te of a)Q.push(typeof te=="string"?Buffer.from(te):te);let me=Buffer.concat(Q).toString("utf-8"),fe;try{fe=JSON.parse(me)}catch{E(v,400,{error:"Invalid JSON"});return}w=fe.threadId,P=fe.reply,S=fe.color,C=fe.provider,O=fe.model,L=It(fe),G=fe.sourceId,F=fe.memoryReviewProposalId}if(!w||!P){E(v,400,{error:"Missing threadId or reply"});return}let q=await N.getThread(w);if(!q){E(v,404,{error:"Thread not found"});return}let le;if(F){let Q=await K.findModelProposalsByThread(w);if(le=(await Promise.all(Q.flatMap(fe=>fe.authorityStatus==="accepted"?[]:fe.decisionIds.map(async te=>({modelProposalId:fe.id,underlying:await Z.findPendingProposalForLegacyDecision(te)}))))).filter(fe=>!!fe.underlying).find(fe=>fe.underlying.proposalId===F),!le){E(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let se="";{let Q=await N.getThreadHistory(w);for(let me=Q.length-1;me>=0;me--)if(Q[me].screenshotPath){se=Q[me].screenshotPath;break}}let ne=await rt(w);if(!se&&!ne){E(v,400,{error:"No screenshot available"});return}let X=_.hasActiveThread(w),be=X?_.getQueuedThreadJob(w,Q=>Q._replyText!==void 0||Q._replyPrompt!==void 0):null,ue=be?.id??Ct().slice(0,8),he=[],ke=`${ue}-${Date.now()}`;for(let Q=0;Q<ce.length;Q++){let me=$e(c,`reply-${ke}-${Q}.webp`);await Hn(me,ce[Q]),he.push(me)}await N.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:ue,replyToQuestion:P,screenshotPath:se,...X?{queued:!0}:{},...he.length>0?{replyImagePaths:he}:{}});let z=await N.getThreadHistory(w),ae=[...z].reverse().find(Q=>Q.memoryReview)?.memoryReview,je=await J.contextualize({text:P,subjectHints:q.elementIdentifiers,pendingGroundingExplanationIds:on(z)}).catch(Q=>{console.warn(`[\u22B9 ${y}:${ue}] Imprint context unavailable for reply; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),Fe=new Set(z.flatMap(Q=>Q.memoryReceipt?.status==="committed"?[Q.memoryReceipt.proposalId]:[])),qe=[...z].reverse().find(Q=>Q.memoryReviewCard&&!Fe.has(Q.memoryReviewCard.proposalId))?.memoryReviewCard,Re=[];for(let Q of z)if(Q.annotationIds)for(let me of Q.annotationIds)Re.includes(me)||Re.push(me);let ze=$t(C),xe=le,lt=xe?[xe.underlying.proposalId]:qe?[qe.proposalId]:[],H=Bi(se,z,ze,he.length>0?he:void 0);if(xe?H+=["","## Decision review card",`Privately review proposal ${xe.underlying.proposalId}: ${xe.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(`
|
|
174
|
+
`):qe&&(H+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(qe)}`,"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(`
|
|
175
|
+
`)),be){let Q=be,fe=[...Q._replyTexts??(Q._replyText?[Q._replyText]:[]),P],te=[...Q._replyImagePaths??[],...he];Q._replyTexts=fe,Q._replyText=mr(fe),Q._replyImagePaths=te.length>0?te:void 0,Q._replyPrompt=H,Q.annotationIds=Re.length>0?Re:Q.annotationIds,Q.agentSettings=L??Q.agentSettings,Q.memoryReview=ae??Q.memoryReview,Q.imprintContext=je??Q.imprintContext,Q.surfacedProposalIds=[...new Set([...Q.surfacedProposalIds??[],...lt])],E(v,200,{jobId:ue,position:1,threadId:w,bundled:!0});return}let ge={id:ue,status:"queued",screenshotPath:se,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:w,annotationIds:Re.length>0?Re:void 0,provider:ze,model:O||void 0,agentSettings:L,sourceId:G||void 0,...ae?{memoryReview:ae}:{},...je?{imprintContext:je}:{},...lt.length?{surfacedProposalIds:lt}:{}};ne&&(ge.kind=ne),ge._replyPrompt=H,ge._replyTexts=[P],ge._replyText=mr([P]),he.length>0&&(ge._replyImagePaths=he);let Ne=X?_.enqueueNext(ge):_.enqueue(ge);E(v,200,{jobId:ue,position:Ne,threadId:w})}function nt(a,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
|
|
235
176
|
data: {"status":"connected"}
|
|
236
177
|
|
|
237
|
-
`);let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,k={id:ut().slice(0,8),res:g,sourceId:v};Y.add(k),a.on("close",()=>{Y.delete(k)})}async function dt(a,g,P){s??=mr(a.headers),Ue();let v=[...I.allActive,...w.allActive.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds??[],color:"#000000",kind:"project_model",standalone:K.standalone}))],[k,S,E,J,B]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),q.status(),ge.store.load(),V.load()]),z=[],L=K=>K.reason instanceof Error?K.reason.message:String(K.reason);k.status==="rejected"&&z.push({subsystem:"projection",message:L(k)}),S.status==="rejected"&&z.push({subsystem:"projection",message:L(S)}),E.status==="rejected"?z.push({subsystem:"memory",message:L(E)}):E.value.state==="degraded"&&z.push({subsystem:"memory",message:E.value.error??"Product memory is degraded."}),J.status==="rejected"&&z.push({subsystem:"imprint",message:L(J)}),B.status==="rejected"&&z.push({subsystem:"threads",message:L(B)});let O=k.status==="fulfilled"?k.value.runs:[],N=S.status==="fulfilled"?S.value.proposals:[],Q=fr(O,N),G=Q.actionableProposals.map(K=>({id:K.id,status:K.status,title:K.title,summary:K.summary,decisionIds:K.decisionIds,threadId:K.threadId,runId:K.runId,presentationJobId:K.presentationJobId,authorityStatus:K.authorityStatus,underlyingProposalId:K.underlyingProposalId,createdAt:K.createdAt,updatedAt:K.updatedAt,appliedAt:K.appliedAt,dismissedAt:K.dismissedAt,generatedEvalIds:K.generatedEvalIds,evalProjections:K.evalProjections,error:K.error})),re=E.status==="fulfilled"?E.value:{initialized:!1,state:"degraded",error:L(E)},ce=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(K=>ln(K.messages)))]:[],te=J.status==="fulfilled"?ce.filter(K=>J.value.graph.explanations.some(de=>de.id===K&&de.state==="testing")):[],be=J.status==="fulfilled"?{state:"ready",head:J.value.graph.head,updatedAt:J.value.graph.updatedAt,explanationCount:J.value.graph.explanations.filter(K=>K.state!=="retired").length,concreteCount:J.value.graph.concrete.length,relationCount:J.value.graph.relations.length,pendingGroundingCount:te.length,recoveredTransactions:J.value.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:L(J),pendingGroundingCount:te.length,admission:ge.diagnostics(),admissionWindowStartedAt:e},Ie=z.length>0?"degraded":re.state==="absent"||re.state==="initializing"?"initializing":"healthy",ve=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:ve,serverStartedAt:e,health:{state:Ie,issues:z},version:cn,restartMode:p,projectId:r,projectName:Zn(i),projectRoot:i,requestProjectId:P,projectIdVerified:P===r,devOrigin:s,activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds,color:K.color,kind:K.kind,standalone:"standalone"in K?K.standalone:void 0})),queueDepth:I.depth+w.depth,projectionQueueDepth:w.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:U},projection:{state:k.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:w.active?{id:w.active.id,status:w.active.status,threadId:w.active.threadId,annotationIds:w.active.annotationIds??[],provider:w.active.provider,model:w.active.model}:null,queueDepth:w.depth,recentRuns:Q.recentRuns,recentAppliedRuns:Q.recentAppliedRuns,actionableProposalCounts:Q.actionableProposalCounts,actionableProposals:G},memory:re,imprint:be,recentJobsRetentionMs:Je,recentJobs:Re})}async function ft(a,g){let P=await new Promise(v=>{let k="";a.on("data",S=>{k+=S.toString()}),a.on("end",()=>v(k))});try{let v=JSON.parse(P);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function no(a){let g=await $.load();_(a,200,{ok:!0,...g})}async function oo(a,g){let P=await ze(a);if(!wr(P.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let v=await $.setTheme(P.theme);_(g,200,{ok:!0,exists:!0,preferences:v})}async function Ft(a,g){let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),k=v?I.allActive.filter(L=>L.id===v):I.allActive,S=v?w.allActive.filter(L=>L.id===v):w.allActive,E=[...k.map(L=>L.threadId),...S.map(L=>L.threadId)].filter(Boolean),J=v?I.cancelJob(v):I.cancelActive(),B=v?w.cancelJob(v):w.cancelActive(),z=!!(J||B);for(let L of E)await V.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:v||B?.id||"",cancelled:!0});_(g,200,{cancelled:z})}async function Ae(a){let g=ut().slice(0,8),P=a.threadId,v=!P;P||(P=(await V.createThread(g,[])).id,Ve.set(P,"project_model")),v&&await V.appendMessage(P,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await V.appendMessage(P,{role:"assistant",timestamp:Date.now(),jobId:g,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let k={id:g,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:P,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=w.enqueue(k);return{jobId:g,position:S,threadId:P}}async function Ne(a,g){let P=decodeURIComponent(a),v=await se.findModelProposal(P);if(!v){_(g,404,{error:"Model proposal not found"});return}_(g,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function lt(a,g,P){let v=decodeURIComponent(a),k=[];for await(let N of g)k.push(typeof N=="string"?Buffer.from(N):N);let S;try{S=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{_(P,400,{error:"Invalid JSON"});return}let E=(S.changes??[]).flatMap(N=>{if(!Array.isArray(N.path)||N.path.length===0)return[];let Q=N.path.filter(re=>typeof re=="string"||typeof re=="number");if(Q.length!==N.path.length)return[];let G=Array.isArray(N.decisionIds)?N.decisionIds.filter(re=>typeof re=="string"):void 0;return[{path:Q,value:N.value,remove:N.remove===!0,decisionIds:G}]});if(E.length===0){_(P,400,{error:"No selected model changes"});return}let J=(S.changeSummaries??[]).flatMap(N=>{if(!N||typeof N!="object")return[];let Q=Array.isArray(N.path)?N.path.filter(G=>typeof G=="string"||typeof G=="number"):void 0;return Array.isArray(N.path)&&Q?.length!==N.path.length?[]:[{group:typeof N.group=="string"?N.group:void 0,label:typeof N.label=="string"?N.label:void 0,detail:typeof N.detail=="string"?N.detail:void 0,path:Q,value:N.value,currentValue:N.currentValue}]}),B=await se.findModelProposal(v);if(!B){_(P,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){_(P,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){_(P,409,{error:`Model proposal is already ${B.status}.`});return}let z=B.decisionIds.map(N=>{let Q=B.changes?.filter(ce=>ce.decisionIds.includes(N)).length??0,G=E.filter(ce=>ce.decisionIds?.includes(N)).length,re=G===0?"unprojected":Q>G?"partially_projected":"projected";return{decisionId:N,status:re}}),L=await q.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:E.map(N=>({path:N.path,value:N.value,decisionIds:N.decisionIds})),coverage:z}),O=await se.applySelectedModelProposal(v,E,J);if(!O){_(P,404,{error:"Model proposal not found"});return}if(await et(O),O.threadId){let N=St(S.provider),Q=typeof S.model=="string"&&S.model?S.model:void 0;await V.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${O.id}`,responseText:"",provider:N,model:Q})}_(P,200,{proposal:O,projection:L})}async function Rt(a,g,P){let v=decodeURIComponent(a),{provider:k,model:S}=await ht(g),E=await se.dismissModelProposal(v);if(!E){_(P,404,{error:"Model proposal not found"});return}E.threadId&&await V.appendMessage(E.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${E.id}`,responseText:"",provider:k,model:S}),_(P,200,{proposal:E})}async function ht(a){try{let g=[];for await(let v of a)g.push(typeof v=="string"?Buffer.from(v):v);if(g.length===0)return{};let P=JSON.parse(Buffer.concat(g).toString());return{provider:St(typeof P.provider=="string"?P.provider:void 0),model:typeof P.model=="string"&&P.model?P.model:void 0,agentSettings:yt(P)}}catch{return{}}}async function io(a,g,P){let v=decodeURIComponent(a),k=await q.findJournalEvalCase(v);if(!k){_(P,404,{error:"Eval not found"});return}if(k.status!=="approved"){_(P,400,{error:"Only approved evals can be run"});return}let{screenshot:S,feedback:E,provider:J,model:B,reasoningEffort:z,serviceTier:L,sourceId:O}=await Bn(g),N=St(J)??x;if(N==="copilot"){_(P,400,{error:"Eval runs are not available for Copilot yet."});return}let Q={};try{Q=E?JSON.parse(E):{}}catch{_(P,400,{error:"Invalid eval run context JSON"});return}let G=ut().slice(0,8),re=ut().slice(0,8),ce=Ee(c,`eval-run-${G}.webp`);await dn(ce,S);let te=await ue.persistEvalScreenshot(S),be=Q.viewport,Ie=be&&typeof be=="object"?be:{},ve={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof Ie.width=="number"?Ie.width:0,height:typeof Ie.height=="number"?Ie.height:0}},K=await se.loadModel(),de=await Ar(i,k,K),pe=N==="claude"?A.name:N==="codex"?D.name:null,_e=N==="codex"?C.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=pi({evalCase:k,scope:ve,model:K,screenshotPath:ce,chromeDevtoolsAvailable:_e}),ke=(await V.createThread(re,[])).id;Ve.set(ke,"run_eval");let ee={timestamp:new Date().toISOString(),url:ve.url,viewport:ve.viewport,scrollPosition:{x:typeof Q.scrollX=="number"?Q.scrollX:0,y:typeof Q.scrollY=="number"?Q.scrollY:0},annotations:[],styleModifications:[]};await V.appendMessage(ke,{role:"human",timestamp:Date.now(),jobId:re,screenshotPath:ce,feedbackSummary:`Run eval \u2014 ${k.title}`,feedbackContext:[`Eval: ${k.title}`,"Scope: current page",`URL: ${ve.url||"unknown"}`,"Assertions:",...k.assertions.map(xe=>`- ${xe}`)].join(`
|
|
238
|
-
`)});let he={id:re,status:"queued",screenshotPath:ce,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:ke,kind:"run_eval",evalId:v,evalRunId:G,provider:N,model:B||void 0,agentSettings:yt({reasoningEffort:z,serviceTier:L}),sourceId:O||void 0};he._replyPrompt=Ce,he._evalRunScope=ve,he._evalScreenshotPath=te,he._evalScopeFingerprint=de;let Pe=I.enqueue(he);_(P,200,{jobId:re,runId:G,position:Pe,threadId:ke,screenshotPath:te})}async function pn(a,g,P){let v=decodeURIComponent(a),k={},S,E,J;try{let z=[];for await(let O of g)z.push(typeof O=="string"?Buffer.from(O):O);let L=JSON.parse(Buffer.concat(z).toString());S=L.status,E=L.title,J=L.assertions}catch{_(P,400,{error:"Invalid JSON"});return}if(S!==void 0&&S!=="pending"&&S!=="approved"&&S!=="rejected"){_(P,400,{error:"Invalid status"});return}if(S&&(k.status=S),E!==void 0){if(typeof E!="string"||E.trim().length===0){_(P,400,{error:"Invalid title"});return}k.title=E.trim()}if(J!==void 0){if(!Array.isArray(J)){_(P,400,{error:"Invalid assertions"});return}let z=J.filter(L=>typeof L=="string").map(L=>L.trim()).filter(Boolean);if(z.length===0){_(P,400,{error:"Invalid assertions"});return}k.assertions=z}if(!k.status&&!k.title&&!k.assertions){_(P,400,{error:"No eval changes provided"});return}let B=await q.updateJournalEvalCase(v,k);if(!B){_(P,404,{error:"Eval not found"});return}_(P,200,{eval:B})}async function Fr(a){let g=Ve.get(a);if(g)return g;let k=(await V.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize evals"))return Ve.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Ve.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function Lr(a,g){let P=[];for await(let B of a)P.push(typeof B=="string"?Buffer.from(B):B);let v;if(P.length>0)try{v=JSON.parse(Buffer.concat(P).toString("utf-8")).serverUrl}catch{}let k=[];h.claude?.available&&h.claude.mcp&&!h.claude.mcp.found&&k.push(await Ti(v)),h.codex?.available&&h.codex.mcp&&!h.codex.mcp.found&&k.push(await ji(v)),h.copilot?.available&&h.copilot.mcp&&!h.copilot.mcp.found&&k.push(await Ai(v,h.copilot.path??T));let[S,E,J]=await Promise.all([vo(i),Io(i),wo(i,h.copilot?.path??T)]);h.claude&&(h.claude.mcp=S),h.codex&&(h.codex.mcp=E),h.copilot&&(h.copilot.mcp=J),_(g,200,{results:k,capabilities:{providers:h}})}async function zr(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let k=await q.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await st({decisionId:k.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is an explicitly governed component in the product model.`});_(g,200,{added:!0,alreadyExists:!1,...k,evalId:S})}async function Ur(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let k=await q.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await st({decisionId:k.decisionId,modelPath:`components.${v.name}`,claim:`${v.name} is not governed as a component in the product model.`});_(g,200,{removed:!0,...k,evalId:S})}async function qr(a,g){let P=[];for await(let J of a)P.push(typeof J=="string"?Buffer.from(J):J);let v;try{v=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(g,400,{error:"Missing or invalid path/value"});return}let k=v.value;try{let J=JSON.parse(v.value);J&&typeof J=="object"&&(k=J)}catch{}let S=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:k,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let E=await st({decisionId:S.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} uses ${v.value} in the product model.`});_(g,200,{updated:!0,...S,evalId:E})}async function Wr(a,g){let P=[];for await(let E of a)P.push(typeof E=="string"?Buffer.from(E):E);let v;try{v=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(g,400,{error:"Missing or invalid path"});return}let k=await q.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await q.getCanonicalModelEntries());let S=await st({decisionId:k.decisionId,modelPath:`tokens.${v.path}`,claim:`${v.path} is intentionally absent from the product model.`});_(g,200,{removed:!0,...k,evalId:S})}function Gr(a,g){let P=s??"http://localhost:3000";if(!s){let k=a.headers.referer||a.headers.origin;if(k)try{let S=new URL(typeof k=="string"?k:k[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(P=S.origin)}catch{}}let v=Vo(y,P);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(v)}async function Hr(a){let g=Date.now();if(mt&&g<mt.expires){_(a,200,mt.data);return}try{let{scanForComponents:P}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),k=await P(i);mt={data:k,expires:g+5e3},v(k,i,Nt).then(S=>{Nt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,k)}catch(P){console.error("[Bridge] Scanner error:",P),_(a,500,{error:"Failed to scan components"})}}async function Vr(a){let g=[Ee(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ee(i,"packages","popmelt","dist","canvas.mjs")];try{let P=ud(import.meta.url);g.unshift(Ee(pd(P),"canvas.mjs"))}catch{}for(let P of g)try{let v=await Uo(P,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",g),_(a,404,{error:"Canvas bundle not found"})}async function Kr(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let P=[Ee(c,a),Ee(i,".popmelt","artifacts","thread-media",a),Ee(i,".popmelt","artifacts","eval-screenshots",a),Ee(i,".popmelt","evals","screenshots",a),Ee(i,".popmelt","screenshots",a)],v;for(let E of P)try{v=await Uo(E);break}catch{}if(!v)throw new Error("File not found");let k=a.split(".").pop()?.toLowerCase(),S=k==="png"?"image/png":k==="webp"?"image/webp":k==="jpg"||k==="jpeg"?"image/jpeg":"application/octet-stream";g.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),g.end(v)}catch{_(g,404,{error:"File not found"})}}function un(a){return`/files/${Zn(a)}`}async function Qr(a,g){let P=await V.getThread(a);if(!P){_(g,404,{error:"Thread not found"});return}let v=P.messages.some(O=>O.role==="assistant"&&O.responseText?.includes("<eval_run_result>")),k=P.messages.filter(O=>O.role==="assistant"&&O.responseText?.includes("Model suggestion ready")),[S,E]=await Promise.all([v?q.getJournalEvalRuns().then(O=>O.filter(N=>N.threadId===a).sort((N,Q)=>Q.completedAt-N.completedAt)[0]):Promise.resolve(void 0),k.length>0?se.findModelProposalsByThread(a):Promise.resolve([])]),J=S?await q.findJournalEvalCase(S.evalId):null,B=await Promise.all(E.map(async(O,N)=>{if(O.authorityStatus==="accepted")return O;let Q=(await Promise.all(O.decisionIds.map(G=>q.findPendingProposalForLegacyDecision(G)))).find(Boolean);return{...O,authorityStatus:"legacy_untrusted",presentationJobId:O.presentationJobId??k[N]?.jobId??k.at(-1)?.jobId,underlyingProposalId:Q?.proposalId,underlyingClaim:Q?.claim}})),z=[...B].sort((O,N)=>N.updatedAt-O.updatedAt)[0]??null,L=P.messages.map(({screenshotPath:O,screenshotPaths:N,imagePaths:Q,replyImagePaths:G,...re})=>({...re,...re.role==="assistant"&&S&&re.responseText?.includes("<eval_run_result>")?{evalRun:{...S,title:J?.title}}:{},...O?{screenshotUrl:un(O)}:{},...N?{screenshotUrls:Object.fromEntries(Object.entries(N).map(([ce,te])=>[ce,un(te)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ce,te])=>[ce,te.map(un)]))}:{},...G?{replyImageUrls:G.map(un)}:{}}));_(g,200,{id:P.id,createdAt:P.createdAt,messages:L,modelProposal:z,modelProposals:B})}async function Xr(a,g){let P=decodeURIComponent(a);if(!await V.deleteThread(P)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Wo=9,Go=!1;for(let a=n;a<n+Wo;a++)try{await Td(Bt,a),y=a,Go=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(g){if(g.code==="EADDRINUSE"){let P=await Pd(a);if(ur(P,{projectId:r,version:cn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw g}if(!Go)throw new Error(`[Bridge] All ports ${n}\u2013${n+Wo-1} in use`);for(let[a,g]of Object.entries(h))!g.available||!g.path||u(a,g.path).then(P=>{if(P)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),g.available=!1,g.path=null;for(let v of Y)eo(v,{type:"capabilities_changed",data:{}})}});let Yr=setInterval(()=>{Er(c).catch(()=>{})},hd),Ho=setInterval(()=>{M.expireStale().becameEmpty&&ye()},yd);return Ho.unref?.(),{port:y,projectId:r,close:async()=>{clearInterval(Yr),clearInterval(Ho),ne(),M.clear(),await I.destroyAsync(),w.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{Bt.close(()=>a())})}}}async function Er(o){try{let e=await rd(o),n=Date.now();for(let t of e){let i=Ee(o,t);try{let r=await ad(i);n-r.mtimeMs>gd&&await cd(i)}catch{}}}catch{}}var _d=parseInt(process.env.POPMELT_PORT||"1111",10),Or=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Cd=process.env.POPMELT_DEV_ORIGIN||void 0,$d=process.env.POPMELT_COPILOT_PATH||void 0,Jr=Dr(Or,".popmelt"),Nr=Dr(Jr,"bridge.lock");async function Dd(o){await Ad(Jr,{recursive:!0}),await Md(Nr,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
|
|
239
|
-
`)}async function Br(){try{await Ed(Nr)}catch{}}async function Od(){let o=await $r({port:_d,projectRoot:Or,devOrigin:Cd,copilotPath:$d,restartMode:"detached"});await Dd(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await Br(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}Od().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),Br().finally(()=>process.exit(1))});
|
|
178
|
+
`);let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,P={id:Ct().slice(0,8),res:v,sourceId:w};ie.add(P),a.on("close",()=>{ie.delete(P)})}async function Ee(a,v,R){s??=er(a.headers),Me();let w=[..._.allActive,...$.allActive.map(z=>({id:z.id,status:z.status,threadId:z.threadId,annotationIds:z.annotationIds??[],color:"#000000",kind:"project_model",standalone:z.standalone}))],[P,S,C,O,L]=await Promise.allSettled([K.loadRuns(),K.loadModelProposals(),Z.status(),J.store.load(),N.load()]),G=[],F=z=>z.reason instanceof Error?z.reason.message:String(z.reason);P.status==="rejected"&&G.push({subsystem:"projection",message:F(P)}),S.status==="rejected"&&G.push({subsystem:"projection",message:F(S)}),C.status==="rejected"?G.push({subsystem:"memory",message:F(C)}):C.value.state==="degraded"&&G.push({subsystem:"memory",message:C.value.error??"Product memory is degraded."}),O.status==="rejected"&&G.push({subsystem:"imprint",message:F(O)}),L.status==="rejected"&&G.push({subsystem:"threads",message:F(L)});let ce=P.status==="fulfilled"?P.value.runs:[],q=S.status==="fulfilled"?S.value.proposals:[],le=tr(ce,q),se=le.actionableProposals.map(z=>({id:z.id,status:z.status,title:z.title,summary:z.summary,decisionIds:z.decisionIds,threadId:z.threadId,runId:z.runId,presentationJobId:z.presentationJobId,authorityStatus:z.authorityStatus,underlyingProposalId:z.underlyingProposalId,createdAt:z.createdAt,updatedAt:z.updatedAt,appliedAt:z.appliedAt,dismissedAt:z.dismissedAt,error:z.error})),ne=C.status==="fulfilled"?C.value:{initialized:!1,state:"degraded",error:F(C)},X=L.status==="fulfilled"?[...new Set(Object.values(L.value.threads).flatMap(z=>on(z.messages)))]:[],be=O.status==="fulfilled"?X.filter(z=>O.value.graph.explanations.some(ae=>ae.id===z&&ae.state==="testing")):[],ue=O.status==="fulfilled"?{state:"ready",head:O.value.graph.head,updatedAt:O.value.graph.updatedAt,explanationCount:O.value.graph.explanations.filter(z=>z.state!=="retired").length,concreteCount:O.value.graph.concrete.length,relationCount:O.value.graph.relations.length,pendingGroundingCount:be.length,recoveredTransactions:O.value.recoveredTransactions,admission:J.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(O),pendingGroundingCount:be.length,admission:J.diagnostics(),admissionWindowStartedAt:e},he=G.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",ke=new Date().toISOString();E(v,200,{ok:!0,schemaVersion:3,generatedAt:ke,serverStartedAt:e,health:{state:he,issues:G},version:nn,restartMode:l,projectId:r,projectName:Vn(i),projectRoot:i,requestProjectId:R,projectIdVerified:R===r,devOrigin:s,activeJob:w[0]?{id:w[0].id,status:w[0].status}:null,activeJobs:w.map(z=>({id:z.id,status:z.status,threadId:z.threadId,annotationIds:z.annotationIds,color:z.color,kind:z.kind,standalone:"standalone"in z?z.standalone:void 0})),queueDepth:_.depth+$.depth,projectionQueueDepth:$.depth,leases:{active:h.isActivated,count:h.size,nextExpiryAt:h.nextExpiryAt,shutdownPending:B},projection:{state:P.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:$.active?{id:$.active.id,status:$.active.status,threadId:$.active.threadId,annotationIds:$.active.annotationIds??[],provider:$.active.provider,model:$.active.model}:null,queueDepth:$.depth,recentRuns:le.recentRuns,recentAppliedRuns:le.recentAppliedRuns,actionableProposalCounts:le.actionableProposalCounts,actionableProposals:se},memory:ne,imprint:ue,recentJobsRetentionMs:Ae,recentJobs:Ie})}async function Ze(a,v){let R=await new Promise(w=>{let P="";a.on("data",S=>{P+=S.toString()}),a.on("end",()=>w(P))});try{let w=JSON.parse(R);typeof w.devOrigin=="string"&&(s=w.devOrigin||null),E(v,200,{ok:!0,devOrigin:s})}catch{E(v,400,{error:"Invalid JSON"})}}async function ot(a){let v=await W.load();E(a,200,{ok:!0,...v})}async function it(a,v){let R=await Je(a);if(!ar(R.theme)){E(v,400,{error:"theme must be light, dark, or auto"});return}let w=await W.setTheme(R.theme);E(v,200,{ok:!0,exists:!0,preferences:w})}async function ct(a,v){let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),P=w?_.allActive.filter(F=>F.id===w):_.allActive,S=w?$.allActive.filter(F=>F.id===w):$.allActive,C=[...P.map(F=>F.threadId),...S.map(F=>F.threadId)].filter(Boolean),O=w?_.cancelJob(w):_.cancelActive(),L=w?$.cancelJob(w):$.cancelActive(),G=!!(O||L);for(let F of C)await N.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:w||L?.id||"",cancelled:!0});E(v,200,{cancelled:G})}async function Ot(a){let v=Ct().slice(0,8),R=a.threadId,w=!R;R||(R=(await N.createThread(v,[])).id,Ve.set(R,"project_model")),w&&await N.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:a.reason}),await N.appendMessage(R,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:w?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let P={id:v,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:R,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:w},S=$.enqueue(P);return{jobId:v,position:S,threadId:R}}async function Xn(a,v){let R=decodeURIComponent(a),w=await K.findModelProposal(R);if(!w){E(v,404,{error:"Model proposal not found"});return}E(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:w})}async function Dt(a,v,R){let w=decodeURIComponent(a),P=[];for await(let q of v)P.push(typeof q=="string"?Buffer.from(q):q);let S;try{S=JSON.parse(Buffer.concat(P).toString("utf-8"))}catch{E(R,400,{error:"Invalid JSON"});return}let C=(S.changes??[]).flatMap(q=>{if(!Array.isArray(q.path)||q.path.length===0)return[];let le=q.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(le.length!==q.path.length)return[];let se=Array.isArray(q.decisionIds)?q.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:le,value:q.value,remove:q.remove===!0,decisionIds:se}]});if(C.length===0){E(R,400,{error:"No selected model changes"});return}let O=(S.changeSummaries??[]).flatMap(q=>{if(!q||typeof q!="object")return[];let le=Array.isArray(q.path)?q.path.filter(se=>typeof se=="string"||typeof se=="number"):void 0;return Array.isArray(q.path)&&le?.length!==q.path.length?[]:[{group:typeof q.group=="string"?q.group:void 0,label:typeof q.label=="string"?q.label:void 0,detail:typeof q.detail=="string"?q.detail:void 0,path:le,value:q.value,currentValue:q.currentValue}]}),L=await K.findModelProposal(w);if(!L){E(R,404,{error:"Model proposal not found"});return}if(L.authorityStatus!=="accepted"){E(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(L.status!=="pending"){E(R,409,{error:`Model proposal is already ${L.status}.`});return}let G=L.decisionIds.map(q=>{let le=L.changes?.filter(X=>X.decisionIds.includes(q)).length??0,se=C.filter(X=>X.decisionIds?.includes(q)).length,ne=se===0?"unprojected":le>se?"partially_projected":"projected";return{decisionId:q,status:ne}}),F=await Z.applyModelProjection({runId:L.runId??L.id,presentationJobId:L.presentationJobId,decisionIds:L.decisionIds,changes:C.map(q=>({path:q.path,value:q.value,decisionIds:q.decisionIds})),coverage:G}),ce=await K.applySelectedModelProposal(w,C,O);if(!ce){E(R,404,{error:"Model proposal not found"});return}if(ce.threadId){let q=$t(S.provider),le=typeof S.model=="string"&&S.model?S.model:void 0;await N.appendMessage(ce.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ce.id}`,responseText:"",provider:q,model:le})}E(R,200,{proposal:ce,projection:F})}async function Oe(a,v,R){let w=decodeURIComponent(a),{provider:P,model:S}=await De(v),C=await K.dismissModelProposal(w);if(!C){E(R,404,{error:"Model proposal not found"});return}C.threadId&&await N.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${C.id}`,responseText:"",provider:P,model:S}),E(R,200,{proposal:C})}async function De(a){try{let v=[];for await(let w of a)v.push(typeof w=="string"?Buffer.from(w):w);if(v.length===0)return{};let R=JSON.parse(Buffer.concat(v).toString());return{provider:$t(typeof R.provider=="string"?R.provider:void 0),model:typeof R.model=="string"&&R.model?R.model:void 0,agentSettings:It(R)}}catch{return{}}}async function rt(a){let v=Ve.get(a);if(v)return v;let P=(await N.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(P.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(P.startsWith("Materialize model")||P.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function vt(a,v){let R=[];for await(let L of a)R.push(typeof L=="string"?Buffer.from(L):L);let w;if(R.length>0)try{w=JSON.parse(Buffer.concat(R).toString("utf-8")).serverUrl}catch{}let P=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&P.push(await ui(w)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&P.push(await mi(w)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&P.push(await fi(w,m.copilot.path??T));let[S,C,O]=await Promise.all([po(i),uo(i),mo(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=C),m.copilot&&(m.copilot.mcp=O),E(v,200,{results:P,capabilities:{providers:m}})}async function dt(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{E(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){E(v,400,{error:"Missing or invalid name"});return}let P=await Z.recordDirectModelMutation({key:`components.${w.name}`,value:{description:""},claim:`${w.name} is an explicitly governed component in the product model.`});await K.applyCanonicalEntries(await Z.getCanonicalModelEntries()),E(v,200,{added:!0,alreadyExists:!1,...P})}async function Yn(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{E(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){E(v,400,{error:"Missing or invalid name"});return}let P=await Z.recordDirectModelMutation({key:`components.${w.name}`,value:null,claim:`${w.name} is not governed as a component in the product model.`});await K.applyCanonicalEntries(await Z.getCanonicalModelEntries()),E(v,200,{removed:!0,...P})}async function an(a,v){let R=[];for await(let C of a)R.push(typeof C=="string"?Buffer.from(C):C);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{E(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"||typeof w.value!="string"){E(v,400,{error:"Missing or invalid path/value"});return}let P=w.value;try{let C=JSON.parse(w.value);C&&typeof C=="object"&&(P=C)}catch{}let S=await Z.recordDirectModelMutation({key:`tokens.${w.path}`,value:P,claim:`${w.path} uses ${w.value} in the product model.`});await K.applyCanonicalEntries(await Z.getCanonicalModelEntries()),E(v,200,{updated:!0,...S})}async function kr(a,v){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{E(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"){E(v,400,{error:"Missing or invalid path"});return}let P=await Z.recordDirectModelMutation({key:`tokens.${w.path}`,value:null,claim:`${w.path} is intentionally absent from the product model.`});await K.applyCanonicalEntries(await Z.getCanonicalModelEntries()),E(v,200,{removed:!0,...P})}function Pr(a,v){let R=s??"http://localhost:3000";if(!s){let P=a.headers.referer||a.headers.origin;if(P)try{let S=new URL(typeof P=="string"?P:P[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(R=S.origin)}catch{}}let w=No(y,R);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(w)}async function Rr(a){let v=Date.now();if(st&&v<st.expires){E(a,200,st.data);return}try{let{scanForComponents:R}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:w}=await import("./render-generator-HWFLZYC3.mjs"),P=await R(i);st={data:P,expires:v+5e3},w(P,i,Ye).then(S=>{Ye=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),E(a,200,P)}catch(R){console.error("[Bridge] Scanner error:",R),E(a,500,{error:"Failed to scan components"})}}async function Tr(a){let v=[$e(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),$e(i,"packages","popmelt","dist","canvas.mjs")];try{let R=Bc(import.meta.url);v.unshift($e(Dc(R),"canvas.mjs"))}catch{}for(let R of v)try{let w=await pr(R,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(w);return}catch{}console.error("[Bridge] Canvas bundle not found in:",v),E(a,404,{error:"Canvas bundle not found"})}async function jr(a,v){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){E(v,400,{error:"Invalid filename"});return}try{let R=[$e(c,a),$e(i,".popmelt","artifacts","thread-media",a),$e(i,".popmelt","artifacts","eval-screenshots",a),$e(i,".popmelt","evals","screenshots",a),$e(i,".popmelt","screenshots",a)],w;for(let C of R)try{w=await pr(C);break}catch{}if(!w)throw new Error("File not found");let P=a.split(".").pop()?.toLowerCase(),S=P==="png"?"image/png":P==="webp"?"image/webp":P==="jpg"||P==="jpeg"?"image/jpeg":P==="svg"?"image/svg+xml":P==="txt"?"text/plain; charset=utf-8":"application/octet-stream";v.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),v.end(w)}catch{E(v,404,{error:"File not found"})}}function Jt(a){return`/files/${Vn(a)}`}async function Ar(a,v){let R=await N.getThread(a);if(!R){E(v,404,{error:"Thread not found"});return}let w=R.messages.filter(L=>L.role==="assistant"&&L.responseText?.includes("Model suggestion ready")),P=await(w.length>0?K.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(P.map(async(L,G)=>{if(L.authorityStatus==="accepted")return L;let F=(await Promise.all(L.decisionIds.map(ce=>Z.findPendingProposalForLegacyDecision(ce)))).find(Boolean);return{...L,authorityStatus:"legacy_untrusted",presentationJobId:L.presentationJobId??w[G]?.jobId??w.at(-1)?.jobId,underlyingProposalId:F?.proposalId,underlyingClaim:F?.claim}})),C=[...S].sort((L,G)=>G.updatedAt-L.updatedAt)[0]??null,O=R.messages.map(({screenshotPath:L,screenshotPaths:G,imagePaths:F,attachmentFiles:ce,replyImagePaths:q,...le})=>({...le,...L?{screenshotUrl:Jt(L)}:{},...G?{screenshotUrls:Object.fromEntries(Object.entries(G).map(([se,ne])=>[se,Jt(ne)]))}:{},...F?{imageUrls:Object.fromEntries(Object.entries(F).map(([se,ne])=>[se,ne.map(Jt)]))}:{},...ce?{attachments:Object.fromEntries(Object.entries(ce).map(([se,ne])=>[se,ne.map(({path:X,...be})=>({...be,url:Jt(X)}))]))}:{},...q?{replyImageUrls:q.map(Jt)}:{}}));E(v,200,{id:R.id,createdAt:R.createdAt,messages:O,modelProposal:C,modelProposals:S})}async function Mr(a,v){let R=decodeURIComponent(a);if(!await N.deleteThread(R)){E(v,404,{deleted:!1,error:"Thread not found"});return}E(v,200,{deleted:!0})}let Oo=9,Do=!1;for(let a=n;a<n+Oo;a++)try{await nd(at,a),y=a,Do=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(v){if(v.code==="EADDRINUSE"){let R=await td(a);if(Zi(R,{projectId:r,version:nn,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw v}if(!Do)throw new Error(`[Bridge] All ports ${n}\u2013${n+Oo-1} in use`);for(let[a,v]of Object.entries(m))!v.available||!v.path||u(a,v.path).then(R=>{if(R)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),v.available=!1,v.path=null;for(let w of ie)Kn(w,{type:"capabilities_changed",data:{}})}});let Er=setInterval(()=>{hr(c).catch(()=>{}),pe.sweep().catch(()=>{})},qc),Jo=setInterval(()=>{h.expireStale().becameEmpty&&Y()},Uc);return Jo.unref?.(),{port:y,projectId:r,close:async()=>{clearInterval(Er),clearInterval(Jo),U(),h.clear(),await pe.cleanupPartials(),await _.destroyAsync(),$.destroy();for(let a of ie)try{a.res.end()}catch{}return ie.clear(),new Promise(a=>{at.close(()=>a())})}}}async function hr(o){try{let e=await Mc(o),n=Date.now();for(let t of e){let i=$e(o,t);try{let r=await _c(i);n-r.mtimeMs>zc&&await Cc(i)}catch{}}}catch{}}var sd=parseInt(process.env.POPMELT_PORT||"1111",10),wr=process.env.POPMELT_PROJECT_ROOT||process.cwd(),ad=process.env.POPMELT_DEV_ORIGIN||void 0,cd=process.env.POPMELT_COPILOT_PATH||void 0,br=Ir(wr,".popmelt"),xr=Ir(br,"bridge.lock");async function dd(o){await od(br,{recursive:!0}),await rd(xr,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
|
|
179
|
+
`)}async function Sr(){try{await id(xr)}catch{}}async function ld(){let o=await vr({port:sd,projectRoot:wr,devOrigin:ad,copilotPath:cd,restartMode:"detached"});await dd(o.port),await new Promise(e=>{let n=!1,t=async()=>{n||(n=!0,await o.close(),await Sr(),e(),process.exit(0))};process.on("SIGTERM",t),process.on("SIGINT",t)})}ld().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),Sr().finally(()=>process.exit(1))});
|