@popmelt.com/core 0.8.7 → 0.8.8
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 +56 -116
- package/dist/{chunk-ETDSTV4E.mjs → chunk-DLYPQXHS.mjs} +1 -1
- package/dist/cli.mjs +46 -106
- package/dist/index.d.mts +1 -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-UVBM5TBI.mjs +182 -0
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +47 -107
- package/package.json +1 -1
- package/dist/server-FZ2YAIA5.mjs +0 -242
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
2
|
+
import{spawn as Cc}from"child_process";import{readFile as Oc,unlink as Dc}from"fs/promises";import{join as Nc}from"path";import{execFileSync as ac,spawn as ri}from"child_process";import{randomUUID as Et}from"crypto";import{mkdir as cc,readFile as ii,readdir as dc,realpath as lc,stat as pc,unlink as uc,writeFile as Un}from"fs/promises";import{createServer as mc}from"http";import{tmpdir as fc}from"os";import{basename as zn,dirname as hc,isAbsolute as li,join as _e,relative as gc,resolve as yc}from"path";import{fileURLToPath as vc}from"url";function Oo(o,e){return`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -26,68 +26,12 @@ import{spawn as Pd}from"child_process";import{readFile as Td,unlink as jd}from"f
|
|
|
26
26
|
});
|
|
27
27
|
</script>
|
|
28
28
|
</body>
|
|
29
|
-
</html>`}var
|
|
30
|
-
\u2026[truncated]`:t}function
|
|
31
|
-
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function
|
|
32
|
-
`)[0].slice(0,80)}`:"Bash";y.push(
|
|
33
|
-
`)}`)),
|
|
34
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function ks(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Ht(o).toLowerCase().includes("error"))return o.message}function Gt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let i=Gt(r,e);if(i)return i}}function po(o){let e=Ht(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Ps,readFile as Ts}from"fs/promises";import{join as uo}from"path";var wn=class{constructor(e){let n=uo(e,".popmelt");this.decisionsDir=uo(n,"decisions")}async listDecisionIds(){try{return(await Ps(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 Ts(uo(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 pr(o,e){let n=o.match(/<eval_run_result>\s*([\s\S]*?)\s*<\/eval_run_result>/);if(n?.[1])try{let t=JSON.parse(n[1]),r=Ds(t.assertionResults,e),i=Os(r);return{status:i,summary:rt(t.summary)||hr(i),assertionResults:r,tooling:Js(t.tooling)}}catch{}return{status:"needs_review",summary:Ns(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 ur(o,e){let n=(o.selectedChanges??[]).flatMap(f=>Array.isArray(f.path)&&f.path.length?[f.path]:[]),t=o.changes??[],r=n.length>0?n:t.map(f=>f.path),i=[...new Set(r.map(f=>f.map(String).join(".")).filter(Boolean))].map(f=>({kind:"model_path",value:f}));if(i.length===0||o.decisionIds.length===0)return[];let s=new Set(o.decisionIds),c=new Set(i.map(f=>f.value)),d=e.cases.find(f=>f.status!=="rejected"&&(f.sourceDecisionIds.some(u=>s.has(u))||(f.dependencies??[]).some(u=>u.kind==="model_path"&&c.has(u.value)))),l=(o.selectedChanges??[]).find(f=>f.label?.trim())?.label?.trim()??t.find(f=>f.label?.trim())?.label?.trim()??o.title,w=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=>js(f,o.decisionIds)),m=xn(o.underlyingClaim??o.summary),p=[...new Set([...d&&!w?d.assertions:[],...x,...x.length===0&&m?[m]:[]])],y=i[0].value,h=y.startsWith("components.")?"component":y.startsWith("tokens.")?"visual":"workflow";return[{id:d?.id??`eval-model-${o.id}`,title:d&&!w?d.title:l,status:"pending",category:d?.category??h,prompt:d&&!w?d.prompt:"Verify these product expectations across the declared scenarios.",assertions:p,rationale:d&&!w?d.rationale:Ms(y),sourceDecisionIds:[...new Set([...d?.sourceDecisionIds??[],...o.decisionIds])],sourceThreadIds:[...new Set([...d?.sourceThreadIds??[],...o.threadId?[o.threadId]:[]])],dependencies:[...new Map([...d?.dependencies??[],...i].map(f=>[`${f.kind}:${f.value}`,f])).values()]}]}function js(o,e){let n=String(o.path[0]??"");if(n==="rules")return As(o.value,e);if(n==="components"){let s=mr(String(o.path[1]??o.label??"component")),c=bn(o.value),d=c?Kt(c.usage):[];if(d.length>0){let w=_s(d),j=d.length===1?"uses":"use";return[`The ${w} ${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?rt(c.constraint):"";if(l){let w=Es(l,s);if(w)return[w]}}if(n==="tokens"){let s=o.path.slice(1).map(String).join("."),c=bn(o.value),d=c&&"value"in c?c.value:o.value,l=$s(d);if(s&&l)return[`The ${s} token resolves to ${l}.`]}let t=bn(o.value),r=t?rt(t.text)||rt(t.constraint):typeof o.value=="string"?o.value:"",i=xn(r||o.detail||"");return i?[i]:[]}function As(o,e){if(!Array.isArray(o))return[];let n=new Set(e),t=o.flatMap(s=>{let c=bn(s),d=c?rt(c.text):"";return d?[{text:d,sources:c?Kt(c.sources):[]}]:[]}),r=t.filter(s=>s.sources.some(c=>n.has(c)));return(r.length>0?r:t.length===1?t:[]).map(s=>xn(s.text)).filter(s=>!!s)}function Es(o,e){let n=o.trim().match(/^Use this shared component wherever (.+?) instead of (?:maintaining|creating) (.+?)\.?$/i);return n?Tt(`Wherever ${Vt(n[1])}, the shared ${e} implementation is used instead of ${Vt(n[2])}`):xn(o)}function mo(o){let e=o.trim();if(!e)return"";let n=e.match(/^The accepted decision establishes (.+?) as (.+?)\.?$/i);if(n)return Tt(`${lr(n[1])} is ${Vt(n[2])}`);let t=e.match(/^The accepted decision establishes (.+?)\.?$/i);if(t)return Tt(lr(t[1]));let r=e.match(/^Use (.+?)\.?$/i);if(r)return Tt(`The product uses ${Vt(r[1])}`);let i=e.match(/^Do not (.+?)\.?$/i);return i?Tt(`The product does not ${Vt(i[1])}`):/\b(product memory|memory event|decision history|model proposal)\b/i.test(e)?"":Tt(e)}var xn=mo;function Ms(o){let e=o.split(".");return e[0]==="components"?`Protects the shared ${mr(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 bn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function mr(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").trim().toLowerCase()}function _s(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 $s(o){return typeof o=="string"?o.trim():typeof o=="number"||typeof o=="boolean"?String(o):""}function Tt(o){let e=o.trim().replace(/[.]+$/,"");return e?`${e}.`:""}function lr(o){let e=o.trim();return e?e.charAt(0).toUpperCase()+e.slice(1):""}function Vt(o){let e=o.trim();return e?e.charAt(0).toLowerCase()+e.slice(1):""}function fr(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.
|
|
35
|
-
|
|
36
|
-
## Eval
|
|
37
|
-
\`\`\`json
|
|
38
|
-
${JSON.stringify(o.evalCase,null,2)}
|
|
39
|
-
\`\`\`
|
|
40
|
-
|
|
41
|
-
## Scope
|
|
42
|
-
\`\`\`json
|
|
43
|
-
${JSON.stringify(o.scope,null,2)}
|
|
44
|
-
\`\`\`
|
|
45
|
-
|
|
46
|
-
## Current Design Model
|
|
47
|
-
\`\`\`json
|
|
48
|
-
${JSON.stringify(o.model??null,null,2)}
|
|
49
|
-
\`\`\`
|
|
50
|
-
|
|
51
|
-
## Evidence
|
|
52
|
-
- Current page screenshot: ${o.screenshotPath}
|
|
53
|
-
- Chrome DevTools MCP is ${o.chromeDevtoolsAvailable?"configured for this provider and approved by the bridge when the runtime exposes its tools":"not detected by the bridge"}.
|
|
54
|
-
|
|
55
|
-
## Instructions
|
|
56
|
-
1. Evaluate only the supplied current runtime scope; do not navigate into other scenarios during this run.
|
|
57
|
-
2. Compare the runtime URL, component evidence, and visible state with the eval's declared scenarios. If the runtime does not satisfy an applicable declared scenario, mark affected assertions "needs_review" and name the scope mismatch instead of guessing.
|
|
58
|
-
3. Use the screenshot as baseline evidence.
|
|
59
|
-
4. If Chrome DevTools MCP tools are available, prefer them for DOM, computed style, accessibility, console, and layout evidence.
|
|
60
|
-
5. Judge each assertion independently as "pass", "fail", or "needs_review".
|
|
61
|
-
6. Keep failures actionable and grounded in observed evidence.
|
|
62
|
-
7. Do not propose visual markers yet.
|
|
63
|
-
8. End with exactly one machine-readable <eval_run_result> block.
|
|
64
|
-
9. Do not ask the user for additional Chrome DevTools permission. If DevTools is unavailable, denied, or not useful, continue immediately from the screenshot, source, and model evidence.
|
|
65
|
-
10. Before the structured block, keep the visible response brief. Use one checklist row per assertion with these markers: \u2611 pass, \u2612 fail, \u25A1 needs_review. Do not include long reasoning paragraphs.
|
|
66
|
-
|
|
67
|
-
The block must be valid JSON with this shape:
|
|
68
|
-
|
|
69
|
-
\`\`\`json
|
|
70
|
-
{
|
|
71
|
-
"status": "pass",
|
|
72
|
-
"summary": "Short run summary.",
|
|
73
|
-
"assertionResults": [
|
|
74
|
-
{
|
|
75
|
-
"assertion": "Original assertion text",
|
|
76
|
-
"status": "pass",
|
|
77
|
-
"summary": "What was observed.",
|
|
78
|
-
"evidence": ["Screenshot shows ...", "DOM selector ..."]
|
|
79
|
-
}
|
|
80
|
-
],
|
|
81
|
-
"tooling": {
|
|
82
|
-
"chromeDevtools": "available",
|
|
83
|
-
"evidenceTypes": ["screenshot", "dom", "computed_styles"]
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
\`\`\`
|
|
88
|
-
|
|
89
|
-
Allowed statuses: pass, fail, needs_review.
|
|
90
|
-
Allowed chromeDevtools values: available, unavailable, unknown.`}function rt(o){return typeof o=="string"?o.trim():""}function Kt(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}function Cs(o){let e=rt(o);return e==="pass"||e==="fail"||e==="needs_review"?e:null}function Ds(o,e){let t=(Array.isArray(o)?o:[]).map(r=>{if(!r||typeof r!="object")return null;let i=r,s=rt(i.assertion);return s?{assertion:s,status:Cs(i.status)??"needs_review",summary:rt(i.summary)||hr("needs_review"),evidence:Kt(i.evidence)}:null}).filter(r=>r!==null);return t.length>0?t:e.map(r=>({assertion:r,status:"needs_review",summary:"No structured assertion result was returned.",evidence:[]}))}function Os(o){return o.some(e=>e.status==="fail")?"fail":o.some(e=>e.status==="needs_review")?"needs_review":"pass"}function Js(o){if(!o||typeof o!="object")return{chromeDevtools:"unknown",evidenceTypes:["screenshot"]};let e=o,n=rt(e.chromeDevtools);return{chromeDevtools:n==="available"||n==="unavailable"||n==="unknown"?n:"unknown",evidenceTypes:Kt(e.evidenceTypes).length>0?Kt(e.evidenceTypes):["screenshot"]}}function hr(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 Ns(o,e){return o.length>e?`${o.slice(0,e)}...`:o}import{createHash as Bs}from"crypto";import{mkdir as Fs,writeFile as Ls}from"fs/promises";import{join as fo}from"path";var Sn=class{constructor(e){this.root=fo(e,".popmelt","artifacts")}async persistEvalScreenshot(e){let n=fo(this.root,"eval-screenshots"),t=Bs("sha256").update(e).digest("hex"),r=fo(n,`${t}.webp`);return await Fs(n,{recursive:!0}),await Ls(r,e,{flag:"wx"}).catch(i=>{if(i.code!=="EEXIST")throw i}),r}};import{randomUUID as gr}from"crypto";import{mkdir as ho,readFile as go,writeFile as Rn}from"fs/promises";import{dirname as yo,join as jt}from"path";var Ge="[ProjectionWorker]",zs={version:1,runs:[]},Us={version:1,updatedAt:0,proposals:[]},qs=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 yr(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(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Ge} Rule count ${e.length} exceeds cap of 30`),e}function Gs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Hs(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let m of i){if(!m||typeof m!="object")continue;let p=m.sources;if(Array.isArray(p))for(let y of p)typeof y=="string"&&t.has(y)&&r.add(y)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=i.filter(m=>{if(!m||typeof m!="object")return!1;let p=m.id,y=typeof p=="string"?d.find(h=>h&&typeof h=="object"&&h.id===p):void 0;return JSON.stringify(y)!==JSON.stringify(m)}).length,w=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(w[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:[...r],uncoveredDecisionIds:e.filter(m=>!r.has(m))}}function Vs(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 r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function kn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=Ks(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=Vs(n)}function vr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function Qs(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 Xs(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 Ir(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=Qs(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Xs(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Pn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=jt(e,".popmelt");this.runsPath=jt(t,"projection-runs.json"),this.legacyRunsPath=jt(t,"materialization-runs.json"),this.proposalsPath=jt(t,"projection-queue.json"),this.legacyProposalsPath=jt(t,"model-proposals.json"),this.modelPath=jt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await go(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 r=t.key.split(".");t.value===null?vr(n,r):kn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(qs),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(m=>m.id);console.log(`${Ge} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=ta(r,s),d=Gs(r,t.totalCandidateDecisionCount,c);n=gr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let w=!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)w=!1,j=h.error,console.error(`${Ge} ${p} spawn error:`,j);else{let f=ea(h.text,i);if(f){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let R of f)kn(u,R.path,R.value);Array.isArray(u.rules)&&(u.rules=yr(u.rules));let A=Hs(u,i,s);if(f){let R=[...new Set(f.flatMap($=>$.decisionIds))];A.coveredDecisionIds=R,A.uncoveredDecisionIds=i.filter($=>!R.includes($))}T=A;let D=await this.createModelProposal({decisionIds:i,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(`${Ge} Created model proposal ${D.id} for ${i.length} decision(s)`)}else w=!1,j="No valid bounded <model-changes> block found in response",console.error(`${Ge} ${j}`)}}catch(m){w=!1,j=m instanceof Error?m.message:String(m),console.error(`${Ge} Error:`,j)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:j,outputStats:T,proposalId:x}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:w,error:j}),{processedIds:i,success:w,error:j,runId:n,proposalId:x}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=yr(e.rules)),await Rn(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 ho(yo(this.runsPath),{recursive:!0}),await Rn(this.runsPath,JSON.stringify(n,null,2)),n):{...zs,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Us,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(t);for(let s of r.changes??[])kn(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?vr(s,d.path):kn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async attachGeneratedEvals(e,n){let t=await this.findModelProposal(e);if(!t)return null;let r=new Set(t.generatedEvalIds??[]),i=new Map((t.evalProjections??[]).map(s=>[s.evalId,s]));for(let s of n){let c=typeof s=="string"?{evalId:s,title:s,action:"created"}:s;r.add(c.evalId),i.set(c.evalId,c)}return this.updateModelProposal(e,{generatedEvalIds:[...r],evalProjections:[...i.values()]})}async createModelProposal(e){let n={id:gr().slice(0,8),status:"pending",title:Ys(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"}.`:Zs(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await ho(yo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await Rn(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(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await ho(yo(this.runsPath),{recursive:!0}),await Rn(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 go(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await go(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let i=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...In(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:gn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Ge} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...yn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Ys(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Zs(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function ea(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),i=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(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 w=Array.isArray(d.decisionIds)?d.decisionIds.filter(j=>typeof j=="string"&&r.has(j)):[];return w.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:w,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function ta(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
29
|
+
</html>`}var Ii=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),wi=new Set(["default","flex","fast","priority"]);function yt(o){let e=typeof o.reasoningEffort=="string"&&Ii.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&wi.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 bi}from"child_process";import{createInterface as xi}from"readline";var Si=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"]),Do=1e5;function ki(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Si.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>Do?t.slice(0,Do)+`
|
|
30
|
+
\u2026[truncated]`:t}function dn(o,e){let{prompt:n,projectRoot:t,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:p,reasoningEffort:x,timeoutMs:T=3e5,onEvent:P}=e,b=[];d?b.push("--resume",d,"-p",n):b.push("-p",n),b.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),p&&b.push("--model",p),x&&b.push("--effort",x);for(let y of s)b.push("--allowedTools",y);let f=bi(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=[],A=!1,g="",E,C,h=!1,M=setTimeout(()=>{h=!0,f.kill("SIGTERM"),setTimeout(()=>{try{f.kill("SIGKILL")}catch{}},5e3)},T),O=xi({input:f.stdout}),J=new Set;O.on("line",K=>{if(K.trim())try{let Z=JSON.parse(K);Z.session_id&&!m&&(m=Z.session_id);let re=Z.type??(Z.event?.type?`event.${Z.event.type}`:"unknown");if(J.add(re),Z.type==="result"&&Z.result&&I.length===0){let D=typeof Z.result=="string"?Z.result:"";D&&(I.push(D),P?.({type:"delta",jobId:o,text:D},o))}if(Z.type==="assistant"&&Array.isArray(Z.message?.content)){typeof Z.error=="string"&&(E=Z.error);for(let D of Z.message.content){if(D.type==="text"&&D.text&&(I.push(D.text),P?.({type:"delta",jobId:o,text:D.text},o)),D.type==="tool_use"&&D.name){let V=D.input?.file_path||D.input?.path||void 0,ge=ki(D);if(P?.({type:"tool_use",jobId:o,tool:D.name,...V?{file:V}:{},...ge?{content:ge}:{}},o),D.name==="Edit"&&D.input?.file_path){let L={tool:"Edit",file_path:D.input.file_path,old_string:D.input.old_string,new_string:D.input.new_string,replace_all:D.input.replace_all};u.push(L),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:L.file_path,oldString:typeof L.old_string=="string"?L.old_string:void 0,newString:typeof L.new_string=="string"?L.new_string:void 0,replaceAll:typeof L.replace_all=="boolean"?L.replace_all:void 0})}else D.name==="Write"&&D.input?.file_path&&(u.push({tool:"Write",file_path:D.input.file_path,content:D.input.content}),k.push({sequence:k.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:D.input.file_path,content:typeof D.input.content=="string"?D.input.content:void 0}))}D.type==="thinking"&&D.thinking&&P?.({type:"thinking",jobId:o,text:D.thinking},o)}}Z.type==="result"&&Z.is_error===!0&&(A=!0,typeof Z.error=="string"&&(E=Z.error),typeof Z.result=="string"&&(C=Z.result)),Z.type==="user"&&Z.tool_use_result?.file?.filePath&&P?.({type:"tool_use",jobId:o,tool:"Read",file:Z.tool_use_result.file.filePath},o)}catch{}});let z=[];f.stderr?.on("data",K=>{z.push(K.toString())}),f.on("close",K=>{if(clearTimeout(M),O.close(),I.length===0&&J.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...J].join(", ")}`),h)A=!0,g=`Timed out after ${Math.round(T/6e4)} minutes`;else if(K!==0&&K!==null){A=!0;let re=z.join("").trim(),D=I.join("").trim(),V=I.length===0&&J.size>0?` (no text captured, event types: ${[...J].join(", ")})`:"";g=re||C||D||`Claude process exited with code ${K}${V}`}A&&!g&&C&&(g=C);let Z=Ri(g,E);y({sessionId:m,text:I.join(""),success:!A,error:A?Z.message:void 0,errorCode:A?Z.code:void 0,recoverableError:A?Z.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:k.length>0?k:void 0})}),f.on("error",K=>{clearTimeout(M),A=!0,g=K.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 Ri(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 Pi,spawnSync as qo}from"child_process";import{readFileSync as Ti,statSync as ji}from"fs";import{basename as Mi,extname as Ai,isAbsolute as Ei,relative as Uo,resolve as _i}from"path";import{createInterface as $i}from"readline";function No(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Jo=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"]),Xn=2e5,Ci=1e5,zo=2e5;function Go(o){let e=Mi(o).toLowerCase(),n=Ai(o).toLowerCase();return Jo.has(n)||Jo.has(e)}function Nt(o,e){let n=Ei(e)?e:_i(o,e),t=Uo(o,n);return t===""||t.startsWith("..")?null:n}function ln(o,e){if(!Go(e))return;let n=Nt(o,e);if(n)try{let t=ji(n);return t.isFile()?t.size>Xn?{exists:!0,truncated:!0}:{exists:!0,content:Ti(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Oi(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}function Di(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 Bo(o){return Oi(o,["patch","diff","unifiedDiff","unified_diff"])}function Yn(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Lo(o,e){let n=qo("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:zo+65536});return n.status!==0?null:n.stdout??""}function Ni(o){let e=new Set;for(let n of o.split(`
|
|
31
|
+
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let r=t.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function Fo(o){let e=Lo(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Lo(o,["diff","--no-ext-diff","HEAD","--"])??"",t=Yn(n,zo);return{status:e,changedFiles:Ni(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function Ji(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function Bi(o,e){if(!Go(e))return;let n=Nt(o,e);if(!n)return;let t=Uo(o,n);if(t===""||t.startsWith(".."))return;let r=qo("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Xn+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=Yn(i,Xn);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Li(o,e,n){return e.map(t=>{let r=n.has(t)?n.get(t):Bi(o,t),i=ln(o,t);return{filePath:t,...r?{before:r}:{},...i?{after:i}:{}}})}function pn(o,e){let{prompt:n,projectRoot:t,screenshotPath:r,resumeSessionId:i,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:p=[]}=e,x=[];if(i){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(i),x.push(n),r&&x.push("--image",r)}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),r&&x.push("--image",r)}let T=Pi("codex",x,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),P=new Promise(b=>{let f,l=[],y=[],m=[],I=new Map,u=new Map,k=!1,A="",g=$i({input:T.stdout}),E=new Set;g.on("line",h=>{if(h.trim())try{let M=JSON.parse(h),O=M.type??"unknown";if(E.add(O),O==="thread.started"&&M.thread_id&&!f&&(f=M.thread_id),(O==="item.agentMessage.delta"||O==="item/agentMessage/delta")&&M.delta?.text&&(l.push(M.delta.text),c?.({type:"delta",jobId:o,text:M.delta.text},o)),(O==="item.reasoning.delta"||O==="item/reasoning/delta")&&M.delta?.text&&c?.({type:"thinking",jobId:o,text:M.delta.text},o),(O==="item.started"||O==="item/started")&&M.item){let J=M.item.type;if(J==="command_execution"){let z=M.item.command,K=z?No(z):void 0,Z=Fo(t),re=new Map;for(let V of Z?.changedFiles??[])re.set(V,ln(t,V));typeof M.item.id=="string"&&u.set(M.item.id,{...z?{rawCommand:z}:{},...K?{command:K}:{},...Z?{beforeWorktree:Z}:{},beforeSnapshots:re});let D=K?`Bash: ${K.split(`
|
|
32
|
+
`)[0].slice(0,80)}`:"Bash";y.push(D),c?.({type:"tool_use",jobId:o,tool:"Bash",...K?{content:K}:{}},o)}else if(J==="file_change"){let z=M.item.filename||M.item.path;z&&!I.has(z)&&I.set(z,ln(t,z)),y.push(z?`Edit ${z.split("/").pop()}`:"Edit");let K=z?Nt(t,z)??z:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...K?{file:K}:{}},o)}else if(J==="file_read"){let z=M.item.filename||M.item.path;y.push(z?`Read ${z.split("/").pop()}`:"Read");let K=z?Nt(t,z)??z:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...K?{file:K}:{}},o)}else if(J==="web_search")y.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(J==="mcp_tool_call"){let z=M.item.tool_name||M.item.name||"MCP";y.push(z),c?.({type:"tool_use",jobId:o,tool:z},o)}}if((O==="item.completed"||O==="item/completed")&&M.item){if(M.item.type==="agent_message"){let J=M.item.text;typeof J=="string"&&J&&(l.push(J),c?.({type:"delta",jobId:o,text:J},o))}else if(M.item.type==="reasoning"){let J=M.item.text;typeof J=="string"&&J&&c?.({type:"thinking",jobId:o,text:J},o)}else if(M.item.type==="file_change"&&Array.isArray(M.item.changes))for(let J of M.item.changes){let z=J.path||J.filename,K=J.kind==="add"?"Write":"Edit";if(z){y.push(`${K} ${z.split("/").pop()}`);let Z=Nt(t,z)??z;c?.({type:"tool_use",jobId:o,tool:K,file:Z},o);let re=J,D=typeof re.kind=="string"?re.kind:void 0,V=Di(D),ge=I.get(z),L=ln(t,z);m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:V,filePath:z,...ge?{before:ge}:{},...L?{after:L}:{},...Bo(re)?{patch:Bo(re)}:{},...D?{rawKind:D}:{}}),I.set(z,L)}}else if(M.item.type==="command_execution"){let J=typeof M.item.id=="string"?M.item.id:void 0,z=J?u.get(J):void 0,K=typeof M.item.command=="string"?M.item.command:z?.rawCommand,Z=K?No(K):z?.command,re=Fo(t);if(Ji(z?.beforeWorktree,re)){let D=[...new Set([...z?.beforeWorktree?.changedFiles??[],...re?.changedFiles??[]])],V=typeof M.item.aggregated_output=="string"?Yn(M.item.aggregated_output,Ci):void 0,ge=typeof M.item.exit_code=="number"?M.item.exit_code:M.item.exit_code===null?null:void 0,L=typeof M.item.status=="string"?M.item.status:void 0;m.push({sequence:m.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...K?{rawCommand:K}:{},...Z?{command:Z}:{},...ge!==void 0?{exitCode:ge}:{},...L?{status:L}:{},...V?{output:V.text}:{},...V?.truncated?{outputTruncated:!0}:{},...z?.beforeWorktree?{beforeWorktree:z.beforeWorktree}:{},...re?{afterWorktree:re}:{},...D.length>0?{touchedFiles:Li(t,D,z?.beforeSnapshots??new Map)}:{}})}J&&u.delete(J)}}O==="turn.failed"&&(k=!0,A=M.error?.message||M.message||"Turn failed")}catch{}});let C=[];T.stderr?.on("data",h=>{C.push(h.toString())}),T.on("close",h=>{g.close(),l.length===0&&E.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...E].join(", ")}`),h!==0&&h!==null&&(k=!0,A=C.join("")||`Codex process exited with code ${h}`),b({sessionId:f,text:l.join(""),success:!k,error:k?A:void 0,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})}),T.on("error",h=>{k=!0,A=h.message,b({sessionId:f,text:l.join(""),success:!1,error:A,editEvents:m.length>0?m:void 0,toolsUsed:y.length>0?y:void 0})})});return{process:T,result:P}}import{spawn as Fi}from"child_process";import{createInterface as qi}from"readline";function Ho(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 Wo(o,e){let{prompt:n,projectRoot:t,resumeSessionId:r,model:i,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"];r&&p.push(`--resume=${r}`),i&&p.push("--model",i),p.push("-p",n);let x=Fi(d,p,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),T=new Promise(P=>{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=qi({input:x.stdout}),A=new Set,g=[];k.on("line",C=>{if(C.trim())try{let h=JSON.parse(C),M=Bt(h);A.add(M),g.length<5&&zi(M)&&g.push(C.slice(0,800));let O=Jt(h,["sessionId","session_id","id"],["session","conversation","thread"]);O&&!b&&(b=O);let J=Ui(h,f.length===0);J&&(f.push(J),c?.({type:"delta",jobId:o,text:J},o));let z=Gi(h);z&&c?.({type:"thinking",jobId:o,text:z},o);let K=Hi(h);K&&(l.push(K.label),c?.({type:"tool_use",jobId:o,tool:K.tool,...K.file?{file:K.file}:{},...K.content?{content:K.content}:{}},o));let Z=Wi(h);Z&&(y=!0,m=Z)}catch{}});let E=[];x.stderr?.on("data",C=>{E.push(C.toString())}),x.on("close",C=>{clearTimeout(u),k.close(),f.length===0&&A.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...A].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
|
|
33
|
+
`)}`)),I?(y=!0,m=`Timed out after ${Math.round(s/6e4)} minutes`):C!==0&&C!==null&&(y=!0,m=E.join("").trim()||m||`Copilot process exited with code ${C}`);let h=y?Ho(m,i):null;P({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",C=>{clearTimeout(u);let h=Ho(C.message,i);P({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:T}}function Bt(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 Ui(o,e=!1){let n=Bt(o).toLowerCase(),t=o.update,r=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return Je(o.delta)??Je(o.content)??Je(o.message);if(n==="assistant.message"&&e)return Je(o.message)??Je(o.content)??Je(o);if(n==="result"&&e)return Je(o.result)??Je(o.output)??Je(o.message)??Je(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&Zn(o))return o.text;if(typeof o.message=="string"&&Zn(o))return o.message;if(typeof o.delta=="string"&&Zn(o))return o.delta}function Je(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(Je).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=Je(e[n]);if(t)return t}}function zi(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Gi(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function Hi(o){let e=Jt(o,["tool","toolName","tool_name","name"]),n=Jt(o,["command","cmd"]),t=Jt(o,["file","path","filename","filePath"]),r=Bt(o);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
34
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function Wi(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"&&Bt(o).toLowerCase().includes("error"))return o.message}function Jt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let i=Jt(r,e);if(i)return i}}function Zn(o){let e=Bt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as Vi,readFile as Ki}from"fs/promises";import{join as eo}from"path";var un=class{constructor(e){let n=eo(e,".popmelt");this.decisionsDir=eo(n,"decisions")}async listDecisionIds(){try{return(await Vi(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 Ki(eo(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{randomUUID as Vo}from"crypto";import{mkdir as to,readFile as no,writeFile as mn}from"fs/promises";import{dirname as oo,join as vt}from"path";var Ue="[ProjectionWorker]",Qi={version:1,runs:[]},Xi={version:1,updatedAt:0,proposals:[]},Yi=12;function Zi(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 Ko(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(`${Ue} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Ue} Rule count ${e.length} exceeds cap of 30`),e}function es(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function ts(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let f of i){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)&&r.add(y)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(n?.rules)?n.rules:[],p=i.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:{},T=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},P=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(T[f])).length;return{ruleCount:p,tokenSectionCount:P,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(f=>!r.has(f))}}function ns(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function os(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function fn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=os(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=ns(n)}function Qo(o,e){let n=o;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function rs(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 is(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 Xo(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=rs(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?is(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var hn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=vt(e,".popmelt");this.runsPath=vt(t,"projection-runs.json"),this.legacyRunsPath=vt(t,"materialization-runs.json"),this.proposalsPath=vt(t,"projection-queue.json"),this.legacyProposalsPath=vt(t,"model-proposals.json"),this.modelPath=vt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await no(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Zi(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?Qo(n,r):fn(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Yi),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(f=>f.id);console.log(`${Ue} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=ds(r,s),d=es(r,t.totalCandidateDecisionCount,c);n=Vo().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:i,startedAt:Date.now(),promptStats:d};await this.persistRun(p);let x=!0,T,P,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,T=m.error,console.error(`${Ue} ${l} spawn error:`,T);else{let I=cs(m.text,i);if(I){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of I)fn(u,g.path,g.value);Array.isArray(u.rules)&&(u.rules=Ko(u.rules));let k=ts(u,i,s);if(I){let g=[...new Set(I.flatMap(E=>E.decisionIds))];k.coveredDecisionIds=g,k.uncoveredDecisionIds=i.filter(E=>!g.includes(E))}P=k;let A=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:l,model:e.model??this.options.model,outputStats:P,changes:I});b=A.id,console.log(`${Ue} Created model proposal ${A.id} for ${i.length} decision(s)`)}else x=!1,T="No valid bounded <model-changes> block found in response",console.error(`${Ue} ${T}`)}}catch(f){x=!1,T=f instanceof Error?f.message:String(f),console.error(`${Ue} Error:`,T)}return await this.persistRun({...p,status:x?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:P,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:x,error:T}),{processedIds:i,success:x,error:T,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ko(e.rules)),await mn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ue} 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 to(oo(this.runsPath),{recursive:!0}),await mn(this.runsPath,JSON.stringify(n,null,2)),n):{...Qi,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Xi,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(t);for(let s of r.changes??[])fn(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?Qo(s,d.path):fn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:Vo().slice(0,8),status:"pending",title:ss(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"}.`:as(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await to(oo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await mn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ue} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await to(oo(this.runsPath),{recursive:!0}),await mn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ue} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await no(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await no(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let i=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...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})}:(i==="copilot"&&console.warn(`${Ue} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...dn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function ss(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function as(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function cs(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),i=t.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(T=>typeof T=="string"||typeof T=="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(T=>typeof T=="string"&&r.has(T)):[];return x.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:x,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===t.length?i:null}catch{return null}}function ds(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
91
35
|
Kind: ${i.kind}
|
|
92
36
|
Claim: ${i.claim}
|
|
93
37
|
${i.rationale?`Rationale: ${i.rationale}`:""}
|
|
@@ -166,75 +110,71 @@ Example:
|
|
|
166
110
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
167
111
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
168
112
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
169
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
170
|
-
`),n=[],t=null;for(let r of e){let i=r.match(
|
|
113
|
+
Include property and bindings when the decision context has class-level evidence.`}var gn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let r of this.listeners)r(e,n,t)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as ls}from"child_process";import{readFile as er}from"fs/promises";import{homedir as io}from"os";import{join as Ve}from"path";var so=/popmelt/i;function lt(){return{found:!1,name:null,scope:null,disabled:!1}}function It(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function Lt(o){for(let e of Object.keys(o))if(so.test(e))return e;return null}async function yn(o){try{let e=await er(o,"utf-8");return JSON.parse(e)}catch{return null}}async function ao(o){let e=io(),n=await yn(Ve(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Lt(r.mcpServers);if(i)return It(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Lt(c.mcpServers);if(d){let p=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(x=>so.test(x));return It(d,"project",p)}}}}}let t=await yn(Ve(o,".mcp.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Lt(r.mcpServers);if(s){let c=await Yo(o,s);return It(s,"mcp.json",c)}}let i=Lt(r);if(i&&i!=="mcpServers"){let s=await Yo(o,i);return It(i,"mcp.json",s)}}return lt()}async function Yo(o,e){let n=Ve(o,".claude","settings.local.json"),t=await yn(n);if(t&&typeof t=="object"){let r=t;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var ps=/^\[mcp_servers\.([^\]]+)\]/;function us(o){let e=o.split(`
|
|
114
|
+
`),n=[],t=null;for(let r of e){let i=r.match(ps);i?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
171
115
|
`)}),t={name:i[1],bodyLines:[]}):r.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
172
116
|
`)}),t=null):t&&t.bodyLines.push(r)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
173
|
-
`)}),n}function
|
|
174
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
117
|
+
`)}),n}function ms(o){return/enabled\s*=\s*false/i.test(o)}async function co(o){let e=process.env.CODEX_HOME||Ve(io(),".codex"),n=await Zo(Ve(e,"config.toml"),"user");if(n.found)return n;let t=await Zo(Ve(o,".codex","config.toml"),"project");return t.found?t:lt()}async function lo(o,e="copilot"){let n=await fs(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Ve(io(),".copilot"),r=await ro(Ve(t,"mcp-config.json"),"user");if(r.found)return r;let i=await ro(Ve(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await ro(Ve(o,".github","mcp.json"),"mcp.json");return s.found?s:lt()}async function fs(o){try{let e=await new Promise((n,t)=>{ls(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return tr(JSON.parse(e),"user")}catch{return lt()}}async function ro(o,e){let n=await yn(o);return tr(n,e)}function tr(o,e){if(!o||typeof o!="object")return lt();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=Lt(t);return r?It(r,e):lt()}async function Zo(o,e){try{let n=await er(o,"utf-8"),t=us(n);for(let r of t)if(so.test(r.name)){let i=ms(r.body);return It(r.name,e,i)}}catch{}return lt()}import{execFile as nr}from"child_process";import{mkdir as hs,readFile as or,writeFile as rr}from"fs/promises";import{homedir as ir}from"os";import{dirname as gs,join as po}from"path";var uo="https://mcp.popmelt.com/mcp";async function sr(o=uo){let e=po(ir(),".claude.json"),n;try{let r=await or(e,"utf-8");n=JSON.parse(r)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let r of Object.keys(t))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await rr(e,JSON.stringify(n,null,2)+`
|
|
118
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function ar(o=uo){let e=process.env.CODEX_HOME||po(ir(),".codex"),n=po(e,"config.toml"),t;try{t=await or(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await hs(gs(n),{recursive:!0});let r=`
|
|
175
119
|
[mcp_servers.popmelt]
|
|
176
120
|
url = "${o}"
|
|
177
|
-
`;return await jr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function _r(o=ko,e="copilot"){let n=await pa(e);if(ua(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{Pr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function pa(o){try{let e=await new Promise((n,t)=>{Pr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return JSON.parse(e)}catch{return null}}function ua(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var En=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as $o,readFile as ut,writeFile as Co}from"fs/promises";import{join as Ye}from"path";var ma=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Po(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Mn(o){return new Set(Po(o).split(" ").filter(e=>e.length>2&&!ma.has(e)))}function $r(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 fa(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 ha(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Po).filter(Boolean),i=Mn([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 fa(s)){let l=Po(d.value);for(let T of r){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($r(Mn(l),i)*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 ga(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function ya(o){return Math.ceil(JSON.stringify(o).length/4)}function Xt(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let h=[...o.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===y.id&&f.toState==="deferred"&&f.transitionContext?.kind==="proposal_deferral")?.transitionContext;return h?h.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||h.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||h.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||h.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||h.resurfaceWhen.includes("after_date")&&!!(h.revisitAfter&&Date.parse(t)>=Date.parse(h.revisitAfter)):!1}),s=o.records.filter(y=>y.recordType==="implementation_attempt"),c=ha(n,e),d=[...c.values()].sort((y,h)=>h.score-y.score),l=Mn([e.action,e.text].filter(Boolean).join(" ")),w=i.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($r(Mn(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 w){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:ga(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:ya(f)};if(m+u.estimatedTokens>T)break;x.push(u),m+=u.estimatedTokens}let p=Math.max(0,w.length-x.length);return{packets:x,subjectMatches:d.map(({score:y,...h})=>h),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:m},uncertainty:c.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var va=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function To(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function _n(o){return new Set(To(o).split(" ").filter(e=>e.length>2&&!va.has(e)))}function Cr(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 Ia(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(To).filter(Boolean),r=_n([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let w=To(l.value);for(let x of t){let m=w===x?95:w.includes(x)||x.includes(w)?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(Cr(_n(w),r)*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&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function wa(o){return Math.ceil(JSON.stringify(o).length/4)}function Et(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ba(o,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(i=>i.state==="completed"),r=t.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function xa(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),i=t[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function Dr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter($=>$.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter($=>$.recordType==="decision"&&$.state==="active"),c=i?s.filter($=>i.has($.id)):s,d=o.records.filter($=>$.recordType==="implementation_attempt"),l=o.records.filter($=>$.recordType==="verification_attempt"),w=o.records.filter($=>$.recordType==="freshness_signal"&&$.state==="open"),j=o.records.filter($=>$.recordType==="evidence"),T=o.records.filter($=>$.recordType==="model_entry"),x=[...o.records].reverse().filter($=>$.recordType==="eval_spec").filter(($,I,b)=>b.findIndex(M=>M.legacyId===$.legacyId)===I),m=Ia(r,e),p=new Map(m.map($=>[$.subjectId,$.score])),y=_n([e.action,e.text].filter(Boolean).join(" ")),h=c.flatMap($=>{let I=Math.max(0,...$.subjects.map(F=>p.get(F.subjectId)??0)),b=Math.round(Cr(_n($.claim),y)*35),M=I+b;return M>=50?[{decision:$,score:M}]:[]}).sort(($,I)=>I.score-$.score||$.decision.id.localeCompare(I.decision.id)),f=new Map;for(let $ of h.slice(0,t))f.set($.decision.id,$.decision);for(let $ of o.relationships){if(!Et($,"excepts")&&!Et($,"contradicts"))continue;let I=s.find(M=>M.id===$.from.entityId),b=s.find(M=>M.id===$.to.entityId);!I||!b||!f.has(I.id)&&!f.has(b.id)||(f.size<t&&f.set(I.id,I),f.size<t&&f.set(b.id,b))}let u=[...f.values()],A=$=>$.from.entityType==="decision"&&$.to.entityType==="decision"&&f.has($.from.entityId)&&f.has($.to.entityId),D=($,I=!1)=>{let b=new Set($.map(C=>C.id)),M=w.filter(C=>C.target.entityType==="decision"&&b.has(C.target.entityId)),F=new Set(o.relationships.filter(C=>Et(C,"excepts")&&b.has(C.from.entityId)&&b.has(C.to.entityId)).flatMap(C=>[C.from.entityId,C.to.entityId])),U=o.relationships.filter(C=>Et(C,"contradicts")&&b.has(C.from.entityId)&&b.has(C.to.entityId)).map(C=>({id:C.id,decisionIds:[C.from.entityId,C.to.entityId],unresolvedQuestion:C.reason,expansionRefs:[{kind:"record",id:C.id}]})),ne=new Set(U.flatMap(C=>C.decisionIds)),oe=j.filter(C=>C.sourceRefs.some(Z=>Z.kind==="record"&&b.has(Z.id))||o.relationships.some(Z=>Z.relationshipType==="supports"&&Z.from.entityType==="evidence"&&Z.from.entityId===C.id&&Z.to.entityType==="decision"&&b.has(Z.to.entityId))),ye=Math.max(0,h.length-$.length),Y=o.relationships.some(C=>Et(C,"contradicts")&&A(C)&&(!b.has(C.from.entityId)||!b.has(C.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:[]}):$.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(C=>C.expansionRefs)}),oe.some(C=>C.availability!=="available")&&q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:oe.map(C=>({kind:"record",id:C.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:C,...Z})=>Z),modelEntries:T.filter(C=>C.decisionIds.some(Z=>b.has(Z))).map(C=>({id:C.id,key:C.key,value:C.value,decisionIds:C.decisionIds})),evalSpecs:x.filter(C=>C.decisionIds.some(Z=>b.has(Z))).map(C=>({id:C.id,legacyId:C.legacyId,state:C.state,title:C.title,assertionCount:C.assertions.length,decisionIds:C.decisionIds,expansionRef:{kind:"record",id:C.id}})),decisions:$.map(C=>({id:C.id,kind:C.kind,claim:C.claim,subjectIds:C.subjects.map(Z=>Z.subjectId),authority:C.authority,effectiveState:ne.has(C.id)?"conflicted":F.has(C.id)?"excepted":"active",freshness:M.filter(Z=>Z.target.entityId===C.id).map(Z=>Z.signalType),expansionRef:{kind:"record",id:C.id}})),conflicts:U,uncertainties:q,implementation:$.map(C=>ba(C.id,d)),verification:$.map(C=>xa(C.id,l,M)),evidence:oe.map(C=>({evidenceId:C.id,summary:C.summary,availability:C.availability,sourceRefs:C.sourceRefs})),completeness:{status:V?"truncated":"complete",omittedDecisionCount:ye,omittedEvidenceCount:0,conflictsComplete:!Y}};return ge.budget.estimatedTokens=wa(ge),ge},R=D(u);for(;R.budget.estimatedTokens>n&&u.length>0;){let $=u.pop(),I=o.relationships.filter(b=>Et(b,"contradicts")&&(b.from.entityId===$.id||b.to.entityId===$.id)).flatMap(b=>[b.from.entityId,b.to.entityId]);u=u.filter(b=>!I.includes(b.id)),R=D(u,!0)}return R}var Sa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Mt(o){return Sa.test(o)}function Ra(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 jo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function je(o,e,n){Mt(n)||ae(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function He(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ae(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&ae(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&ae(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ka={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"])},Pa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ta(o,e,n){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.entity.entityId`,e.entity.entityId),He(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=ka[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ae(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Pa.has(i)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||ae(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&ae(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ae(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&He(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function ja(o,e,n,t){je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),He(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&ae(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ae(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ae(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&ae(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||ae(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&jo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&ae(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),He(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ae(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&ae(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&ae(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),He(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),He(o,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ae(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(He(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&ae(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&ae(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&ae(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&jo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&jo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Aa(o,e,n){if(je(o,`${n}.id`,e.id),je(o,`${n}.projectId`,e.projectId),je(o,`${n}.participantId`,e.participantId),je(o,`${n}.from.entityId`,e.from.entityId),je(o,`${n}.to.entityId`,e.to.entityId),He(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||ae(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&ae(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?ae(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&wt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ae(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ae(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&ae(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ae(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];je(e,"manifest.projectId",o.manifest.projectId),He(e,"manifest.createdAt",o.manifest.createdAt),He(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,y)=>{let h=n.get(p);h?ae(e,y,"duplicate_id",`ID is already used at ${h}.`):n.set(p,y)};o.records.forEach((p,y)=>{let h=`records[${y}]`;t(p.id,h),ja(e,p,h,o.manifest.projectId)}),o.events.forEach((p,y)=>{let h=`events[${y}]`;t(p.id,h),Ta(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),Aa(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}]`),je(e,`artifacts[${y}].id`,p.id)}),o.tombstones.forEach((p,y)=>{let h=`tombstones[${y}]`;t(p.id,h),je(e,`${h}.id`,p.id),je(e,`${h}.objectId`,p.objectId),je(e,`${h}.deletedById`,p.deletedById),He(e,`${h}.deletedAt`,p.deletedAt),wt(e,`${h}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),i=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,y)=>{let h=`${p.entityType}:${p.entityId}`;!r.has(h)&&!i.has(h)&&ae(e,y,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};o.events.forEach((p,y)=>s(p.entity,`events[${y}].entity`)),o.relationships.forEach((p,y)=>{s(p.from,`relationships[${y}].from`),s(p.to,`relationships[${y}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,y)=>{c.has(p)||ae(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,y,h)=>{!r.has(`${p}:${y}`)&&!i.has(`${p}:${y}`)&&ae(e,h,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,y)=>{let h=`records[${y}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${h}.granteeId`),l("participant",p.grantedById,`${h}.grantedById`),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`));break;case"observation":p.captureContext.subjectIds.forEach((f,u)=>l("subject",f,`${h}.captureContext.subjectIds[${u}]`)),p.captureContext.artifactIds.forEach((f,u)=>d(f,`${h}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":p.subjects.forEach((f,u)=>l("subject",f.subjectId,`${h}.subjects[${u}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((f,u)=>d(f,`${h}.messageArtifactIds[${u}]`)),p.resultRefs.forEach((f,u)=>s(f,`${h}.resultRefs[${u}]`));break;case"iteration":p.threadIds.forEach((f,u)=>l("thread",f,`${h}.threadIds[${u}]`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"evidence":p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"advisory_explanation":p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`)),p.supersededById&&l("advisory_explanation",p.supersededById,`${h}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((f,u)=>l("iteration",f,`${h}.iterationIds[${u}]`)),p.coverageClaims.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverageClaims[${u}].decisionId`)),p.artifactIds.forEach((f,u)=>d(f,`${h}.artifactIds[${u}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${h}.replacesSpecId`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.subjectIds.forEach((f,u)=>l("subject",f,`${h}.subjectIds[${u}]`)),(p.dependencies??[]).forEach((f,u)=>{f.kind==="subject"&&f.subjectId&&l("subject",f.subjectId,`${h}.dependencies[${u}].subjectId`)}),(p.scenarios??[]).forEach((f,u)=>{f.subjectIds?.forEach((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":wt(e,`${h}.authority`,p.authority,!0),l("participant",p.appliedById,`${h}.appliedById`),p.decisionIds.forEach((f,u)=>l("decision",f,`${h}.decisionIds[${u}]`)),p.entryIds.forEach((f,u)=>l("model_entry",f,`${h}.entryIds[${u}]`)),p.coverage.forEach((f,u)=>l("decision",f.decisionId,`${h}.coverage[${u}].decisionId`));break;case"freshness_signal":s(p.target,`${h}.target`),p.evidenceIds.forEach((f,u)=>l("evidence",f,`${h}.evidenceIds[${u}]`));break;default:break}});let w=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=w.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 Ra(e)}function Yt(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 Or(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ea(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function $n(o,e){let n=[],t=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Mt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Ea(e))Mt(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Yt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Or(o,t,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Yt(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={...Yt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Or(o,i,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...Yt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Yt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ma}from"crypto";import{readFile as _a,readdir as $a,realpath as Ca}from"fs/promises";import{join as Zt,relative as Da}from"path";var Oa=["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 _t(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Jr(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ma("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function Ao(o,e){try{return JSON.parse(await _a(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Ja(o){let e=_t(o);if(!e)return 0;let n=0,t=r=>{let i=_t(r);if(!i){n+=1;return}for(let s of Object.values(i))t(s)};for(let r of Object.values(e))t(r);return n}function Na(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function xt(o){let e=[],n=await Ca(o.projectRoot).catch(()=>o.projectRoot),t=Zt(n,".popmelt"),r=await Ao(Zt(t,"threads.json"),e),i=await Ao(Zt(t,"model.json"),e),s=_t(r),c=_t(s?.threads)??{},d=Object.entries(c).map(([C,Z])=>({key:C,value:_t(Z)})).filter(C=>!!C.value),l=Zt(t,"decisions"),w=await $a(l).catch(()=>[]),j=[];for(let C of w.filter(Z=>Z.endsWith(".json")).sort()){let Z=_t(await Ao(Zt(l,C),e));Z&&j.push({file:C,value:Z})}let T=d.flatMap(({value:C})=>[C.createdAt,C.updatedAt]).filter(C=>typeof C=="number"&&Number.isFinite(C)),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=ze(Math.max(x,...T)),A=[],D=[],R=new Map,$=new Map,I=new Map(j.map(C=>[C.value.id??C.file.replace(/^d-|\.json$/g,""),C.value])),b=new Map,M=(C,Z,ue,se,Je)=>{let Ne=R.get(ue);if(Ne)return Ne;let ke=le(m,"artifact",C,se);return D.push({id:ke,kind:Z,mediaType:Je,location:ue,availability:"available"}),R.set(ue,ke),ke};for(let{file:C,value:Z}of j){let ue=Z.id??C.replace(/^d-|\.json$/g,""),se=Z.createdAt??x,Je=[M(`${ue}:envelope`,"other",`.popmelt/decisions/${C}`,se,"application/json")];Z.screenshotPath&&Je.push(M(`${ue}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,se,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ne,ke]of(Z.pastedImagePaths??[]).entries())Je.push(M(`${ue}:image:${Ne}`,"image",ke,se));b.set(ue,Je)}let F=(C,Z,ue)=>({id:C,schemaVersion:1,projectId:p,createdAt:u,participantId:Z,sourceRefs:ue}),H=(C,Z)=>{A.push(Z);let ue=$.get(C)??[];ue.push(Z.id),$.set(C,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:Da(process.cwd(),n)||n,aliases:[],locators:[{id:le(m,"locator",n,x),kind:"project_root",value:n,status:"current",validFrom:ze(x),sourceRefs:[]}]});let ne=new Map,oe=(C,Z)=>{let ue=ne.get(C);if(ue)return ue;let se=le(m,"subject",C,Z),Je={...F(se,y,[{kind:"external",id:C}]),createdAt:ze(Z),recordType:"subject",subjectType:"element",label:C,aliases:[],locators:[{id:le(m,"locator",C,Z),kind:"dom_selector",value:C,status:"current",validFrom:ze(Z),sourceRefs:[{kind:"external",id:C}]}]};return A.push(Je),ne.set(C,se),se};for(let{key:C,value:Z}of d){let ue=Z.id??C,se=Z.createdAt??x,Je=le(m,"thread",ue,se),Ne={kind:"thread",id:ue},ke=[],qe=[],Ke=Array.isArray(Z.messages)?Z.messages:[],tt,at,ft=0;Ke.forEach((be,ct)=>{let _e=be.timestamp??se,nt=le(m,"artifact",`${ue}:message:${ct}`,_e);if(ke.push(nt),D.push({id:nt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,availability:"available"}),R.set(`.popmelt/threads.json#/threads/${ue}/messages/${ct}`,nt),be.screenshotPath&&M(`${ue}:message:${ct}:screenshot`,"screenshot",be.screenshotPath,_e),be.role==="human"){tt=be;let Ee=be.feedbackSummary??be.replyToQuestion;if(Ee?.trim()){let Be=le(m,"observation",`${ue}:${ct}`,_e),pt=Z.elementIdentifiers??[],Pt={...F(Be,y,[Ne,{kind:"message",id:nt}]),createdAt:ze(_e),recordType:"observation",state:"open",statement:Ee,captureContext:{subjectIds:pt.map(gt=>oe(gt,se)),artifactIds:[nt]},resolvedByIds:[]};H(ue,Pt),at=Be,qe.push({entityType:"observation",entityId:Be})}return}if(be.role!=="assistant")return;let dt=be.jobId??`${ue}:${ct}`,lt=le(m,"iteration",dt,_e),ht=I.get(dt),io=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",so={...F(lt,h,[Ne,{kind:"message",id:nt},...(b.get(dt)??[]).map(Ee=>({kind:"artifact",id:Ee}))]),createdAt:ze(_e),recordType:"iteration",threadIds:[Je],startedAt:ze(tt?.timestamp,_e),completedAt:ze(_e),requestSummary:Jr(tt?.feedbackSummary,tt?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:io,execution:{provider:be.provider??ht?.provider,model:be.model??ht?.model,sessionId:be.sessionId??ht?.sessionId},artifactIds:[nt,...b.get(dt)??[]]};H(ue,so),qe.push({entityType:"iteration",entityId:lt});let Ut=be.resolutions??ht?.resolutions??[];for(let[Ee,Be]of Ut.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let pt=Z.elementIdentifiers??[],Pt=(pt.length?pt:[n]).map(fn=>({subjectId:fn===n?f:oe(fn,se),role:"governed"})),gt=le(m,"proposal",`${dt}:${Be.annotationId??"resolution"}:${Ee}`,_e),ao={...F(gt,h,[Ne,{kind:"iteration",id:lt}]),createdAt:ze(_e),recordType:"proposal",state:"pending",claim:Be.summary,subjects:Pt,subjectSemantics:Pt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Jr(tt?.feedbackSummary,tt?.replyToQuestion,Be.summary),iterationId:lt,inferredById:h}};H(ue,ao),qe.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ue,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Ut.some(Ee=>Ee.status==="resolved")||ht?.gitDiff){let Ee=le(m,"implementation",dt,_e),Be={...F(Ee,h,[Ne,{kind:"iteration",id:lt}]),createdAt:ze(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[lt],coverageClaims:[],summary:Ut.map(pt=>pt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};H(ue,Be),qe.push({entityType:"implementation_attempt",entityId:Ee}),ft+=1}at&&(at=void 0)});let Lt=Ke.at(-1),zt={...F(Je,y,[Ne]),createdAt:ze(se),recordType:"thread",state:Lt?.question?"open":"resolved",messageArtifactIds:ke,outcome:Lt?.question?"question_unresolved":ft?"implementation_only":"no_outcome",resultRefs:qe};A.push(zt),$.set(ue,[Je,...$.get(ue)??[]])}let ye=Ja(i);ye&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ye} model values were not promoted because their accepted decision provenance is unresolved.`});let Y={manifest:{formatVersion:1,projectId:p,createdAt:ze(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=bt(Y),ge=(o.proofCaseIds??Oa).map(C=>({legacyId:C,threadFound:d.some(({key:Z,value:ue})=>(ue.id??Z)===C),decisionEnvelopeFound:I.has(C),recordIds:$.get(C)??[]}));return{bundle:Y,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((C,Z)=>C+(Z.value.messages?.length??0),0),decisionEnvelopes:j.length,modelEntries:ye,artifactsReferenced:D.length},imported:Na(A),unresolvedAcceptance:e.filter(C=>C.code==="acceptance_unresolved").length,deferredModelEntries:ye,proofCases:ge,issues:e,schemaIssues:V.issues}}}import{createHash as Ba}from"crypto";import{mkdir as Nr,open as Eo,readFile as Mo,readdir as Fa,rename as La,unlink as _o}from"fs/promises";import{join as it}from"path";var za={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Dn(o){return Ba("sha256").update(JSON.stringify(o)).digest("hex")}function Br(o){return Dn(o)}function Fr(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let r=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(r<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let i=o.records[r];if(i.projectId!==t.projectId||i.createdAt!==t.createdAt||i.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[r]=structuredClone(t)}for(let t of e.projectionUpdates){let r=o.records.find(i=>i.recordType===t.entityType&&i.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ua(o,e,n){return Fr(structuredClone(o),e,n)}async function St(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Eo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await La(n,o)}catch(r){throw await _o(n).catch(()=>{}),r}}async function Cn(o){return JSON.parse(await Mo(o,"utf8"))}var On=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=bt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Nr(this.journalDir,{recursive:!0});try{throw await Mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=Dn(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await St(this.checkpointPath,r),await St(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await St(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=Dn(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await St(it(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await St(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Mt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...i,hash:Br(i)},c=Ua(t.bundle,e,n.committedAt),d=bt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await St(it(this.journalDir,l),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await St(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...za,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Cn(this.manifestPath),n=await Cn(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!==Dn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Fa(this.journalDir),r=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,w=new Set;for(let T of s){let x=await Cn(it(this.journalDir,T)),{hash:m,...p}=x;if(m!==Br(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(w.has(x.transactionId))throw new Error(`Duplicate transaction ID: ${x.transactionId}`);Fr(c,x.mutation,x.committedAt),d=x.sequence,l=x.hash,w.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=bt(c);if(!j.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(j.issues)}`);return{bundle:c,manifest:e,transactionIds:w,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Nr(this.memoryDir,{recursive:!0});let n;try{n=await Eo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Cn(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await _o(this.lockPath),n=await Eo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await _o(this.lockPath).catch(()=>{})}}};import{randomBytes as qa}from"crypto";function fe(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=qa(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var Wa=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Lr(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Wa(),l=d.records,w=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(A=>A.kind==="thread"&&A.id===e.threadId));w||(w={id:le(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));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(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(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(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(A)),j.push(A)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),x;if(T.length>0){x=le(r,"live-observation",i,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(r,"live-iteration",i,e.completedAt),p={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...x?[{kind:"record",id:x}]:[]],recordType:"iteration",threadIds:[w.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(r,"live-proposal",`${i}:${u}`,e.completedAt),R=f.map(I=>({subjectId:I.id,role:"governed"})),$={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($),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(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:m}],recordType:"implementation_attempt",state:"completed",iterationIds:[m],coverageClaims:A.map(R=>({decisionId:R.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map($=>$.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 Ga}from"crypto";import{mkdir as Ha,open as Va,readFile as Ka,rename as Qa,unlink as Xa}from"fs/promises";import{join as zr}from"path";function Ur(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qr(o){return Ga("sha256").update(JSON.stringify(o)).digest("hex")}async function Ya(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Va(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
179
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Qa(n,o)}catch(r){throw await Xa(n).catch(()=>{}),r}}function Za(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,l,w)=>{let j=d[l]??=[];j.includes(w)||j.push(w)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let w of[l.label,...l.aliases,...l.locators.filter(j=>j.status==="current").map(j=>j.value)]){let j=Ur(w);j&&s(t,j,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:qr(c)}}function Wr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Ur(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 Jn=class{constructor(e){this.indexDir=zr(e,".popmelt","memory","indexes"),this.indexPath=zr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Ka(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===qr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Za(e,n);return await Ha(this.indexDir,{recursive:!0}),await Ya(this.indexPath,t),t}};var en="popmelt:imprint",Gr="popmelt:imprint-evidence",$t="popmelt:imprint-relation";function Nn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===en)?.id}function Do(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 Bn(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 Fn=class{constructor(e){this.projectRoot=e;this.store=new On(e),this.indexStore=new Jn(e),this.manifestPath=Ye(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await ut(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await xt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await xt({...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=Ye(this.projectRoot,".popmelt","memory","migrations"),n=Ye(e,"legacy-evals-v1.json");try{let i=JSON.parse(await ut(n,"utf8"));return{migrated:!1,specs:i.specs??0,runs:i.runs??0}}catch{}let t=[],r=[];try{let i=JSON.parse(await ut(Ye(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));t=Array.isArray(i.cases)?i.cases:[]}catch{}try{let i=JSON.parse(await ut(Ye(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));r=Array.isArray(i.runs)?i.runs:[]}catch{}return t.length>0&&(t=(await this.reconcileEvalCases(t)).valid,await this.syncEvalSpecs(t),await this.syncLegacyEvalRuns(t,r)),await $o(e,{recursive:!0}),await Co(n,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:t.length,runs:r.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:t.length,runs:r.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Ye(this.projectRoot,".popmelt","memory","migrations"),n=Ye(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await ut(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await ut(Ye(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await $o(e,{recursive:!0}),await Co(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,w=new Set(r.bundle.records.map(u=>u.id)),j=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(A=>A.kind==="external"&&A.uri===$t?[A.id]:[]))),T=new Map,x=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let A=x.find(D=>Nn(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(b=>b.id===A),R=[],$=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 b of $){let M=le(l,"imprint-evidence-record",b.id,Date.parse(b.createdAt));R.push(M),!w.has(M)&&(m.push({id:M,schemaVersion:1,projectId:l,createdAt:b.createdAt,participantId:c.id,sourceRefs:Do([{kind:"external",id:b.id,uri:Gr},{kind:"external",id:u.id,uri:en},{kind:"thread",id:b.threadId},{kind:"message",id:b.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(b.kind)?"user_feedback":"judgment",summary:b.summary,availability:"available",artifactIds:[]}),y.push({id:le(l,"imprint-evidence-link",`${u.id}:${b.id}`,Date.parse(b.createdAt)),schemaVersion:1,projectId:l,createdAt:b.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:b.id,uri:Gr}],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:Do([...D?.sourceRefs??[],{kind:"external",id:u.id,uri:en}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...D?.evidenceIds??[],...R])],concreteBindings:Bn(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:$t}],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 $o(e,{recursive:!0}),await Co(n,JSON.stringify({version:2,migratedAt:f,explanations:t.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:h}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Xt(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Dr(t.bundle,r),reviewSelection:Xt(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:$n(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await xt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=$n(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),r=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:fe(i),decisionId:fe(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:fe(i),replacementProposalId:fe(i),acceptanceEventId:fe(i),decisionId:fe(i),relationshipId:fe(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:fe(i),reason:e.reason}:{...c,action:"defer",eventId:fe(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=$n(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(T=>T.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:fe(i),committedAt:s});await this.refreshIndex(w);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:w.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=Lr(n.bundle,e),r=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await ut(Ye(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),i=t.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?r:i??r,c=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),w=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=Nn(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(w,"imprint-explanation",f.explanationId,Date.parse(u?.createdAt??d)))}for(let f of e.summary.changes){let u={kind:"external",id:f.explanationId,uri:en},A=p.get(f.explanationId),D=m.find(b=>b.id===A),R=n?.explanations.find(b=>b.id===f.explanationId),$={id:le(w,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,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 I={id:A,schemaVersion:1,projectId:w,createdAt:D?.createdAt??R?.createdAt??d,participantId:D?.participantId??s.id,sourceRefs:Do([...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??[],$.id])],concreteBindings:R?Bn(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(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:I.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(f=>f.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===$t?[u.id]:[])));for(let f of n?.relations??[]){let u=p.get(f.fromId),A=p.get(f.toId);!u||!A||y.has(f.id)||x.push({id:le(w,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:w,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:$t}],recordType:"relationship",relationshipType:f.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId: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 ut(Ye(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="ai"&&R.status==="active")??t;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(R=>R.recordType==="advisory_explanation"),l=new Map(d.flatMap(R=>{let $=Nn(R);return $?[[$,R]]:[]})),w=new Map([...[...l].map(([R,$])=>[R,$.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 $=l.get(R.id);if(!$){j.push({id:w.get(R.id),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:en}],recordType:"advisory_explanation",kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Bn(e,R.id),supersededById:R.supersededBy?w.get(R.supersededBy):void 0,updatedAt:R.updatedAt});continue}let I={...structuredClone($),kind:R.kind,state:R.state,statement:R.statement,rationale:R.rationale,scope:structuredClone(R.scope),concreteBindings:Bn(e,R.id),supersededById:R.supersededBy?w.get(R.supersededBy):void 0,updatedAt:R.updatedAt},b=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});b($)!==b(I)&&T.push(I)}for(let[R,$]of l)x.has(R)||$.state==="retired"||T.push({...structuredClone($),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 $=R.sourceRefs.find(I=>I.kind==="external"&&I.uri===$t)?.id;return $?[[$,R]]:[]})),y=new Set(p.keys()),h=[];for(let R of e.relations){let $=w.get(R.fromId),I=w.get(R.toId);!$||!I||y.has(R.id)||h.push({id:le(c,"imprint-relation",R.id,Date.parse(R.createdAt)),schemaVersion:1,projectId:c,createdAt:R.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:R.id,uri:$t}],recordType:"relationship",relationshipType:R.type,from:{entityType:"advisory_explanation",entityId:$},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 r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&t.set(r.key,r);return[...t.values()]}async getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),r=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),i=new Map(r.map(p=>[p.id,p])),s=new Map(r.flatMap(p=>{let y=Nn(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]]:[])),w=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=r.map(p=>{let y=p.evidenceIds.flatMap(u=>{let A=l.get(u);if(!A)return[];let D=A.sourceRefs.find(b=>b.kind==="thread")?.id,R=A.sourceRefs.find(b=>b.kind==="message")?.id,$=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:$,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(w.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,$=i.get(R);return $?[{id:u.id,type:u.relationshipType,direction:A?"outgoing":"incoming",explanationId:$.id,statement:$.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 r=[...t.values()],i=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=i.filter(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===c.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(i=>i.recordType==="decision"&&e.includes(i.id)?i.subjects.map(s=>s.subjectId):[])),r=[];for(let i of n.records)if(!(i.recordType!=="subject"||!t.has(i.id)))for(let s of i.locators.filter(c=>c.status==="current"))s.kind==="source_file"?r.push({kind:"source_file",value:s.value,subjectId:i.id}):s.kind==="route_pattern"?r.push({kind:"route",value:s.value,subjectId:i.id}):s.kind==="token_path"?r.push({kind:"model_path",value:s.value,subjectId:i.id}):(s.kind==="dom_selector"||s.kind==="file_export"||s.kind==="source_span")&&r.push({kind:"subject",value:s.value,subjectId:i.id});return[...new Map(r.map(i=>[`${i.kind}:${i.value}:${i.subjectId??""}`,i])).values()]}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),t=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=n.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),c=fe(i),d=fe(i),l=fe(i),w=fe(i),j=fe(i),T=new Set(n.bundle.records.flatMap(b=>b.recordType==="model_entry"&&b.key===e.key?b.decisionIds:[])),x=n.bundle.records.filter(b=>b.recordType==="decision"&&b.state==="active"&&T.has(b.id)),m={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],y={...m,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},h={...m,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},f={...m,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},u={...m,id:w,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},A={...m,id:j,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},D={...m,id:fe(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},R=x.map(b=>({...m,id:fe(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:b.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),$=x.map(b=>({...m,id:fe(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:b.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,...$],artifacts:[],tombstones:[],projectionUpdates:x.map(b=>({entityType:"decision",entityId:b.id,fromState:"active",state:"superseded"}))},{transactionId:fe(i),committedAt:s});return await this.refreshIndex(I),{decisionId:l,entryId:w}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let n=await this.store.load();for(let t of e){let r=this.latestEvalSpec(n.bundle,t.id),i=n.bundle.records.flatMap(m=>m.recordType!=="decision"?[]:t.sourceDecisionIds.some(p=>p===m.id||m.sourceRefs.some(y=>y.id===p))?[m.id]:[]),s=[...new Set(n.bundle.records.flatMap(m=>m.recordType==="decision"&&i.includes(m.id)?m.subjects.map(p=>p.subjectId):[]))],d={state:t.status==="pending"?"draft":t.status==="approved"?"active":"retired",title:t.title,category:t.category,prompt:t.prompt,assertions:t.assertions,rationale:t.rationale,decisionIds:i,subjectIds:s,threadRefs:t.sourceThreadIds,dependencies:t.dependencies??[],scenarios:t.scenarios??[]};if(r&&JSON.stringify({state:r.state,title:r.title,category:r.category,prompt:r.prompt,assertions:r.assertions,rationale:r.rationale,decisionIds:r.decisionIds,subjectIds:r.subjectIds,threadRefs:r.threadRefs,dependencies:r.dependencies??[],scenarios:r.scenarios??[]})===JSON.stringify(d))continue;let l=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!l)throw new Error("No active local owner participant is available.");let w=Date.now(),j=new Date(w).toISOString(),T={id:fe(w),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:j,participantId:l.id,sourceRefs:[{kind:"external",id:t.id,uri:"popmelt:eval-spec"},...i.map(m=>({kind:"record",id:m}))],recordType:"eval_spec",legacyId:t.id,replacesSpecId:r?.id,...d,targets:i.map(m=>({entityType:"decision",entityId:m})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},x=r?[{id:fe(w),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:r.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(w),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)),r=e.records.filter(s=>s.recordType==="verification_attempt"),i=e.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.targetKind==="verification_result");return t.map(s=>{let c=r.filter(w=>w.evalSpecId===s.id).sort((w,j)=>j.createdAt.localeCompare(w.createdAt))[0],d=c&&i.some(w=>w.target.entityType==="verification_attempt"&&w.target.entityId===c.id),l=s.state==="draft"?"draft":s.state==="retired"?"retired":c?d?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:s.legacyId,canonicalSpecId:s.id,verificationState:l,title:s.title,status:s.state==="draft"?"pending":s.state==="active"?"approved":"rejected",category:s.category,prompt:s.prompt,assertions:s.assertions,rationale:s.rationale,sourceDecisionIds:s.decisionIds,sourceThreadIds:s.threadRefs,dependencies:s.dependencies??[],scenarios:s.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(n=>n.id===e)??null}async updateJournalEvalCase(e,n){let t=await this.findJournalEvalCase(e);if(!t)return null;let[r]=await this.syncEvalSpecs([{...t,...n}]);return r??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Map(e.records.flatMap(t=>t.recordType==="eval_spec"?[[t.id,t]]:[]));return e.records.flatMap(t=>{if(t.recordType!=="verification_attempt"||!t.evalSpecId)return[];let r=n.get(t.evalSpecId);if(!r)return[];let i=t.evalRun,s=Date.parse(t.createdAt);return[{id:i?.id??t.id,evalId:r.legacyId,threadId:i?.threadId,status:t.state==="passed"?"pass":t.state==="failed"?"fail":"needs_review",createdAt:i?.createdAt??s,completedAt:i?.completedAt??s,durationMs:i?.durationMs??0,scope:i?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:t.summary??"",assertionResults:i?.assertionResults??r.assertions.map(c=>({assertion:c,status:"needs_review",summary:t.summary??"",evidence:[]})),tooling:i?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:i?.provider,model:i?.model,screenshotPath:i?.screenshotPath,codeFingerprint:i?.codeFingerprint,scopeFingerprint:t.scopeFingerprint}]}).sort((t,r)=>t.completedAt-r.completedAt)}async recordEvalVerification(e,n){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(T=>T.recordType==="verification_attempt"&&T.evalRun?.id===n.id))return;let r=this.latestEvalSpec(t.bundle,e.id);if(!r)return;let i=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(!i)return;let s=n.completedAt,c=new Date(s).toISOString(),d={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:r.id},{kind:"external",id:n.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:n.summary,availability:"available",artifactIds:[]},l={id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:r.id}],recordType:"verification_attempt",evalSpecId:r.id,scopeFingerprint:n.scopeFingerprint,state:n.status==="pass"?"passed":n.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:i.id,name:n.model??n.provider??"Popmelt eval runner"},targets:r.targets,summary:n.summary,evidenceIds:[d.id],evalRun:{id:n.id,threadId:n.threadId,createdAt:n.createdAt,completedAt:n.completedAt,durationMs:n.durationMs,scope:n.scope,assertionResults:n.assertionResults,tooling:n.tooling,provider:n.provider,model:n.model,screenshotPath:n.screenshotPath,codeFingerprint:n.codeFingerprint}},w=r.targets.map(T=>({id:fe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:d.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:l.id},to:T,reason:n.summary})),j=await this.store.commit({records:[d,l],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(s),committedAt:c});await this.refreshIndex(j)}async syncLegacyEvalRuns(e,n){let t=new Map(e.map(r=>[r.id,r]));for(let r of[...n].sort((i,s)=>i.completedAt-s.completedAt)){let i=t.get(r.evalId);i&&await this.recordEvalVerification(i,r)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let n=await this.store.load();if(n.bundle.records.some(l=>l.recordType==="freshness_signal"&&l.state==="open"&&l.targetKind==="verification_result"&&l.target.entityType==="verification_attempt"&&l.target.entityId===e.verificationAttemptId))return;let t=n.bundle.records.find(l=>l.recordType==="verification_attempt"&&l.id===e.verificationAttemptId&&l.evalSpecId===e.evalSpecId),r=n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active"&&l.kind==="system")??n.bundle.records.find(l=>l.recordType==="participant"&&l.status==="active");if(!t||!r)return;let i=Date.now(),s=new Date(i).toISOString(),c={id:fe(i),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:r.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:t.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:t.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:t.evidenceIds},d=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(i),committedAt:s});await this.refreshIndex(d)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let n=await this.store.load(),t=new Set(n.bundle.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id,...d.sourceRefs.map(l=>l.id)]:[])),r=e.filter(d=>(d.dependencies?.length??0)>0||d.sourceDecisionIds.some(l=>t.has(l))),i=e.filter(d=>!r.includes(d)).map(d=>d.id);if(i.length===0)return{valid:r,discardedIds:i};let s=n.bundle.records.find(d=>d.recordType==="participant"&&d.kind==="human"&&d.status==="active");if(!s)return{valid:r,discardedIds:i};let c=i.flatMap(d=>{let l=this.latestEvalSpec(n.bundle,d);return l?[l]:[]}).filter(d=>!n.bundle.tombstones.some(l=>l.objectType==="eval_spec"&&l.objectId===d.id));if(c.length>0){let d=Date.now(),l=new Date(d).toISOString();n=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(w=>({id:fe(d),schemaVersion:1,projectId:n.bundle.manifest.projectId,objectId:w.id,objectType:"eval_spec",deletedAt:l,deletedById:s.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:fe(d),committedAt:l}),await this.refreshIndex(n)}return{valid:r,discardedIds:i}}latestEvalSpec(e,n){return[...e.records].reverse().find(t=>t.recordType==="eval_spec"&&t.legacyId===n)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(m=>m.recordType==="model_projection"&&m.state==="applied"&&m.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(m=>m.recordType==="decision"&&e.decisionIds.includes(m.id)&&m.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=fe(s),l=e.changes.map(m=>{let p=m.decisionIds?.filter(f=>e.decisionIds.includes(f)),y=p?.length?p:e.decisionIds,h=[...new Set(r.filter(f=>y.includes(f.id)).flatMap(f=>f.subjects.map(u=>u.subjectId)))];return{id:fe(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:y.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:m.path.map(String).join("."),subjectIds:h,decisionIds:y,value:m.value}}),w=new Set(l.flatMap(m=>m.decisionIds)),j={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(m=>({kind:"record",id:m})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(m=>m.id),coverage:e.decisionIds.map(m=>e.coverage?.find(p=>p.decisionId===m)??{decisionId:m,status:w.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:i.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 xt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Wr(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Dt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Re(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Ct(o,e,n){let t=Re(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Oo(o){let e=Dt(o),n=Dt(e.authority),t=n.level,r=n.mode,i=Ct(t,"authority.level",["owner","delegate","contributor"]),s=Ct(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Re(e.proposalId,"proposalId"),participantId:Re(e.participantId,"participantId"),occurredAt:Re(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Re(e.eventId,"eventId"),decisionId:Re(e.decisionId,"decisionId"),kind:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Re(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Re(e.eventId,"eventId"),reason:Re(e.reason,"reason")};case"defer":{let d=Dt(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:Re(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=>Re(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Ct(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Re(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Re(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Re(e.acceptanceEventId,"acceptanceEventId"),decisionId:Re(e.decisionId,"decisionId"),relationshipId:Re(e.relationshipId,"relationshipId"),claim:Re(e.claim,"claim"),kind:Ct(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Dt(d);return{subjectId:Re(l.subjectId,"subjectId"),role:Ct(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Re(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Jo(o){let e=Dt(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>Re(c,s))}},t=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:Dt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Ln(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
180
|
-
`)}async function
|
|
181
|
-
`)}function
|
|
121
|
+
`;return await rr(n,t+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function cr(o=uo,e="copilot"){let n=await ys(e);if(vs(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,r)=>{nr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function ys(o){try{let e=await new Promise((n,t)=>{nr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){t(r);return}n(i)})});return JSON.parse(e)}catch{return null}}function vs(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 vn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:n,createdAt:r?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,r]of this.leases)r.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{mkdir as xr,readFile as zt,writeFile as Sr}from"fs/promises";import{join as St}from"path";var Is=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function mo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function In(o){return new Set(mo(o).split(" ").filter(e=>e.length>2&&!Is.has(e)))}function dr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ws(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 bs(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(mo).filter(Boolean),i=In([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 ws(s)){let p=mo(d.value);for(let P of r){let b=p===P?95:p.includes(P)||P.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 T=["/","#","[","]","="].some(P=>d.value.includes(P))?0:Math.round(dr(In(p),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}c&&n.set(s.id,c)}return n}function xs(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function Ss(o){return Math.ceil(JSON.stringify(o).length/4)}function Ft(o,e){let n=o.records.filter(y=>y.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(y=>{if(y.recordType!=="proposal"||r&&!r.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let 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=bs(n,e),d=[...c.values()].sort((y,m)=>m.score-y.score),p=In([e.action,e.text].filter(Boolean).join(" ")),x=i.flatMap(y=>{let m=y.subjects.map(A=>c.get(A.subjectId)).filter(A=>!!A),I=Math.max(0,...m.map(A=>A.score)),u=Math.round(dr(In(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)),T=Math.max(1,e.maxPackets??3),P=Math.max(200,e.maxEstimatedTokens??1200),b=[],f=0;for(let y of x){if(b.length>=T)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,...A})=>A)},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:xs(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:Ss(I)};if(f+u.estimatedTokens>P)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:P,estimatedTokens:f},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var ks=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function fo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function wn(o){return new Set(fo(o).split(" ").filter(e=>e.length>2&&!ks.has(e)))}function lr(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 Rs(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(fo).filter(Boolean),r=wn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of d){let x=fo(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 P=["/","#","[","]","="].some(b=>p.value.includes(b))?0:Math.round(lr(wn(x),r)*55);P>=30&&P>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:P>=45?"strong":"weak",matchedBy:"semantic",score:P})}c&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Ps(o){return Math.ceil(JSON.stringify(o).length/4)}function wt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ts(o,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(i=>i.state==="completed"),r=t.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function js(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),i=t[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function pr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(g=>g.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=i?s.filter(g=>i.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"),T=o.records.filter(g=>g.recordType==="evidence"),P=o.records.filter(g=>g.recordType==="model_entry"),b=Rs(r,e),f=new Map(b.map(g=>[g.subjectId,g.score])),l=wn([e.action,e.text].filter(Boolean).join(" ")),y=c.flatMap(g=>{let E=Math.max(0,...g.subjects.map(M=>f.get(M.subjectId)??0)),C=Math.round(lr(wn(g.claim),l)*35),h=E+C;return h>=50?[{decision:g,score:h}]:[]}).sort((g,E)=>E.score-g.score||g.decision.id.localeCompare(E.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(!wt(g,"excepts")&&!wt(g,"contradicts"))continue;let E=s.find(h=>h.id===g.from.entityId),C=s.find(h=>h.id===g.to.entityId);!E||!C||!m.has(E.id)&&!m.has(C.id)||(m.size<t&&m.set(E.id,E),m.size<t&&m.set(C.id,C))}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,E=!1)=>{let C=new Set(g.map(L=>L.id)),h=x.filter(L=>L.target.entityType==="decision"&&C.has(L.target.entityId)),M=new Set(o.relationships.filter(L=>wt(L,"excepts")&&C.has(L.from.entityId)&&C.has(L.to.entityId)).flatMap(L=>[L.from.entityId,L.to.entityId])),J=o.relationships.filter(L=>wt(L,"contradicts")&&C.has(L.from.entityId)&&C.has(L.to.entityId)).map(L=>({id:L.id,decisionIds:[L.from.entityId,L.to.entityId],unresolvedQuestion:L.reason,expansionRefs:[{kind:"record",id:L.id}]})),z=new Set(J.flatMap(L=>L.decisionIds)),K=T.filter(L=>L.sourceRefs.some(G=>G.kind==="record"&&C.has(G.id))||o.relationships.some(G=>G.relationshipType==="supports"&&G.from.entityType==="evidence"&&G.from.entityId===L.id&&G.to.entityType==="decision"&&C.has(G.to.entityId))),Z=Math.max(0,y.length-g.length),re=o.relationships.some(L=>wt(L,"contradicts")&&u(L)&&(!C.has(L.from.entityId)||!C.has(L.to.entityId))),D=E||Z>0||re,V=[];b.length===0&&(e.subjectHints?.length??0)>0?V.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&V.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),J.length&&V.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:J.flatMap(L=>L.expansionRefs)}),K.some(L=>L.availability!=="available")&&V.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:K.map(L=>({kind:"record",id:L.id}))}),D&&V.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:b.map(({score:L,...G})=>G),modelEntries:P.filter(L=>L.decisionIds.some(G=>C.has(G))).map(L=>({id:L.id,key:L.key,value:L.value,decisionIds:L.decisionIds})),decisions:g.map(L=>({id:L.id,kind:L.kind,claim:L.claim,subjectIds:L.subjects.map(G=>G.subjectId),authority:L.authority,effectiveState:z.has(L.id)?"conflicted":M.has(L.id)?"excepted":"active",freshness:h.filter(G=>G.target.entityId===L.id).map(G=>G.signalType),expansionRef:{kind:"record",id:L.id}})),conflicts:J,uncertainties:V,implementation:g.map(L=>Ts(L.id,d)),verification:g.map(L=>js(L.id,p,h)),evidence:K.map(L=>({evidenceId:L.id,summary:L.summary,availability:L.availability,sourceRefs:L.sourceRefs})),completeness:{status:D?"truncated":"complete",omittedDecisionCount:Z,omittedEvidenceCount:0,conflictsComplete:!re}};return ge.budget.estimatedTokens=Ps(ge),ge},A=k(I);for(;A.budget.estimatedTokens>n&&I.length>0;){let g=I.pop(),E=o.relationships.filter(C=>wt(C,"contradicts")&&(C.from.entityId===g.id||C.to.entityId===g.id)).flatMap(C=>[C.from.entityId,C.to.entityId]);I=I.filter(C=>!E.includes(C.id)),A=k(I,!0)}return A}var Ms=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function bt(o){return Ms.test(o)}function As(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 ho(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Re(o,e,n){bt(n)||ee(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function ze(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&ee(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function pt(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 Es={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"])},_s=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function $s(o,e,n){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.entity.entityId`,e.entity.entityId),ze(o,`${n}.createdAt`,e.createdAt),pt(o,`${n}.authority`,e.authority);let t=Es[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&ee(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(_s.has(i)&&(pt(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&&ze(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Cs(o,e,n,t){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),ze(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"&&(pt(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"&&ho(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."),ze(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ee(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&ee(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&ee(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),ze(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),ze(o,`${n}.concreteBindings[${i}].updatedAt`,r.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"&&(ze(o,`${n}.appliedAt`,e.appliedAt),pt(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(r=>!r.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&&ho(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&ho(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Os(o,e,n){if(Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.from.entityId`,e.from.entityId),Re(o,`${n}.to.entityId`,e.to.entityId),ze(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 r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&ee(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?ee(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&pt(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 ut(o){let e=[];Re(e,"manifest.projectId",o.manifest.projectId),ze(e,"manifest.createdAt",o.manifest.createdAt),ze(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),Cs(e,l,m,o.manifest.projectId)}),o.events.forEach((l,y)=>{let m=`events[${y}]`;t(l.id,m),$s(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),Os(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}]`),Re(e,`artifacts[${y}].id`,l.id)}),o.tombstones.forEach((l,y)=>{let m=`tombstones[${y}]`;t(l.id,m),Re(e,`${m}.id`,l.id),Re(e,`${m}.objectId`,l.objectId),Re(e,`${m}.deletedById`,l.deletedById),ze(e,`${m}.deletedAt`,l.deletedAt),pt(e,`${m}.authority`,l.authority,!0)});let r=new Set(o.records.map(l=>`${l.recordType}:${l.id}`)),i=new Set(o.tombstones.map(l=>`${l.objectType}:${l.objectId}`)),s=(l,y)=>{let m=`${l.entityType}:${l.entityId}`;!r.has(m)&&!i.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)=>{!r.has(`${l}:${y}`)&&!i.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,A)=>p("subject",k,`${m}.scenarios[${u}].subjectIds[${A}]`))}),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":pt(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])),T=new Map(o.records.map(l=>[`${l.recordType}:${l.id}`,l])),P=new Map;o.events.forEach((l,y)=>{let m=`${l.entity.entityType}:${l.entity.entityId}:${l.fromState??"null"}`,I=P.get(m)??new Set;I.add(l.toState),P.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 A=Date.parse(m);(A<Date.parse(k.startsAt)||k.endsAt&&A>Date.parse(k.endsAt)||k.revokedAt&&A>=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=T.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=T.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."),T.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 As(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 ur(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ds(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 bn(o,e){let n=[],t=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),bt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Ds(e))bt(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=ur(o,t,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...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,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=ur(o,i,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:i.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i,d],events:[s,c],relationships:[p]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...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:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...qt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as Ns}from"crypto";import{readFile as Js,readdir as Bs,realpath as Ls}from"fs/promises";import{join as Ut,relative as Fs}from"path";var qs=["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 xt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Be(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function mr(...o){return o.find(e=>!!e?.trim())?.trim()}function oe(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ns("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function go(o,e){try{return JSON.parse(await Js(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function Us(o){let e=xt(o);if(!e)return 0;let n=0,t=r=>{let i=xt(r);if(!i){n+=1;return}for(let s of Object.values(i))t(s)};for(let r of Object.values(e))t(r);return n}function zs(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function mt(o){let e=[],n=await Ls(o.projectRoot).catch(()=>o.projectRoot),t=Ut(n,".popmelt"),r=await go(Ut(t,"threads.json"),e),i=await go(Ut(t,"model.json"),e),s=xt(r),c=xt(s?.threads)??{},d=Object.entries(c).map(([G,W])=>({key:G,value:xt(W)})).filter(G=>!!G.value),p=Ut(t,"decisions"),x=await Bs(p).catch(()=>[]),T=[];for(let G of x.filter(W=>W.endsWith(".json")).sort()){let W=xt(await go(Ut(p,G),e));W&&T.push({file:G,value:W})}let P=d.flatMap(({value:G})=>[G.createdAt,G.updatedAt]).filter(G=>typeof G=="number"&&Number.isFinite(G)),b=P.length?Math.min(...P):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=Be(Math.max(b,...P)),k=[],A=[],g=new Map,E=new Map,C=new Map(T.map(G=>[G.value.id??G.file.replace(/^d-|\.json$/g,""),G.value])),h=new Map,M=(G,W,se,ke,ve)=>{let Pe=g.get(se);if(Pe)return Pe;let $e=oe(f,"artifact",G,ke);return A.push({id:$e,kind:W,mediaType:ve,location:se,availability:"available"}),g.set(se,$e),$e};for(let{file:G,value:W}of T){let se=W.id??G.replace(/^d-|\.json$/g,""),ke=W.createdAt??b,ve=[M(`${se}:envelope`,"other",`.popmelt/decisions/${G}`,ke,"application/json")];W.screenshotPath&&ve.push(M(`${se}:screenshot`,"screenshot",`.popmelt/${W.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,W.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Pe,$e]of(W.pastedImagePaths??[]).entries())ve.push(M(`${se}:image:${Pe}`,"image",$e,ke));h.set(se,ve)}let O=(G,W,se)=>({id:G,schemaVersion:1,projectId:l,createdAt:u,participantId:W,sourceRefs:se}),J=(G,W)=>{k.push(W);let se=E.get(G)??[];se.push(W.id),E.set(G,se)},z=[{...O(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...O(m,m,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];k.push(...z),k.push({...O(I,y,[]),recordType:"subject",subjectType:"project",label:Fs(process.cwd(),n)||n,aliases:[],locators:[{id:oe(f,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Be(b),sourceRefs:[]}]});let K=new Map,Z=(G,W)=>{let se=K.get(G);if(se)return se;let ke=oe(f,"subject",G,W),ve={...O(ke,y,[{kind:"external",id:G}]),createdAt:Be(W),recordType:"subject",subjectType:"element",label:G,aliases:[],locators:[{id:oe(f,"locator",G,W),kind:"dom_selector",value:G,status:"current",validFrom:Be(W),sourceRefs:[{kind:"external",id:G}]}]};return k.push(ve),K.set(G,ke),ke};for(let{key:G,value:W}of d){let se=W.id??G,ke=W.createdAt??b,ve=oe(f,"thread",se,ke),Pe={kind:"thread",id:se},$e=[],He=[],Ct=Array.isArray(W.messages)?W.messages:[],We,Ot,on=0;Ct.forEach((Ie,nt)=>{let Me=Ie.timestamp??ke,Xe=oe(f,"artifact",`${se}:message:${nt}`,Me);if($e.push(Xe),A.push({id:Xe,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${se}/messages/${nt}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${se}/messages/${nt}`,Xe),Ie.screenshotPath&&M(`${se}:message:${nt}:screenshot`,"screenshot",Ie.screenshotPath,Me),Ie.role==="human"){We=Ie;let Ce=Ie.feedbackSummary??Ie.replyToQuestion;if(Ce?.trim()){let Oe=oe(f,"observation",`${se}:${nt}`,Me),it=W.elementIdentifiers??[],gt={...O(Oe,y,[Pe,{kind:"message",id:Xe}]),createdAt:Be(Me),recordType:"observation",state:"open",statement:Ce,captureContext:{subjectIds:it.map(at=>Z(at,ke)),artifactIds:[Xe]},resolvedByIds:[]};J(se,gt),Ot=Oe,He.push({entityType:"observation",entityId:Oe})}return}if(Ie.role!=="assistant")return;let ot=Ie.jobId??`${se}:${nt}`,rt=oe(f,"iteration",ot,Me),Ye=C.get(ot),Wn=Ie.cancelled?"cancelled":Ie.error?"failed":Ie.question?"question_asked":(Ie.resolutions?.length??0)>0?"completed":"no_change",Vn={...O(rt,m,[Pe,{kind:"message",id:Xe},...(h.get(ot)??[]).map(Ce=>({kind:"artifact",id:Ce}))]),createdAt:Be(Me),recordType:"iteration",threadIds:[ve],startedAt:Be(We?.timestamp,Me),completedAt:Be(Me),requestSummary:mr(We?.feedbackSummary,We?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Ie.question??Ie.error??Ie.responseText?.slice(0,1e3),outcome:Wn,execution:{provider:Ie.provider??Ye?.provider,model:Ie.model??Ye?.model,sessionId:Ie.sessionId??Ye?.sessionId},artifactIds:[Xe,...h.get(ot)??[]]};J(se,Vn),He.push({entityType:"iteration",entityId:rt});let Dt=Ie.resolutions??Ye?.resolutions??[];for(let[Ce,Oe]of Dt.entries()){if(Oe.status!=="resolved"||!Oe.summary?.trim())continue;let it=W.elementIdentifiers??[],gt=(it.length?it:[n]).map(sn=>({subjectId:sn===n?I:Z(sn,ke),role:"governed"})),at=oe(f,"proposal",`${ot}:${Oe.annotationId??"resolution"}:${Ce}`,Me),Kn={...O(at,m,[Pe,{kind:"iteration",id:rt}]),createdAt:Be(Me),recordType:"proposal",state:"pending",claim:Oe.summary,subjects:gt,subjectSemantics:gt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:mr(We?.feedbackSummary,We?.replyToQuestion,Oe.summary),iterationId:rt,inferredById:m}};J(se,Kn),He.push({entityType:"proposal",entityId:at}),e.push({severity:"warning",code:"acceptance_unresolved",source:se,message:`Proposal ${at} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Dt.some(Ce=>Ce.status==="resolved")||Ye?.gitDiff){let Ce=oe(f,"implementation",ot,Me),Oe={...O(Ce,m,[Pe,{kind:"iteration",id:rt}]),createdAt:Be(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[rt],coverageClaims:[],summary:Dt.map(it=>it.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};J(se,Oe),He.push({entityType:"implementation_attempt",entityId:Ce}),on+=1}Ot&&(Ot=void 0)});let rn=Ct.at(-1),Hn={...O(ve,y,[Pe]),createdAt:Be(ke),recordType:"thread",state:rn?.question?"open":"resolved",messageArtifactIds:$e,outcome:rn?.question?"question_unresolved":on?"implementation_only":"no_outcome",resultRefs:He};k.push(Hn),E.set(se,[ve,...E.get(se)??[]])}let re=Us(i);re&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${re} model values were not promoted because their accepted decision provenance is unresolved.`});let D={manifest:{formatVersion:1,projectId:l,createdAt:Be(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:A,tombstones:[]},V=ut(D),L=(o.proofCaseIds??qs).map(G=>({legacyId:G,threadFound:d.some(({key:W,value:se})=>(se.id??W)===G),decisionEnvelopeFound:C.has(G),recordIds:E.get(G)??[]}));return{bundle:D,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((G,W)=>G+(W.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:re,artifactsReferenced:A.length},imported:zs(k),unresolvedAcceptance:e.filter(G=>G.code==="acceptance_unresolved").length,deferredModelEntries:re,proofCases:L,issues:e,schemaIssues:V.issues}}}import{createHash as Gs}from"crypto";import{mkdir as fr,open as yo,readFile as vo,readdir as Hs,rename as Ws,unlink as Io}from"fs/promises";import{join as et}from"path";var Vs={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Sn(o){return Gs("sha256").update(JSON.stringify(o)).digest("hex")}function hr(o){return Sn(o)}function gr(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let r=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(r<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let i=o.records[r];if(i.projectId!==t.projectId||i.createdAt!==t.createdAt||i.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[r]=structuredClone(t)}for(let t of e.projectionUpdates){let r=o.records.find(i=>i.recordType===t.entityType&&i.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=n,o}function Ks(o,e,n){return gr(structuredClone(o),e,n)}async function ft(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await yo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
122
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ws(n,o)}catch(r){throw await Io(n).catch(()=>{}),r}}async function xn(o){return JSON.parse(await vo(o,"utf8"))}var kn=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=ut(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await fr(this.journalDir,{recursive:!0});try{throw await vo(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 vo(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=Sn(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await ft(this.checkpointPath,r),await ft(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await ft(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=Sn(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await ft(et(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await ft(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!bt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...i,hash:hr(i)},c=Ks(t.bundle,e,n.committedAt),d=ut(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let p=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await ft(et(this.journalDir,p),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await ft(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Vs,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await xn(this.manifestPath),n=await xn(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!==Sn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Hs(this.journalDir),r=t.filter(P=>P.endsWith(".tmp")),s=t.filter(P=>/^\d{12}-[0-9a-f-]+\.json$/i.test(P)).sort().filter(P=>Number(P.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,p=n.journalHash??null,x=new Set;for(let P of s){let b=await xn(et(this.journalDir,P)),{hash:f,...l}=b;if(f!==hr(l))throw new Error(`Journal hash mismatch: ${P}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${P}`);if(b.previousHash!==p)throw new Error(`Journal chain mismatch at ${P}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${P}`);if(x.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);gr(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 T=ut(c);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:p}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await fr(this.memoryDir,{recursive:!0});let n;try{n=await yo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await xn(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await Io(this.lockPath),n=await yo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Io(this.lockPath).catch(()=>{})}}};import{randomBytes as Qs}from"crypto";function ye(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Qs(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var Xs=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function yr(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Xs(),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(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(x));let T=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let k=o.records.find(A=>A.recordType==="subject"&&A.locators.some(g=>g.value===u&&g.status==="current"));k||(k={id:oe(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:oe(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},p.push(k)),T.push(k)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let k=o.records.find(A=>A.recordType==="subject"&&A.locators.some(g=>g.kind==="source_file"&&g.value===u&&g.status==="current"));k||(k={id:oe(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:oe(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},p.push(k)),T.push(k)}let P=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),b;if(P.length>0){b=oe(r,"live-observation",i,e.createdAt);let u={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:P.map(k=>k.claim.trim()).join(" "),captureContext:{subjectIds:T.map(k=>k.id),artifactIds:[]},resolvedByIds:[]};p.push(u)}let f=oe(r,"live-iteration",i,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=T.length>0?T:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(P.length>0&&I.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,k]of P.entries()){let A=oe(r,"live-proposal",`${i}:${u}`,e.completedAt),g=I.map(C=>({subjectId:C.id,role:"governed"})),E={id:A,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(E),y.push(A)}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)),A={id:oe(r,"live-implementation",i,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(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:f}]})),summary:m.map(g=>g.summary).join(" "),artifactIds:[]};p.push(A)}return{mutation:d,iterationId:f,proposalIds:y,observationId:b}}import{createHash as Ys}from"crypto";import{mkdir as Zs,open as ea,readFile as ta,rename as na,unlink as oa}from"fs/promises";import{join as vr}from"path";function Ir(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function wr(o){return Ys("sha256").update(JSON.stringify(o)).digest("hex")}async function ra(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await ea(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
123
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await na(n,o)}catch(r){throw await oa(n).catch(()=>{}),r}}function ia(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,p,x)=>{let T=d[p]??=[];T.includes(x)||T.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(T=>T.status==="current").map(T=>T.value)]){let T=Ir(x);T&&s(t,T,p.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let p of d.subjects)s(r,p.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let p of d.subjects)s(i,p.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:wr(c)}}function br(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Ir(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 Rn=class{constructor(e){this.indexDir=vr(e,".popmelt","memory","indexes"),this.indexPath=vr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await ta(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===wr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=ia(e,n);return await Zs(this.indexDir,{recursive:!0}),await ra(this.indexPath,t),t}};var Gt="popmelt:imprint",kr="popmelt:imprint-evidence",kt="popmelt:imprint-relation";function Pn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Gt)?.id}function wo(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 Tn(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 kn(e),this.indexStore=new Rn(e),this.manifestPath=St(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await zt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await mt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await mt({...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=St(this.projectRoot,".popmelt","memory","migrations"),n=St(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await zt(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await zt(St(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await xr(e,{recursive:!0}),await Sr(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let p=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(u=>u.id)),T=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(k=>k.kind==="external"&&k.uri===kt?[k.id]:[]))),P=new Map,b=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let k=b.find(A=>Pn(A)===u.id);P.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=P.get(u.id),A=b.find(h=>h.id===k),g=[],E=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 E){let M=oe(p,"imprint-evidence-record",h.id,Date.parse(h.createdAt));g.push(M),!x.has(M)&&(f.push({id:M,schemaVersion:1,projectId:p,createdAt:h.createdAt,participantId:c.id,sourceRefs:wo([{kind:"external",id:h.id,uri:kr},{kind:"external",id:u.id,uri:Gt},{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:kr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),m+=1)}let C={id:k,schemaVersion:1,projectId:p,createdAt:A?.createdAt??u.createdAt,participantId:A?.participantId??c.id,sourceRefs:wo([...A?.sourceRefs??[],{kind:"external",id:u.id,uri:Gt}]),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([...A?.evidenceIds??[],...g])],concreteBindings:Tn(t,u.id),supersededById:u.supersededBy?P.get(u.supersededBy):void 0,updatedAt:u.updatedAt};A?l.push(C):f.push(C)}for(let u of t.relations){let k=P.get(u.fromId),A=P.get(u.toId);!k||!A||T.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:kt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"advisory_explanation",entityId:A},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 xr(e,{recursive:!0}),await Sr(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),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Ft(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:pr(t.bundle,r),reviewSelection:Ft(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:bn(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 mt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=bn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(P=>P.recordType==="proposal"&&P.id===e.proposalId),r=n.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:ye(i),decisionId:ye(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:ye(i),replacementProposalId:ye(i),acceptanceEventId:ye(i),decisionId:ye(i),relationshipId:ye(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:ye(i),reason:e.reason}:{...c,action:"defer",eventId:ye(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(P=>P.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=bn(n.bundle,d);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(P=>P.message).join(" ")};let x=await this.store.commitReviewPlan(p.plan,{transactionId:ye(i),committedAt:s});await this.refreshIndex(x);let T=p.plan.resultRefs.find(P=>P.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:T,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=yr(n.bundle,e),r=oe(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await zt(St(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),i=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?r:i??r,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,T=[],P=[],b=[],f=t.bundle.records.filter(I=>I.recordType==="advisory_explanation"),l=new Map(f.flatMap(I=>{let u=Pn(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:Gt},k=l.get(I.explanationId),A=f.find(h=>h.id===k),g=n?.explanations.find(h=>h.id===I.explanationId),E={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:[]};T.push(E);let C={id:k,schemaVersion:1,projectId:x,createdAt:A?.createdAt??g?.createdAt??d,participantId:A?.participantId??s.id,sourceRefs:wo([...A?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??A?.kind??"pattern",state:g?.state??I.state,statement:g?.statement??I.statement,rationale:g?.rationale??A?.rationale??e.summary.detail,scope:structuredClone(g?.scope??A?.scope??{kind:"project",values:[]}),subjectIds:A?.subjectIds??[c.id],evidenceIds:[...new Set([...A?.evidenceIds??[],E.id])],concreteBindings:g?Tn(n,I.explanationId):A?.concreteBindings??[],supersededById:g?.supersededBy?l.get(g.supersededBy):A?.supersededById,updatedAt:g?.updatedAt??d};A?P.push(C):T.push(C),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:C.id},to:{entityType:"evidence",entityId:E.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===kt?[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:kt}],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:T,recordReplacements:P,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 zt(St(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"),i=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??t;if(!i)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 E=Pn(g);return E?[[E,g]]:[]})),x=new Map([...[...p].map(([g,E])=>[g,E.id]),...e.explanations.filter(g=>!p.has(g.id)).map(g=>[g.id,oe(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),T=[],P=[],b=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let E=p.get(g.id);if(!E){T.push({id:x.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:g.id,uri:Gt}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Tn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let C={...structuredClone(E),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:Tn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt},h=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});h(E)!==h(C)&&P.push(C)}for(let[g,E]of p)b.has(g)||E.state==="retired"||P.push({...structuredClone(E),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 E=g.sourceRefs.find(C=>C.kind==="external"&&C.uri===kt)?.id;return E?[[E,g]]:[]})),y=new Set(l.keys()),m=[];for(let g of e.relations){let E=x.get(g.fromId),C=x.get(g.toId);!E||!C||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:i.id,sourceRefs:[{kind:"external",id:g.id,uri:kt}],recordType:"relationship",relationshipType:g.type,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:C},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(!T.length&&!P.length&&!m.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let k=e.updatedAt,A=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(k));try{let g=await this.store.commit({records:T,recordReplacements:P,events:[],relationships:m,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:A,committedAt:k});return await this.refreshIndex(g),{status:"synced",relationships:m.length+u.length,explanations:T.length+P.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 r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&t.set(r.key,r);return[...t.values()]}async getImprintView(e=[]){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let t=await this.store.load(),r=t.bundle.records.filter(l=>l.recordType==="advisory_explanation"),i=new Map(r.map(l=>[l.id,l])),s=new Map(r.flatMap(l=>{let y=Pn(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]:[])),T=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=r.map(l=>{let y=l.evidenceIds.flatMap(u=>{let k=p.get(u);if(!k)return[];let A=k.sourceRefs.find(h=>h.kind==="thread")?.id,g=k.sourceRefs.find(h=>h.kind==="message")?.id,E=k.kind==="judgment"||k.kind==="user_feedback"||k.kind==="project_state"?k.kind:"other",C=d.get(k.participantId)??"unknown";return[{id:k.id,kind:E,summary:k.summary,createdAt:k.createdAt,participantKind:C,threadId:A,jobId:g}]}).sort((u,k)=>k.createdAt.localeCompare(u.createdAt)),m=t.bundle.relationships.flatMap(u=>{if(x.has(u.id))return[];if(!T.has(u.relationshipType))return[];let k=u.from.entityType==="advisory_explanation"&&u.from.entityId===l.id&&u.to.entityType==="advisory_explanation",A=u.to.entityType==="advisory_explanation"&&u.to.entityId===l.id&&u.from.entityType==="advisory_explanation";if(!k&&!A)return[];let g=k?u.to.entityId:u.from.entityId,E=i.get(g);return E?[{id:u.id,type:u.relationshipType,direction:k?"outgoing":"incoming",explanationId:E.id,statement:E.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)||P[l.state]-P[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 r=[...t.values()],i=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=i.filter(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:r.some(p=>p.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async 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"),r=n.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),c=ye(i),d=ye(i),p=ye(i),x=ye(i),T=ye(i),P=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"&&P.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:r.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:[r.id],decisionIds:[p],value:e.value},k={...f,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[p],entryIds:[x],coverage:[{decisionId:p,status:"projected"}]},A={...f,id:ye(i),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(i),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}.`})),E=b.map(h=>({...f,id:ye(i),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"}})),C=await this.store.commit({records:[y,I,u,k],events:[m,...g],relationships:[A,...E],artifacts:[],tombstones:[],projectionUpdates:b.map(h=>({entityType:"decision",entityId:h.id,fromState:"active",state:"superseded"}))},{transactionId:ye(i),committedAt:s});return await this.refreshIndex(C),{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(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return t?{proposalId:t.id,claim:t.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),t=n.bundle.records.find(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 r=n.bundle.records.filter(f=>f.recordType==="decision"&&e.decisionIds.includes(f.id)&&f.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active");if(!i)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(r.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:i.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)),T={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(f=>({kind:"record",id:f})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds: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"})},P=p.flatMap(f=>f.decisionIds.map(l=>({id:ye(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:T.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,T],events:[],relationships:P,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 mt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=br(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Pt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function xe(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Rt(o,e,n){let t=xe(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function bo(o){let e=Pt(o),n=Pt(e.authority),t=n.level,r=n.mode,i=Rt(t,"authority.level",["owner","delegate","contributor"]),s=Rt(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:xe(e.proposalId,"proposalId"),participantId:xe(e.participantId,"participantId"),occurredAt:xe(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:xe(e.eventId,"eventId"),decisionId:xe(e.decisionId,"decisionId"),kind:Rt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:xe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:xe(e.eventId,"eventId"),reason:xe(e.reason,"reason")};case"defer":{let d=Pt(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:xe(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=>xe(p,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(p=>Rt(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:xe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:xe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:xe(e.acceptanceEventId,"acceptanceEventId"),decisionId:xe(e.decisionId,"decisionId"),relationshipId:xe(e.relationshipId,"relationshipId"),claim:xe(e.claim,"claim"),kind:Rt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let p=Pt(d);return{subjectId:xe(p.subjectId,"subjectId"),role:Rt(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:xe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function xo(o){let e=Pt(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>xe(c,s))}},t=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:Pt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Mn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
124
|
+
`)}async function Rr(o,e,n,t){let r=Mn(e);if(!(!r&&n.length===0))try{let i=await o.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(i.actionPacket.decisions.length===0&&i.reviewSelection.packets.length===0)return;let s=new Map(i.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(i.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:i.source,...i.actionPacket.decisions.length>0?{acceptedTruth:{decisions:i.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:i.actionPacket.conflicts,truncated:i.actionPacket.completeness.status==="truncated"}}:{},packets:i.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(p=>p.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:i.reviewSelection.completeness.status==="truncated",estimatedTokens:i.actionPacket.budget.estimatedTokens+i.reviewSelection.completeness.estimatedTokens}}catch(i){t?.(i);return}}function Pr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((t,r)=>["",`${r+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((t,r)=>["",`${r+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
125
|
+
`)}function Tr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!r||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&i.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function jr(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 So(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],r=await sa(o),i=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,p,x,T,P,b,f,l,y,m,I,u,k,A=[],g=[],E=0,C=[];for(;E<r.length;){let h=r.indexOf(i,E);if(h===-1)break;let M=h+i.length;if(r.slice(h,h+s.length).equals(s))break;let O=M;r[O]===13&&r[O+1]===10&&(O+=2);let J=r.indexOf(`\r
|
|
182
126
|
\r
|
|
183
|
-
`,
|
|
127
|
+
`,O);if(J===-1)break;let z=r.slice(O,J).toString("utf-8"),K=J+4,Z=r.indexOf(i,K),re=Z!==-1?Z-2:r.length;C.push({headers:z,body:r.slice(K,re)}),E=Z!==-1?Z:r.length}for(let h of C){let M=h.headers.match(/name="([^"]+)"/);if(!M)continue;let O=M[1];if(O==="screenshot")c=h.body;else if(O==="feedback")d=h.body.toString("utf-8");else if(O==="color")p=h.body.toString("utf-8");else if(O==="provider")x=h.body.toString("utf-8");else if(O==="model")T=h.body.toString("utf-8");else if(O==="reasoningEffort")P=h.body.toString("utf-8");else if(O==="serviceTier")b=h.body.toString("utf-8");else if(O==="goal")f=h.body.toString("utf-8");else if(O==="pageUrl")l=h.body.toString("utf-8");else if(O==="viewport")y=h.body.toString("utf-8");else if(O==="planId")m=h.body.toString("utf-8");else if(O==="manifest")I=h.body.toString("utf-8");else if(O==="tasks")u=h.body.toString("utf-8");else if(O==="sourceId")k=h.body.toString("utf-8");else if(O.startsWith("screenshot-")){let J=O.slice(11);try{let z=decodeURIComponent(J);g.push({pathname:z,data:h.body})}catch{}}else if(O.startsWith("image-")){let J=O.split("-"),z=parseInt(J[J.length-1],10),K=J.slice(1,-1).join("-");K&&!isNaN(z)&&A.push({annotationId:K,index:z,data:h.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:p,provider:x,model:T,reasoningEffort:P,serviceTier:b,goal:f,pageUrl:l,viewport:y,planId:m,manifest:I,tasks:u,sourceId:k,pastedImages:A,pageScreenshots:g}}function sa(o){return new Promise((e,n)=>{let t=[];o.on("data",r=>t.push(r)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as aa}from"crypto";var ca=/<orientation>\s*([\s\S]*?)\s*<\/orientation>/gi,da=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),la=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 pa(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Mr(o,e,n,t=Date.now()){let r=pa(o);if(!r)return null;let i=typeof r.transition=="string"&&da.has(r.transition)?r.transition:null,s=Ht(r.focus);if(!i||!s)return null;let c=typeof r.evidencePosture=="string"&&la.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:aa(),jobId:e,sequence:n,timestamp:t,transition:i,snapshot:{focus:s,seeking:Ht(r.seeking),workingHypothesis:Ht(r.workingHypothesis),evidencePosture:c,update:Ht(r.update),nextObservation:Ht(r.nextObservation)},contextPolicy:"exclude"}}function ko(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function ua(o,e,n=0){let t=[],r=new Set,i=n;return{visibleText:o.replace(ca,(c,d)=>{try{let p=Mr(JSON.parse(d),e,i);if(!p)return"";let x=ko(p);if(r.has(x))return"";r.add(x),t.push(p),i++}catch{}return""}).replace(/\n{3,}/g,`
|
|
184
128
|
|
|
185
|
-
`).trim(),orientations:t}}function
|
|
129
|
+
`).trim(),orientations:t}}function ma(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 An=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){let r=this.buffer.indexOf("<orientation>");if(r<0){let c=ma(this.buffer);n+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}n+=this.buffer.slice(0,r);let i=this.buffer.indexOf("</orientation>",r+13);if(i<0){this.buffer=this.buffer.slice(r);break}let s=this.buffer.slice(r+13,i).trim();this.buffer=this.buffer.slice(i+14);try{let c=Mr(JSON.parse(s),this.jobId,this.sequence);if(!c)continue;let d=ko(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=ua(e,this.jobId,this.sequence),t=n.orientations.filter(r=>{let i=ko(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",{visibleText:n.visibleText,orientations:t}}},Ar=`## Public orientation updates
|
|
186
130
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
187
131
|
<orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
|
|
188
132
|
|
|
189
133
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
190
134
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
191
135
|
|
|
192
|
-
These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;function
|
|
136
|
+
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 Wt(o,e){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let t of o.annotations){let r=t.elements.map(c=>{let d=[c.selector];return c.reactComponent&&d.push(`(${c.reactComponent})`),d.join(" ")}).join(", "),i=t.instruction||"No text";n.push(`- id=${t.id} [${t.type}] ${i} \u2192 Elements: ${r||"none"}`);let s=e?.[t.id];if(s&&s.length>0)for(let c of s)n.push(` Attached image: use the Read tool to view ${c}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let t of o.styleModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"";for(let i of t.changes)n.push(`- ${t.selector} ${r}: ${i.property} ${i.original} \u2192 ${i.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let t of o.textModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=JSON.stringify(t.original),s=JSON.stringify(t.modified),c=t.textNodePath.length>0?` textNodePath=${t.textNodePath.join(".")}`:"";n.push(`- ${t.selector} ${r}${c}: ${i} \u2192 ${s}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let t of o.domModifications){let r=t.element?.reactComponent?`(${t.element.reactComponent})`:"",i=t.sourceElement?.reactComponent?` from ${t.sourceSelector} (${t.sourceElement.reactComponent})`:t.sourceSelector?` from ${t.sourceSelector}`:"",s=t.referenceSelector?` ${t.placement} ${t.referenceSelector}`:` at index ${t.targetIndex}`;n.push(`- ${t.operation}: ${t.selector} ${r}${i} \u2192 ${t.targetParentSelector}${s}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let t of o.spacingTokenChanges){n.push(`
|
|
193
137
|
### ${t.tokenName}: ${t.originalPx}px \u2192 ${t.newPx}px`);for(let r of t.affectedElements){let i=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${i}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${i}: ${r.property} ${t.originalPx}px \u2192 ${t.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let t=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[t.selector];t.reactComponent&&r.push(`(${t.reactComponent})`),t.context&&r.push(`in ${t.context}`),t.textContent&&r.push(`"${t.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
194
|
-
`)}function
|
|
195
|
-
`)}function
|
|
196
|
-
`)}function
|
|
197
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(
|
|
198
|
-
`));return
|
|
199
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Pc(n,o)}catch(r){throw await Tc(n).catch(()=>{}),r}}function Ac(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Ec(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=De(e):o.explanations.push(De(e))}function Fo(o,e){let n=De(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(De(t.explanation))}else if(t.op==="replace_explanation")Ec(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push(De(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(i=>i.id===t.evidence.id)||(r.evidence.push(De(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,De(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(s=>s.id===t.relation.fromId),i=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!r||!i)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push(De(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Mc(o,e){let n=[],t=De(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:De(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=t.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:De(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=t.explanations.find(c=>c.id===i);s&&n.unshift({op:"replace_explanation",explanation:De(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=t.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:De(i)})}t=Fo(t,[r])}return n}function ui(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 Vn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await li(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 kc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=Ac(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await li(Ot(this.journalDir,t[c]),"utf8")),{hash:l,...w}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==pi(w))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Fo(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(j=>j.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=Mc(t.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:De(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:pi(s)},d=Fo(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await an(Ot(this.journalDir,l),c);let w={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await an(this.graphPath,d),await an(this.manifestPath,w),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(ui));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>ui(w).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:r,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await an(this.graphPath,e.graph),await an(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var _c=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),$c=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Cc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Kn(o){return new Set(Cc(o).split(" ").filter(e=>e.length>2&&!$c.has(e)))}function Qn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Lo(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 st(o,e,n){return{id:Ve(),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 Ae(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function mi(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 fi(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function zo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let T=String(r.reason);if(!_c.has(T))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:T},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let i=r.summary,s=i?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:Ae(i?.title,120),detail:Ae(i?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(T=>typeof T=="string"&&!!T.trim()):[],l=[];for(let T of Array.isArray(r.mutations)?r.mutations:[]){if(!T||typeof T!="object")continue;let x=T;if(x.op==="add"&&["intention","principle","pattern"].includes(String(x.kind))){let m=Ae(x.statement),p=Ae(x.rationale);if(!m||!p)continue;l.push({op:"add",clientId:Ae(x.clientId,100)||void 0,kind:x.kind,statement:m,rationale:p,scope:mi(x.scope),rootReason:Ae(x.rootReason,300)||void 0})}else if(x.op==="revise"&&typeof x.explanationId=="string"){let m={op:"revise",explanationId:x.explanationId,statement:Ae(x.statement)||void 0,rationale:Ae(x.rationale)||void 0,scope:mi(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=Ae(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=Ae(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=Ae(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=Ae(x.modelPath,300);m&&l.push({op:"bind_concrete",explanationId:x.explanationId,modelPath:m,rationale:Ae(x.rationale)})}else x.op==="retire"&&typeof x.explanationId=="string"&&l.push({op:"retire",explanationId:x.explanationId,reason:Ae(x.reason)})}let w=r.grounding,j=w&&typeof w.explanationId=="string"&&Ae(w.question)?{explanationId:w.explanationId,question:Ae(w.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:j},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Uo(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(i=>` - Concrete terminal: ${i.modelPath} = ${JSON.stringify(i.value)}`)].join(`
|
|
200
|
-
`)),...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(`
|
|
201
|
-
`)}var cn=class{constructor(e,n){this.noopCounts=new Map;this.store=new Vn(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=Kn(e.text??""),t=Kn((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:i}=await this.store.load(),s=i.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let p=Kn([m.statement,m.rationale].join(" ")),y=Kn(m.scope.values.join(" ")),h=Qn(p,n),f=Qn(y,n),u=Qn(y,t),A=Qn(p,t),D=h+f*.2+u*.25+A*.1+(m.state==="grounded"?.08:0)+(r.has(m.id)?1:0),R=r.has(m.id)||(n.size?h>=.12||f>=.5:u>=.2||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)),w=new Set(i.relations.flatMap(m=>l.has(m.fromId)?[m.toId]:l.has(m.toId)?[m.fromId]:[])),j=new Set(i.explanations.flatMap(m=>w.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),T=i.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(i.relations.filter(y=>y.fromId===m.id&&y.type==="instantiates").map(y=>y.toId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:i.concrete.filter(y=>p.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||T.length<j.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(m=>l.has(m.fromId)&&l.has(m.toId)&&m.type!=="instantiates").map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),i=new Map(r.graph.explanations.map(I=>[I.id,I])),s=new Map,c=new Map,d=[],l=new Set,w=new Set(n.pendingGroundingExplanationIds??[]),j=new Set(e.mutations.flatMap(I=>I.op==="add"&&I.clientId?[I.clientId]:[])),T=I=>i.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)&&fi(n.concreteModel,I.modelPath).found&&x.add(I.explanationId);let m=r.graph.explanations.length===0;for(let I of e.mutations){if(I.op!=="add")continue;let b=!!(I.clientId&&x.has(I.clientId)),M=!!I.rootReason?.trim()||m;if(!b&&!M)continue;m&&(m=!1);let F=Ve();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:Lo(I.scope),state:H?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[st(n,"supports",e.summary.detail)]};i.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 b=p(I.explanationId),M=i.get(b);if(M?.state!=="grounded")continue;let F=Ve(),H={id:F,kind:M.kind,statement:I.statement??M.statement,rationale:I.rationale??M.rationale,scope:I.scope?Lo(I.scope):M.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[st(n,"supports",e.summary.detail)]};i.set(F,H),c.set(b,F),l.add(F),d.push({op:"add_explanation",explanation:H}),d.push({op:"add_relation",relation:{id:Ve(),type:"refines",fromId:F,toId:b,rationale:I.rationale??e.summary.detail,createdAt:t}})}let y=I=>{let b=p(I);return c.get(b)??b};for(let I of e.mutations){if(I.op==="add")continue;if(I.op==="bind_concrete"){let M=y(I.explanationId);if(!i.has(M))continue;let F=fi(n.concreteModel,I.modelPath);if(!F.found)continue;let H=r.graph.concrete.find(U=>U.modelPath===I.modelPath&&JSON.stringify(U.value)===JSON.stringify(F.value));H||(H={id:Ve(),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:Ve(),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(!i.has(M)||!i.has(F)||M===F)continue;d.push({op:"add_relation",relation:{id:Ve(),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(!i.has(M)||!i.has(F)||M===F)continue;d.push({op:"add_evidence",explanationId:M,evidence:st(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:Ve(),type:"contradicts",fromId:F,toId:M,rationale:I.reason,createdAt:t}}),l.add(M),l.add(F);continue}let b=y(I.explanationId);if(i.has(b))if(l.add(b),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:Lo(I.scope)}:{},...I.reopenGrounding?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:b,patch:M,updatedAt:t})}else I.op==="evidence"?(d.push({op:"add_evidence",explanationId:b,evidence:st(n,I.stance,I.summary)}),I.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:b,patch:{state:"challenged"},updatedAt:t})):I.op==="retire"&&(d.push({op:"add_evidence",explanationId:b,evidence:st(n,"challenges",I.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:b,patch:{state:"retired"},updatedAt:t}))}for(let I of e.appliedExplanationIds){let b=y(I),M=i.get(b);!M||M.state==="grounded"||M.state==="retired"||w.has(b)&&!l.has(b)||(l.has(b)||(l.add(b),d.push({op:"add_evidence",explanationId:b,evidence:{...st(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),M.state==="emerging"&&d.push({op:"revise_explanation",explanationId:b,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let h=Ve(),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 b=u.get(I);if(!b)return[];let M=!r.graph.explanations.some(H=>H.id===I),F=b.state==="challenged"||b.state==="retired";return[{explanationId:I,action:M?"added":F?"challenged":"revised",statement:b.statement,state:b.state}]}),D=e.grounding?y(e.grounding.explanationId):void 0,R=D?u.get(D):void 0,$=R?.state==="testing"&&!w.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,...$?{grounding:$}:{}}}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 w of l)await this.store.undo(w,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ve());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...st(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...st(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${i.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(w=>w.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...st(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${i.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:Ve(),committedAt:n,source:s,summary:d,mutations:c})}};function hi(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Xn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function qo(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 gi(o){let e=qo(Xn(o.origin));if(e)return e;let n=qo(Xn(o.referer));if(n)return n;let t=Xn(o["x-forwarded-host"]);if(!t)return null;let r=Xn(o["x-forwarded-proto"])==="https"?"https":"http";return qo(`${r}://${t}`)}function yi(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Yn}from"crypto";import{mkdir as dn,readFile as Rt,unlink as Jc,writeFile as Nt}from"fs/promises";import{dirname as Zn,extname as Nc,join as Oe}from"path";var Dc={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Oc(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function vi(o,e){let n=e??Oc(o);return{kind:n,...Dc[n]}}function Jt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function Ii(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Bc={version:1,threads:{}},wi=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],ln={version:2,updatedAt:0,files:{}};function Fc(o){return JSON.stringify(o,null,2)}function Lc(o){return Object.fromEntries(wi.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function zc(o){let e={...o};for(let n of wi)delete e[n];return e}function Bt(o){let e=o;if(o.error){let n=vi(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=Jt(e.result,!1),t=Jt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var eo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Oe(e,".popmelt");this.legacyFilePath=Oe(n,"threads.json"),this.threadsDir=Oe(n,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(n,"artifacts","thread-messages"),this.mediaDir=Oe(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Rt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let i=await this.readThread(Oe(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await Rt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Bt)}]))},this.index={...ln,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Bc,threads:{}},this.index={...ln,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>t.has(s)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Bt(n)):r.messages.push(Bt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Bt(c);Object.assign(c,d),delete c.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,i)=>i.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let s=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let h=y.imprintSummary?.grounding;if(h?.question&&!y.imprintSummary?.resolvedAction)return h.question},l=r.messages.findLastIndex(y=>!!d(y)),w=r.messages.findLastIndex(y=>y.role==="human"),j=l>w?d(r.messages[l]):void 0,T=r.messages.at(-1)?.role,x=Array.from(new Set(r.messages.slice(0,Math.max(0,w)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),m=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),p=c.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:m,hasError:p,lastMessageRole:T,pendingQuestion:j,acknowledgedJobIds:x,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await Rt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let c=await Rt(Oe(Zn(this.legacyFilePath),r.path),"utf8");Yn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return Bt({...i,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Lc(e),t=zc(e);if(Object.keys(n).length===0)return t;let r=Fc(n),i=Yn("sha256").update(r).digest("hex"),s=Oe("artifacts","thread-messages",`${i}.json`);await dn(this.artifactsDir,{recursive:!0});try{await Rt(Oe(Zn(this.legacyFilePath),s),"utf8")}catch{await Nt(Oe(Zn(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Zn(t)===this.mediaDir)return t;try{let r=await Rt(t),i=Yn("sha256").update(r).digest("hex"),s=Oe(this.mediaDir,`${i}${Nc(t)||".bin"}`);await dn(this.mediaDir,{recursive:!0});try{await Rt(s)}catch{await Nt(s,r)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await dn(this.threadsDir,{recursive:!0});let n=this.index??{...ln,files:{}},t=n.files[e.id]??`${Yn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Nt(Oe(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Nt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await dn(this.threadsDir,{recursive:!0}),this.index=this.index??{...ln,files:{}},await Nt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...ln,files:{}},t=n.files[e];t&&await Jc(Oe(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await dn(this.threadsDir,{recursive:!0}),await Nt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Uc,open as qc,readFile as Wc,rename as Gc,unlink as Hc}from"fs/promises";import{dirname as Vc,join as Kc}from"path";var bi={schemaVersion:1,theme:"auto",updatedAt:null};function xi(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Qc(o,e){await Uc(Vc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await qc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
202
|
-
`,"utf8"),await t.sync()}finally{await t.close()}await
|
|
203
|
-
`)}function
|
|
204
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let
|
|
205
|
-
`)}function
|
|
138
|
+
`)}function Er(o,e,n){let t=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!i&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let 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 T of s)if(typeof T=="object"&&T!==null&&"text"in T){let P=T,b=P.scope||"general";x.has(b)||x.set(b,[]),x.get(b).push(P.text)}for(let[T,P]of x){t.push(`**${T.charAt(0).toUpperCase()+T.slice(1)}**`);for(let b of P)t.push(`- ${b}`)}}else for(let x of s)typeof x=="string"&&t.push(`- ${x}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Novel Pattern Detection"),t.push("When you make a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), flag it:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you decided to do (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.push("Still do the work \u2014 just flag it so the developer can review and set policy.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let 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 T={...e,annotations:p,styleModifications:e.styleModifications},P=Wt(T,n?.imagePaths);P&&(t.push(""),t.push(P))}}else{let s=Wt(e,n?.imagePaths);s&&(t.push(""),t.push(s))}return t.push(""),t.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output a resolution block listing what you did for each annotation:"),t.push("<resolution>"),t.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),t.push("</resolution>"),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
139
|
+
`)}function _r(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function $r(o,e,n,t){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${c.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),c.feedbackSummary&&r.push(`Annotations: ${c.feedbackSummary}`))):c.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${c.question}"`)):(r.push(`### Round ${s} (assistant)`),c.responseText&&r.push(`Response: ${c.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t&&t.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of t)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output a resolution block listing what you did for each annotation:"),r.push("<resolution>"),r.push('[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]'),r.push("</resolution>"),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
|
|
140
|
+
`)}function fa(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 ha(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&&!fa(e[n]))return!1;return!0}function Cr(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(ha):[]}catch{return[]}}function Or(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let r=t;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}import{execFile as ga}from"child_process";import{readdir as ya,readFile as va,stat as Ia}from"fs/promises";import{homedir as Vt}from"os";import{join as Ke}from"path";var _n=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Dr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Dr()}],Kt=[{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"}],Qt={id:"",label:"Default",source:"cli"},wa=/^\s*-\s+"([^"]+)"/;function ba(o){let e=[],n=!1;for(let t of o.split(`
|
|
141
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let r=t.match(wa);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Ro(i),source:"cli"})}return $n([Qt,...e])}function xa(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,r)=>{let i=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(t=>{let r=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!r)return[];let i=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Ro(r),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:r,label:i,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function Dr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Sa(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return $n(e.map(n=>({id:n,label:Ro(n),source:"cli"})))}function Ro(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let i=t[1]==="sonnet"?"Sonn":Ta(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${i}${s}${t[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function Nr(o="copilot"){let e=await En(o,["help","config"]),n=ba(e);return n.length>1?n:[Qt]}async function Jr(o="codex"){let e=await En(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ke(Vt(),".codex");return Lr(Ke(t,"models_cache.json"))}),n=xa(e);return n.length>0?$n([...n,...Kt]):Kt}async function Br(o="claude"){let e=Ke(Vt(),".claude"),n=[Ke(Vt(),".claude","stats-cache.json"),Ke(Vt(),".claude","settings.json"),Ke(Vt(),".claude.json"),Ke(e,"cache","changelog.md")],[t,r,i]=await Promise.all([En(o,["--help"]).catch(()=>""),En(o,["--version"]).catch(()=>""),ka(e).catch(()=>[])]),s=Pa([...n,...i]),c=await Promise.all(s.map(p=>Lr(p).catch(()=>""))),d=Sa([t,r,...c].join(`
|
|
142
|
+
`));return $n([..._n,...d])}function En(o,e,n=5e3){return new Promise((t,r)=>{ga(o,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}t(s)})})}async function Lr(o){return va(o,"utf-8")}async function ka(o){let e=[Ke(o,"projects"),Ke(o,"telemetry")],n=[];for(let t of e)await Fr(t,n,4);return n.sort((t,r)=>r.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function Fr(o,e,n){if(n<0)return;let t;try{t=await ya(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async r=>{let i=Ke(o,r.name);if(r.isDirectory()){await Fr(i,e,n-1);return}if(!(!r.isFile()||!Ra(r.name)))try{let s=await Ia(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function Ra(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function $n(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 Pa(o){return[...new Set(o)]}function Ta(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Cn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let t=n>=0?n+1:0,r=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let r=this.bufferEvent(n,e);for(let i of this.listeners)i(r,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let r={...n,seq:t.nextSeq++};return t.events.push(r),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),r}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,n,t){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!i){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as Ge}from"crypto";import{createHash as ja}from"crypto";import{mkdir as Ma,open as Aa,readFile as qr,readdir as Ea,rename as _a,unlink as $a}from"fs/promises";import{dirname as Ca,join as Tt}from"path";function Ae(o){return structuredClone(o)}function Ur(o){return ja("sha256").update(JSON.stringify(o)).digest("hex")}async function Xt(o,e){await Ma(Ca(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Aa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
143
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await _a(n,o)}catch(r){throw await $a(n).catch(()=>{}),r}}function Oa(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Da(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Ae(e):o.explanations.push(Ae(e))}function Po(o,e){let n=Ae(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(Ae(t.explanation))}else if(t.op==="replace_explanation")Da(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push(Ae(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(i=>i.id===t.evidence.id)||(r.evidence.push(Ae(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,Ae(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(s=>s.id===t.relation.fromId),i=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!r||!i)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push(Ae(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function Na(o,e){let n=[],t=Ae(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:Ae(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=t.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:Ae(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=t.explanations.find(c=>c.id===i);s&&n.unshift({op:"replace_explanation",explanation:Ae(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=t.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:Ae(i)})}t=Po(t,[r])}return n}function zr(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 On=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Tt(e,".popmelt","imprint"),this.manifestPath=Tt(this.imprintDir,"manifest.json"),this.graphPath=Tt(this.imprintDir,"graph.json"),this.journalDir=Tt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await qr(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 Ea(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=Oa(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await qr(Tt(this.journalDir,t[c]),"utf8")),{hash:p,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||p!==Ur(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Po(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(T=>T.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=Na(t.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:Ae(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Ur(s)},d=Po(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let p=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Xt(Tt(this.journalDir,p),c);let x={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Xt(this.graphPath,d),await Xt(this.manifestPath,x),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(zr));if(i.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(x=>zr(x).some(T=>c.has(T)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Xt(this.graphPath,e.graph),await Xt(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Ja=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ba=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function La(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dn(o){return new Set(La(o).split(" ").filter(e=>e.length>2&&!Ba.has(e)))}function Nn(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 To(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:Ge(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Gr(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 Hr(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function jo(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let P=String(r.reason);if(!Ja.has(P))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:P},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let i=r.summary,s=i?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:je(i?.title,120),detail:je(i?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(P=>typeof P=="string"&&!!P.trim()):[],p=[];for(let P of Array.isArray(r.mutations)?r.mutations:[]){if(!P||typeof P!="object")continue;let b=P;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let f=je(b.statement),l=je(b.rationale);if(!f||!l)continue;p.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:f,rationale:l,scope:Gr(b.scope),rootReason:je(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let f={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:Gr(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=je(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=je(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=je(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=je(b.modelPath,300);f&&p.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:f,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&p.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let x=r.grounding,T=x&&typeof x.explanationId=="string"&&je(x.question)?{explanationId:x.explanationId,question:je(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:p,grounding:T},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Mo(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(i=>` - Concrete terminal: ${i.modelPath} = ${JSON.stringify(i.value)}`)].join(`
|
|
144
|
+
`)),...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(`
|
|
145
|
+
`)}var Yt=class{constructor(e,n){this.noopCounts=new Map;this.store=new On(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=Dn(e.text??""),t=Dn((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:i}=await this.store.load(),s=i.explanations.filter(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let l=Dn([f.statement,f.rationale].join(" ")),y=Dn(f.scope.values.join(" ")),m=Nn(l,n),I=Nn(y,n),u=Nn(y,t),k=Nn(l,t),A=m+I*.2+u*.25+k*.1+(f.state==="grounded"?.08:0)+(r.has(f.id)?1:0),g=r.has(f.id)||(n.size?m>=.12||I>=.5:u>=.2||k>=.2);return{item:f,score:A,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(i.relations.flatMap(f=>p.has(f.fromId)?[f.toId]:p.has(f.toId)?[f.fromId]:[])),T=new Set(i.explanations.flatMap(f=>x.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),P=i.explanations.filter(f=>T.has(f.id)&&!p.has(f.id)).sort((f,l)=>l.updatedAt.localeCompare(f.updatedAt)).slice(0,4),b=[...d,...P];for(let f of P)p.add(f.id);return{explanations:b.map(f=>{let l=new Set(i.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:i.concrete.filter(y=>l.has(y.id)).map(y=>({id:y.id,modelPath:y.modelPath,value:y.value}))}}),truncated:s.length>d.length||P.length<T.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.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(),r=await this.store.load(),i=new Map(r.graph.explanations.map(h=>[h.id,h])),s=new Map,c=new Map,d=[],p=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),T=new Set(e.mutations.flatMap(h=>h.op==="revise"&&e.mutations.some(M=>M.op==="evidence"&&M.stance==="challenges"&&M.explanationId===h.explanationId)?[h.explanationId]:[])),P=new Set(e.mutations.flatMap(h=>h.op==="add"&&h.clientId?[h.clientId]:[])),b=h=>i.has(h)||P.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)&&Hr(n.concreteModel,h.modelPath).found&&f.add(h.explanationId);let l=r.graph.explanations.length===0;for(let h of e.mutations){if(h.op!=="add")continue;let M=!!(h.clientId&&f.has(h.clientId)),O=!!h.rootReason?.trim()||l;if(!M&&!O)continue;l&&(l=!1);let J=Ge();h.clientId&&s.set(h.clientId,J);let z=h.clientId?e.appliedExplanationIds.includes(h.clientId):!1,K={id:J,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:To(h.scope),state:z?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};i.set(J,K),p.add(J),d.push({op:"add_explanation",explanation:K})}let y=h=>s.get(h)??h;for(let h of e.mutations){if(h.op!=="revise")continue;let M=y(h.explanationId),O=i.get(M);if(O?.state!=="grounded")continue;let J=Ge(),z={id:J,kind:O.kind,statement:h.statement??O.statement,rationale:h.rationale??O.rationale,scope:h.scope?To(h.scope):O.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};i.set(J,z),c.set(M,J),p.add(J),d.push({op:"add_explanation",explanation:z}),d.push({op:"add_relation",relation:{id:Ge(),type:"refines",fromId:J,toId:M,rationale:h.rationale??e.summary.detail,createdAt:t}})}let m=h=>{let M=y(h);return c.get(M)??M};for(let h of e.mutations){if(h.op==="add")continue;if(h.op==="bind_concrete"){let O=m(h.explanationId);if(!i.has(O))continue;let J=Hr(n.concreteModel,h.modelPath);if(!J.found)continue;let z=r.graph.concrete.find(K=>K.modelPath===h.modelPath&&JSON.stringify(K.value)===JSON.stringify(J.value));z||(z={id:Ge(),modelPath:h.modelPath,value:structuredClone(J.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:z})),d.push({op:"add_relation",relation:{id:Ge(),type:"instantiates",fromId:O,toId:z.id,rationale:h.rationale,createdAt:t}}),p.add(O);continue}if(h.op==="relation"){let O=m(h.fromId),J=m(h.toId);if(!i.has(O)||!i.has(J)||O===J)continue;d.push({op:"add_relation",relation:{id:Ge(),type:h.type,fromId:O,toId:J,rationale:h.rationale,createdAt:t}}),p.add(O),p.add(J);continue}if(h.op==="supersede"){let O=m(h.explanationId),J=m(h.replacementId);if(!i.has(O)||!i.has(J)||O===J)continue;d.push({op:"add_evidence",explanationId:O,evidence:tt(n,"challenges",h.reason)}),d.push({op:"revise_explanation",explanationId:O,patch:{state:"challenged",supersededBy:J},updatedAt:t}),d.push({op:"add_relation",relation:{id:Ge(),type:"supersedes",fromId:J,toId:O,rationale:h.reason,createdAt:t}}),p.add(O),p.add(J);continue}let M=m(h.explanationId);if(i.has(M))if(p.add(M),h.op==="revise"){if(c.has(y(h.explanationId)))continue;let O=i.get(M);if(!O||O.state!=="emerging"&&O.state!=="testing")continue;let J={...h.statement?{statement:h.statement}:{},...h.rationale?{rationale:h.rationale}:{},...h.scope?{scope:To(h.scope)}:{},...h.reopenGrounding||T.has(h.explanationId)?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:M,patch:J,updatedAt:t})}else if(h.op==="evidence"){if(h.stance==="challenges"&&T.has(h.explanationId))continue;d.push({op:"add_evidence",explanationId:M,evidence:tt(n,h.stance,h.summary)}),h.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged"},updatedAt:t})}else h.op==="retire"&&(d.push({op:"add_evidence",explanationId:M,evidence:tt(n,"challenges",h.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"retired"},updatedAt:t}))}for(let h of e.appliedExplanationIds){let M=m(h),O=i.get(M);!O||O.state==="grounded"||O.state==="retired"||x.has(M)&&!p.has(M)||(p.has(M)||(p.add(M),d.push({op:"add_evidence",explanationId:M,evidence:{...tt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),O.state==="emerging"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let I=Ge(),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])),A=[...p].flatMap(h=>{let M=k.get(h);if(!M)return[];let O=!r.graph.explanations.some(z=>z.id===h),J=M.state==="challenged"||M.state==="retired";return[{explanationId:h,action:O?"added":J?"challenged":"revised",statement:M.statement,state:M.state}]}),g=e.grounding?m(e.grounding.explanationId):void 0,E=g?k.get(g):void 0,C=E?.state==="testing"&&!x.has(E.id)?{explanationId:E.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:A,...C?{grounding:C}:{}}}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,Ge());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(p=>p.id===t);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...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: ${i.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: ${i.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:i.scope.kind,values:p},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.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: ${i.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:Ge(),committedAt:n,source:s,summary:d,mutations:c})}};function Wr(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Jn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Ao(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 Vr(o){let e=Ao(Jn(o.origin));if(e)return e;let n=Ao(Jn(o.referer));if(n)return n;let t=Jn(o["x-forwarded-host"]);if(!t)return null;let r=Jn(o["x-forwarded-proto"])==="https"?"https":"http";return Ao(`${r}://${t}`)}function Kr(o,e,n=5){let t=(d,p)=>(p.completedAt??p.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,p)=>p.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,p)=>(d[p.status]=(d[p.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Bn}from"crypto";import{mkdir as Zt,readFile as ht,unlink as Ua,writeFile as Mt}from"fs/promises";import{dirname as Ln,extname as za,join as Ee}from"path";var Fa={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 qa(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 Qr(o,e){let n=e??qa(o);return{kind:n,...Fa[n]}}function jt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function Xr(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Ga={version:1,threads:{}},Yr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],en={version:2,updatedAt:0,files:{}};function Ha(o){return JSON.stringify(o,null,2)}function Wa(o){return Object.fromEntries(Yr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Va(o){let e={...o};for(let n of Yr)delete e[n];return e}function At(o){let e=o;if(o.error){let n=Qr(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=jt(e.result,!1),t=jt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Fn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Ee(e,".popmelt");this.legacyFilePath=Ee(n,"threads.json"),this.threadsDir=Ee(n,"threads"),this.indexPath=Ee(this.threadsDir,"index.json"),this.artifactsDir=Ee(n,"artifacts","thread-messages"),this.mediaDir=Ee(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await ht(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let i=await this.readThread(Ee(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await ht(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(At)}]))},this.index={...en,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Ga,threads:{}},this.index={...en,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>t.has(s)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(At(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,At(n)):r.messages.push(At(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=At(c);Object.assign(c,d),delete c.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,i)=>i.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let s=r.messages.find(y=>y.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(y=>y.role==="assistant"),d=y=>{if(y.role!=="assistant")return;if(y.question)return y.question;let m=y.imprintSummary?.grounding;if(m?.question&&!y.imprintSummary?.resolvedAction)return m.question},p=r.messages.findLastIndex(y=>!!d(y)),x=r.messages.findLastIndex(y=>y.role==="human"),T=p>x?d(r.messages[p]):void 0,P=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,x)).filter(y=>y.role==="assistant"&&!!y.jobId).map(y=>y.jobId))),f=c.some(y=>!!y.responseText||!!y.question||!!y.result||!!y.memoryReviewCard||!!y.memoryReceipt),l=c.some(y=>!!y.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:f,hasError:l,lastMessageRole:P,pendingQuestion:T,acknowledgedJobIds:b,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await ht(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let c=await ht(Ee(Ln(this.legacyFilePath),r.path),"utf8");Bn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return At({...i,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Wa(e),t=Va(e);if(Object.keys(n).length===0)return t;let r=Ha(n),i=Bn("sha256").update(r).digest("hex"),s=Ee("artifacts","thread-messages",`${i}.json`);await Zt(this.artifactsDir,{recursive:!0});try{await ht(Ee(Ln(this.legacyFilePath),s),"utf8")}catch{await Mt(Ee(Ln(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Ln(t)===this.mediaDir)return t;try{let r=await ht(t),i=Bn("sha256").update(r).digest("hex"),s=Ee(this.mediaDir,`${i}${za(t)||".bin"}`);await Zt(this.mediaDir,{recursive:!0});try{await ht(s)}catch{await Mt(s,r)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await Zt(this.threadsDir,{recursive:!0});let n=this.index??{...en,files:{}},t=n.files[e.id]??`${Bn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Mt(Ee(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Mt(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 Zt(this.threadsDir,{recursive:!0}),this.index=this.index??{...en,files:{}},await Mt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...en,files:{}},t=n.files[e];t&&await Ua(Ee(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await Zt(this.threadsDir,{recursive:!0}),await Mt(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Ka,open as Qa,readFile as Xa,rename as Ya,unlink as Za}from"fs/promises";import{dirname as ec,join as tc}from"path";var Zr={schemaVersion:1,theme:"auto",updatedAt:null};function ei(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function nc(o,e){await Ka(ec(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Qa(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
146
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await Ya(n,o)}catch(t){throw await Za(n).catch(()=>{}),t}}var qn=class{constructor(e){this.path=tc(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Xa(this.path,"utf8")),n=ei(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Zr}}}catch{return{exists:!1,preferences:{...Zr}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await nc(this.path,n),n}};function ti(o){return ei(o)!==null}function ni(o){return rc(o).slice(0,12)}var oc=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function rc(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):ic(o),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let P=7;P>=0;P--)e.push(n/Math.pow(2,P*8)&255);let t=1779033703,r=3144134277,i=1013904242,s=2773480762,c=1359893119,d=2600822924,p=528734635,x=1541459225,T=new Array(64);for(let P=0;P<e.length;P+=64){for(let A=0;A<16;A++){let g=P+A*4;T[A]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let A=16;A<64;A++){let g=Qe(T[A-15],7)^Qe(T[A-15],18)^T[A-15]>>>3,E=Qe(T[A-2],17)^Qe(T[A-2],19)^T[A-2]>>>10;T[A]=T[A-16]+g+T[A-7]+E>>>0}let b=t,f=r,l=i,y=s,m=c,I=d,u=p,k=x;for(let A=0;A<64;A++){let g=Qe(m,6)^Qe(m,11)^Qe(m,25),E=m&I^~m&u,C=k+g+E+oc[A]+T[A]>>>0,h=Qe(b,2)^Qe(b,13)^Qe(b,22),M=b&f^b&l^f&l,O=h+M>>>0;k=u,u=I,I=m,m=y+C>>>0,y=l,l=f,f=b,b=C+O>>>0}t=t+b>>>0,r=r+f>>>0,i=i+l>>>0,s=s+y>>>0,c=c+m>>>0,d=d+I>>>0,p=p+u>>>0,x=x+k>>>0}return[t,r,i,s,c,d,p,x].map(P=>P.toString(16).padStart(8,"0")).join("")}function Qe(o,e){return o>>>e|o<<32-e}function ic(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 oi={name:"@popmelt.com/core",version:"0.8.8",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 tn=oi.version;var Ic=1111,wc=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],bc=1800*1e3,xc=3600*1e3,si=45e3,Sc=5e3,kc=1e4;function ai(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
147
|
+
`)}function nn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Rc(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 pi(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 Pc(o,e){let n=[];for(let t of o)if(t.type==="delta"){let r=t.text;if(!r)continue;let i=n[n.length-1];i&&i.kind==="text"?i.text+=r:n.push({kind:"text",text:r})}else if(t.type==="tool_use"){let r=t.tool||"",i=t.file??void 0,s=t.content??void 0,c=i?i.split("/").pop()??i:void 0,d;switch(r){case"Read":d=c?`Reading ${c}`:"Reading file";break;case"Edit":d=c?`Editing ${c}`:"Editing file";break;case"Write":d=c?`Writing ${c}`:"Writing file";break;case"Bash":d=s?s.split(`
|
|
148
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":d="Searching files";break;case"Grep":d="Searching code";break;case"WebFetch":d="Fetching page";break;case"WebSearch":d="Searching web";break;default:d=r?`Using ${r}`:"tool";break}let p=i??s??void 0,x=i?li(i)?i:yc(e,i):void 0,T=n[n.length-1];T&&T.kind==="tool_group"&&T.tool===r?T.items.push({label:d,detail:p,...x?{filePath:x}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:d,detail:p,...x?{filePath:x}:{}}]})}else t.type==="orientation"&&n.push({kind:"orientation",orientation:t.orientation});return n}function Tc(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(`
|
|
149
|
+
`)}function jc(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function ci(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...t,...n,...r].map(s=>jc(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Mc(o,e){let n=o.headers.origin;pi(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function $(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Le(o){let e=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>16384)throw new Error("Request body too large");e.push(i)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}function Ac(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Ec(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,r,i]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Gn(o,e){try{o.res.write(`event: ${e.type}
|
|
206
150
|
data: ${JSON.stringify(e)}
|
|
207
151
|
|
|
208
|
-
`)}catch{}}function
|
|
209
|
-
${t}
|
|
210
|
-
${r}`).digest("hex").slice(0,16)}catch{return}}function kd(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 _i(o,e,n){let t=e.dependencies??[];if(t.length===0&&(e.scenarios?.length??0)===0)return;let r=[["scenarios",e.scenarios??[]]];for(let i of[...t].sort((s,c)=>`${s.kind}:${s.value}`.localeCompare(`${c.kind}:${c.value}`)))if(i.kind==="model_path")r.push([i.kind,i.value,kd(n,i.value)]);else if(i.kind==="source_file"){let s=Di(o,i.value),d=s===o||s.startsWith(`${o}/`)?await Wo(s,"utf8").catch(()=>"[missing]"):"[outside-project]";r.push([i.kind,i.value,d])}else r.push([i.kind,i.value]);return Ci("sha256").update(JSON.stringify(r)).digest("hex").slice(0,16)}async function Ho(o={}){let e=new Date().toISOString(),n=o.port??ld,t=o.projectRoot??process.cwd(),r=await od(t).catch(()=>t),i=Ri(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Me(ad(),"popmelt-bridge"),d=o.maxTurns??40,l=o.maxBudgetUsd??1,w=[...o.allowedTools??pd],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:ro("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=Pi(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 ai(h.claude.path).catch(()=>Wn):Wn)})(),(async()=>{h.codex&&(h.codex.models=h.codex.available&&h.codex.path?await si(h.codex.path).catch(()=>rn):rn)})(),(async()=>{h.copilot&&(h.copilot.models=h.copilot.available&&h.copilot.path?await ii(h.copilot.path).catch(()=>[sn]):[sn])})()]);let[A,D,R]=await Promise.all([bo(r),xo(r),So(r,h.copilot?.path??T)]),$=await Rr(r);h.claude&&(h.claude.mcp=A),h.codex&&(h.codex.mcp=D),h.copilot&&(h.copilot.mcp=R),A.found&&A.name&&w.push(`mcp__${A.name}__*`),await td(c,{recursive:!0}),$i(c).catch(()=>{});let I=new Hn(1),b=new Tn,M=new En(ji),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()+hd,P=()=>{if(a!==H)return;if(M.size>0){ne();return}if(!(I.isRunning||I.depth>0||b.isRunning||b.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 eo(r),q=new Fn(r),ge=new cn(r,i),C=new to(r),Z=new wn(r),ue=new Sn(r),se=new Pn(r,{claudePath:j,provider:x,timeoutMs:m,loadProjectableDecisions:a=>q.getProjectableDecisions(a),onEvent:a=>{for(let g of Y)oo(g,a)}});q.beginAutomaticInitialization({writerVersion:pn}).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 Ee({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 Je=20,Ne=300*1e3,ke=[];function qe(){let a=Date.now()-Ne;for(;ke.length>0&&(ke[0].completedAt<a||ke.length>Je);)ke.shift()}let Ke=new Map;async function tt(a){if(a.status!=="applied")return[];let g={version:1,updatedAt:Date.now(),cases:await q.getJournalEvalCases()},P=ur(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=>Go(B)?Ti(r,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,ie)=>({id:`route-${ie+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 at(a){let g=a.modelPath.split(".").at(-1)?.replace(/[-_]+/g," ")??"Product constraint",P=mo(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 ft=null,Lt;I.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&oo(v,a)}),b.addListener((a,g,P)=>{for(let v of Y)(!P||!v.sourceId||v.sourceId===P)&&oo(v,a)}),b.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?Ir(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 tt(L)}}let S=vd(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,b.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),ke.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),qe();else{if(a.status="error",a.error=P.error??"Projection failed",a.threadId){let E=`Model projection failed.
|
|
152
|
+
`)}catch{}}function _t(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function _c(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 $c(o,e){return new Promise((n,t)=>{let r=s=>{o.removeListener("listening",i),t(s)},i=()=>{o.removeListener("error",r),n()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}async function Eo(o={}){let e=new Date().toISOString(),n=o.port??Ic,t=o.projectRoot??process.cwd(),r=await lc(t).catch(()=>t),i=ni(r),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??_e(fc(),"popmelt-bridge"),d=o.maxTurns??40,p=o.maxBudgetUsd??1,x=[...o.allowedTools??wc],T=o.claudePath??"claude",P=o.copilotPath??"copilot",b=o.provider??"claude",f=o.timeoutMs,l=o.restartMode??"embedded",y=n,m={},I={claude:T,codex:"codex",copilot:P};for(let[a,v]of Object.entries(I))try{let R=v.includes("/")?v:ac("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=ri(v,["--version"],{stdio:["ignore","ignore","ignore"]}),j=!1,S=N=>{j||(j=!0,R(N))},_=setTimeout(()=>{w.kill("SIGTERM"),S(!0)},5e3);w.on("error",()=>{clearTimeout(_),S(!1)}),w.on("close",N=>{clearTimeout(_),S(N===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Br(m.claude.path).catch(()=>_n):_n)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Jr(m.codex.path).catch(()=>Kt):Kt)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await Nr(m.copilot.path).catch(()=>[Qt]):[Qt])})()]);let[k,A,g]=await Promise.all([ao(r),co(r),lo(r,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=k),m.codex&&(m.codex.mcp=A),m.copilot&&(m.copilot.mcp=g),k.found&&k.name&&x.push(`mcp__${k.name}__*`),await cc(c,{recursive:!0}),di(c).catch(()=>{});let E=new Cn(1),C=new gn,h=new vn(si),M=null,O=0,J=!1,z=()=>{O+=1,J=!1,M&&clearTimeout(M),M=null},K=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},Z=()=>{if(l!=="detached"||h.size>0||J)return;J=!0;let a=++O,v=Date.now()+kc,R=()=>{if(a!==O)return;if(h.size>0){z();return}if(!(E.isRunning||E.depth>0||C.isRunning||C.depth>0)||Date.now()>=v){J=!1,M=setTimeout(K,50),M.unref?.();return}M=setTimeout(R,250),M.unref?.()};R()},re=new Set,D=new Fn(r),V=new jn(r),ge=new Yt(r,i),L=new qn(r),G=new un(r),W=new hn(r,{claudePath:T,provider:b,timeoutMs:f,loadProjectableDecisions:a=>V.getProjectableDecisions(a),onEvent:a=>{for(let v of re)Gn(v,a)}});V.beginAutomaticInitialization({writerVersion:tn}).then(async a=>{a.state==="ready"?(await V.migrateImprintSnapshot(),await V.syncImprintGraph(),await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),b!=="copilot"&&(await W.getUnprojectedPatternDecisions()).length>0&&await Ye({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,ke=300*1e3,ve=[];function Pe(){let a=Date.now()-ke;for(;ve.length>0&&(ve[0].completedAt<a||ve.length>se);)ve.shift()}let $e=new Map,He=null,Ct;E.addListener((a,v,R)=>{for(let w of re)(!R||!w.sourceId||w.sourceId===R)&&Gn(w,a)}),C.addListener((a,v,R)=>{for(let w of re)(!R||!w.sourceId||w.sourceId===R)&&Gn(w,a)}),C.setProcessor(async a=>{let v=a.provider??b;try{let R=await W.run({provider:v,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let w=await W.loadRuns(),j=R.runId?w.runs.find(_=>_.id===R.runId):void 0;if(R.success&&R.proposalId){let _=await W.findModelProposal(R.proposalId),N=await W.loadModel(),B=_?Xo(_,N):null;if(_&&B){let H=_.decisionIds.map(F=>({decisionId:F,status:"projected"}));await V.applyModelProjection({runId:_.runId??_.id,presentationJobId:_.presentationJobId,decisionIds:_.decisionIds,changes:B.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:H}),await W.applySelectedModelProposal(_.id,B.map(F=>({path:F.path,value:F.value})),B.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=Tc(R,j);if(a.threadId&&(await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:v})||await D.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,C.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),ve.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Pe();else{if(a.status="error",a.error=R.error??"Projection failed",a.threadId){let _=`Model projection failed.
|
|
211
153
|
|
|
212
|
-
${a.error}`;await
|
|
154
|
+
${a.error}`;await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:_,error:a.error,model:a.model,provider:v})||await D.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:_,error:a.error,model:a.model,provider:v})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),ve.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Pe()}}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.
|
|
213
155
|
|
|
214
|
-
${a.error}`;await
|
|
156
|
+
${a.error}`;await D.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})||await D.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:w,error:a.error,model:a.model,provider:v})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),ve.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Pe()}}),E.setProcessor(async a=>{let v=a,R=v._replyPrompt,w=v._replyText,j=v._replyImagePaths,S=a.provider??b,_=!!(a.surfacedProposalIds?.length&&R),N=!_&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&w!==void 0&&await D.updateMessage(a.threadId,a.id,{queued:!1});let B;if(a.threadId){let q=await D.getThread(a.threadId);if(q){for(let ie=q.messages.length-1;ie>=0;ie--)if(q.messages[ie].sessionId){B=q.messages[ie].sessionId;break}}}_&&(B=void 0);let H;if(B&&R){if(H=w??R,j&&j.length>0){H+=`
|
|
215
157
|
|
|
216
|
-
The developer attached reference images with their reply:`;for(let
|
|
217
|
-
Attached image: use the Read tool to view the image at: ${
|
|
158
|
+
The developer attached reference images with their reply:`;for(let q of j)H+=`
|
|
159
|
+
Attached image: use the Read tool to view the image at: ${q}`}a.kind==="synthesize"?H+=`
|
|
218
160
|
|
|
219
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
161
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:H+=`
|
|
220
162
|
|
|
221
|
-
After completing work, output a <resolution> block with declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block.`}else if(
|
|
163
|
+
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(B)H=Wt(a.feedback,a.imagePaths)+`
|
|
222
164
|
|
|
223
165
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
224
166
|
|
|
225
167
|
After completing work, output a <resolution> block with declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
226
168
|
|
|
227
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let
|
|
169
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let q=!R&&a.threadId?await D.getThreadHistory(a.threadId):void 0,ie=R?null:await W.loadModel();H=R??Er(a.screenshotPath,a.feedback,{threadHistory:q&&q.length>0?q:void 0,provider:S,imagePaths:a.imagePaths,designModel:ie??void 0,screenshotPaths:a.screenshotPaths})}H+=Pr(a.memoryReview),N&&(H+=Mo(a.imprintContext)),H+=`
|
|
228
170
|
|
|
229
|
-
${Yr}`;let O=xd(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 Un(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:ie,result:ce}=S==="codex"?In(a.id,{prompt:L,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:z,model:a.model,sandboxMode:E?"read-only":void 0,configOverrides:gn(a.agentSettings),onEvent:G}):S==="copilot"?dr(a.id,{prompt:L,projectRoot:r,resumeSessionId:z,model:a.model,timeoutMs:m,copilotPath:h.copilot?.path??T,onEvent:G}):yn(a.id,{prompt:L,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:E?["Read"]:w,claudePath:j,resumeSessionId:z,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:m,onEvent:G});I.setActiveProcess(a.id,ie);let te=await ce,xe=Q.finalize(te.text),we=xe.visibleText,Ie=B?zo(we):{visibleText:we,draft:void 0,error:void 0},K=Ie.visibleText;for(let de of xe.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=ei(we),pe=ni(we);if(pe.length>0&&a.annotationIds&&a.annotationIds.length>0){let W=new Set(a.annotationIds);pe.every(Qe=>W.has(Qe.annotationId))||(pe=pe.map((Qe,Xe)=>({...Qe,annotationId:a.annotationIds[Xe%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),ot=Ce?yd(Ce.events,r):void 0,Pe,ee=Qr(we),he=Kr(we);if(he)if(!(a.memoryReview?.packets.some(re=>re.proposalId===he.proposalId)||a.surfacedProposalIds?.includes(he.proposalId)))Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Pe=await q.commitConversationalReview(he)}catch(re){Pe={status:"rejected",action:he.action,proposalId:he.proposalId,message:re instanceof Error?re.message:String(re)}}let Te=[...(te.fileEdits??[]).map(W=>W.file_path),...(te.editEvents??[]).flatMap(W=>W.filePath?[W.filePath]:[])],Se,yt=a.imprintContext?.pendingGroundingExplanationIds??[];if(Ie.draft?.decision==="none"&&ge.recordNoop(Ie.draft.reason),a.threadId&&Ie.draft?.decision==="mutate"&&!he&&!ee)try{Se=await ge.capture(Ie.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:yt}),Se&&await q.recordImprintEvidence({summary:Se,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 Ie.error&&console.warn(`${O} Ignored invalid imprint block: ${Ie.error}`);let We=Se?.transactionId;if(a.threadId&&Se&&!Se.grounding){let W=await V.getThread(a.threadId),re=new Set(Se.changes.map(Xe=>Xe.explanationId)),Qe=W?gd(W.messages,re):void 0;if(Qe?.imprintSummary){let Xe=Qe.imprintSummary;await V.updateAssistantMessage(a.threadId,Qe.jobId,{imprintSummary:{...Xe,detail:Se.detail,changes:Se.changes,additionalObservationCount:(Xe.additionalObservationCount??0)+1,coalescedTransactionIds:[...Xe.coalescedTransactionIds??[],Se.transactionId]}}),Se=void 0}}let qt=Ii({question:de,resolutions:pe,changedFiles:Te,decisionRequired:!!ee,imprintTransactionId:We,groundingRequired:!!Se?.grounding}),X=ot?.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&&ot&&ot.length>0?ot:void 0,turn:{phase:"complete",orientation:X,result:qt},result:qt,memoryReviewCard:ee??void 0,memoryReceipt:Pe,imprintSummary:Se,model:a.model,provider:S})}if(a.threadId&&!he&&!a.surfacedProposalIds?.length&&a.kind!=="run_eval"&&a.kind!=="synthesize_evals"&&a.kind!=="project_model"){let W=a.feedback.annotations.flatMap(re=>re.linkedSelector?[re.pathname?`${re.pathname}:${re.linkedSelector}`:re.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Ln(a.feedback)||"[request unavailable]"),responseSummary:de??K,outcome:de?"question_asked":pe.some(re=>re.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:te.sessionId},subjectHints:W,filePaths:[...(te.fileEdits??[]).map(re=>re.file_path),...(te.editEvents??[]).flatMap(re=>re.filePath?[re.filePath]:[])].map(re=>Go(re)?Ti(r,re):re),resolutions:pe.map(re=>({status:re.status,summary:re.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(re=>re.id)})}catch(re){console.warn(`${O} Canonical memory capture failed; iteration remains available in legacy history:`,re instanceof Error?re.message:String(re))}}if(Pe?.status==="committed"&&Pe.decisionId&&S!=="copilot"&&await Ee({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Pe.decisionId}`}),a.kind==="run_eval"&&K&&a.evalId&&a.evalRunId){let W=await q.findJournalEvalCase(a.evalId),re=a._evalRunScope;if(W&&re){let Qe=pr(we,W.assertions),Xe=Date.now(),Qi={id:a.evalRunId,evalId:a.evalId,threadId:a.threadId,createdAt:a.createdAt,completedAt:Xe,durationMs:Xe-a.createdAt,scope:re,provider:S,model:a.model,screenshotPath:a._evalScreenshotPath,codeFingerprint:Mi(r),rawResponse:we,scopeFingerprint:a._evalScopeFingerprint,...Qe};await q.recordEvalVerification(W,Qi),console.log(`${O} Eval run: ${W.title} \u2192 ${Qe.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=oi(we);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:qt},a.id,a.sourceId),ke.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),ke.push({id:a.id,status:"error",completedAt:Date.now(),error:te.error,threadId:a.threadId,annotationIds:a.annotationIds});qe()});let zt=sd(async(a,g)=>{if(wd(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=bd(a,k);if(E&&E!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:E,projectName:no(r)});return}if(a.headers.origin){if(!Oi(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(E!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:E,projectName:no(r)});return}}try{if(a.method==="POST"&&S==="/send")await _e(a,g);else if(a.method==="GET"&&S==="/events")dt(a,g);else if(a.method==="GET"&&S==="/status")await lt(a,g,E);else if(a.method==="GET"&&S==="/ui-preferences")await io(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await so(a,g);else if(a.method==="PATCH"&&S==="/config")await ht(a,g);else if(a.method==="POST"&&S==="/leases"){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await Ue(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:ji})}catch{_(g,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(p!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!J){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=M.heartbeat(J);if(!B){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:B})}else{let B=M.release(J);_(g,B.found?200:404,{ok:B.found}),B.becameEmpty&&ye()}}else if(a.method==="POST"&&S==="/shutdown"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0}),setTimeout(oe,100)}else if(a.method==="POST"&&S==="/restart"){if(p!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:p});return}_(g,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of Y)try{J.res.end()}catch{}zt.close(()=>{Pi(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(g,200,{providers:h});else if(S.startsWith("/imprint/"))await ct(a,g,S);else if(S.startsWith("/memory/"))await be(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await Ni(a,g);else if(a.method==="POST"&&S==="/reply")await nt(a,g);else if(a.method==="POST"&&S==="/cancel")Ut(a,g);else if(a.method==="POST"&&S==="/materialize")_(g,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(g,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let J=await se.loadRuns();_(g,200,J)}else if(a.method==="GET"&&S==="/projection/proposals"){let J=await se.loadModelProposals();_(g,200,J)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let J=S.slice(22,-15);await pt(J,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let J=S.slice(22,-6);await Be(J,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let J=S.slice(22,-8);await Pt(J,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await Bi(a,g);else if(a.method==="DELETE"&&S==="/model/component")await Fi(a,g);else if(a.method==="PATCH"&&S==="/model/token")await Li(a,g);else if(a.method==="DELETE"&&S==="/model/token")await zi(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 _i(r,O,J);return O.verificationState==="passing"&&(!O.verifiedScopeFingerprint||!N||O.verifiedScopeFingerprint!==N)?{...O,verificationState:"stale"}:O})),z=Mi(r),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 ao(J,a,g)}else if(a.method==="PATCH"&&S.startsWith("/evals/"))await fn(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 Gi(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 Hi(J,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let J=S.slice(8);await Vi(J,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Ui(a,g):a.method==="GET"&&S==="/canvas/manifest"?await qi(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Wi(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 be(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=>mn(S.messages)))];_(g,200,await q.getImprintView(k));return}if(a.method==="POST"&&P==="/memory/constraints"){let v=await Ue(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(ie=>ie.name===k||ie.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 Ue(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-${mt().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:kt(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 ie=kt(typeof v.provider=="string"?v.provider:void 0);N.status==="committed"&&N.decisionId&&ie!=="copilot"&&await Ee({provider:ie,model:typeof v.model=="string"?v.model:void 0,agentSettings:vt(v),threadId: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 Ue(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 Ue(a),k=await q.review(Jo(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 Ue(a),k=await q.contextualize(Jo(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 Ue(a),k=await q.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:pn});_(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 Ue(a),k=await q.planReview(Oo(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 Ue(a),k=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await q.commitReview(Oo(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 Ue(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 ct(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=>mn(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 Ue(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(ie=>ie.role==="assistant"&&ie.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-${mt().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(ie=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ie));let N=Jt(z.result,!!z.question),Q=z.turn?{...z.turn,result:Jt(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 _e(a,g){let{screenshot:P,feedback:v,color:k,provider:S,model:E,reasoningEffort:J,serviceTier:B,sourceId:z,pastedImages:L,pageScreenshots:O}=await zn(a),N;try{N=JSON.parse(v)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let Q=mt().slice(0,8),G={};if(O.length>0)for(let ee of O){let he=encodeURIComponent(ee.pathname),Te=Me(c,`screenshot-${Q}-${he}.webp`);await un(Te,ee.data),G[ee.pathname]=Te}let ie=Me(c,`screenshot-${Q}.webp`);await un(ie,P);let ce={};if(L.length>0)for(let ee of L){let he=Me(c,`pasted-${Q}-${ee.annotationId}-${ee.index}.webp`);await un(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),xe;if(te.length>0){let ee=await V.findContinuationThread(te);ee?(xe=ee.id,await V.addElementIdentifiers(xe,te)):xe=(await V.createThread(Q,te)).id}else xe=(await V.createThread(Q,[])).id;let we=N.annotations.map(ee=>ee.id),Ie=Object.keys(G).length>0,K=await Hr(q,N,te,ee=>console.warn(`[\u22B9 ${y}:${Q}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),de=await ge.contextualize({text:Ln(N),subjectHints:[...te,...N.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(he=>!!he))],pendingGroundingExplanationIds:mn((await V.getThread(xe))?.messages??[])}).catch(ee=>{console.warn(`[\u22B9 ${y}:${Q}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),pe={id:Q,status:"queued",screenshotPath:ie,feedback:N,createdAt:Date.now(),color:k,threadId:xe,annotationIds:we,provider:kt(S),model:E||void 0,agentSettings:vt({reasoningEffort:J,serviceTier:B}),...Object.keys(ce).length>0?{imagePaths:ce}:{},sourceId:z||void 0,...Ie?{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 Te=he.pathname||"(unknown)";ee.has(Te)||ee.set(Te,[]),ee.get(Te).push(he.instruction||Ei({...N,annotations:[he]}))}Ce=[...ee.entries()].map(([he,Te])=>`\`${he}\`
|
|
230
|
-
${
|
|
171
|
+
${Ar}`;let F=Ec(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})`:""}${B?` (resuming: ${B.slice(0,8)})`:""}`);let U=new An(a.id),ne=(q,ie)=>{if(q.type==="delta"&&"text"in q){let Ne=U.push(q.text);Ne.visibleText&&(E.accumulateText(ie,"response",Ne.visibleText),E.broadcast({...q,text:Ne.visibleText},ie,a.sourceId));for(let st of Ne.orientations)E.broadcast({type:"orientation",jobId:ie,orientation:st},ie,a.sourceId);return}else q.type==="thinking"&&"text"in q&&E.accumulateText(ie,"thinking",q.text);E.broadcast(q,ie,a.sourceId)},{process:de,result:le}=S==="codex"?pn(a.id,{prompt:H,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:B,model:a.model,sandboxMode:_?"read-only":void 0,configOverrides:cn(a.agentSettings),onEvent:ne}):S==="copilot"?Wo(a.id,{prompt:H,projectRoot:r,resumeSessionId:B,model:a.model,timeoutMs:f,copilotPath:m.copilot?.path??P,onEvent:ne}):dn(a.id,{prompt:H,projectRoot:r,maxTurns:d,maxBudgetUsd:p,allowedTools:_?["Read"]:x,claudePath:T,resumeSessionId:B,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:ne});E.setActiveProcess(a.id,de);let Y=await le,be=U.finalize(Y.text),he=be.visibleText,we=N?jo(he):{visibleText:he,draft:void 0,error:void 0},Fe=we.visibleText;for(let q of be.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:q},a.id,a.sourceId);if(a.result=Fe,Y.success){console.log(`${F} Iteration complete`),Y.fileEdits&&Y.fileEdits.length>0&&console.log(`${F} Captured ${Y.fileEdits.length} file edit(s): ${Y.fileEdits.map(te=>`${te.tool} ${te.file_path}`).join(", ")}`),Y.editEvents&&Y.editEvents.length>0&&console.log(`${F} Captured ${Y.editEvents.length} edit event(s): ${Y.editEvents.map(te=>`${te.operation} ${te.filePath}`).join(", ")}`),a.status="done";let q=_r(he),ie=Cr(he);if(ie.length>0&&a.annotationIds&&a.annotationIds.length>0){let te=new Set(a.annotationIds);ie.every(ct=>te.has(ct.annotationId))||(ie=ie.map((ct,dt)=>({...ct,annotationId:a.annotationIds[dt%a.annotationIds.length]})))}let Ne=Y.fileEdits&&Y.fileEdits.length>0?Y.fileEdits.map(te=>`${te.tool} ${te.file_path.split("/").pop()}`):Y.toolsUsed,st=E.getBufferedEvents(a.id),De=st?Pc(st.events,r):void 0,Te,Ze=jr(he),Q=Tr(he);if(Q)if(!(a.memoryReview?.packets.some(ae=>ae.proposalId===Q.proposalId)||a.surfacedProposalIds?.includes(Q.proposalId)))Te={status:"rejected",action:Q.action,proposalId:Q.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Te=await V.commitConversationalReview(Q)}catch(ae){Te={status:"rejected",action:Q.action,proposalId:Q.proposalId,message:ae instanceof Error?ae.message:String(ae)}}let Se=[...(Y.fileEdits??[]).map(te=>te.file_path),...(Y.editEvents??[]).flatMap(te=>te.filePath?[te.filePath]:[])],pe,qe=a.imprintContext?.pendingGroundingExplanationIds??[];if(we.draft?.decision==="none"&&ge.recordNoop(we.draft.reason),a.threadId&&we.draft?.decision==="mutate"&&!Q&&!Ze)try{pe=await ge.capture(we.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await W.loadModel(),pendingGroundingExplanationIds:qe}),pe&&await V.recordImprintEvidence({summary:pe,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 we.error&&console.warn(`${F} Ignored invalid imprint block: ${we.error}`);let Qn=pe?.transactionId;if(a.threadId&&pe&&!pe.grounding){let te=await D.getThread(a.threadId),ae=new Set(pe.changes.map(dt=>dt.explanationId)),ct=te?Rc(te.messages,ae):void 0;if(ct?.imprintSummary){let dt=ct.imprintSummary;await D.updateAssistantMessage(a.threadId,ct.jobId,{imprintSummary:{...dt,detail:pe.detail,changes:pe.changes,additionalObservationCount:(dt.additionalObservationCount??0)+1,coalescedTransactionIds:[...dt.coalescedTransactionIds??[],pe.transactionId]}}),pe=void 0}}let X=Xr({question:q,resolutions:ie,changedFiles:Se,decisionRequired:!!Ze,imprintTransactionId:Qn,groundingRequired:!!pe?.grounding}),ue=De?.flatMap(te=>te.kind==="orientation"?[te.orientation]:[])??[];if(a.threadId){let te=_?Ze?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Fe;await D.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:te,resolutions:!_&&ie.length>0?ie:void 0,question:_?void 0:q??void 0,sessionId:Y.sessionId,toolsUsed:_?void 0:Ne,editEvents:!_&&Y.editEvents&&Y.editEvents.length>0?Y.editEvents:void 0,segments:!_&&De&&De.length>0?De:void 0,turn:{phase:"complete",orientation:ue,result:X},result:X,memoryReviewCard:Ze??void 0,memoryReceipt:Te,imprintSummary:pe,model:a.model,provider:S})}if(a.threadId&&!Q&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let te=a.feedback.annotations.flatMap(ae=>ae.linkedSelector?[ae.pathname?`${ae.pathname}:${ae.linkedSelector}`:ae.linkedSelector]:[]);try{await V.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:w??(Mn(a.feedback)||"[request unavailable]"),responseSummary:q??Fe,outcome:q?"question_asked":ie.some(ae=>ae.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:Y.sessionId},subjectHints:te,filePaths:[...(Y.fileEdits??[]).map(ae=>ae.file_path),...(Y.editEvents??[]).flatMap(ae=>ae.filePath?[ae.filePath]:[])].map(ae=>li(ae)?gc(r,ae):ae),resolutions:ie.map(ae=>({status:ae.status,summary:ae.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ae=>ae.id)})}catch(ae){console.warn(`${F} Canonical memory capture failed; iteration remains available in legacy history:`,ae instanceof Error?ae.message:String(ae))}}Te?.status==="committed"&&Te.decisionId&&S!=="copilot"&&await Ye({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Te.decisionId}`}),q&&(console.log(`${F} \u{1F4AC} Question detected: "${q.slice(0,120)}" \u2192 broadcasting to ${re.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),E.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:q,annotationIds:a.annotationIds},a.id,a.sourceId));let me=Or(he);me.length>0&&(console.log(`${F} Novel pattern(s): ${me.map(te=>`${te.category}/${te.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:me,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ie.length>0?ie:void 0,responseText:Fe,threadId:a.threadId,annotationIds:a.annotationIds,result:X},a.id,a.sourceId),ve.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${F} Error: ${Y.error}`),a.status="error",a.error=Y.error,a.threadId&&await D.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:Y.error||"Unknown error",model:a.model,provider:S}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:Y.error||"Unknown error",provider:S,model:a.model,recoverable:Y.recoverableError,code:Y.errorCode},a.id,a.sourceId),ve.push({id:a.id,status:"error",completedAt:Date.now(),error:Y.error,threadId:a.threadId,annotationIds:a.annotationIds});Pe()});let We=mc(async(a,v)=>{if(Mc(a,v),a.method==="OPTIONS"){v.writeHead(204),v.end();return}let R=a.url||"/",w=R.split("?")[0],j=new URL(R,`http://127.0.0.1:${y}`),S=j.pathname,_=Ac(a,j);if(_&&_!==i){$(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:_,projectName:zn(r)});return}if(a.headers.origin){if(!pi(a.headers.origin)){$(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(_!==i){$(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:_,projectName:zn(r)});return}}try{if(a.method==="POST"&&S==="/send")await rn(a,v);else if(a.method==="GET"&&S==="/events")Ie(a,v);else if(a.method==="GET"&&S==="/status")await nt(a,v,_);else if(a.method==="GET"&&S==="/ui-preferences")await Xe(v);else if(a.method==="PATCH"&&S==="/ui-preferences")await ot(a,v);else if(a.method==="PATCH"&&S==="/config")await Me(a,v);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){$(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let N=await Le(a),B=typeof N.leaseId=="string"?N.leaseId.trim():"",H=typeof N.ownerPid=="number"&&Number.isInteger(N.ownerPid)&&N.ownerPid>0?N.ownerPid:void 0;if(!B||B.length>128){$(v,400,{error:"A valid leaseId is required."});return}z();let F=h.acquire(B,H);$(v,201,{ok:!0,lease:F,ttlMs:si})}catch{$(v,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){$(v,409,{error:"Bridge leases are only available for detached bridges."});return}let N="";try{N=decodeURIComponent(S.slice(8))}catch{$(v,400,{error:"Invalid lease id."});return}if(!N){$(v,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let B=h.heartbeat(N);if(!B){$(v,404,{error:"Lease not found."});return}$(v,200,{ok:!0,lease:B})}else{let B=h.release(N);$(v,B.found?200:404,{ok:B.found}),B.becameEmpty&&Z()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){$(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}$(v,200,{ok:!0}),setTimeout(K,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){$(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}$(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let N of re)try{N.res.end()}catch{}We.close(()=>{ri(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")$(v,200,{providers:m});else if(S.startsWith("/imprint/"))await on(a,v,S);else if(S.startsWith("/memory/"))await Ot(a,v,S);else if(a.method==="POST"&&S==="/mcp/install")await it(a,v);else if(a.method==="POST"&&S==="/reply")await Hn(a,v);else if(a.method==="POST"&&S==="/cancel")rt(a,v);else if(a.method==="POST"&&S==="/materialize")$(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")$(v,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let N=await W.loadRuns();$(v,200,N)}else if(a.method==="GET"&&S==="/projection/proposals"){let N=await W.loadModelProposals();$(v,200,N)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let N=S.slice(22,-15);await Vn(N,a,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let N=S.slice(22,-6);await Wn(N,v)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let N=S.slice(22,-8);await Dt(N,a,v)}else if(S.startsWith("/model/proposals/"))$(v,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await gt(a,v);else if(a.method==="DELETE"&&S==="/model/component")await at(a,v);else if(a.method==="PATCH"&&S==="/model/token")await Kn(a,v);else if(a.method==="DELETE"&&S==="/model/token")await sn(a,v);else if(a.method==="POST"&&S==="/model/consolidate")$(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")$(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let N=await W.loadModel();$(v,200,{model:N})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let N=S.slice(6,S.length-7),B=parseInt(j.searchParams.get("afterSeq")??"-1",10),H=E.getBufferedEvents(N,isNaN(B)?-1:B);H?$(v,200,H):$(v,404,{error:"Unknown job"})}else if(a.method==="GET"&&w.startsWith("/files/"))await hi(w.slice(7),v);else if(a.method==="GET"&&S==="/threads/recent"){let N=Math.min(Math.max(parseInt(j.searchParams.get("limit")??"5",10)||5,1),20),B=await D.listRecent(N);$(v,200,B)}else if(a.method==="GET"&&S.startsWith("/decision/")){let N=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(N))$(v,400,{error:"Invalid decision id"});else{let B=await D.getThread(N),H=[...B?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(B&&H?.annotationSnapshot){let F=[...B.messages].reverse().find(ce=>ce.resolutions?.length);$(v,200,{decision:{id:B.id,createdAt:H.timestamp,url:H.annotationSnapshot.url,viewport:H.annotationSnapshot.viewport,color:H.annotationSnapshot.color,annotations:H.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await G.loadDecision(N);F?$(v,200,{decision:F,authority:"legacy_archive"}):$(v,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let N=S.slice(8);await gi(N,v)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let N=S.slice(8);await yi(N,v)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?ui(a,v):a.method==="GET"&&S==="/canvas/manifest"?await mi(v):a.method==="GET"&&S==="/canvas/app.mjs"?await fi(v):$(v,404,{error:"Not found"})}catch(N){console.error("[Bridge] Request error:",N),$(v,500,{error:N instanceof Error?N.message:"Internal error"})}});async function Ot(a,v,R){try{if(a.method==="GET"&&R==="/memory/status"){$(v,200,await V.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){$(v,200,await V.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){$(v,200,await V.getModelView());return}if(a.method==="GET"&&R==="/memory/imprint-view"){let w=await D.load(),j=[...new Set(Object.values(w.threads).flatMap(S=>nn(S.messages)))];$(v,200,await V.getImprintView(j));return}if(a.method==="POST"&&R==="/memory/constraints"){let w=await Le(a),j=typeof w.reactComponent=="string"?w.reactComponent.trim():"",S=await V.getModelView(),_=j?S.entries.filter(N=>N.key===`components.${j}`||N.key.startsWith(`components.${j}.`)):[];$(v,200,{modelEntries:_});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let w=await Le(a),j=typeof w.threadId=="string"?w.threadId:"",S=typeof w.proposalId=="string"?w.proposalId:"",_=String(w.action);if(!j||!S||!["accept","edit_and_accept","reject","defer"].includes(_)){$(v,400,{error:"A valid thread, proposal, and review action are required."});return}let N=await D.getThread(j),B=N?.messages.find(Y=>Y.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!N||!B){$(v,409,{error:"This decision review card is not available in the thread."});return}let H=await W.findModelProposalsByThread(j),F=(await Promise.all(H.map(async Y=>({proposal:Y,matches:(await Promise.all(Y.decisionIds.map(be=>V.findPendingProposalForLegacyDecision(be)))).some(be=>be?.proposalId===S)})))).find(Y=>Y.matches)?.proposal,ce={proposalId:S,action:_,kind:B.kind,claim:_==="edit_and_accept"&&typeof w.claim=="string"?w.claim.trim():void 0,reason:_==="defer"?void 0:`The owner explicitly chose ${_.replaceAll("_"," ")} from the decision review card.`,taskContext:_==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:_==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){$(v,400,{error:"Edited decision wording is required."});return}let U=await V.commitConversationalReview(ce),ne=`memory-${Et().slice(0,8)}`,de=_==="accept"?"> Accepted decision":_==="edit_and_accept"?"> Edited and accepted decision":_==="reject"?"> Rejected decision":"> Deferred decision";await D.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:ne,replyToQuestion:de}),await D.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:ne,responseText:"",memoryReceipt:U,provider:_t(typeof w.provider=="string"?w.provider:void 0),model:typeof w.model=="string"?w.model:void 0}),U.status==="committed"&&F&&await W.dismissModelProposal(F.id);let le=_t(typeof w.provider=="string"?w.provider:void 0);U.status==="committed"&&U.decisionId&&le!=="copilot"&&await Ye({provider:le,model:typeof w.model=="string"?w.model:void 0,agentSettings:yt(w),threadId:j,reason:`Project accepted decision ${U.decisionId}`}),$(v,U.status==="committed"?200:409,{receipt:U});return}if(a.method==="POST"&&R==="/memory/analyze"){let w=await Le(a),j=await V.analyzeLegacy({projectKey:typeof w.projectKey=="string"?w.projectKey:void 0}),S=Object.fromEntries([...new Set(j.issues.map(_=>_.code))].map(_=>[_,j.issues.filter(N=>N.code===_).length]));$(v,200,{...j,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&R==="/memory/review"){let w=await Le(a),j=await V.review(xo(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(v,200,j);return}if(a.method==="POST"&&R==="/memory/context"){let w=await Le(a),j=await V.contextualize(xo(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(v,200,j);return}if(a.method==="POST"&&R==="/memory/initialize"){let w=await Le(a),j=await V.initializeFromLegacy({confirmed:w.confirm===!0,projectKey:typeof w.projectKey=="string"?w.projectKey:void 0,writerVersion:tn});$(v,201,{status:j.status,report:{source:j.report.source,imported:j.report.imported,unresolvedAcceptance:j.report.unresolvedAcceptance,deferredModelEntries:j.report.deferredModelEntries,proofCases:j.report.proofCases,schemaIssues:j.report.schemaIssues}});return}if(a.method==="POST"&&R==="/memory/plan"){let w=await Le(a),j=await V.planReview(bo(w.command),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(v,j.result.ok?200:422,j);return}if(a.method==="POST"&&R==="/memory/commit"){let w=await Le(a),j=w.transaction&&typeof w.transaction=="object"&&!Array.isArray(w.transaction)?w.transaction:{},S=await V.commitReview(bo(w.command),{transactionId:typeof j.transactionId=="string"?j.transactionId:"",committedAt:typeof j.committedAt=="string"?j.committedAt:""});$(v,200,{status:await V.status(),journal:S.report});return}if(a.method==="POST"&&R==="/memory/recover"){let w=await Le(a),j=await V.recover(w.confirm===!0);$(v,200,{status:await V.status(),journal:j.report});return}$(v,404,{error:"Memory endpoint not found."})}catch(w){let j=w instanceof Error?w.message:String(w),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(j),_=/required|invalid|unsupported|expected|must be|confirmation/i.test(j);if(S||_){$(v,S?409:400,{error:j});return}throw w}}async function on(a,v,R){if(a.method==="GET"&&R==="/imprint/status"){let[w,j]=await Promise.all([ge.store.load(),D.load()]),S=[...new Set(Object.values(j.threads).flatMap(_=>nn(_.messages)))].filter(_=>w.graph.explanations.some(N=>N.id===_&&N.state==="testing"));$(v,200,{state:"ready",head:w.graph.head,updatedAt:w.graph.updatedAt,explanationCount:w.graph.explanations.filter(_=>_.state!=="retired").length,concreteCount:w.graph.concrete.length,relationCount:w.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:w.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let w=await Le(a),j=typeof w.threadId=="string"?w.threadId:"",S=typeof w.transactionId=="string"?w.transactionId:"",_=String(w.action);if(!j||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes(_)){$(v,400,{error:"A valid thread, imprint update, and action are required."});return}let B=await D.getThread(j),H=[...B?.messages??[]].reverse().find(le=>le.role==="assistant"&&le.imprintSummary?.transactionId===S),F=H?.imprintSummary;if(!B||!H||!F){$(v,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){$(v,409,{error:"This imprint summary has already been resolved."});return}let ce=`imprint-${Et().slice(0,8)}`;await ge.applyGroundingAction({summary:F,action:_,value:typeof w.value=="string"?w.value:void 0,threadId:j,jobId:ce}),await V.recordImprintEvidence({summary:F,action:_,threadId:j,jobId:ce}).catch(le=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",le));let U=jt(H.result,!!H.question),ne=H.turn?{...H.turn,result:jt(H.turn.result,!!H.question)}:void 0;await D.updateAssistantMessage(j,H.jobId,{imprintSummary:{...F,resolvedAction:_},...U?{result:U}:{},...ne?{turn:ne}:{}});let de={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 D.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:ce,replyToQuestion:de[_]}),$(v,200,{ok:!0,action:_});return}$(v,404,{error:"Imprint endpoint not found."})}async function rn(a,v){let{screenshot:R,feedback:w,color:j,provider:S,model:_,reasoningEffort:N,serviceTier:B,sourceId:H,pastedImages:F,pageScreenshots:ce}=await So(a),U;try{U=JSON.parse(w)}catch{$(v,400,{error:"Invalid feedback JSON"});return}let ne=Et().slice(0,8),de={};if(ce.length>0)for(let Q of ce){let Se=encodeURIComponent(Q.pathname),pe=_e(c,`screenshot-${ne}-${Se}.webp`);await Un(pe,Q.data),de[Q.pathname]=pe}let le=_e(c,`screenshot-${ne}.webp`);await Un(le,R);let Y={};if(F.length>0)for(let Q of F){let Se=_e(c,`pasted-${ne}-${Q.annotationId}-${Q.index}.webp`);await Un(Se,Q.data),Y[Q.annotationId]||(Y[Q.annotationId]=[]),Y[Q.annotationId].push(Se)}let be=U.annotations.map(Q=>Q.linkedSelector?Q.pathname?`${Q.pathname}:${Q.linkedSelector}`:Q.linkedSelector:null).filter(Q=>!!Q),he;if(be.length>0){let Q=await D.findContinuationThread(be);Q?(he=Q.id,await D.addElementIdentifiers(he,be)):he=(await D.createThread(ne,be)).id}else he=(await D.createThread(ne,[])).id;let we=U.annotations.map(Q=>Q.id),Fe=Object.keys(de).length>0,q=await Rr(V,U,be,Q=>console.warn(`[\u22B9 ${y}:${ne}] Contextual memory unavailable; continuing without it:`,Q instanceof Error?Q.message:String(Q))),ie=await ge.contextualize({text:Mn(U),subjectHints:[...be,...U.annotations.flatMap(Q=>[Q.pathname,Q.elements?.[0]?.reactComponent].filter(Se=>!!Se))],pendingGroundingExplanationIds:nn((await D.getThread(he))?.messages??[])}).catch(Q=>{console.warn(`[\u22B9 ${y}:${ne}] Imprint context unavailable; continuing without it:`,Q instanceof Error?Q.message:String(Q))}),Ne={id:ne,status:"queued",screenshotPath:le,feedback:U,createdAt:Date.now(),color:j,threadId:he,annotationIds:we,provider:_t(S),model:_||void 0,agentSettings:yt({reasoningEffort:N,serviceTier:B}),...Object.keys(Y).length>0?{imagePaths:Y}:{},sourceId:H||void 0,...Fe?{screenshotPaths:de}:{},...q?{memoryReview:q}:{},...ie?{imprintContext:ie}:{}},st=new Set(U.annotations.map(Q=>Q.pathname).filter(Boolean)),De;if(st.size>1){let Q=new Map;for(let Se of U.annotations){let pe=Se.pathname||"(unknown)";Q.has(pe)||Q.set(pe,[]),Q.get(pe).push(Se.instruction||ci({...U,annotations:[Se]}))}De=[...Q.entries()].map(([Se,pe])=>`\`${Se}\`
|
|
172
|
+
${pe.map(qe=>`- ${qe}`).join(`
|
|
231
173
|
`)}`).join(`
|
|
232
|
-
`)}else
|
|
233
|
-
`):
|
|
234
|
-
`)
|
|
235
|
-
`)),we){let X=we,W=[...X._replyTexts??(X._replyText?[X._replyText]:[]),k],re=[...X._replyImagePaths??[],...K];X._replyTexts=W,X._replyText=Ai(W),X._replyImagePaths=re.length>0?re:void 0,X._replyPrompt=yt,X.annotationIds=ee.length>0?ee:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=$e??X.memoryReview,X.imprintContext=Ce??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...Se])],_(g,200,{jobId:Ie,position:1,threadId:v,bundled:!0});return}let We={id:Ie,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}:{},...Se.length?{surfacedProposalIds:Se}:{}};ie?We.kind="resolve_eval":te&&(We.kind=te),We._replyPrompt=yt,We._evalRemediation=!!ie,We._replyTexts=[k],We._replyText=Ai([k]),K.length>0&&(We._replyImagePaths=K);let qt=xe?I.enqueueNext(We):I.enqueue(We);_(g,200,{jobId:Ie,position:qt,threadId:v})}function dt(a,g){g.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),g.write(`event: connected
|
|
174
|
+
`)}else De=ci(U);let Te=Wt(U,Object.keys(Y).length>0?Y:void 0);await D.appendMessage(he,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:le,...Fe?{screenshotPaths:de}:{},...Object.keys(Y).length>0?{imagePaths:Y}:{},annotationIds:we,annotationSnapshot:{url:U.url,viewport:U.viewport,annotations:U.annotations,color:j||void 0},feedbackSummary:De,feedbackContext:Te||void 0,...q?{memoryReview:q}:{},...ie?{imprintContext:ie}:{}});let Ze=E.enqueue(Ne);$(v,200,{jobId:ne,position:Ze,threadId:he})}async function Hn(a,v){let R=a.headers["content-type"]||"",w,j,S,_,N,B,H,F,ce=[];if(R.includes("multipart/form-data")){let X=await So(a),ue=X.feedback?JSON.parse(X.feedback):{};w=ue.threadId,j=ue.reply,S=ue.color,_=ue.provider,N=ue.model,B=yt(ue),H=ue.sourceId||X.sourceId,F=typeof ue.memoryReviewProposalId=="string"?ue.memoryReviewProposalId:void 0;for(let me of X.pastedImages)ce.push(me.data)}else{let X=[];for await(let te of a)X.push(typeof te=="string"?Buffer.from(te):te);let ue=Buffer.concat(X).toString("utf-8"),me;try{me=JSON.parse(ue)}catch{$(v,400,{error:"Invalid JSON"});return}w=me.threadId,j=me.reply,S=me.color,_=me.provider,N=me.model,B=yt(me),H=me.sourceId,F=me.memoryReviewProposalId}if(!w||!j){$(v,400,{error:"Missing threadId or reply"});return}let U=await D.getThread(w);if(!U){$(v,404,{error:"Thread not found"});return}let ne;if(F){let X=await W.findModelProposalsByThread(w);if(ne=(await Promise.all(X.flatMap(me=>me.authorityStatus==="accepted"?[]:me.decisionIds.map(async te=>({modelProposalId:me.id,underlying:await V.findPendingProposalForLegacyDecision(te)}))))).filter(me=>!!me.underlying).find(me=>me.underlying.proposalId===F),!ne){$(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let de="";{let X=await D.getThreadHistory(w);for(let ue=X.length-1;ue>=0;ue--)if(X[ue].screenshotPath){de=X[ue].screenshotPath;break}}let le=await Oe(w);if(!de&&!le){$(v,400,{error:"No screenshot available"});return}let Y=E.hasActiveThread(w),be=Y?E.getQueuedThreadJob(w,X=>X._replyText!==void 0||X._replyPrompt!==void 0):null,he=be?.id??Et().slice(0,8),we=[],Fe=`${he}-${Date.now()}`;for(let X=0;X<ce.length;X++){let ue=_e(c,`reply-${Fe}-${X}.webp`);await Un(ue,ce[X]),we.push(ue)}await D.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:he,replyToQuestion:j,screenshotPath:de,...Y?{queued:!0}:{},...we.length>0?{replyImagePaths:we}:{}});let q=await D.getThreadHistory(w),ie=[...q].reverse().find(X=>X.memoryReview)?.memoryReview,Ne=await ge.contextualize({text:j,subjectHints:U.elementIdentifiers,pendingGroundingExplanationIds:nn(q)}).catch(X=>{console.warn(`[\u22B9 ${y}:${he}] Imprint context unavailable for reply; continuing without it:`,X instanceof Error?X.message:String(X))}),st=new Set(q.flatMap(X=>X.memoryReceipt?.status==="committed"?[X.memoryReceipt.proposalId]:[])),De=[...q].reverse().find(X=>X.memoryReviewCard&&!st.has(X.memoryReviewCard.proposalId))?.memoryReviewCard,Te=[];for(let X of q)if(X.annotationIds)for(let ue of X.annotationIds)Te.includes(ue)||Te.push(ue);let Ze=_t(_),Q=ne,Se=Q?[Q.underlying.proposalId]:De?[De.proposalId]:[],pe=$r(de,q,Ze,we.length>0?we:void 0);if(Q?pe+=["","## Decision review card",`Privately review proposal ${Q.underlying.proposalId}: ${Q.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(`
|
|
175
|
+
`):De&&(pe+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(De)}`,"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(`
|
|
176
|
+
`)),be){let X=be,me=[...X._replyTexts??(X._replyText?[X._replyText]:[]),j],te=[...X._replyImagePaths??[],...we];X._replyTexts=me,X._replyText=ai(me),X._replyImagePaths=te.length>0?te:void 0,X._replyPrompt=pe,X.annotationIds=Te.length>0?Te:X.annotationIds,X.agentSettings=B??X.agentSettings,X.memoryReview=ie??X.memoryReview,X.imprintContext=Ne??X.imprintContext,X.surfacedProposalIds=[...new Set([...X.surfacedProposalIds??[],...Se])],$(v,200,{jobId:he,position:1,threadId:w,bundled:!0});return}let qe={id:he,status:"queued",screenshotPath:de,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:Te.length>0?Te:void 0,provider:Ze,model:N||void 0,agentSettings:B,sourceId:H||void 0,...ie?{memoryReview:ie}:{},...Ne?{imprintContext:Ne}:{},...Se.length?{surfacedProposalIds:Se}:{}};le&&(qe.kind=le),qe._replyPrompt=pe,qe._replyTexts=[j],qe._replyText=ai([j]),we.length>0&&(qe._replyImagePaths=we);let Qn=Y?E.enqueueNext(qe):E.enqueue(qe);$(v,200,{jobId:he,position:Qn,threadId:w})}function Ie(a,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
|
|
236
177
|
data: {"status":"connected"}
|
|
237
178
|
|
|
238
|
-
`);let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,k={id:mt().slice(0,8),res:g,sourceId:v};Y.add(k),a.on("close",()=>{Y.delete(k)})}async function lt(a,g,P){s??=gi(a.headers),qe();let v=[...I.allActive,...b.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=yi(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})),ie=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=>mn(K.messages)))]:[],te=J.status==="fulfilled"?ce.filter(K=>J.value.graph.explanations.some(de=>de.id===K&&de.state==="testing")):[],xe=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},we=z.length>0?"degraded":ie.state==="absent"||ie.state==="initializing"?"initializing":"healthy",Ie=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:Ie,serverStartedAt:e,health:{state:we,issues:z},version:pn,restartMode:p,projectId:i,projectName:no(r),projectRoot:r,requestProjectId:P,projectIdVerified:P===i,devOrigin:s,activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.map(K=>({id:K.id,status:K.status,threadId:K.threadId,annotationIds:K.annotationIds,color:K.color,kind:K.kind,standalone:"standalone"in K?K.standalone:void 0})),queueDepth:I.depth+b.depth,projectionQueueDepth:b.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:U},projection:{state:k.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:b.active?{id:b.active.id,status:b.active.status,threadId:b.active.threadId,annotationIds:b.active.annotationIds??[],provider:b.active.provider,model:b.active.model}:null,queueDepth:b.depth,recentRuns:Q.recentRuns,recentAppliedRuns:Q.recentAppliedRuns,actionableProposalCounts:Q.actionableProposalCounts,actionableProposals:G},memory:ie,imprint:xe,recentJobsRetentionMs:Ne,recentJobs:ke})}async function ht(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 io(a){let g=await C.load();_(a,200,{ok:!0,...g})}async function so(a,g){let P=await Ue(a);if(!Si(P.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let v=await C.setTheme(P.theme);_(g,200,{ok:!0,exists:!0,preferences:v})}async function Ut(a,g){let v=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),k=v?I.allActive.filter(L=>L.id===v):I.allActive,S=v?b.allActive.filter(L=>L.id===v):b.allActive,E=[...k.map(L=>L.threadId),...S.map(L=>L.threadId)].filter(Boolean),J=v?I.cancelJob(v):I.cancelActive(),B=v?b.cancelJob(v):b.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 Ee(a){let g=mt().slice(0,8),P=a.threadId,v=!P;P||(P=(await V.createThread(g,[])).id,Ke.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=b.enqueue(k);return{jobId:g,position:S,threadId:P}}async function Be(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 pt(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(ie=>typeof ie=="string"||typeof ie=="number");if(Q.length!==N.path.length)return[];let G=Array.isArray(N.decisionIds)?N.decisionIds.filter(ie=>typeof ie=="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,ie=G===0?"unprojected":Q>G?"partially_projected":"projected";return{decisionId:N,status:ie}}),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 tt(O),O.threadId){let N=kt(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 Pt(a,g,P){let v=decodeURIComponent(a),{provider:k,model:S}=await gt(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 gt(a){try{let g=[];for await(let v of a)g.push(typeof v=="string"?Buffer.from(v):v);if(g.length===0)return{};let P=JSON.parse(Buffer.concat(g).toString());return{provider:kt(typeof P.provider=="string"?P.provider:void 0),model:typeof P.model=="string"&&P.model?P.model:void 0,agentSettings:vt(P)}}catch{return{}}}async function ao(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 zn(g),N=kt(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=mt().slice(0,8),ie=mt().slice(0,8),ce=Me(c,`eval-run-${G}.webp`);await un(ce,S);let te=await ue.persistEvalScreenshot(S),xe=Q.viewport,we=xe&&typeof xe=="object"?xe:{},Ie={type:"current_page",url:typeof Q.url=="string"?Q.url:"",viewport:{width:typeof we.width=="number"?we.width:0,height:typeof we.height=="number"?we.height:0}},K=await se.loadModel(),de=await _i(r,k,K),pe=N==="claude"?A.name:N==="codex"?D.name:null,$e=N==="codex"?$.length>0:typeof pe=="string"&&/chrome|devtools/i.test(pe),Ce=fr({evalCase:k,scope:Ie,model:K,screenshotPath:ce,chromeDevtoolsAvailable:$e}),Pe=(await V.createThread(ie,[])).id;Ke.set(Pe,"run_eval");let ee={timestamp:new Date().toISOString(),url:Ie.url,viewport:Ie.viewport,scrollPosition:{x:typeof Q.scrollX=="number"?Q.scrollX:0,y:typeof Q.scrollY=="number"?Q.scrollY:0},annotations:[],styleModifications:[]};await V.appendMessage(Pe,{role:"human",timestamp:Date.now(),jobId:ie,screenshotPath:ce,feedbackSummary:`Run eval \u2014 ${k.title}`,feedbackContext:[`Eval: ${k.title}`,"Scope: current page",`URL: ${Ie.url||"unknown"}`,"Assertions:",...k.assertions.map(Se=>`- ${Se}`)].join(`
|
|
239
|
-
`)});let he={id:ie,status:"queued",screenshotPath:ce,feedback:ee,createdAt:Date.now(),color:"#111827",threadId:Pe,kind:"run_eval",evalId:v,evalRunId:G,provider:N,model:B||void 0,agentSettings:vt({reasoningEffort:z,serviceTier:L}),sourceId:O||void 0};he._replyPrompt=Ce,he._evalRunScope=Ie,he._evalScreenshotPath=te,he._evalScopeFingerprint=de;let Te=I.enqueue(he);_(P,200,{jobId:ie,runId:G,position:Te,threadId:Pe,screenshotPath:te})}async function fn(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 Ji(a){let g=Ke.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 Ke.set(a,"synthesize_evals"),"synthesize_evals";if(k.startsWith("Synthesize rules"))return Ke.set(a,"synthesize"),"synthesize";if(k.startsWith("Run eval"))return Ke.set(a,"run_eval"),"run_eval";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return Ke.set(a,"project_model"),"project_model"}async function Ni(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 Er(v)),h.codex?.available&&h.codex.mcp&&!h.codex.mcp.found&&k.push(await Mr(v)),h.copilot?.available&&h.copilot.mcp&&!h.copilot.mcp.found&&k.push(await _r(v,h.copilot.path??T));let[S,E,J]=await Promise.all([bo(r),xo(r),So(r,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 Bi(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 at({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 Fi(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 at({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 Li(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 at({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 zi(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 at({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 Ui(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=Xo(y,P);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(v)}async function qi(a){let g=Date.now();if(ft&&g<ft.expires){_(a,200,ft.data);return}try{let{scanForComponents:P}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:v}=await import("./render-generator-EANIDD2E.mjs"),k=await P(r);ft={data:k,expires:g+5e3},v(k,r,Lt).then(S=>{Lt=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 Wi(a){let g=[Me(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Me(r,"packages","popmelt","dist","canvas.mjs")];try{let P=dd(import.meta.url);g.unshift(Me(cd(P),"canvas.mjs"))}catch{}for(let P of g)try{let v=await Wo(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 Gi(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let P=[Me(c,a),Me(r,".popmelt","artifacts","thread-media",a),Me(r,".popmelt","artifacts","eval-screenshots",a),Me(r,".popmelt","evals","screenshots",a),Me(r,".popmelt","screenshots",a)],v;for(let E of P)try{v=await Wo(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 hn(a){return`/files/${no(a)}`}async function Hi(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,...ie})=>({...ie,...ie.role==="assistant"&&S&&ie.responseText?.includes("<eval_run_result>")?{evalRun:{...S,title:J?.title}}:{},...O?{screenshotUrl:hn(O)}:{},...N?{screenshotUrls:Object.fromEntries(Object.entries(N).map(([ce,te])=>[ce,hn(te)]))}:{},...Q?{imageUrls:Object.fromEntries(Object.entries(Q).map(([ce,te])=>[ce,te.map(hn)]))}:{},...G?{replyImageUrls:G.map(hn)}:{}}));_(g,200,{id:P.id,createdAt:P.createdAt,messages:L,modelProposal:z,modelProposals:B})}async function Vi(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 Vo=9,Ko=!1;for(let a=n;a<n+Vo;a++)try{await Rd(zt,a),y=a,Ko=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(g){if(g.code==="EADDRINUSE"){let P=await Sd(a);if(hi(P,{projectId:i,version:pn,restartMode:p}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw g}if(!Ko)throw new Error(`[Bridge] All ports ${n}\u2013${n+Vo-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)oo(v,{type:"capabilities_changed",data:{}})}});let Ki=setInterval(()=>{$i(c).catch(()=>{})},ud),Qo=setInterval(()=>{M.expireStale().becameEmpty&&ye()},fd);return Qo.unref?.(),{port:y,projectId:i,close:async()=>{clearInterval(Ki),clearInterval(Qo),ne(),M.clear(),await I.destroyAsync(),b.destroy();for(let a of Y)try{a.res.end()}catch{}return Y.clear(),new Promise(a=>{zt.close(()=>a())})}}}async function $i(o){try{let e=await nd(o),n=Date.now();for(let t of e){let r=Me(o,t);try{let i=await rd(r);n-i.mtimeMs>md&&await id(r)}catch{}}}catch{}}var ve="\x1B[35m[popmelt]\x1B[0m";async function Ed(){let o=process.argv.slice(2);if(o[0]==="memory"){await _d(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${ve} Usage: popmelt wrap -- <dev command>`),console.error(`${ve} Example: popmelt wrap -- next dev`),console.error(`${ve} Example: popmelt wrap -- astro dev`),process.exit(1));let n=o.slice(e+1);await Dd(n);return}if(o[0]==="bridge"){await $d();return}if(o[0]==="stop"){await Cd();return}console.log(`${ve} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function Ft(o,e){let n=o.indexOf(e);return n>=0?o[n+1]:void 0}function Md(){console.log(`${ve} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function _d(o){if(o[0]!=="import"&&o[0]!=="review"){Md(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=Ft(o,"--project")??process.cwd(),n=Ft(o,"--project-key"),t=await xt({projectRoot:e,projectKey:n});if(o[0]==="review"){let c=Ft(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=Xt(t.bundle,{subjectHints:[c],action:Ft(o,"--action"),maxPackets:Number(Ft(o,"--max-packets")??3),maxEstimatedTokens:Number(Ft(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${ve} Contextual memory review (read-only)`),console.log(`${ve} Subject: ${c}`),console.log(`${ve} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${ve} Uncertainty: ${d.uncertainty}`);for(let[l,w]of d.packets.entries())console.log(""),console.log(`${l+1}. ${w.proposal.claim}`),console.log(` Authority: ${w.authority}; presentation: ${w.presentation}; implementation: ${w.implementation.state}`),console.log(` Why now: ${w.trigger.reason}`),console.log(` Proposal: ${w.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(t.report,null,2));return}let r=t.report,i=r.proofCases.filter(c=>c.threadFound).length,s=r.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${ve} Legacy memory analysis (read-only)`),console.log(`${ve} Project: ${r.projectRoot}`),console.log(`${ve} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${ve} Imported: ${Object.entries(r.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${ve} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${ve} Model values deferred: ${r.deferredModelEntries}`),console.log(`${ve} Proof coverage: ${i}/${r.proofCases.length} threads found`),console.log(`${ve} Schema validation: ${s.length===0?"passed":`${s.length} errors`}`),r.issues.length){let c=new Map;for(let d of r.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${ve} Review flags: ${[...c].map(([d,l])=>`${d}=${l}`).join(", ")}`)}}async function $d(){let o=await Ho({projectRoot:process.cwd()});console.log(`${ve} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
240
|
-
${ve} Shutting down bridge...`),await o.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function Cd(){let o=Ad(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await Td(o,"utf8"))}catch{console.log(`${ve} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${ve} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${ve} Bridge process ${e.pid} already dead`);else throw n}try{await jd(o)}catch{}}async function Dd(o){let e=await Ho({projectRoot:process.cwd()});console.log(`${ve} Bridge running on http://localhost:${e.port}`);let[n,...t]=o;console.log(`${ve} Starting: ${o.join(" ")}`);let r=Pd(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=s=>{r.kill(s)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r.on("exit",async(s,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(s??0)})}Ed().catch(o=>{console.error(`${ve} Fatal:`,o),process.exit(1)});
|
|
179
|
+
`);let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,j={id:Et().slice(0,8),res:v,sourceId:w};re.add(j),a.on("close",()=>{re.delete(j)})}async function nt(a,v,R){s??=Vr(a.headers),Pe();let w=[...E.allActive,...C.allActive.map(q=>({id:q.id,status:q.status,threadId:q.threadId,annotationIds:q.annotationIds??[],color:"#000000",kind:"project_model",standalone:q.standalone}))],[j,S,_,N,B]=await Promise.allSettled([W.loadRuns(),W.loadModelProposals(),V.status(),ge.store.load(),D.load()]),H=[],F=q=>q.reason instanceof Error?q.reason.message:String(q.reason);j.status==="rejected"&&H.push({subsystem:"projection",message:F(j)}),S.status==="rejected"&&H.push({subsystem:"projection",message:F(S)}),_.status==="rejected"?H.push({subsystem:"memory",message:F(_)}):_.value.state==="degraded"&&H.push({subsystem:"memory",message:_.value.error??"Product memory is degraded."}),N.status==="rejected"&&H.push({subsystem:"imprint",message:F(N)}),B.status==="rejected"&&H.push({subsystem:"threads",message:F(B)});let ce=j.status==="fulfilled"?j.value.runs:[],U=S.status==="fulfilled"?S.value.proposals:[],ne=Kr(ce,U),de=ne.actionableProposals.map(q=>({id:q.id,status:q.status,title:q.title,summary:q.summary,decisionIds:q.decisionIds,threadId:q.threadId,runId:q.runId,presentationJobId:q.presentationJobId,authorityStatus:q.authorityStatus,underlyingProposalId:q.underlyingProposalId,createdAt:q.createdAt,updatedAt:q.updatedAt,appliedAt:q.appliedAt,dismissedAt:q.dismissedAt,error:q.error})),le=_.status==="fulfilled"?_.value:{initialized:!1,state:"degraded",error:F(_)},Y=B.status==="fulfilled"?[...new Set(Object.values(B.value.threads).flatMap(q=>nn(q.messages)))]:[],be=N.status==="fulfilled"?Y.filter(q=>N.value.graph.explanations.some(ie=>ie.id===q&&ie.state==="testing")):[],he=N.status==="fulfilled"?{state:"ready",head:N.value.graph.head,updatedAt:N.value.graph.updatedAt,explanationCount:N.value.graph.explanations.filter(q=>q.state!=="retired").length,concreteCount:N.value.graph.concrete.length,relationCount:N.value.graph.relations.length,pendingGroundingCount:be.length,recoveredTransactions:N.value.recoveredTransactions,admission:ge.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(N),pendingGroundingCount:be.length,admission:ge.diagnostics(),admissionWindowStartedAt:e},we=H.length>0?"degraded":le.state==="absent"||le.state==="initializing"?"initializing":"healthy",Fe=new Date().toISOString();$(v,200,{ok:!0,schemaVersion:3,generatedAt:Fe,serverStartedAt:e,health:{state:we,issues:H},version:tn,restartMode:l,projectId:i,projectName:zn(r),projectRoot:r,requestProjectId:R,projectIdVerified:R===i,devOrigin:s,activeJob:w[0]?{id:w[0].id,status:w[0].status}:null,activeJobs:w.map(q=>({id:q.id,status:q.status,threadId:q.threadId,annotationIds:q.annotationIds,color:q.color,kind:q.kind,standalone:"standalone"in q?q.standalone:void 0})),queueDepth:E.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:h.isActivated,count:h.size,nextExpiryAt:h.nextExpiryAt,shutdownPending:J},projection:{state:j.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:C.active?{id:C.active.id,status:C.active.status,threadId:C.active.threadId,annotationIds:C.active.annotationIds??[],provider:C.active.provider,model:C.active.model}:null,queueDepth:C.depth,recentRuns:ne.recentRuns,recentAppliedRuns:ne.recentAppliedRuns,actionableProposalCounts:ne.actionableProposalCounts,actionableProposals:de},memory:le,imprint:he,recentJobsRetentionMs:ke,recentJobs:ve})}async function Me(a,v){let R=await new Promise(w=>{let j="";a.on("data",S=>{j+=S.toString()}),a.on("end",()=>w(j))});try{let w=JSON.parse(R);typeof w.devOrigin=="string"&&(s=w.devOrigin||null),$(v,200,{ok:!0,devOrigin:s})}catch{$(v,400,{error:"Invalid JSON"})}}async function Xe(a){let v=await L.load();$(a,200,{ok:!0,...v})}async function ot(a,v){let R=await Le(a);if(!ti(R.theme)){$(v,400,{error:"theme must be light, dark, or auto"});return}let w=await L.setTheme(R.theme);$(v,200,{ok:!0,exists:!0,preferences:w})}async function rt(a,v){let w=new URL(a.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),j=w?E.allActive.filter(F=>F.id===w):E.allActive,S=w?C.allActive.filter(F=>F.id===w):C.allActive,_=[...j.map(F=>F.threadId),...S.map(F=>F.threadId)].filter(Boolean),N=w?E.cancelJob(w):E.cancelActive(),B=w?C.cancelJob(w):C.cancelActive(),H=!!(N||B);for(let F of _)await D.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:w||B?.id||"",cancelled:!0});$(v,200,{cancelled:H})}async function Ye(a){let v=Et().slice(0,8),R=a.threadId,w=!R;R||(R=(await D.createThread(v,[])).id,$e.set(R,"project_model")),w&&await D.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:a.reason}),await D.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 j={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=C.enqueue(j);return{jobId:v,position:S,threadId:R}}async function Wn(a,v){let R=decodeURIComponent(a),w=await W.findModelProposal(R);if(!w){$(v,404,{error:"Model proposal not found"});return}$(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:w})}async function Vn(a,v,R){let w=decodeURIComponent(a),j=[];for await(let U of v)j.push(typeof U=="string"?Buffer.from(U):U);let S;try{S=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{$(R,400,{error:"Invalid JSON"});return}let _=(S.changes??[]).flatMap(U=>{if(!Array.isArray(U.path)||U.path.length===0)return[];let ne=U.path.filter(le=>typeof le=="string"||typeof le=="number");if(ne.length!==U.path.length)return[];let de=Array.isArray(U.decisionIds)?U.decisionIds.filter(le=>typeof le=="string"):void 0;return[{path:ne,value:U.value,remove:U.remove===!0,decisionIds:de}]});if(_.length===0){$(R,400,{error:"No selected model changes"});return}let N=(S.changeSummaries??[]).flatMap(U=>{if(!U||typeof U!="object")return[];let ne=Array.isArray(U.path)?U.path.filter(de=>typeof de=="string"||typeof de=="number"):void 0;return Array.isArray(U.path)&&ne?.length!==U.path.length?[]:[{group:typeof U.group=="string"?U.group:void 0,label:typeof U.label=="string"?U.label:void 0,detail:typeof U.detail=="string"?U.detail:void 0,path:ne,value:U.value,currentValue:U.currentValue}]}),B=await W.findModelProposal(w);if(!B){$(R,404,{error:"Model proposal not found"});return}if(B.authorityStatus!=="accepted"){$(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(B.status!=="pending"){$(R,409,{error:`Model proposal is already ${B.status}.`});return}let H=B.decisionIds.map(U=>{let ne=B.changes?.filter(Y=>Y.decisionIds.includes(U)).length??0,de=_.filter(Y=>Y.decisionIds?.includes(U)).length,le=de===0?"unprojected":ne>de?"partially_projected":"projected";return{decisionId:U,status:le}}),F=await V.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:_.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:H}),ce=await W.applySelectedModelProposal(w,_,N);if(!ce){$(R,404,{error:"Model proposal not found"});return}if(ce.threadId){let U=_t(S.provider),ne=typeof S.model=="string"&&S.model?S.model:void 0;await D.appendMessage(ce.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ce.id}`,responseText:"",provider:U,model:ne})}$(R,200,{proposal:ce,projection:F})}async function Dt(a,v,R){let w=decodeURIComponent(a),{provider:j,model:S}=await Ce(v),_=await W.dismissModelProposal(w);if(!_){$(R,404,{error:"Model proposal not found"});return}_.threadId&&await D.appendMessage(_.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${_.id}`,responseText:"",provider:j,model:S}),$(R,200,{proposal:_})}async function Ce(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:yt(R)}}catch{return{}}}async function Oe(a){let v=$e.get(a);if(v)return v;let j=(await D.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(j.startsWith("Synthesize rules"))return $e.set(a,"synthesize"),"synthesize";if(j.startsWith("Materialize model")||j.startsWith("Project model"))return $e.set(a,"project_model"),"project_model"}async function it(a,v){let R=[];for await(let B of a)R.push(typeof B=="string"?Buffer.from(B):B);let w;if(R.length>0)try{w=JSON.parse(Buffer.concat(R).toString("utf-8")).serverUrl}catch{}let j=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&j.push(await sr(w)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&j.push(await ar(w)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&j.push(await cr(w,m.copilot.path??P));let[S,_,N]=await Promise.all([ao(r),co(r),lo(r,m.copilot?.path??P)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=_),m.copilot&&(m.copilot.mcp=N),$(v,200,{results:j,capabilities:{providers:m}})}async function gt(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{$(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){$(v,400,{error:"Missing or invalid name"});return}let j=await V.recordDirectModelMutation({key:`components.${w.name}`,value:{description:""},claim:`${w.name} is an explicitly governed component in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),$(v,200,{added:!0,alreadyExists:!1,...j})}async function at(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{$(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){$(v,400,{error:"Missing or invalid name"});return}let j=await V.recordDirectModelMutation({key:`components.${w.name}`,value:null,claim:`${w.name} is not governed as a component in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),$(v,200,{removed:!0,...j})}async function Kn(a,v){let R=[];for await(let _ of a)R.push(typeof _=="string"?Buffer.from(_):_);let w;try{w=JSON.parse(Buffer.concat(R).toString("utf-8"))}catch{$(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"||typeof w.value!="string"){$(v,400,{error:"Missing or invalid path/value"});return}let j=w.value;try{let _=JSON.parse(w.value);_&&typeof _=="object"&&(j=_)}catch{}let S=await V.recordDirectModelMutation({key:`tokens.${w.path}`,value:j,claim:`${w.path} uses ${w.value} in the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),$(v,200,{updated:!0,...S})}async function sn(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{$(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"){$(v,400,{error:"Missing or invalid path"});return}let j=await V.recordDirectModelMutation({key:`tokens.${w.path}`,value:null,claim:`${w.path} is intentionally absent from the product model.`});await W.applyCanonicalEntries(await V.getCanonicalModelEntries()),$(v,200,{removed:!0,...j})}function ui(a,v){let R=s??"http://localhost:3000";if(!s){let j=a.headers.referer||a.headers.origin;if(j)try{let S=new URL(typeof j=="string"?j:j[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(R=S.origin)}catch{}}let w=Oo(y,R);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(w)}async function mi(a){let v=Date.now();if(He&&v<He.expires){$(a,200,He.data);return}try{let{scanForComponents:R}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:w}=await import("./render-generator-EANIDD2E.mjs"),j=await R(r);He={data:j,expires:v+5e3},w(j,r,Ct).then(S=>{Ct=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),$(a,200,j)}catch(R){console.error("[Bridge] Scanner error:",R),$(a,500,{error:"Failed to scan components"})}}async function fi(a){let v=[_e(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),_e(r,"packages","popmelt","dist","canvas.mjs")];try{let R=vc(import.meta.url);v.unshift(_e(hc(R),"canvas.mjs"))}catch{}for(let R of v)try{let w=await ii(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),$(a,404,{error:"Canvas bundle not found"})}async function hi(a,v){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){$(v,400,{error:"Invalid filename"});return}try{let R=[_e(c,a),_e(r,".popmelt","artifacts","thread-media",a),_e(r,".popmelt","artifacts","eval-screenshots",a),_e(r,".popmelt","evals","screenshots",a),_e(r,".popmelt","screenshots",a)],w;for(let _ of R)try{w=await ii(_);break}catch{}if(!w)throw new Error("File not found");let j=a.split(".").pop()?.toLowerCase(),S=j==="png"?"image/png":j==="webp"?"image/webp":j==="jpg"||j==="jpeg"?"image/jpeg":"application/octet-stream";v.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),v.end(w)}catch{$(v,404,{error:"File not found"})}}function an(a){return`/files/${zn(a)}`}async function gi(a,v){let R=await D.getThread(a);if(!R){$(v,404,{error:"Thread not found"});return}let w=R.messages.filter(B=>B.role==="assistant"&&B.responseText?.includes("Model suggestion ready")),j=await(w.length>0?W.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(j.map(async(B,H)=>{if(B.authorityStatus==="accepted")return B;let F=(await Promise.all(B.decisionIds.map(ce=>V.findPendingProposalForLegacyDecision(ce)))).find(Boolean);return{...B,authorityStatus:"legacy_untrusted",presentationJobId:B.presentationJobId??w[H]?.jobId??w.at(-1)?.jobId,underlyingProposalId:F?.proposalId,underlyingClaim:F?.claim}})),_=[...S].sort((B,H)=>H.updatedAt-B.updatedAt)[0]??null,N=R.messages.map(({screenshotPath:B,screenshotPaths:H,imagePaths:F,replyImagePaths:ce,...U})=>({...U,...B?{screenshotUrl:an(B)}:{},...H?{screenshotUrls:Object.fromEntries(Object.entries(H).map(([ne,de])=>[ne,an(de)]))}:{},...F?{imageUrls:Object.fromEntries(Object.entries(F).map(([ne,de])=>[ne,de.map(an)]))}:{},...ce?{replyImageUrls:ce.map(an)}:{}}));$(v,200,{id:R.id,createdAt:R.createdAt,messages:N,modelProposal:_,modelProposals:S})}async function yi(a,v){let R=decodeURIComponent(a);if(!await D.deleteThread(R)){$(v,404,{deleted:!1,error:"Thread not found"});return}$(v,200,{deleted:!0})}let _o=9,$o=!1;for(let a=n;a<n+_o;a++)try{await $c(We,a),y=a,$o=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(v){if(v.code==="EADDRINUSE"){let R=await _c(a);if(Wr(R,{projectId:i,version:tn,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw v}if(!$o)throw new Error(`[Bridge] All ports ${n}\u2013${n+_o-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 re)Gn(w,{type:"capabilities_changed",data:{}})}});let vi=setInterval(()=>{di(c).catch(()=>{})},bc),Co=setInterval(()=>{h.expireStale().becameEmpty&&Z()},Sc);return Co.unref?.(),{port:y,projectId:i,close:async()=>{clearInterval(vi),clearInterval(Co),z(),h.clear(),await E.destroyAsync(),C.destroy();for(let a of re)try{a.res.end()}catch{}return re.clear(),new Promise(a=>{We.close(()=>a())})}}}async function di(o){try{let e=await dc(o),n=Date.now();for(let t of e){let r=_e(o,t);try{let i=await pc(r);n-i.mtimeMs>xc&&await uc(r)}catch{}}}catch{}}var fe="\x1B[35m[popmelt]\x1B[0m";async function Jc(){let o=process.argv.slice(2);if(o[0]==="memory"){await Lc(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${fe} Usage: popmelt wrap -- <dev command>`),console.error(`${fe} Example: popmelt wrap -- next dev`),console.error(`${fe} Example: popmelt wrap -- astro dev`),process.exit(1));let n=o.slice(e+1);await Uc(n);return}if(o[0]==="bridge"){await Fc();return}if(o[0]==="stop"){await qc();return}console.log(`${fe} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function $t(o,e){let n=o.indexOf(e);return n>=0?o[n+1]:void 0}function Bc(){console.log(`${fe} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function Lc(o){if(o[0]!=="import"&&o[0]!=="review"){Bc(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=$t(o,"--project")??process.cwd(),n=$t(o,"--project-key"),t=await mt({projectRoot:e,projectKey:n});if(o[0]==="review"){let c=$t(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=Ft(t.bundle,{subjectHints:[c],action:$t(o,"--action"),maxPackets:Number($t(o,"--max-packets")??3),maxEstimatedTokens:Number($t(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${fe} Contextual memory review (read-only)`),console.log(`${fe} Subject: ${c}`),console.log(`${fe} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${fe} Uncertainty: ${d.uncertainty}`);for(let[p,x]of d.packets.entries())console.log(""),console.log(`${p+1}. ${x.proposal.claim}`),console.log(` Authority: ${x.authority}; presentation: ${x.presentation}; implementation: ${x.implementation.state}`),console.log(` Why now: ${x.trigger.reason}`),console.log(` Proposal: ${x.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(t.report,null,2));return}let r=t.report,i=r.proofCases.filter(c=>c.threadFound).length,s=r.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${fe} Legacy memory analysis (read-only)`),console.log(`${fe} Project: ${r.projectRoot}`),console.log(`${fe} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${fe} Imported: ${Object.entries(r.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${fe} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${fe} Model values deferred: ${r.deferredModelEntries}`),console.log(`${fe} Proof coverage: ${i}/${r.proofCases.length} threads found`),console.log(`${fe} Schema validation: ${s.length===0?"passed":`${s.length} errors`}`),r.issues.length){let c=new Map;for(let d of r.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${fe} Review flags: ${[...c].map(([d,p])=>`${d}=${p}`).join(", ")}`)}}async function Fc(){let o=await Eo({projectRoot:process.cwd()});console.log(`${fe} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
180
|
+
${fe} Shutting down bridge...`),await o.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function qc(){let o=Nc(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await Oc(o,"utf8"))}catch{console.log(`${fe} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${fe} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${fe} Bridge process ${e.pid} already dead`);else throw n}try{await Dc(o)}catch{}}async function Uc(o){let e=await Eo({projectRoot:process.cwd()});console.log(`${fe} Bridge running on http://localhost:${e.port}`);let[n,...t]=o;console.log(`${fe} Starting: ${o.join(" ")}`);let r=Cc(n,t,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=s=>{r.kill(s)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r.on("exit",async(s,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(s??0)})}Jc().catch(o=>{console.error(`${fe} Fatal:`,o),process.exit(1)});
|