@popmelt.com/core 0.17.0 → 0.18.1

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.
@@ -1,30 +1,30 @@
1
- import{a as ri,b as ii}from"./chunk-NOHXTT24.mjs";import{spawn as au}from"child_process";import{closeSync as du,openSync as cu}from"fs";import{appendFile as lu,mkdir as pu,readFile as uu,realpath as mu}from"fs/promises";import{dirname as fu,join as Zr}from"path";import{fileURLToPath as hu}from"url";function zt(n){return Ea(n).slice(0,12)}var ja=[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 Ea(n){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(n)):_a(n),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let g=7;g>=0;g--)e.push(t/Math.pow(2,g*8)&255);let o=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,d=2600822924,c=528734635,I=1541459225,v=new Array(64);for(let g=0;g<e.length;g+=64){for(let m=0;m<16;m++){let f=g+m*4;v[m]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let m=16;m<64;m++){let f=ct(v[m-15],7)^ct(v[m-15],18)^v[m-15]>>>3,M=ct(v[m-2],17)^ct(v[m-2],19)^v[m-2]>>>10;v[m]=v[m-16]+f+v[m-7]+M>>>0}let k=o,b=r,h=i,p=s,y=a,w=d,u=c,x=I;for(let m=0;m<64;m++){let f=ct(y,6)^ct(y,11)^ct(y,25),M=y&w^~y&u,$=x+f+M+ja[m]+v[m]>>>0,E=ct(k,2)^ct(k,13)^ct(k,22),F=k&b^k&h^b&h,Y=E+F>>>0;x=u,u=w,w=y,y=p+$>>>0,p=h,h=b,b=k,k=$+Y>>>0}o=o+k>>>0,r=r+b>>>0,i=i+h>>>0,s=s+p>>>0,a=a+y>>>0,d=d+w>>>0,c=c+u>>>0,I=I+x>>>0}return[o,r,i,s,a,d,c,I].map(g=>g.toString(16).padStart(8,"0")).join("")}function ct(n,e){return n>>>e|n<<32-e}function _a(n){let e=[];for(let t=0;t<n.length;t++){let o=n.charCodeAt(t);o<128?e.push(o):o<2048?e.push(192|o>>6,128|o&63):e.push(224|o>>12,128|o>>6&63,128|o&63)}return e}var si={name:"@popmelt.com/core",version:"0.17.0",description:"A tiny, powerful design layer for humans and AI",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 . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0",three:">=0.150.0"},peerDependenciesMeta:{next:{optional:!0},three:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitest/coverage-v8":"3.2.4",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",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.6",vitest:"^3.2.4"}};var mt=si.version;import{execFileSync as Ep,spawn as ua}from"child_process";import{randomUUID as yt}from"crypto";import{mkdir as _p,readFile as Cp,readdir as $p,realpath as Op,stat as wa,unlink as Dp,writeFile as Ko}from"fs/promises";import{createServer as Np}from"http";import{tmpdir as Bp}from"os";import{basename as Ho,isAbsolute as Yr,join as it,relative as Jp,resolve as qp}from"path";function ai(n){let e=n.instruction?.trim();return e?n.attachments?.some(o=>o.name?.trim()===e)?null:e:null}function Zo(n,e){let t=n?.tagName?.toLowerCase(),o=n?.id?`#${n.id}`:"",r=n?.className?`.${n.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=t?`${t}${o}${r}`:e;return n?.reactComponent?`<${n.reactComponent}> ${i}`:i}function $a(n){let e=n.elements?.[0]?.reactComponent||n.elements?.[0]?.tagName||n.linkedSelector,t=n.type&&n.type!=="annotation"?`${n.type} annotation`:"Annotation";return e?`${t} on ${e}`:t}function di(n){let e=n.annotations.map(r=>({kind:"annotation",annotationId:r.id,pathname:r.pathname,text:ai(r)??$a(r)})),t=new Map,o=r=>{let i=`${r.pathname??""}:${r.durableSelector??r.selector}`,s=t.get(i);if(s){s.changes.push(r.text),r.annotationNumber!==void 0&&(s.annotationNumber===void 0||r.annotationNumber<s.annotationNumber)&&(s.annotationNumber=r.annotationNumber);return}let a={kind:"changes",elementKey:i,elementLabel:Zo(r.element,r.selector),...r.annotationNumber!==void 0?{annotationNumber:r.annotationNumber}:{},pathname:r.pathname,changes:[r.text]};t.set(i,a),e.push(a)};for(let r of n.styleModifications??[])for(let i of r.changes)o({...r,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let r of n.textModifications??[])o({...r,text:`Text: ${r.original||"empty"} \u2192 ${r.modified||"empty"}`});for(let r of n.domModifications??[])o({...r,text:r.operation==="copy"?"Copied element":"Moved element"});return n.spacingTokenChanges?.length&&e.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:n.spacingTokenChanges.map(r=>`${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`)}),e}function ci(n){let e=n.annotations.flatMap(r=>{let i=ai(r);return i?[{instruction:i,pathname:r.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(r=>r.pathname).filter(Boolean)).size<=1)return e.map(r=>r.instruction).join(`
1
+ import{a as ii,b as si}from"./chunk-NOHXTT24.mjs";import{spawn as du}from"child_process";import{closeSync as cu,openSync as lu}from"fs";import{appendFile as pu,mkdir as uu,readFile as mu,realpath as fu}from"fs/promises";import{dirname as hu,join as ei}from"path";import{fileURLToPath as gu}from"url";function zt(n){return Ca(n).slice(0,12)}var _a=[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 Ca(n){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(n)):$a(n),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let g=7;g>=0;g--)e.push(t/Math.pow(2,g*8)&255);let o=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,d=2600822924,c=528734635,y=1541459225,w=new Array(64);for(let g=0;g<e.length;g+=64){for(let m=0;m<16;m++){let f=g+m*4;w[m]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let m=16;m<64;m++){let f=ct(w[m-15],7)^ct(w[m-15],18)^w[m-15]>>>3,M=ct(w[m-2],17)^ct(w[m-2],19)^w[m-2]>>>10;w[m]=w[m-16]+f+w[m-7]+M>>>0}let S=o,b=r,h=i,p=s,I=a,v=d,u=c,x=y;for(let m=0;m<64;m++){let f=ct(I,6)^ct(I,11)^ct(I,25),M=I&v^~I&u,$=x+f+M+_a[m]+w[m]>>>0,E=ct(S,2)^ct(S,13)^ct(S,22),F=S&b^S&h^b&h,Y=E+F>>>0;x=u,u=v,v=I,I=p+$>>>0,p=h,h=b,b=S,S=$+Y>>>0}o=o+S>>>0,r=r+b>>>0,i=i+h>>>0,s=s+p>>>0,a=a+I>>>0,d=d+v>>>0,c=c+u>>>0,y=y+x>>>0}return[o,r,i,s,a,d,c,y].map(g=>g.toString(16).padStart(8,"0")).join("")}function ct(n,e){return n>>>e|n<<32-e}function $a(n){let e=[];for(let t=0;t<n.length;t++){let o=n.charCodeAt(t);o<128?e.push(o):o<2048?e.push(192|o>>6,128|o&63):e.push(224|o>>12,128|o>>6&63,128|o&63)}return e}var ai={name:"@popmelt.com/core",version:"0.18.1",description:"A tiny, powerful design layer for humans and AI",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,packageManager:"pnpm@9.12.0",engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && node scripts/check-eslint-suppressions.mjs","pack:smoke":"node scripts/pack-smoke.mjs","peer:smoke":"node scripts/peer-compat-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:coverage":"vitest run --coverage.enabled","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run format && pnpm run lint && pnpm run test:coverage && pnpm run build && pnpm run pack:smoke"},exports:{".":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./next":{types:"./dist/plugin-next.d.mts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"},"./media":{types:"./dist/media.d.mts",import:"./dist/media.mjs"},"./three":{types:"./dist/adapter-three.d.mts",import:"./dist/adapter-three.mjs"},"./react-three-fiber":{types:"./dist/adapter-react-three-fiber.d.mts",import:"./dist/adapter-react-three-fiber.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.3"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0","@react-three/fiber":">=8.0.0",three:">=0.150.0"},peerDependenciesMeta:{next:{optional:!0},"@react-three/fiber":{optional:!0},three:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@react-three/fiber":"9.7.0","@tanstack/react-router":"1.120.5","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/three":"^0.185.4","@types/ws":"8.18.1","@vitejs/plugin-react":"^5.1.1","@vitest/coverage-v8":"3.2.4",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.5.24",prettier:"3.5.3",react:"19.1.0","react-dom":"19.1.0",three:"^0.185.1",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.6",vitest:"3.2.4"}};var mt=ai.version;import{execFileSync as _p,spawn as fa}from"child_process";import{randomUUID as yt}from"crypto";import{mkdir as Cp,readFile as $p,readdir as Op,realpath as Dp,stat as ba,unlink as Np,writeFile as Ko}from"fs/promises";import{createServer as Bp}from"http";import{tmpdir as Jp}from"os";import{basename as Ho,isAbsolute as Zr,join as it,relative as qp,resolve as Lp}from"path";function di(n){let e=n.instruction?.trim();return e?n.attachments?.some(o=>o.name?.trim()===e)?null:e:null}function Zo(n,e){let t=n?.tagName?.toLowerCase(),o=n?.id?`#${n.id}`:"",r=n?.className?`.${n.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=t?`${t}${o}${r}`:e;return n?.reactComponent?`<${n.reactComponent}> ${i}`:i}function Da(n){let e=n.elements?.[0]?.reactComponent||n.elements?.[0]?.tagName||n.linkedSelector,t=n.type&&n.type!=="annotation"?`${n.type} annotation`:"Annotation";return e?`${t} on ${e}`:t}function ci(n){let e=n.annotations.map(r=>{let i=r.interactionEpisode?.steps.length??0;return{kind:"annotation",annotationId:r.id,pathname:r.pathname,text:di(r)??Da(r),...i>0?{interactionEpisodeStepCount:i}:{}}}),t=new Map,o=r=>{let i=`${r.pathname??""}:${r.durableSelector??r.selector}`,s=t.get(i);if(s){s.changes.push(r.text),r.annotationNumber!==void 0&&(s.annotationNumber===void 0||r.annotationNumber<s.annotationNumber)&&(s.annotationNumber=r.annotationNumber);return}let a={kind:"changes",elementKey:i,elementLabel:Zo(r.element,r.selector),...r.annotationNumber!==void 0?{annotationNumber:r.annotationNumber}:{},pathname:r.pathname,changes:[r.text]};t.set(i,a),e.push(a)};for(let r of n.styleModifications??[])for(let i of r.changes)o({...r,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let r of n.textModifications??[])o({...r,text:`Text: ${r.original||"empty"} \u2192 ${r.modified||"empty"}`});for(let r of n.domModifications??[])o({...r,text:r.operation==="copy"?"Copied element":"Moved element"});return n.spacingTokenChanges?.length&&e.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:n.spacingTokenChanges.map(r=>`${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`)}),e}function li(n){let e=n.annotations.flatMap(r=>{let i=di(r);return i?[{instruction:i,pathname:r.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(r=>r.pathname).filter(Boolean)).size<=1)return e.map(r=>r.instruction).join(`
2
2
 
3
3
  `);let o=new Map;for(let r of e){let i=r.pathname||"(unknown)",s=o.get(i)??[];s.push(r.instruction),o.set(i,s)}return[...o.entries()].map(([r,i])=>`\`${r}\`
4
4
  ${i.map(s=>`- ${s}`).join(`
5
5
  `)}`).join(`
6
- `)}var Oa=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Da=new Set(["default","flex","fast","priority"]);function Gt(n){let e=typeof n.reasoningEffort=="string"&&Oa.has(n.reasoningEffort)?n.reasoningEffort:void 0,t=typeof n.serviceTier=="string"&&Da.has(n.serviceTier)?n.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function oo(n){let e=[];return n?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(n.reasoningEffort)}`),n?.serviceTier&&e.push(`service_tier=${JSON.stringify(n.serviceTier)}`),e}import{createHash as ec,randomUUID as tc}from"crypto";import{isAbsolute as nc,relative as oc}from"path";import{randomUUID as ht}from"crypto";function er(n,e){return{storeId:n,explanationId:e}}function Na(n,e){let{fromId:t,toId:o,toStoreId:r,...i}=e;return{...i,from:er(n,t),to:er(r??n,o)}}var li={project:0,route:1,component:2,selector:2,file:3},pi={intention:0,principle:1,pattern:2};function Wt(n,e){let t=li[n.scope.kind]-li[e.scope.kind];return t!==0?t:pi[n.kind]-pi[e.kind]}function ui(n){return n==="expresses"||n==="excepts"}function Ba(n,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=n.explanations.find(i=>i.id===e.fromId),o=n.explanations.find(i=>i.id===e.toId);if(!t||!o)return;let r=Wt(t,o);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function Et(n){let e=structuredClone(n),t=new Set;return e.relations=n.relations.flatMap(o=>{let r=Ba(n,o);if(!r)return[];let i=`${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`;return t.has(i)?[]:(t.add(i),[r])}),e}import{createHash as Ja}from"crypto";import{mkdir as qa,open as La,readFile as mi,readdir as Fa,rename as Ua,unlink as za}from"fs/promises";import{dirname as Ga,join as Vt}from"path";function Ge(n){return structuredClone(n)}function fi(n){return Ja("sha256").update(JSON.stringify(n)).digest("hex")}async function _t(n,e){await qa(Ga(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await La(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
7
- `,"utf8"),await o.sync()}finally{await o.close()}try{await Ua(t,n)}catch(r){throw await za(t).catch(()=>{}),r}}function Wa(n,e){return{version:1,projectId:n,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Va(n,e){let t=n.explanations.findIndex(o=>o.id===e.id);t>=0?n.explanations[t]=Ge(e):n.explanations.push(Ge(e))}function ro(n,e){let t=Ge(n);for(let o of e)if(o.op==="add_explanation"){if(t.explanations.some(r=>r.id===o.explanation.id))throw new Error(`Imprint explanation already exists: ${o.explanation.id}`);t.explanations.push(Ge(o.explanation))}else if(o.op==="replace_explanation")Va(t,o.explanation);else if(o.op==="remove_explanation")t.explanations=t.explanations.filter(r=>r.id!==o.explanationId),t.relations=t.relations.filter(r=>r.fromId!==o.explanationId&&(r.toStoreId!==void 0||r.toId!==o.explanationId));else if(o.op==="add_concrete")t.concrete.some(r=>r.id===o.concrete.id)||t.concrete.push(Ge(o.concrete));else if(o.op==="remove_concrete")t.concrete=t.concrete.filter(r=>r.id!==o.concreteId),t.relations=t.relations.filter(r=>r.fromId!==o.concreteId&&(r.toStoreId!==void 0||r.toId!==o.concreteId));else if(o.op==="add_evidence"){let r=t.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);r.evidence.some(i=>i.id===o.evidence.id)||(r.evidence.push(Ge(o.evidence)),r.updatedAt=o.evidence.createdAt)}else if(o.op==="revise_explanation"){let r=t.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);Object.assign(r,Ge(o.patch),{updatedAt:o.updatedAt})}else if(o.op==="add_relation"){let r=o.relation,i=t.explanations.find(I=>I.id===r.fromId),s=!!r.toStoreId,a=s?void 0:t.explanations.find(I=>I.id===r.toId),d=t.concrete.some(I=>I.id===r.fromId),c=!s&&t.concrete.some(I=>I.id===r.toId);if(ui(r.type)){if(!(r.type==="expresses"?s?!!i:!!((i||d)&&a):!!(i&&(a||s))))throw new Error(`Imprint ${r.type} relation has invalid endpoints: ${r.id}`);if(t.relations.some(v=>v.type===r.type&&v.fromId===r.fromId&&v.toStoreId===r.toStoreId&&v.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`);if(r.type==="expresses"&&i&&a){if(Wt(i,a)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let v=new Map;for(let b of t.relations)b.type!=="expresses"||b.toStoreId||v.set(b.fromId,[...v.get(b.fromId)??[],b.toId]);let g=[r.toId],k=new Set;for(;g.length;){let b=g.pop();if(b===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);k.has(b)||(k.add(b),g.push(...v.get(b)??[]))}}}else if(!i||!a&&!c)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);t.relations.some(I=>I.id===r.id)||t.relations.push(Ge(r))}else o.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==o.relationId));return t}function Ka(n,e){let t=[],o=Ge(n);for(let r of e){if(r.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=o.explanations.find(s=>s.id===r.explanationId);i&&t.unshift({op:"add_explanation",explanation:Ge(i)})}else if(r.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=o.concrete.find(s=>s.id===r.concreteId);i&&t.unshift({op:"add_concrete",concrete:Ge(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=o.explanations.find(a=>a.id===i);s&&t.unshift({op:"replace_explanation",explanation:Ge(s)})}else if(r.op==="add_relation")t.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=o.relations.find(s=>s.id===r.relationId);i&&t.unshift({op:"add_relation",relation:Ge(i)})}o=ro(o,[r])}return t}function hi(n){return n.op==="add_explanation"||n.op==="replace_explanation"?[n.explanation.id]:n.op==="remove_explanation"||n.op==="add_evidence"||n.op==="revise_explanation"?[n.explanationId]:n.op==="add_relation"?[n.relation.fromId,...n.relation.toStoreId?[]:[n.relation.toId]]:[]}var Kt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Vt(e,".popmelt","imprint"),this.manifestPath=Vt(this.imprintDir,"manifest.json"),this.graphPath=Vt(this.imprintDir,"graph.json"),this.journalDir=Vt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await mi(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 t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),o=(await Fa(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=Wa(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<o.length;a++){let d=JSON.parse(await mi(Vt(this.journalDir,o[a]),"utf8")),{hash:c,...I}=d;if(d.sequence!==a+1||d.previousHash!==s||c!==fi(I))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=ro(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 load(){let e=await this.loadRaw();return{...e,graph:Et(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),o=Et(t.graph),r=new Map(o.relations.map(s=>[s.id,s])),i=[];for(let s of t.graph.relations){let a=r.get(s.id);a&&a.type===s.type&&a.fromId===s.fromId&&a.toStoreId===s.toStoreId&&a.toId===s.toId||(i.push({op:"remove_relation",relationId:s.id}),a&&i.push({op:"add_relation",relation:a}))}if(i.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:i}),{migrated:!0,relationMutations:i.length}}return await _t(this.graphPath,o),await _t(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let o=await this.load();if(o.transactions.some(v=>v.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=o.graph.head.sequence+1,i=Ka(o.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:o.graph.head.hash,source:e.source,summary:e.summary,mutations:Ge(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:fi(s)},d=ro(o.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let c=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await _t(Vt(this.journalDir,c),a);let I={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await _t(this.graphPath,d),await _t(this.manifestPath,I),t={graph:d,transaction:a}}),await this.writeChain,t}async undo(e,t,o,r){let i=await this.load(),s=i.transactions.find(c=>c.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(c=>c.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(hi));if(i.transactions.filter(c=>c.sequence>s.sequence).some(c=>c.mutations.some(I=>hi(I).some(v=>a.has(v)))))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:o,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await _t(this.graphPath,e.graph),await _t(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Ha=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Qa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only","consistent","match","matched","matching","mirror","mirrored","mirroring","align","aligned","aligning"]),Xa=[/\bconsistent\s+with\b/i,/\bmatch(?:es|ed|ing)?\b/i,/\bmirror(?:s|ed|ing)?\b/i,/\bthe\s+same\s+as\b/i,/\bborrow(?:s|ed|ing)?\s+from\b/i,/\balign(?:s|ed|ing)?\s+with\b/i,/\b(?:more|look|looks|feel|feels|behave|behaves)\s+like\b/i],Ya=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function nr(n){return!!(n&&Ya.test(n))}function Za(n){return n.scope.kind==="project"||nr(`${n.statement} ${n.rationale}`)}function ed(n){let e=n?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function td(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function nd(n){return n.length>4&&n.endsWith("ies")?[n,`${n.slice(0,-3)}y`]:n.length>3&&n.endsWith("s")&&!n.endsWith("ss")?[n,n.slice(0,-1)]:[n]}function ft(n){return new Set(td(n).split(" ").filter(e=>e.length>2&&!Qa.has(e)).flatMap(nd))}function gi(n){return n.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function od(n){if(n)for(let e of Xa){let t=e.exec(n);if(!t||t.index<=0)continue;let o=gi(n.slice(0,t.index)),r=gi(n.slice(t.index+t[0].length));if(o&&r)return{target:o,reference:r}}}function St(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function tr(n){return!n||!Array.isArray(n.values)||n.values.length===0?{kind:"project",values:["*"]}:{kind:n.kind,values:[...new Set(n.values.map(e=>e.trim()).filter(Boolean))]}}function Tt(n,e,t){return{id:ht(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:n.threadId,jobId:n.jobId,createdAt:n.occurredAt??new Date().toISOString()}}function Se(n,e=800){return typeof n=="string"?n.trim().slice(0,e):""}function yi(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(o=>typeof o=="string"&&!!o.trim());return t.length?{kind:e.kind,values:t}:void 0}function Ii(n,e,t){if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,s=Se(i.explanationId,100),a=Se(i.clientId,100),d=Se(i.storeId,100);if(s&&a)throw new Error("relation endpoint must use either explanationId or clientId, not both");let c=s||a;return c?{explanationId:c,...d?{storeId:d}:{}}:void 0}let o=Se(e,100),r=Se(t,100);return o?{explanationId:o,...r?{storeId:r}:{}}:void 0}function wi(n,e){if(!n||!e.trim())return{found:!1};let t=n;for(let o of e.split(".").filter(Boolean))if(Array.isArray(t)){let r=Number(o);if(!Number.isInteger(r)||r<0||r>=t.length)return{found:!1};t=t[r]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,o))t=t[o];else return{found:!1};return{found:!0,value:t}}function Ht(n,e={}){let t=[...n.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],o=n.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),r=t.at(-1)?.[1],i,s=[];if(r)i=r;else{let d=[...n.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:o,error:"imprint assessment is missing"};try{let c=JSON.parse(d);if(!c||typeof c!="object"||Array.isArray(c)||!Object.prototype.hasOwnProperty.call(c,"imprint"))return{visibleText:o,error:"imprint assessment is missing"};let I=c;i=I.imprint,s=Array.isArray(I.annotations)?I.annotations:[]}catch{return{visibleText:o,error:"resolution envelope is invalid"}}}try{let a=typeof i=="string"?JSON.parse(i):i;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("imprint assessment is invalid");if(a.decision==="none"){let h=String(a.reason);if(!Ha.has(h))throw new Error("imprint no-op reason is invalid");if(h==="task_specific_detail"&&s.some(M=>{if(!M||typeof M!="object"||Array.isArray(M))return!1;let $=M;return($.finalScope??$.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(a.usedExplanationIds)?a.usedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[],y=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[],w=new Set(e.context?.explanations.map(M=>M.id)??[]);if([...new Set([...p,...y])].some(M=>!w.has(M)))throw new Error("imprint use must cite only surfaced explanations");let x=[...new Set([...p,...e.applicationOccurred?[]:y])],m=e.applicationOccurred?y:[],f;if(m.length){f=m;let M=new Set(e.context?.pendingGroundingExplanationIds??[]),$=m.filter(E=>{let F=e.context?.explanations.find(Y=>Y.id===E);return w.has(E)&&F&&(F.state==="emerging"||F.state==="testing")&&!M.has(E)});if($.length){let E=a.grounding,F=typeof E?.explanationId=="string"&&$.includes(E.explanationId)?E.explanationId:$[0],Y=Se(E?.question,300);return{draft:{decision:"apply",summary:{title:Se(a.summary?.title,120)||"Applied shared understanding",detail:Se(a.summary?.detail,500)||Se(e.requestText||o,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:m,grounding:{explanationId:F,question:Y||"Does applying this understanding here match your intent?"}},visibleText:o}}}if(h==="duplicate"){let M=Se(a.duplicateOfExplanationId,100),$=a.scopeComparison;if(!M)throw new Error("duplicate assessment requires duplicateOfExplanationId");if($!=="equivalent"&&$!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let E=e.context?.explanations.find(F=>F.id===M);if(!E)throw new Error("duplicate assessment must cite a surfaced explanation");if(nr(e.requestText)&&!Za(E))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:h,duplicateOfExplanationId:M,scopeComparison:$,...x.length?{usedExplanationIds:x}:{},...f?{appliedExplanationIds:f}:{}},visibleText:o}}return{draft:{decision:"none",reason:h,...x.length?{usedExplanationIds:x}:{},...f?{appliedExplanationIds:f}:{}},visibleText:o}}if(a.decision==="recognize"){let h=Se(a.explanationId,100);if(!h)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(u=>u.id===h);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let y=a.summary,w={title:Se(y?.title,120),detail:Se(y?.detail,500)};if(!w.title||!w.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:h,summary:w},visibleText:o}}if(a.decision==="apply"){let h=a.summary,p={title:Se(h?.title,120),detail:Se(h?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let y=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[];if(!y.length)throw new Error("application requires appliedExplanationIds");let w=new Map(e.context?.explanations.map(M=>[M.id,M])??[]);if(y.some(M=>!w.has(M)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(y)]},visibleText:o};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),x=y.filter(M=>{let $=w.get(M);return $&&($.state==="emerging"||$.state==="testing")&&!u.has(M)});if(!x.length){if(y.every($=>w.get($)?.state==="grounded"||u.has($)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:y},visibleText:o};throw new Error("application must cite a surfaced ungrounded explanation")}let m=a.grounding,f=typeof m?.explanationId=="string"&&x.includes(m.explanationId)?m.explanationId:x[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:y,grounding:{explanationId:f,question:Se(m?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:o}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,c=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(c)))throw new Error("summary.kind is invalid");let I={kind:c,title:Se(d?.title,120),detail:Se(d?.detail,500)};if(!I.title||!I.detail)throw new Error("summary title and detail are required");let v=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(h=>typeof h=="string"&&!!h.trim()):[],g=[];for(let h of Array.isArray(a.mutations)?a.mutations:[]){if(!h||typeof h!="object")continue;let p=h;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let y=Se(p.statement),w=Se(p.rationale);if(!y||!w)continue;g.push({op:"add",clientId:Se(p.clientId,100)||void 0,kind:p.kind,statement:y,rationale:w,scope:yi(p.scope),rootReason:Se(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let y={op:"revise",explanationId:p.explanationId,statement:Se(p.statement)||void 0,rationale:Se(p.rationale)||void 0,scope:yi(p.scope),reopenGrounding:p.reopenGrounding===!0};(y.statement||y.rationale||y.scope||y.reopenGrounding)&&g.push(y)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let y=Se(p.summary);y&&g.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:y})}else if(p.op==="relation"){if(!["expresses","excepts"].includes(String(p.type)))throw new Error("relation type is invalid");let y=Se(p.rationale),w=Ii(p.from,p.fromId,p.fromStoreId),u=Ii(p.to,p.toId,p.toStoreId);if(!y)throw new Error("relation rationale is required");if(!w||!u)throw new Error("relation endpoints require an explanationId or clientId");g.push({op:"relation",type:p.type,from:w,to:u,rationale:y})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let y=Se(p.reason);y&&g.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:y})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let y=Se(p.modelPath,300);y&&g.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:y,rationale:Se(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&g.push({op:"retire",explanationId:p.explanationId,reason:Se(p.reason)})}let k=a.grounding,b=k&&typeof k.explanationId=="string"&&Se(k.question)?{explanationId:k.explanationId,question:Se(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:I,appliedExplanationIds:v,mutations:g,grounding:b},visibleText:o}}catch(a){return{visibleText:o,error:a instanceof Error?a.message:String(a)}}}function Qt(n,e={}){let t=n?.explanations??[],o=new Set(n?.pendingGroundingExplanationIds??[]),r=new Set(n?.correctionExplanationIds??[]),i=nr(e.requestText),s=n?.retrievalIntent,a=n?.historicalCaveats??[],d=t.find(g=>g.storeId&&!g.readOnly)?.storeId,c=(g,k)=>{let b=g[k];return b?`[${b.storeId}] ${b.explanationId}`:k==="from"?g.fromId:g.toId},I=!!n?.relations?.some(g=>g.from&&g.to&&g.from.storeId!==g.to.storeId),v=t.some(g=>g.readOnly);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.",...t.length?["","Relevant explanations from the project imprint:",...t.map((g,k)=>[`${k+1}. [${g.state}; ${g.kind}] ${g.statement}`,` - Why: ${g.rationale}`,` - Scope: ${g.scope.kind} ${g.scope.values.join(", ")}`,` - Explanation: ${g.id}`,...g.storeId?[` - Store: ${g.storeId}${g.readOnly?" (read-only)":" (writable primary)"}`]:[],...o.has(g.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(g.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...g.concrete.map(b=>` - Concrete terminal: ${b.modelPath} = ${JSON.stringify(b.value)}`)].join(`
8
- `)),...n?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...n?.relations?.length?["","Known explanation topology:",...n.relations.map(g=>`- ${g.storeId?`[owned by ${g.storeId}${g.readOnly?"; read-only":""}] `:""}${c(g,"from")} --${g.type}--> ${c(g,"to")}: ${g.rationale}`)]:[],...v||I?["","Store-qualified topology remains locally owned: the relation must originate at an explanation in the writable primary store, while its target may be in a mounted read-only store. Never proxy a relation whose source belongs to a mounted store.",`For a cross-store relation, use qualified endpoints: {"op":"relation","type":"expresses|excepts","from":{"storeId":"${d??"<writable-primary-store>"}","clientId":"<new-specific-client-id>"},"to":{"storeId":"<mounted-target-store>","explanationId":"<existing-abstract-target-id>"},"rationale":"<why>"}. Use clientId for a new explanation created in this transaction and explanationId for an existing durable explanation.`]:[],...s?["","Explicit pattern transfer detected:",`- Target: ${s.target}`,`- Reference: ${s.reference}`,"Before editing, state which dimensions you intend to transfer from the reference and which target-specific behavior you will preserve. Compare the relevant surface, spacing, typography, radius, and interaction behavior; transfer only the dimensions supported by the request and evidence. If the intended transfer remains materially ambiguous after inspecting both anchors, ask one focused question."]:[],...a.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...a.map((g,k)=>[`${k+1}. [challenged; ${g.kind}] ${g.statement}`,` - Why it was previously proposed: ${g.rationale}`,` - Scope: ${g.scope.kind} ${g.scope.values.join(", ")}`,` - Historical explanation: ${g.id}`,...g.storeId?[` - Store: ${g.storeId}${g.readOnly?" (read-only)":" (writable primary)"}`]:[]].join(`
6
+ `)}var Na=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ba=new Set(["default","flex","fast","priority"]);function Gt(n){let e=typeof n.reasoningEffort=="string"&&Na.has(n.reasoningEffort)?n.reasoningEffort:void 0,t=typeof n.serviceTier=="string"&&Ba.has(n.serviceTier)?n.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function oo(n){let e=[];return n?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(n.reasoningEffort)}`),n?.serviceTier&&e.push(`service_tier=${JSON.stringify(n.serviceTier)}`),e}import{createHash as nc,randomUUID as oc}from"crypto";import{isAbsolute as rc,relative as ic}from"path";import{randomUUID as ht}from"crypto";function er(n,e){return{storeId:n,explanationId:e}}function Ja(n,e){let{fromId:t,toId:o,toStoreId:r,...i}=e;return{...i,from:er(n,t),to:er(r??n,o)}}var pi={project:0,route:1,component:2,selector:2,file:3},ui={intention:0,principle:1,pattern:2};function Wt(n,e){let t=pi[n.scope.kind]-pi[e.scope.kind];return t!==0?t:ui[n.kind]-ui[e.kind]}function mi(n){return n==="expresses"||n==="excepts"}function qa(n,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=n.explanations.find(i=>i.id===e.fromId),o=n.explanations.find(i=>i.id===e.toId);if(!t||!o)return;let r=Wt(t,o);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function Et(n){let e=structuredClone(n),t=new Set;return e.relations=n.relations.flatMap(o=>{let r=qa(n,o);if(!r)return[];let i=`${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`;return t.has(i)?[]:(t.add(i),[r])}),e}import{createHash as La}from"crypto";import{mkdir as Fa,open as Ua,readFile as fi,readdir as za,rename as Ga,unlink as Wa}from"fs/promises";import{dirname as Va,join as Vt}from"path";function Ge(n){return structuredClone(n)}function hi(n){return La("sha256").update(JSON.stringify(n)).digest("hex")}async function _t(n,e){await Fa(Va(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await Ua(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
7
+ `,"utf8"),await o.sync()}finally{await o.close()}try{await Ga(t,n)}catch(r){throw await Wa(t).catch(()=>{}),r}}function Ka(n,e){return{version:1,projectId:n,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Ha(n,e){let t=n.explanations.findIndex(o=>o.id===e.id);t>=0?n.explanations[t]=Ge(e):n.explanations.push(Ge(e))}function ro(n,e){let t=Ge(n);for(let o of e)if(o.op==="add_explanation"){if(t.explanations.some(r=>r.id===o.explanation.id))throw new Error(`Imprint explanation already exists: ${o.explanation.id}`);t.explanations.push(Ge(o.explanation))}else if(o.op==="replace_explanation")Ha(t,o.explanation);else if(o.op==="remove_explanation")t.explanations=t.explanations.filter(r=>r.id!==o.explanationId),t.relations=t.relations.filter(r=>r.fromId!==o.explanationId&&(r.toStoreId!==void 0||r.toId!==o.explanationId));else if(o.op==="add_concrete")t.concrete.some(r=>r.id===o.concrete.id)||t.concrete.push(Ge(o.concrete));else if(o.op==="remove_concrete")t.concrete=t.concrete.filter(r=>r.id!==o.concreteId),t.relations=t.relations.filter(r=>r.fromId!==o.concreteId&&(r.toStoreId!==void 0||r.toId!==o.concreteId));else if(o.op==="add_evidence"){let r=t.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);r.evidence.some(i=>i.id===o.evidence.id)||(r.evidence.push(Ge(o.evidence)),r.updatedAt=o.evidence.createdAt)}else if(o.op==="revise_explanation"){let r=t.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);Object.assign(r,Ge(o.patch),{updatedAt:o.updatedAt})}else if(o.op==="add_relation"){let r=o.relation,i=t.explanations.find(y=>y.id===r.fromId),s=!!r.toStoreId,a=s?void 0:t.explanations.find(y=>y.id===r.toId),d=t.concrete.some(y=>y.id===r.fromId),c=!s&&t.concrete.some(y=>y.id===r.toId);if(mi(r.type)){if(!(r.type==="expresses"?s?!!i:!!((i||d)&&a):!!(i&&(a||s))))throw new Error(`Imprint ${r.type} relation has invalid endpoints: ${r.id}`);if(t.relations.some(w=>w.type===r.type&&w.fromId===r.fromId&&w.toStoreId===r.toStoreId&&w.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`);if(r.type==="expresses"&&i&&a){if(Wt(i,a)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let w=new Map;for(let b of t.relations)b.type!=="expresses"||b.toStoreId||w.set(b.fromId,[...w.get(b.fromId)??[],b.toId]);let g=[r.toId],S=new Set;for(;g.length;){let b=g.pop();if(b===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);S.has(b)||(S.add(b),g.push(...w.get(b)??[]))}}}else if(!i||!a&&!c)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);t.relations.some(y=>y.id===r.id)||t.relations.push(Ge(r))}else o.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==o.relationId));return t}function Qa(n,e){let t=[],o=Ge(n);for(let r of e){if(r.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=o.explanations.find(s=>s.id===r.explanationId);i&&t.unshift({op:"add_explanation",explanation:Ge(i)})}else if(r.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=o.concrete.find(s=>s.id===r.concreteId);i&&t.unshift({op:"add_concrete",concrete:Ge(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=o.explanations.find(a=>a.id===i);s&&t.unshift({op:"replace_explanation",explanation:Ge(s)})}else if(r.op==="add_relation")t.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=o.relations.find(s=>s.id===r.relationId);i&&t.unshift({op:"add_relation",relation:Ge(i)})}o=ro(o,[r])}return t}function gi(n){return n.op==="add_explanation"||n.op==="replace_explanation"?[n.explanation.id]:n.op==="remove_explanation"||n.op==="add_evidence"||n.op==="revise_explanation"?[n.explanationId]:n.op==="add_relation"?[n.relation.fromId,...n.relation.toStoreId?[]:[n.relation.toId]]:[]}var Kt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Vt(e,".popmelt","imprint"),this.manifestPath=Vt(this.imprintDir,"manifest.json"),this.graphPath=Vt(this.imprintDir,"graph.json"),this.journalDir=Vt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await fi(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 t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),o=(await za(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=Ka(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<o.length;a++){let d=JSON.parse(await fi(Vt(this.journalDir,o[a]),"utf8")),{hash:c,...y}=d;if(d.sequence!==a+1||d.previousHash!==s||c!==hi(y))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=ro(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 load(){let e=await this.loadRaw();return{...e,graph:Et(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),o=Et(t.graph),r=new Map(o.relations.map(s=>[s.id,s])),i=[];for(let s of t.graph.relations){let a=r.get(s.id);a&&a.type===s.type&&a.fromId===s.fromId&&a.toStoreId===s.toStoreId&&a.toId===s.toId||(i.push({op:"remove_relation",relationId:s.id}),a&&i.push({op:"add_relation",relation:a}))}if(i.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:i}),{migrated:!0,relationMutations:i.length}}return await _t(this.graphPath,o),await _t(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let o=await this.load();if(o.transactions.some(w=>w.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=o.graph.head.sequence+1,i=Qa(o.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:o.graph.head.hash,source:e.source,summary:e.summary,mutations:Ge(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:hi(s)},d=ro(o.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let c=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await _t(Vt(this.journalDir,c),a);let y={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await _t(this.graphPath,d),await _t(this.manifestPath,y),t={graph:d,transaction:a}}),await this.writeChain,t}async undo(e,t,o,r){let i=await this.load(),s=i.transactions.find(c=>c.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(c=>c.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(gi));if(i.transactions.filter(c=>c.sequence>s.sequence).some(c=>c.mutations.some(y=>gi(y).some(w=>a.has(w)))))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:o,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await _t(this.graphPath,e.graph),await _t(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Xa=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ya=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only","consistent","match","matched","matching","mirror","mirrored","mirroring","align","aligned","aligning"]),Za=[/\bconsistent\s+with\b/i,/\bmatch(?:es|ed|ing)?\b/i,/\bmirror(?:s|ed|ing)?\b/i,/\bthe\s+same\s+as\b/i,/\bborrow(?:s|ed|ing)?\s+from\b/i,/\balign(?:s|ed|ing)?\s+with\b/i,/\b(?:more|look|looks|feel|feels|behave|behaves)\s+like\b/i],ed=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function nr(n){return!!(n&&ed.test(n))}function td(n){return n.scope.kind==="project"||nr(`${n.statement} ${n.rationale}`)}function nd(n){let e=n?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function od(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function rd(n){return n.length>4&&n.endsWith("ies")?[n,`${n.slice(0,-3)}y`]:n.length>3&&n.endsWith("s")&&!n.endsWith("ss")?[n,n.slice(0,-1)]:[n]}function ft(n){return new Set(od(n).split(" ").filter(e=>e.length>2&&!Ya.has(e)).flatMap(rd))}function yi(n){return n.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function id(n){if(n)for(let e of Za){let t=e.exec(n);if(!t||t.index<=0)continue;let o=yi(n.slice(0,t.index)),r=yi(n.slice(t.index+t[0].length));if(o&&r)return{target:o,reference:r}}}function St(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function tr(n){return!n||!Array.isArray(n.values)||n.values.length===0?{kind:"project",values:["*"]}:{kind:n.kind,values:[...new Set(n.values.map(e=>e.trim()).filter(Boolean))]}}function Tt(n,e,t){return{id:ht(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:n.threadId,jobId:n.jobId,createdAt:n.occurredAt??new Date().toISOString()}}function Se(n,e=800){return typeof n=="string"?n.trim().slice(0,e):""}function Ii(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(o=>typeof o=="string"&&!!o.trim());return t.length?{kind:e.kind,values:t}:void 0}function wi(n,e,t){if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,s=Se(i.explanationId,100),a=Se(i.clientId,100),d=Se(i.storeId,100);if(s&&a)throw new Error("relation endpoint must use either explanationId or clientId, not both");let c=s||a;return c?{explanationId:c,...d?{storeId:d}:{}}:void 0}let o=Se(e,100),r=Se(t,100);return o?{explanationId:o,...r?{storeId:r}:{}}:void 0}function vi(n,e){if(!n||!e.trim())return{found:!1};let t=n;for(let o of e.split(".").filter(Boolean))if(Array.isArray(t)){let r=Number(o);if(!Number.isInteger(r)||r<0||r>=t.length)return{found:!1};t=t[r]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,o))t=t[o];else return{found:!1};return{found:!0,value:t}}function Ht(n,e={}){let t=[...n.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],o=n.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),r=t.at(-1)?.[1],i,s=[];if(r)i=r;else{let d=[...n.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:o,error:"imprint assessment is missing"};try{let c=JSON.parse(d);if(!c||typeof c!="object"||Array.isArray(c)||!Object.prototype.hasOwnProperty.call(c,"imprint"))return{visibleText:o,error:"imprint assessment is missing"};let y=c;i=y.imprint,s=Array.isArray(y.annotations)?y.annotations:[]}catch{return{visibleText:o,error:"resolution envelope is invalid"}}}try{let a=typeof i=="string"?JSON.parse(i):i;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("imprint assessment is invalid");if(a.decision==="none"){let h=String(a.reason);if(!Xa.has(h))throw new Error("imprint no-op reason is invalid");if(h==="task_specific_detail"&&s.some(M=>{if(!M||typeof M!="object"||Array.isArray(M))return!1;let $=M;return($.finalScope??$.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(a.usedExplanationIds)?a.usedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[],I=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[],v=new Set(e.context?.explanations.map(M=>M.id)??[]);if([...new Set([...p,...I])].some(M=>!v.has(M)))throw new Error("imprint use must cite only surfaced explanations");let x=[...new Set([...p,...e.applicationOccurred?[]:I])],m=e.applicationOccurred?I:[],f;if(m.length){f=m;let M=new Set(e.context?.pendingGroundingExplanationIds??[]),$=m.filter(E=>{let F=e.context?.explanations.find(Y=>Y.id===E);return v.has(E)&&F&&(F.state==="emerging"||F.state==="testing")&&!M.has(E)});if($.length){let E=a.grounding,F=typeof E?.explanationId=="string"&&$.includes(E.explanationId)?E.explanationId:$[0],Y=Se(E?.question,300);return{draft:{decision:"apply",summary:{title:Se(a.summary?.title,120)||"Applied shared understanding",detail:Se(a.summary?.detail,500)||Se(e.requestText||o,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:m,grounding:{explanationId:F,question:Y||"Does applying this understanding here match your intent?"}},visibleText:o}}}if(h==="duplicate"){let M=Se(a.duplicateOfExplanationId,100),$=a.scopeComparison;if(!M)throw new Error("duplicate assessment requires duplicateOfExplanationId");if($!=="equivalent"&&$!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let E=e.context?.explanations.find(F=>F.id===M);if(!E)throw new Error("duplicate assessment must cite a surfaced explanation");if(nr(e.requestText)&&!td(E))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:h,duplicateOfExplanationId:M,scopeComparison:$,...x.length?{usedExplanationIds:x}:{},...f?{appliedExplanationIds:f}:{}},visibleText:o}}return{draft:{decision:"none",reason:h,...x.length?{usedExplanationIds:x}:{},...f?{appliedExplanationIds:f}:{}},visibleText:o}}if(a.decision==="recognize"){let h=Se(a.explanationId,100);if(!h)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(u=>u.id===h);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let I=a.summary,v={title:Se(I?.title,120),detail:Se(I?.detail,500)};if(!v.title||!v.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:h,summary:v},visibleText:o}}if(a.decision==="apply"){let h=a.summary,p={title:Se(h?.title,120),detail:Se(h?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let I=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(M=>typeof M=="string"&&!!M.trim()):[];if(!I.length)throw new Error("application requires appliedExplanationIds");let v=new Map(e.context?.explanations.map(M=>[M.id,M])??[]);if(I.some(M=>!v.has(M)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(I)]},visibleText:o};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),x=I.filter(M=>{let $=v.get(M);return $&&($.state==="emerging"||$.state==="testing")&&!u.has(M)});if(!x.length){if(I.every($=>v.get($)?.state==="grounded"||u.has($)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:I},visibleText:o};throw new Error("application must cite a surfaced ungrounded explanation")}let m=a.grounding,f=typeof m?.explanationId=="string"&&x.includes(m.explanationId)?m.explanationId:x[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:I,grounding:{explanationId:f,question:Se(m?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:o}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,c=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(c)))throw new Error("summary.kind is invalid");let y={kind:c,title:Se(d?.title,120),detail:Se(d?.detail,500)};if(!y.title||!y.detail)throw new Error("summary title and detail are required");let w=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(h=>typeof h=="string"&&!!h.trim()):[],g=[];for(let h of Array.isArray(a.mutations)?a.mutations:[]){if(!h||typeof h!="object")continue;let p=h;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let I=Se(p.statement),v=Se(p.rationale);if(!I||!v)continue;g.push({op:"add",clientId:Se(p.clientId,100)||void 0,kind:p.kind,statement:I,rationale:v,scope:Ii(p.scope),rootReason:Se(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let I={op:"revise",explanationId:p.explanationId,statement:Se(p.statement)||void 0,rationale:Se(p.rationale)||void 0,scope:Ii(p.scope),reopenGrounding:p.reopenGrounding===!0};(I.statement||I.rationale||I.scope||I.reopenGrounding)&&g.push(I)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let I=Se(p.summary);I&&g.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:I})}else if(p.op==="relation"){if(!["expresses","excepts"].includes(String(p.type)))throw new Error("relation type is invalid");let I=Se(p.rationale),v=wi(p.from,p.fromId,p.fromStoreId),u=wi(p.to,p.toId,p.toStoreId);if(!I)throw new Error("relation rationale is required");if(!v||!u)throw new Error("relation endpoints require an explanationId or clientId");g.push({op:"relation",type:p.type,from:v,to:u,rationale:I})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let I=Se(p.reason);I&&g.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:I})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let I=Se(p.modelPath,300);I&&g.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:I,rationale:Se(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&g.push({op:"retire",explanationId:p.explanationId,reason:Se(p.reason)})}let S=a.grounding,b=S&&typeof S.explanationId=="string"&&Se(S.question)?{explanationId:S.explanationId,question:Se(S.question,300)}:void 0;return{draft:{decision:"mutate",summary:y,appliedExplanationIds:w,mutations:g,grounding:b},visibleText:o}}catch(a){return{visibleText:o,error:a instanceof Error?a.message:String(a)}}}function Qt(n,e={}){let t=n?.explanations??[],o=new Set(n?.pendingGroundingExplanationIds??[]),r=new Set(n?.correctionExplanationIds??[]),i=nr(e.requestText),s=n?.retrievalIntent,a=n?.historicalCaveats??[],d=t.find(g=>g.storeId&&!g.readOnly)?.storeId,c=(g,S)=>{let b=g[S];return b?`[${b.storeId}] ${b.explanationId}`:S==="from"?g.fromId:g.toId},y=!!n?.relations?.some(g=>g.from&&g.to&&g.from.storeId!==g.to.storeId),w=t.some(g=>g.readOnly);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.",...t.length?["","Relevant explanations from the project imprint:",...t.map((g,S)=>[`${S+1}. [${g.state}; ${g.kind}] ${g.statement}`,` - Why: ${g.rationale}`,` - Scope: ${g.scope.kind} ${g.scope.values.join(", ")}`,` - Explanation: ${g.id}`,...g.storeId?[` - Store: ${g.storeId}${g.readOnly?" (read-only)":" (writable primary)"}`]:[],...o.has(g.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(g.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...g.concrete.map(b=>` - Concrete terminal: ${b.modelPath} = ${JSON.stringify(b.value)}`)].join(`
8
+ `)),...n?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...n?.relations?.length?["","Known explanation topology:",...n.relations.map(g=>`- ${g.storeId?`[owned by ${g.storeId}${g.readOnly?"; read-only":""}] `:""}${c(g,"from")} --${g.type}--> ${c(g,"to")}: ${g.rationale}`)]:[],...w||y?["","Store-qualified topology remains locally owned: the relation must originate at an explanation in the writable primary store, while its target may be in a mounted read-only store. Never proxy a relation whose source belongs to a mounted store.",`For a cross-store relation, use qualified endpoints: {"op":"relation","type":"expresses|excepts","from":{"storeId":"${d??"<writable-primary-store>"}","clientId":"<new-specific-client-id>"},"to":{"storeId":"<mounted-target-store>","explanationId":"<existing-abstract-target-id>"},"rationale":"<why>"}. Use clientId for a new explanation created in this transaction and explanationId for an existing durable explanation.`]:[],...s?["","Explicit pattern transfer detected:",`- Target: ${s.target}`,`- Reference: ${s.reference}`,"Before editing, state which dimensions you intend to transfer from the reference and which target-specific behavior you will preserve. Compare the relevant surface, spacing, typography, radius, and interaction behavior; transfer only the dimensions supported by the request and evidence. If the intended transfer remains materially ambiguous after inspecting both anchors, ask one focused question."]:[],...a.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...a.map((g,S)=>[`${S+1}. [challenged; ${g.kind}] ${g.statement}`,` - Why it was previously proposed: ${g.rationale}`,` - Scope: ${g.scope.kind} ${g.scope.values.join(", ")}`,` - Historical explanation: ${g.id}`,...g.storeId?[` - Store: ${g.storeId}${g.readOnly?" (read-only)":" (writable primary)"}`]:[]].join(`
9
9
  `)),"Use these caveats only to avoid repeating a rejected or over-broad transfer. Do not cite them as usedExplanationIds or treat them as active guidance."]:[],...t.some(g=>g.readOnly)?["","Mounted-store explanations are read-only context. They may inform the work and be cited as used understanding, but do not mutate, ground, revise, or add evidence to them without an explicit writable orientation for that store."]:[],...n?.unavailableStoreIds?.length?["",`Some mounted Imprint knowledge was unavailable during this bounded read: ${n.unavailableStoreIds.join(", ")}. Do not infer its contents.`]:[],...n?.unavailableTopologyStoreIds?.length?["",`Some mounted Imprint topology was unavailable during this bounded read: ${n.unavailableTopologyStoreIds.join(", ")}. Available explanations remain usable, but do not infer missing relationships.`]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","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.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","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 anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","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. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, 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.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...i?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"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.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason 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 with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","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 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. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.",'As soon as one or more surfaced explanations become actively useful during the work, emit `<imprint-use>{"explanationIds":["<every actively useful surfaced explanation id>"]}</imprint-use>` immediately. This live receipt is hidden from conversational prose. Emit it at the point of use rather than waiting for the final response. Emit a later marker only when additional explanations become actively useful. Never emit it for explanations that were merely retrieved, read, searched, or considered.',"Treat Imprint as actively useful when a surfaced explanation materially informs an answer, recommendation, implementation choice, or other decision. Whenever it is actively useful, always cite every materially used surfaced explanation in `usedExplanationIds`. This produces a usage receipt only; it does not strengthen or mutate shared understanding. Do not cite explanations that were merely retrieved, read, or considered but did not influence the result.","`appliedExplanationIds` is narrower: include an explanation there only when it governed a completed implementation or other observable action that genuinely tests the explanation. Never use `appliedExplanationIds` for an answer-only, informational, research, or read-only request. An explanation may be used without being applied; every applied explanation is also understood to be used.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change","usedExplanationIds":["<every surfaced explanation that was actively useful, or omit when none>"]}',"A no-op reason cannot suppress genuine application evidence. When a completed action was governed by an ungrounded explanation, report decision apply directly so the summary and grounding question are intentional. Answering a question with that explanation is usage, not application.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"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":"expresses|excepts","from":{"clientId":"<new-specific-client-id>"},"to":{"explanationId":"<existing-abstract-id>"},"rationale":"<why; use clientId for new transaction-local explanations and explanationId for existing durable explanations>"},{"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 expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}','The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only mutation objects actually needed. A new explanation established through completed implementation must include its clientId in appliedExplanationIds; the bridge also derives this application from a completed change as a safeguard. Applying a grounded explanation never requires a mutation, but actively using it still requires its id in appliedExplanationIds. Never claim that a new explanation is grounded."].join(`
10
- `)}var kt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Kt(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualGraph(){let e=await this.store.readHead(),t=`${e.sequence}:${e.hash??""}`,o=this.contextualGraphCache?.headKey===t?this.contextualGraphCache.graph:void 0;return o||(o=(await this.store.load()).graph,this.contextualGraphCache={headKey:t,graph:o}),o}async explanationsByIds(e){if(!e.length)return[];let t=await this.contextualGraph(),o=new Map(t.explanations.map(r=>[r.id,r]));return[...new Set(e)].flatMap(r=>{let i=o.get(r);if(!i||i.state==="retired"||i.state==="challenged")return[];let s=new Set(t.relations.filter(a=>!a.toStoreId&&a.toId===i.id&&a.type==="expresses").map(a=>a.fromId));return[{id:i.id,kind:i.kind,statement:i.statement,rationale:i.rationale,scope:i.scope,state:i.state,concrete:t.concrete.filter(a=>s.has(a.id)).map(a=>({id:a.id,modelPath:a.modelPath,value:a.value}))}]})}async contextualize(e){let t=ft(e.text??""),o=ft((e.subjectHints??[]).join(" ")),r=od(e.text),i=ft(r?.target??""),s=ft(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!t.size&&!o.size&&!a.size&&!d.size)return;let c=await this.contextualGraph(),I=c.explanations.filter(m=>m.state!=="retired"&&(m.state!=="challenged"||d.has(m.id))).map(m=>{let f=ft([m.statement,m.rationale].join(" ")),M=ft(m.scope.values.join(" ")),$=St(f,t),E=St(M,t),F=St(M,o),Y=St(f,o),L=$+E*.2+F*.25+Y*.75+(m.state==="grounded"?.08:0)+(a.has(m.id)?1:0)+(d.has(m.id)?1:0),R=a.has(m.id)||d.has(m.id)||$>=.12||E>=.5||F>=.2||Y>=.2;return{item:m,score:L,relevant:R}}).filter(m=>m.relevant&&m.score>=.18).sort((m,f)=>f.score-m.score||f.item.updatedAt.localeCompare(m.item.updatedAt)),v=Math.max(1,e.maxExplanations??6),g=m=>c.explanations.filter(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let M=St(ft(`${f.statement} ${f.rationale}`),m),$=St(ft(f.scope.values.join(" ")),m);return{item:f,score:M+$*.35+(f.state==="grounded"?.08:0)}}).filter(f=>f.score>=.18).sort((f,M)=>M.score-f.score||M.item.updatedAt.localeCompare(f.item.updatedAt)),k=[],b=m=>{k.length<v&&!k.some(f=>f.id===m.id)&&k.push(m)};if(r&&(g(i).slice(0,2).forEach(({item:m})=>b(m)),g(s).slice(0,2).forEach(({item:m})=>b(m))),I.forEach(({item:m})=>b(m)),!k.length)return;let h=new Set(k.map(m=>m.id)),p=new Set(c.relations.flatMap(m=>m.toStoreId?[]:h.has(m.fromId)?[m.toId]:h.has(m.toId)?[m.fromId]:[])),y=new Set(c.explanations.flatMap(m=>p.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),w=c.explanations.filter(m=>y.has(m.id)&&!h.has(m.id)).sort((m,f)=>f.updatedAt.localeCompare(m.updatedAt)).slice(0,4),u=[...k,...w];for(let m of w)h.add(m.id);let x=r?c.explanations.filter(m=>m.state==="challenged").map(m=>{let f=ft(`${m.statement} ${m.rationale} ${m.scope.values.join(" ")}`),M=St(f,i),$=St(f,s);return{item:m,score:M+$,targetScore:M,referenceScore:$}}).filter(m=>m.targetScore>=.12&&m.referenceScore>=.12).sort((m,f)=>f.score-m.score||f.item.updatedAt.localeCompare(m.item.updatedAt)).slice(0,3).map(({item:m})=>({id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state})):[];return{explanations:u.map(m=>{let f=new Set(c.relations.filter(M=>!M.toStoreId&&M.toId===m.id&&M.type==="expresses").map(M=>M.fromId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:c.concrete.filter(M=>f.has(M.id)).map(M=>({id:M.id,modelPath:M.modelPath,value:M.value}))}}),truncated:I.length>k.length||w.length<y.size,...r?{retrievalIntent:r}:{},...x.length?{historicalCaveats:x}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},relations:c.relations.filter(m=>!m.toStoreId&&h.has(m.fromId)&&h.has(m.toId)).map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}async capture(e,t){let o=e.decision==="mutate"?e.mutations:[],r=t.applicationOccurred?o.flatMap(P=>P.op==="add"&&P.clientId?[P.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(o.length===0&&i.length===0)return;let s=t.occurredAt??new Date().toISOString(),a=await this.store.load(),d=new Map(a.graph.explanations.map(P=>[P.id,P])),c=new Map,I=new Map,v=[],g=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),b=new Set(o.flatMap(P=>P.op==="revise"&&o.some(j=>j.op==="evidence"&&j.stance==="challenges"&&j.explanationId===P.explanationId)?[P.explanationId]:[])),h=new Set(o.flatMap(P=>P.op==="add"&&P.clientId?[P.clientId]:[])),p=t.storeId?.trim(),y=P=>d.has(P)||h.has(P),w=new Map((t.context?.explanations??[]).flatMap(P=>P.storeId?[[`${P.storeId}:${P.id}`,P]]:[])),u=P=>P.storeId??p,x=P=>{let j=u(P.from),B=u(P.to);return p&&j!==p||!p&&(P.from.storeId||P.to.storeId)||!y(P.from.explanationId)?!1:!B||B===p?y(P.to.explanationId):!!w.get(`${B}:${P.to.explanationId}`)?.memoryId},m=new Set;for(let P of o)P.op==="relation"&&(u(P.from)!==u(P.to)||P.from.explanationId!==P.to.explanationId)&&x(P)?(m.add(P.from.explanationId),u(P.to)===p&&m.add(P.to.explanationId)):P.op==="supersede"&&P.explanationId!==P.replacementId&&y(P.explanationId)&&y(P.replacementId)?(m.add(P.explanationId),m.add(P.replacementId)):P.op==="bind_concrete"&&y(P.explanationId)&&wi(t.concreteModel,P.modelPath).found&&m.add(P.explanationId);let f=a.graph.explanations.length===0;for(let P of o){if(P.op!=="add")continue;let j=!!(P.clientId&&m.has(P.clientId)),B=!!P.rootReason?.trim()||f;if(!j&&!B)continue;f&&(f=!1);let _=ht();P.clientId&&c.set(P.clientId,_);let Q=P.clientId?i.includes(P.clientId):!1,de={id:_,kind:P.kind,statement:P.statement,rationale:P.rationale,scope:tr(P.scope),state:Q?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[Tt(t,"supports",e.summary.detail)]};d.set(_,de),g.add(_),v.push({op:"add_explanation",explanation:de})}let M=P=>c.get(P)??P;for(let P of o){if(P.op!=="revise")continue;let j=M(P.explanationId),B=d.get(j);if(B?.state!=="grounded")continue;let _=ht(),Q={id:_,kind:B.kind,statement:P.statement??B.statement,rationale:P.rationale??B.rationale,scope:P.scope?tr(P.scope):B.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[Tt(t,"supports",e.summary.detail)]};d.set(_,Q),I.set(j,_),g.add(_),v.push({op:"add_explanation",explanation:Q});let de=Wt(B,Q);de!==0&&v.push({op:"add_relation",relation:{id:ht(),type:"expresses",fromId:de>0?j:_,toId:de>0?_:j,rationale:P.rationale??e.summary.detail,createdAt:s}})}let $=P=>{let j=M(P);return I.get(j)??j};for(let P of o){if(P.op==="add")continue;if(P.op==="bind_concrete"){let B=$(P.explanationId);if(!d.has(B))continue;let _=wi(t.concreteModel,P.modelPath);if(!_.found)continue;let Q=a.graph.concrete.find(de=>de.modelPath===P.modelPath&&JSON.stringify(de.value)===JSON.stringify(_.value));Q||(Q={id:ht(),modelPath:P.modelPath,value:structuredClone(_.value),createdAt:s,updatedAt:s},v.push({op:"add_concrete",concrete:Q})),v.push({op:"add_relation",relation:{id:ht(),type:"expresses",fromId:Q.id,toId:B,rationale:P.rationale,createdAt:s}}),g.add(B);continue}if(P.op==="relation"){if(!x(P))continue;let B=u(P.from),_=u(P.to);if(p&&B!==p)continue;let Q=$(P.from.explanationId),de=_===p?$(P.to.explanationId):P.to.explanationId,Z=d.get(Q),se=_===p?d.get(de):w.get(`${_}:${de}`);if(!Z||!se||_===p&&Q===de)continue;if(P.type==="expresses"&&Wt(Z,se)<0){if(_!==p)continue;[Q,de]=[de,Q]}v.push({op:"add_relation",relation:{id:ht(),type:P.type,fromId:Q,..._&&_!==p?{toStoreId:_}:{},toId:de,rationale:P.rationale,createdAt:s}}),g.add(Q),_===p&&g.add(de);continue}if(P.op==="supersede"){let B=$(P.explanationId),_=$(P.replacementId);if(!d.has(B)||!d.has(_)||B===_)continue;v.push({op:"add_evidence",explanationId:B,evidence:Tt(t,"challenges",P.reason)}),v.push({op:"revise_explanation",explanationId:B,patch:{state:"challenged",supersededBy:_},updatedAt:s}),g.add(B),g.add(_);continue}let j=$(P.explanationId);if(d.has(j))if(g.add(j),P.op==="revise"){if(I.has(M(P.explanationId)))continue;let B=d.get(j);if(!B||B.state!=="emerging"&&B.state!=="testing")continue;let _={...P.statement?{statement:P.statement}:{},...P.rationale?{rationale:P.rationale}:{},...P.scope?{scope:tr(P.scope)}:{},...P.reopenGrounding||b.has(P.explanationId)?{state:"testing"}:{}};v.push({op:"revise_explanation",explanationId:j,patch:_,updatedAt:s})}else if(P.op==="evidence"){if(P.stance==="challenges"&&b.has(P.explanationId))continue;v.push({op:"add_evidence",explanationId:j,evidence:Tt(t,P.stance,P.summary)}),P.stance==="challenges"&&v.push({op:"revise_explanation",explanationId:j,patch:{state:"challenged"},updatedAt:s})}else P.op==="retire"&&(v.push({op:"add_evidence",explanationId:j,evidence:Tt(t,"challenges",P.reason||"Retired after contradictory collaboration evidence.")}),v.push({op:"revise_explanation",explanationId:j,patch:{state:"retired"},updatedAt:s}))}for(let P of i){let j=$(P),B=d.get(j);!B||B.state==="grounded"||B.state==="retired"||k.has(j)&&!g.has(j)||(g.has(j)||(g.add(j),v.push({op:"add_evidence",explanationId:j,evidence:{...Tt(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),B.state==="emerging"&&v.push({op:"revise_explanation",explanationId:j,patch:{state:"testing"},updatedAt:s}))}let E=new Set(a.graph.relations.map(P=>`${P.type}:${P.fromId}:${P.toStoreId??""}:${P.toId}`)),F=v.filter(P=>{if(P.op!=="add_relation")return!0;let j=`${P.relation.type}:${P.relation.fromId}:${P.relation.toStoreId??""}:${P.relation.toId}`;return E.has(j)?!1:(E.add(j),!0)});if(!F.length)return;let Y=ht(),L=await this.store.commit({transactionId:Y,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:F}),R=new Map(L.graph.explanations.map(P=>[P.id,P])),J=[...g].flatMap(P=>{let j=R.get(P);if(!j)return[];let B=!a.graph.explanations.some(Q=>Q.id===P),_=j.state==="challenged"||j.state==="retired";return[{explanationId:P,action:B?"added":_?"challenged":"revised",statement:j.statement,state:j.state}]}),W=i.map($).find(P=>R.get(P)?.state==="testing"&&!k.has(P)),ee=e.grounding?$(e.grounding.explanationId):W,H=ee?R.get(ee):void 0,ie=H?.state==="testing"&&!k.has(H.id)?{explanationId:H.id,question:e.grounding?.question||ed(H),state:"testing"}:void 0;return{transactionId:Y,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:J,...ie?{grounding:ie}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),o=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!o)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(c=>c.id===o);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},a=[],d="";if(e.action==="yes"?(a.push({op:"add_evidence",explanationId:o,evidence:{...Tt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:o,evidence:{...Tt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${i.statement}`),!a.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:ht(),committedAt:t,source:s,summary:d,mutations:a}),"applied"}};function Xt(n){return n.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
10
+ `)}var kt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Kt(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualGraph(){let e=await this.store.readHead(),t=`${e.sequence}:${e.hash??""}`,o=this.contextualGraphCache?.headKey===t?this.contextualGraphCache.graph:void 0;return o||(o=(await this.store.load()).graph,this.contextualGraphCache={headKey:t,graph:o}),o}async explanationsByIds(e){if(!e.length)return[];let t=await this.contextualGraph(),o=new Map(t.explanations.map(r=>[r.id,r]));return[...new Set(e)].flatMap(r=>{let i=o.get(r);if(!i||i.state==="retired"||i.state==="challenged")return[];let s=new Set(t.relations.filter(a=>!a.toStoreId&&a.toId===i.id&&a.type==="expresses").map(a=>a.fromId));return[{id:i.id,kind:i.kind,statement:i.statement,rationale:i.rationale,scope:i.scope,state:i.state,concrete:t.concrete.filter(a=>s.has(a.id)).map(a=>({id:a.id,modelPath:a.modelPath,value:a.value}))}]})}async contextualize(e){let t=ft(e.text??""),o=ft((e.subjectHints??[]).join(" ")),r=id(e.text),i=ft(r?.target??""),s=ft(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!t.size&&!o.size&&!a.size&&!d.size)return;let c=await this.contextualGraph(),y=c.explanations.filter(m=>m.state!=="retired"&&(m.state!=="challenged"||d.has(m.id))).map(m=>{let f=ft([m.statement,m.rationale].join(" ")),M=ft(m.scope.values.join(" ")),$=St(f,t),E=St(M,t),F=St(M,o),Y=St(f,o),L=$+E*.2+F*.25+Y*.75+(m.state==="grounded"?.08:0)+(a.has(m.id)?1:0)+(d.has(m.id)?1:0),R=a.has(m.id)||d.has(m.id)||$>=.12||E>=.5||F>=.2||Y>=.2;return{item:m,score:L,relevant:R}}).filter(m=>m.relevant&&m.score>=.18).sort((m,f)=>f.score-m.score||f.item.updatedAt.localeCompare(m.item.updatedAt)),w=Math.max(1,e.maxExplanations??6),g=m=>c.explanations.filter(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let M=St(ft(`${f.statement} ${f.rationale}`),m),$=St(ft(f.scope.values.join(" ")),m);return{item:f,score:M+$*.35+(f.state==="grounded"?.08:0)}}).filter(f=>f.score>=.18).sort((f,M)=>M.score-f.score||M.item.updatedAt.localeCompare(f.item.updatedAt)),S=[],b=m=>{S.length<w&&!S.some(f=>f.id===m.id)&&S.push(m)};if(r&&(g(i).slice(0,2).forEach(({item:m})=>b(m)),g(s).slice(0,2).forEach(({item:m})=>b(m))),y.forEach(({item:m})=>b(m)),!S.length)return;let h=new Set(S.map(m=>m.id)),p=new Set(c.relations.flatMap(m=>m.toStoreId?[]:h.has(m.fromId)?[m.toId]:h.has(m.toId)?[m.fromId]:[])),I=new Set(c.explanations.flatMap(m=>p.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),v=c.explanations.filter(m=>I.has(m.id)&&!h.has(m.id)).sort((m,f)=>f.updatedAt.localeCompare(m.updatedAt)).slice(0,4),u=[...S,...v];for(let m of v)h.add(m.id);let x=r?c.explanations.filter(m=>m.state==="challenged").map(m=>{let f=ft(`${m.statement} ${m.rationale} ${m.scope.values.join(" ")}`),M=St(f,i),$=St(f,s);return{item:m,score:M+$,targetScore:M,referenceScore:$}}).filter(m=>m.targetScore>=.12&&m.referenceScore>=.12).sort((m,f)=>f.score-m.score||f.item.updatedAt.localeCompare(m.item.updatedAt)).slice(0,3).map(({item:m})=>({id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state})):[];return{explanations:u.map(m=>{let f=new Set(c.relations.filter(M=>!M.toStoreId&&M.toId===m.id&&M.type==="expresses").map(M=>M.fromId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:c.concrete.filter(M=>f.has(M.id)).map(M=>({id:M.id,modelPath:M.modelPath,value:M.value}))}}),truncated:y.length>S.length||v.length<I.size,...r?{retrievalIntent:r}:{},...x.length?{historicalCaveats:x}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},relations:c.relations.filter(m=>!m.toStoreId&&h.has(m.fromId)&&h.has(m.toId)).map(m=>({id:m.id,type:m.type,fromId:m.fromId,toId:m.toId,rationale:m.rationale}))}}async capture(e,t){let o=e.decision==="mutate"?e.mutations:[],r=t.applicationOccurred?o.flatMap(P=>P.op==="add"&&P.clientId?[P.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(o.length===0&&i.length===0)return;let s=t.occurredAt??new Date().toISOString(),a=await this.store.load(),d=new Map(a.graph.explanations.map(P=>[P.id,P])),c=new Map,y=new Map,w=[],g=new Set,S=new Set(t.pendingGroundingExplanationIds??[]),b=new Set(o.flatMap(P=>P.op==="revise"&&o.some(j=>j.op==="evidence"&&j.stance==="challenges"&&j.explanationId===P.explanationId)?[P.explanationId]:[])),h=new Set(o.flatMap(P=>P.op==="add"&&P.clientId?[P.clientId]:[])),p=t.storeId?.trim(),I=P=>d.has(P)||h.has(P),v=new Map((t.context?.explanations??[]).flatMap(P=>P.storeId?[[`${P.storeId}:${P.id}`,P]]:[])),u=P=>P.storeId??p,x=P=>{let j=u(P.from),B=u(P.to);return p&&j!==p||!p&&(P.from.storeId||P.to.storeId)||!I(P.from.explanationId)?!1:!B||B===p?I(P.to.explanationId):!!v.get(`${B}:${P.to.explanationId}`)?.memoryId},m=new Set;for(let P of o)P.op==="relation"&&(u(P.from)!==u(P.to)||P.from.explanationId!==P.to.explanationId)&&x(P)?(m.add(P.from.explanationId),u(P.to)===p&&m.add(P.to.explanationId)):P.op==="supersede"&&P.explanationId!==P.replacementId&&I(P.explanationId)&&I(P.replacementId)?(m.add(P.explanationId),m.add(P.replacementId)):P.op==="bind_concrete"&&I(P.explanationId)&&vi(t.concreteModel,P.modelPath).found&&m.add(P.explanationId);let f=a.graph.explanations.length===0;for(let P of o){if(P.op!=="add")continue;let j=!!(P.clientId&&m.has(P.clientId)),B=!!P.rootReason?.trim()||f;if(!j&&!B)continue;f&&(f=!1);let _=ht();P.clientId&&c.set(P.clientId,_);let Q=P.clientId?i.includes(P.clientId):!1,de={id:_,kind:P.kind,statement:P.statement,rationale:P.rationale,scope:tr(P.scope),state:Q?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[Tt(t,"supports",e.summary.detail)]};d.set(_,de),g.add(_),w.push({op:"add_explanation",explanation:de})}let M=P=>c.get(P)??P;for(let P of o){if(P.op!=="revise")continue;let j=M(P.explanationId),B=d.get(j);if(B?.state!=="grounded")continue;let _=ht(),Q={id:_,kind:B.kind,statement:P.statement??B.statement,rationale:P.rationale??B.rationale,scope:P.scope?tr(P.scope):B.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[Tt(t,"supports",e.summary.detail)]};d.set(_,Q),y.set(j,_),g.add(_),w.push({op:"add_explanation",explanation:Q});let de=Wt(B,Q);de!==0&&w.push({op:"add_relation",relation:{id:ht(),type:"expresses",fromId:de>0?j:_,toId:de>0?_:j,rationale:P.rationale??e.summary.detail,createdAt:s}})}let $=P=>{let j=M(P);return y.get(j)??j};for(let P of o){if(P.op==="add")continue;if(P.op==="bind_concrete"){let B=$(P.explanationId);if(!d.has(B))continue;let _=vi(t.concreteModel,P.modelPath);if(!_.found)continue;let Q=a.graph.concrete.find(de=>de.modelPath===P.modelPath&&JSON.stringify(de.value)===JSON.stringify(_.value));Q||(Q={id:ht(),modelPath:P.modelPath,value:structuredClone(_.value),createdAt:s,updatedAt:s},w.push({op:"add_concrete",concrete:Q})),w.push({op:"add_relation",relation:{id:ht(),type:"expresses",fromId:Q.id,toId:B,rationale:P.rationale,createdAt:s}}),g.add(B);continue}if(P.op==="relation"){if(!x(P))continue;let B=u(P.from),_=u(P.to);if(p&&B!==p)continue;let Q=$(P.from.explanationId),de=_===p?$(P.to.explanationId):P.to.explanationId,Z=d.get(Q),se=_===p?d.get(de):v.get(`${_}:${de}`);if(!Z||!se||_===p&&Q===de)continue;if(P.type==="expresses"&&Wt(Z,se)<0){if(_!==p)continue;[Q,de]=[de,Q]}w.push({op:"add_relation",relation:{id:ht(),type:P.type,fromId:Q,..._&&_!==p?{toStoreId:_}:{},toId:de,rationale:P.rationale,createdAt:s}}),g.add(Q),_===p&&g.add(de);continue}if(P.op==="supersede"){let B=$(P.explanationId),_=$(P.replacementId);if(!d.has(B)||!d.has(_)||B===_)continue;w.push({op:"add_evidence",explanationId:B,evidence:Tt(t,"challenges",P.reason)}),w.push({op:"revise_explanation",explanationId:B,patch:{state:"challenged",supersededBy:_},updatedAt:s}),g.add(B),g.add(_);continue}let j=$(P.explanationId);if(d.has(j))if(g.add(j),P.op==="revise"){if(y.has(M(P.explanationId)))continue;let B=d.get(j);if(!B||B.state!=="emerging"&&B.state!=="testing")continue;let _={...P.statement?{statement:P.statement}:{},...P.rationale?{rationale:P.rationale}:{},...P.scope?{scope:tr(P.scope)}:{},...P.reopenGrounding||b.has(P.explanationId)?{state:"testing"}:{}};w.push({op:"revise_explanation",explanationId:j,patch:_,updatedAt:s})}else if(P.op==="evidence"){if(P.stance==="challenges"&&b.has(P.explanationId))continue;w.push({op:"add_evidence",explanationId:j,evidence:Tt(t,P.stance,P.summary)}),P.stance==="challenges"&&w.push({op:"revise_explanation",explanationId:j,patch:{state:"challenged"},updatedAt:s})}else P.op==="retire"&&(w.push({op:"add_evidence",explanationId:j,evidence:Tt(t,"challenges",P.reason||"Retired after contradictory collaboration evidence.")}),w.push({op:"revise_explanation",explanationId:j,patch:{state:"retired"},updatedAt:s}))}for(let P of i){let j=$(P),B=d.get(j);!B||B.state==="grounded"||B.state==="retired"||S.has(j)&&!g.has(j)||(g.has(j)||(g.add(j),w.push({op:"add_evidence",explanationId:j,evidence:{...Tt(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),B.state==="emerging"&&w.push({op:"revise_explanation",explanationId:j,patch:{state:"testing"},updatedAt:s}))}let E=new Set(a.graph.relations.map(P=>`${P.type}:${P.fromId}:${P.toStoreId??""}:${P.toId}`)),F=w.filter(P=>{if(P.op!=="add_relation")return!0;let j=`${P.relation.type}:${P.relation.fromId}:${P.relation.toStoreId??""}:${P.relation.toId}`;return E.has(j)?!1:(E.add(j),!0)});if(!F.length)return;let Y=ht(),L=await this.store.commit({transactionId:Y,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:F}),R=new Map(L.graph.explanations.map(P=>[P.id,P])),J=[...g].flatMap(P=>{let j=R.get(P);if(!j)return[];let B=!a.graph.explanations.some(Q=>Q.id===P),_=j.state==="challenged"||j.state==="retired";return[{explanationId:P,action:B?"added":_?"challenged":"revised",statement:j.statement,state:j.state}]}),W=i.map($).find(P=>R.get(P)?.state==="testing"&&!S.has(P)),ee=e.grounding?$(e.grounding.explanationId):W,H=ee?R.get(ee):void 0,ie=H?.state==="testing"&&!S.has(H.id)?{explanationId:H.id,question:e.grounding?.question||nd(H),state:"testing"}:void 0;return{transactionId:Y,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:J,...ie?{grounding:ie}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),o=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!o)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(c=>c.id===o);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},a=[],d="";if(e.action==="yes"?(a.push({op:"add_evidence",explanationId:o,evidence:{...Tt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:o,evidence:{...Tt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${i.statement}`),!a.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:ht(),committedAt:t,source:s,summary:d,mutations:a}),"applied"}};function Xt(n){return n.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
11
11
  `)}async function io(n,e,t,o){let r=Xt(e);if(!(!r&&t.length===0))try{let i=await n.contextualize({action:r||void 0,subjectHints:t,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])),a=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:a.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(c=>c.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){o?.(i);return}}function Sn(n){if(!n?.packets.length&&!n?.acceptedTruth?.decisions.length)return"";let e=n.packets.some(o=>o.presentation==="surface_before_action");return["","## Contextual product memory","",...n.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.",...n.acceptedTruth.decisions.flatMap((o,r)=>["",`${r+1}. [${o.kind}; ${o.effectiveState}] ${o.claim}`,...o.storeId?[` - Store: ${o.storeId}${o.readOnly?" (read-only)":" (writable primary)"}`]:[],` - Implementation: ${o.implementation}`,` - Verification: ${o.verification}`,...o.freshness.length?[` - Freshness warnings: ${o.freshness.join(", ")}`]:[],` - Decision: ${o.id}`]),...n.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...n.acceptedTruth.conflicts.map(o=>`- ${o.unresolvedQuestion}`)]:[],...n.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...n.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...n.packets.flatMap((o,r)=>["",`${r+1}. ${o.claim}`,...o.storeId?[` - Store: ${o.storeId}${o.readOnly?" (read-only)":" (writable primary)"}`]:[]," - Authority: unaccepted candidate",` - Proposed kind: ${o.proposedKind??"unspecified"}`,` - Presentation: ${o.presentation}`,` - Packet: ${o.packetId}`,` - Evidence references available: ${o.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.",...n.packets.some(o=>o.readOnly)?["","Candidates from mounted stores are read-only in this orientation. Do not emit a memory-review action for them; if the developer wants to resolve one, ask them to make that store writable explicitly."]:[],"",n.packets.some(o=>o.readOnly)?"If\u2014and only if\u2014the developer explicitly resolves one of the writable-primary candidates in this conversation, emit one machine-readable block in addition to your normal response:":"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."]:[],...n.unavailableStoreIds?.length?["",`Some mounted knowledge was unavailable during this bounded read: ${n.unavailableStoreIds.join(", ")}. Continue with the available context and expand intentionally if the missing store is material.`]:[]].join(`
12
- `)}import{mkdir as Ci,readFile as An,writeFile as $i}from"fs/promises";import{join as tn}from"path";var rd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function or(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function so(n){return new Set(or(n).split(" ").filter(e=>e.length>2&&!rd.has(e)))}function vi(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function id(n,e){let t=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(or).filter(Boolean),r=so([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of n){if(t.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a,d=[{value:s.label,by:"semantic"},...s.aliases.map(c=>({value:c,by:"alias"})),...s.locators.map(c=>({value:c.value,by:"locator"}))];for(let c of d){let I=or(c.value);for(let k of o){let b=I===k?95:I.includes(k)||k.includes(I)?75:0;b>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let g=["/","#","[","]","="].some(k=>c.value.includes(k))?0:Math.round(vi(so(I),r)*55);g>=30&&g>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:g>=45?"strong":"weak",matchedBy:"semantic",score:g})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function sd(n){return Math.ceil(JSON.stringify(n).length/4)}function Yt(n,e){return n.relationshipType===e&&n.from.entityType==="decision"&&n.to.entityType==="decision"}function ad(n,e){let t=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===n));if(!t.length)return{decisionId:n,state:"unimplemented",attemptIds:[]};let o=t.filter(i=>i.state==="completed"),r=o.some(i=>i.coverageClaims.some(s=>s.decisionId===n&&s.coverage==="full"));return{decisionId:n,state:r?"implemented":o.length?"partial":"unknown",attemptIds:t.map(i=>i.id)}}function dd(n,e,t){let o=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===n)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=t.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===n),i=o[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:n},state:s,attemptIds:o.map(a=>a.id)}}function bi(n,e){let t=Math.max(300,e.maxEstimatedTokens??1200),o=Math.max(1,e.maxDecisions??6),r=n.records.filter(f=>f.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=n.records.filter(f=>f.recordType==="decision"&&f.state==="active"),a=i?s.filter(f=>i.has(f.id)):s,d=n.records.filter(f=>f.recordType==="implementation_attempt"),c=n.records.filter(f=>f.recordType==="verification_attempt"),I=n.records.filter(f=>f.recordType==="freshness_signal"&&f.state==="open"),v=n.records.filter(f=>f.recordType==="evidence"),g=n.records.filter(f=>f.recordType==="model_entry"),k=id(r,e),b=new Map(k.map(f=>[f.subjectId,f.score])),h=so([e.action,e.text].filter(Boolean).join(" ")),p=a.flatMap(f=>{let M=Math.max(0,...f.subjects.map(F=>b.get(F.subjectId)??0)),$=Math.round(vi(so(f.claim),h)*35),E=M+$;return E>=50?[{decision:f,score:E}]:[]}).sort((f,M)=>M.score-f.score||f.decision.id.localeCompare(M.decision.id)),y=new Map;for(let f of p.slice(0,o))y.set(f.decision.id,f.decision);for(let f of n.relationships){if(!Yt(f,"excepts")&&!Yt(f,"contradicts"))continue;let M=s.find(E=>E.id===f.from.entityId),$=s.find(E=>E.id===f.to.entityId);!M||!$||!y.has(M.id)&&!y.has($.id)||(y.size<o&&y.set(M.id,M),y.size<o&&y.set($.id,$))}let w=[...y.values()],u=f=>f.from.entityType==="decision"&&f.to.entityType==="decision"&&y.has(f.from.entityId)&&y.has(f.to.entityId),x=(f,M=!1)=>{let $=new Set(f.map(j=>j.id)),E=I.filter(j=>j.target.entityType==="decision"&&$.has(j.target.entityId)),F=new Set(n.relationships.filter(j=>Yt(j,"excepts")&&$.has(j.from.entityId)&&$.has(j.to.entityId)).flatMap(j=>[j.from.entityId,j.to.entityId])),L=n.relationships.filter(j=>Yt(j,"contradicts")&&$.has(j.from.entityId)&&$.has(j.to.entityId)).map(j=>({id:j.id,decisionIds:[j.from.entityId,j.to.entityId],unresolvedQuestion:j.reason,expansionRefs:[{kind:"record",id:j.id}]})),R=new Set(L.flatMap(j=>j.decisionIds)),J=v.filter(j=>j.sourceRefs.some(B=>B.kind==="record"&&$.has(B.id))||n.relationships.some(B=>B.relationshipType==="supports"&&B.from.entityType==="evidence"&&B.from.entityId===j.id&&B.to.entityType==="decision"&&$.has(B.to.entityId))),W=Math.max(0,p.length-f.length),ee=n.relationships.some(j=>Yt(j,"contradicts")&&u(j)&&(!$.has(j.from.entityId)||!$.has(j.to.entityId))),H=M||W>0||ee,ie=[];k.length===0&&(e.subjectHints?.length??0)>0?ie.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):f.length===0&&ie.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),L.length&&ie.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:L.flatMap(j=>j.expansionRefs)}),J.some(j=>j.availability!=="available")&&ie.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:J.map(j=>({kind:"record",id:j.id}))}),H&&ie.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:n.manifest.projectId}]});let P={contractVersion:1,projectId:n.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:k.map(({score:j,...B})=>B),modelEntries:g.filter(j=>j.decisionIds.some(B=>$.has(B))).map(j=>({id:j.id,key:j.key,value:j.value,decisionIds:j.decisionIds})),decisions:f.map(j=>({id:j.id,kind:j.kind,claim:j.claim,subjectIds:j.subjects.map(B=>B.subjectId),authority:j.authority,effectiveState:R.has(j.id)?"conflicted":F.has(j.id)?"excepted":"active",freshness:E.filter(B=>B.target.entityId===j.id).map(B=>B.signalType),expansionRef:{kind:"record",id:j.id}})),conflicts:L,uncertainties:ie,implementation:f.map(j=>ad(j.id,d)),verification:f.map(j=>dd(j.id,c,E)),evidence:J.map(j=>({evidenceId:j.id,summary:j.summary,availability:j.availability,sourceRefs:j.sourceRefs})),completeness:{status:H?"truncated":"complete",omittedDecisionCount:W,omittedEvidenceCount:0,conflictsComplete:!ee}};return P.budget.estimatedTokens=sd(P),P},m=x(w);for(;m.budget.estimatedTokens>t&&w.length>0;){let f=w.pop(),M=n.relationships.filter($=>Yt($,"contradicts")&&($.from.entityId===f.id||$.to.entityId===f.id)).flatMap($=>[$.from.entityId,$.to.entityId]);w=w.filter($=>!M.includes($.id)),m=x(w,!0)}return m}var cd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function rr(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ao(n){return new Set(rr(n).split(" ").filter(e=>e.length>2&&!cd.has(e)))}function xi(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function ld(n){return[{value:n.label,by:"label"},...n.aliases.map(e=>({value:e,by:"alias"})),...n.locators.map(e=>({value:e.value,by:"locator"}))]}function pd(n,e){let t=new Map,o=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(rr).filter(Boolean),i=ao([e.action,e.text].filter(Boolean).join(" "));for(let s of n){if(o.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a;for(let d of ld(s)){let c=rr(d.value);for(let g of r){let k=c===g?95:c.includes(g)||g.includes(c)?75:0;k>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:d.by,score:k})}let v=["/","#","[","]","="].some(g=>d.value.includes(g))?0:Math.round(xi(ao(c),i)*55);v>=30&&v>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:v>=45?"strong":"weak",matchedBy:"query_text",score:v})}a&&t.set(s.id,a)}return t}function ud(n,e){let t=new Set(n.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),o=new Set(n.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(a=>t.has(a))||s.sourceRefs.some(a=>a.kind==="thread"&&o.has(a.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 md(n){return Math.ceil(JSON.stringify(n).length/4)}function ir(n,e){let t=n.records.filter(p=>p.recordType==="subject"),o=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=n.records.filter(p=>{if(p.recordType!=="proposal"||r&&!r.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let y=[...n.events].reverse().find(w=>w.entity.entityType==="proposal"&&w.entity.entityId===p.id&&w.toState==="deferred"&&w.transitionContext?.kind==="proposal_deferral")?.transitionContext;return y?y.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||y.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||y.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||y.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||y.resurfaceWhen.includes("after_date")&&!!(y.revisitAfter&&Date.parse(o)>=Date.parse(y.revisitAfter)):!1}),s=n.records.filter(p=>p.recordType==="implementation_attempt"),a=pd(t,e),d=[...a.values()].sort((p,y)=>y.score-p.score),c=ao([e.action,e.text].filter(Boolean).join(" ")),I=i.flatMap(p=>{let y=p.subjects.map(m=>a.get(m.subjectId)).filter(m=>!!m),w=Math.max(0,...y.map(m=>m.score)),u=Math.round(xi(ao(p.claim),c)*35),x=w+u;return x>=50?[{proposal:p,proposalMatches:y,score:x}]:[]}).sort((p,y)=>y.score-p.score||p.proposal.id.localeCompare(y.proposal.id)),v=Math.max(1,e.maxPackets??3),g=Math.max(200,e.maxEstimatedTokens??1200),k=[],b=0;for(let p of I){if(k.length>=v)break;let y=p.proposal.sourceRefs.slice(0,4),w={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:n.manifest.projectId,generatedAt:o,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(x=>x.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:x,...m})=>m)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(x=>x.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ud(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:y},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...y]},u={...w,estimatedTokens:md(w)};if(b+u.estimatedTokens>g)break;k.push(u),b+=u.estimatedTokens}let h=Math.max(0,I.length-k.length);return{packets:k,subjectMatches:d.map(({score:p,...y})=>y),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:I.length,omittedPacketCount:h,maxEstimatedTokens:g,estimatedTokens:b},uncertainty:a.size===0?"subject_unresolved":I.length===0?"no_relevant_pending_proposal":void 0}}var fd=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Zt(n){return fd.test(n)}function hd(n){return{valid:!n.some(e=>e.severity==="error"),issues:n}}function re(n,e,t,o){n.push({path:e,code:t,message:o,severity:"error"})}function sr(n,e,t,o){n.push({path:e,code:t,message:o,severity:"warning"})}function Ne(n,e,t){Zt(t)||re(n,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function nt(n,e,t){(!t||Number.isNaN(Date.parse(t)))&&re(n,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Ct(n,e,t,o=!1){o&&t.level==="contributor"&&re(n,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&re(n,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var gd={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->emerging","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"])},yd=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Id(n,e,t){Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),Ne(n,`${t}.entity.entityId`,e.entity.entityId),nt(n,`${t}.createdAt`,e.createdAt),Ct(n,`${t}.authority`,e.authority);let o=gd[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;o&&!o.has(r)&&re(n,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(yd.has(i)&&(Ct(n,`${t}.authority`,e.authority,!0),e.reason?.trim()||re(n,`${t}.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)&&re(n,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&re(n,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&nt(n,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function wd(n,e,t,o){Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),nt(n,`${t}.createdAt`,e.createdAt),e.projectId!==o&&re(n,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&re(n,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&re(n,`${t}.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)&&re(n,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Ct(n,`${t}.authority`,e.authority,!0),e.claim.trim()||re(n,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&sr(n,`${t}.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())&&re(n,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),nt(n,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&re(n,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&re(n,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&re(n,`${t}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),nt(n,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),nt(n,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&re(n,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(nt(n,`${t}.appliedAt`,e.appliedAt),Ct(n,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&re(n,`${t}.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())&&re(n,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&re(n,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&sr(n,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&sr(n,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function vd(n,e,t){if(Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),Ne(n,`${t}.from.entityId`,e.from.entityId),Ne(n,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&re(n,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&re(n,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),nt(n,`${t}.createdAt`,e.createdAt),e.reason.trim()||re(n,`${t}.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&&re(n,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?re(n,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Ct(n,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&re(n,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&re(n,t,"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))&&re(n,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&re(n,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function $t(n){let e=[];Ne(e,"manifest.projectId",n.manifest.projectId),nt(e,"manifest.createdAt",n.manifest.createdAt),nt(e,"manifest.updatedAt",n.manifest.updatedAt);let t=new Map,o=(h,p)=>{let y=t.get(h);y?re(e,p,"duplicate_id",`ID is already used at ${y}.`):t.set(h,p)};n.records.forEach((h,p)=>{let y=`records[${p}]`;o(h.id,y),wd(e,h,y,n.manifest.projectId)}),n.events.forEach((h,p)=>{let y=`events[${p}]`;o(h.id,y),Id(e,h,y),h.projectId!==n.manifest.projectId&&re(e,`${y}.projectId`,"project_mismatch","Event belongs to another project.")}),n.relationships.forEach((h,p)=>{let y=`relationships[${p}]`;o(h.id,y),vd(e,h,y),h.projectId!==n.manifest.projectId&&re(e,`${y}.projectId`,"project_mismatch","Relationship belongs to another project.")}),n.artifacts.forEach((h,p)=>{o(h.id,`artifacts[${p}]`),Ne(e,`artifacts[${p}].id`,h.id)}),n.tombstones.forEach((h,p)=>{let y=`tombstones[${p}]`;o(h.id,y),Ne(e,`${y}.id`,h.id),Ne(e,`${y}.objectId`,h.objectId),Ne(e,`${y}.deletedById`,h.deletedById),nt(e,`${y}.deletedAt`,h.deletedAt),Ct(e,`${y}.authority`,h.authority,!0)});let r=new Set(n.records.map(h=>`${h.recordType}:${h.id}`)),i=new Set(n.tombstones.map(h=>`${h.objectType}:${h.objectId}`)),s=(h,p)=>{if(h.storeId)return;let y=`${h.entityType}:${h.entityId}`;!r.has(y)&&!i.has(y)&&re(e,p,"dangling_entity_reference",`No record or tombstone exists for ${y}.`)};n.events.forEach((h,p)=>s(h.entity,`events[${p}].entity`)),n.relationships.forEach((h,p)=>{s(h.from,`relationships[${p}].from`),s(h.to,`relationships[${p}].to`)});let a=new Set(n.artifacts.map(h=>h.id)),d=(h,p)=>{a.has(h)||re(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},c=(h,p,y)=>{!r.has(`${h}:${p}`)&&!i.has(`${h}:${p}`)&&re(e,y,"dangling_entity_reference",`No ${h} record or tombstone exists.`)};n.records.forEach((h,p)=>{let y=`records[${p}]`;switch(h.recordType){case"authority_grant":c("participant",h.granteeId,`${y}.granteeId`),c("participant",h.grantedById,`${y}.grantedById`),h.subjectIds.forEach((w,u)=>c("subject",w,`${y}.subjectIds[${u}]`));break;case"observation":h.captureContext.subjectIds.forEach((w,u)=>c("subject",w,`${y}.captureContext.subjectIds[${u}]`)),h.captureContext.artifactIds.forEach((w,u)=>d(w,`${y}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":h.subjects.forEach((w,u)=>c("subject",w.subjectId,`${y}.subjects[${u}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((w,u)=>d(w,`${y}.messageArtifactIds[${u}]`)),h.resultRefs.forEach((w,u)=>s(w,`${y}.resultRefs[${u}]`));break;case"iteration":h.threadIds.forEach((w,u)=>c("thread",w,`${y}.threadIds[${u}]`)),h.artifactIds.forEach((w,u)=>d(w,`${y}.artifactIds[${u}]`));break;case"evidence":h.artifactIds.forEach((w,u)=>d(w,`${y}.artifactIds[${u}]`));break;case"advisory_explanation":h.subjectIds.forEach((w,u)=>c("subject",w,`${y}.subjectIds[${u}]`)),h.evidenceIds.forEach((w,u)=>c("evidence",w,`${y}.evidenceIds[${u}]`)),h.supersededById&&c("advisory_explanation",h.supersededById,`${y}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((w,u)=>c("iteration",w,`${y}.iterationIds[${u}]`)),h.coverageClaims.forEach((w,u)=>c("decision",w.decisionId,`${y}.coverageClaims[${u}].decisionId`)),h.artifactIds.forEach((w,u)=>d(w,`${y}.artifactIds[${u}]`));break;case"eval_spec":h.replacesSpecId&&c("eval_spec",h.replacesSpecId,`${y}.replacesSpecId`),h.decisionIds.forEach((w,u)=>c("decision",w,`${y}.decisionIds[${u}]`)),h.subjectIds.forEach((w,u)=>c("subject",w,`${y}.subjectIds[${u}]`)),(h.dependencies??[]).forEach((w,u)=>{w.kind==="subject"&&w.subjectId&&c("subject",w.subjectId,`${y}.dependencies[${u}].subjectId`)}),(h.scenarios??[]).forEach((w,u)=>{w.subjectIds?.forEach((x,m)=>c("subject",x,`${y}.scenarios[${u}].subjectIds[${m}]`))}),h.targets.forEach((w,u)=>c(w.entityType,w.entityId,`${y}.targets[${u}]`));break;case"verification_attempt":h.evalSpecId&&c("eval_spec",h.evalSpecId,`${y}.evalSpecId`),h.targets.forEach((w,u)=>c(w.entityType,w.entityId,`${y}.targets[${u}]`)),h.evidenceIds.forEach((w,u)=>c("evidence",w,`${y}.evidenceIds[${u}]`));break;case"model_entry":h.subjectIds.forEach((w,u)=>c("subject",w,`${y}.subjectIds[${u}]`)),h.decisionIds.forEach((w,u)=>c("decision",w,`${y}.decisionIds[${u}]`));break;case"model_projection":Ct(e,`${y}.authority`,h.authority,!0),c("participant",h.appliedById,`${y}.appliedById`),h.decisionIds.forEach((w,u)=>c("decision",w,`${y}.decisionIds[${u}]`)),h.entryIds.forEach((w,u)=>c("model_entry",w,`${y}.entryIds[${u}]`)),h.coverage.forEach((w,u)=>c("decision",w.decisionId,`${y}.coverage[${u}].decisionId`));break;case"freshness_signal":s(h.target,`${y}.target`),h.evidenceIds.forEach((w,u)=>c("evidence",w,`${y}.evidenceIds[${u}]`));break;default:break}});let I=new Map(n.events.map(h=>[h.id,h])),v=new Map(n.records.map(h=>[`${h.recordType}:${h.id}`,h])),g=new Map;n.events.forEach((h,p)=>{let y=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,w=g.get(y)??new Set;w.add(h.toState),g.set(y,w),w.size>1&&re(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(n.records.flatMap(h=>h.recordType==="authority_grant"?[[h.id,h]]:[])),b=(h,p,y,w,u)=>{if(h.level!=="delegate"||!h.grantId)return;let x=k.get(h.grantId);if(!x){re(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(x.granteeId!==p||x.level!=="delegate")&&re(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let m=Date.parse(y);(m<Date.parse(x.startsAt)||x.endsAt&&m>Date.parse(x.endsAt)||x.revokedAt&&m>=Date.parse(x.revokedAt))&&re(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),x.subjectIds.length&&w.length&&!w.every(f=>x.subjectIds.includes(f))&&re(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let h of n.records)h.recordType==="decision"&&b(h.authority,h.acceptedById,h.createdAt,h.subjects.map(p=>p.subjectId),`records:${h.id}.authority`);n.events.forEach((h,p)=>{let y=v.get(`${h.entity.entityType}:${h.entity.entityId}`),w=y&&"subjects"in y?y.subjects.map(u=>u.subjectId):[];b(h.authority,h.participantId,h.createdAt,w,`events[${p}].authority`)}),n.relationships.forEach((h,p)=>{if(!h.authority)return;let y=[h.from,h.to].flatMap(w=>{let u=v.get(`${w.entityType}:${w.entityId}`);return u&&"subjects"in u?u.subjects.map(x=>x.subjectId):[]});b(h.authority,h.participantId,h.createdAt,y,`relationships[${p}].authority`)});for(let h of n.records){if(h.recordType!=="decision")continue;let p=I.get(h.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==h.proposalId||p.toState!=="accepted")&&re(e,`records:${h.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==h.acceptedById&&re(e,`records:${h.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),v.has(`proposal:${h.proposalId}`)||re(e,`records:${h.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),h.state==="superseded"&&(n.relationships.some(w=>w.relationshipType==="supersedes"&&w.to.entityType==="decision"&&w.to.entityId===h.id)||re(e,`records:${h.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),h.state==="revoked"&&(n.events.some(w=>w.entity.entityType==="decision"&&w.entity.entityId===h.id&&w.toState==="revoked"&&!!w.reason?.trim())||re(e,`records:${h.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let h of n.records){if(h.recordType!=="proposal"||h.state!=="accepted")continue;n.records.some(y=>y.recordType==="decision"&&y.proposalId===h.id)||re(e,`records:${h.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return hd(e)}function Tn(n,e,t,o){return{id:o,schemaVersion:1,projectId:n.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function Si(n,e,t,o,r){return{id:r,schemaVersion:1,projectId:n.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:o,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function bd(n){switch(n.action){case"accept":return[n.eventId,n.decisionId];case"edit_and_accept":return[n.withdrawalEventId,n.replacementProposalId,n.acceptanceEventId,n.decisionId,n.relationshipId];case"reject":case"defer":return[n.eventId]}}function co(n,e){let t=[],o=n.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);o?o.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${o.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Zt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of bd(e))Zt(i)||t.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!o)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Si(n,o,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.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:n.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.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={...Tn(n,o,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...Tn(n,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Si(n,i,e,a.id,e.decisionId),c={id:e.relationshipId,schemaVersion:1,projectId:n.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:o.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[i,d],events:[s,a],relationships:[c]},projectionUpdates:[{entityType:"proposal",entityId:o.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={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}let r={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.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:o.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}import{createHash as xd}from"crypto";import{readFile as Sd,readdir as Td,realpath as kd}from"fs/promises";import{join as kn,relative as Pd}from"path";var Rd=["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 en(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function Ze(n,e=0){return new Date(Number.isFinite(n)?n:e).toISOString()}function Ti(...n){return n.find(e=>!!e?.trim())?.trim()}function fe(n,e,t,o){let i=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),s=xd("sha256").update(`${n}\0${e}\0${t}`).digest("hex"),a=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${a}${s.slice(4,7)}-${s.slice(7,19)}`}async function ar(n,e){try{return JSON.parse(await Sd(n,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:n,message:t instanceof Error?t.message:String(t)}),null}}function Ad(n){let e=en(n);if(!e)return 0;let t=0,o=r=>{let i=en(r);if(!i){t+=1;return}for(let s of Object.values(i))o(s)};for(let r of Object.values(e))o(r);return t}function Md(n){let e={};for(let t of n)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function Pn(n){let e=[],t=await kd(n.projectRoot).catch(()=>n.projectRoot),o=kn(t,".popmelt"),r=await ar(kn(o,"threads.json"),e),i=await ar(kn(o,"model.json"),e),s=en(r),a=en(s?.threads)??{},d=Object.entries(a).map(([B,_])=>({key:B,value:en(_)})).filter(B=>!!B.value),c=kn(o,"decisions"),I=await Td(c).catch(()=>[]),v=[];for(let B of I.filter(_=>_.endsWith(".json")).sort()){let _=en(await ar(kn(c,B),e));_&&v.push({file:B,value:_})}let g=d.flatMap(({value:B})=>[B.createdAt,B.updatedAt]).filter(B=>typeof B=="number"&&Number.isFinite(B)),k=g.length?Math.min(...g):0,b=n.projectKey??t;n.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 h=fe(b,"project",b,k),p=fe(b,"participant","legacy-owner",k),y=fe(b,"participant","legacy-agent",k),w=fe(b,"subject","project",k),u=Ze(Math.max(k,...g)),x=[],m=[],f=new Map,M=new Map,$=new Map(v.map(B=>[B.value.id??B.file.replace(/^d-|\.json$/g,""),B.value])),E=new Map,F=(B,_,Q,de,Z)=>{let se=f.get(Q);if(se)return se;let xe=fe(b,"artifact",B,de);return m.push({id:xe,kind:_,mediaType:Z,location:Q,availability:"available"}),f.set(Q,xe),xe};for(let{file:B,value:_}of v){let Q=_.id??B.replace(/^d-|\.json$/g,""),de=_.createdAt??k,Z=[F(`${Q}:envelope`,"other",`.popmelt/decisions/${B}`,de,"application/json")];_.screenshotPath&&Z.push(F(`${Q}:screenshot`,"screenshot",`.popmelt/${_.screenshotPath.replace(/^\.popmelt\//,"")}`,de,_.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[se,xe]of(_.pastedImagePaths??[]).entries())Z.push(F(`${Q}:image:${se}`,"image",xe,de));E.set(Q,Z)}let Y=(B,_,Q)=>({id:B,schemaVersion:1,projectId:h,createdAt:u,participantId:_,sourceRefs:Q}),L=(B,_)=>{x.push(_);let Q=M.get(B)??[];Q.push(_.id),M.set(B,Q)},R=[{...Y(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...Y(y,y,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];x.push(...R),x.push({...Y(w,p,[]),recordType:"subject",subjectType:"project",label:Pd(process.cwd(),t)||t,aliases:[],locators:[{id:fe(b,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:Ze(k),sourceRefs:[]}]});let J=new Map,W=(B,_)=>{let Q=J.get(B);if(Q)return Q;let de=fe(b,"subject",B,_),Z={...Y(de,p,[{kind:"external",id:B}]),createdAt:Ze(_),recordType:"subject",subjectType:"element",label:B,aliases:[],locators:[{id:fe(b,"locator",B,_),kind:"dom_selector",value:B,status:"current",validFrom:Ze(_),sourceRefs:[{kind:"external",id:B}]}]};return x.push(Z),J.set(B,de),de};for(let{key:B,value:_}of d){let Q=_.id??B,de=_.createdAt??k,Z=fe(b,"thread",Q,de),se={kind:"thread",id:Q},xe=[],qe=[],pe=Array.isArray(_.messages)?_.messages:[],Te,Ce,Ue=0;pe.forEach((Me,tt)=>{let ze=Me.timestamp??de,ut=fe(b,"artifact",`${Q}:message:${tt}`,ze);if(xe.push(ut),m.push({id:ut,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${Q}/messages/${tt}`,availability:"available"}),f.set(`.popmelt/threads.json#/threads/${Q}/messages/${tt}`,ut),Me.screenshotPath&&F(`${Q}:message:${tt}:screenshot`,"screenshot",Me.screenshotPath,ze),Me.role==="human"){Te=Me;let We=Me.feedbackSummary??Me.replyToQuestion;if(We?.trim()){let Ve=fe(b,"observation",`${Q}:${tt}`,ze),vt=_.elementIdentifiers??[],bt={...Y(Ve,p,[se,{kind:"message",id:ut}]),createdAt:Ze(ze),recordType:"observation",state:"open",statement:We,captureContext:{subjectIds:vt.map(At=>W(At,de)),artifactIds:[ut]},resolvedByIds:[]};L(Q,bt),Ce=Ve,qe.push({entityType:"observation",entityId:Ve})}return}if(Me.role!=="assistant")return;let It=Me.jobId??`${Q}:${tt}`,wt=fe(b,"iteration",It,ze),Rt=$.get(It),Qo=Me.cancelled?"cancelled":Me.error?"failed":Me.question?"question_asked":(Me.resolutions?.length??0)>0?"completed":"no_change",Xo={...Y(wt,y,[se,{kind:"message",id:ut},...(E.get(It)??[]).map(We=>({kind:"artifact",id:We}))]),createdAt:Ze(ze),recordType:"iteration",threadIds:[Z],startedAt:Ze(Te?.timestamp,ze),completedAt:Ze(ze),requestSummary:Ti(Te?.feedbackSummary,Te?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Me.question??Me.error??Me.responseText?.slice(0,1e3),outcome:Qo,execution:{provider:Me.provider??Rt?.provider,model:Me.model??Rt?.model,sessionId:Me.sessionId??Rt?.sessionId},artifactIds:[ut,...E.get(It)??[]]};L(Q,Xo),qe.push({entityType:"iteration",entityId:wt});let wn=Me.resolutions??Rt?.resolutions??[];for(let[We,Ve]of wn.entries()){if(Ve.status!=="resolved"||!Ve.summary?.trim())continue;let vt=_.elementIdentifiers??[],bt=(vt.length?vt:[t]).map(eo=>({subjectId:eo===t?w:W(eo,de),role:"governed"})),At=fe(b,"proposal",`${It}:${Ve.annotationId??"resolution"}:${We}`,ze),Yo={...Y(At,y,[se,{kind:"iteration",id:wt}]),createdAt:Ze(ze),recordType:"proposal",state:"pending",claim:Ve.summary,subjects:bt,subjectSemantics:bt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Ti(Te?.feedbackSummary,Te?.replyToQuestion,Ve.summary),iterationId:wt,inferredById:y}};L(Q,Yo),qe.push({entityType:"proposal",entityId:At}),e.push({severity:"warning",code:"acceptance_unresolved",source:Q,message:`Proposal ${At} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(wn.some(We=>We.status==="resolved")||Rt?.gitDiff){let We=fe(b,"implementation",It,ze),Ve={...Y(We,y,[se,{kind:"iteration",id:wt}]),createdAt:Ze(ze),recordType:"implementation_attempt",state:"completed",iterationIds:[wt],coverageClaims:[],summary:wn.map(vt=>vt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};L(Q,Ve),qe.push({entityType:"implementation_attempt",entityId:We}),Ue+=1}Ce&&(Ce=void 0)});let De=pe.at(-1),st={...Y(Z,p,[se]),createdAt:Ze(de),recordType:"thread",state:De?.question?"open":"resolved",messageArtifactIds:xe,outcome:De?.question?"question_unresolved":Ue?"implementation_only":"no_outcome",resultRefs:qe};x.push(st),M.set(Q,[Z,...M.get(Q)??[]])}let ee=Ad(i);ee&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ee} model values were not promoted because their accepted decision provenance is unresolved.`});let H={manifest:{formatVersion:1,projectId:h,createdAt:Ze(k),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:n.writerVersion??"0.8.4-dev"}},records:x,events:[],relationships:[],artifacts:m,tombstones:[]},ie=$t(H),j=(n.proofCaseIds??Rd).map(B=>({legacyId:B,threadFound:d.some(({key:_,value:Q})=>(Q.id??_)===B),decisionEnvelopeFound:$.has(B),recordIds:M.get(B)??[]}));return{bundle:H,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((B,_)=>B+(_.value.messages?.length??0),0),decisionEnvelopes:v.length,modelEntries:ee,artifactsReferenced:m.length},imported:Md(x),unresolvedAcceptance:e.filter(B=>B.code==="acceptance_unresolved").length,deferredModelEntries:ee,proofCases:j,issues:e,schemaIssues:ie.issues}}}var jd=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function ki(n,e){let t=n.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),o=n.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!t||!o)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=n.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=jd(),c=d.records,I=n.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(x=>x.kind==="thread"&&x.id===e.threadId));I||(I={id:fe(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.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:[]},c.push(I));let v=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let x=n.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.value===u&&f.status==="current"));x||(x={id:fe(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:fe(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},c.push(x)),v.push(x)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let x=n.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.kind==="source_file"&&f.value===u&&f.status==="current"));x||(x={id:fe(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:fe(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},c.push(x)),v.push(x)}let g=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),k;if(g.length>0){k=fe(r,"live-observation",i,e.createdAt);let u={id:k,schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:g.map(x=>x.claim.trim()).join(" "),captureContext:{subjectIds:v.map(x=>x.id),artifactIds:[]},resolvedByIds:[]};c.push(u)}let b=fe(r,"live-iteration",i,e.completedAt),h={id:b,schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[I.id],startedAt:s,completedAt:a,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};c.push(h);let p=[],y=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),w=v.length>0?v:n.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(g.length>0&&w.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,x]of g.entries()){let m=fe(r,"live-proposal",`${i}:${u}`,e.completedAt),f=w.map($=>({subjectId:$.id,role:"governed"})),M={id:m,schemaVersion:1,projectId:n.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:b},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:x.claim.trim(),rationale:x.rationale?.trim()||void 0,proposedKind:x.proposedKind,subjects:f,subjectSemantics:f.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:x.sourceText?.trim()||e.requestSummary,iterationId:b,inferredById:o.id}};c.push(M),p.push(m)}if(y.length>0){let u=new Set(e.governingDecisionIds??[]),x=n.records.filter(f=>f.recordType==="decision"&&f.state==="active"&&u.has(f.id)),m={id:fe(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:b}],recordType:"implementation_attempt",state:"completed",iterationIds:[b],coverageClaims:x.map(f=>({decisionId:f.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${y.map(M=>M.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:b}]})),summary:y.map(f=>f.summary).join(" "),artifactIds:[]};c.push(m)}return{mutation:d,iterationId:b,proposalIds:p,observationId:k}}import{createHash as Ed}from"crypto";import{mkdir as Pi,open as dr,readFile as cr,readdir as _d,rename as Cd,unlink as lr}from"fs/promises";import{join as gt}from"path";var $d={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function lo(n){return Ed("sha256").update(JSON.stringify(n)).digest("hex")}function Ri(n){return lo(n)}function Ai(n,e,t){[...e.records,...e.recordReplacements??[]].some(o=>o.recordType==="advisory_explanation")&&!n.manifest.features.includes("advisory_explanations")&&n.manifest.features.push("advisory_explanations");for(let o of e.recordReplacements??[]){if(o.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${o.recordType}.`);let r=n.records.findIndex(s=>s.recordType===o.recordType&&s.id===o.id);if(r<0)throw new Error(`Record replacement target not found: ${o.recordType} ${o.id}`);let i=n.records[r];if(i.projectId!==o.projectId||i.createdAt!==o.createdAt||i.participantId!==o.participantId)throw new Error(`Record replacement changed immutable identity for ${o.id}.`);n.records[r]=structuredClone(o)}for(let o of e.projectionUpdates){let r=n.records.find(i=>i.recordType===o.entityType&&i.id===o.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${o.entityType} ${o.entityId}`);if(r.state!==o.fromState)throw new Error(`Projection state conflict for ${o.entityType} ${o.entityId}: expected ${o.fromState}, found ${r.state}`);r.state=o.state}return n.records.push(...e.records),n.events.push(...e.events),n.relationships.push(...e.relationships),n.artifacts.push(...e.artifacts),n.tombstones.push(...e.tombstones),n.manifest.updatedAt=t,n}function Od(n,e,t){return Ai(structuredClone(n),e,t)}async function Ot(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await dr(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
13
- `,"utf8"),await o.sync()}finally{await o.close()}try{await Cd(t,n)}catch(r){throw await lr(t).catch(()=>{}),r}}async function Rn(n){return JSON.parse(await cr(n,"utf8"))}var po=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=gt(e,".popmelt","memory"),this.journalDir=gt(this.memoryDir,"journal"),this.manifestPath=gt(this.memoryDir,"manifest.json"),this.checkpointPath=gt(this.memoryDir,"checkpoint.json"),this.lockPath=gt(this.memoryDir,"writer.lock")}async readHead(){let e=await Rn(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=$t(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Pi(this.journalDir,{recursive:!0});try{throw await cr(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(o){if(o instanceof Error&&o.message==="Memory journal is already initialized."||o.code!=="ENOENT")throw o}await this.withWriterLock(async()=>{try{throw await cr(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 o=lo(e),r={storageVersion:1,sequence:0,hash:o,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:o},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await Ot(this.checkpointPath,r),await Ot(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 Ot(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 t=lo(e.bundle),o=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await Ot(gt(this.memoryDir,o),r),e.manifest.checkpoint={file:o,sequence:r.sequence,hash:t},await Ot(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Zt(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let o=await this.loadInternal();if(o.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let r=o.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:o.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:o.report.headHash,mutation:e},s={...i,hash:Ri(i)},a=Od(o.bundle,e,t.committedAt),d=$t(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let c=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await Ot(gt(this.journalDir,c),s),o.manifest.head={sequence:r,hash:s.hash},o.manifest.updatedAt=t.committedAt,await Ot(this.manifestPath,o.manifest),{bundle:a,report:{checkpointSequence:o.report.checkpointSequence,appliedTransactions:o.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:o.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...$d,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Rn(this.manifestPath),t=await Rn(gt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==lo(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let o=await _d(this.journalDir),r=o.filter(g=>g.endsWith(".tmp")),s=o.filter(g=>/^\d{12}-[0-9a-f-]+\.json$/i.test(g)).sort().filter(g=>Number(g.slice(0,12))>t.sequence),a=structuredClone(t.bundle),d=t.sequence,c=t.journalHash??null,I=new Set;for(let g of s){let k=await Rn(gt(this.journalDir,g)),{hash:b,...h}=k;if(b!==Ri(h))throw new Error(`Journal hash mismatch: ${g}`);if(k.sequence!==d+1)throw new Error(`Journal sequence gap at ${g}`);if(k.previousHash!==c)throw new Error(`Journal chain mismatch at ${g}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${g}`);if(I.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);Ai(a,k.mutation,k.committedAt),d=k.sequence,c=k.hash,I.add(k.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==c)throw new Error("Journal manifest head hash mismatch.");let v=$t(a);if(!v.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(v.issues)}`);return{bundle:a,manifest:e,transactionIds:I,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:c}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Pi(this.memoryDir,{recursive:!0});let t;try{t=await dr(this.lockPath,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let r=await Rn(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 lr(this.lockPath),t=await dr(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await lr(this.lockPath).catch(()=>{})}}};import{createHash as Dd}from"crypto";import{mkdir as Nd,open as Bd,readFile as Jd,rename as qd,unlink as Ld}from"fs/promises";import{join as Mi}from"path";function ji(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ei(n){return Dd("sha256").update(JSON.stringify(n)).digest("hex")}async function Fd(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await Bd(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
14
- `,"utf8"),await o.sync()}finally{await o.close()}try{await qd(t,n)}catch(r){throw await Ld(t).catch(()=>{}),r}}function Ud(n,e,t=new Date().toISOString()){let o={},r={},i={},s=(d,c,I)=>{let v=d[c]??=[];v.includes(I)||v.push(I)};for(let d of n.records)if(d.recordType==="subject"){let c=d;for(let I of[c.label,...c.aliases,...c.locators.filter(v=>v.status==="current").map(v=>v.value)]){let v=ji(I);v&&s(o,v,c.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let c of d.subjects)s(r,c.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let c of d.subjects)s(i,c.subjectId,d.id);let a={version:1,projectId:n.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:o,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:Ei(a)}}function _i(n,e){let t=[...new Set(e.flatMap(o=>n.subjectIdsByValue[ji(o)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(o=>n.decisionIdsBySubject[o]??[]))],proposalIds:[...new Set(t.flatMap(o=>n.proposalIdsBySubject[o]??[]))]}}var uo=class{constructor(e){this.indexDir=Mi(e,".popmelt","memory","indexes"),this.indexPath=Mi(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await Jd(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===t.sequence&&r.journalHead.hash===t.hash&&i===Ei(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let o=Ud(e,t);return await Nd(this.indexDir,{recursive:!0}),await Fd(this.indexPath,o),o}};import{randomBytes as zd}from"crypto";function je(n=Date.now()){let t=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),o=zd(10).toString("hex"),r=(Number.parseInt(o[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${o.slice(0,3)}-${r}${o.slice(4,7)}-${o.slice(7,19)}`}var jn="popmelt:imprint",Oi="popmelt:imprint-evidence",nn="popmelt:imprint-relation";function Mn(n){return n.sourceRefs.find(e=>e.kind==="external"&&e.uri===jn)?.id}function pr(n){let e=new Set;return n.filter(t=>{let o=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(o)?!1:(e.add(o),!0)})}function mo(n,e){if(!n)return[];let t=new Set(n.relations.flatMap(o=>o.type==="expresses"&&!o.toStoreId&&o.toId===e?[o.fromId]:[]));return n.concrete.filter(o=>t.has(o.id)).map(o=>({id:o.id,modelPath:o.modelPath,value:structuredClone(o.value),createdAt:o.createdAt,updatedAt:o.updatedAt}))}function ur(n){if(n==="expresses")return"expresses";if(n==="excepts")return"excepts"}var sn=class{constructor(e){this.projectRoot=e;this.store=new po(e),this.indexStore=new uo(e),this.manifestPath=tn(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await An(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 o=await Pn({...e,projectRoot:this.projectRoot});if(o.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(o.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(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Pn({...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=tn(this.projectRoot,".popmelt","memory","migrations"),t=tn(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await An(t,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let o;try{o=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!o?.explanations)return await Ci(e,{recursive:!0}),await $i(t,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"),a=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(!a||!d)return{migrated:!1,explanations:0,evidence:0};let c=r.bundle.manifest.projectId,I=new Set(r.bundle.records.map(u=>u.id)),v=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(x=>x.kind==="external"&&x.uri===nn?[x.id]:[]))),g=new Map,k=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of o.explanations){let x=k.find(m=>Mn(m)===u.id);g.set(u.id,x?.id??fe(c,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let b=[],h=[],p=[],y=0;for(let u of o.explanations){let x=g.get(u.id),m=k.find(E=>E.id===x),f=[],M=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 E of M){let F=fe(c,"imprint-evidence-record",E.id,Date.parse(E.createdAt));f.push(F),!I.has(F)&&(b.push({id:F,schemaVersion:1,projectId:c,createdAt:E.createdAt,participantId:a.id,sourceRefs:pr([{kind:"external",id:E.id,uri:Oi},{kind:"external",id:u.id,uri:jn},{kind:"thread",id:E.threadId},{kind:"message",id:E.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(E.kind)?"user_feedback":"judgment",summary:E.summary,availability:"available",artifactIds:[]}),p.push({id:fe(c,"imprint-evidence-link",`${u.id}:${E.id}`,Date.parse(E.createdAt)),schemaVersion:1,projectId:c,createdAt:E.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:E.id,uri:Oi}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:x},to:{entityType:"evidence",entityId:F},reason:"This advisory explanation was derived from collaboration evidence."}),y+=1)}let $={id:x,schemaVersion:1,projectId:c,createdAt:m?.createdAt??u.createdAt,participantId:m?.participantId??a.id,sourceRefs:pr([...m?.sourceRefs??[],{kind:"external",id:u.id,uri:jn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...m?.evidenceIds??[],...f])],concreteBindings:mo(o,u.id),supersededById:u.supersededBy?g.get(u.supersededBy):void 0,updatedAt:u.updatedAt};m?h.push($):b.push($)}for(let u of o.relations){let x=ur(u.type);if(!x||u.toStoreId)continue;let m=g.get(u.fromId),f=g.get(u.toId);!m||!f||v.has(u.id)||p.push({id:fe(c,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:c,createdAt:u.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:u.id,uri:nn}],recordType:"relationship",relationshipType:x,from:{entityType:"advisory_explanation",entityId:m},to:{entityType:"advisory_explanation",entityId:f},reason:u.rationale||"The Imprint graph connected these explanations."})}let w=new Date().toISOString();if(b.length||h.length||p.length)try{let u=await this.store.commit({records:b,recordReplacements:h,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(c,"imprint-advisories-v2",o.projectId,Date.parse(o.updatedAt)),committedAt:w});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Ci(e,{recursive:!0}),await $i(t,JSON.stringify({version:2,migratedAt:w,explanations:o.explanations.length,evidence:y,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:o.explanations.length,evidence:y}}async review(e,t={}){let o=await this.loadSource(t),r=await this.withIndexedCandidates(o,e);return{source:o.source,selection:ir(o.bundle,r)}}async contextualize(e,t={}){let o=await this.loadSource(t),r=await this.withIndexedCandidates(o,e);return{source:o.source,actionPacket:bi(o.bundle,r),reviewSelection:ir(o.bundle,r)}}async imprintTopology(){let e;try{e=await this.loadJournalSource()}catch(t){if(t.code==="ENOENT")return{explanations:[],relations:[]};throw t}return{explanations:e.bundle.records.flatMap(t=>t.recordType==="advisory_explanation"?[{memoryId:t.id,explanationId:Mn(t)??t.id}]:[]),relations:e.bundle.relationships.flatMap(t=>t.relationshipType!=="expresses"&&t.relationshipType!=="excepts"||t.from.entityType!=="advisory_explanation"||t.to.entityType!=="advisory_explanation"?[]:[{id:t.id,type:t.relationshipType,from:{memoryId:t.from.entityId,...t.from.storeId?{storeId:t.from.storeId}:{}},to:{memoryId:t.to.entityId,...t.to.storeId?{storeId:t.to.storeId}:{}},rationale:t.reason}])}}async planReview(e,t={}){let o=await this.loadSource(t);return{source:o.source,result:co(o.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 t=await Pn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(o=>o.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let o=await this.store.load(),r=co(o.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,t);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 t=await this.store.load(),o=t.bundle.records.find(g=>g.recordType==="proposal"&&g.id===e.proposalId),r=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!o||o.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:o?o.state!=="pending"?`The proposal is already ${o.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),a={proposalId:o.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:je(i),decisionId:je(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:je(i),replacementProposalId:je(i),acceptanceEventId:je(i),decisionId:je(i),relationshipId:je(i),claim:e.claim,kind:e.kind,subjects:o.subjects,subjectSemantics:o.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:je(i),reason:e.reason}:{...a,action:"defer",eventId:je(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:o.subjects.map(g=>g.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},c=co(t.bundle,d);if(!c.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:c.errors.map(g=>g.message).join(" ")};let I=await this.store.commitReviewPlan(c.plan,{transactionId:je(i),committedAt:s});await this.refreshIndex(I);let v=c.plan.resultRefs.find(g=>g.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:v,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:I.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),o=ki(t.bundle,e),r=fe(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(o.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:o.iterationId,proposalIds:o.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:o.iterationId,proposalIds:o.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let o=await this.store.load(),r=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),i=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="ai"&&w.status==="active"),s=e.action?r:i??r,a=o.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),I=o.bundle.manifest.projectId,v=[],g=[],k=[],b=o.bundle.records.filter(w=>w.recordType==="advisory_explanation"),h=new Map(b.flatMap(w=>{let u=Mn(w);return u?[[u,w.id]]:[]}));for(let w of e.summary.changes)if(!h.has(w.explanationId)){let u=t?.explanations.find(x=>x.id===w.explanationId);h.set(w.explanationId,fe(I,"imprint-explanation",w.explanationId,Date.parse(u?.createdAt??d)))}for(let w of e.summary.changes){let u={kind:"external",id:w.explanationId,uri:jn},x=h.get(w.explanationId),m=b.find(E=>E.id===x),f=t?.explanations.find(E=>E.id===w.explanationId),M={id:fe(I,"imprint-live-evidence",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,c),schemaVersion:1,projectId:I,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:[]};v.push(M);let $={id:x,schemaVersion:1,projectId:I,createdAt:m?.createdAt??f?.createdAt??d,participantId:m?.participantId??s.id,sourceRefs:pr([...m?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:f?.kind??m?.kind??"pattern",state:f?.state??w.state,statement:f?.statement??w.statement,rationale:f?.rationale??m?.rationale??e.summary.detail,scope:structuredClone(f?.scope??m?.scope??{kind:"project",values:[]}),subjectIds:m?.subjectIds??[a.id],evidenceIds:[...new Set([...m?.evidenceIds??[],M.id])],concreteBindings:f?mo(t,w.explanationId):m?.concreteBindings??[],supersededById:f?.supersededBy?h.get(f.supersededBy):m?.supersededById,updatedAt:f?.updatedAt??d};m?g.push($):v.push($),k.push({id:fe(I,"imprint-live-evidence-link",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,c),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:$.id},to:{entityType:"evidence",entityId:M.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(o.bundle.relationships.flatMap(w=>w.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===nn?[u.id]:[])));for(let w of t?.relations??[]){let u=ur(w.type);if(!u)continue;let x=h.get(w.fromId),m=w.toStoreId?e.qualifiedExplanationMemoryIds?.[`${w.toStoreId}:${w.toId}`]:h.get(w.toId);!x||!m||p.has(w.id)||k.push({id:fe(I,"imprint-relation",w.id,Date.parse(w.createdAt)),schemaVersion:1,projectId:I,createdAt:w.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:w.id,uri:nn}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:x},to:{entityType:"advisory_explanation",entityId:m,...w.toStoreId?{storeId:w.toStoreId}:{}},reason:w.rationale||"The Imprint graph connected these explanations."})}let y=fe(o.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let w=await this.store.commit({records:v,recordReplacements:g,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:y,committedAt:d});await this.refreshIndex(w)}catch(w){if(!(w instanceof Error)||!w.message.includes("Transaction already exists"))throw w}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),o=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")??o;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let a=t.bundle.manifest.projectId,d=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),c=new Map(d.flatMap(f=>{let M=Mn(f);return M?[[M,f]]:[]})),I=new Map([...[...c].map(([f,M])=>[f,M.id]),...e.explanations.filter(f=>!c.has(f.id)).map(f=>[f.id,fe(a,"imprint-explanation",f.id,Date.parse(f.createdAt))])]),v=[],g=[],k=new Set(e.explanations.map(f=>f.id));for(let f of e.explanations){let M=c.get(f.id);if(!M){v.push({id:I.get(f.id),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:jn}],recordType:"advisory_explanation",kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:mo(e,f.id),supersededById:f.supersededBy?I.get(f.supersededBy):void 0,updatedAt:f.updatedAt});continue}let $={...structuredClone(M),kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),concreteBindings:mo(e,f.id),supersededById:f.supersededBy?I.get(f.supersededBy):void 0,updatedAt:f.updatedAt},E=F=>JSON.stringify({kind:F.kind,state:F.state,statement:F.statement,rationale:F.rationale,scope:F.scope,concreteBindings:F.concreteBindings,supersededById:F.supersededById,updatedAt:F.updatedAt});E(M)!==E($)&&g.push($)}for(let[f,M]of c)k.has(f)||M.state==="retired"||g.push({...structuredClone(M),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let b=new Set(t.bundle.tombstones.flatMap(f=>f.objectType==="relationship"?[f.objectId]:[])),h=new Map(t.bundle.relationships.flatMap(f=>{if(b.has(f.id))return[];let M=f.sourceRefs.find($=>$.kind==="external"&&$.uri===nn)?.id;return M?[[M,f]]:[]})),p=[],y=new Set;for(let f of e.relations){let M=ur(f.type);if(!M||f.toStoreId)continue;let $=I.get(f.fromId),E=I.get(f.toId);if(!$||!E)continue;let F=h.get(f.id);F&&F.relationshipType===M&&F.from.entityType==="advisory_explanation"&&F.from.entityId===$&&F.to.entityType==="advisory_explanation"&&F.to.entityId===E||(F&&y.add(f.id),p.push({id:fe(a,"imprint-relation",`${f.id}:${M}:${$}:${E}`,Date.parse(f.createdAt)),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:nn}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:$},to:{entityType:"advisory_explanation",entityId:E},reason:f.rationale||"The Imprint graph connected these explanations."}))}let w=new Set(e.relations.map(f=>f.id)),u=o?[...h].filter(([f])=>!w.has(f)||y.has(f)).map(([,f])=>({id:fe(a,"imprint-relationship-tombstone",f.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:f.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:o.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!v.length&&!g.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let x=e.updatedAt,m=fe(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(x));try{let f=await this.store.commit({records:v,recordReplacements:g,events:[],relationships:p,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:m,committedAt:x});return await this.refreshIndex(f),{status:"synced",relationships:p.length+u.length,explanations:v.length+g.length,headSequence:f.report.headSequence}}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f;return{status:"no_change",relationships:0,explanations:0,headSequence:t.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 t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let o={};for(let r of t.bundle.records)o[r.recordType]=(o[r.recordType]??0)+1;return{status:e,journal:t.report,records:o,openFreshnessSignals:t.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:t.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:t}=await this.store.load(),o=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(a=>a.status==="projected").map(a=>a.decisionId):[])),r=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!o.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,a)=>a.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(),t=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),o=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=>t.has(i))&&o.set(r.key,r);return[...o.values()]}async getImprintView(e=[],t){let o=()=>({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 o();let r=await this.store.load(),i=r.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(i.map(p=>[p.id,p])),a=new Map(i.flatMap(p=>{let y=Mn(p);return y?[[y,p.id]]:[]})),d=new Set(e.map(p=>a.get(p)??p)),c=new Map(r.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),I=new Map(r.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),v=new Set(r.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),g=new Set(["expresses","operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=i.map(p=>{let y=p.evidenceIds.flatMap(m=>{let f=I.get(m);if(!f)return[];let M=f.sourceRefs.find(Y=>Y.kind==="thread")?.id,$=f.sourceRefs.find(Y=>Y.kind==="message")?.id,E=f.kind==="judgment"||f.kind==="user_feedback"||f.kind==="project_state"?f.kind:"other",F=c.get(f.participantId)??"unknown";return[{id:f.id,kind:E,summary:f.summary,createdAt:f.createdAt,participantKind:F,threadId:M,jobId:$}]}).sort((m,f)=>f.createdAt.localeCompare(m.createdAt)),w=r.bundle.relationships.flatMap(m=>{if(v.has(m.id))return[];if(!g.has(m.relationshipType))return[];let f=m.from.entityType==="advisory_explanation"&&m.from.entityId===p.id&&m.to.entityType==="advisory_explanation",M=m.to.entityType==="advisory_explanation"&&m.to.entityId===p.id&&m.from.entityType==="advisory_explanation";if(!f&&!M)return[];let $=f?m.to.entityId:m.from.entityId,E=s.get($);return E?[{id:m.id,type:m.relationshipType==="excepts"?"excepts":"expresses",direction:f?"outgoing":"incoming",explanationId:E.id,statement:E.statement,rationale:m.reason}]:[]}),u=[...(p.supersededById?[p.supersededById]:[]).flatMap(m=>{let f=s.get(m);return f?[{id:`supersedes:${p.id}:${f.id}`,type:"supersedes",direction:"incoming",explanationId:f.id,statement:f.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...i.flatMap(m=>m.supersededById===p.id?[{id:`supersedes:${m.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:m.id,statement:m.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],x=[...new Set([...p.sourceRefs.flatMap(m=>m.kind==="thread"?[m.id]:[]),...y.flatMap(m=>m.threadId?[m.threadId]:[])])].filter(m=>!t||t.has(m));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(m=>({...structuredClone(m)})),relations:[...w,...u],sourceThreadIds:x,needsGrounding:p.state==="testing"&&d.has(p.id)}}).sort((p,y)=>Number(y.needsGrounding)-Number(p.needsGrounding)||k[p.state]-k[y.state]||y.updatedAt.localeCompare(p.updatedAt)),h={total:b.filter(p=>p.state!=="retired").length,emerging:b.filter(p=>p.state==="emerging").length,testing:b.filter(p=>p.state==="testing").length,grounded:b.filter(p=>p.state==="grounded").length,challenged:b.filter(p=>p.state==="challenged").length,retired:b.filter(p=>p.state==="retired").length,needsGrounding:b.filter(p=>p.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:h,explanations:b}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(a=>a.recordType==="decision"&&a.state==="active"?[a.id]:[])),o=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,c)=>d.createdAt.localeCompare(c.createdAt)))a.decisionIds.some(d=>t.has(d))&&o.set(a.key,a);let r=[...o.values()],i=e.records.filter(a=>a.recordType==="verification_attempt");return{decisions:e.records.filter(a=>a.recordType==="decision"&&a.state==="active").map(a=>{let d=i.filter(c=>c.targets.some(I=>I.entityType==="decision"&&I.entityId===a.id)).sort((c,I)=>I.createdAt.localeCompare(c.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(c=>c.decisionIds.includes(a.id)),verification:d?d.state:"unverified"}}),entries:r.map(a=>({id:a.id,key:a.key,value:a.value,decisionIds:a.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),o=t.bundle.records.find(E=>E.recordType==="participant"&&E.kind==="human"&&E.status==="active"),r=t.bundle.records.find(E=>E.recordType==="subject"&&E.subjectType==="project");if(!o||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=je(i),d=je(i),c=je(i),I=je(i),v=je(i),g=new Set(t.bundle.records.flatMap(E=>E.recordType==="model_entry"&&E.key===e.key?E.decisionIds:[])),k=t.bundle.records.filter(E=>E.recordType==="decision"&&E.state==="active"&&g.has(E.id)),b={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},h=[{subjectId:r.id,role:"governed"}],p={...b,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:h,origin:{mode:"declared",sourceText:e.claim,reviewedById:o.id}},y={...b,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:a},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},w={...b,id:c,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:o.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:h,noChange:!1,effectiveAt:s},u={...b,id:I,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[c],value:e.value},x={...b,id:v,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:o.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[c],entryIds:[I],coverage:[{decisionId:c,status:"projected"}]},m={...b,id:je(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:I},to:{entityType:"decision",entityId:c},reason:"The model change is projected from the owner-confirmed decision."},f=k.map(E=>({...b,id:je(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:E.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),M=k.map(E=>({...b,id:je(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:w.id},to:{entityType:"decision",entityId:E.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),$=await this.store.commit({records:[p,w,u,x],events:[y,...f],relationships:[m,...M],artifacts:[],tombstones:[],projectionUpdates:k.map(E=>({entityType:"decision",entityId:E.id,fromState:"active",state:"superseded"}))},{transactionId:je(i),committedAt:s});return await this.refreshIndex($),{decisionId:c,entryId:I}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),o=t.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return o?{proposalId:o.id,claim:o.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),o=new Map(t.records.flatMap(r=>r.recordType==="subject"?[[r.id,r.label]]:[]));return t.records.filter(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.kind==="thread"&&i.id===e)).sort((r,i)=>r.createdAt.localeCompare(i.createdAt)).map(r=>({proposalId:r.id,claim:r.claim,rationale:r.rationale,proposedKind:r.proposedKind,subjectLabels:r.subjects.flatMap(i=>{let s=o.get(i.subjectId);return s?[s]:[]})}))}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 t=await this.store.load(),o=t.bundle.records.find(b=>b.recordType==="model_projection"&&b.state==="applied"&&b.runId===e.runId);if(o)return{projectionId:o.id,entryIds:o.entryIds,headSequence:t.report.headSequence};let r=t.bundle.records.filter(b=>b.recordType==="decision"&&e.decisionIds.includes(b.id)&&b.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=t.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=je(s),c=e.changes.map(b=>{let h=b.decisionIds?.filter(w=>e.decisionIds.includes(w)),p=h?.length?h:e.decisionIds,y=[...new Set(r.filter(w=>p.includes(w.id)).flatMap(w=>w.subjects.map(u=>u.subjectId)))];return{id:je(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:p.map(w=>({kind:"record",id:w})),recordType:"model_entry",key:b.path.map(String).join("."),subjectIds:y,decisionIds:p,value:b.value}}),I=new Set(c.flatMap(b=>b.decisionIds)),v={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(b=>({kind:"record",id:b})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:a,decisionIds:e.decisionIds,entryIds:c.map(b=>b.id),coverage:e.decisionIds.map(b=>e.coverage?.find(h=>h.decisionId===b)??{decisionId:b,status:I.has(b)?"projected":"unprojected"})},g=c.flatMap(b=>b.decisionIds.map(h=>({id:je(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:v.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b.id},to:{entityType:"decision",entityId:h},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...c,v],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:je(s),committedAt:a});return await this.refreshIndex(k),{projectionId:d,entryIds:c.map(b=>b.id),headSequence:k.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await Pn({...e,projectRoot:this.projectRoot})).bundle}}async loadJournalSource(){let e=await this.store.readHead(),t=`${e.checkpointSequence}:${e.checkpointHash}:${e.sequence}:${e.hash??""}`;if(this.contextualSourceCache?.headKey===t)return this.contextualSourceCache.value;let o=await this.store.load(),r={source:"journal",bundle:o.bundle,journal:o.report};return this.contextualSourceCache={headKey:t,value:r},r}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let o=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=_i(o,t.subjectHints??[]);return r?{...t,subjectIds:[...new Set([...t.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:t}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 rn(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object.");return n}function Oe(n,e){if(typeof n!="string"||!n.trim())throw new Error(`${e} must be a non-empty string.`);return n}function on(n,e,t){let o=Oe(n,e);if(!t.includes(o))throw new Error(`${e} is invalid.`);return o}function mr(n){let e=rn(n),t=rn(e.authority),o=t.level,r=t.mode,i=on(o,"authority.level",["owner","delegate","contributor"]),s=on(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Oe(e.proposalId,"proposalId"),participantId:Oe(e.participantId,"participantId"),occurredAt:Oe(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...a,action:"accept",eventId:Oe(e.eventId,"eventId"),decisionId:Oe(e.decisionId,"decisionId"),kind:on(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Oe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Oe(e.eventId,"eventId"),reason:Oe(e.reason,"reason")};case"defer":{let d=rn(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...a,action:"defer",eventId:Oe(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(c=>Oe(c,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(c=>on(c,"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{...a,action:"edit_and_accept",withdrawalEventId:Oe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Oe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Oe(e.acceptanceEventId,"acceptanceEventId"),decisionId:Oe(e.decisionId,"decisionId"),relationshipId:Oe(e.relationshipId,"relationshipId"),claim:Oe(e.claim,"claim"),kind:on(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let c=rn(d);return{subjectId:Oe(c.subjectId,"subjectId"),role:on(c.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:Oe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function fr(n){let e=rn(n),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Oe(a,s))}},o=(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:rn(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:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:o(e.maxPackets,"maxPackets"),maxEstimatedTokens:o(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}}var Gd=1400,Wd=6,Vd=2,hr=6;function Di(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.projectRoot=="string"&&!!e.projectRoot.trim()&&typeof e.projectId=="string"&&!!e.projectId.trim()}function Ji(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Di(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(Di):[],o=new Set([e.primary.storeId]);return{primary:e.primary,mounted:t.filter(r=>o.has(r.storeId)?!1:(o.add(r.storeId),!0))}}function Ni(n){return[n.primary,...n.mounted]}function En(n){let e=[],t=Math.max(0,...n.map(o=>o.length));for(let o=0;o<t;o++)for(let r of n)r[o]!==void 0&&e.push(r[o]);return e}function Bi(n){return Math.ceil(JSON.stringify(n).length/4)}function Kd(n,e,t){return{...n,...n.acceptedTruth?{acceptedTruth:{...n.acceptedTruth,decisions:n.acceptedTruth.decisions.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),conflicts:n.acceptedTruth.conflicts.map(o=>({...o,storeId:e.storeId}))}}:{},packets:n.packets.map(o=>({...o,presentation:t?"advisory":o.presentation,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Hd(n,e,t,o){if(!n.length)return;if(!o&&e.length===0)return n[0].context;let r=n.map(({store:v,context:g})=>Kd(g,v,v.storeId!==t)),i=En(r.map(v=>v.acceptedTruth?.decisions??[])).slice(0,Wd),s=new Set(i.map(v=>`${v.storeId}:${v.id}`)),a=r.flatMap(v=>v.acceptedTruth?.conflicts??[]).filter(v=>v.decisionIds.every(g=>s.has(`${v.storeId}:${g}`))),d=En(r.map(v=>v.packets)).slice(0,Vd),c=i.length<r.reduce((v,g)=>v+(g.acceptedTruth?.decisions.length??0),0)||d.length<r.reduce((v,g)=>v+g.packets.length,0),I={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:c||r.some(v=>v.acceptedTruth?.truncated)}}:{},packets:d,truncated:c||e.length>0||r.some(v=>v.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;Bi(I)>Gd;){if(I.packets.length)I.packets.pop();else if(I.acceptedTruth?.decisions.length)I.acceptedTruth.decisions.pop();else break;I.truncated=!0,I.acceptedTruth&&(I.acceptedTruth.truncated=!0)}if(I.estimatedTokens=Bi(I),!(!I.packets.length&&!I.acceptedTruth?.decisions.length))return I}function qi(n,e,t){return{...n,explanations:n.explanations.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),relations:n.relations?.map(o=>({...o,storeId:e.storeId,readOnly:t,from:o.from??{storeId:e.storeId,explanationId:o.fromId},to:o.to??{storeId:o.toStoreId??e.storeId,explanationId:o.toId}})),historicalCaveats:n.historicalCaveats?.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Ee(n,e){return`${n}:${e}`}function Qd(n){let e=n.from??{storeId:n.storeId??"",explanationId:n.fromId},t=n.to??{storeId:n.storeId??"",explanationId:n.toId};return`${n.storeId??""}:${n.type}:${Ee(e.storeId,e.explanationId)}:${Ee(t.storeId,t.explanationId)}`}function Xd(n,e){let t=new Map;for(let{store:o,topology:r}of n)for(let i of r.explanations)t.set(Ee(o.storeId,i.memoryId),i.explanationId);return n.flatMap(({store:o,topology:r})=>r.relations.flatMap(i=>{let s=i.from.storeId??o.storeId,a=i.to.storeId??o.storeId,d=t.get(Ee(s,i.from.memoryId)),c=t.get(Ee(a,i.to.memoryId));return!d||!c?[]:[{id:i.id,type:i.type,fromId:d,toId:c,rationale:i.rationale,storeId:o.storeId,readOnly:o.storeId!==e,from:{storeId:s,explanationId:d},to:{storeId:a,explanationId:c}}]}))}function Yd(n){let e=new Set;return n.filter(t=>{let o=Qd(t);return e.has(o)?!1:(e.add(o),!0)})}function Zd(n,e,t,o,r=[],i=[],s=[]){if(!n.length)return;if(!o&&e.length===0)return n[0].context;let a=n.map(({store:u,context:x})=>qi(x,u,u.storeId!==t)),d=En(a.map(u=>u.explanations)),c=Yd([...a.flatMap(u=>u.relations??[]),...r]),I=new Map([...d,...i].map(u=>[Ee(u.storeId??"",u.id),u])),v=[],g=new Set,k=u=>{if(!u||v.length>=hr)return;let x=Ee(u.storeId??"",u.id);g.has(x)||(g.add(x),v.push(u))};for(let u of d.slice(0,hr)){let x=Ee(u.storeId??"",u.id),m=c.flatMap(f=>f.from&&Ee(f.from.storeId,f.from.explanationId)===x?[I.get(Ee(f.to.storeId,f.to.explanationId))]:f.to&&Ee(f.to.storeId,f.to.explanationId)===x?[I.get(Ee(f.from.storeId,f.from.explanationId))]:[]).find(Boolean);m&&(k(u),k(m))}d.forEach(k),i.forEach(k);let b=v,h=c.filter(u=>{let x=u.from,m=u.to;return!!(x&&m&&g.has(Ee(x.storeId,x.explanationId))&&g.has(Ee(m.storeId,m.explanationId)))}),p=new Set([...d.map(u=>Ee(u.storeId??"",u.id)),...i.map(u=>Ee(u.storeId??"",u.id))]).size,y=[...new Set(a.flatMap(u=>u.pendingGroundingExplanationIds??[]))],w=[...new Set(a.flatMap(u=>u.correctionExplanationIds??[]))];return{explanations:b,relations:h,truncated:b.length<p||e.length>0||a.some(u=>u.truncated),...a.find(u=>u.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(u=>u.retrievalIntent).retrievalIntent}:{},historicalCaveats:En(a.map(u=>u.historicalCaveats??[])).slice(0,3),...y.length?{pendingGroundingExplanationIds:y}:{},...w.length?{correctionExplanationIds:w}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var fo=class{constructor(e,t,o=r=>({memory:new sn(r.projectRoot),imprint:new kt(r.projectRoot,r.projectId)})){this.primary=e;this.createReader=o;this.readers=new Map;this.state={reads:0,storeReads:0,failedStoreReads:0,lastDurationMs:0};this.readers.set(e.storeId,t)}diagnostics(){return{...this.state}}normalized(e){return!e||e.primary.storeId!==this.primary.storeId||e.primary.projectId!==this.primary.projectId?{primary:this.primary,mounted:[]}:{primary:this.primary,mounted:e.mounted}}reader(e){let t=this.readers.get(e.storeId);if(t)return t;let o=this.createReader(e);return this.readers.set(e.storeId,o),o}async memoryContext(e,t,o){let r=performance.now(),i=Ni(this.normalized(e)),s=await Promise.allSettled(i.map(async c=>{let I,v=await io(this.reader(c).memory,t,o,g=>{I=g});if(I)throw I;return{store:c,context:v}})),a=s.flatMap(c=>c.status==="fulfilled"&&c.value.context?[c.value]:[]),d=s.flatMap((c,I)=>c.status==="rejected"?[i[I].storeId]:[]);return this.record(i.length,d.length,r),Hd(a,d,this.primary.storeId,i.length>1)}async imprintContext(e,t){let o=performance.now(),r=Ni(this.normalized(e)),i=r.length>1,s=r.map(async R=>({store:R,context:await this.reader(R).imprint.contextualize(R.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async R=>({store:R,topology:await(this.reader(R).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[d,c]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),I=d.flatMap(R=>R.status==="fulfilled"&&R.value.context?[R.value]:[]),v=d.flatMap((R,J)=>R.status==="rejected"?[r[J].storeId]:[]),g=c.flatMap(R=>R.status==="fulfilled"?[R.value]:[]),k=c.flatMap((R,J)=>R.status==="rejected"?[r[J].storeId]:[]),b=new Map(g.flatMap(({store:R,topology:J})=>J.explanations.map(W=>[Ee(R.storeId,W.explanationId),W.memoryId]))),h=I.map(({store:R,context:J})=>({store:R,context:{...J,explanations:J.explanations.map(W=>({...W,memoryId:b.get(Ee(R.storeId,W.id))}))}})),p=Xd(g,this.primary.storeId),y=h.map(({store:R,context:J})=>qi(J,R,R.storeId!==this.primary.storeId)),w=En(y.map(R=>R.explanations)).slice(0,hr),u=new Set(w.map(R=>Ee(R.storeId??"",R.id))),x=new Set(y.flatMap(R=>R.explanations.map(J=>Ee(J.storeId??"",J.id)))),m=new Map,f=(R,J)=>{if(x.has(Ee(R,J)))return;let W=m.get(R)??new Set;W.add(J),m.set(R,W)};for(let R of p){if(!R.from||!R.to)continue;let J=Ee(R.from.storeId,R.from.explanationId),W=Ee(R.to.storeId,R.to.explanationId);u.has(J)&&f(R.to.storeId,R.to.explanationId),u.has(W)&&f(R.from.storeId,R.from.explanationId)}let M=new Map(r.map(R=>[R.storeId,R])),$=[...m].map(async([R,J])=>{let W=M.get(R),ee=W?this.reader(W).imprint.explanationsByIds:void 0;if(!W||!ee)return{storeId:R,explanations:[]};let H=await ee.call(this.reader(W).imprint,[...J]);return{storeId:R,explanations:H.map(ie=>({...ie,memoryId:b.get(Ee(R,ie.id)),storeId:R,storeRoot:W.projectRoot,readOnly:R!==this.primary.storeId}))}}),E=await Promise.allSettled($),F=E.flatMap(R=>R.status==="fulfilled"?R.value.explanations:[]),Y=E.flatMap((R,J)=>R.status==="rejected"?[[...m.keys()][J]]:[]),L=[...new Set([...k,...Y])];return this.record(r.length,new Set([...v,...L]).size,o),Zd(h,v,this.primary.storeId,i,p,F,L)}record(e,t,o){this.state.reads+=1,this.state.storeReads+=e,this.state.failedStoreReads+=t,this.state.lastDurationMs=Math.max(0,performance.now()-o)}};function an(n,e){return!n||e||n.attention!=="response_requested"?n:{...n,attention:"response_available"}}function _n(n){let e=Array.from(new Set((n.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],o=n.decisionRequired?"decision_required":n.question||n.groundingRequired?"response_requested":n.reviewRequired||n.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return n.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:n.imprintTransactionId}),{attention:o,outcomes:t}}var Dt=1,gr="bridge";function Li(n){return`codex-session:${n}`}function rc(n,e){return`codex-${ec("sha256").update(`${n}:${e}`).digest("hex").slice(0,16)}`}function Fi(n){return{timestamp:new Date().toISOString(),url:"codex://ambient",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[{id:"ambient-prompt",type:"instruction",instruction:n,elements:[]}],styleModifications:[]}}function Ui(n,e){let t=new Set,o=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(nc(s)?oc(e,s):s)},r=(i,s="",a=0)=>{if(!(a>5||i===null||i===void 0)){if(typeof i=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&o(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))o(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,c]of Object.entries(i))r(c,d,a+1)}};for(let i of n)r(i.toolInput);return[...t]}function ho(n){return n?Math.ceil(n.length/4):0}function zi(n,e,t,o,r,i){let s=["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${t}; the tool session is ${n}.`,"The human remains the authority for accepted product decisions and Imprint grounding. Never infer acceptance from implementation, praise, silence, or ambiguity.","Popmelt records the turn automatically. Use Popmelt Core tools only for intentional context expansion, explicit decision review, Imprint grounding, or a structured learning assessment."].join(`
15
- `),a=Sn(o),d=Gi(r,i),c=[s,a,d].filter(Boolean).join(`
16
- `);return{additionalContext:c,contextBudget:{protocolEstimatedTokens:ho(s),memoryEstimatedTokens:ho(a),imprintEstimatedTokens:ho(d),totalEstimatedTokens:ho(c)}}}function Gi(n,e){return n?Qt(n,{requestText:e}).split(`
12
+ `)}import{mkdir as $i,readFile as An,writeFile as Oi}from"fs/promises";import{join as tn}from"path";var sd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function or(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function so(n){return new Set(or(n).split(" ").filter(e=>e.length>2&&!sd.has(e)))}function bi(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function ad(n,e){let t=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(or).filter(Boolean),r=so([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of n){if(t.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a,d=[{value:s.label,by:"semantic"},...s.aliases.map(c=>({value:c,by:"alias"})),...s.locators.map(c=>({value:c.value,by:"locator"}))];for(let c of d){let y=or(c.value);for(let S of o){let b=y===S?95:y.includes(S)||S.includes(y)?75:0;b>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:c.by,score:b})}let g=["/","#","[","]","="].some(S=>c.value.includes(S))?0:Math.round(bi(so(y),r)*55);g>=30&&g>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:g>=45?"strong":"weak",matchedBy:"semantic",score:g})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function dd(n){return Math.ceil(JSON.stringify(n).length/4)}function Yt(n,e){return n.relationshipType===e&&n.from.entityType==="decision"&&n.to.entityType==="decision"}function cd(n,e){let t=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===n));if(!t.length)return{decisionId:n,state:"unimplemented",attemptIds:[]};let o=t.filter(i=>i.state==="completed"),r=o.some(i=>i.coverageClaims.some(s=>s.decisionId===n&&s.coverage==="full"));return{decisionId:n,state:r?"implemented":o.length?"partial":"unknown",attemptIds:t.map(i=>i.id)}}function ld(n,e,t){let o=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===n)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=t.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===n),i=o[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:n},state:s,attemptIds:o.map(a=>a.id)}}function xi(n,e){let t=Math.max(300,e.maxEstimatedTokens??1200),o=Math.max(1,e.maxDecisions??6),r=n.records.filter(f=>f.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=n.records.filter(f=>f.recordType==="decision"&&f.state==="active"),a=i?s.filter(f=>i.has(f.id)):s,d=n.records.filter(f=>f.recordType==="implementation_attempt"),c=n.records.filter(f=>f.recordType==="verification_attempt"),y=n.records.filter(f=>f.recordType==="freshness_signal"&&f.state==="open"),w=n.records.filter(f=>f.recordType==="evidence"),g=n.records.filter(f=>f.recordType==="model_entry"),S=ad(r,e),b=new Map(S.map(f=>[f.subjectId,f.score])),h=so([e.action,e.text].filter(Boolean).join(" ")),p=a.flatMap(f=>{let M=Math.max(0,...f.subjects.map(F=>b.get(F.subjectId)??0)),$=Math.round(bi(so(f.claim),h)*35),E=M+$;return E>=50?[{decision:f,score:E}]:[]}).sort((f,M)=>M.score-f.score||f.decision.id.localeCompare(M.decision.id)),I=new Map;for(let f of p.slice(0,o))I.set(f.decision.id,f.decision);for(let f of n.relationships){if(!Yt(f,"excepts")&&!Yt(f,"contradicts"))continue;let M=s.find(E=>E.id===f.from.entityId),$=s.find(E=>E.id===f.to.entityId);!M||!$||!I.has(M.id)&&!I.has($.id)||(I.size<o&&I.set(M.id,M),I.size<o&&I.set($.id,$))}let v=[...I.values()],u=f=>f.from.entityType==="decision"&&f.to.entityType==="decision"&&I.has(f.from.entityId)&&I.has(f.to.entityId),x=(f,M=!1)=>{let $=new Set(f.map(j=>j.id)),E=y.filter(j=>j.target.entityType==="decision"&&$.has(j.target.entityId)),F=new Set(n.relationships.filter(j=>Yt(j,"excepts")&&$.has(j.from.entityId)&&$.has(j.to.entityId)).flatMap(j=>[j.from.entityId,j.to.entityId])),L=n.relationships.filter(j=>Yt(j,"contradicts")&&$.has(j.from.entityId)&&$.has(j.to.entityId)).map(j=>({id:j.id,decisionIds:[j.from.entityId,j.to.entityId],unresolvedQuestion:j.reason,expansionRefs:[{kind:"record",id:j.id}]})),R=new Set(L.flatMap(j=>j.decisionIds)),J=w.filter(j=>j.sourceRefs.some(B=>B.kind==="record"&&$.has(B.id))||n.relationships.some(B=>B.relationshipType==="supports"&&B.from.entityType==="evidence"&&B.from.entityId===j.id&&B.to.entityType==="decision"&&$.has(B.to.entityId))),W=Math.max(0,p.length-f.length),ee=n.relationships.some(j=>Yt(j,"contradicts")&&u(j)&&(!$.has(j.from.entityId)||!$.has(j.to.entityId))),H=M||W>0||ee,ie=[];S.length===0&&(e.subjectHints?.length??0)>0?ie.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):f.length===0&&ie.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),L.length&&ie.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:L.flatMap(j=>j.expansionRefs)}),J.some(j=>j.availability!=="available")&&ie.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:J.map(j=>({kind:"record",id:j.id}))}),H&&ie.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:n.manifest.projectId}]});let P={contractVersion:1,projectId:n.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:S.map(({score:j,...B})=>B),modelEntries:g.filter(j=>j.decisionIds.some(B=>$.has(B))).map(j=>({id:j.id,key:j.key,value:j.value,decisionIds:j.decisionIds})),decisions:f.map(j=>({id:j.id,kind:j.kind,claim:j.claim,subjectIds:j.subjects.map(B=>B.subjectId),authority:j.authority,effectiveState:R.has(j.id)?"conflicted":F.has(j.id)?"excepted":"active",freshness:E.filter(B=>B.target.entityId===j.id).map(B=>B.signalType),expansionRef:{kind:"record",id:j.id}})),conflicts:L,uncertainties:ie,implementation:f.map(j=>cd(j.id,d)),verification:f.map(j=>ld(j.id,c,E)),evidence:J.map(j=>({evidenceId:j.id,summary:j.summary,availability:j.availability,sourceRefs:j.sourceRefs})),completeness:{status:H?"truncated":"complete",omittedDecisionCount:W,omittedEvidenceCount:0,conflictsComplete:!ee}};return P.budget.estimatedTokens=dd(P),P},m=x(v);for(;m.budget.estimatedTokens>t&&v.length>0;){let f=v.pop(),M=n.relationships.filter($=>Yt($,"contradicts")&&($.from.entityId===f.id||$.to.entityId===f.id)).flatMap($=>[$.from.entityId,$.to.entityId]);v=v.filter($=>!M.includes($.id)),m=x(v,!0)}return m}var pd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function rr(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ao(n){return new Set(rr(n).split(" ").filter(e=>e.length>2&&!pd.has(e)))}function Si(n,e){if(!n.size||!e.size)return 0;let t=0;for(let o of n)e.has(o)&&(t+=1);return t/Math.min(n.size,e.size)}function ud(n){return[{value:n.label,by:"label"},...n.aliases.map(e=>({value:e,by:"alias"})),...n.locators.map(e=>({value:e.value,by:"locator"}))]}function md(n,e){let t=new Map,o=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(rr).filter(Boolean),i=ao([e.action,e.text].filter(Boolean).join(" "));for(let s of n){if(o.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a;for(let d of ud(s)){let c=rr(d.value);for(let g of r){let S=c===g?95:c.includes(g)||g.includes(c)?75:0;S>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:d.by,score:S})}let w=["/","#","[","]","="].some(g=>d.value.includes(g))?0:Math.round(Si(ao(c),i)*55);w>=30&&w>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:w>=45?"strong":"weak",matchedBy:"query_text",score:w})}a&&t.set(s.id,a)}return t}function fd(n,e){let t=new Set(n.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),o=new Set(n.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(a=>t.has(a))||s.sourceRefs.some(a=>a.kind==="thread"&&o.has(a.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 hd(n){return Math.ceil(JSON.stringify(n).length/4)}function ir(n,e){let t=n.records.filter(p=>p.recordType==="subject"),o=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=n.records.filter(p=>{if(p.recordType!=="proposal"||r&&!r.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let I=[...n.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===p.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return I?I.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||I.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||I.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||I.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||I.resurfaceWhen.includes("after_date")&&!!(I.revisitAfter&&Date.parse(o)>=Date.parse(I.revisitAfter)):!1}),s=n.records.filter(p=>p.recordType==="implementation_attempt"),a=md(t,e),d=[...a.values()].sort((p,I)=>I.score-p.score),c=ao([e.action,e.text].filter(Boolean).join(" ")),y=i.flatMap(p=>{let I=p.subjects.map(m=>a.get(m.subjectId)).filter(m=>!!m),v=Math.max(0,...I.map(m=>m.score)),u=Math.round(Si(ao(p.claim),c)*35),x=v+u;return x>=50?[{proposal:p,proposalMatches:I,score:x}]:[]}).sort((p,I)=>I.score-p.score||p.proposal.id.localeCompare(I.proposal.id)),w=Math.max(1,e.maxPackets??3),g=Math.max(200,e.maxEstimatedTokens??1200),S=[],b=0;for(let p of y){if(S.length>=w)break;let I=p.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:n.manifest.projectId,generatedAt:o,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(x=>x.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:x,...m})=>m)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(x=>x.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:fd(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:I},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...I]},u={...v,estimatedTokens:hd(v)};if(b+u.estimatedTokens>g)break;S.push(u),b+=u.estimatedTokens}let h=Math.max(0,y.length-S.length);return{packets:S,subjectMatches:d.map(({score:p,...I})=>I),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:y.length,omittedPacketCount:h,maxEstimatedTokens:g,estimatedTokens:b},uncertainty:a.size===0?"subject_unresolved":y.length===0?"no_relevant_pending_proposal":void 0}}var gd=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Zt(n){return gd.test(n)}function yd(n){return{valid:!n.some(e=>e.severity==="error"),issues:n}}function re(n,e,t,o){n.push({path:e,code:t,message:o,severity:"error"})}function sr(n,e,t,o){n.push({path:e,code:t,message:o,severity:"warning"})}function Ne(n,e,t){Zt(t)||re(n,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function nt(n,e,t){(!t||Number.isNaN(Date.parse(t)))&&re(n,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Ct(n,e,t,o=!1){o&&t.level==="contributor"&&re(n,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&re(n,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Id={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->emerging","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"])},wd=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function vd(n,e,t){Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),Ne(n,`${t}.entity.entityId`,e.entity.entityId),nt(n,`${t}.createdAt`,e.createdAt),Ct(n,`${t}.authority`,e.authority);let o=Id[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;o&&!o.has(r)&&re(n,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(wd.has(i)&&(Ct(n,`${t}.authority`,e.authority,!0),e.reason?.trim()||re(n,`${t}.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)&&re(n,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&re(n,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&nt(n,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function bd(n,e,t,o){Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),nt(n,`${t}.createdAt`,e.createdAt),e.projectId!==o&&re(n,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&re(n,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&re(n,`${t}.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)&&re(n,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Ct(n,`${t}.authority`,e.authority,!0),e.claim.trim()||re(n,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&sr(n,`${t}.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())&&re(n,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),nt(n,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&re(n,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&re(n,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&re(n,`${t}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),nt(n,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),nt(n,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&re(n,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(nt(n,`${t}.appliedAt`,e.appliedAt),Ct(n,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&re(n,`${t}.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())&&re(n,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&re(n,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&sr(n,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&sr(n,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function xd(n,e,t){if(Ne(n,`${t}.id`,e.id),Ne(n,`${t}.projectId`,e.projectId),Ne(n,`${t}.participantId`,e.participantId),Ne(n,`${t}.from.entityId`,e.from.entityId),Ne(n,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&re(n,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&re(n,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),nt(n,`${t}.createdAt`,e.createdAt),e.reason.trim()||re(n,`${t}.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&&re(n,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?re(n,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Ct(n,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&re(n,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&re(n,t,"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))&&re(n,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&re(n,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function $t(n){let e=[];Ne(e,"manifest.projectId",n.manifest.projectId),nt(e,"manifest.createdAt",n.manifest.createdAt),nt(e,"manifest.updatedAt",n.manifest.updatedAt);let t=new Map,o=(h,p)=>{let I=t.get(h);I?re(e,p,"duplicate_id",`ID is already used at ${I}.`):t.set(h,p)};n.records.forEach((h,p)=>{let I=`records[${p}]`;o(h.id,I),bd(e,h,I,n.manifest.projectId)}),n.events.forEach((h,p)=>{let I=`events[${p}]`;o(h.id,I),vd(e,h,I),h.projectId!==n.manifest.projectId&&re(e,`${I}.projectId`,"project_mismatch","Event belongs to another project.")}),n.relationships.forEach((h,p)=>{let I=`relationships[${p}]`;o(h.id,I),xd(e,h,I),h.projectId!==n.manifest.projectId&&re(e,`${I}.projectId`,"project_mismatch","Relationship belongs to another project.")}),n.artifacts.forEach((h,p)=>{o(h.id,`artifacts[${p}]`),Ne(e,`artifacts[${p}].id`,h.id)}),n.tombstones.forEach((h,p)=>{let I=`tombstones[${p}]`;o(h.id,I),Ne(e,`${I}.id`,h.id),Ne(e,`${I}.objectId`,h.objectId),Ne(e,`${I}.deletedById`,h.deletedById),nt(e,`${I}.deletedAt`,h.deletedAt),Ct(e,`${I}.authority`,h.authority,!0)});let r=new Set(n.records.map(h=>`${h.recordType}:${h.id}`)),i=new Set(n.tombstones.map(h=>`${h.objectType}:${h.objectId}`)),s=(h,p)=>{if(h.storeId)return;let I=`${h.entityType}:${h.entityId}`;!r.has(I)&&!i.has(I)&&re(e,p,"dangling_entity_reference",`No record or tombstone exists for ${I}.`)};n.events.forEach((h,p)=>s(h.entity,`events[${p}].entity`)),n.relationships.forEach((h,p)=>{s(h.from,`relationships[${p}].from`),s(h.to,`relationships[${p}].to`)});let a=new Set(n.artifacts.map(h=>h.id)),d=(h,p)=>{a.has(h)||re(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},c=(h,p,I)=>{!r.has(`${h}:${p}`)&&!i.has(`${h}:${p}`)&&re(e,I,"dangling_entity_reference",`No ${h} record or tombstone exists.`)};n.records.forEach((h,p)=>{let I=`records[${p}]`;switch(h.recordType){case"authority_grant":c("participant",h.granteeId,`${I}.granteeId`),c("participant",h.grantedById,`${I}.grantedById`),h.subjectIds.forEach((v,u)=>c("subject",v,`${I}.subjectIds[${u}]`));break;case"observation":h.captureContext.subjectIds.forEach((v,u)=>c("subject",v,`${I}.captureContext.subjectIds[${u}]`)),h.captureContext.artifactIds.forEach((v,u)=>d(v,`${I}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":h.subjects.forEach((v,u)=>c("subject",v.subjectId,`${I}.subjects[${u}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((v,u)=>d(v,`${I}.messageArtifactIds[${u}]`)),h.resultRefs.forEach((v,u)=>s(v,`${I}.resultRefs[${u}]`));break;case"iteration":h.threadIds.forEach((v,u)=>c("thread",v,`${I}.threadIds[${u}]`)),h.artifactIds.forEach((v,u)=>d(v,`${I}.artifactIds[${u}]`));break;case"evidence":h.artifactIds.forEach((v,u)=>d(v,`${I}.artifactIds[${u}]`));break;case"advisory_explanation":h.subjectIds.forEach((v,u)=>c("subject",v,`${I}.subjectIds[${u}]`)),h.evidenceIds.forEach((v,u)=>c("evidence",v,`${I}.evidenceIds[${u}]`)),h.supersededById&&c("advisory_explanation",h.supersededById,`${I}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((v,u)=>c("iteration",v,`${I}.iterationIds[${u}]`)),h.coverageClaims.forEach((v,u)=>c("decision",v.decisionId,`${I}.coverageClaims[${u}].decisionId`)),h.artifactIds.forEach((v,u)=>d(v,`${I}.artifactIds[${u}]`));break;case"eval_spec":h.replacesSpecId&&c("eval_spec",h.replacesSpecId,`${I}.replacesSpecId`),h.decisionIds.forEach((v,u)=>c("decision",v,`${I}.decisionIds[${u}]`)),h.subjectIds.forEach((v,u)=>c("subject",v,`${I}.subjectIds[${u}]`)),(h.dependencies??[]).forEach((v,u)=>{v.kind==="subject"&&v.subjectId&&c("subject",v.subjectId,`${I}.dependencies[${u}].subjectId`)}),(h.scenarios??[]).forEach((v,u)=>{v.subjectIds?.forEach((x,m)=>c("subject",x,`${I}.scenarios[${u}].subjectIds[${m}]`))}),h.targets.forEach((v,u)=>c(v.entityType,v.entityId,`${I}.targets[${u}]`));break;case"verification_attempt":h.evalSpecId&&c("eval_spec",h.evalSpecId,`${I}.evalSpecId`),h.targets.forEach((v,u)=>c(v.entityType,v.entityId,`${I}.targets[${u}]`)),h.evidenceIds.forEach((v,u)=>c("evidence",v,`${I}.evidenceIds[${u}]`));break;case"model_entry":h.subjectIds.forEach((v,u)=>c("subject",v,`${I}.subjectIds[${u}]`)),h.decisionIds.forEach((v,u)=>c("decision",v,`${I}.decisionIds[${u}]`));break;case"model_projection":Ct(e,`${I}.authority`,h.authority,!0),c("participant",h.appliedById,`${I}.appliedById`),h.decisionIds.forEach((v,u)=>c("decision",v,`${I}.decisionIds[${u}]`)),h.entryIds.forEach((v,u)=>c("model_entry",v,`${I}.entryIds[${u}]`)),h.coverage.forEach((v,u)=>c("decision",v.decisionId,`${I}.coverage[${u}].decisionId`));break;case"freshness_signal":s(h.target,`${I}.target`),h.evidenceIds.forEach((v,u)=>c("evidence",v,`${I}.evidenceIds[${u}]`));break;default:break}});let y=new Map(n.events.map(h=>[h.id,h])),w=new Map(n.records.map(h=>[`${h.recordType}:${h.id}`,h])),g=new Map;n.events.forEach((h,p)=>{let I=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,v=g.get(I)??new Set;v.add(h.toState),g.set(I,v),v.size>1&&re(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let S=new Map(n.records.flatMap(h=>h.recordType==="authority_grant"?[[h.id,h]]:[])),b=(h,p,I,v,u)=>{if(h.level!=="delegate"||!h.grantId)return;let x=S.get(h.grantId);if(!x){re(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(x.granteeId!==p||x.level!=="delegate")&&re(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let m=Date.parse(I);(m<Date.parse(x.startsAt)||x.endsAt&&m>Date.parse(x.endsAt)||x.revokedAt&&m>=Date.parse(x.revokedAt))&&re(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),x.subjectIds.length&&v.length&&!v.every(f=>x.subjectIds.includes(f))&&re(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let h of n.records)h.recordType==="decision"&&b(h.authority,h.acceptedById,h.createdAt,h.subjects.map(p=>p.subjectId),`records:${h.id}.authority`);n.events.forEach((h,p)=>{let I=w.get(`${h.entity.entityType}:${h.entity.entityId}`),v=I&&"subjects"in I?I.subjects.map(u=>u.subjectId):[];b(h.authority,h.participantId,h.createdAt,v,`events[${p}].authority`)}),n.relationships.forEach((h,p)=>{if(!h.authority)return;let I=[h.from,h.to].flatMap(v=>{let u=w.get(`${v.entityType}:${v.entityId}`);return u&&"subjects"in u?u.subjects.map(x=>x.subjectId):[]});b(h.authority,h.participantId,h.createdAt,I,`relationships[${p}].authority`)});for(let h of n.records){if(h.recordType!=="decision")continue;let p=y.get(h.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==h.proposalId||p.toState!=="accepted")&&re(e,`records:${h.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==h.acceptedById&&re(e,`records:${h.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),w.has(`proposal:${h.proposalId}`)||re(e,`records:${h.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),h.state==="superseded"&&(n.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===h.id)||re(e,`records:${h.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),h.state==="revoked"&&(n.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===h.id&&v.toState==="revoked"&&!!v.reason?.trim())||re(e,`records:${h.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let h of n.records){if(h.recordType!=="proposal"||h.state!=="accepted")continue;n.records.some(I=>I.recordType==="decision"&&I.proposalId===h.id)||re(e,`records:${h.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return yd(e)}function Tn(n,e,t,o){return{id:o,schemaVersion:1,projectId:n.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function Ti(n,e,t,o,r){return{id:r,schemaVersion:1,projectId:n.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:o,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Sd(n){switch(n.action){case"accept":return[n.eventId,n.decisionId];case"edit_and_accept":return[n.withdrawalEventId,n.replacementProposalId,n.acceptanceEventId,n.decisionId,n.relationshipId];case"reject":case"defer":return[n.eventId]}}function co(n,e){let t=[],o=n.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);o?o.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${o.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Zt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Sd(e))Zt(i)||t.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!o)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Ti(n,o,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.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:n.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.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={...Tn(n,o,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...Tn(n,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Ti(n,i,e,a.id,e.decisionId),c={id:e.relationshipId,schemaVersion:1,projectId:n.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:o.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[i,d],events:[s,a],relationships:[c]},projectionUpdates:[{entityType:"proposal",entityId:o.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={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}let r={...Tn(n,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.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:o.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}import{createHash as Td}from"crypto";import{readFile as kd,readdir as Pd,realpath as Rd}from"fs/promises";import{join as kn,relative as Ad}from"path";var Md=["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 en(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function Ze(n,e=0){return new Date(Number.isFinite(n)?n:e).toISOString()}function ki(...n){return n.find(e=>!!e?.trim())?.trim()}function fe(n,e,t,o){let i=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),s=Td("sha256").update(`${n}\0${e}\0${t}`).digest("hex"),a=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${a}${s.slice(4,7)}-${s.slice(7,19)}`}async function ar(n,e){try{return JSON.parse(await kd(n,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:n,message:t instanceof Error?t.message:String(t)}),null}}function jd(n){let e=en(n);if(!e)return 0;let t=0,o=r=>{let i=en(r);if(!i){t+=1;return}for(let s of Object.values(i))o(s)};for(let r of Object.values(e))o(r);return t}function Ed(n){let e={};for(let t of n)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function Pn(n){let e=[],t=await Rd(n.projectRoot).catch(()=>n.projectRoot),o=kn(t,".popmelt"),r=await ar(kn(o,"threads.json"),e),i=await ar(kn(o,"model.json"),e),s=en(r),a=en(s?.threads)??{},d=Object.entries(a).map(([B,_])=>({key:B,value:en(_)})).filter(B=>!!B.value),c=kn(o,"decisions"),y=await Pd(c).catch(()=>[]),w=[];for(let B of y.filter(_=>_.endsWith(".json")).sort()){let _=en(await ar(kn(c,B),e));_&&w.push({file:B,value:_})}let g=d.flatMap(({value:B})=>[B.createdAt,B.updatedAt]).filter(B=>typeof B=="number"&&Number.isFinite(B)),S=g.length?Math.min(...g):0,b=n.projectKey??t;n.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 h=fe(b,"project",b,S),p=fe(b,"participant","legacy-owner",S),I=fe(b,"participant","legacy-agent",S),v=fe(b,"subject","project",S),u=Ze(Math.max(S,...g)),x=[],m=[],f=new Map,M=new Map,$=new Map(w.map(B=>[B.value.id??B.file.replace(/^d-|\.json$/g,""),B.value])),E=new Map,F=(B,_,Q,de,Z)=>{let se=f.get(Q);if(se)return se;let xe=fe(b,"artifact",B,de);return m.push({id:xe,kind:_,mediaType:Z,location:Q,availability:"available"}),f.set(Q,xe),xe};for(let{file:B,value:_}of w){let Q=_.id??B.replace(/^d-|\.json$/g,""),de=_.createdAt??S,Z=[F(`${Q}:envelope`,"other",`.popmelt/decisions/${B}`,de,"application/json")];_.screenshotPath&&Z.push(F(`${Q}:screenshot`,"screenshot",`.popmelt/${_.screenshotPath.replace(/^\.popmelt\//,"")}`,de,_.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[se,xe]of(_.pastedImagePaths??[]).entries())Z.push(F(`${Q}:image:${se}`,"image",xe,de));E.set(Q,Z)}let Y=(B,_,Q)=>({id:B,schemaVersion:1,projectId:h,createdAt:u,participantId:_,sourceRefs:Q}),L=(B,_)=>{x.push(_);let Q=M.get(B)??[];Q.push(_.id),M.set(B,Q)},R=[{...Y(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...Y(I,I,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];x.push(...R),x.push({...Y(v,p,[]),recordType:"subject",subjectType:"project",label:Ad(process.cwd(),t)||t,aliases:[],locators:[{id:fe(b,"locator",t,S),kind:"project_root",value:t,status:"current",validFrom:Ze(S),sourceRefs:[]}]});let J=new Map,W=(B,_)=>{let Q=J.get(B);if(Q)return Q;let de=fe(b,"subject",B,_),Z={...Y(de,p,[{kind:"external",id:B}]),createdAt:Ze(_),recordType:"subject",subjectType:"element",label:B,aliases:[],locators:[{id:fe(b,"locator",B,_),kind:"dom_selector",value:B,status:"current",validFrom:Ze(_),sourceRefs:[{kind:"external",id:B}]}]};return x.push(Z),J.set(B,de),de};for(let{key:B,value:_}of d){let Q=_.id??B,de=_.createdAt??S,Z=fe(b,"thread",Q,de),se={kind:"thread",id:Q},xe=[],qe=[],pe=Array.isArray(_.messages)?_.messages:[],Te,Ce,Ue=0;pe.forEach((Me,tt)=>{let ze=Me.timestamp??de,ut=fe(b,"artifact",`${Q}:message:${tt}`,ze);if(xe.push(ut),m.push({id:ut,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${Q}/messages/${tt}`,availability:"available"}),f.set(`.popmelt/threads.json#/threads/${Q}/messages/${tt}`,ut),Me.screenshotPath&&F(`${Q}:message:${tt}:screenshot`,"screenshot",Me.screenshotPath,ze),Me.role==="human"){Te=Me;let We=Me.feedbackSummary??Me.replyToQuestion;if(We?.trim()){let Ve=fe(b,"observation",`${Q}:${tt}`,ze),vt=_.elementIdentifiers??[],bt={...Y(Ve,p,[se,{kind:"message",id:ut}]),createdAt:Ze(ze),recordType:"observation",state:"open",statement:We,captureContext:{subjectIds:vt.map(At=>W(At,de)),artifactIds:[ut]},resolvedByIds:[]};L(Q,bt),Ce=Ve,qe.push({entityType:"observation",entityId:Ve})}return}if(Me.role!=="assistant")return;let It=Me.jobId??`${Q}:${tt}`,wt=fe(b,"iteration",It,ze),Rt=$.get(It),Qo=Me.cancelled?"cancelled":Me.error?"failed":Me.question?"question_asked":(Me.resolutions?.length??0)>0?"completed":"no_change",Xo={...Y(wt,I,[se,{kind:"message",id:ut},...(E.get(It)??[]).map(We=>({kind:"artifact",id:We}))]),createdAt:Ze(ze),recordType:"iteration",threadIds:[Z],startedAt:Ze(Te?.timestamp,ze),completedAt:Ze(ze),requestSummary:ki(Te?.feedbackSummary,Te?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Me.question??Me.error??Me.responseText?.slice(0,1e3),outcome:Qo,execution:{provider:Me.provider??Rt?.provider,model:Me.model??Rt?.model,sessionId:Me.sessionId??Rt?.sessionId},artifactIds:[ut,...E.get(It)??[]]};L(Q,Xo),qe.push({entityType:"iteration",entityId:wt});let wn=Me.resolutions??Rt?.resolutions??[];for(let[We,Ve]of wn.entries()){if(Ve.status!=="resolved"||!Ve.summary?.trim())continue;let vt=_.elementIdentifiers??[],bt=(vt.length?vt:[t]).map(eo=>({subjectId:eo===t?v:W(eo,de),role:"governed"})),At=fe(b,"proposal",`${It}:${Ve.annotationId??"resolution"}:${We}`,ze),Yo={...Y(At,I,[se,{kind:"iteration",id:wt}]),createdAt:Ze(ze),recordType:"proposal",state:"pending",claim:Ve.summary,subjects:bt,subjectSemantics:bt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:ki(Te?.feedbackSummary,Te?.replyToQuestion,Ve.summary),iterationId:wt,inferredById:I}};L(Q,Yo),qe.push({entityType:"proposal",entityId:At}),e.push({severity:"warning",code:"acceptance_unresolved",source:Q,message:`Proposal ${At} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(wn.some(We=>We.status==="resolved")||Rt?.gitDiff){let We=fe(b,"implementation",It,ze),Ve={...Y(We,I,[se,{kind:"iteration",id:wt}]),createdAt:Ze(ze),recordType:"implementation_attempt",state:"completed",iterationIds:[wt],coverageClaims:[],summary:wn.map(vt=>vt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};L(Q,Ve),qe.push({entityType:"implementation_attempt",entityId:We}),Ue+=1}Ce&&(Ce=void 0)});let De=pe.at(-1),st={...Y(Z,p,[se]),createdAt:Ze(de),recordType:"thread",state:De?.question?"open":"resolved",messageArtifactIds:xe,outcome:De?.question?"question_unresolved":Ue?"implementation_only":"no_outcome",resultRefs:qe};x.push(st),M.set(Q,[Z,...M.get(Q)??[]])}let ee=jd(i);ee&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ee} model values were not promoted because their accepted decision provenance is unresolved.`});let H={manifest:{formatVersion:1,projectId:h,createdAt:Ze(S),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:n.writerVersion??"0.8.4-dev"}},records:x,events:[],relationships:[],artifacts:m,tombstones:[]},ie=$t(H),j=(n.proofCaseIds??Md).map(B=>({legacyId:B,threadFound:d.some(({key:_,value:Q})=>(Q.id??_)===B),decisionEnvelopeFound:$.has(B),recordIds:M.get(B)??[]}));return{bundle:H,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((B,_)=>B+(_.value.messages?.length??0),0),decisionEnvelopes:w.length,modelEntries:ee,artifactsReferenced:m.length},imported:Ed(x),unresolvedAcceptance:e.filter(B=>B.code==="acceptance_unresolved").length,deferredModelEntries:ee,proofCases:j,issues:e,schemaIssues:ie.issues}}}var _d=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Pi(n,e){let t=n.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),o=n.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!t||!o)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=n.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=_d(),c=d.records,y=n.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(x=>x.kind==="thread"&&x.id===e.threadId));y||(y={id:fe(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.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:[]},c.push(y));let w=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let x=n.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.value===u&&f.status==="current"));x||(x={id:fe(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:fe(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},c.push(x)),w.push(x)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let x=n.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.kind==="source_file"&&f.value===u&&f.status==="current"));x||(x={id:fe(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:fe(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},c.push(x)),w.push(x)}let g=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),S;if(g.length>0){S=fe(r,"live-observation",i,e.createdAt);let u={id:S,schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:g.map(x=>x.claim.trim()).join(" "),captureContext:{subjectIds:w.map(x=>x.id),artifactIds:[]},resolvedByIds:[]};c.push(u)}let b=fe(r,"live-iteration",i,e.completedAt),h={id:b,schemaVersion:1,projectId:n.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...S?[{kind:"record",id:S}]:[]],recordType:"iteration",threadIds:[y.id],startedAt:s,completedAt:a,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};c.push(h);let p=[],I=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),v=w.length>0?w:n.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(g.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,x]of g.entries()){let m=fe(r,"live-proposal",`${i}:${u}`,e.completedAt),f=v.map($=>({subjectId:$.id,role:"governed"})),M={id:m,schemaVersion:1,projectId:n.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:b},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:x.claim.trim(),rationale:x.rationale?.trim()||void 0,proposedKind:x.proposedKind,subjects:f,subjectSemantics:f.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:x.sourceText?.trim()||e.requestSummary,iterationId:b,inferredById:o.id}};c.push(M),p.push(m)}if(I.length>0){let u=new Set(e.governingDecisionIds??[]),x=n.records.filter(f=>f.recordType==="decision"&&f.state==="active"&&u.has(f.id)),m={id:fe(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:b}],recordType:"implementation_attempt",state:"completed",iterationIds:[b],coverageClaims:x.map(f=>({decisionId:f.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${I.map(M=>M.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:b}]})),summary:I.map(f=>f.summary).join(" "),artifactIds:[]};c.push(m)}return{mutation:d,iterationId:b,proposalIds:p,observationId:S}}import{createHash as Cd}from"crypto";import{mkdir as Ri,open as dr,readFile as cr,readdir as $d,rename as Od,unlink as lr}from"fs/promises";import{join as gt}from"path";var Dd={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function lo(n){return Cd("sha256").update(JSON.stringify(n)).digest("hex")}function Ai(n){return lo(n)}function Mi(n,e,t){[...e.records,...e.recordReplacements??[]].some(o=>o.recordType==="advisory_explanation")&&!n.manifest.features.includes("advisory_explanations")&&n.manifest.features.push("advisory_explanations");for(let o of e.recordReplacements??[]){if(o.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${o.recordType}.`);let r=n.records.findIndex(s=>s.recordType===o.recordType&&s.id===o.id);if(r<0)throw new Error(`Record replacement target not found: ${o.recordType} ${o.id}`);let i=n.records[r];if(i.projectId!==o.projectId||i.createdAt!==o.createdAt||i.participantId!==o.participantId)throw new Error(`Record replacement changed immutable identity for ${o.id}.`);n.records[r]=structuredClone(o)}for(let o of e.projectionUpdates){let r=n.records.find(i=>i.recordType===o.entityType&&i.id===o.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${o.entityType} ${o.entityId}`);if(r.state!==o.fromState)throw new Error(`Projection state conflict for ${o.entityType} ${o.entityId}: expected ${o.fromState}, found ${r.state}`);r.state=o.state}return n.records.push(...e.records),n.events.push(...e.events),n.relationships.push(...e.relationships),n.artifacts.push(...e.artifacts),n.tombstones.push(...e.tombstones),n.manifest.updatedAt=t,n}function Nd(n,e,t){return Mi(structuredClone(n),e,t)}async function Ot(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await dr(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
13
+ `,"utf8"),await o.sync()}finally{await o.close()}try{await Od(t,n)}catch(r){throw await lr(t).catch(()=>{}),r}}async function Rn(n){return JSON.parse(await cr(n,"utf8"))}var po=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=gt(e,".popmelt","memory"),this.journalDir=gt(this.memoryDir,"journal"),this.manifestPath=gt(this.memoryDir,"manifest.json"),this.checkpointPath=gt(this.memoryDir,"checkpoint.json"),this.lockPath=gt(this.memoryDir,"writer.lock")}async readHead(){let e=await Rn(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=$t(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Ri(this.journalDir,{recursive:!0});try{throw await cr(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(o){if(o instanceof Error&&o.message==="Memory journal is already initialized."||o.code!=="ENOENT")throw o}await this.withWriterLock(async()=>{try{throw await cr(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 o=lo(e),r={storageVersion:1,sequence:0,hash:o,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:o},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await Ot(this.checkpointPath,r),await Ot(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 Ot(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 t=lo(e.bundle),o=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await Ot(gt(this.memoryDir,o),r),e.manifest.checkpoint={file:o,sequence:r.sequence,hash:t},await Ot(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Zt(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let o=await this.loadInternal();if(o.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let r=o.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:o.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:o.report.headHash,mutation:e},s={...i,hash:Ai(i)},a=Nd(o.bundle,e,t.committedAt),d=$t(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let c=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await Ot(gt(this.journalDir,c),s),o.manifest.head={sequence:r,hash:s.hash},o.manifest.updatedAt=t.committedAt,await Ot(this.manifestPath,o.manifest),{bundle:a,report:{checkpointSequence:o.report.checkpointSequence,appliedTransactions:o.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:o.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...Dd,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Rn(this.manifestPath),t=await Rn(gt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==lo(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let o=await $d(this.journalDir),r=o.filter(g=>g.endsWith(".tmp")),s=o.filter(g=>/^\d{12}-[0-9a-f-]+\.json$/i.test(g)).sort().filter(g=>Number(g.slice(0,12))>t.sequence),a=structuredClone(t.bundle),d=t.sequence,c=t.journalHash??null,y=new Set;for(let g of s){let S=await Rn(gt(this.journalDir,g)),{hash:b,...h}=S;if(b!==Ai(h))throw new Error(`Journal hash mismatch: ${g}`);if(S.sequence!==d+1)throw new Error(`Journal sequence gap at ${g}`);if(S.previousHash!==c)throw new Error(`Journal chain mismatch at ${g}`);if(S.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${g}`);if(y.has(S.transactionId))throw new Error(`Duplicate transaction ID: ${S.transactionId}`);Mi(a,S.mutation,S.committedAt),d=S.sequence,c=S.hash,y.add(S.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==c)throw new Error("Journal manifest head hash mismatch.");let w=$t(a);if(!w.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(w.issues)}`);return{bundle:a,manifest:e,transactionIds:y,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:c}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Ri(this.memoryDir,{recursive:!0});let t;try{t=await dr(this.lockPath,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let r=await Rn(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 lr(this.lockPath),t=await dr(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await lr(this.lockPath).catch(()=>{})}}};import{createHash as Bd}from"crypto";import{mkdir as Jd,open as qd,readFile as Ld,rename as Fd,unlink as Ud}from"fs/promises";import{join as ji}from"path";function Ei(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function _i(n){return Bd("sha256").update(JSON.stringify(n)).digest("hex")}async function zd(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,o=await qd(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
14
+ `,"utf8"),await o.sync()}finally{await o.close()}try{await Fd(t,n)}catch(r){throw await Ud(t).catch(()=>{}),r}}function Gd(n,e,t=new Date().toISOString()){let o={},r={},i={},s=(d,c,y)=>{let w=d[c]??=[];w.includes(y)||w.push(y)};for(let d of n.records)if(d.recordType==="subject"){let c=d;for(let y of[c.label,...c.aliases,...c.locators.filter(w=>w.status==="current").map(w=>w.value)]){let w=Ei(y);w&&s(o,w,c.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let c of d.subjects)s(r,c.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let c of d.subjects)s(i,c.subjectId,d.id);let a={version:1,projectId:n.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:o,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:_i(a)}}function Ci(n,e){let t=[...new Set(e.flatMap(o=>n.subjectIdsByValue[Ei(o)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(o=>n.decisionIdsBySubject[o]??[]))],proposalIds:[...new Set(t.flatMap(o=>n.proposalIdsBySubject[o]??[]))]}}var uo=class{constructor(e){this.indexDir=ji(e,".popmelt","memory","indexes"),this.indexPath=ji(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await Ld(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===t.sequence&&r.journalHead.hash===t.hash&&i===_i(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let o=Gd(e,t);return await Jd(this.indexDir,{recursive:!0}),await zd(this.indexPath,o),o}};import{randomBytes as Wd}from"crypto";function je(n=Date.now()){let t=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),o=Wd(10).toString("hex"),r=(Number.parseInt(o[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${o.slice(0,3)}-${r}${o.slice(4,7)}-${o.slice(7,19)}`}var jn="popmelt:imprint",Di="popmelt:imprint-evidence",nn="popmelt:imprint-relation";function Mn(n){return n.sourceRefs.find(e=>e.kind==="external"&&e.uri===jn)?.id}function pr(n){let e=new Set;return n.filter(t=>{let o=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(o)?!1:(e.add(o),!0)})}function mo(n,e){if(!n)return[];let t=new Set(n.relations.flatMap(o=>o.type==="expresses"&&!o.toStoreId&&o.toId===e?[o.fromId]:[]));return n.concrete.filter(o=>t.has(o.id)).map(o=>({id:o.id,modelPath:o.modelPath,value:structuredClone(o.value),createdAt:o.createdAt,updatedAt:o.updatedAt}))}function ur(n){if(n==="expresses")return"expresses";if(n==="excepts")return"excepts"}var sn=class{constructor(e){this.projectRoot=e;this.store=new po(e),this.indexStore=new uo(e),this.manifestPath=tn(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await An(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 o=await Pn({...e,projectRoot:this.projectRoot});if(o.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(o.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(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Pn({...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=tn(this.projectRoot,".popmelt","memory","migrations"),t=tn(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await An(t,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let o;try{o=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!o?.explanations)return await $i(e,{recursive:!0}),await Oi(t,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"),a=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(!a||!d)return{migrated:!1,explanations:0,evidence:0};let c=r.bundle.manifest.projectId,y=new Set(r.bundle.records.map(u=>u.id)),w=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(x=>x.kind==="external"&&x.uri===nn?[x.id]:[]))),g=new Map,S=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of o.explanations){let x=S.find(m=>Mn(m)===u.id);g.set(u.id,x?.id??fe(c,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let b=[],h=[],p=[],I=0;for(let u of o.explanations){let x=g.get(u.id),m=S.find(E=>E.id===x),f=[],M=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 E of M){let F=fe(c,"imprint-evidence-record",E.id,Date.parse(E.createdAt));f.push(F),!y.has(F)&&(b.push({id:F,schemaVersion:1,projectId:c,createdAt:E.createdAt,participantId:a.id,sourceRefs:pr([{kind:"external",id:E.id,uri:Di},{kind:"external",id:u.id,uri:jn},{kind:"thread",id:E.threadId},{kind:"message",id:E.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(E.kind)?"user_feedback":"judgment",summary:E.summary,availability:"available",artifactIds:[]}),p.push({id:fe(c,"imprint-evidence-link",`${u.id}:${E.id}`,Date.parse(E.createdAt)),schemaVersion:1,projectId:c,createdAt:E.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:E.id,uri:Di}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:x},to:{entityType:"evidence",entityId:F},reason:"This advisory explanation was derived from collaboration evidence."}),I+=1)}let $={id:x,schemaVersion:1,projectId:c,createdAt:m?.createdAt??u.createdAt,participantId:m?.participantId??a.id,sourceRefs:pr([...m?.sourceRefs??[],{kind:"external",id:u.id,uri:jn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...m?.evidenceIds??[],...f])],concreteBindings:mo(o,u.id),supersededById:u.supersededBy?g.get(u.supersededBy):void 0,updatedAt:u.updatedAt};m?h.push($):b.push($)}for(let u of o.relations){let x=ur(u.type);if(!x||u.toStoreId)continue;let m=g.get(u.fromId),f=g.get(u.toId);!m||!f||w.has(u.id)||p.push({id:fe(c,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:c,createdAt:u.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:u.id,uri:nn}],recordType:"relationship",relationshipType:x,from:{entityType:"advisory_explanation",entityId:m},to:{entityType:"advisory_explanation",entityId:f},reason:u.rationale||"The Imprint graph connected these explanations."})}let v=new Date().toISOString();if(b.length||h.length||p.length)try{let u=await this.store.commit({records:b,recordReplacements:h,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:fe(c,"imprint-advisories-v2",o.projectId,Date.parse(o.updatedAt)),committedAt:v});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await $i(e,{recursive:!0}),await Oi(t,JSON.stringify({version:2,migratedAt:v,explanations:o.explanations.length,evidence:I,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:o.explanations.length,evidence:I}}async review(e,t={}){let o=await this.loadSource(t),r=await this.withIndexedCandidates(o,e);return{source:o.source,selection:ir(o.bundle,r)}}async contextualize(e,t={}){let o=await this.loadSource(t),r=await this.withIndexedCandidates(o,e);return{source:o.source,actionPacket:xi(o.bundle,r),reviewSelection:ir(o.bundle,r)}}async imprintTopology(){let e;try{e=await this.loadJournalSource()}catch(t){if(t.code==="ENOENT")return{explanations:[],relations:[]};throw t}return{explanations:e.bundle.records.flatMap(t=>t.recordType==="advisory_explanation"?[{memoryId:t.id,explanationId:Mn(t)??t.id}]:[]),relations:e.bundle.relationships.flatMap(t=>t.relationshipType!=="expresses"&&t.relationshipType!=="excepts"||t.from.entityType!=="advisory_explanation"||t.to.entityType!=="advisory_explanation"?[]:[{id:t.id,type:t.relationshipType,from:{memoryId:t.from.entityId,...t.from.storeId?{storeId:t.from.storeId}:{}},to:{memoryId:t.to.entityId,...t.to.storeId?{storeId:t.to.storeId}:{}},rationale:t.reason}])}}async planReview(e,t={}){let o=await this.loadSource(t);return{source:o.source,result:co(o.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 t=await Pn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(o=>o.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let o=await this.store.load(),r=co(o.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,t);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 t=await this.store.load(),o=t.bundle.records.find(g=>g.recordType==="proposal"&&g.id===e.proposalId),r=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active");if(!o||o.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:o?o.state!=="pending"?`The proposal is already ${o.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),a={proposalId:o.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:je(i),decisionId:je(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:je(i),replacementProposalId:je(i),acceptanceEventId:je(i),decisionId:je(i),relationshipId:je(i),claim:e.claim,kind:e.kind,subjects:o.subjects,subjectSemantics:o.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:je(i),reason:e.reason}:{...a,action:"defer",eventId:je(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:o.subjects.map(g=>g.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},c=co(t.bundle,d);if(!c.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:c.errors.map(g=>g.message).join(" ")};let y=await this.store.commitReviewPlan(c.plan,{transactionId:je(i),committedAt:s});await this.refreshIndex(y);let w=c.plan.resultRefs.find(g=>g.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:w,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:y.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),o=Pi(t.bundle,e),r=fe(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(o.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:o.iterationId,proposalIds:o.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:o.iterationId,proposalIds:o.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let o=await this.store.load(),r=o.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active"),i=o.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="ai"&&v.status==="active"),s=e.action?r:i??r,a=o.bundle.records.find(v=>v.recordType==="subject"&&v.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),c=Date.parse(d),y=o.bundle.manifest.projectId,w=[],g=[],S=[],b=o.bundle.records.filter(v=>v.recordType==="advisory_explanation"),h=new Map(b.flatMap(v=>{let u=Mn(v);return u?[[u,v.id]]:[]}));for(let v of e.summary.changes)if(!h.has(v.explanationId)){let u=t?.explanations.find(x=>x.id===v.explanationId);h.set(v.explanationId,fe(y,"imprint-explanation",v.explanationId,Date.parse(u?.createdAt??d)))}for(let v of e.summary.changes){let u={kind:"external",id:v.explanationId,uri:jn},x=h.get(v.explanationId),m=b.find(E=>E.id===x),f=t?.explanations.find(E=>E.id===v.explanationId),M={id:fe(y,"imprint-live-evidence",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,c),schemaVersion:1,projectId:y,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:[]};w.push(M);let $={id:x,schemaVersion:1,projectId:y,createdAt:m?.createdAt??f?.createdAt??d,participantId:m?.participantId??s.id,sourceRefs:pr([...m?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:f?.kind??m?.kind??"pattern",state:f?.state??v.state,statement:f?.statement??v.statement,rationale:f?.rationale??m?.rationale??e.summary.detail,scope:structuredClone(f?.scope??m?.scope??{kind:"project",values:[]}),subjectIds:m?.subjectIds??[a.id],evidenceIds:[...new Set([...m?.evidenceIds??[],M.id])],concreteBindings:f?mo(t,v.explanationId):m?.concreteBindings??[],supersededById:f?.supersededBy?h.get(f.supersededBy):m?.supersededById,updatedAt:f?.updatedAt??d};m?g.push($):w.push($),S.push({id:fe(y,"imprint-live-evidence-link",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,c),schemaVersion:1,projectId:y,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:$.id},to:{entityType:"evidence",entityId:M.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(o.bundle.relationships.flatMap(v=>v.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===nn?[u.id]:[])));for(let v of t?.relations??[]){let u=ur(v.type);if(!u)continue;let x=h.get(v.fromId),m=v.toStoreId?e.qualifiedExplanationMemoryIds?.[`${v.toStoreId}:${v.toId}`]:h.get(v.toId);!x||!m||p.has(v.id)||S.push({id:fe(y,"imprint-relation",v.id,Date.parse(v.createdAt)),schemaVersion:1,projectId:y,createdAt:v.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:v.id,uri:nn}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:x},to:{entityType:"advisory_explanation",entityId:m,...v.toStoreId?{storeId:v.toStoreId}:{}},reason:v.rationale||"The Imprint graph connected these explanations."})}let I=fe(o.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,c);try{let v=await this.store.commit({records:w,recordReplacements:g,events:[],relationships:S,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:I,committedAt:d});await this.refreshIndex(v)}catch(v){if(!(v instanceof Error)||!v.message.includes("Transaction already exists"))throw v}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=Et(JSON.parse(await An(tn(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),o=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")??o;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let a=t.bundle.manifest.projectId,d=t.bundle.records.filter(f=>f.recordType==="advisory_explanation"),c=new Map(d.flatMap(f=>{let M=Mn(f);return M?[[M,f]]:[]})),y=new Map([...[...c].map(([f,M])=>[f,M.id]),...e.explanations.filter(f=>!c.has(f.id)).map(f=>[f.id,fe(a,"imprint-explanation",f.id,Date.parse(f.createdAt))])]),w=[],g=[],S=new Set(e.explanations.map(f=>f.id));for(let f of e.explanations){let M=c.get(f.id);if(!M){w.push({id:y.get(f.id),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:jn}],recordType:"advisory_explanation",kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:mo(e,f.id),supersededById:f.supersededBy?y.get(f.supersededBy):void 0,updatedAt:f.updatedAt});continue}let $={...structuredClone(M),kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),concreteBindings:mo(e,f.id),supersededById:f.supersededBy?y.get(f.supersededBy):void 0,updatedAt:f.updatedAt},E=F=>JSON.stringify({kind:F.kind,state:F.state,statement:F.statement,rationale:F.rationale,scope:F.scope,concreteBindings:F.concreteBindings,supersededById:F.supersededById,updatedAt:F.updatedAt});E(M)!==E($)&&g.push($)}for(let[f,M]of c)S.has(f)||M.state==="retired"||g.push({...structuredClone(M),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let b=new Set(t.bundle.tombstones.flatMap(f=>f.objectType==="relationship"?[f.objectId]:[])),h=new Map(t.bundle.relationships.flatMap(f=>{if(b.has(f.id))return[];let M=f.sourceRefs.find($=>$.kind==="external"&&$.uri===nn)?.id;return M?[[M,f]]:[]})),p=[],I=new Set;for(let f of e.relations){let M=ur(f.type);if(!M||f.toStoreId)continue;let $=y.get(f.fromId),E=y.get(f.toId);if(!$||!E)continue;let F=h.get(f.id);F&&F.relationshipType===M&&F.from.entityType==="advisory_explanation"&&F.from.entityId===$&&F.to.entityType==="advisory_explanation"&&F.to.entityId===E||(F&&I.add(f.id),p.push({id:fe(a,"imprint-relation",`${f.id}:${M}:${$}:${E}`,Date.parse(f.createdAt)),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:nn}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:$},to:{entityType:"advisory_explanation",entityId:E},reason:f.rationale||"The Imprint graph connected these explanations."}))}let v=new Set(e.relations.map(f=>f.id)),u=o?[...h].filter(([f])=>!v.has(f)||I.has(f)).map(([,f])=>({id:fe(a,"imprint-relationship-tombstone",f.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:f.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:o.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!w.length&&!g.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let x=e.updatedAt,m=fe(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(x));try{let f=await this.store.commit({records:w,recordReplacements:g,events:[],relationships:p,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:m,committedAt:x});return await this.refreshIndex(f),{status:"synced",relationships:p.length+u.length,explanations:w.length+g.length,headSequence:f.report.headSequence}}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f;return{status:"no_change",relationships:0,explanations:0,headSequence:t.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 t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let o={};for(let r of t.bundle.records)o[r.recordType]=(o[r.recordType]??0)+1;return{status:e,journal:t.report,records:o,openFreshnessSignals:t.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:t.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:t}=await this.store.load(),o=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(a=>a.status==="projected").map(a=>a.decisionId):[])),r=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!o.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,a)=>a.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(),t=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),o=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=>t.has(i))&&o.set(r.key,r);return[...o.values()]}async getImprintView(e=[],t){let o=()=>({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 o();let r=await this.store.load(),i=r.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(i.map(p=>[p.id,p])),a=new Map(i.flatMap(p=>{let I=Mn(p);return I?[[I,p.id]]:[]})),d=new Set(e.map(p=>a.get(p)??p)),c=new Map(r.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),y=new Map(r.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),w=new Set(r.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),g=new Set(["expresses","operationalizes","excepts"]),S={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=i.map(p=>{let I=p.evidenceIds.flatMap(m=>{let f=y.get(m);if(!f)return[];let M=f.sourceRefs.find(Y=>Y.kind==="thread")?.id,$=f.sourceRefs.find(Y=>Y.kind==="message")?.id,E=f.kind==="judgment"||f.kind==="user_feedback"||f.kind==="project_state"?f.kind:"other",F=c.get(f.participantId)??"unknown";return[{id:f.id,kind:E,summary:f.summary,createdAt:f.createdAt,participantKind:F,threadId:M,jobId:$}]}).sort((m,f)=>f.createdAt.localeCompare(m.createdAt)),v=r.bundle.relationships.flatMap(m=>{if(w.has(m.id))return[];if(!g.has(m.relationshipType))return[];let f=m.from.entityType==="advisory_explanation"&&m.from.entityId===p.id&&m.to.entityType==="advisory_explanation",M=m.to.entityType==="advisory_explanation"&&m.to.entityId===p.id&&m.from.entityType==="advisory_explanation";if(!f&&!M)return[];let $=f?m.to.entityId:m.from.entityId,E=s.get($);return E?[{id:m.id,type:m.relationshipType==="excepts"?"excepts":"expresses",direction:f?"outgoing":"incoming",explanationId:E.id,statement:E.statement,rationale:m.reason}]:[]}),u=[...(p.supersededById?[p.supersededById]:[]).flatMap(m=>{let f=s.get(m);return f?[{id:`supersedes:${p.id}:${f.id}`,type:"supersedes",direction:"incoming",explanationId:f.id,statement:f.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...i.flatMap(m=>m.supersededById===p.id?[{id:`supersedes:${m.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:m.id,statement:m.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],x=[...new Set([...p.sourceRefs.flatMap(m=>m.kind==="thread"?[m.id]:[]),...I.flatMap(m=>m.threadId?[m.threadId]:[])])].filter(m=>!t||t.has(m));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:I.length,recentEvidence:I.slice(0,4),concrete:p.concreteBindings.map(m=>({...structuredClone(m)})),relations:[...v,...u],sourceThreadIds:x,needsGrounding:p.state==="testing"&&d.has(p.id)}}).sort((p,I)=>Number(I.needsGrounding)-Number(p.needsGrounding)||S[p.state]-S[I.state]||I.updatedAt.localeCompare(p.updatedAt)),h={total:b.filter(p=>p.state!=="retired").length,emerging:b.filter(p=>p.state==="emerging").length,testing:b.filter(p=>p.state==="testing").length,grounded:b.filter(p=>p.state==="grounded").length,challenged:b.filter(p=>p.state==="challenged").length,retired:b.filter(p=>p.state==="retired").length,needsGrounding:b.filter(p=>p.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:h,explanations:b}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(a=>a.recordType==="decision"&&a.state==="active"?[a.id]:[])),o=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,c)=>d.createdAt.localeCompare(c.createdAt)))a.decisionIds.some(d=>t.has(d))&&o.set(a.key,a);let r=[...o.values()],i=e.records.filter(a=>a.recordType==="verification_attempt");return{decisions:e.records.filter(a=>a.recordType==="decision"&&a.state==="active").map(a=>{let d=i.filter(c=>c.targets.some(y=>y.entityType==="decision"&&y.entityId===a.id)).sort((c,y)=>y.createdAt.localeCompare(c.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(c=>c.decisionIds.includes(a.id)),verification:d?d.state:"unverified"}}),entries:r.map(a=>({id:a.id,key:a.key,value:a.value,decisionIds:a.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),o=t.bundle.records.find(E=>E.recordType==="participant"&&E.kind==="human"&&E.status==="active"),r=t.bundle.records.find(E=>E.recordType==="subject"&&E.subjectType==="project");if(!o||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=je(i),d=je(i),c=je(i),y=je(i),w=je(i),g=new Set(t.bundle.records.flatMap(E=>E.recordType==="model_entry"&&E.key===e.key?E.decisionIds:[])),S=t.bundle.records.filter(E=>E.recordType==="decision"&&E.state==="active"&&g.has(E.id)),b={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},h=[{subjectId:r.id,role:"governed"}],p={...b,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:h,origin:{mode:"declared",sourceText:e.claim,reviewedById:o.id}},I={...b,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:a},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...b,id:c,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:o.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:h,noChange:!1,effectiveAt:s},u={...b,id:y,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[c],value:e.value},x={...b,id:w,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:o.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[c],entryIds:[y],coverage:[{decisionId:c,status:"projected"}]},m={...b,id:je(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:y},to:{entityType:"decision",entityId:c},reason:"The model change is projected from the owner-confirmed decision."},f=S.map(E=>({...b,id:je(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:E.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),M=S.map(E=>({...b,id:je(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:E.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),$=await this.store.commit({records:[p,v,u,x],events:[I,...f],relationships:[m,...M],artifacts:[],tombstones:[],projectionUpdates:S.map(E=>({entityType:"decision",entityId:E.id,fromState:"active",state:"superseded"}))},{transactionId:je(i),committedAt:s});return await this.refreshIndex($),{decisionId:c,entryId:y}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),o=t.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return o?{proposalId:o.id,claim:o.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),o=new Map(t.records.flatMap(r=>r.recordType==="subject"?[[r.id,r.label]]:[]));return t.records.filter(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.kind==="thread"&&i.id===e)).sort((r,i)=>r.createdAt.localeCompare(i.createdAt)).map(r=>({proposalId:r.id,claim:r.claim,rationale:r.rationale,proposedKind:r.proposedKind,subjectLabels:r.subjects.flatMap(i=>{let s=o.get(i.subjectId);return s?[s]:[]})}))}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 t=await this.store.load(),o=t.bundle.records.find(b=>b.recordType==="model_projection"&&b.state==="applied"&&b.runId===e.runId);if(o)return{projectionId:o.id,entryIds:o.entryIds,headSequence:t.report.headSequence};let r=t.bundle.records.filter(b=>b.recordType==="decision"&&e.decisionIds.includes(b.id)&&b.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=t.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=je(s),c=e.changes.map(b=>{let h=b.decisionIds?.filter(v=>e.decisionIds.includes(v)),p=h?.length?h:e.decisionIds,I=[...new Set(r.filter(v=>p.includes(v.id)).flatMap(v=>v.subjects.map(u=>u.subjectId)))];return{id:je(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:p.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:b.path.map(String).join("."),subjectIds:I,decisionIds:p,value:b.value}}),y=new Set(c.flatMap(b=>b.decisionIds)),w={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(b=>({kind:"record",id:b})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:a,decisionIds:e.decisionIds,entryIds:c.map(b=>b.id),coverage:e.decisionIds.map(b=>e.coverage?.find(h=>h.decisionId===b)??{decisionId:b,status:y.has(b)?"projected":"unprojected"})},g=c.flatMap(b=>b.decisionIds.map(h=>({id:je(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:w.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b.id},to:{entityType:"decision",entityId:h},reason:"The owner applied this model entry as a projection of accepted product truth."}))),S=await this.store.commit({records:[...c,w],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:je(s),committedAt:a});return await this.refreshIndex(S),{projectionId:d,entryIds:c.map(b=>b.id),headSequence:S.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await Pn({...e,projectRoot:this.projectRoot})).bundle}}async loadJournalSource(){let e=await this.store.readHead(),t=`${e.checkpointSequence}:${e.checkpointHash}:${e.sequence}:${e.hash??""}`;if(this.contextualSourceCache?.headKey===t)return this.contextualSourceCache.value;let o=await this.store.load(),r={source:"journal",bundle:o.bundle,journal:o.report};return this.contextualSourceCache={headKey:t,value:r},r}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let o=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Ci(o,t.subjectHints??[]);return r?{...t,subjectIds:[...new Set([...t.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:t}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 rn(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object.");return n}function Oe(n,e){if(typeof n!="string"||!n.trim())throw new Error(`${e} must be a non-empty string.`);return n}function on(n,e,t){let o=Oe(n,e);if(!t.includes(o))throw new Error(`${e} is invalid.`);return o}function mr(n){let e=rn(n),t=rn(e.authority),o=t.level,r=t.mode,i=on(o,"authority.level",["owner","delegate","contributor"]),s=on(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Oe(e.proposalId,"proposalId"),participantId:Oe(e.participantId,"participantId"),occurredAt:Oe(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...a,action:"accept",eventId:Oe(e.eventId,"eventId"),decisionId:Oe(e.decisionId,"decisionId"),kind:on(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Oe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Oe(e.eventId,"eventId"),reason:Oe(e.reason,"reason")};case"defer":{let d=rn(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...a,action:"defer",eventId:Oe(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(c=>Oe(c,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(c=>on(c,"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{...a,action:"edit_and_accept",withdrawalEventId:Oe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Oe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Oe(e.acceptanceEventId,"acceptanceEventId"),decisionId:Oe(e.decisionId,"decisionId"),relationshipId:Oe(e.relationshipId,"relationshipId"),claim:Oe(e.claim,"claim"),kind:on(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let c=rn(d);return{subjectId:Oe(c.subjectId,"subjectId"),role:on(c.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:Oe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function fr(n){let e=rn(n),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Oe(a,s))}},o=(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:rn(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:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:o(e.maxPackets,"maxPackets"),maxEstimatedTokens:o(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}}var Vd=1400,Kd=6,Hd=2,hr=6;function Ni(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.projectRoot=="string"&&!!e.projectRoot.trim()&&typeof e.projectId=="string"&&!!e.projectId.trim()}function qi(n){if(!n||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Ni(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(Ni):[],o=new Set([e.primary.storeId]);return{primary:e.primary,mounted:t.filter(r=>o.has(r.storeId)?!1:(o.add(r.storeId),!0))}}function Bi(n){return[n.primary,...n.mounted]}function En(n){let e=[],t=Math.max(0,...n.map(o=>o.length));for(let o=0;o<t;o++)for(let r of n)r[o]!==void 0&&e.push(r[o]);return e}function Ji(n){return Math.ceil(JSON.stringify(n).length/4)}function Qd(n,e,t){return{...n,...n.acceptedTruth?{acceptedTruth:{...n.acceptedTruth,decisions:n.acceptedTruth.decisions.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),conflicts:n.acceptedTruth.conflicts.map(o=>({...o,storeId:e.storeId}))}}:{},packets:n.packets.map(o=>({...o,presentation:t?"advisory":o.presentation,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Xd(n,e,t,o){if(!n.length)return;if(!o&&e.length===0)return n[0].context;let r=n.map(({store:w,context:g})=>Qd(g,w,w.storeId!==t)),i=En(r.map(w=>w.acceptedTruth?.decisions??[])).slice(0,Kd),s=new Set(i.map(w=>`${w.storeId}:${w.id}`)),a=r.flatMap(w=>w.acceptedTruth?.conflicts??[]).filter(w=>w.decisionIds.every(g=>s.has(`${w.storeId}:${g}`))),d=En(r.map(w=>w.packets)).slice(0,Hd),c=i.length<r.reduce((w,g)=>w+(g.acceptedTruth?.decisions.length??0),0)||d.length<r.reduce((w,g)=>w+g.packets.length,0),y={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:c||r.some(w=>w.acceptedTruth?.truncated)}}:{},packets:d,truncated:c||e.length>0||r.some(w=>w.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;Ji(y)>Vd;){if(y.packets.length)y.packets.pop();else if(y.acceptedTruth?.decisions.length)y.acceptedTruth.decisions.pop();else break;y.truncated=!0,y.acceptedTruth&&(y.acceptedTruth.truncated=!0)}if(y.estimatedTokens=Ji(y),!(!y.packets.length&&!y.acceptedTruth?.decisions.length))return y}function Li(n,e,t){return{...n,explanations:n.explanations.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),relations:n.relations?.map(o=>({...o,storeId:e.storeId,readOnly:t,from:o.from??{storeId:e.storeId,explanationId:o.fromId},to:o.to??{storeId:o.toStoreId??e.storeId,explanationId:o.toId}})),historicalCaveats:n.historicalCaveats?.map(o=>({...o,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Ee(n,e){return`${n}:${e}`}function Yd(n){let e=n.from??{storeId:n.storeId??"",explanationId:n.fromId},t=n.to??{storeId:n.storeId??"",explanationId:n.toId};return`${n.storeId??""}:${n.type}:${Ee(e.storeId,e.explanationId)}:${Ee(t.storeId,t.explanationId)}`}function Zd(n,e){let t=new Map;for(let{store:o,topology:r}of n)for(let i of r.explanations)t.set(Ee(o.storeId,i.memoryId),i.explanationId);return n.flatMap(({store:o,topology:r})=>r.relations.flatMap(i=>{let s=i.from.storeId??o.storeId,a=i.to.storeId??o.storeId,d=t.get(Ee(s,i.from.memoryId)),c=t.get(Ee(a,i.to.memoryId));return!d||!c?[]:[{id:i.id,type:i.type,fromId:d,toId:c,rationale:i.rationale,storeId:o.storeId,readOnly:o.storeId!==e,from:{storeId:s,explanationId:d},to:{storeId:a,explanationId:c}}]}))}function ec(n){let e=new Set;return n.filter(t=>{let o=Yd(t);return e.has(o)?!1:(e.add(o),!0)})}function tc(n,e,t,o,r=[],i=[],s=[]){if(!n.length)return;if(!o&&e.length===0)return n[0].context;let a=n.map(({store:u,context:x})=>Li(x,u,u.storeId!==t)),d=En(a.map(u=>u.explanations)),c=ec([...a.flatMap(u=>u.relations??[]),...r]),y=new Map([...d,...i].map(u=>[Ee(u.storeId??"",u.id),u])),w=[],g=new Set,S=u=>{if(!u||w.length>=hr)return;let x=Ee(u.storeId??"",u.id);g.has(x)||(g.add(x),w.push(u))};for(let u of d.slice(0,hr)){let x=Ee(u.storeId??"",u.id),m=c.flatMap(f=>f.from&&Ee(f.from.storeId,f.from.explanationId)===x?[y.get(Ee(f.to.storeId,f.to.explanationId))]:f.to&&Ee(f.to.storeId,f.to.explanationId)===x?[y.get(Ee(f.from.storeId,f.from.explanationId))]:[]).find(Boolean);m&&(S(u),S(m))}d.forEach(S),i.forEach(S);let b=w,h=c.filter(u=>{let x=u.from,m=u.to;return!!(x&&m&&g.has(Ee(x.storeId,x.explanationId))&&g.has(Ee(m.storeId,m.explanationId)))}),p=new Set([...d.map(u=>Ee(u.storeId??"",u.id)),...i.map(u=>Ee(u.storeId??"",u.id))]).size,I=[...new Set(a.flatMap(u=>u.pendingGroundingExplanationIds??[]))],v=[...new Set(a.flatMap(u=>u.correctionExplanationIds??[]))];return{explanations:b,relations:h,truncated:b.length<p||e.length>0||a.some(u=>u.truncated),...a.find(u=>u.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(u=>u.retrievalIntent).retrievalIntent}:{},historicalCaveats:En(a.map(u=>u.historicalCaveats??[])).slice(0,3),...I.length?{pendingGroundingExplanationIds:I}:{},...v.length?{correctionExplanationIds:v}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var fo=class{constructor(e,t,o=r=>({memory:new sn(r.projectRoot),imprint:new kt(r.projectRoot,r.projectId)})){this.primary=e;this.createReader=o;this.readers=new Map;this.state={reads:0,storeReads:0,failedStoreReads:0,lastDurationMs:0};this.readers.set(e.storeId,t)}diagnostics(){return{...this.state}}normalized(e){return!e||e.primary.storeId!==this.primary.storeId||e.primary.projectId!==this.primary.projectId?{primary:this.primary,mounted:[]}:{primary:this.primary,mounted:e.mounted}}reader(e){let t=this.readers.get(e.storeId);if(t)return t;let o=this.createReader(e);return this.readers.set(e.storeId,o),o}async memoryContext(e,t,o){let r=performance.now(),i=Bi(this.normalized(e)),s=await Promise.allSettled(i.map(async c=>{let y,w=await io(this.reader(c).memory,t,o,g=>{y=g});if(y)throw y;return{store:c,context:w}})),a=s.flatMap(c=>c.status==="fulfilled"&&c.value.context?[c.value]:[]),d=s.flatMap((c,y)=>c.status==="rejected"?[i[y].storeId]:[]);return this.record(i.length,d.length,r),Xd(a,d,this.primary.storeId,i.length>1)}async imprintContext(e,t){let o=performance.now(),r=Bi(this.normalized(e)),i=r.length>1,s=r.map(async R=>({store:R,context:await this.reader(R).imprint.contextualize(R.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async R=>({store:R,topology:await(this.reader(R).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[d,c]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),y=d.flatMap(R=>R.status==="fulfilled"&&R.value.context?[R.value]:[]),w=d.flatMap((R,J)=>R.status==="rejected"?[r[J].storeId]:[]),g=c.flatMap(R=>R.status==="fulfilled"?[R.value]:[]),S=c.flatMap((R,J)=>R.status==="rejected"?[r[J].storeId]:[]),b=new Map(g.flatMap(({store:R,topology:J})=>J.explanations.map(W=>[Ee(R.storeId,W.explanationId),W.memoryId]))),h=y.map(({store:R,context:J})=>({store:R,context:{...J,explanations:J.explanations.map(W=>({...W,memoryId:b.get(Ee(R.storeId,W.id))}))}})),p=Zd(g,this.primary.storeId),I=h.map(({store:R,context:J})=>Li(J,R,R.storeId!==this.primary.storeId)),v=En(I.map(R=>R.explanations)).slice(0,hr),u=new Set(v.map(R=>Ee(R.storeId??"",R.id))),x=new Set(I.flatMap(R=>R.explanations.map(J=>Ee(J.storeId??"",J.id)))),m=new Map,f=(R,J)=>{if(x.has(Ee(R,J)))return;let W=m.get(R)??new Set;W.add(J),m.set(R,W)};for(let R of p){if(!R.from||!R.to)continue;let J=Ee(R.from.storeId,R.from.explanationId),W=Ee(R.to.storeId,R.to.explanationId);u.has(J)&&f(R.to.storeId,R.to.explanationId),u.has(W)&&f(R.from.storeId,R.from.explanationId)}let M=new Map(r.map(R=>[R.storeId,R])),$=[...m].map(async([R,J])=>{let W=M.get(R),ee=W?this.reader(W).imprint.explanationsByIds:void 0;if(!W||!ee)return{storeId:R,explanations:[]};let H=await ee.call(this.reader(W).imprint,[...J]);return{storeId:R,explanations:H.map(ie=>({...ie,memoryId:b.get(Ee(R,ie.id)),storeId:R,storeRoot:W.projectRoot,readOnly:R!==this.primary.storeId}))}}),E=await Promise.allSettled($),F=E.flatMap(R=>R.status==="fulfilled"?R.value.explanations:[]),Y=E.flatMap((R,J)=>R.status==="rejected"?[[...m.keys()][J]]:[]),L=[...new Set([...S,...Y])];return this.record(r.length,new Set([...w,...L]).size,o),tc(h,w,this.primary.storeId,i,p,F,L)}record(e,t,o){this.state.reads+=1,this.state.storeReads+=e,this.state.failedStoreReads+=t,this.state.lastDurationMs=Math.max(0,performance.now()-o)}};function an(n,e){return!n||e||n.attention!=="response_requested"?n:{...n,attention:"response_available"}}function _n(n){let e=Array.from(new Set((n.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],o=n.decisionRequired?"decision_required":n.question||n.groundingRequired?"response_requested":n.reviewRequired||n.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return n.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:n.imprintTransactionId}),{attention:o,outcomes:t}}var Dt=1,gr="bridge";function Fi(n){return`codex-session:${n}`}function sc(n,e){return`codex-${nc("sha256").update(`${n}:${e}`).digest("hex").slice(0,16)}`}function Ui(n){return{timestamp:new Date().toISOString(),url:"codex://ambient",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[{id:"ambient-prompt",type:"instruction",instruction:n,elements:[]}],styleModifications:[]}}function zi(n,e){let t=new Set,o=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(rc(s)?ic(e,s):s)},r=(i,s="",a=0)=>{if(!(a>5||i===null||i===void 0)){if(typeof i=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&o(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))o(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,c]of Object.entries(i))r(c,d,a+1)}};for(let i of n)r(i.toolInput);return[...t]}function ho(n){return n?Math.ceil(n.length/4):0}function Gi(n,e,t,o,r,i){let s=["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${t}; the tool session is ${n}.`,"The human remains the authority for accepted product decisions and Imprint grounding. Never infer acceptance from implementation, praise, silence, or ambiguity.","Popmelt records the turn automatically. Use Popmelt Core tools only for intentional context expansion, explicit decision review, Imprint grounding, or a structured learning assessment."].join(`
15
+ `),a=Sn(o),d=Wi(r,i),c=[s,a,d].filter(Boolean).join(`
16
+ `);return{additionalContext:c,contextBudget:{protocolEstimatedTokens:ho(s),memoryEstimatedTokens:ho(a),imprintEstimatedTokens:ho(d),totalEstimatedTokens:ho(c)}}}function Wi(n,e){return n?Qt(n,{requestText:e}).split(`
17
17
  `).map(t=>t.startsWith("As soon as one or more surfaced explanations become actively useful")?"":t.startsWith("At the end, emit exactly one machine-readable <resolution> envelope")?"Do not print a machine-readable resolution envelope in the visible Codex response. When this collaboration changes reusable shared understanding, call `popmelt_assess_turn` before the final response.":t.startsWith("The final shape is `<resolution>")?'Pass the complete `<resolution>{"annotations":[...],"imprint":{...}}</resolution>` shape as `assessmentText` to `popmelt_assess_turn`; do not include it in conversational prose.':t).join(`
18
18
  `):["","## Continuous imprinting","","An imprint is provisional, advisory shared understanding; accepted product decisions always win. Ordinary completion, implementation, praise, silence, and ambiguity are not learning.","Before finishing, ask one level above the exact task whether human-supplied evidence established a reusable intention, rationale, relationship, or applicability boundary that would change a future decision. The default is no Imprint action.","Call `popmelt_assess_turn` only when reusable understanding changed. Before mutating, require all six: reusable, novel, durable, atomic, scoped, and supported by the human anywhere in the thread. If overlap with project knowledge is plausible, expand context before adding so the result can be consolidated or related instead of duplicated.",'For a genuinely new root, pass `assessmentText` as `<resolution>{"annotations":[],"imprint":{"decision":"mutate","summary":{"kind":"added","title":"<short title>","detail":"<what changed>"},"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one atomic claim>","rationale":"<human-supported reason>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<why no existing explanation is related>"}]}}</resolution>`.','Include `appliedExplanationIds:["new-1"]` and a `grounding` question only when completed implementation or another observable action genuinely tested the new explanation; otherwise omit them.',"When context expansion surfaces related explanations, follow its complete relationship, application, correction, and topology contract. Do not print a machine-readable resolution envelope in the visible response."].join(`
19
- `)}function Cn(n){if(!n)return;if(n.decision==="recognize")return[n.explanationId];let e=[...new Set([...n.usedExplanationIds??[],...n.appliedExplanationIds??[]])];return e.length?e:void 0}function ic(n,e){let t=e.flatMap((o,r)=>{let i=n[r];return i?[{packetId:`ambient:${o}`,proposalId:o,claim:i.claim.trim(),proposedKind:i.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:o}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var go=class{constructor(e){this.options=e;this.turns=new Map;let t={storeId:e.storeId,projectRoot:e.projectRoot,projectId:e.projectId};this.knowledgeViewReader=e.knowledgeViewReader??new fo(t,{memory:e.memoryService,imprint:e.imprintService})}knowledgeDiagnostics(){return this.knowledgeViewReader.diagnostics()}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([Li(e)])}async prepare(e){if(e.executionOwner===gr)return{status:"managed_by_bridge",protocolVersion:Dt};let t=this.key(e.sessionId,e.turnId),o=this.turns.get(t);if(o){let g=zi(o.sessionId,o.threadId,o.jobId,o.memoryContext,o.imprintContext,o.prompt);return{status:"already_prepared",protocolVersion:Dt,threadId:o.threadId,jobId:o.jobId,...g}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${tc()}`,[Li(e.sessionId)]));let i=rc(e.sessionId,e.turnId),s=r.messages.find(g=>g.jobId===i&&g.role==="human"),a=Fi(e.prompt),d=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),c=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(g=>g.role==="assistant"&&g.imprintSummary?.grounding&&!g.imprintSummary.resolvedAction?[g.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(r.id,{role:"human",timestamp:Date.now(),jobId:i,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...d?{memoryReview:d}:{},...c?{imprintContext:c}:{}});let I={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:d,imprintContext:c,events:[]};this.turns.set(t,I);let v=zi(e.sessionId,r.id,i,d,c,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Dt,threadId:r.id,jobId:i,...v}}async recordEvent(e){if(e.executionOwner===gr)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(o=>o.toolUseId===e.toolUseId)?{status:"recorded"}:(t.events.push({toolName:e.toolName,toolUseId:e.toolUseId,toolInput:e.toolInput,toolResponse:e.toolResponse,occurredAt:Date.now()}),{status:"recorded"}):{status:"turn_not_prepared"}}async assess(e){let t=[...this.turns.values()].find(d=>d.threadId===e.threadId&&d.jobId===e.jobId);if(!t)return{status:"turn_not_found"};if((await this.options.threadStore.getThread(t.threadId))?.messages.some(d=>d.role==="assistant"&&d.jobId===t.jobId))return{status:"turn_completed"};if(t.assessmentEvaluation?.receipt.status==="committed")return t.assessmentEvaluation.receipt;t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)};let r=t.assessment.semanticCandidates.length?{status:"queued_for_turn_completion",count:t.assessment.semanticCandidates.length}:void 0,i=Ui(t.events,this.options.projectRoot).length>0,s=Ht(t.assessment.assessmentText,{context:t.imprintContext,requestText:t.prompt,applicationOccurred:i}),a;if(s.error)a={receipt:{status:"rejected",reason:s.error},imprintAssessment:{state:s.error.includes("missing")?"missing":"invalid",reason:s.error}};else if(s.draft?.decision==="none")this.options.imprintService.recordNoop(s.draft.reason),a={receipt:{status:"assessed",outcome:"no_change",reason:s.draft.reason,...r?{semanticCandidates:r}:{}},imprintAssessment:{state:"none",reason:s.draft.reason},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else if(s.draft?.decision==="recognize")a={receipt:{status:"assessed",outcome:"recognized",...r?{semanticCandidates:r}:{}},imprintAssessment:{state:"none",reason:"recognized existing grounded understanding"},imprintUsedExplanationIds:Cn(s.draft)};else if(s.draft?.decision==="mutate"||s.draft?.decision==="apply")try{let d=await this.options.imprintService.capture(s.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:t.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:i,storeId:this.options.storeId,context:t.imprintContext});if(d)await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId,qualifiedExplanationMemoryIds:Object.fromEntries((t.imprintContext?.explanations??[]).flatMap(c=>c.storeId&&c.memoryId?[[`${c.storeId}:${c.id}`,c.memoryId]]:[]))}).catch(()=>{}),a={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...r?{semanticCandidates:r}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else{let c="imprint mutation failed admission or produced no durable change";a={receipt:{status:"rejected",reason:c},imprintAssessment:{state:"invalid",reason:c},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}}catch(d){let c=d instanceof Error?d.message:"imprint mutation failed";a={receipt:{status:"rejected",reason:c},imprintAssessment:{state:"invalid",reason:c},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}else{let d="imprint assessment is missing";a={receipt:{status:"rejected",reason:d},imprintAssessment:{state:"missing",reason:d}}}return t.assessmentEvaluation=a,(a.imprintAssessment.state==="missing"||a.imprintAssessment.state==="invalid")&&this.options.imprintService.recordAssessmentFailure(a.imprintAssessment.state),a.receipt}async complete(e){if(e.executionOwner===gr)return{status:"managed_by_bridge",protocolVersion:Dt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Dt};let r=(await this.options.threadStore.getThread(t.threadId))?.messages.find(p=>p.role==="assistant"&&p.jobId===t.jobId);if(r)return e.lastAssistantMessage&&e.lastAssistantMessage!==r.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Dt,threadId:t.threadId,jobId:t.jobId};let i=Ui(t.events,this.options.projectRoot),s=i.length>0,a=t.assessmentEvaluation?.imprintSummary,d=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},c=t.assessmentEvaluation?.imprintUsedExplanationIds,I=t.assessmentEvaluation?.imprintAppliedExplanationIds,v=s?"completed":"no_change",g=_n({changedFiles:i}),k={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(p=>p.toolName),turn:{phase:"complete",orientation:[],result:g},result:g,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:c,imprintAppliedExplanationIds:I};await this.options.threadStore.appendMessage(t.threadId,k);let b=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:v,execution:{provider:"codex",model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:i,resolutions:s?[{status:"resolved",summary:`Changed ${i.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(p=>p.id),imprintAssessment:d}),h=ic(t.assessment?.semanticCandidates??[],b.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:Dt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Fi(e.query),o=await this.knowledgeViewReader.memoryContext(e.knowledgeView,t,e.subjectHints??[]),r=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints});return{memoryContext:o,imprintContext:r,formattedContext:[Sn(o),Gi(r,e.query)].filter(Boolean).join(`
20
- `)}}};import{spawn as sc}from"child_process";import{createInterface as ac}from"readline";function $n(n,e){let t=e.trim();if(!t)return"";let o=n.length>0?`
21
-
22
- ${t}`:t;return n.push(o),o}var dc=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"]),Wi=1e5;function cc(n){let e=n.input?.file_path||n.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!dc.has(t))return;let o;if(n.name==="Write"&&typeof n.input?.content=="string"?o=n.input.content:n.name==="Edit"&&typeof n.input?.new_string=="string"&&(o=n.input.new_string),!!o)return o.length>Wi?o.slice(0,Wi)+`
23
- \u2026[truncated]`:o}function yo(n,e){let{prompt:t,projectRoot:o,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:d,model:c,reasoningEffort:I,timeoutMs:v=3e5,onEvent:g}=e,k=[];d?k.push("--resume",d,"-p",t):k.push("-p",t),k.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),c&&k.push("--model",c),I&&k.push("--effort",I);for(let p of s)k.push("--allowedTools",p);let b=sc(a,k,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(p=>{let y,w=[],u=[],x=[],m=!1,f="",M,$,E=!1,F=setTimeout(()=>{E=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},v),Y=ac({input:b.stdout}),L=new Set;Y.on("line",J=>{if(J.trim())try{let W=JSON.parse(J);W.session_id&&!y&&(y=W.session_id);let ee=W.type??(W.event?.type?`event.${W.event.type}`:"unknown");if(L.add(ee),W.type==="result"&&W.result&&w.length===0){let H=typeof W.result=="string"?W.result:"";if(H){let ie=$n(w,H);ie&&g?.({type:"delta",jobId:n,text:ie},n)}}if(W.type==="assistant"&&Array.isArray(W.message?.content)){typeof W.error=="string"&&(M=W.error);for(let H of W.message.content){if(H.type==="text"&&H.text){let ie=$n(w,H.text);ie&&g?.({type:"delta",jobId:n,text:ie},n)}if(H.type==="tool_use"&&H.name){let ie=H.input?.file_path||H.input?.path||void 0,P=cc(H);if(g?.({type:"tool_use",jobId:n,tool:H.name,...ie?{file:ie}:{},...P?{content:P}:{}},n),H.name==="Edit"&&H.input?.file_path){let j={tool:"Edit",file_path:H.input.file_path,old_string:H.input.old_string,new_string:H.input.new_string,replace_all:H.input.replace_all};u.push(j),x.push({sequence:x.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:j.file_path,oldString:typeof j.old_string=="string"?j.old_string:void 0,newString:typeof j.new_string=="string"?j.new_string:void 0,replaceAll:typeof j.replace_all=="boolean"?j.replace_all:void 0})}else H.name==="Write"&&H.input?.file_path&&(u.push({tool:"Write",file_path:H.input.file_path,content:H.input.content}),x.push({sequence:x.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:H.input.file_path,content:typeof H.input.content=="string"?H.input.content:void 0}))}H.type==="thinking"&&H.thinking&&g?.({type:"thinking",jobId:n,text:H.thinking},n)}}W.type==="result"&&W.is_error===!0&&(m=!0,typeof W.error=="string"&&(M=W.error),typeof W.result=="string"&&($=W.result)),W.type==="user"&&W.tool_use_result?.file?.filePath&&g?.({type:"tool_use",jobId:n,tool:"Read",file:W.tool_use_result.file.filePath},n)}catch{}});let R=[];b.stderr?.on("data",J=>{R.push(J.toString())}),b.on("close",J=>{if(clearTimeout(F),Y.close(),w.length===0&&L.size>0&&console.warn(`[Claude:${n}] No text captured. Event types seen: ${[...L].join(", ")}`),E)m=!0,f=`Timed out after ${Math.round(v/6e4)} minutes`;else if(J!==0&&J!==null){m=!0;let ee=R.join("").trim(),H=w.join("").trim(),ie=w.length===0&&L.size>0?` (no text captured, event types: ${[...L].join(", ")})`:"";f=ee||$||H||`Claude process exited with code ${J}${ie}`}m&&!f&&$&&(f=$);let W=lc(f,M);p({sessionId:y,text:w.join(""),success:!m,error:m?W.message:void 0,errorCode:m?W.code:void 0,recoverableError:m?W.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:x.length>0?x:void 0})}),b.on("error",J=>{clearTimeout(F),m=!0,f=J.message,p({sessionId:y,text:w.join(""),success:!1,error:f,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:x.length>0?x:void 0})})});return{process:b,result:h}}function lc(n,e){let t=n.trim()||"Claude CLI failed",o=`${e??""} ${t}`.toLowerCase();return o.includes("authentication_failed")||o.includes("not logged in")||o.includes("please run /login")||o.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:o.includes("model")&&(o.includes("not found")||o.includes("unknown")||o.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as uc,spawnSync as es}from"child_process";import{readFileSync as mc,statSync as fc}from"fs";import{basename as hc,extname as gc,isAbsolute as yc,relative as ts,resolve as Ic}from"path";import{createInterface as wc}from"readline";function wo(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Io(n,e){for(let t of n)if(t)for(let o of e){let r=t[o];if(typeof r=="string"&&r.trim())return r.trim()}}function Vi(n){let e=wo(n);if(e)return e;if(typeof n=="string")try{return wo(JSON.parse(n))}catch{return}}function yr(n){return n.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function pc(n,e,t,o){return n!=="node_repl"||e!=="js"?!1:o&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(o)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function Ki(n){let e=wo(n)??{},t=wo(e.invocation),o=Vi(e.arguments)??Vi(t?.arguments),r=Io([e,t],["server","server_name"]),i=Io([e,t],["tool","tool_name","name"]),s=Io([o,e,t],["title","display_name","description"]),a=Io([o],["code","script"]),d=pc(r,i,s,a)?"Browser":r?yr(r):i?yr(i):"MCP",c=i&&yr(i),I=s??c,v=I&&I!==d?`${d}: ${I}`:d;return{tool:d,...I?{content:I}:{},telemetryLabel:v}}function Hi(n){let e=n.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):n}var Qi=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"]),Ir=2e5,vc=1e5,ns=2e5;function os(n){let e=hc(n).toLowerCase(),t=gc(n).toLowerCase();return Qi.has(t)||Qi.has(e)}function On(n,e){let t=yc(e)?e:Ic(n,e),o=ts(n,t);return o===""||o.startsWith("..")?null:t}function vo(n,e){if(!os(e))return;let t=On(n,e);if(t)try{let o=fc(t);return o.isFile()?o.size>Ir?{exists:!0,truncated:!0}:{exists:!0,content:mc(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function bc(n,e){for(let t of e){let o=n[t];if(typeof o=="string")return o}}function xc(n){let e=n?.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 Xi(n){return bc(n,["patch","diff","unifiedDiff","unified_diff"])}function wr(n,e){return n.length<=e?{text:n}:{text:n.slice(0,e),truncated:!0}}function Yi(n,e){let t=es("git",e,{cwd:n,encoding:"utf8",timeout:5e3,maxBuffer:ns+65536});return t.status!==0?null:t.stdout??""}function Sc(n){let e=new Set;for(let t of n.split(`
24
- `)){if(t.length<4)continue;let o=t.slice(3).trim();if(!o)continue;o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));let r=o.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function Zi(n){let e=Yi(n,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Yi(n,["diff","--no-ext-diff","HEAD","--"])??"",o=wr(t,ns);return{status:e,changedFiles:Sc(e),...o.text?{diff:o.text}:{},...o.truncated?{diffTruncated:!0}:{}}}function Tc(n,e){return!n||!e?!1:n.status!==e.status||(n.diff??"")!==(e.diff??"")}function kc(n,e){if(!os(e))return;let t=On(n,e);if(!t)return;let o=ts(n,t);if(o===""||o.startsWith(".."))return;let r=es("git",["show",`HEAD:${o}`],{cwd:n,encoding:"utf8",timeout:5e3,maxBuffer:Ir+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=wr(i,Ir);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Pc(n,e,t){return e.map(o=>{let r=t.has(o)?t.get(o):kc(n,o),i=vo(n,o);return{filePath:o,...r?{before:r}:{},...i?{after:i}:{}}})}function bo(n,e){let{prompt:t,projectRoot:o,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:d="workspace-write",configOverrides:c=[]}=e,I=[];if(i){I.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let k of c)I.push("-c",k);s&&I.push("-m",s),I.push(i),I.push(t),r&&I.push("--image",r)}else{I.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let k of c)I.push("-c",k);s&&I.push("-m",s),I.push(t),r&&I.push("--image",r)}let v=uc("codex",I,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:n}}),g=new Promise(k=>{let b,h=[],p=[],y=[],w=new Map,u=new Map,x=!1,m="",f=wc({input:v.stdout}),M=new Set;f.on("line",E=>{if(E.trim())try{let F=JSON.parse(E),Y=F.type??"unknown";if(M.add(Y),Y==="thread.started"&&F.thread_id&&!b&&(b=F.thread_id),(Y==="item.agentMessage.delta"||Y==="item/agentMessage/delta")&&F.delta?.text&&(h.push(F.delta.text),a?.({type:"delta",jobId:n,text:F.delta.text},n)),(Y==="item.reasoning.delta"||Y==="item/reasoning/delta")&&F.delta?.text&&a?.({type:"thinking",jobId:n,text:F.delta.text},n),(Y==="item.started"||Y==="item/started")&&F.item){let L=F.item.type;if(L==="command_execution"){let R=F.item.command,J=R?Hi(R):void 0,W=Zi(o),ee=new Map;for(let ie of W?.changedFiles??[])ee.set(ie,vo(o,ie));typeof F.item.id=="string"&&u.set(F.item.id,{...R?{rawCommand:R}:{},...J?{command:J}:{},...W?{beforeWorktree:W}:{},beforeSnapshots:ee});let H=J?`Bash: ${J.split(`
25
- `)[0].slice(0,80)}`:"Bash";p.push(H),a?.({type:"tool_use",jobId:n,tool:"Bash",...J?{content:J}:{}},n)}else if(L==="file_change"){let R=F.item.filename||F.item.path;R&&!w.has(R)&&w.set(R,vo(o,R)),p.push(R?`Edit ${R.split("/").pop()}`:"Edit");let J=R?On(o,R)??R:void 0;a?.({type:"tool_use",jobId:n,tool:"Edit",...J?{file:J}:{}},n)}else if(L==="file_read"){let R=F.item.filename||F.item.path;p.push(R?`Read ${R.split("/").pop()}`:"Read");let J=R?On(o,R)??R:void 0;a?.({type:"tool_use",jobId:n,tool:"Read",...J?{file:J}:{}},n)}else if(L==="web_search")p.push("WebSearch"),a?.({type:"tool_use",jobId:n,tool:"WebSearch"},n);else if(L==="mcp_tool_call"){let R=Ki(F.item);p.push(R.telemetryLabel),a?.({type:"tool_use",jobId:n,tool:R.tool,...R.content?{content:R.content}:{}},n)}}if((Y==="item.completed"||Y==="item/completed")&&F.item){if(F.item.type==="agent_message"){let L=F.item.text;if(typeof L=="string"&&L){let R=$n(h,L);R&&a?.({type:"delta",jobId:n,text:R},n)}}else if(F.item.type==="reasoning"){let L=F.item.text;typeof L=="string"&&L&&a?.({type:"thinking",jobId:n,text:L},n)}else if(F.item.type==="file_change"&&Array.isArray(F.item.changes))for(let L of F.item.changes){let R=L.path||L.filename,J=L.kind==="add"?"Write":"Edit";if(R){p.push(`${J} ${R.split("/").pop()}`);let W=On(o,R)??R;a?.({type:"tool_use",jobId:n,tool:J,file:W},n);let ee=L,H=typeof ee.kind=="string"?ee.kind:void 0,ie=xc(H),P=w.get(R),j=vo(o,R);y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:R,...P?{before:P}:{},...j?{after:j}:{},...Xi(ee)?{patch:Xi(ee)}:{},...H?{rawKind:H}:{}}),w.set(R,j)}}else if(F.item.type==="command_execution"){let L=typeof F.item.id=="string"?F.item.id:void 0,R=L?u.get(L):void 0,J=typeof F.item.command=="string"?F.item.command:R?.rawCommand,W=J?Hi(J):R?.command,ee=Zi(o);if(Tc(R?.beforeWorktree,ee)){let H=[...new Set([...R?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],ie=typeof F.item.aggregated_output=="string"?wr(F.item.aggregated_output,vc):void 0,P=typeof F.item.exit_code=="number"?F.item.exit_code:F.item.exit_code===null?null:void 0,j=typeof F.item.status=="string"?F.item.status:void 0;y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...J?{rawCommand:J}:{},...W?{command:W}:{},...P!==void 0?{exitCode:P}:{},...j?{status:j}:{},...ie?{output:ie.text}:{},...ie?.truncated?{outputTruncated:!0}:{},...R?.beforeWorktree?{beforeWorktree:R.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...H.length>0?{touchedFiles:Pc(o,H,R?.beforeSnapshots??new Map)}:{}})}L&&u.delete(L)}}Y==="turn.failed"&&(x=!0,m=F.error?.message||F.message||"Turn failed")}catch{}});let $=[];v.stderr?.on("data",E=>{$.push(E.toString())}),v.on("close",E=>{f.close(),h.length===0&&M.size>0&&console.warn(`[Codex:${n}] No text captured. Event types seen: ${[...M].join(", ")}`),E!==0&&E!==null&&(x=!0,m=$.join("")||`Codex process exited with code ${E}`),k({sessionId:b,text:h.join(""),success:!x,error:x?m:void 0,editEvents:y.length>0?y:void 0,toolsUsed:p.length>0?p:void 0})}),v.on("error",E=>{x=!0,m=E.message,k({sessionId:b,text:h.join(""),success:!1,error:m,editEvents:y.length>0?y:void 0,toolsUsed:p.length>0?p:void 0})})});return{process:v,result:g}}import{spawn as Rc}from"child_process";import{createInterface as Ac}from"readline";function rs(n,e){let t=n.trim()||"Copilot CLI failed",o=t.toLowerCase();return o.includes("no authentication information")||o.includes("not authenticated")||o.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`."}:o.includes("model")&&(o.includes("not available")||o.includes("not found")||o.includes("disabled")||o.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:o.includes("mcp")&&(o.includes("blocked")||o.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."}:o.includes("permission")||o.includes("denied")||o.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function is(n,e){let{prompt:t,projectRoot:o,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:d="copilot"}=e,c=["--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&&c.push(`--resume=${r}`),i&&c.push("--model",i),c.push("-p",t);let I=Rc(d,c,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),v=new Promise(g=>{let k,b=[],h=[],p=!1,y="",w=!1,u=setTimeout(()=>{w=!0,I.kill("SIGTERM"),setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},5e3)},s),x=Ac({input:I.stdout}),m=new Set,f=[];x.on("line",$=>{if($.trim())try{let E=JSON.parse($),F=Nn(E);m.add(F),f.length<5&&jc(F)&&f.push($.slice(0,800));let Y=Dn(E,["sessionId","session_id","id"],["session","conversation","thread"]);Y&&!k&&(k=Y);let L=Mc(E,b.length===0);L&&(b.push(L),a?.({type:"delta",jobId:n,text:L},n));let R=Ec(E);R&&a?.({type:"thinking",jobId:n,text:R},n);let J=_c(E);J&&(h.push(J.label),a?.({type:"tool_use",jobId:n,tool:J.tool,...J.file?{file:J.file}:{},...J.content?{content:J.content}:{}},n));let W=Cc(E);W&&(p=!0,y=W)}catch{}});let M=[];I.stderr?.on("data",$=>{M.push($.toString())}),I.on("close",$=>{clearTimeout(u),x.close(),b.length===0&&m.size>0&&(console.warn(`[Copilot:${n}] No text captured. Event types seen: ${[...m].join(", ")}`),f.length>0&&console.warn(`[Copilot:${n}] Sample text-bearing candidates: ${f.join(`
26
- `)}`)),w?(p=!0,y=`Timed out after ${Math.round(s/6e4)} minutes`):$!==0&&$!==null&&(p=!0,y=M.join("").trim()||y||`Copilot process exited with code ${$}`);let E=p?rs(y,i):null;g({sessionId:k,text:b.join(""),success:!p,error:E?.message,errorCode:E?.code,recoverableError:E?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),I.on("error",$=>{clearTimeout(u);let E=rs($.message,i);g({sessionId:k,text:b.join(""),success:!1,error:E.message,errorCode:E.code,recoverableError:E.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:I,result:v}}function Nn(n){if(typeof n.type=="string")return n.type;let e=n.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof n.event=="string"?n.event:"unknown"}function Mc(n,e=!1){let t=Nn(n).toLowerCase(),o=n.update,r=o?.content;if(o?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return et(n.delta)??et(n.content)??et(n.message);if(t==="assistant.message"&&e)return et(n.message)??et(n.content)??et(n);if(t==="result"&&e)return et(n.result)??et(n.output)??et(n.message)??et(n);let i=n.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof n.text=="string"&&vr(n))return n.text;if(typeof n.message=="string"&&vr(n))return n.message;if(typeof n.delta=="string"&&vr(n))return n.delta}function et(n){if(typeof n=="string")return n;if(!n)return;if(Array.isArray(n)){let t=n.map(et).filter(o=>!!o);return t.length>0?t.join(""):void 0}if(typeof n!="object")return;let e=n;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let o=et(e[t]);if(o)return o}}function jc(n){let e=n.toLowerCase();return e.includes("assistant.message")||e==="result"}function Ec(n){if(typeof n.thinking=="string")return n.thinking;if(typeof n.reasoning=="string")return n.reasoning;let e=n.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function _c(n){let e=Dn(n,["tool","toolName","tool_name","name"]),t=Dn(n,["command","cmd"]),o=Dn(n,["file","path","filename","filePath"]),r=Nn(n);if(t||r.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
27
- `)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:o?`${e} ${o.split("/").pop()}`:e,...o?{file:o}:{}};if(o&&(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} ${o.split("/").pop()}`,file:o}}}function Cc(n){if(typeof n.error=="string")return n.error;if(n.error&&typeof n.error=="object"){let e=n.error;if(typeof e.message=="string")return e.message}if(typeof n.message=="string"&&Nn(n).toLowerCase().includes("error"))return n.message}function Dn(n,e,t=[]){for(let o of e){let r=n[o];if(typeof r=="string")return r}for(let[o,r]of Object.entries(n)){if(!r||typeof r!="object"||t.length>0&&!t.some(s=>o.toLowerCase().includes(s)))continue;let i=Dn(r,e);if(i)return i}}function vr(n){let e=Nn(n).toLowerCase();return(typeof n.role=="string"?n.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readFile as $c,readdir as Oc}from"fs/promises";import{join as br}from"path";var xo=class{constructor(e){let t=br(e,".popmelt");this.decisionsDir=br(t,"decisions")}async listDecisionIds(){try{return(await Oc(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await $c(br(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(o=>this.loadDecision(o)))).filter(o=>o!==null)}};import{createHash as Dc,randomUUID as Nc}from"crypto";import{mkdir as xr,readFile as ss,readdir as as,rename as So,stat as ds,unlink as To,writeFile as ko}from"fs/promises";import{extname as Bc,join as ot}from"path";var Jc=10080*60*1e3,qc=600*1e3,Lc=3600*1e3;function Fc(n){return n==="image/svg+xml"?".svg":n==="text/plain"?".txt":".bin"}function Uc(n,e){return[...n.trim()].map(o=>o==="/"||o==="\\"||o.charCodeAt(0)<32?"-":o).join("").slice(0,120)||e}var Po=class{constructor(e){this.draftsDir=ot(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=ot(e,".popmelt","artifacts","thread-media")}async stage(e){let t=Nc(),o=Fc(e.mimeType),r=`${t}${o}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:Uc(e.name,`pasted-context${o}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await xr(this.draftsDir,{recursive:!0});let a=ot(this.draftsDir,r),d=ot(this.draftsDir,`${t}.json`),c=`${a}.part`,I=`${d}.part`;return await ko(c,e.data),await So(c,a),await ko(I,JSON.stringify(s,null,2)),await So(I,d),s}async claim(e){await Promise.all(e.map(async t=>{let o=await this.readManifest(t);o&&(delete o.releasedAt,o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async release(e){await Promise.all(e.map(async t=>{let o=await this.readManifest(t);o&&(o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async promote(e){let t={};for(let o of e){let r=await this.readManifest(o.id);if(!r)throw new Error(`Draft attachment ${o.id} is unavailable or expired.`);if(r.annotationId!==o.annotationId)throw new Error(`Draft attachment ${o.id} does not belong to annotation ${o.annotationId}.`);let i=ot(this.draftsDir,r.contentFile),s=await ss(i),a=Dc("sha256").update(s).digest("hex"),d=ot(this.mediaDir,`${a}${Bc(r.contentFile)||".bin"}`);await xr(this.mediaDir,{recursive:!0});try{await ds(d)}catch{let c=`${d}.part`;await ko(c,s),await So(c,d)}(t[o.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:d}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return t}async sweep(e=Date.now()){let t;try{t=await as(this.draftsDir)}catch{return}await Promise.all(t.map(async o=>{let r=ot(this.draftsDir,o);if(o.endsWith(".part")){let a=await ds(r).catch(()=>null);a&&e-a.mtimeMs>Lc&&await To(r).catch(()=>{});return}if(!o.endsWith(".json"))return;let i=await this.readManifest(o.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>qc:e-i.lastSeenAt>Jc)||await Promise.all([To(r).catch(()=>{}),To(ot(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await as(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>To(ot(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await ss(ot(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await xr(this.draftsDir,{recursive:!0});let t=ot(this.draftsDir,`${e.id}.json`),o=`${t}.part`;await ko(o,JSON.stringify(e,null,2)),await So(o,t)}};import{randomUUID as Wc}from"crypto";var dn="<orientation>",zc="</orientation>",Gc="<\\/orientation>",Nt=[zc,Gc];function cn(n,e){let t=e;for(;t<n.length&&/\s/.test(n[t]);)t++;if(t>=n.length)return{status:"incomplete",start:t};if(n[t]!=="{")return{status:"invalid",start:t};let o=0,r=!1,i=!1;for(let s=t;s<n.length;s++){let a=n[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"')r=!0;else if(a==="{")o++;else if(a==="}"){if(o--,o===0)return{status:"complete",start:t,end:s+1};if(o<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function Sr(n,e){if(!e)return;let t=n[n.length-1];t?.kind==="text"?t.text+=e:n.push({kind:"text",text:e})}function cs(n,e){let t=null;for(let o of Nt){let r=n.indexOf(o,e);r>=0&&(!t||r<t.index)&&(t={index:r,tag:o})}return t}function ls(n){let e=[],t=0;for(;t<n.length;){let o=n.indexOf(dn,t),r=cs(n,t);if(r&&(o<0||r.index<o)){Sr(e,n.slice(t,r.index)),t=r.index+r.tag.length;continue}if(o<0){Sr(e,n.slice(t));break}Sr(e,n.slice(t,o));let i=o+dn.length,s=cn(n,i);if(s.status!=="complete"){let c=cs(n,i);if(c){t=c.index+c.tag.length;continue}t=i;continue}e.push({kind:"orientation",json:n.slice(s.start,s.end)}),t=s.end;let a=t;for(;a<n.length&&/\s/.test(n[a]);)a++;let d=Nt.find(c=>n.startsWith(c,a));d&&(t=a+d.length)}return e}var ln="<imprint-use>",Ro="</imprint-use>";function Vc(n){let e=Math.min(n.length,ln.length-1);for(let t=e;t>0;t--)if(ln.startsWith(n.slice(-t)))return t;return 0}function ps(n,e,t,o,r=Date.now()){if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let c=e?.explanations.find(I=>I.id===d);return c?[{id:c.id,kind:c.kind,statement:c.statement,state:c.state,scope:c.scope}]:[]});return a.length===0?null:{id:Wc(),jobId:t,sequence:o,timestamp:r,explanations:a}}var Ao=class{constructor(e,t){this.jobId=e;this.context=t;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let t=e.explanations.filter(o=>!this.explanationIds.has(o.id));if(t.length===0)return null;for(let o of t)this.explanationIds.add(o.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",o=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let c=this.buffer.slice(d);if(Ro.startsWith(c)&&c.length<Ro.length||(c.startsWith(Ro)&&(this.buffer=this.buffer.slice(d+Ro.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(ln);if(r<0){let d=Vc(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,r);let i=r+ln.length,s=cn(this.buffer,i);if(s.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(i);continue}let a=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=ps(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let c=this.takeNewExplanations(d);c&&o.push(c)}catch{}}return{visibleText:t,usages:o}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],o="",r=0;for(;r<e.length;){let i=e.indexOf(ln,r);if(i<0){o+=e.slice(r);break}o+=e.slice(r,i);let s=i+ln.length,a=cn(e,s);if(a.status!=="complete"){r=s;continue}try{let I=ps(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(I){let v=this.takeNewExplanations(I);v&&t.push(v)}}catch{}let c=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+c}return{visibleText:o.trim(),usages:t}}};function Pt(n,e=240){if(!n)return;let t=n.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function pn(n){return n?[Pt(n.selector,400),Pt(n.context,200),Pt(n.reactComponent,120),Pt(n.textContent)].filter(e=>!!e):[]}function Tr(n){return[...new Set(n.filter(e=>!!e))]}function us(n,e){return Tr([...e,...n.annotations.flatMap(t=>[Pt(t.pathname,200),Pt(t.linkedSelector,400),...t.elements.flatMap(pn)]),...n.styleModifications.flatMap(t=>pn(t.element)),...(n.textModifications??[]).flatMap(t=>pn(t.element)),...(n.domModifications??[]).flatMap(t=>[...pn(t.element),...pn(t.sourceElement)])])}function ms(n,e){let t=[...n].reverse().find(o=>o.annotationSnapshot)?.annotationSnapshot;return Tr(t?[...e,...t.annotations.flatMap(o=>[Pt(o.pathname,200),Pt(o.linkedSelector,400),...o.elements.flatMap(pn)])]:e)}var Mo=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 t of this.leases.values())(e===null||t.expiresAt<e)&&(e=t.expiresAt);return e}acquire(e,t,o=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:t,createdAt:r?.createdAt??o,expiresAt:o+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,t=Date.now()){let o=this.leases.get(e);return o?(o.expiresAt=t+this.ttlMs,o):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[o,r]of this.leases)r.expiresAt>e||(this.leases.delete(o),t.push(o));return{expiredIds:t,becameEmpty:t.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{randomUUID as fs}from"crypto";import{mkdir as kr,readFile as Pr,writeFile as jo}from"fs/promises";import{dirname as Rr,join as un}from"path";var rt="[ProjectionWorker]",Kc={version:1,runs:[]},Hc={version:1,updatedAt:0,proposals:[]},Qc=12;function Xc(n){return Array.isArray(n)?n.map(e=>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 hs(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let o=t;if(typeof o.id!="string"||typeof o.text!="string"){console.warn(`${rt} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:o.id,scope:typeof o.scope=="string"?o.scope:"general",text:o.text,sources:Array.isArray(o.sources)?o.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${rt} Rule count ${e.length} exceeds cap of 30`),e}function Yc(n,e,t){return{decisionCount:n.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Zc(n,e,t){let o=new Set(e),r=new Set,i=Array.isArray(n.rules)?n.rules:[];for(let b of i){if(!b||typeof b!="object")continue;let h=b.sources;if(Array.isArray(h))for(let p of h)typeof p=="string"&&o.has(p)&&r.add(p)}let s=n.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},a=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},d=Array.isArray(t?.rules)?t.rules:[],c=i.filter(b=>{if(!b||typeof b!="object")return!1;let h=b.id,p=typeof h=="string"?d.find(y=>y&&typeof y=="object"&&y.id===h):void 0;return JSON.stringify(p)!==JSON.stringify(b)}).length,I=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},v=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},g=Object.keys(s).filter(b=>JSON.stringify(s[b])!==JSON.stringify(I[b])).length,k=Object.keys(a).filter(b=>JSON.stringify(a[b])!==JSON.stringify(v[b])).length;return{ruleCount:c,tokenSectionCount:g,componentCount:k,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(b=>!r.has(b))}}function el(n){if(n!==void 0)return JSON.parse(JSON.stringify(n))}function tl(n,e,t){let o=n[e];if(o&&typeof o=="object")return o;let r=typeof t=="number"?[]:{};return n[String(e)]=r,r}function Eo(n,e,t){let o=n;for(let i=0;i<e.length-1;i++)o=tl(o,e[i],e[i+1]);let r=e[e.length-1];o[String(r)]=el(t)}function gs(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=t[String(e[r])];if(!i||typeof i!="object")return;t=i}let o=e[e.length-1];Array.isArray(t)&&typeof o=="number"?t.splice(o,1):delete t[String(o)]}function nl(n,e){if(!n)return{exists:!1};let t=n;for(let o of e){if(!t||typeof t!="object"||!(String(o)in t))return{exists:!1};t=t[String(o)]}return{exists:!0,value:t}}function ol(n,e){return Array.isArray(e)?n===void 0?e.length>0:!Array.isArray(n)||e.length<=n.length?!1:n.every((t,o)=>JSON.stringify(t)===JSON.stringify(e[o])):!1}function ys(n,e){if(n.authorityStatus!=="accepted"||!n.changes?.length)return null;for(let t of n.changes){let o=nl(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?ol(o.exists?o.value:void 0,t.value):!o.exists))return null}return n.changes}var _o=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let o=un(e,".popmelt");this.runsPath=un(o,"projection-runs.json"),this.legacyRunsPath=un(o,"materialization-runs.json"),this.proposalsPath=un(o,"projection-queue.json"),this.legacyProposalsPath=un(o,"model-proposals.json"),this.modelPath=un(o,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Pr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Xc(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let o of e){let r=o.key.split(".");o.value===null?gs(t,r):Eo(t,r,o.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Qc),t=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!t.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let o=await this.selectUnprojectedPatternDecisions(),r=o.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(b=>b.id);console.log(`${rt} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=al(r,s),d=Yc(r,o.totalCandidateDecisionCount,a);t=fs().slice(0,8);let c={id:t,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(c);let I=!0,v,g,k;try{let b=`projection-${Date.now()}`,{provider:h,result:p}=this.spawnModelAgent(b,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});c={...c,provider:h},await this.persistRun(c);let y=await p;if(!y.success)I=!1,v=y.error,console.error(`${rt} ${h} spawn error:`,v);else{let w=sl(y.text,i);if(w){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let f of w)Eo(u,f.path,f.value);Array.isArray(u.rules)&&(u.rules=hs(u.rules));let x=Zc(u,i,s);if(w){let f=[...new Set(w.flatMap(M=>M.decisionIds))];x.coveredDecisionIds=f,x.uncoveredDecisionIds=i.filter(M=>!f.includes(M))}g=x;let m=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:g,changes:w});k=m.id,console.log(`${rt} Created model proposal ${m.id} for ${i.length} decision(s)`)}else I=!1,v="No valid bounded <model-changes> block found in response",console.error(`${rt} ${v}`)}}catch(b){I=!1,v=b instanceof Error?b.message:String(b),console.error(`${rt} Error:`,v)}return await this.persistRun({...c,status:I?"proposed":"failed",completedAt:Date.now(),error:v,outputStats:g,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:I,error:v}),{processedIds:i,success:I,error:v,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=hs(e.rules)),await jo(this.modelPath,JSON.stringify(e,null,2)),console.log(`${rt} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await kr(Rr(this.runsPath),{recursive:!0}),await jo(this.runsPath,JSON.stringify(t,null,2)),t):{...Kc,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 t=e??{...Hc,proposals:[]},o=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(o);for(let s of r.changes??[])Eo(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(o=>o.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>r.updatedAt-o.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>o.createdAt-r.createdAt||o.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,t,o,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 t)!Array.isArray(d.path)||d.path.length===0||(d.remove?gs(s,d.path):Eo(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:o})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:fs().slice(0,8),status:"pending",title:rl(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"}.`:il(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()},o=await this.loadModelProposals();return o.proposals=[t,...o.proposals.filter(r=>r.id!==t.id)].slice(0,100),o.updatedAt=Date.now(),await this.persistModelProposals(o),t}async updateModelProposal(e,t){let o=await this.loadModelProposals(),r=null;return o.proposals=o.proposals.map(i=>i.id!==e?i:(r={...i,...t,updatedAt:Date.now()},r)),r?(o.updatedAt=Date.now(),await this.persistModelProposals(o),r):null}async persistModelProposals(e){try{await kr(Rr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:o,...r})=>r)};await jo(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${rt} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),o=t.runs.findIndex(r=>r.id===e.id);o>=0?t.runs[o]=e:t.runs.push(e),await kr(Rr(this.runsPath),{recursive:!0}),await jo(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${rt} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Pr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Pr(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,o,r){let i=o.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...bo(e,{prompt:t,projectRoot:this.projectRoot,model:o.model??this.options.model,configOverrides:oo(o.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${rt} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...yo(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?o.model??this.options.model:void 0,reasoningEffort:o.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function rl(n){let t=(Array.isArray(n.rules)?n.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let o=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?Object.keys(n.components):[];return o.length>0?`Model update for ${o[0]}`:"Model update"}function il(n,e){let t=Array.isArray(n.rules)?n.rules.length:0,o=n.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?Object.keys(n.tokens).length:0,r=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?Object.keys(n.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${o} token section${o===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function sl(n,e){let t=n.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let o=JSON.parse(t[1]);if(!Array.isArray(o)||o.length===0||o.length>40)return null;let r=new Set(e),i=o.flatMap((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(v=>typeof v=="string"||typeof v=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let c=d.path[0];if(c!=="tokens"&&c!=="components"&&c!=="rules")return[];if(c==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let I=Array.isArray(d.decisionIds)?d.decisionIds.filter(v=>typeof v=="string"&&r.has(v)):[];return I.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:I,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===o.length?i:null}catch{return null}}function al(n,e){let t=n.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
19
+ `)}function Cn(n){if(!n)return;if(n.decision==="recognize")return[n.explanationId];let e=[...new Set([...n.usedExplanationIds??[],...n.appliedExplanationIds??[]])];return e.length?e:void 0}function ac(n,e){let t=e.flatMap((o,r)=>{let i=n[r];return i?[{packetId:`ambient:${o}`,proposalId:o,claim:i.claim.trim(),proposedKind:i.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:o}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var go=class{constructor(e){this.options=e;this.turns=new Map;let t={storeId:e.storeId,projectRoot:e.projectRoot,projectId:e.projectId};this.knowledgeViewReader=e.knowledgeViewReader??new fo(t,{memory:e.memoryService,imprint:e.imprintService})}knowledgeDiagnostics(){return this.knowledgeViewReader.diagnostics()}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([Fi(e)])}async prepare(e){if(e.executionOwner===gr)return{status:"managed_by_bridge",protocolVersion:Dt};let t=this.key(e.sessionId,e.turnId),o=this.turns.get(t);if(o){let g=Gi(o.sessionId,o.threadId,o.jobId,o.memoryContext,o.imprintContext,o.prompt);return{status:"already_prepared",protocolVersion:Dt,threadId:o.threadId,jobId:o.jobId,...g}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${oc()}`,[Fi(e.sessionId)]));let i=sc(e.sessionId,e.turnId),s=r.messages.find(g=>g.jobId===i&&g.role==="human"),a=Ui(e.prompt),d=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),c=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(g=>g.role==="assistant"&&g.imprintSummary?.grounding&&!g.imprintSummary.resolvedAction?[g.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(r.id,{role:"human",timestamp:Date.now(),jobId:i,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...d?{memoryReview:d}:{},...c?{imprintContext:c}:{}});let y={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:d,imprintContext:c,events:[]};this.turns.set(t,y);let w=Gi(e.sessionId,r.id,i,d,c,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Dt,threadId:r.id,jobId:i,...w}}async recordEvent(e){if(e.executionOwner===gr)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(o=>o.toolUseId===e.toolUseId)?{status:"recorded"}:(t.events.push({toolName:e.toolName,toolUseId:e.toolUseId,toolInput:e.toolInput,toolResponse:e.toolResponse,occurredAt:Date.now()}),{status:"recorded"}):{status:"turn_not_prepared"}}async assess(e){let t=[...this.turns.values()].find(d=>d.threadId===e.threadId&&d.jobId===e.jobId);if(!t)return{status:"turn_not_found"};if((await this.options.threadStore.getThread(t.threadId))?.messages.some(d=>d.role==="assistant"&&d.jobId===t.jobId))return{status:"turn_completed"};if(t.assessmentEvaluation?.receipt.status==="committed")return t.assessmentEvaluation.receipt;t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)};let r=t.assessment.semanticCandidates.length?{status:"queued_for_turn_completion",count:t.assessment.semanticCandidates.length}:void 0,i=zi(t.events,this.options.projectRoot).length>0,s=Ht(t.assessment.assessmentText,{context:t.imprintContext,requestText:t.prompt,applicationOccurred:i}),a;if(s.error)a={receipt:{status:"rejected",reason:s.error},imprintAssessment:{state:s.error.includes("missing")?"missing":"invalid",reason:s.error}};else if(s.draft?.decision==="none")this.options.imprintService.recordNoop(s.draft.reason),a={receipt:{status:"assessed",outcome:"no_change",reason:s.draft.reason,...r?{semanticCandidates:r}:{}},imprintAssessment:{state:"none",reason:s.draft.reason},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else if(s.draft?.decision==="recognize")a={receipt:{status:"assessed",outcome:"recognized",...r?{semanticCandidates:r}:{}},imprintAssessment:{state:"none",reason:"recognized existing grounded understanding"},imprintUsedExplanationIds:Cn(s.draft)};else if(s.draft?.decision==="mutate"||s.draft?.decision==="apply")try{let d=await this.options.imprintService.capture(s.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:t.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:i,storeId:this.options.storeId,context:t.imprintContext});if(d)await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId,qualifiedExplanationMemoryIds:Object.fromEntries((t.imprintContext?.explanations??[]).flatMap(c=>c.storeId&&c.memoryId?[[`${c.storeId}:${c.id}`,c.memoryId]]:[]))}).catch(()=>{}),a={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...r?{semanticCandidates:r}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else{let c="imprint mutation failed admission or produced no durable change";a={receipt:{status:"rejected",reason:c},imprintAssessment:{state:"invalid",reason:c},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}}catch(d){let c=d instanceof Error?d.message:"imprint mutation failed";a={receipt:{status:"rejected",reason:c},imprintAssessment:{state:"invalid",reason:c},imprintUsedExplanationIds:Cn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}else{let d="imprint assessment is missing";a={receipt:{status:"rejected",reason:d},imprintAssessment:{state:"missing",reason:d}}}return t.assessmentEvaluation=a,(a.imprintAssessment.state==="missing"||a.imprintAssessment.state==="invalid")&&this.options.imprintService.recordAssessmentFailure(a.imprintAssessment.state),a.receipt}async complete(e){if(e.executionOwner===gr)return{status:"managed_by_bridge",protocolVersion:Dt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Dt};let r=(await this.options.threadStore.getThread(t.threadId))?.messages.find(p=>p.role==="assistant"&&p.jobId===t.jobId);if(r)return e.lastAssistantMessage&&e.lastAssistantMessage!==r.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Dt,threadId:t.threadId,jobId:t.jobId};let i=zi(t.events,this.options.projectRoot),s=i.length>0,a=t.assessmentEvaluation?.imprintSummary,d=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},c=t.assessmentEvaluation?.imprintUsedExplanationIds,y=t.assessmentEvaluation?.imprintAppliedExplanationIds,w=s?"completed":"no_change",g=_n({changedFiles:i}),S={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(p=>p.toolName),turn:{phase:"complete",orientation:[],result:g},result:g,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:c,imprintAppliedExplanationIds:y};await this.options.threadStore.appendMessage(t.threadId,S);let b=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:w,execution:{provider:"codex",model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:i,resolutions:s?[{status:"resolved",summary:`Changed ${i.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(p=>p.id),imprintAssessment:d}),h=ac(t.assessment?.semanticCandidates??[],b.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:Dt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Ui(e.query),o=await this.knowledgeViewReader.memoryContext(e.knowledgeView,t,e.subjectHints??[]),r=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints});return{memoryContext:o,imprintContext:r,formattedContext:[Sn(o),Wi(r,e.query)].filter(Boolean).join(`
20
+ `)}}};import{spawn as dc}from"child_process";import{createInterface as cc}from"readline";function $n(n,e){let t=e.trim();if(!t)return"";let o=n.length>0?`
21
+
22
+ ${t}`:t;return n.push(o),o}var lc=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"]),Vi=1e5;function pc(n){let e=n.input?.file_path||n.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!lc.has(t))return;let o;if(n.name==="Write"&&typeof n.input?.content=="string"?o=n.input.content:n.name==="Edit"&&typeof n.input?.new_string=="string"&&(o=n.input.new_string),!!o)return o.length>Vi?o.slice(0,Vi)+`
23
+ \u2026[truncated]`:o}function yo(n,e){let{prompt:t,projectRoot:o,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:d,model:c,reasoningEffort:y,timeoutMs:w=3e5,onEvent:g}=e,S=[];d?S.push("--resume",d,"-p",t):S.push("-p",t),S.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),c&&S.push("--model",c),y&&S.push("--effort",y);for(let p of s)S.push("--allowedTools",p);let b=dc(a,S,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(p=>{let I,v=[],u=[],x=[],m=!1,f="",M,$,E=!1,F=setTimeout(()=>{E=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},w),Y=cc({input:b.stdout}),L=new Set;Y.on("line",J=>{if(J.trim())try{let W=JSON.parse(J);W.session_id&&!I&&(I=W.session_id);let ee=W.type??(W.event?.type?`event.${W.event.type}`:"unknown");if(L.add(ee),W.type==="result"&&W.result&&v.length===0){let H=typeof W.result=="string"?W.result:"";if(H){let ie=$n(v,H);ie&&g?.({type:"delta",jobId:n,text:ie},n)}}if(W.type==="assistant"&&Array.isArray(W.message?.content)){typeof W.error=="string"&&(M=W.error);for(let H of W.message.content){if(H.type==="text"&&H.text){let ie=$n(v,H.text);ie&&g?.({type:"delta",jobId:n,text:ie},n)}if(H.type==="tool_use"&&H.name){let ie=H.input?.file_path||H.input?.path||void 0,P=pc(H);if(g?.({type:"tool_use",jobId:n,tool:H.name,...ie?{file:ie}:{},...P?{content:P}:{}},n),H.name==="Edit"&&H.input?.file_path){let j={tool:"Edit",file_path:H.input.file_path,old_string:H.input.old_string,new_string:H.input.new_string,replace_all:H.input.replace_all};u.push(j),x.push({sequence:x.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:j.file_path,oldString:typeof j.old_string=="string"?j.old_string:void 0,newString:typeof j.new_string=="string"?j.new_string:void 0,replaceAll:typeof j.replace_all=="boolean"?j.replace_all:void 0})}else H.name==="Write"&&H.input?.file_path&&(u.push({tool:"Write",file_path:H.input.file_path,content:H.input.content}),x.push({sequence:x.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:H.input.file_path,content:typeof H.input.content=="string"?H.input.content:void 0}))}H.type==="thinking"&&H.thinking&&g?.({type:"thinking",jobId:n,text:H.thinking},n)}}W.type==="result"&&W.is_error===!0&&(m=!0,typeof W.error=="string"&&(M=W.error),typeof W.result=="string"&&($=W.result)),W.type==="user"&&W.tool_use_result?.file?.filePath&&g?.({type:"tool_use",jobId:n,tool:"Read",file:W.tool_use_result.file.filePath},n)}catch{}});let R=[];b.stderr?.on("data",J=>{R.push(J.toString())}),b.on("close",J=>{if(clearTimeout(F),Y.close(),v.length===0&&L.size>0&&console.warn(`[Claude:${n}] No text captured. Event types seen: ${[...L].join(", ")}`),E)m=!0,f=`Timed out after ${Math.round(w/6e4)} minutes`;else if(J!==0&&J!==null){m=!0;let ee=R.join("").trim(),H=v.join("").trim(),ie=v.length===0&&L.size>0?` (no text captured, event types: ${[...L].join(", ")})`:"";f=ee||$||H||`Claude process exited with code ${J}${ie}`}m&&!f&&$&&(f=$);let W=uc(f,M);p({sessionId:I,text:v.join(""),success:!m,error:m?W.message:void 0,errorCode:m?W.code:void 0,recoverableError:m?W.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:x.length>0?x:void 0})}),b.on("error",J=>{clearTimeout(F),m=!0,f=J.message,p({sessionId:I,text:v.join(""),success:!1,error:f,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:x.length>0?x:void 0})})});return{process:b,result:h}}function uc(n,e){let t=n.trim()||"Claude CLI failed",o=`${e??""} ${t}`.toLowerCase();return o.includes("authentication_failed")||o.includes("not logged in")||o.includes("please run /login")||o.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:o.includes("model")&&(o.includes("not found")||o.includes("unknown")||o.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as fc,spawnSync as ts}from"child_process";import{readFileSync as hc,statSync as gc}from"fs";import{basename as yc,extname as Ic,isAbsolute as wc,relative as ns,resolve as vc}from"path";import{createInterface as bc}from"readline";function wo(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Io(n,e){for(let t of n)if(t)for(let o of e){let r=t[o];if(typeof r=="string"&&r.trim())return r.trim()}}function Ki(n){let e=wo(n);if(e)return e;if(typeof n=="string")try{return wo(JSON.parse(n))}catch{return}}function yr(n){return n.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function mc(n,e,t,o){return n!=="node_repl"||e!=="js"?!1:o&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(o)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function Hi(n){let e=wo(n)??{},t=wo(e.invocation),o=Ki(e.arguments)??Ki(t?.arguments),r=Io([e,t],["server","server_name"]),i=Io([e,t],["tool","tool_name","name"]),s=Io([o,e,t],["title","display_name","description"]),a=Io([o],["code","script"]),d=mc(r,i,s,a)?"Browser":r?yr(r):i?yr(i):"MCP",c=i&&yr(i),y=s??c,w=y&&y!==d?`${d}: ${y}`:d;return{tool:d,...y?{content:y}:{},telemetryLabel:w}}function Qi(n){let e=n.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):n}var Xi=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"]),Ir=2e5,xc=1e5,os=2e5;function rs(n){let e=yc(n).toLowerCase(),t=Ic(n).toLowerCase();return Xi.has(t)||Xi.has(e)}function On(n,e){let t=wc(e)?e:vc(n,e),o=ns(n,t);return o===""||o.startsWith("..")?null:t}function vo(n,e){if(!rs(e))return;let t=On(n,e);if(t)try{let o=gc(t);return o.isFile()?o.size>Ir?{exists:!0,truncated:!0}:{exists:!0,content:hc(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Sc(n,e){for(let t of e){let o=n[t];if(typeof o=="string")return o}}function Tc(n){let e=n?.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 Yi(n){return Sc(n,["patch","diff","unifiedDiff","unified_diff"])}function wr(n,e){return n.length<=e?{text:n}:{text:n.slice(0,e),truncated:!0}}function Zi(n,e){let t=ts("git",e,{cwd:n,encoding:"utf8",timeout:5e3,maxBuffer:os+65536});return t.status!==0?null:t.stdout??""}function kc(n){let e=new Set;for(let t of n.split(`
24
+ `)){if(t.length<4)continue;let o=t.slice(3).trim();if(!o)continue;o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));let r=o.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function es(n){let e=Zi(n,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Zi(n,["diff","--no-ext-diff","HEAD","--"])??"",o=wr(t,os);return{status:e,changedFiles:kc(e),...o.text?{diff:o.text}:{},...o.truncated?{diffTruncated:!0}:{}}}function Pc(n,e){return!n||!e?!1:n.status!==e.status||(n.diff??"")!==(e.diff??"")}function Rc(n,e){if(!rs(e))return;let t=On(n,e);if(!t)return;let o=ns(n,t);if(o===""||o.startsWith(".."))return;let r=ts("git",["show",`HEAD:${o}`],{cwd:n,encoding:"utf8",timeout:5e3,maxBuffer:Ir+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=wr(i,Ir);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Ac(n,e,t){return e.map(o=>{let r=t.has(o)?t.get(o):Rc(n,o),i=vo(n,o);return{filePath:o,...r?{before:r}:{},...i?{after:i}:{}}})}function bo(n,e){let{prompt:t,projectRoot:o,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:d="workspace-write",configOverrides:c=[]}=e,y=[];if(i){y.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let S of c)y.push("-c",S);s&&y.push("-m",s),y.push(i),y.push(t),r&&y.push("--image",r)}else{y.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let S of c)y.push("-c",S);s&&y.push("-m",s),y.push(t),r&&y.push("--image",r)}let w=fc("codex",y,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:n}}),g=new Promise(S=>{let b,h=[],p=[],I=[],v=new Map,u=new Map,x=!1,m="",f=bc({input:w.stdout}),M=new Set;f.on("line",E=>{if(E.trim())try{let F=JSON.parse(E),Y=F.type??"unknown";if(M.add(Y),Y==="thread.started"&&F.thread_id&&!b&&(b=F.thread_id),(Y==="item.agentMessage.delta"||Y==="item/agentMessage/delta")&&F.delta?.text&&(h.push(F.delta.text),a?.({type:"delta",jobId:n,text:F.delta.text},n)),(Y==="item.reasoning.delta"||Y==="item/reasoning/delta")&&F.delta?.text&&a?.({type:"thinking",jobId:n,text:F.delta.text},n),(Y==="item.started"||Y==="item/started")&&F.item){let L=F.item.type;if(L==="command_execution"){let R=F.item.command,J=R?Qi(R):void 0,W=es(o),ee=new Map;for(let ie of W?.changedFiles??[])ee.set(ie,vo(o,ie));typeof F.item.id=="string"&&u.set(F.item.id,{...R?{rawCommand:R}:{},...J?{command:J}:{},...W?{beforeWorktree:W}:{},beforeSnapshots:ee});let H=J?`Bash: ${J.split(`
25
+ `)[0].slice(0,80)}`:"Bash";p.push(H),a?.({type:"tool_use",jobId:n,tool:"Bash",...J?{content:J}:{}},n)}else if(L==="file_change"){let R=F.item.filename||F.item.path;R&&!v.has(R)&&v.set(R,vo(o,R)),p.push(R?`Edit ${R.split("/").pop()}`:"Edit");let J=R?On(o,R)??R:void 0;a?.({type:"tool_use",jobId:n,tool:"Edit",...J?{file:J}:{}},n)}else if(L==="file_read"){let R=F.item.filename||F.item.path;p.push(R?`Read ${R.split("/").pop()}`:"Read");let J=R?On(o,R)??R:void 0;a?.({type:"tool_use",jobId:n,tool:"Read",...J?{file:J}:{}},n)}else if(L==="web_search")p.push("WebSearch"),a?.({type:"tool_use",jobId:n,tool:"WebSearch"},n);else if(L==="mcp_tool_call"){let R=Hi(F.item);p.push(R.telemetryLabel),a?.({type:"tool_use",jobId:n,tool:R.tool,...R.content?{content:R.content}:{}},n)}}if((Y==="item.completed"||Y==="item/completed")&&F.item){if(F.item.type==="agent_message"){let L=F.item.text;if(typeof L=="string"&&L){let R=$n(h,L);R&&a?.({type:"delta",jobId:n,text:R},n)}}else if(F.item.type==="reasoning"){let L=F.item.text;typeof L=="string"&&L&&a?.({type:"thinking",jobId:n,text:L},n)}else if(F.item.type==="file_change"&&Array.isArray(F.item.changes))for(let L of F.item.changes){let R=L.path||L.filename,J=L.kind==="add"?"Write":"Edit";if(R){p.push(`${J} ${R.split("/").pop()}`);let W=On(o,R)??R;a?.({type:"tool_use",jobId:n,tool:J,file:W},n);let ee=L,H=typeof ee.kind=="string"?ee.kind:void 0,ie=Tc(H),P=v.get(R),j=vo(o,R);I.push({sequence:I.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ie,filePath:R,...P?{before:P}:{},...j?{after:j}:{},...Yi(ee)?{patch:Yi(ee)}:{},...H?{rawKind:H}:{}}),v.set(R,j)}}else if(F.item.type==="command_execution"){let L=typeof F.item.id=="string"?F.item.id:void 0,R=L?u.get(L):void 0,J=typeof F.item.command=="string"?F.item.command:R?.rawCommand,W=J?Qi(J):R?.command,ee=es(o);if(Pc(R?.beforeWorktree,ee)){let H=[...new Set([...R?.beforeWorktree?.changedFiles??[],...ee?.changedFiles??[]])],ie=typeof F.item.aggregated_output=="string"?wr(F.item.aggregated_output,xc):void 0,P=typeof F.item.exit_code=="number"?F.item.exit_code:F.item.exit_code===null?null:void 0,j=typeof F.item.status=="string"?F.item.status:void 0;I.push({sequence:I.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...J?{rawCommand:J}:{},...W?{command:W}:{},...P!==void 0?{exitCode:P}:{},...j?{status:j}:{},...ie?{output:ie.text}:{},...ie?.truncated?{outputTruncated:!0}:{},...R?.beforeWorktree?{beforeWorktree:R.beforeWorktree}:{},...ee?{afterWorktree:ee}:{},...H.length>0?{touchedFiles:Ac(o,H,R?.beforeSnapshots??new Map)}:{}})}L&&u.delete(L)}}Y==="turn.failed"&&(x=!0,m=F.error?.message||F.message||"Turn failed")}catch{}});let $=[];w.stderr?.on("data",E=>{$.push(E.toString())}),w.on("close",E=>{f.close(),h.length===0&&M.size>0&&console.warn(`[Codex:${n}] No text captured. Event types seen: ${[...M].join(", ")}`),E!==0&&E!==null&&(x=!0,m=$.join("")||`Codex process exited with code ${E}`),S({sessionId:b,text:h.join(""),success:!x,error:x?m:void 0,editEvents:I.length>0?I:void 0,toolsUsed:p.length>0?p:void 0})}),w.on("error",E=>{x=!0,m=E.message,S({sessionId:b,text:h.join(""),success:!1,error:m,editEvents:I.length>0?I:void 0,toolsUsed:p.length>0?p:void 0})})});return{process:w,result:g}}import{spawn as Mc}from"child_process";import{createInterface as jc}from"readline";function is(n,e){let t=n.trim()||"Copilot CLI failed",o=t.toLowerCase();return o.includes("no authentication information")||o.includes("not authenticated")||o.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`."}:o.includes("model")&&(o.includes("not available")||o.includes("not found")||o.includes("disabled")||o.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:o.includes("mcp")&&(o.includes("blocked")||o.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."}:o.includes("permission")||o.includes("denied")||o.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function ss(n,e){let{prompt:t,projectRoot:o,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:d="copilot"}=e,c=["--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&&c.push(`--resume=${r}`),i&&c.push("--model",i),c.push("-p",t);let y=Mc(d,c,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),w=new Promise(g=>{let S,b=[],h=[],p=!1,I="",v=!1,u=setTimeout(()=>{v=!0,y.kill("SIGTERM"),setTimeout(()=>{try{y.kill("SIGKILL")}catch{}},5e3)},s),x=jc({input:y.stdout}),m=new Set,f=[];x.on("line",$=>{if($.trim())try{let E=JSON.parse($),F=Nn(E);m.add(F),f.length<5&&_c(F)&&f.push($.slice(0,800));let Y=Dn(E,["sessionId","session_id","id"],["session","conversation","thread"]);Y&&!S&&(S=Y);let L=Ec(E,b.length===0);L&&(b.push(L),a?.({type:"delta",jobId:n,text:L},n));let R=Cc(E);R&&a?.({type:"thinking",jobId:n,text:R},n);let J=$c(E);J&&(h.push(J.label),a?.({type:"tool_use",jobId:n,tool:J.tool,...J.file?{file:J.file}:{},...J.content?{content:J.content}:{}},n));let W=Oc(E);W&&(p=!0,I=W)}catch{}});let M=[];y.stderr?.on("data",$=>{M.push($.toString())}),y.on("close",$=>{clearTimeout(u),x.close(),b.length===0&&m.size>0&&(console.warn(`[Copilot:${n}] No text captured. Event types seen: ${[...m].join(", ")}`),f.length>0&&console.warn(`[Copilot:${n}] Sample text-bearing candidates: ${f.join(`
26
+ `)}`)),v?(p=!0,I=`Timed out after ${Math.round(s/6e4)} minutes`):$!==0&&$!==null&&(p=!0,I=M.join("").trim()||I||`Copilot process exited with code ${$}`);let E=p?is(I,i):null;g({sessionId:S,text:b.join(""),success:!p,error:E?.message,errorCode:E?.code,recoverableError:E?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),y.on("error",$=>{clearTimeout(u);let E=is($.message,i);g({sessionId:S,text:b.join(""),success:!1,error:E.message,errorCode:E.code,recoverableError:E.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:y,result:w}}function Nn(n){if(typeof n.type=="string")return n.type;let e=n.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof n.event=="string"?n.event:"unknown"}function Ec(n,e=!1){let t=Nn(n).toLowerCase(),o=n.update,r=o?.content;if(o?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return et(n.delta)??et(n.content)??et(n.message);if(t==="assistant.message"&&e)return et(n.message)??et(n.content)??et(n);if(t==="result"&&e)return et(n.result)??et(n.output)??et(n.message)??et(n);let i=n.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof n.text=="string"&&vr(n))return n.text;if(typeof n.message=="string"&&vr(n))return n.message;if(typeof n.delta=="string"&&vr(n))return n.delta}function et(n){if(typeof n=="string")return n;if(!n)return;if(Array.isArray(n)){let t=n.map(et).filter(o=>!!o);return t.length>0?t.join(""):void 0}if(typeof n!="object")return;let e=n;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let o=et(e[t]);if(o)return o}}function _c(n){let e=n.toLowerCase();return e.includes("assistant.message")||e==="result"}function Cc(n){if(typeof n.thinking=="string")return n.thinking;if(typeof n.reasoning=="string")return n.reasoning;let e=n.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function $c(n){let e=Dn(n,["tool","toolName","tool_name","name"]),t=Dn(n,["command","cmd"]),o=Dn(n,["file","path","filename","filePath"]),r=Nn(n);if(t||r.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
27
+ `)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:o?`${e} ${o.split("/").pop()}`:e,...o?{file:o}:{}};if(o&&(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} ${o.split("/").pop()}`,file:o}}}function Oc(n){if(typeof n.error=="string")return n.error;if(n.error&&typeof n.error=="object"){let e=n.error;if(typeof e.message=="string")return e.message}if(typeof n.message=="string"&&Nn(n).toLowerCase().includes("error"))return n.message}function Dn(n,e,t=[]){for(let o of e){let r=n[o];if(typeof r=="string")return r}for(let[o,r]of Object.entries(n)){if(!r||typeof r!="object"||t.length>0&&!t.some(s=>o.toLowerCase().includes(s)))continue;let i=Dn(r,e);if(i)return i}}function vr(n){let e=Nn(n).toLowerCase();return(typeof n.role=="string"?n.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readFile as Dc,readdir as Nc}from"fs/promises";import{join as br}from"path";var xo=class{constructor(e){let t=br(e,".popmelt");this.decisionsDir=br(t,"decisions")}async listDecisionIds(){try{return(await Nc(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await Dc(br(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(o=>this.loadDecision(o)))).filter(o=>o!==null)}};import{createHash as Bc,randomUUID as Jc}from"crypto";import{mkdir as xr,readFile as as,readdir as ds,rename as So,stat as cs,unlink as To,writeFile as ko}from"fs/promises";import{extname as qc,join as ot}from"path";var Lc=10080*60*1e3,Fc=600*1e3,Uc=3600*1e3;function zc(n){return n==="image/svg+xml"?".svg":n==="text/plain"?".txt":".bin"}function Gc(n,e){return[...n.trim()].map(o=>o==="/"||o==="\\"||o.charCodeAt(0)<32?"-":o).join("").slice(0,120)||e}var Po=class{constructor(e){this.draftsDir=ot(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=ot(e,".popmelt","artifacts","thread-media")}async stage(e){let t=Jc(),o=zc(e.mimeType),r=`${t}${o}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:Gc(e.name,`pasted-context${o}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await xr(this.draftsDir,{recursive:!0});let a=ot(this.draftsDir,r),d=ot(this.draftsDir,`${t}.json`),c=`${a}.part`,y=`${d}.part`;return await ko(c,e.data),await So(c,a),await ko(y,JSON.stringify(s,null,2)),await So(y,d),s}async claim(e){await Promise.all(e.map(async t=>{let o=await this.readManifest(t);o&&(delete o.releasedAt,o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async release(e){await Promise.all(e.map(async t=>{let o=await this.readManifest(t);o&&(o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async promote(e){let t={};for(let o of e){let r=await this.readManifest(o.id);if(!r)throw new Error(`Draft attachment ${o.id} is unavailable or expired.`);if(r.annotationId!==o.annotationId)throw new Error(`Draft attachment ${o.id} does not belong to annotation ${o.annotationId}.`);let i=ot(this.draftsDir,r.contentFile),s=await as(i),a=Bc("sha256").update(s).digest("hex"),d=ot(this.mediaDir,`${a}${qc(r.contentFile)||".bin"}`);await xr(this.mediaDir,{recursive:!0});try{await cs(d)}catch{let c=`${d}.part`;await ko(c,s),await So(c,d)}(t[o.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:d}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return t}async sweep(e=Date.now()){let t;try{t=await ds(this.draftsDir)}catch{return}await Promise.all(t.map(async o=>{let r=ot(this.draftsDir,o);if(o.endsWith(".part")){let a=await cs(r).catch(()=>null);a&&e-a.mtimeMs>Uc&&await To(r).catch(()=>{});return}if(!o.endsWith(".json"))return;let i=await this.readManifest(o.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>Fc:e-i.lastSeenAt>Lc)||await Promise.all([To(r).catch(()=>{}),To(ot(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await ds(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>To(ot(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await as(ot(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await xr(this.draftsDir,{recursive:!0});let t=ot(this.draftsDir,`${e.id}.json`),o=`${t}.part`;await ko(o,JSON.stringify(e,null,2)),await So(o,t)}};import{randomUUID as Kc}from"crypto";var dn="<orientation>",Wc="</orientation>",Vc="<\\/orientation>",Nt=[Wc,Vc];function cn(n,e){let t=e;for(;t<n.length&&/\s/.test(n[t]);)t++;if(t>=n.length)return{status:"incomplete",start:t};if(n[t]!=="{")return{status:"invalid",start:t};let o=0,r=!1,i=!1;for(let s=t;s<n.length;s++){let a=n[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"')r=!0;else if(a==="{")o++;else if(a==="}"){if(o--,o===0)return{status:"complete",start:t,end:s+1};if(o<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function Sr(n,e){if(!e)return;let t=n[n.length-1];t?.kind==="text"?t.text+=e:n.push({kind:"text",text:e})}function ls(n,e){let t=null;for(let o of Nt){let r=n.indexOf(o,e);r>=0&&(!t||r<t.index)&&(t={index:r,tag:o})}return t}function ps(n){let e=[],t=0;for(;t<n.length;){let o=n.indexOf(dn,t),r=ls(n,t);if(r&&(o<0||r.index<o)){Sr(e,n.slice(t,r.index)),t=r.index+r.tag.length;continue}if(o<0){Sr(e,n.slice(t));break}Sr(e,n.slice(t,o));let i=o+dn.length,s=cn(n,i);if(s.status!=="complete"){let c=ls(n,i);if(c){t=c.index+c.tag.length;continue}t=i;continue}e.push({kind:"orientation",json:n.slice(s.start,s.end)}),t=s.end;let a=t;for(;a<n.length&&/\s/.test(n[a]);)a++;let d=Nt.find(c=>n.startsWith(c,a));d&&(t=a+d.length)}return e}var ln="<imprint-use>",Ro="</imprint-use>";function Hc(n){let e=Math.min(n.length,ln.length-1);for(let t=e;t>0;t--)if(ln.startsWith(n.slice(-t)))return t;return 0}function us(n,e,t,o,r=Date.now()){if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let c=e?.explanations.find(y=>y.id===d);return c?[{id:c.id,kind:c.kind,statement:c.statement,state:c.state,scope:c.scope}]:[]});return a.length===0?null:{id:Kc(),jobId:t,sequence:o,timestamp:r,explanations:a}}var Ao=class{constructor(e,t){this.jobId=e;this.context=t;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let t=e.explanations.filter(o=>!this.explanationIds.has(o.id));if(t.length===0)return null;for(let o of t)this.explanationIds.add(o.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",o=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let c=this.buffer.slice(d);if(Ro.startsWith(c)&&c.length<Ro.length||(c.startsWith(Ro)&&(this.buffer=this.buffer.slice(d+Ro.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(ln);if(r<0){let d=Hc(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,r);let i=r+ln.length,s=cn(this.buffer,i);if(s.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(i);continue}let a=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=us(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let c=this.takeNewExplanations(d);c&&o.push(c)}catch{}}return{visibleText:t,usages:o}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],o="",r=0;for(;r<e.length;){let i=e.indexOf(ln,r);if(i<0){o+=e.slice(r);break}o+=e.slice(r,i);let s=i+ln.length,a=cn(e,s);if(a.status!=="complete"){r=s;continue}try{let y=us(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(y){let w=this.takeNewExplanations(y);w&&t.push(w)}}catch{}let c=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+c}return{visibleText:o.trim(),usages:t}}};function Pt(n,e=240){if(!n)return;let t=n.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function pn(n){return n?[Pt(n.selector,400),Pt(n.context,200),Pt(n.reactComponent,120),Pt(n.textContent)].filter(e=>!!e):[]}function Tr(n){return[...new Set(n.filter(e=>!!e))]}function ms(n,e){return Tr([...e,...n.annotations.flatMap(t=>[Pt(t.pathname,200),Pt(t.linkedSelector,400),...t.elements.flatMap(pn)]),...n.styleModifications.flatMap(t=>pn(t.element)),...(n.textModifications??[]).flatMap(t=>pn(t.element)),...(n.domModifications??[]).flatMap(t=>[...pn(t.element),...pn(t.sourceElement)])])}function fs(n,e){let t=[...n].reverse().find(o=>o.annotationSnapshot)?.annotationSnapshot;return Tr(t?[...e,...t.annotations.flatMap(o=>[Pt(o.pathname,200),Pt(o.linkedSelector,400),...o.elements.flatMap(pn)])]:e)}var Mo=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 t of this.leases.values())(e===null||t.expiresAt<e)&&(e=t.expiresAt);return e}acquire(e,t,o=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:t,createdAt:r?.createdAt??o,expiresAt:o+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,t=Date.now()){let o=this.leases.get(e);return o?(o.expiresAt=t+this.ttlMs,o):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[o,r]of this.leases)r.expiresAt>e||(this.leases.delete(o),t.push(o));return{expiredIds:t,becameEmpty:t.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};import{randomUUID as hs}from"crypto";import{mkdir as kr,readFile as Pr,writeFile as jo}from"fs/promises";import{dirname as Rr,join as un}from"path";var rt="[ProjectionWorker]",Qc={version:1,runs:[]},Xc={version:1,updatedAt:0,proposals:[]},Yc=12;function Zc(n){return Array.isArray(n)?n.map(e=>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 gs(n){let e=[];for(let t of n){if(!t||typeof t!="object")continue;let o=t;if(typeof o.id!="string"||typeof o.text!="string"){console.warn(`${rt} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:o.id,scope:typeof o.scope=="string"?o.scope:"general",text:o.text,sources:Array.isArray(o.sources)?o.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${rt} Rule count ${e.length} exceeds cap of 30`),e}function el(n,e,t){return{decisionCount:n.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function tl(n,e,t){let o=new Set(e),r=new Set,i=Array.isArray(n.rules)?n.rules:[];for(let b of i){if(!b||typeof b!="object")continue;let h=b.sources;if(Array.isArray(h))for(let p of h)typeof p=="string"&&o.has(p)&&r.add(p)}let s=n.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},a=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},d=Array.isArray(t?.rules)?t.rules:[],c=i.filter(b=>{if(!b||typeof b!="object")return!1;let h=b.id,p=typeof h=="string"?d.find(I=>I&&typeof I=="object"&&I.id===h):void 0;return JSON.stringify(p)!==JSON.stringify(b)}).length,y=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},w=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},g=Object.keys(s).filter(b=>JSON.stringify(s[b])!==JSON.stringify(y[b])).length,S=Object.keys(a).filter(b=>JSON.stringify(a[b])!==JSON.stringify(w[b])).length;return{ruleCount:c,tokenSectionCount:g,componentCount:S,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(b=>!r.has(b))}}function nl(n){if(n!==void 0)return JSON.parse(JSON.stringify(n))}function ol(n,e,t){let o=n[e];if(o&&typeof o=="object")return o;let r=typeof t=="number"?[]:{};return n[String(e)]=r,r}function Eo(n,e,t){let o=n;for(let i=0;i<e.length-1;i++)o=ol(o,e[i],e[i+1]);let r=e[e.length-1];o[String(r)]=nl(t)}function ys(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=t[String(e[r])];if(!i||typeof i!="object")return;t=i}let o=e[e.length-1];Array.isArray(t)&&typeof o=="number"?t.splice(o,1):delete t[String(o)]}function rl(n,e){if(!n)return{exists:!1};let t=n;for(let o of e){if(!t||typeof t!="object"||!(String(o)in t))return{exists:!1};t=t[String(o)]}return{exists:!0,value:t}}function il(n,e){return Array.isArray(e)?n===void 0?e.length>0:!Array.isArray(n)||e.length<=n.length?!1:n.every((t,o)=>JSON.stringify(t)===JSON.stringify(e[o])):!1}function Is(n,e){if(n.authorityStatus!=="accepted"||!n.changes?.length)return null;for(let t of n.changes){let o=rl(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?il(o.exists?o.value:void 0,t.value):!o.exists))return null}return n.changes}var _o=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let o=un(e,".popmelt");this.runsPath=un(o,"projection-runs.json"),this.legacyRunsPath=un(o,"materialization-runs.json"),this.proposalsPath=un(o,"projection-queue.json"),this.legacyProposalsPath=un(o,"model-proposals.json"),this.modelPath=un(o,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Pr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Zc(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let o of e){let r=o.key.split(".");o.value===null?ys(t,r):Eo(t,r,o.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Yc),t=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!t.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let o=await this.selectUnprojectedPatternDecisions(),r=o.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(b=>b.id);console.log(`${rt} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=cl(r,s),d=el(r,o.totalCandidateDecisionCount,a);t=hs().slice(0,8);let c={id:t,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(c);let y=!0,w,g,S;try{let b=`projection-${Date.now()}`,{provider:h,result:p}=this.spawnModelAgent(b,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});c={...c,provider:h},await this.persistRun(c);let I=await p;if(!I.success)y=!1,w=I.error,console.error(`${rt} ${h} spawn error:`,w);else{let v=dl(I.text,i);if(v){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let f of v)Eo(u,f.path,f.value);Array.isArray(u.rules)&&(u.rules=gs(u.rules));let x=tl(u,i,s);if(v){let f=[...new Set(v.flatMap(M=>M.decisionIds))];x.coveredDecisionIds=f,x.uncoveredDecisionIds=i.filter(M=>!f.includes(M))}g=x;let m=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:g,changes:v});S=m.id,console.log(`${rt} Created model proposal ${m.id} for ${i.length} decision(s)`)}else y=!1,w="No valid bounded <model-changes> block found in response",console.error(`${rt} ${w}`)}}catch(b){y=!1,w=b instanceof Error?b.message:String(b),console.error(`${rt} Error:`,w)}return await this.persistRun({...c,status:y?"proposed":"failed",completedAt:Date.now(),error:w,outputStats:g,proposalId:S}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:y,error:w}),{processedIds:i,success:y,error:w,runId:t,proposalId:S}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=gs(e.rules)),await jo(this.modelPath,JSON.stringify(e,null,2)),console.log(`${rt} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await kr(Rr(this.runsPath),{recursive:!0}),await jo(this.runsPath,JSON.stringify(t,null,2)),t):{...Qc,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 t=e??{...Xc,proposals:[]},o=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(o);for(let s of r.changes??[])Eo(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(o=>o.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>r.updatedAt-o.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>o.createdAt-r.createdAt||o.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,t,o,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 t)!Array.isArray(d.path)||d.path.length===0||(d.remove?ys(s,d.path):Eo(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:o})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:hs().slice(0,8),status:"pending",title:sl(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"}.`:al(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()},o=await this.loadModelProposals();return o.proposals=[t,...o.proposals.filter(r=>r.id!==t.id)].slice(0,100),o.updatedAt=Date.now(),await this.persistModelProposals(o),t}async updateModelProposal(e,t){let o=await this.loadModelProposals(),r=null;return o.proposals=o.proposals.map(i=>i.id!==e?i:(r={...i,...t,updatedAt:Date.now()},r)),r?(o.updatedAt=Date.now(),await this.persistModelProposals(o),r):null}async persistModelProposals(e){try{await kr(Rr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:o,...r})=>r)};await jo(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${rt} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),o=t.runs.findIndex(r=>r.id===e.id);o>=0?t.runs[o]=e:t.runs.push(e),await kr(Rr(this.runsPath),{recursive:!0}),await jo(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${rt} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Pr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Pr(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,o,r){let i=o.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...bo(e,{prompt:t,projectRoot:this.projectRoot,model:o.model??this.options.model,configOverrides:oo(o.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${rt} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...yo(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?o.model??this.options.model:void 0,reasoningEffort:o.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function sl(n){let t=(Array.isArray(n.rules)?n.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let o=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?Object.keys(n.components):[];return o.length>0?`Model update for ${o[0]}`:"Model update"}function al(n,e){let t=Array.isArray(n.rules)?n.rules.length:0,o=n.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?Object.keys(n.tokens).length:0,r=n.components&&typeof n.components=="object"&&!Array.isArray(n.components)?Object.keys(n.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${o} token section${o===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function dl(n,e){let t=n.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let o=JSON.parse(t[1]);if(!Array.isArray(o)||o.length===0||o.length>40)return null;let r=new Set(e),i=o.flatMap((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(w=>typeof w=="string"||typeof w=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let c=d.path[0];if(c!=="tokens"&&c!=="components"&&c!=="rules")return[];if(c==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let y=Array.isArray(d.decisionIds)?d.decisionIds.filter(w=>typeof w=="string"&&r.has(w)):[];return y.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:y,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===o.length?i:null}catch{return null}}function cl(n,e){let t=n.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
28
28
  Kind: ${i.kind}
29
29
  Claim: ${i.claim}
30
30
  ${i.rationale?`Rationale: ${i.rationale}`:""}
@@ -103,17 +103,17 @@ Example:
103
103
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
104
104
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
105
105
  - bindings: Tailwind class names (without responsive prefixes) that use this token
106
- Include property and bindings when the decision context has class-level evidence.`}var Co=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,t,o){for(let r of this.listeners)r(e,t,o)}cancelJob(e){let t=this.queue.findIndex(r=>r.id===e);if(t>=0){let[r]=this.queue.splice(t,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 o=this.activeJob;return!o||o.id!==e?null:(o.status="cancelled",o.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},o.id),this.processNext(),o)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}cancelAll(){let e=[...this.activeJob?[this.activeJob]:[],...this.queue];this.activeJob=null,this.queue=[];for(let t of e)t.status="cancelled",t.error="Cancelled by user",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);return e}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(t=>{e.status!=="cancelled"&&(e.status="error",e.error=t instanceof Error?t.message:String(t),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 dl}from"child_process";import{readFile as vs}from"fs/promises";import{homedir as Mr}from"os";import{join as lt}from"path";var jr=/popmelt/i;function Bt(){return{found:!1,name:null,scope:null,disabled:!1}}function mn(n,e,t=!1){return{found:!0,name:n,scope:e,disabled:t}}function Bn(n){for(let e of Object.keys(n))if(jr.test(e))return e;return null}async function $o(n){try{let e=await vs(n,"utf-8");return JSON.parse(e)}catch{return null}}async function Er(n){let e=Mr(),t=await $o(lt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Bn(r.mcpServers);if(i)return mn(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[n];if(s&&typeof s=="object"){let a=s;if(a.mcpServers&&typeof a.mcpServers=="object"){let d=Bn(a.mcpServers);if(d){let c=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(I=>jr.test(I));return mn(d,"project",c)}}}}}let o=await $o(lt(n,".mcp.json"));if(o&&typeof o=="object"){let r=o;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Bn(r.mcpServers);if(s){let a=await Is(n,s);return mn(s,"mcp.json",a)}}let i=Bn(r);if(i&&i!=="mcpServers"){let s=await Is(n,i);return mn(i,"mcp.json",s)}}return Bt()}async function Is(n,e){let t=lt(n,".claude","settings.local.json"),o=await $o(t);if(o&&typeof o=="object"){let r=o;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var cl=/^\[mcp_servers\.([^\]]+)\]/;function ll(n){let e=n.split(`
107
- `),t=[],o=null;for(let r of e){let i=r.match(cl);i?(o&&t.push({name:o.name,body:o.bodyLines.join(`
106
+ Include property and bindings when the decision context has class-level evidence.`}var Co=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,t,o){for(let r of this.listeners)r(e,t,o)}cancelJob(e){let t=this.queue.findIndex(r=>r.id===e);if(t>=0){let[r]=this.queue.splice(t,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 o=this.activeJob;return!o||o.id!==e?null:(o.status="cancelled",o.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},o.id),this.processNext(),o)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}cancelAll(){let e=[...this.activeJob?[this.activeJob]:[],...this.queue];this.activeJob=null,this.queue=[];for(let t of e)t.status="cancelled",t.error="Cancelled by user",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);return e}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(t=>{e.status!=="cancelled"&&(e.status="error",e.error=t instanceof Error?t.message:String(t),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 ll}from"child_process";import{readFile as bs}from"fs/promises";import{homedir as Mr}from"os";import{join as lt}from"path";var jr=/popmelt/i;function Bt(){return{found:!1,name:null,scope:null,disabled:!1}}function mn(n,e,t=!1){return{found:!0,name:n,scope:e,disabled:t}}function Bn(n){for(let e of Object.keys(n))if(jr.test(e))return e;return null}async function $o(n){try{let e=await bs(n,"utf-8");return JSON.parse(e)}catch{return null}}async function Er(n){let e=Mr(),t=await $o(lt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Bn(r.mcpServers);if(i)return mn(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[n];if(s&&typeof s=="object"){let a=s;if(a.mcpServers&&typeof a.mcpServers=="object"){let d=Bn(a.mcpServers);if(d){let c=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(y=>jr.test(y));return mn(d,"project",c)}}}}}let o=await $o(lt(n,".mcp.json"));if(o&&typeof o=="object"){let r=o;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Bn(r.mcpServers);if(s){let a=await ws(n,s);return mn(s,"mcp.json",a)}}let i=Bn(r);if(i&&i!=="mcpServers"){let s=await ws(n,i);return mn(i,"mcp.json",s)}}return Bt()}async function ws(n,e){let t=lt(n,".claude","settings.local.json"),o=await $o(t);if(o&&typeof o=="object"){let r=o;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var pl=/^\[mcp_servers\.([^\]]+)\]/;function ul(n){let e=n.split(`
107
+ `),t=[],o=null;for(let r of e){let i=r.match(pl);i?(o&&t.push({name:o.name,body:o.bodyLines.join(`
108
108
  `)}),o={name:i[1],bodyLines:[]}):r.startsWith("[")?o&&(t.push({name:o.name,body:o.bodyLines.join(`
109
109
  `)}),o=null):o&&o.bodyLines.push(r)}return o&&t.push({name:o.name,body:o.bodyLines.join(`
110
- `)}),t}function pl(n){return/enabled\s*=\s*false/i.test(n)}async function _r(n){let e=process.env.CODEX_HOME||lt(Mr(),".codex"),t=await ws(lt(e,"config.toml"),"user");if(t.found)return t;let o=await ws(lt(n,".codex","config.toml"),"project");return o.found?o:Bt()}async function Cr(n,e="copilot"){let t=await ul(e);if(t.found)return t;let o=process.env.COPILOT_HOME||lt(Mr(),".copilot"),r=await Ar(lt(o,"mcp-config.json"),"user");if(r.found)return r;let i=await Ar(lt(n,".mcp.json"),"mcp.json");if(i.found)return i;let s=await Ar(lt(n,".github","mcp.json"),"mcp.json");return s.found?s:Bt()}async function ul(n){try{let e=await new Promise((t,o)=>{dl(n,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}t(i)})});return bs(JSON.parse(e),"user")}catch{return Bt()}}async function Ar(n,e){let t=await $o(n);return bs(t,e)}function bs(n,e){if(!n||typeof n!="object")return Bt();let t=n,o=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=Bn(o);return r?mn(r,e):Bt()}async function ws(n,e){try{let t=await vs(n,"utf-8"),o=ll(t);for(let r of o)if(jr.test(r.name)){let i=pl(r.body);return mn(r.name,e,i)}}catch{}return Bt()}import{execFile as xs}from"child_process";import{mkdir as ml,readFile as Ss,writeFile as Ts}from"fs/promises";import{homedir as ks}from"os";import{dirname as fl,join as $r}from"path";var Or="https://mcp.popmelt.com/mcp";async function Ps(n=Or){let e=$r(ks(),".claude.json"),t;try{let r=await Ss(e,"utf-8");t=JSON.parse(r)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let o=t.mcpServers;for(let r of Object.keys(o))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return o.popmelt={type:"http",url:n},await Ts(e,JSON.stringify(t,null,2)+`
111
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Rs(n=Or){let e=process.env.CODEX_HOME||$r(ks(),".codex"),t=$r(e,"config.toml"),o;try{o=await Ss(t,"utf-8")}catch{o=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(o))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ml(fl(t),{recursive:!0});let r=`
110
+ `)}),t}function ml(n){return/enabled\s*=\s*false/i.test(n)}async function _r(n){let e=process.env.CODEX_HOME||lt(Mr(),".codex"),t=await vs(lt(e,"config.toml"),"user");if(t.found)return t;let o=await vs(lt(n,".codex","config.toml"),"project");return o.found?o:Bt()}async function Cr(n,e="copilot"){let t=await fl(e);if(t.found)return t;let o=process.env.COPILOT_HOME||lt(Mr(),".copilot"),r=await Ar(lt(o,"mcp-config.json"),"user");if(r.found)return r;let i=await Ar(lt(n,".mcp.json"),"mcp.json");if(i.found)return i;let s=await Ar(lt(n,".github","mcp.json"),"mcp.json");return s.found?s:Bt()}async function fl(n){try{let e=await new Promise((t,o)=>{ll(n,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}t(i)})});return xs(JSON.parse(e),"user")}catch{return Bt()}}async function Ar(n,e){let t=await $o(n);return xs(t,e)}function xs(n,e){if(!n||typeof n!="object")return Bt();let t=n,o=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=Bn(o);return r?mn(r,e):Bt()}async function vs(n,e){try{let t=await bs(n,"utf-8"),o=ul(t);for(let r of o)if(jr.test(r.name)){let i=ml(r.body);return mn(r.name,e,i)}}catch{}return Bt()}import{execFile as Ss}from"child_process";import{mkdir as hl,readFile as Ts,writeFile as ks}from"fs/promises";import{homedir as Ps}from"os";import{dirname as gl,join as $r}from"path";var Or="https://mcp.popmelt.com/mcp";async function Rs(n=Or){let e=$r(Ps(),".claude.json"),t;try{let r=await Ts(e,"utf-8");t=JSON.parse(r)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let o=t.mcpServers;for(let r of Object.keys(o))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return o.popmelt={type:"http",url:n},await ks(e,JSON.stringify(t,null,2)+`
111
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function As(n=Or){let e=process.env.CODEX_HOME||$r(Ps(),".codex"),t=$r(e,"config.toml"),o;try{o=await Ts(t,"utf-8")}catch{o=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(o))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await hl(gl(t),{recursive:!0});let r=`
112
112
  [mcp_servers.popmelt]
113
113
  url = "${n}"
114
- `;return await Ts(t,o+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function As(n=Or,e="copilot"){let t=await hl(e);if(gl(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((o,r)=>{xs(e,["mcp","add","--transport","http","--json","popmelt",n],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}o()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(o){return{installed:!1,provider:"copilot",scope:null,reason:o instanceof Error?o.message:"install_failed"}}}async function hl(n){try{let e=await new Promise((t,o)=>{xs(n,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}t(i)})});return JSON.parse(e)}catch{return null}}function gl(n){if(!n||typeof n!="object")return!1;let e=n,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(o=>/popmelt/i.test(o))}function Ms(n){let e=n.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]);if(typeof t.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(t.action)))return null;let o=t.action,r=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((o==="accept"||o==="edit_and_accept")&&!r||o==="edit_and_accept"&&typeof t.claim!="string"||o!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(a=>typeof a=="string"&&i.has(a)):void 0;return{proposalId:t.proposalId,action:o,kind:r,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function js(n){let e=n.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),o=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!o||typeof t.proposalId!="string"||!t.proposalId||typeof t.title!="string"||!t.title.trim()||typeof t.claim!="string"||!t.claim.trim()||typeof t.rationale!="string"||!t.rationale.trim()?null:{proposalId:t.proposalId,kind:o,title:t.title.trim(),claim:t.claim.trim(),rationale:t.rationale.trim(),scope:typeof t.scope=="string"&&t.scope.trim()?t.scope.trim():void 0}}catch{return null}}async function Dr(n){let t=(n.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let o=t[1]||t[2],r=await yl(n),i=Buffer.from(`--${o}`),s=Buffer.from(`--${o}--`),a,d,c,I,v,g,k,b,h,p,y,w,u,x,m,f,M,$=[],E=[],F=0,Y=[];for(;F<r.length;){let L=r.indexOf(i,F);if(L===-1)break;let R=L+i.length;if(r.slice(L,L+s.length).equals(s))break;let J=R;r[J]===13&&r[J+1]===10&&(J+=2);let W=r.indexOf(`\r
114
+ `;return await ks(t,o+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ms(n=Or,e="copilot"){let t=await yl(e);if(Il(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((o,r)=>{Ss(e,["mcp","add","--transport","http","--json","popmelt",n],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}o()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(o){return{installed:!1,provider:"copilot",scope:null,reason:o instanceof Error?o.message:"install_failed"}}}async function yl(n){try{let e=await new Promise((t,o)=>{Ss(n,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}t(i)})});return JSON.parse(e)}catch{return null}}function Il(n){if(!n||typeof n!="object")return!1;let e=n,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(o=>/popmelt/i.test(o))}function js(n){let e=n.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]);if(typeof t.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(t.action)))return null;let o=t.action,r=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((o==="accept"||o==="edit_and_accept")&&!r||o==="edit_and_accept"&&typeof t.claim!="string"||o!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(a=>typeof a=="string"&&i.has(a)):void 0;return{proposalId:t.proposalId,action:o,kind:r,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function Es(n){let e=n.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),o=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!o||typeof t.proposalId!="string"||!t.proposalId||typeof t.title!="string"||!t.title.trim()||typeof t.claim!="string"||!t.claim.trim()||typeof t.rationale!="string"||!t.rationale.trim()?null:{proposalId:t.proposalId,kind:o,title:t.title.trim(),claim:t.claim.trim(),rationale:t.rationale.trim(),scope:typeof t.scope=="string"&&t.scope.trim()?t.scope.trim():void 0}}catch{return null}}async function Dr(n){let t=(n.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let o=t[1]||t[2],r=await wl(n),i=Buffer.from(`--${o}`),s=Buffer.from(`--${o}--`),a,d,c,y,w,g,S,b,h,p,I,v,u,x,m,f,M,$=[],E=[],F=0,Y=[];for(;F<r.length;){let L=r.indexOf(i,F);if(L===-1)break;let R=L+i.length;if(r.slice(L,L+s.length).equals(s))break;let J=R;r[J]===13&&r[J+1]===10&&(J+=2);let W=r.indexOf(`\r
115
115
  \r
116
- `,J);if(W===-1)break;let ee=r.slice(J,W).toString("utf-8"),H=W+4,ie=r.indexOf(i,H),P=ie!==-1?ie-2:r.length;Y.push({headers:ee,body:r.slice(H,P)}),F=ie!==-1?ie:r.length}for(let L of Y){let R=L.headers.match(/name="([^"]+)"/);if(!R)continue;let J=R[1];if(J==="screenshot")a=L.body;else if(J==="feedback")d=L.body.toString("utf-8");else if(J==="color")c=L.body.toString("utf-8");else if(J==="provider")I=L.body.toString("utf-8");else if(J==="model")v=L.body.toString("utf-8");else if(J==="reasoningEffort")g=L.body.toString("utf-8");else if(J==="serviceTier")k=L.body.toString("utf-8");else if(J==="goal")b=L.body.toString("utf-8");else if(J==="pageUrl")h=L.body.toString("utf-8");else if(J==="viewport")p=L.body.toString("utf-8");else if(J==="planId")y=L.body.toString("utf-8");else if(J==="manifest")w=L.body.toString("utf-8");else if(J==="tasks")u=L.body.toString("utf-8");else if(J==="sourceId")x=L.body.toString("utf-8");else if(J==="continuationThreadId")m=L.body.toString("utf-8");else if(J==="continuationTargetBindingId")f=L.body.toString("utf-8");else if(J==="continuationSelectorAliases")try{let W=JSON.parse(L.body.toString("utf-8"));Array.isArray(W)&&(M=W.filter(ee=>typeof ee=="string"&&ee.length>0))}catch{}else if(J.startsWith("screenshot-")){let W=J.slice(11);try{let ee=decodeURIComponent(W);E.push({pathname:ee,data:L.body})}catch{}}else if(J.startsWith("image-")){let W=J.split("-"),ee=parseInt(W[W.length-1],10),H=W.slice(1,-1).join("-");H&&!isNaN(ee)&&$.push({annotationId:H,index:ee,data:L.body})}}if(!a)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:a,feedback:d,color:c,provider:I,model:v,reasoningEffort:g,serviceTier:k,goal:b,pageUrl:h,viewport:p,planId:y,manifest:w,tasks:u,sourceId:x,continuationThreadId:m,continuationTargetBindingId:f,continuationSelectorAliases:M,pastedImages:$,pageScreenshots:E}}function yl(n){return new Promise((e,t)=>{let o=[];n.on("data",r=>o.push(r)),n.on("end",()=>e(Buffer.concat(o))),n.on("error",t)})}var Il=String.raw`
116
+ `,J);if(W===-1)break;let ee=r.slice(J,W).toString("utf-8"),H=W+4,ie=r.indexOf(i,H),P=ie!==-1?ie-2:r.length;Y.push({headers:ee,body:r.slice(H,P)}),F=ie!==-1?ie:r.length}for(let L of Y){let R=L.headers.match(/name="([^"]+)"/);if(!R)continue;let J=R[1];if(J==="screenshot")a=L.body;else if(J==="feedback")d=L.body.toString("utf-8");else if(J==="color")c=L.body.toString("utf-8");else if(J==="provider")y=L.body.toString("utf-8");else if(J==="model")w=L.body.toString("utf-8");else if(J==="reasoningEffort")g=L.body.toString("utf-8");else if(J==="serviceTier")S=L.body.toString("utf-8");else if(J==="goal")b=L.body.toString("utf-8");else if(J==="pageUrl")h=L.body.toString("utf-8");else if(J==="viewport")p=L.body.toString("utf-8");else if(J==="planId")I=L.body.toString("utf-8");else if(J==="manifest")v=L.body.toString("utf-8");else if(J==="tasks")u=L.body.toString("utf-8");else if(J==="sourceId")x=L.body.toString("utf-8");else if(J==="continuationThreadId")m=L.body.toString("utf-8");else if(J==="continuationTargetBindingId")f=L.body.toString("utf-8");else if(J==="continuationSelectorAliases")try{let W=JSON.parse(L.body.toString("utf-8"));Array.isArray(W)&&(M=W.filter(ee=>typeof ee=="string"&&ee.length>0))}catch{}else if(J.startsWith("screenshot-")){let W=J.slice(11);try{let ee=decodeURIComponent(W);E.push({pathname:ee,data:L.body})}catch{}}else if(J.startsWith("image-")){let W=J.split("-"),ee=parseInt(W[W.length-1],10),H=W.slice(1,-1).join("-");H&&!isNaN(ee)&&$.push({annotationId:H,index:ee,data:L.body})}}if(!a)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:a,feedback:d,color:c,provider:y,model:w,reasoningEffort:g,serviceTier:S,goal:b,pageUrl:h,viewport:p,planId:I,manifest:v,tasks:u,sourceId:x,continuationThreadId:m,continuationTargetBindingId:f,continuationSelectorAliases:M,pastedImages:$,pageScreenshots:E}}function wl(n){return new Promise((e,t)=>{let o=[];n.on("data",r=>o.push(r)),n.on("end",()=>e(Buffer.concat(o))),n.on("error",t)})}var vl=String.raw`
117
117
  (() => {
118
118
  const hidden = [];
119
119
  const visit = (root) => {
@@ -134,7 +134,7 @@ url = "${n}"
134
134
  visit(document);
135
135
  window.__popmeltNativeCaptureHidden = hidden;
136
136
  })()
137
- `,wl=String.raw`
137
+ `,bl=String.raw`
138
138
  (() => {
139
139
  for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
140
140
  if (value) element.style.setProperty('visibility', value, priority);
@@ -142,19 +142,19 @@ url = "${n}"
142
142
  }
143
143
  delete window.__popmeltNativeCaptureHidden;
144
144
  })()
145
- `;function Oo(n){try{let e=new URL(n);return e.hash="",e.href}catch{return null}}function vl(n,e){let t=Oo(e);if(!t)return null;let o=new URL(t),r=n.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Oo(s.url)),i=r.find(s=>Oo(s.url)===t);return i||(r.find(s=>{let a=new URL(Oo(s.url));return a.origin===o.origin&&a.pathname===o.pathname})??null)}function bl(n){let e={x:Number(n.x),y:Number(n.y),width:Number(n.width),height:Number(n.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function xl(n){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let o=new URL("/json/list",n).href,r=await fetch(o,{signal:e.signal});if(!r.ok)throw new Error(`CDP discovery returned ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}finally{clearTimeout(t)}}async function Sl(n){let{WebSocket:e}=await import("ws");return new Promise((t,o)=>{let r=new e(n,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),t(r)},s=a=>{r.off("open",i),o(a)};r.once("open",i),r.once("error",s)})}function Tl(n){let e=1,t=new Map;return n.on("message",o=>{let r;try{r=JSON.parse(String(o))}catch{return}if(!r.id)return;let i=t.get(r.id);i&&(t.delete(r.id),clearTimeout(i.timeout),r.error?i.reject(new Error(r.error.message||`CDP error ${r.error.code??""}`.trim())):i.resolve(r.result??{}))}),n.on("close",()=>{for(let[o,r]of t)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),t.delete(o)}),(o,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{t.delete(a),s(new Error(`CDP ${o} timed out`))},4e3);t.set(a,{resolve:i,reject:s,timeout:d}),n.send(JSON.stringify({id:a,method:o,params:r}),c=>{c&&(clearTimeout(d),t.delete(a),s(c))})})}async function Es(n,e){let t=bl(e.clip),o=await xl(n),r=vl(o,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Sl(r.webSocketDebuggerUrl),s=Tl(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Il,returnByValue:!0}),a=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),c=typeof d.data=="string"?d.data:"";if(!c)throw new Error("CDP returned an empty screenshot");return Buffer.from(c,"base64")}finally{a&&await s("Runtime.evaluate",{expression:wl,returnByValue:!0}).catch(()=>{}),i.close()}}import{spawn as kl}from"child_process";import{isAbsolute as Pl,resolve as Rl}from"path";import{createInterface as Al}from"readline";function Jn(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function _e(n){return typeof n=="string"&&n?n:void 0}function Do(n){if(typeof n=="string")return n;if(Array.isArray(n)){let t=n.map(Do).filter(o=>!!o);return t.length>0?t.join(""):void 0}let e=Jn(n);if(e)return _e(e.text)??Do(e.content)??Do(e.message)}function _s(n){return/^\*\*([^\n]+)\*\*$/.exec(n.trim())?.[1]?.trim()||void 0}function Ml(n){return _e(n.file_path)??_e(n.filePath)??_e(n.path)??_e(n.filename)}function jl(n){return _e(n.command)??_e(n.cmd)??_e(n.content)??_e(n.new_string)??_e(n.newText)}function El(n){let e=n.toLowerCase();return e==="bash"||e==="shell"||e==="execute"?"Bash":e==="read"?"Read":e==="write"?"Write":e==="edit"||e==="apply_patch"?"Edit":n}function Cs(n,e="runtime"){let t=n.trim()||"OMP failed",o=t.toLowerCase(),r=o.includes("enoent")||o.includes("not found")||o.includes("no such file");return e==="spawn"&&r?{message:"OMP is not installed or is not available on PATH.",code:"omp_not_installed",recoverable:!0}:o.includes("auth")||o.includes("login")||o.includes("credential")?{message:`OMP is not authenticated. Open OMP once and finish provider setup. (${t})`,code:"omp_auth_required",recoverable:!0}:{message:t,code:"omp_error",recoverable:!1}}function _l(n){if(!n)return;let e=n.indexOf("/");if(!(e<=0||e===n.length-1))return{provider:n.slice(0,e),modelId:n.slice(e+1)}}function $s(n,e){let{prompt:t,projectRoot:o,resumeSessionId:r,model:i,reasoningEffort:s,serviceTier:a,timeoutMs:d=3e5,onEvent:c,ompPath:I="omp",ompArgsPrefix:v=[]}=e,g=_l(i),k=[...v,"--mode","rpc"];a&&k.push("--service-tier",a),r&&k.push("--resume",r);let b=kl(I,k,{cwd:o,stdio:["pipe","pipe","pipe"]}),h=new Promise(p=>{let y=[],w=[],u=[],x=[],m,f=!1,M=!1,$=!1,E=!g,F=!1,Y=!s,L=!1,R=!1,J,W=!1,ee="",H=!1,ie=!1,P=se=>{ie||(ie=!0,p(se))},j=se=>{b.stdin?.writable&&b.stdin.write(`${JSON.stringify(se)}
146
- `)},B=se=>{W=!0,ee=se,b.stdin?.end()},_=()=>{if(!(!M||f||W)){if(!E){!$&&g&&($=!0,j({id:`popmelt_model_${n}`,type:"set_model",provider:g.provider,modelId:g.modelId}));return}if(!Y){!F&&s&&(F=!0,j({id:`popmelt_thinking_${n}`,type:"set_thinking_level",level:s}));return}f=!0,j({id:`popmelt_prompt_${n}`,type:"prompt",message:t})}},Q=()=>{J&&clearTimeout(J),b.stdin?.writable&&b.stdin.end(),setTimeout(()=>{b.exitCode===null&&b.kill("SIGTERM")},2e3).unref?.()},de=setTimeout(()=>{H=!0,b.kill("SIGTERM"),setTimeout(()=>{b.exitCode===null&&b.kill("SIGKILL")},5e3).unref?.()},d),Z=Al({input:b.stdout});Z.on("line",se=>{if(!se.trim())return;let xe;try{xe=JSON.parse(se)}catch{return}let qe=_e(xe.type);if(qe==="ready"&&!M){if(M=!0,j({id:`popmelt_state_${n}`,type:"get_state"}),i&&!g){B(`OMP model selector is invalid: ${i}`);return}_();return}if(qe==="response"){let pe=_e(xe.command),Te=xe.success!==!1;if(pe==="get_state"&&Te){let Ce=Jn(xe.data);m=_e(Ce?.sessionFile)??_e(Ce?.sessionId)??m,L&&R&&Q()}else pe==="set_model"?Te?(E=!0,_()):B(_e(xe.error)??"OMP rejected the selected model."):pe==="set_thinking_level"?Te?(Y=!0,_()):B(_e(xe.error)??"OMP rejected the selected thinking level."):pe==="prompt"&&!Te&&(W=!0,ee=_e(xe.error)??"OMP rejected the prompt.",b.stdin?.end());return}if(qe==="message_update"){let pe=Jn(xe.assistantMessageEvent),Te=_e(pe?.type),Ce=_e(pe?.delta);if(Ce&&Te==="text_delta")w.push(Ce);else if(Ce&&Te==="thinking_delta"){let Ue=_s(Ce);c?.(Ue?{type:"status",jobId:n,text:Ue}:{type:"thinking",jobId:n,text:Ce},n)}return}if(qe==="message_end"){let pe=Jn(xe.message);if(pe?.role==="assistant"){let Te=Do(pe.content)||w.join("");if(w.length=0,Te){let Ce=_s(Te);Ce?c?.({type:"status",jobId:n,text:Ce},n):(y.length=0,y.push(Te.trim()),c?.({type:"delta",jobId:n,text:Te.trim()},n))}}return}if(qe==="tool_execution_start"){let pe=_e(xe.toolName)??"Tool",Te=El(pe),Ce=Jn(xe.args)??{},Ue=Ml(Ce),De=Ue?Pl(Ue)?Ue:Rl(o,Ue):void 0,st=jl(Ce);u.push(De?`${Te} ${Ue}`:Te),c?.({type:"tool_use",jobId:n,tool:Te,...De?{file:De}:{},...st?{content:st}:{}},n);return}if(qe==="extension_error"){let pe=_e(xe.error);pe&&x.push(pe);return}qe==="agent_end"&&(L=!0,R=!0,j({id:`popmelt_final_state_${n}`,type:"get_state"}),J=setTimeout(Q,1e3),J.unref?.())}),b.stderr?.on("data",se=>{x.push(se.toString())}),b.on("error",se=>{clearTimeout(de),Z.close();let xe=Cs(se.message,"spawn");P({sessionId:m,text:y.join(""),success:!1,error:xe.message,errorCode:xe.code,recoverableError:xe.recoverable,provider:"omp",toolsUsed:u.length>0?u:void 0})}),b.on("close",se=>{if(clearTimeout(de),Z.close(),H?(W=!0,ee=`OMP timed out after ${Math.round(d/6e4)} minutes.`):!W&&se!==0?(W=!0,ee=x.join("").trim()||`OMP exited with code ${se}.`):!W&&!L&&(W=!0,ee=x.join("").trim()||"OMP exited before completing the run."),W){let xe=Cs(ee);P({sessionId:m,text:y.join(""),success:!1,error:xe.message,errorCode:xe.code,recoverableError:xe.recoverable,provider:"omp",toolsUsed:u.length>0?u:void 0});return}P({sessionId:m,text:y.join(""),success:!0,provider:"omp",toolsUsed:u.length>0?u:void 0})})});return{process:b,result:h}}import{randomUUID as Cl}from"crypto";var $l=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Ol=new Set(["strengthened","weakened","mixed","unknown"]);function qn(n,e=180){if(typeof n!="string")return;let t=n.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Dl(n){return!n||typeof n!="object"||Array.isArray(n)?null:n}function Os(n,e,t,o=Date.now()){let r=Dl(n);if(!r)return null;let i=typeof r.transition=="string"&&$l.has(r.transition)?r.transition:null,s=qn(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&Ol.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Cl(),jobId:e,sequence:t,timestamp:o,transition:i,snapshot:{focus:s,seeking:qn(r.seeking),workingHypothesis:qn(r.workingHypothesis),evidencePosture:a,update:qn(r.update),nextObservation:qn(r.nextObservation)},contextPolicy:"exclude"}}function Nr(n){return JSON.stringify({transition:n.transition,snapshot:n.snapshot})}function Br(n,e,t=0){let o=[],r=[],i=new Set,s=t;for(let d of ls(n)){if(d.kind==="text"){d.text&&r.push(d);continue}try{let c=Os(JSON.parse(d.json),e,s);if(!c)continue;let I=Nr(c);if(i.has(I))continue;i.add(I),o.push(c),r.push({kind:"orientation",orientation:c}),s++}catch{}}return{visibleText:r.map(d=>d.kind==="text"?d.text:`
145
+ `;function Oo(n){try{let e=new URL(n);return e.hash="",e.href}catch{return null}}function xl(n,e){let t=Oo(e);if(!t)return null;let o=new URL(t),r=n.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Oo(s.url)),i=r.find(s=>Oo(s.url)===t);return i||(r.find(s=>{let a=new URL(Oo(s.url));return a.origin===o.origin&&a.pathname===o.pathname})??null)}function Sl(n){let e={x:Number(n.x),y:Number(n.y),width:Number(n.width),height:Number(n.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Tl(n){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let o=new URL("/json/list",n).href,r=await fetch(o,{signal:e.signal});if(!r.ok)throw new Error(`CDP discovery returned ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}finally{clearTimeout(t)}}async function kl(n){let{WebSocket:e}=await import("ws");return new Promise((t,o)=>{let r=new e(n,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),t(r)},s=a=>{r.off("open",i),o(a)};r.once("open",i),r.once("error",s)})}function Pl(n){let e=1,t=new Map;return n.on("message",o=>{let r;try{r=JSON.parse(String(o))}catch{return}if(!r.id)return;let i=t.get(r.id);i&&(t.delete(r.id),clearTimeout(i.timeout),r.error?i.reject(new Error(r.error.message||`CDP error ${r.error.code??""}`.trim())):i.resolve(r.result??{}))}),n.on("close",()=>{for(let[o,r]of t)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),t.delete(o)}),(o,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{t.delete(a),s(new Error(`CDP ${o} timed out`))},4e3);t.set(a,{resolve:i,reject:s,timeout:d}),n.send(JSON.stringify({id:a,method:o,params:r}),c=>{c&&(clearTimeout(d),t.delete(a),s(c))})})}async function _s(n,e){let t=Sl(e.clip),o=await Tl(n),r=xl(o,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await kl(r.webSocketDebuggerUrl),s=Pl(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:vl,returnByValue:!0}),a=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),c=typeof d.data=="string"?d.data:"";if(!c)throw new Error("CDP returned an empty screenshot");return Buffer.from(c,"base64")}finally{a&&await s("Runtime.evaluate",{expression:bl,returnByValue:!0}).catch(()=>{}),i.close()}}import{spawn as Rl}from"child_process";import{isAbsolute as Al,resolve as Ml}from"path";import{createInterface as jl}from"readline";function Jn(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function _e(n){return typeof n=="string"&&n?n:void 0}function Do(n){if(typeof n=="string")return n;if(Array.isArray(n)){let t=n.map(Do).filter(o=>!!o);return t.length>0?t.join(""):void 0}let e=Jn(n);if(e)return _e(e.text)??Do(e.content)??Do(e.message)}function Cs(n){return/^\*\*([^\n]+)\*\*$/.exec(n.trim())?.[1]?.trim()||void 0}function El(n){return _e(n.file_path)??_e(n.filePath)??_e(n.path)??_e(n.filename)}function _l(n){return _e(n.command)??_e(n.cmd)??_e(n.content)??_e(n.new_string)??_e(n.newText)}function Cl(n){let e=n.toLowerCase();return e==="bash"||e==="shell"||e==="execute"?"Bash":e==="read"?"Read":e==="write"?"Write":e==="edit"||e==="apply_patch"?"Edit":n}function $s(n,e="runtime"){let t=n.trim()||"OMP failed",o=t.toLowerCase(),r=o.includes("enoent")||o.includes("not found")||o.includes("no such file");return e==="spawn"&&r?{message:"OMP is not installed or is not available on PATH.",code:"omp_not_installed",recoverable:!0}:o.includes("auth")||o.includes("login")||o.includes("credential")?{message:`OMP is not authenticated. Open OMP once and finish provider setup. (${t})`,code:"omp_auth_required",recoverable:!0}:{message:t,code:"omp_error",recoverable:!1}}function $l(n){if(!n)return;let e=n.indexOf("/");if(!(e<=0||e===n.length-1))return{provider:n.slice(0,e),modelId:n.slice(e+1)}}function Os(n,e){let{prompt:t,projectRoot:o,resumeSessionId:r,model:i,reasoningEffort:s,serviceTier:a,timeoutMs:d=3e5,onEvent:c,ompPath:y="omp",ompArgsPrefix:w=[]}=e,g=$l(i),S=[...w,"--mode","rpc"];a&&S.push("--service-tier",a),r&&S.push("--resume",r);let b=Rl(y,S,{cwd:o,stdio:["pipe","pipe","pipe"]}),h=new Promise(p=>{let I=[],v=[],u=[],x=[],m,f=!1,M=!1,$=!1,E=!g,F=!1,Y=!s,L=!1,R=!1,J,W=!1,ee="",H=!1,ie=!1,P=se=>{ie||(ie=!0,p(se))},j=se=>{b.stdin?.writable&&b.stdin.write(`${JSON.stringify(se)}
146
+ `)},B=se=>{W=!0,ee=se,b.stdin?.end()},_=()=>{if(!(!M||f||W)){if(!E){!$&&g&&($=!0,j({id:`popmelt_model_${n}`,type:"set_model",provider:g.provider,modelId:g.modelId}));return}if(!Y){!F&&s&&(F=!0,j({id:`popmelt_thinking_${n}`,type:"set_thinking_level",level:s}));return}f=!0,j({id:`popmelt_prompt_${n}`,type:"prompt",message:t})}},Q=()=>{J&&clearTimeout(J),b.stdin?.writable&&b.stdin.end(),setTimeout(()=>{b.exitCode===null&&b.kill("SIGTERM")},2e3).unref?.()},de=setTimeout(()=>{H=!0,b.kill("SIGTERM"),setTimeout(()=>{b.exitCode===null&&b.kill("SIGKILL")},5e3).unref?.()},d),Z=jl({input:b.stdout});Z.on("line",se=>{if(!se.trim())return;let xe;try{xe=JSON.parse(se)}catch{return}let qe=_e(xe.type);if(qe==="ready"&&!M){if(M=!0,j({id:`popmelt_state_${n}`,type:"get_state"}),i&&!g){B(`OMP model selector is invalid: ${i}`);return}_();return}if(qe==="response"){let pe=_e(xe.command),Te=xe.success!==!1;if(pe==="get_state"&&Te){let Ce=Jn(xe.data);m=_e(Ce?.sessionFile)??_e(Ce?.sessionId)??m,L&&R&&Q()}else pe==="set_model"?Te?(E=!0,_()):B(_e(xe.error)??"OMP rejected the selected model."):pe==="set_thinking_level"?Te?(Y=!0,_()):B(_e(xe.error)??"OMP rejected the selected thinking level."):pe==="prompt"&&!Te&&(W=!0,ee=_e(xe.error)??"OMP rejected the prompt.",b.stdin?.end());return}if(qe==="message_update"){let pe=Jn(xe.assistantMessageEvent),Te=_e(pe?.type),Ce=_e(pe?.delta);if(Ce&&Te==="text_delta")v.push(Ce);else if(Ce&&Te==="thinking_delta"){let Ue=Cs(Ce);c?.(Ue?{type:"status",jobId:n,text:Ue}:{type:"thinking",jobId:n,text:Ce},n)}return}if(qe==="message_end"){let pe=Jn(xe.message);if(pe?.role==="assistant"){let Te=Do(pe.content)||v.join("");if(v.length=0,Te){let Ce=Cs(Te);Ce?c?.({type:"status",jobId:n,text:Ce},n):(I.length=0,I.push(Te.trim()),c?.({type:"delta",jobId:n,text:Te.trim()},n))}}return}if(qe==="tool_execution_start"){let pe=_e(xe.toolName)??"Tool",Te=Cl(pe),Ce=Jn(xe.args)??{},Ue=El(Ce),De=Ue?Al(Ue)?Ue:Ml(o,Ue):void 0,st=_l(Ce);u.push(De?`${Te} ${Ue}`:Te),c?.({type:"tool_use",jobId:n,tool:Te,...De?{file:De}:{},...st?{content:st}:{}},n);return}if(qe==="extension_error"){let pe=_e(xe.error);pe&&x.push(pe);return}qe==="agent_end"&&(L=!0,R=!0,j({id:`popmelt_final_state_${n}`,type:"get_state"}),J=setTimeout(Q,1e3),J.unref?.())}),b.stderr?.on("data",se=>{x.push(se.toString())}),b.on("error",se=>{clearTimeout(de),Z.close();let xe=$s(se.message,"spawn");P({sessionId:m,text:I.join(""),success:!1,error:xe.message,errorCode:xe.code,recoverableError:xe.recoverable,provider:"omp",toolsUsed:u.length>0?u:void 0})}),b.on("close",se=>{if(clearTimeout(de),Z.close(),H?(W=!0,ee=`OMP timed out after ${Math.round(d/6e4)} minutes.`):!W&&se!==0?(W=!0,ee=x.join("").trim()||`OMP exited with code ${se}.`):!W&&!L&&(W=!0,ee=x.join("").trim()||"OMP exited before completing the run."),W){let xe=$s(ee);P({sessionId:m,text:I.join(""),success:!1,error:xe.message,errorCode:xe.code,recoverableError:xe.recoverable,provider:"omp",toolsUsed:u.length>0?u:void 0});return}P({sessionId:m,text:I.join(""),success:!0,provider:"omp",toolsUsed:u.length>0?u:void 0})})});return{process:b,result:h}}import{randomUUID as Ol}from"crypto";var Dl=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Nl=new Set(["strengthened","weakened","mixed","unknown"]);function qn(n,e=180){if(typeof n!="string")return;let t=n.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Bl(n){return!n||typeof n!="object"||Array.isArray(n)?null:n}function Ds(n,e,t,o=Date.now()){let r=Bl(n);if(!r)return null;let i=typeof r.transition=="string"&&Dl.has(r.transition)?r.transition:null,s=qn(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&Nl.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Ol(),jobId:e,sequence:t,timestamp:o,transition:i,snapshot:{focus:s,seeking:qn(r.seeking),workingHypothesis:qn(r.workingHypothesis),evidencePosture:a,update:qn(r.update),nextObservation:qn(r.nextObservation)},contextPolicy:"exclude"}}function Nr(n){return JSON.stringify({transition:n.transition,snapshot:n.snapshot})}function Br(n,e,t=0){let o=[],r=[],i=new Set,s=t;for(let d of ps(n)){if(d.kind==="text"){d.text&&r.push(d);continue}try{let c=Ds(JSON.parse(d.json),e,s);if(!c)continue;let y=Nr(c);if(i.has(y))continue;i.add(y),o.push(c),r.push({kind:"orientation",orientation:c}),s++}catch{}}return{visibleText:r.map(d=>d.kind==="text"?d.text:`
147
147
 
148
148
  `).join("").replace(/\n{3,}/g,`
149
149
 
150
- `).trim(),orientations:o,segments:r}}function Nl(n){let e=[dn,...Nt],t=Math.min(n.length,Math.max(...e.map(o=>o.length))-1);for(let o=t;o>0;o--){let r=n.slice(-o);if(e.some(i=>i.startsWith(r)))return o}return 0}function Bl(n){return Nt.find(e=>n.startsWith(e))}function Jl(n){return Nt.some(e=>e.startsWith(n)&&n.length<e.length)}var No=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",o=[];for(;this.buffer;){if(this.optionalClosePending){let c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let I=this.buffer.slice(c);if(Jl(I))break;let v=Bl(I);if(v&&(this.buffer=this.buffer.slice(c+v.length)),this.optionalClosePending=!1,!this.buffer)break}let r=this.buffer.indexOf(dn),i=Nt.map(c=>({index:this.buffer.indexOf(c),tag:c})).filter(c=>c.index>=0).sort((c,I)=>c.index-I.index)[0];if(i&&(r<0||i.index<r)){t+=this.buffer.slice(0,i.index),this.buffer=this.buffer.slice(i.index+i.tag.length);continue}if(r<0){let c=Nl(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,r);let s=r+dn.length,a=cn(this.buffer,s);if(a.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(a.status==="invalid"){this.buffer=this.buffer.slice(s);continue}let d=this.buffer.slice(a.start,a.end);this.buffer=this.buffer.slice(a.end),this.optionalClosePending=!0;try{let c=Os(JSON.parse(d),this.jobId,this.sequence);if(!c)continue;let I=Nr(c);if(this.signatures.has(I))continue;this.signatures.add(I),o.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:o}}finalize(e){let t=Br(e,this.jobId,this.sequence),o=t.orientations.filter(r=>{let i=Nr(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:o}}},Ds=`## Public orientation updates
150
+ `).trim(),orientations:o,segments:r}}function Jl(n){let e=[dn,...Nt],t=Math.min(n.length,Math.max(...e.map(o=>o.length))-1);for(let o=t;o>0;o--){let r=n.slice(-o);if(e.some(i=>i.startsWith(r)))return o}return 0}function ql(n){return Nt.find(e=>n.startsWith(e))}function Ll(n){return Nt.some(e=>e.startsWith(n)&&n.length<e.length)}var No=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",o=[];for(;this.buffer;){if(this.optionalClosePending){let c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let y=this.buffer.slice(c);if(Ll(y))break;let w=ql(y);if(w&&(this.buffer=this.buffer.slice(c+w.length)),this.optionalClosePending=!1,!this.buffer)break}let r=this.buffer.indexOf(dn),i=Nt.map(c=>({index:this.buffer.indexOf(c),tag:c})).filter(c=>c.index>=0).sort((c,y)=>c.index-y.index)[0];if(i&&(r<0||i.index<r)){t+=this.buffer.slice(0,i.index),this.buffer=this.buffer.slice(i.index+i.tag.length);continue}if(r<0){let c=Jl(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,r);let s=r+dn.length,a=cn(this.buffer,s);if(a.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(a.status==="invalid"){this.buffer=this.buffer.slice(s);continue}let d=this.buffer.slice(a.start,a.end);this.buffer=this.buffer.slice(a.end),this.optionalClosePending=!0;try{let c=Ds(JSON.parse(d),this.jobId,this.sequence);if(!c)continue;let y=Nr(c);if(this.signatures.has(y))continue;this.signatures.add(y),o.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:o}}finalize(e){let t=Br(e,this.jobId,this.sequence),o=t.orientations.filter(r=>{let i=Nr(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:o}}},Ns=`## Public orientation updates
151
151
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
152
152
  <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>
153
153
 
154
154
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
155
155
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
156
156
 
157
- 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.`;var Ns=`## Project collaboration history
157
+ 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.`;var Bs=`## Project collaboration history
158
158
  Popmelt's durable collaboration history lives in the project's \`.popmelt\` directory. High-confidence relevant Imprint explanations may already be surfaced elsewhere in this prompt. Start with that supplied Imprint context and use it directly when it adequately answers the developer's question. For questions about the current implementation, inspect the relevant source only as needed to confirm how that understanding is expressed.
159
159
 
160
160
  For answer-only or explanation-only requests, use a narrow default evidence budget: begin with the supplied Imprint, inspect the selected component once, and inspect at most one directly surrounding layout source only if the component does not adequately explain the observation. Explain the dominant visible phenomenon rather than auditing every property in the screenshot. Stop once the answer is supported. Broaden beyond that only when evidence conflicts, the selected target remains materially ambiguous, or the developer explicitly asks for a comprehensive audit.
@@ -163,25 +163,25 @@ Search raw \`.popmelt\` records only when the supplied Imprint context is insuff
163
163
 
164
164
  Use Popmelt history to explain why a decision was made or how shared understanding developed. Use git history only when the question depends on chronology or source provenance. Clearly distinguish recorded human or collaboration evidence from your own inference.
165
165
 
166
- Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Bs(n){n.push(""),n.push("## User-facing communication"),n.push("Keep Popmelt implementation details private. In progress updates, questions, and final prose, never mention internal tracking attributes or their values, raw selectors, element identifiers, identity machinery, lifecycle machinery, completion metadata, resolution envelopes, or similar Popmelt protocol terminology."),n.push("Do not narrate searches for internal markers or explain how Popmelt locates, binds, continues, or resolves work. Refer instead to the visible element or component, the requested change, and the user-visible result."),n.push("Use these internal mechanisms silently. Required tagged metadata blocks are still mandatory, but do not introduce, describe, or refer to them in user-visible prose. Discuss Popmelt internals only when the developer explicitly asks about them.")}function ql(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase()}function Ll(n){if(!n.subjectLabel){let t=[n.selector];return n.reactComponent&&t.push(`(${n.reactComponent})`),t.join(" ")}let e=Object.entries(n.dataAttributes??{}).filter(([t])=>t!=="adapter"&&t!=="key").map(([t,o])=>`${ql(t)}: ${o}`);return[`${n.subjectLabel} (${n.tagName} rendered subject)`,n.context?`${n.imageObject||n.videoObject?"context":"scene path"}: ${n.context}`:"",...e].filter(Boolean).join(" | ")}function Ln(n,e,t){let o=[];if(n.annotations.length>0){o.push("## Annotations");for(let r of n.annotations){let i=r.elements.map(Ll).join(", "),s=r.instruction||"No text";o.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);for(let c of r.elements){let I=c.imageObject;if(I){let k=h=>Number(h.toFixed(3)),b=h=>`x=${k(h.x)}, y=${k(h.y)}, width=${k(h.width)}, height=${k(h.height)}`;o.push(` Image object: ${JSON.stringify(c.subjectLabel||c.textContent||"object")}`),o.push(` Source image: ${I.src}${I.alt?` | alt: ${JSON.stringify(I.alt)}`:""}`),o.push(` Intrinsic image size: ${I.width} \xD7 ${I.height} px.`),o.push(` Bounding box in original-image pixels (top-left origin; x right, y down): ${b(I.box)}.`),o.push(` Normalized bounding box (0\u20131, same origin/axes): ${b(I.normalizedBox)}. These are image-space coordinates, not page/CSS coordinates.`)}let v=c.videoObject;if(v){let k=h=>Number(h.toFixed(3)),b=h=>`x=${k(h.x)}, y=${k(h.y)}, width=${k(h.width)}, height=${k(h.height)}`;o.push(` Video object: ${JSON.stringify(c.subjectLabel||c.textContent||"object")}`),o.push(` Source video: ${v.src}`),o.push(` Intrinsic video size: ${v.width} \xD7 ${v.height} px | duration: ${k(v.duration)}s | annotated frame: ${k(v.currentTime)}s.`),o.push(` Bounding box in source-frame pixels (top-left origin; x right, y down): ${b(v.box)}.`),o.push(` Normalized bounding box (0\u20131, same origin/axes): ${b(v.normalizedBox)}. These are video-frame coordinates, not page/CSS coordinates.`),o.push(` Saved track span: ${k(v.trackStart)}s\u2013${k(v.trackEnd)}s.`)}let g=c.sourceElement;if(g){o.push(` Source element: <${g.tagName}> ${g.selector}${g.context?` | context: ${g.context}`:""}`);let k=g.reactComponentPath?.join(" \u2192 ")||g.reactComponent;o.push(` React component: ${k||"unavailable in this build"}.`);let b=g.reactSource;o.push(b?` JSX source: ${b.fileName}:${b.lineNumber}${b.columnNumber?`:${b.columnNumber}`:""}`:" JSX file/line unavailable in this build; locate the source using the component, image URL, and element context above.")}}r.subjectFeedback?.warning&&o.push(` Object context warning: ${r.subjectFeedback.warning}`);let a=e?.[r.id];if(a&&a.length>0)for(let[c,I]of a.entries())o.push(c===r.subjectFeedback?.cropImageIndex?` Object crop (clean pixels of the bounding box above, longest side capped at 1024px): use the Read tool to view ${I}`:` Attached image: use the Read tool to view ${I}`);let d=t?.[r.id];if(d?.length)for(let c of d)o.push(` Attached context (${c.name}, ${c.mimeType}): use the Read tool to inspect ${c.path}`)}}if(n.styleModifications.length>0){o.push(""),o.push("## Style Changes (make permanent in source)"),o.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 r of n.styleModifications){let i=Zo(r.element,r.selector);for(let s of r.changes){let a=s.token?` [${s.token}]`:"";o.push(`- ${r.selector} (${i}): ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(n.textModifications?.length){o.push(""),o.push("## Text Changes (make permanent in source)"),o.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 r of n.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),d=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";o.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(n.domModifications?.length){o.push(""),o.push("## DOM Structure Changes (make permanent in source)"),o.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 r of n.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;o.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(n.spacingTokenChanges?.length){o.push(""),o.push("## Spacing Token Changes"),o.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of n.spacingTokenChanges){o.push(`
166
+ Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function Js(n){n.push(""),n.push("## User-facing communication"),n.push("Keep Popmelt implementation details private. In progress updates, questions, and final prose, never mention internal tracking attributes or their values, raw selectors, element identifiers, identity machinery, lifecycle machinery, completion metadata, resolution envelopes, or similar Popmelt protocol terminology."),n.push("Do not narrate searches for internal markers or explain how Popmelt locates, binds, continues, or resolves work. Refer instead to the visible element or component, the requested change, and the user-visible result."),n.push("Use these internal mechanisms silently. Required tagged metadata blocks are still mandatory, but do not introduce, describe, or refer to them in user-visible prose. Discuss Popmelt internals only when the developer explicitly asks about them.")}function qs(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase()}function Jr(n){let e=n.subject,t=[e?`${e.label} (${n.tagName} rendered subject)`:`<${n.tagName}>`,n.role?`role=${n.role}`:"",!e&&n.ariaLabel?`label="${n.ariaLabel}"`:"",!e&&n.text?`text="${n.text}"`:""].filter(Boolean),o=[n.value!==void 0?`value="${n.value}"`:"",n.checked!==void 0?`checked=${n.checked}`:"",n.expanded!==void 0?`expanded=${n.expanded}`:"",n.pressed!==void 0?`pressed=${n.pressed}`:"",n.selected!==void 0?`selected=${n.selected}`:"",n.disabled!==void 0?`disabled=${n.disabled}`:"",e?.context?`context="${e.context}"`:"",...Object.entries(e?.data??{}).map(([s,a])=>`${qs(s)}="${a}"`)].filter(Boolean),r=n.media,i=r?r.kind==="video"?`video time=${r.currentTime}s${r.duration!==void 0?`/${r.duration}s`:""} paused=${r.paused}`:r.kind==="image"?`image ${r.naturalWidth}x${r.naturalHeight} complete=${r.complete}`:`canvas ${r.width}x${r.height}`:"";return[...t,...o,i].filter(Boolean).join(" ")}function Fl(n){if(!n.subjectLabel){let t=[n.selector];return n.reactComponent&&t.push(`(${n.reactComponent})`),t.join(" ")}let e=Object.entries(n.dataAttributes??{}).filter(([t])=>t!=="adapter"&&t!=="key").map(([t,o])=>`${qs(t)}: ${o}`);return[`${n.subjectLabel} (${n.tagName} rendered subject)`,n.context?`${n.imageObject||n.videoObject?"context":"scene path"}: ${n.context}`:"",...e].filter(Boolean).join(" | ")}function Ln(n,e,t){let o=[];if(n.annotations.length>0){o.push("## Annotations");for(let r of n.annotations){let i=r.elements.map(Fl).join(", "),s=r.instruction||"No text";o.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);for(let y of r.elements){let w=y.imageObject;if(w){let b=p=>Number(p.toFixed(3)),h=p=>`x=${b(p.x)}, y=${b(p.y)}, width=${b(p.width)}, height=${b(p.height)}`;o.push(` Image object: ${JSON.stringify(y.subjectLabel||y.textContent||"object")}`),o.push(` Source image: ${w.src}${w.alt?` | alt: ${JSON.stringify(w.alt)}`:""}`),o.push(` Intrinsic image size: ${w.width} \xD7 ${w.height} px.`),o.push(` Bounding box in original-image pixels (top-left origin; x right, y down): ${h(w.box)}.`),o.push(` Normalized bounding box (0\u20131, same origin/axes): ${h(w.normalizedBox)}. These are image-space coordinates, not page/CSS coordinates.`)}let g=y.videoObject;if(g){let b=p=>Number(p.toFixed(3)),h=p=>`x=${b(p.x)}, y=${b(p.y)}, width=${b(p.width)}, height=${b(p.height)}`;o.push(` Video object: ${JSON.stringify(y.subjectLabel||y.textContent||"object")}`),o.push(` Source video: ${g.src}`),o.push(` Intrinsic video size: ${g.width} \xD7 ${g.height} px | duration: ${b(g.duration)}s | annotated frame: ${b(g.currentTime)}s.`),o.push(` Bounding box in source-frame pixels (top-left origin; x right, y down): ${h(g.box)}.`),o.push(` Normalized bounding box (0\u20131, same origin/axes): ${h(g.normalizedBox)}. These are video-frame coordinates, not page/CSS coordinates.`),o.push(` Saved track span: ${b(g.trackStart)}s\u2013${b(g.trackEnd)}s.`)}let S=y.sourceElement;if(S){o.push(` Source element: <${S.tagName}> ${S.selector}${S.context?` | context: ${S.context}`:""}`);let b=S.reactComponentPath?.join(" \u2192 ")||S.reactComponent;o.push(` React component: ${b||"unavailable in this build"}.`);let h=S.reactSource;o.push(h?` JSX source: ${h.fileName}:${h.lineNumber}${h.columnNumber?`:${h.columnNumber}`:""}`:" JSX file/line unavailable in this build; locate the source using the component, image URL, and element context above.")}}r.subjectFeedback?.warning&&o.push(` Object context warning: ${r.subjectFeedback.warning}`);let a=e?.[r.id],d=new Set;if(r.interactionEpisode){let y=r.interactionEpisode,w=new Map((y.frames??[]).map(g=>[g.id,g]));o.push(` Interaction episode: ${y.steps.length} semantic step${y.steps.length===1?"":"s"}.`),y.subject&&o.push(` Episode subject: ${Jr(y.subject)}.`);for(let[g,S]of y.steps.entries()){let b=S.outcome==="no-observable-change"?"no observable page change":`${S.changes.length} observed change${S.changes.length===1?"":"s"}`;o.push(` ${g+1}. ${S.action.label}${S.action.key?` (${S.action.key})`:""} \u2014 ${b}.`);for(let I of S.changes)o.push(` ${I.kind}: ${Jr(I.element)}`);S.result&&o.push(` resulting target: ${Jr(S.result)}`);let h=S.visuals?.beforeFrameId?w.get(S.visuals.beforeFrameId):void 0,p=S.visuals?.afterFrameId?w.get(S.visuals.afterFrameId):void 0;h&&a?.[h.imageIndex]&&(d.add(h.imageIndex),o.push(` visual before: use the Read tool to view ${a[h.imageIndex]}`)),p&&a?.[p.imageIndex]&&(d.add(p.imageIndex),o.push(h?.id===p.id?" visual after: unchanged from the visual before.":` visual after: use the Read tool to view ${a[p.imageIndex]}`))}}if(a&&a.length>0)for(let[y,w]of a.entries())d.has(y)||o.push(y===r.subjectFeedback?.cropImageIndex?` Object crop (clean pixels of the bounding box above, longest side capped at 1024px): use the Read tool to view ${w}`:` Attached image: use the Read tool to view ${w}`);let c=t?.[r.id];if(c?.length)for(let y of c)o.push(` Attached context (${y.name}, ${y.mimeType}): use the Read tool to inspect ${y.path}`)}}if(n.styleModifications.length>0){o.push(""),o.push("## Style Changes (make permanent in source)"),o.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 r of n.styleModifications){let i=Zo(r.element,r.selector);for(let s of r.changes){let a=s.token?` [${s.token}]`:"";o.push(`- ${r.selector} (${i}): ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(n.textModifications?.length){o.push(""),o.push("## Text Changes (make permanent in source)"),o.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 r of n.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),d=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";o.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(n.domModifications?.length){o.push(""),o.push("## DOM Structure Changes (make permanent in source)"),o.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 r of n.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;o.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(n.spacingTokenChanges?.length){o.push(""),o.push("## Spacing Token Changes"),o.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of n.spacingTokenChanges){o.push(`
167
167
  ### ${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`);for(let i of r.affectedElements){let s=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?o.push(`- ${i.selector}${s}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):o.push(`- ${i.selector}${s}: ${i.property} ${r.originalPx}px \u2192 ${r.newPx}px`),o.push(` class="${i.className}"`)}}}if(n.inspectedElement){let r=n.inspectedElement;o.push(""),o.push("## Inspected Element"),o.push("The developer has this element selected in the inspector:");let i=[r.selector];r.reactComponent&&i.push(`(${r.reactComponent})`),r.context&&i.push(`in ${r.context}`),r.textContent&&i.push(`"${r.textContent.slice(0,80)}"`),o.push(`- ${i.join(" ")}`)}return o.join(`
168
- `)}function Js(n,e,t){let o=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(o.push("You are reviewing a UI screenshot with developer annotations."),o.push(""),!i&&t?.provider!=="codex"&&(o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${n}`),o.push("")),o.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){o.push(""),o.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&o.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${a.question}"`);else{if(o.push(`### Round ${s} (assistant)`),a.responseText&&o.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let c=d.finalScope??d.inferredScope,I=c?` [${c.breadth} ${c.target}]`:"";o.push(`- ${d.annotationId}: ${d.status}${I} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&o.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&o.push(`Tools used: ${a.toolsUsed.join(", ")}`)}o.push(""),o.push("The current round is shown in full below.")}if(t?.designModel){o.push(""),o.push("## Established Design Policies"),o.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=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(o.push(""),o.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let I=new Map;for(let v of s)if(typeof v=="object"&&v!==null&&"text"in v){let g=v,k=g.scope||"general";I.has(k)||I.set(k,[]),I.get(k).push(g.text)}for(let[v,g]of I){o.push(`**${v.charAt(0).toUpperCase()+v.slice(1)}**`);for(let k of g)o.push(`- ${k}`)}}else for(let I of s)typeof I=="string"&&o.push(`- ${I}`);let a=t.designModel.tokens;a&&typeof a=="object"&&(o.push(""),o.push("Design tokens:"),o.push("```json"),o.push(JSON.stringify(a,null,2)),o.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(o.push(""),o.push("Component patterns:"),o.push("```json"),o.push(JSON.stringify(d,null,2)),o.push("```")),o.push(""),o.push("### Applied Model-Gap Details"),o.push("Only when you actually modify the project and implement 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), describe that applied gap:"),o.push("<novel>"),o.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),o.push("</novel>"),o.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),o.push("- `element`: What you are styling or creating"),o.push("- `decision`: What you actually implemented (specific values)"),o.push("- `reason`: Why this is novel (what is missing from the model)"),o.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),o.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(o.push(""),o.push("## Design Context"),o.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=t?.screenshotPaths??{},a=new Map;for(let d of e.annotations){let c=d.pathname||new URL(e.url).pathname;a.has(c)||a.set(c,[]),a.get(c).push(d)}o.push(""),o.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,c]of a){o.push(""),o.push(`## Page: ${d}`);let I=s[d];I&&t?.provider!=="codex"?o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${I}`):!I&&t?.provider!=="codex"&&(Object.keys(s).length===0?(o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${n}`),o.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):o.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let v={...e,annotations:c,styleModifications:e.styleModifications},g=Ln(v,t?.imagePaths,t?.attachmentFiles);g&&(o.push(""),o.push(g))}}else{let s=Ln(e,t?.imagePaths,t?.attachmentFiles);s&&(o.push(""),o.push(s))}return o.push(""),o.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."),o.push(""),o.push("INTERNAL IMPLEMENTATION REQUIREMENT: If any elements you modify have a `data-pm` attribute, preserve it in the source. Do not mention this attribute or requirement in user-visible prose."),Bs(o),o.push(""),o.push("## Internal completion metadata (not user-visible)"),o.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),o.push("<resolution>"),o.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),o.push("</resolution>"),o.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push(""),o.push("## Questions"),o.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),o.push('<question>What do you mean by "..."?</question>'),o.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),o.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),o.join(`
169
- `)}function qs(n){return n.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ls(n,e,t,o){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),t!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${n}`);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 a of e)a.role==="human"?(s++,a.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${a.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),a.feedbackSummary&&r.push(`Annotations: ${a.feedbackSummary}`))):a.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${a.question}"`)):(r.push(`### Round ${s} (assistant)`),a.responseText&&r.push(`Response: ${a.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("INTERNAL IMPLEMENTATION REQUIREMENT: If any elements you modify have a `data-pm` attribute, preserve it in the source. Do not mention this attribute or requirement in user-visible prose."),Bs(r),o&&o.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of o)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Internal completion metadata (not user-visible)"),r.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),r.push("<resolution>"),r.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),r.push("</resolution>"),r.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),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(`
170
- `)}function Fl(n){if(typeof n!="object"||n===null)return!1;let e=n;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Ul(n){if(typeof n!="object"||n===null||typeof n.annotationId!="string"||n.status!=="resolved"&&n.status!=="needs_review"||typeof n.summary!="string")return!1;let e=n;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!Fl(e[t]))return!1;return!0}function Fs(n){let t=[...n.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let o=JSON.parse(t);return(Array.isArray(o)?o:o&&typeof o=="object"&&Array.isArray(o.annotations)?o.annotations:[]).filter(Ul)}catch{return[]}}function zl(n){let e=n.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(o=>{if(typeof o!="object"||o===null)return!1;let r=o;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}function Us(n,e){return e>0?zl(n):[]}import{execFile as Gl}from"child_process";import{readFile as Wl,readdir as Vl,stat as Kl}from"fs/promises";import{homedir as Fn}from"os";import{join as pt}from"path";var Bo=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:zs()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:zs()}],Un=[{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"}],zn={id:"",label:"Default",source:"cli"},qt={id:"",label:"OMP default",source:"cli"},Hl=/^\s*-\s+"([^"]+)"/;function Ql(n){let e=[],t=!1;for(let o of n.split(`
171
- `)){if(/^\s*`model`:/.test(o)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(o))break;if(!t)continue;let r=o.match(Hl);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Gn(i),source:"cli"})}return fn([zn,...e])}function Xl(n){let e=JSON.parse(n);return(Array.isArray(e.models)?e.models:[]).filter(o=>o.visibility===void 0||o.visibility==="list").sort((o,r)=>{let i=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(o=>{let r=typeof o.slug=="string"?o.slug:typeof o.id=="string"?o.id:"";if(!r)return[];let i=typeof o.display_name=="string"&&o.display_name.trim()?o.display_name.trim():Gn(r),s=Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let c=d;return typeof c.effort!="string"?[]:[{effort:c.effort,...typeof c.description=="string"?{description:c.description}:{}}]}):void 0,a=Array.isArray(o.service_tiers)?o.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let c=d;return typeof c.id!="string"?[]:[{id:c.id,label:typeof c.name=="string"?c.name:c.id,...typeof c.description=="string"?{description:c.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof o.default_reasoning_level=="string"?{defaultReasoningLevel:o.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function Yl(n,e){let t=JSON.parse(n),o=t.key==="modelRoles"&&t.value&&typeof t.value=="object"&&"default"in t.value?t.value.default:t.modelRoles?.value?.default;if(typeof o!="string"||!o.trim())return[qt];let r=o.trim(),i=r.split("/").pop()||r,s;if(e){let a=JSON.parse(e);a.key==="defaultThinkingLevel"&&typeof a.value=="string"&&a.value.trim()&&(s=a.value.trim())}return[{id:"",label:Gn(i),source:"cli",...s?{defaultReasoningLevel:s}:{}}]}function Zl(n,e,t){let[o]=Yl(n,e),r=ep(n),i=JSON.parse(t),s=Array.isArray(i.models)?i.models:[],a=s.flatMap(v=>{let g=typeof v.provider=="string"?v.provider.trim():"",k=typeof v.id=="string"?v.id.trim():"",b=typeof v.selector=="string"&&v.selector.trim()?v.selector.trim():g&&k?`${g}/${k}`:"";if(!g||!k||!b)return[];let h=Array.isArray(v.thinking)?v.thinking.flatMap(p=>typeof p=="string"&&p.trim()?[{effort:p.trim()}]:[]):[];return b===r?[{...o??qt,isDefault:!0,upstreamProvider:g,...h.length>0?{supportedReasoningLevels:h}:{}}]:[{id:b,label:Gn(k),source:"cli",upstreamProvider:g,...h.length>0?{supportedReasoningLevels:h}:{}}]}),d=s.find(v=>(typeof v.selector=="string"?v.selector.trim():typeof v.provider=="string"&&typeof v.id=="string"?`${v.provider.trim()}/${v.id.trim()}`:"")===r),c=Array.isArray(d?.thinking)?d.thinking.flatMap(v=>typeof v=="string"&&v.trim()?[{effort:v.trim()}]:[]):[],I={...o??qt,isDefault:!0,...r?.includes("/")?{upstreamProvider:r.split("/")[0]}:{},...c.length>0?{supportedReasoningLevels:c}:{}};return a.some(v=>v.isDefault)?fn(a):fn([I,...a])}function Jr(n,e){let t=new Map(e.map(r=>[r.id,r])),o=new Map(e.map(r=>[Gs(r.label),r]));return n.map(r=>{if(r.upstreamProvider!=="openai-codex"||(r.speedTiers?.length??0)>0)return r;let i=r.id.includes("/")?r.id.slice(r.id.indexOf("/")+1):r.id,s=(i?t.get(i):void 0)??o.get(Gs(r.label));return s?.speedTiers?.length?{...r,speedTiers:s.speedTiers}:r})}function ep(n){let e=JSON.parse(n),t=e.key==="modelRoles"&&e.value&&typeof e.value=="object"&&"default"in e.value?e.value.default:e.modelRoles?.value?.default;return typeof t=="string"&&t.trim()?t.trim():void 0}function zs(){return["low","medium","high","xhigh","max"].map(n=>({effort:n}))}function tp(n){let e=n.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return fn(e.map(t=>({id:t,label:Gn(t),source:"cli"})))}function Gn(n){if(!n)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"},t=n.replace(/-\d{8,}$/,"");if(e[n])return e[n];if(e[t])return e[t];let o=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(o){let i=o[1]==="sonnet"?"Sonn":ip(o[1]),s=o[2]&&o[3]?` ${o[2]}.${o[3]}`:"";return`${i}${s}${o[4]?" Fast":""}`}let r=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark|luna|sol|terra))?$/);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}`:r[3]==="luna"?`GPT ${i} Luna`:r[3]==="sol"?`GPT ${i} Sol`:r[3]==="terra"?`GPT ${i} Terra`:`GPT ${i}`}return t}async function Ws(n="copilot"){let e=await Jt(n,["help","config"]),t=Ql(e);return t.length>1?t:[zn]}async function qr(n="omp"){let[e,t,o]=await Promise.all([Jt(n,["config","get","modelRoles","--json"],1e4),Jt(n,["config","get","defaultThinkingLevel","--json"],1e4),Jt(n,["models","--json"],3e4)]);return Zl(e,t,o)}async function Vs(n="codex"){let e=await Jt(n,["debug","models"]).catch(async()=>{let o=process.env.CODEX_HOME||pt(Fn(),".codex");return Hs(pt(o,"models_cache.json"))}),t=Xl(e);return t.length>0?fn([...t,...Un]):Un}async function Ks(n="claude"){let e=pt(Fn(),".claude"),t=[pt(Fn(),".claude","stats-cache.json"),pt(Fn(),".claude","settings.json"),pt(Fn(),".claude.json"),pt(e,"cache","changelog.md")],[o,r,i]=await Promise.all([Jt(n,["--help"]).catch(()=>""),Jt(n,["--version"]).catch(()=>""),np(e).catch(()=>[])]),s=rp([...t,...i]),a=await Promise.all(s.map(c=>Hs(c).catch(()=>""))),d=tp([o,r,...a].join(`
172
- `));return fn([...Bo,...d])}function Jt(n,e,t=5e3){return new Promise((o,r)=>{Gl(n,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}o(s)})})}async function Hs(n){return Wl(n,"utf-8")}async function np(n){let e=[pt(n,"projects"),pt(n,"telemetry")],t=[];for(let o of e)await Qs(o,t,4);return t.sort((o,r)=>r.mtimeMs-o.mtimeMs).slice(0,80).map(o=>o.path)}async function Qs(n,e,t){if(t<0)return;let o;try{o=await Vl(n,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async r=>{let i=pt(n,r.name);if(r.isDirectory()){await Qs(i,e,t-1);return}if(!(!r.isFile()||!op(r.name)))try{let s=await Kl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function op(n){return n.endsWith(".json")||n.endsWith(".jsonl")||n.endsWith(".md")||n.endsWith(".txt")}function fn(n){let e=new Set,t=[];for(let o of n)e.has(o.id)||(e.add(o.id),t.push(o));return t}function rp(n){return[...new Set(n)]}function ip(n){return n.charAt(0).toUpperCase()+n.slice(1)}function Gs(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}var Jo=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,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){t=i;break}}let o=t>=0?t+1:0,r=this.activeJobs.size+o+1;return this.queue.splice(o,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(o=>o.threadId===e&&(!t||t(o)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,o){let r=this.bufferEvent(t,e);for(let i of this.listeners)i(r,t,o)}bufferEvent(e,t){let o=this.eventBuffers.get(e);o||(o={events:[],nextSeq:0},this.eventBuffers.set(e,o));let r={...t,seq:o.nextSeq++};return o.events.push(r),o.events.length>1e4&&o.events.splice(0,o.events.length-1e4),r}getBufferedEvents(e,t=-1){let o=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!o)return null;let s=t<0?o.events:o.events.filter(a=>a.seq>t);return{jobId:e,events:s,currentSeq:o.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,t,o){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[t]+=o}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let o=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,o)}cancelJob(e){let t=this.activeProcesses.get(e),o=this.activeJobs.get(e);return!t||!o?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),o.status="error",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:"Cancelled by user",cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}cancelAll(){let e=[...this.activeJobs.values(),...this.queue];this.queue=[];for(let t of e)this.activeProcesses.get(t.id)?.kill("SIGTERM"),this.activeProcesses.delete(t.id),this.activeJobs.delete(t.id),t.status="error",t.error="Cancelled by user",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);return e}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 t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let o of t)try{o.kill("SIGTERM")}catch{}await Promise.all(t.map(o=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};o.on("exit",s),o.on("error",s),setTimeout(()=>{if(!i){try{o.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let o of this.cleanupTimers.values())clearTimeout(o);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(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),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)})}}};function Wn(n,e){return n?.projectId===e.projectId&&n.version===e.version&&n.restartMode===e.restartMode}function qo(n){return(Array.isArray(n)?n[0]:n)?.split(",")[0]?.trim()||void 0}function Lr(n){if(!n)return null;try{let e=new URL(n);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Xs(n){let e=Lr(qo(n.origin));if(e)return e;let t=Lr(qo(n.referer));if(t)return t;let o=qo(n["x-forwarded-host"]);if(!o)return null;let r=qo(n["x-forwarded-proto"])==="https"?"https":"http";return Lr(`${r}://${o}`)}function Ys(n,e,t=5){let o=(d,c)=>(c.completedAt??c.startedAt)-(d.completedAt??d.startedAt),r=[...n].sort(o).slice(0,t),i=n.filter(d=>d.status==="applied"||d.status==="failed").sort(o).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,c)=>c.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,c)=>(d[c.status]=(d[c.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{mkdir as sp,readFile as Zs,realpath as ap,writeFile as dp}from"fs/promises";import{join as Lo}from"path";async function Ur(n){return ap(n).catch(()=>n)}function ea(n){return Lo(n,".popmelt","store.json")}function cp(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function Fr(n){let e=await Ur(n);try{let t=JSON.parse(await Zs(ea(e),"utf8"));return cp(t)?t:null}catch{return null}}async function lp(n){let e=await Ur(n),t=await Fr(e);if(t)return t;let o;for(let r of[Lo(e,".popmelt","memory","manifest.json"),Lo(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await Zs(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){o=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${o??zt(e)}`,createdAt:new Date().toISOString()}}async function Fo(n){let e=await Ur(n),t=await Fr(e);if(t)return t;let o=await lp(e),r=Lo(e,".popmelt");await sp(r,{recursive:!0});try{return await dp(ea(e),`${JSON.stringify(o,null,2)}
173
- `,{encoding:"utf8",flag:"wx"}),o}catch(i){let s=await Fr(e);if(s)return s;throw i}}import{createHash as zo,randomUUID as gp}from"crypto";import{mkdir as Kn,readFile as Lt,writeFile as hn}from"fs/promises";import{dirname as Go,extname as yp,join as Xe}from"path";var pp={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 up(n){let e=typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n??"")}})();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 ta(n,e){let t=e??up(n);return{kind:t,...pp[t]}}import{createHash as mp,randomUUID as fp}from"crypto";var na=n=>`${n}-${fp()}`;function zr(n,...e){return`${n}-${mp("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Gr(n){return{schemaVersion:1,submissionIds:[na("submission")],jobId:n.jobId,threadId:n.threadId,artifactIds:[...new Set(n.artifactIds??[])]}}function Vn(n,e=[],t){return{...n,outcomeId:n.outcomeId??na("outcome"),imprintEvidenceIds:[...new Set([...n.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function oa(n){try{return new URL(n).pathname||"/"}catch{return"/"}}function hp(n){let e=[];for(let t of n){if(t.anchor.type==="opaque"){let d=t.anchor;e.some(c=>c.anchor.type==="opaque"&&c.anchor.adapter===d.adapter&&c.anchor.key===d.key)||e.push(t);continue}let o=t.anchor,r=new Set([o.runtimeSelector,o.structuralSelector,...o.legacySelectors??[]].filter(d=>!!d));if(r.size===0)continue;let i=e.filter(d=>d.anchor.type==="dom"&&d.anchor.pathname===o.pathname&&[d.anchor.runtimeSelector,d.anchor.structuralSelector,...d.anchor.legacySelectors??[]].some(c=>!!(c&&r.has(c)))),s=o.runtimeSelector,a=o.structuralSelector;for(let d of i)d.anchor.type==="dom"&&(s??=d.anchor.runtimeSelector,a??=d.anchor.structuralSelector,e.splice(e.indexOf(d),1));e.push({anchor:{type:"dom",pathname:o.pathname,...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})}return e}function Wr(n,e=[]){let t=oa(n.url),o=[],r=(i,s,a)=>{!s&&!a||o.push({anchor:{type:"dom",pathname:i||"/",...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})};for(let i of n.annotations){if(i.target){o.push({anchor:{type:"opaque",adapter:i.target.adapter,key:i.target.key}});continue}i.linkedSelector&&r(i.pathname??t,i.linkedSelector,i.elements[0]?.selector)}for(let i of n.styleModifications)r(i.pathname??t,i.selector,i.durableSelector);for(let i of n.textModifications??[])r(i.pathname??t,i.selector,i.durableSelector);for(let i of n.domModifications??[])r(i.pathname??t,i.selector,i.durableSelector);return o.length===0&&e.length>0&&r(t,e.find(i=>i.includes("[data-pm=")),e.find(i=>!i.includes("[data-pm="))),hp(o)}function ra(n){return Wr(n).flatMap(e=>{if(e.anchor.type==="opaque")return[`${e.anchor.adapter}:${e.anchor.key}`];let t=e.anchor.structuralSelector??e.anchor.runtimeSelector;return t?[`${e.anchor.pathname}:${t}`]:[]})}function ia(n,e){let t=oa(n.url);return[...new Set((e??[]).map(o=>`${t}:${o}`))]}function sa(n,e){return[...new Set([`screenshot:${e}`,...n.annotations.map(t=>`annotation:${t.id}`),...n.annotations.flatMap(t=>(t.attachments??[]).map(o=>`attachment:${o.id}`))])]}function Uo(n,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=zr("submission",n,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:n,artifactIds:[...(e.annotationIds??[]).map(o=>`annotation:${o}`),...e.screenshotPath?[zr("artifact",n,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:zr("outcome",n,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Vr(n){let e=n.lifecycleVersion!==1;n.lifecycleVersion=1;for(let t of n.messages)e=Uo(n.id,t)||e;return e}function aa(n){let e=n.messages.at(-1),t=[...n.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:n.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:n.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let o=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:n.id,status:o?"waiting_input":"resolved",label:o?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var Ip={version:1,threads:{}},da=["feedbackContext","annotationSnapshot","requestItems","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Hn={version:2,updatedAt:0,files:{},activeWorkspaceGeneration:0};function Xr(n){if(!n.startsWith("/"))return{pathname:"/",selector:n};let e=n.indexOf(":");return e<0?{pathname:"/",selector:n}:{pathname:n.slice(0,e)||"/",selector:n.slice(e+1)}}function Ft(n){return n.type==="opaque"?[n.key,...n.legacyKeys??[]]:[n.runtimeSelector,n.structuralSelector,...n.legacySelectors??[]].filter(e=>!!e)}function Kr(n){return n.type==="opaque"?Ft(n).map(e=>`${n.adapter}:${e}`):Ft(n).map(e=>`${n.pathname}:${e}`)}function Xn(n){if(n.length===0)return null;if(n[0].startsWith("codex-session:")){let s=n.filter(a=>a.startsWith("codex-session:")).map(a=>a.slice(14)).filter(Boolean);return s[0]?{anchor:{type:"opaque",adapter:"codex-session",key:s[0],...s.length>1?{legacyKeys:s.slice(1)}:{}}}:null}let e=n.map(Xr),t=e[0].pathname,o=e.filter(s=>s.pathname===t).map(s=>s.selector);if(o.length===0)return null;let r=o.find(s=>s.includes("[data-pm=")),i=o.find(s=>s!==r);return{anchor:{type:"dom",pathname:t,...r?{runtimeSelector:r}:{},...i?{structuralSelector:i}:{},...!r&&!i&&o[0]?{structuralSelector:o[0]}:{}}}}function Hr(n,e=[],t=[]){if(t.length>0)return t.filter(o=>Ft(o.anchor).length>0);if(n.length===1){let o=Xn([n[0],...e]);return o?[o]:[]}return[...new Set(n)].flatMap(o=>{let r=Xn([o]);return r?[r]:[]})}function Qr(n,e=Date.now()){return{id:`target-${gp()}`,anchor:n.anchor,createdAt:e,updatedAt:e}}function Qn(n,e){if(n.anchor.type!==e.anchor.type||n.anchor.type==="opaque"&&e.anchor.type==="opaque"&&n.anchor.adapter!==e.anchor.adapter||n.anchor.type==="dom"&&e.anchor.type==="dom"&&n.anchor.pathname!==e.anchor.pathname)return null;if(n.anchor.type==="opaque"&&e.anchor.type==="opaque"){let i=new Set(Ft(e.anchor));return Ft(n.anchor).some(s=>i.has(s))?["adapter_key"]:null}if(n.anchor.type!=="dom"||e.anchor.type!=="dom")return null;let t=[];n.anchor.runtimeSelector&&n.anchor.runtimeSelector===e.anchor.runtimeSelector&&t.push("runtime_selector"),n.anchor.structuralSelector&&n.anchor.structuralSelector===e.anchor.structuralSelector&&t.push("structural_selector");let o=new Set(Ft(e.anchor));return Ft(n.anchor).some(i=>o.has(i))?(t.length===0&&t.push("legacy_selector"),t):null}function wp(n,e){return Qn(n,e)!==null}function vp(n){return JSON.stringify(n,null,2)}function bp(n){return Object.fromEntries(da.flatMap(e=>n[e]===void 0?[]:[[e,n[e]]]))}function xp(n){let e={...n};for(let t of da)delete e[t];return e}function gn(n){let e=n;if(n.error){let t=ta(n.error,n.errorKind);(n.error!==t.message||n.errorKind!==t.kind||n.responseText!==void 0)&&(e={...n,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=an(e.result,!1),o=an(e.turn?.result,!1);(t!==e.result||o!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...o?{result:o}:{}}}:{}})}return e}var Wo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();this.continuationChain=Promise.resolve();let t=Xe(e,".popmelt");this.legacyFilePath=Xe(t,"threads.json"),this.threadsDir=Xe(t,"threads"),this.indexPath=Xe(this.threadsDir,"index.json"),this.artifactsDir=Xe(t,"artifacts","thread-messages"),this.mediaDir=Xe(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Lt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[r,i]of Object.entries(e.files)){let s=await this.readThread(Xe(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let o=!1;for(let r of Object.values(t))o=Vr(r)||o;return o=this.migrateTargetBindings()||o,o&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Lt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,o])=>[t,{...o,messages:o.messages.map(gn)}]))},this.index={...Hn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Vr(t);return this.migrateTargetBindings(),await this.persistAll(),this.cache}}catch{}return this.cache={...Ip,threads:{}},this.index={...Hn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async isTargetBindingContinuationEligible(e,t){let o=await this.load(),r=this.getActiveWorkspaceGeneration(),i=o.threads[e],s=i?.targetBindings?.find(c=>c.id===t);if(!i||!s||i.archivedAt!==void 0||(i.workspaceGeneration??0)!==r)return!1;let a={anchor:s.anchor},d=Object.values(o.threads).flatMap(c=>c.archivedAt!==void 0?[]:(c.workspaceGeneration??0)!==r?[]:(c.targetBindings??[]).filter(I=>wp(I,a)));return d.length===1&&d[0].id===t}async findContinuationThread(e,t,o=[],r=[],i){return(await this.findContinuationTarget(e,o,r,t,i)).match?.thread??null}async findContinuationTarget(e,t,o,r,i){let s=await this.load(),a=this.getActiveWorkspaceGeneration(),d=r?s.threads[r]:void 0,c=r?d?d.archivedAt!==void 0?"archived":(d.workspaceGeneration??0)!==a?"stale_generation":void 0:"missing_thread":void 0,I=d&&d.archivedAt===void 0&&(d.workspaceGeneration??0)===a,v=Hr(e,I?t:[],o);if(v.length!==1)return{match:null,decision:{action:"created",basis:v.length>1?"batch":"new_target",...c?{rejectedPreference:c}:{},matchCount:0}};if(I){let b=d.targetBindings??[];if(i){let p=b.find(w=>w.id===i);if(!p)return{match:null,decision:{action:"created",basis:"new_target",rejectedPreference:"missing_binding",matchCount:0}};let y=Qn(p,v[0]);return y?{match:{thread:d,binding:p},decision:{action:"continued",basis:"preferred",evidence:["binding_id",...y],matchCount:1}}:{match:null,decision:{action:"created",basis:"new_target",rejectedPreference:"observation_mismatch",matchCount:0}}}if(b.length===1){let p=b[0],y=Qn(p,v[0]);return{match:{thread:d,binding:p},decision:{action:"continued",basis:"preferred",...y?{evidence:y}:{},matchCount:1}}}let h=b.flatMap(p=>{let y=Qn(p,v[0]);return y?[{binding:p,evidence:y}]:[]});if(h.length===1){let p=h[0];return{match:{thread:d,binding:p.binding},decision:{action:"continued",basis:"preferred",evidence:p.evidence,matchCount:1}}}return{match:null,decision:{action:"created",basis:h.length>1?"ambiguous":"new_target",...h.length===0?{rejectedPreference:"observation_mismatch"}:{},matchCount:h.length}}}let g=Object.values(s.threads).flatMap(b=>b.archivedAt!==void 0?[]:(b.workspaceGeneration??0)!==a?[]:(b.targetBindings??[]).flatMap(h=>{let p=Qn(h,v[0]);return p?[{thread:b,binding:h,evidence:p}]:[]})),k=g.length===1?g[0]:null;return{match:k,decision:k?{action:"continued",basis:"unique_match",evidence:k.evidence,...c?{rejectedPreference:c}:{},matchCount:1}:{action:"created",basis:g.length>1?"ambiguous":"new_target",...c?{rejectedPreference:c}:{},matchCount:g.length}}}async createThread(e,t,o=[]){await this.load();let r=Hr(t,[],o);return this.createThreadRecord(e,t,r)}async createThreadRecord(e,t,o){let r=await this.load(),i={id:e,lifecycleVersion:1,workspaceGeneration:this.getActiveWorkspaceGeneration(),createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,targetBindings:o.map(s=>Qr(s)),messages:[]};return r.threads[e]=i,await this.persistThread(i),i}async findOrCreateContinuationThread(e,t,o,r=[],i=[],s){return this.serializeContinuationMutation(async()=>{await this.load();let a=Hr(e,r,i),d=await this.findContinuationTarget(e,r,a,o,s),c=d.match;if(c)return c.binding.anchor=a[0].anchor,c.binding.updatedAt=Date.now(),c.thread.updatedAt=Date.now(),await this.persistThread(c.thread),{thread:c.thread,decision:d.decision,targetBindings:[c.binding]};let I=await this.createThreadRecord(t,e,a);return{thread:I,decision:d.decision,targetBindings:I.targetBindings??[]}})}serializeContinuationMutation(e){let t=this.continuationChain.then(e);return this.continuationChain=t.then(()=>{},()=>{}),t}async appendMessage(e,t){let r=(await this.load()).threads[e];r&&(Uo(e,t),r.messages.push(gn(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;Uo(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,gn(t)):r.messages.push(gn(t)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,t,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(a=>a.jobId===t);if(s.length===0)return!1;for(let a of s)if(Object.assign(a,o),a.error){let d=gn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,t,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(a=>a.role==="assistant"&&a.jobId===t);return s?(Object.assign(s,o),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,t){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of t)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async addElementSelectorAliases(e,t){let r=(await this.load()).threads[e];if(!r||r.elementIdentifiers.length!==1)return;let i=r.targetBindings?.[0],s=Xn(t);!i||!s||(i.anchor=s.anchor,i.updatedAt=Date.now(),r.updatedAt=Date.now(),await this.persistThread(r))}async archiveThread(e){let o=(await this.load()).threads[e];return o?(o.archivedAt=o.archivedAt??Date.now(),o.updatedAt=Date.now(),await this.persistThread(o),!0):!1}async advanceWorkspaceGeneration(){return this.serializeContinuationMutation(async()=>{await this.load();let e=this.index??{...Hn,files:{}},t=(e.activeWorkspaceGeneration??0)+1;return e.activeWorkspaceGeneration=t,e.updatedAt=Date.now(),this.index=e,this.writeChain=this.writeChain.then(async()=>{await Kn(this.threadsDir,{recursive:!0}),await hn(this.indexPath,JSON.stringify(e,null,2))}),await this.writeChain,t})}async listRecent(e=5){let t=await this.load(),o=this.getActiveWorkspaceGeneration(),r=Object.values(t.threads).filter(s=>s.archivedAt===void 0&&(s.workspaceGeneration??0)===o),i=new Map;for(let s of r)for(let a of s.targetBindings??[]){let d=`${s.id}:${a.id}`;for(let c of Kr(a.anchor)){let I=i.get(c)??new Set;I.add(d),i.set(c,I)}}return r.sort((s,a)=>a.updatedAt-s.updatedAt),r.slice(0,e).map(s=>{let a=s.messages.find(m=>m.role==="human"),d=s.messages.find(m=>m.annotationSnapshot?.color)?.annotationSnapshot?.color,c=a?.feedbackSummary||"[thread]",v=a?.requestItems?.find(m=>m.kind==="changes"&&m.annotationNumber!==void 0)?.annotationNumber,g=s.messages.filter(m=>m.role==="assistant"),k=m=>{if(m.role!=="assistant")return;if(m.question)return m.question;let f=m.imprintSummary?.grounding;if(f?.question&&!m.imprintSummary?.resolvedAction)return f.question},b=s.messages.findLastIndex(m=>!!k(m)),h=s.messages.findLastIndex(m=>m.role==="human"),p=b>h?k(s.messages[b]):void 0,y=s.messages.at(-1)?.role,w=Array.from(new Set(s.messages.slice(0,Math.max(0,h)).filter(m=>m.role==="assistant"&&!!m.jobId).map(m=>m.jobId))),u=g.some(m=>!!m.responseText||!!m.question||!!m.result||!!m.memoryReviewCard||!!m.memoryReceipt),x=g.some(m=>!!m.error);return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:c,messageCount:s.messages.length,hasReply:u,hasError:x,lastMessageRole:y,pendingQuestion:p,acknowledgedJobIds:w,elementIdentifiers:s.elementIdentifiers,elementSelectorAliases:[...new Set([...s.elementSelectorAliases??[],...(s.targetBindings??[]).flatMap(m=>Kr(m.anchor))])],targetBindings:s.targetBindings?.map(m=>({...m,continuationEligible:Kr(m.anchor).every(f=>(i.get(f)?.size??0)===1)})),color:d,annotationNumber:v,lifecycle:aa(s)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let o of Object.values(e.threads)){if(o.archivedAt!==void 0)continue;let r=o.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=Vn(r.lifecycle);r.queued&&await this.updateMessage(o.id,r.jobId,{queued:!1}),await this.appendMessage(o.id,{role:"assistant",timestamp:Date.now(),jobId:r.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:i}),t+=1}return t}async getThreadHistory(e,t=6){let o=await this.getThread(e);return!o||o.messages.length===0?[]:o.messages.length<=t?o.messages:[o.messages[0],...o.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await Lt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let{version:o,messages:r,...i}=t,s=await Promise.all(r.map(async({detailArtifact:a,...d})=>{let c={};if(a?.path)try{let I=await Lt(Xe(Go(this.legacyFilePath),a.path),"utf8");zo("sha256").update(I).digest("hex")===a.sha256&&(c=JSON.parse(I))}catch{}return gn({...d,...c})}));return{...i,messages:s}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=bp(e),o=xp(e);if(Object.keys(t).length===0)return o;let r=vp(t),i=zo("sha256").update(r).digest("hex"),s=Xe("artifacts","thread-messages",`${i}.json`);await Kn(this.artifactsDir,{recursive:!0});try{await Lt(Xe(Go(this.legacyFilePath),s),"utf8")}catch{await hn(Xe(Go(this.legacyFilePath),s),r)}return{...o,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async o=>{if(Go(o)===this.mediaDir)return o;try{let r=await Lt(o),i=zo("sha256").update(r).digest("hex"),s=Xe(this.mediaDir,`${i}${yp(o)||".bin"}`);await Kn(this.mediaDir,{recursive:!0});try{await Lt(s)}catch{await hn(s,r)}return s}catch{return o}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([o,r])=>[o,await t(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([o,r])=>[o,await Promise.all(r.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([o,r])=>[o,await Promise.all(r.map(async i=>({...i,path:await t(i.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await Kn(this.threadsDir,{recursive:!0});let t=this.index??{...Hn,files:{}},o=t.files[e.id]??`${zo("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 hn(Xe(this.threadsDir,o),JSON.stringify(i,null,2)),t.files[e.id]=o,t.updatedAt=Date.now(),this.index=t,await hn(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}getActiveWorkspaceGeneration(){return this.index?.activeWorkspaceGeneration??0}migrateTargetBindings(){if(!this.cache)return!1;let e=!1;for(let t of Object.values(this.cache.threads)){if(t.targetBindings){for(let i of t.targetBindings){if(i.anchor.type!=="dom"||!i.anchor.structuralSelector?.startsWith("codex-session:"))continue;let s=Xn([i.anchor.structuralSelector]);s&&(i.anchor=s.anchor,i.updatedAt=Date.now(),e=!0)}continue}let o=(t.elementIdentityIds??[]).flatMap(i=>this.index?.elementIdentities?.[i]?.aliases??[]),r=t.elementIdentifiers.flatMap(i=>{if(i.startsWith("codex-session:")){let g=Xn([i]);return g?[Qr(g)]:[]}let s=Xr(i),a=t.elementIdentifiers.length===1?[...t.elementSelectorAliases??[],...o].map(Xr).filter(g=>g.pathname===s.pathname).map(g=>g.selector):[],d=[s.selector,...a].find(g=>g.includes("[data-pm=")),c=[s.selector,...a].find(g=>!g.includes("[data-pm=")),I=new Set([d,c].filter(Boolean)),v=[...new Set(a)].filter(g=>!I.has(g));return[Qr({anchor:{type:"dom",pathname:s.pathname,...d?{runtimeSelector:d}:{},...c?{structuralSelector:c}:{},...v.length>0?{legacySelectors:v}:{}}})]});t.targetBindings=r,delete t.elementIdentityIds,delete t.elementSelectorAliases,e=!0}return this.index?.elementIdentities&&(delete this.index.elementIdentities,e=!0),e}isThreadInActiveWorkspace(e){if(!e)return!0;let t=this.cache?.threads[e];return!!t&&t.archivedAt===void 0&&(t.workspaceGeneration??0)===this.getActiveWorkspaceGeneration()}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 Kn(this.threadsDir,{recursive:!0}),this.index=this.index??{...Hn,files:{}},await hn(this.indexPath,JSON.stringify(this.index,null,2)))}}};import{mkdir as Sp,open as Tp,readFile as kp,rename as Pp,unlink as Rp}from"fs/promises";import{dirname as Ap,join as Mp}from"path";var ca={schemaVersion:1,theme:"auto",updatedAt:null};function la(n){return n==="light"||n==="dark"||n==="auto"?n:null}async function jp(n,e){await Sp(Ap(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`;try{let o=await Tp(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
174
- `,"utf8"),await o.sync()}finally{await o.close()}await Pp(t,n)}catch(o){throw await Rp(t).catch(()=>{}),o}}var Vo=class{constructor(e){this.path=Mp(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await kp(this.path,"utf8")),t=la(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...ca}}}catch{return{exists:!1,preferences:{...ca}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await jp(this.path,t),t}};function pa(n){return la(n)!==null}var Lp=1111,Fp=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Up=1800*1e3,zp=3600*1e3,ma=45e3,Gp=5e3,Wp=1e4,Vp=2*1024*1024;function fa(n){return n.length<=1?n[0]??"":["The developer sent these queued steering messages while you were working:","",...n.map((e,t)=>`${t+1}. ${e}`)].join(`
175
- `)}function Yn(n){return[...new Set(n.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function ha(n){let e=n.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let t=n[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let o=n.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return o?.imprintSummary?.grounding?[o.imprintSummary.grounding.explanationId]:[]}function Kp(n,e){if(e.size===1)return[...n].reverse().find(t=>{let o=t.imprintSummary;return t.role==="assistant"&&!!o?.grounding&&!o?.resolvedAction&&e.has(o.grounding.explanationId)})}function va(n){if(!n)return!1;try{let e=new URL(n);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Hp(n,e,t){let o=[...t];for(let r of n)if(r.type==="tool_use"){let i=r.tool||"",s=r.file??void 0,a=r.content??void 0,d=s?s.split("/").pop()??s:void 0,c;switch(i){case"Read":c=d?`Reading ${d}`:"Reading file";break;case"Edit":c=d?`Editing ${d}`:"Editing file";break;case"Write":c=d?`Writing ${d}`:"Writing file";break;case"Bash":c=a?a.split(`
176
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=i?`Using ${i}`:"tool";break}let I=s??a??void 0,v=s?Yr(s)?s:qp(e,s):void 0,g=o[o.length-1];g&&g.kind==="tool_group"&&g.tool===i?g.items.push({label:c,detail:I,...v?{filePath:v}:{}}):o.push({kind:"tool_group",tool:i,items:[{label:c,detail:I,...v?{filePath:v}:{}}]})}return o}function Qp(n,e){if(n.processedIds.length===0&&n.success)return"No accepted decisions were ready for model projection.";if(n.success&&n.proposalId)return"";let t=[];return n.success?t.push("Model suggestion ready."):t.push("Model projection failed."),n.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.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"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),n.error&&(t.push(""),t.push(`Error: ${n.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
177
- `)}function Xp(n,e=96){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function ga(n){let e=n.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${a}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}${d.token?` [${d.token}]`:""}`)}),t=(n.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),o=(n.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=n.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;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,...o,...t,...r].map(s=>Xp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Yp(n,e){let t=n.headers.origin;va(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function N(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}var Zp=16384,eu=131072;async function Fe(n,e=Zp){let t=[],o=0;for await(let i of n){let s=typeof i=="string"?Buffer.from(i):i;if(o+=s.length,o>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let r=JSON.parse(Buffer.concat(t).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function tu(n,e){let t=[],o=0;for await(let r of n){let i=typeof r=="string"?Buffer.from(r):r;if(o+=i.length,o>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function nu(n,e){let t=n.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function ou(n,e){if(!n)return e;let t=n.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,o,r,i]=t;return`\x1B[38;2;${parseInt(o,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Zn(n,e){try{n.res.write(`event: ${e.type}
168
+ `)}function Ls(n,e,t){let o=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(o.push("You are reviewing a UI screenshot with developer annotations."),o.push(""),!i&&t?.provider!=="codex"&&(o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${n}`),o.push("")),o.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){o.push(""),o.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&o.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${a.question}"`);else{if(o.push(`### Round ${s} (assistant)`),a.responseText&&o.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let c=d.finalScope??d.inferredScope,y=c?` [${c.breadth} ${c.target}]`:"";o.push(`- ${d.annotationId}: ${d.status}${y} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&o.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&o.push(`Tools used: ${a.toolsUsed.join(", ")}`)}o.push(""),o.push("The current round is shown in full below.")}if(t?.designModel){o.push(""),o.push("## Established Design Policies"),o.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=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(o.push(""),o.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let y=new Map;for(let w of s)if(typeof w=="object"&&w!==null&&"text"in w){let g=w,S=g.scope||"general";y.has(S)||y.set(S,[]),y.get(S).push(g.text)}for(let[w,g]of y){o.push(`**${w.charAt(0).toUpperCase()+w.slice(1)}**`);for(let S of g)o.push(`- ${S}`)}}else for(let y of s)typeof y=="string"&&o.push(`- ${y}`);let a=t.designModel.tokens;a&&typeof a=="object"&&(o.push(""),o.push("Design tokens:"),o.push("```json"),o.push(JSON.stringify(a,null,2)),o.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(o.push(""),o.push("Component patterns:"),o.push("```json"),o.push(JSON.stringify(d,null,2)),o.push("```")),o.push(""),o.push("### Applied Model-Gap Details"),o.push("Only when you actually modify the project and implement 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), describe that applied gap:"),o.push("<novel>"),o.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),o.push("</novel>"),o.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),o.push("- `element`: What you are styling or creating"),o.push("- `decision`: What you actually implemented (specific values)"),o.push("- `reason`: Why this is novel (what is missing from the model)"),o.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),o.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(o.push(""),o.push("## Design Context"),o.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=t?.screenshotPaths??{},a=new Map;for(let d of e.annotations){let c=d.pathname||new URL(e.url).pathname;a.has(c)||a.set(c,[]),a.get(c).push(d)}o.push(""),o.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,c]of a){o.push(""),o.push(`## Page: ${d}`);let y=s[d];y&&t?.provider!=="codex"?o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${y}`):!y&&t?.provider!=="codex"&&(Object.keys(s).length===0?(o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${n}`),o.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):o.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let w={...e,annotations:c,styleModifications:e.styleModifications},g=Ln(w,t?.imagePaths,t?.attachmentFiles);g&&(o.push(""),o.push(g))}}else{let s=Ln(e,t?.imagePaths,t?.attachmentFiles);s&&(o.push(""),o.push(s))}return o.push(""),o.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."),o.push(""),o.push("INTERNAL IMPLEMENTATION REQUIREMENT: If any elements you modify have a `data-pm` attribute, preserve it in the source. Do not mention this attribute or requirement in user-visible prose."),Js(o),o.push(""),o.push("## Internal completion metadata (not user-visible)"),o.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),o.push("<resolution>"),o.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),o.push("</resolution>"),o.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push(""),o.push("## Questions"),o.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),o.push('<question>What do you mean by "..."?</question>'),o.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),o.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),o.join(`
169
+ `)}function Fs(n){return n.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Us(n,e,t,o){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),t!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${n}`);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 a of e)a.role==="human"?(s++,a.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${a.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),a.feedbackSummary&&r.push(`Annotations: ${a.feedbackSummary}`))):a.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${a.question}"`)):(r.push(`### Round ${s} (assistant)`),a.responseText&&r.push(`Response: ${a.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("INTERNAL IMPLEMENTATION REQUIREMENT: If any elements you modify have a `data-pm` attribute, preserve it in the source. Do not mention this attribute or requirement in user-visible prose."),Js(r),o&&o.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of o)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Internal completion metadata (not user-visible)"),r.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),r.push("<resolution>"),r.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),r.push("</resolution>"),r.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),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(`
170
+ `)}function Ul(n){if(typeof n!="object"||n===null)return!1;let e=n;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function zl(n){if(typeof n!="object"||n===null||typeof n.annotationId!="string"||n.status!=="resolved"&&n.status!=="needs_review"||typeof n.summary!="string")return!1;let e=n;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!Ul(e[t]))return!1;return!0}function zs(n){let t=[...n.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let o=JSON.parse(t);return(Array.isArray(o)?o:o&&typeof o=="object"&&Array.isArray(o.annotations)?o.annotations:[]).filter(zl)}catch{return[]}}function Gl(n){let e=n.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(o=>{if(typeof o!="object"||o===null)return!1;let r=o;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}function Gs(n,e){return e>0?Gl(n):[]}import{execFile as Wl}from"child_process";import{readFile as Vl,readdir as Kl,stat as Hl}from"fs/promises";import{homedir as Fn}from"os";import{join as pt}from"path";var Bo=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Ws()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Ws()}],Un=[{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"}],zn={id:"",label:"Default",source:"cli"},qt={id:"",label:"OMP default",source:"cli"},Ql=/^\s*-\s+"([^"]+)"/;function Xl(n){let e=[],t=!1;for(let o of n.split(`
171
+ `)){if(/^\s*`model`:/.test(o)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(o))break;if(!t)continue;let r=o.match(Ql);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Gn(i),source:"cli"})}return fn([zn,...e])}function Yl(n){let e=JSON.parse(n);return(Array.isArray(e.models)?e.models:[]).filter(o=>o.visibility===void 0||o.visibility==="list").sort((o,r)=>{let i=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(o=>{let r=typeof o.slug=="string"?o.slug:typeof o.id=="string"?o.id:"";if(!r)return[];let i=typeof o.display_name=="string"&&o.display_name.trim()?o.display_name.trim():Gn(r),s=Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let c=d;return typeof c.effort!="string"?[]:[{effort:c.effort,...typeof c.description=="string"?{description:c.description}:{}}]}):void 0,a=Array.isArray(o.service_tiers)?o.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let c=d;return typeof c.id!="string"?[]:[{id:c.id,label:typeof c.name=="string"?c.name:c.id,...typeof c.description=="string"?{description:c.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof o.default_reasoning_level=="string"?{defaultReasoningLevel:o.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function Zl(n,e){let t=JSON.parse(n),o=t.key==="modelRoles"&&t.value&&typeof t.value=="object"&&"default"in t.value?t.value.default:t.modelRoles?.value?.default;if(typeof o!="string"||!o.trim())return[qt];let r=o.trim(),i=r.split("/").pop()||r,s;if(e){let a=JSON.parse(e);a.key==="defaultThinkingLevel"&&typeof a.value=="string"&&a.value.trim()&&(s=a.value.trim())}return[{id:"",label:Gn(i),source:"cli",...s?{defaultReasoningLevel:s}:{}}]}function ep(n,e,t){let[o]=Zl(n,e),r=tp(n),i=JSON.parse(t),s=Array.isArray(i.models)?i.models:[],a=s.flatMap(w=>{let g=typeof w.provider=="string"?w.provider.trim():"",S=typeof w.id=="string"?w.id.trim():"",b=typeof w.selector=="string"&&w.selector.trim()?w.selector.trim():g&&S?`${g}/${S}`:"";if(!g||!S||!b)return[];let h=Array.isArray(w.thinking)?w.thinking.flatMap(p=>typeof p=="string"&&p.trim()?[{effort:p.trim()}]:[]):[];return b===r?[{...o??qt,isDefault:!0,upstreamProvider:g,...h.length>0?{supportedReasoningLevels:h}:{}}]:[{id:b,label:Gn(S),source:"cli",upstreamProvider:g,...h.length>0?{supportedReasoningLevels:h}:{}}]}),d=s.find(w=>(typeof w.selector=="string"?w.selector.trim():typeof w.provider=="string"&&typeof w.id=="string"?`${w.provider.trim()}/${w.id.trim()}`:"")===r),c=Array.isArray(d?.thinking)?d.thinking.flatMap(w=>typeof w=="string"&&w.trim()?[{effort:w.trim()}]:[]):[],y={...o??qt,isDefault:!0,...r?.includes("/")?{upstreamProvider:r.split("/")[0]}:{},...c.length>0?{supportedReasoningLevels:c}:{}};return a.some(w=>w.isDefault)?fn(a):fn([y,...a])}function qr(n,e){let t=new Map(e.map(r=>[r.id,r])),o=new Map(e.map(r=>[Vs(r.label),r]));return n.map(r=>{if(r.upstreamProvider!=="openai-codex"||(r.speedTiers?.length??0)>0)return r;let i=r.id.includes("/")?r.id.slice(r.id.indexOf("/")+1):r.id,s=(i?t.get(i):void 0)??o.get(Vs(r.label));return s?.speedTiers?.length?{...r,speedTiers:s.speedTiers}:r})}function tp(n){let e=JSON.parse(n),t=e.key==="modelRoles"&&e.value&&typeof e.value=="object"&&"default"in e.value?e.value.default:e.modelRoles?.value?.default;return typeof t=="string"&&t.trim()?t.trim():void 0}function Ws(){return["low","medium","high","xhigh","max"].map(n=>({effort:n}))}function np(n){let e=n.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return fn(e.map(t=>({id:t,label:Gn(t),source:"cli"})))}function Gn(n){if(!n)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"},t=n.replace(/-\d{8,}$/,"");if(e[n])return e[n];if(e[t])return e[t];let o=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(o){let i=o[1]==="sonnet"?"Sonn":sp(o[1]),s=o[2]&&o[3]?` ${o[2]}.${o[3]}`:"";return`${i}${s}${o[4]?" Fast":""}`}let r=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark|luna|sol|terra))?$/);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}`:r[3]==="luna"?`GPT ${i} Luna`:r[3]==="sol"?`GPT ${i} Sol`:r[3]==="terra"?`GPT ${i} Terra`:`GPT ${i}`}return t}async function Ks(n="copilot"){let e=await Jt(n,["help","config"]),t=Xl(e);return t.length>1?t:[zn]}async function Lr(n="omp"){let[e,t,o]=await Promise.all([Jt(n,["config","get","modelRoles","--json"],1e4),Jt(n,["config","get","defaultThinkingLevel","--json"],1e4),Jt(n,["models","--json"],3e4)]);return ep(e,t,o)}async function Hs(n="codex"){let e=await Jt(n,["debug","models"]).catch(async()=>{let o=process.env.CODEX_HOME||pt(Fn(),".codex");return Xs(pt(o,"models_cache.json"))}),t=Yl(e);return t.length>0?fn([...t,...Un]):Un}async function Qs(n="claude"){let e=pt(Fn(),".claude"),t=[pt(Fn(),".claude","stats-cache.json"),pt(Fn(),".claude","settings.json"),pt(Fn(),".claude.json"),pt(e,"cache","changelog.md")],[o,r,i]=await Promise.all([Jt(n,["--help"]).catch(()=>""),Jt(n,["--version"]).catch(()=>""),op(e).catch(()=>[])]),s=ip([...t,...i]),a=await Promise.all(s.map(c=>Xs(c).catch(()=>""))),d=np([o,r,...a].join(`
172
+ `));return fn([...Bo,...d])}function Jt(n,e,t=5e3){return new Promise((o,r)=>{Wl(n,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}o(s)})})}async function Xs(n){return Vl(n,"utf-8")}async function op(n){let e=[pt(n,"projects"),pt(n,"telemetry")],t=[];for(let o of e)await Ys(o,t,4);return t.sort((o,r)=>r.mtimeMs-o.mtimeMs).slice(0,80).map(o=>o.path)}async function Ys(n,e,t){if(t<0)return;let o;try{o=await Kl(n,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async r=>{let i=pt(n,r.name);if(r.isDirectory()){await Ys(i,e,t-1);return}if(!(!r.isFile()||!rp(r.name)))try{let s=await Hl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function rp(n){return n.endsWith(".json")||n.endsWith(".jsonl")||n.endsWith(".md")||n.endsWith(".txt")}function fn(n){let e=new Set,t=[];for(let o of n)e.has(o.id)||(e.add(o.id),t.push(o));return t}function ip(n){return[...new Set(n)]}function sp(n){return n.charAt(0).toUpperCase()+n.slice(1)}function Vs(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}var Jo=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,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){t=i;break}}let o=t>=0?t+1:0,r=this.activeJobs.size+o+1;return this.queue.splice(o,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(o=>o.threadId===e&&(!t||t(o)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,o){let r=this.bufferEvent(t,e);for(let i of this.listeners)i(r,t,o)}bufferEvent(e,t){let o=this.eventBuffers.get(e);o||(o={events:[],nextSeq:0},this.eventBuffers.set(e,o));let r={...t,seq:o.nextSeq++};return o.events.push(r),o.events.length>1e4&&o.events.splice(0,o.events.length-1e4),r}getBufferedEvents(e,t=-1){let o=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!o)return null;let s=t<0?o.events:o.events.filter(a=>a.seq>t);return{jobId:e,events:s,currentSeq:o.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,t,o){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[t]+=o}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let o=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,o)}cancelJob(e){let t=this.activeProcesses.get(e),o=this.activeJobs.get(e);return!t||!o?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),o.status="error",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:"Cancelled by user",cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}cancelAll(){let e=[...this.activeJobs.values(),...this.queue];this.queue=[];for(let t of e)this.activeProcesses.get(t.id)?.kill("SIGTERM"),this.activeProcesses.delete(t.id),this.activeJobs.delete(t.id),t.status="error",t.error="Cancelled by user",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);return e}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 t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let o of t)try{o.kill("SIGTERM")}catch{}await Promise.all(t.map(o=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};o.on("exit",s),o.on("error",s),setTimeout(()=>{if(!i){try{o.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let o of this.cleanupTimers.values())clearTimeout(o);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(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),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)})}}};function Wn(n,e){return n?.projectId===e.projectId&&n.version===e.version&&n.restartMode===e.restartMode}function qo(n){return(Array.isArray(n)?n[0]:n)?.split(",")[0]?.trim()||void 0}function Fr(n){if(!n)return null;try{let e=new URL(n);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Zs(n){let e=Fr(qo(n.origin));if(e)return e;let t=Fr(qo(n.referer));if(t)return t;let o=qo(n["x-forwarded-host"]);if(!o)return null;let r=qo(n["x-forwarded-proto"])==="https"?"https":"http";return Fr(`${r}://${o}`)}function ea(n,e,t=5){let o=(d,c)=>(c.completedAt??c.startedAt)-(d.completedAt??d.startedAt),r=[...n].sort(o).slice(0,t),i=n.filter(d=>d.status==="applied"||d.status==="failed").sort(o).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,c)=>c.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,c)=>(d[c.status]=(d[c.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{mkdir as ap,readFile as ta,realpath as dp,writeFile as cp}from"fs/promises";import{join as Lo}from"path";async function zr(n){return dp(n).catch(()=>n)}function na(n){return Lo(n,".popmelt","store.json")}function lp(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function Ur(n){let e=await zr(n);try{let t=JSON.parse(await ta(na(e),"utf8"));return lp(t)?t:null}catch{return null}}async function pp(n){let e=await zr(n),t=await Ur(e);if(t)return t;let o;for(let r of[Lo(e,".popmelt","memory","manifest.json"),Lo(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await ta(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){o=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${o??zt(e)}`,createdAt:new Date().toISOString()}}async function Fo(n){let e=await zr(n),t=await Ur(e);if(t)return t;let o=await pp(e),r=Lo(e,".popmelt");await ap(r,{recursive:!0});try{return await cp(na(e),`${JSON.stringify(o,null,2)}
173
+ `,{encoding:"utf8",flag:"wx"}),o}catch(i){let s=await Ur(e);if(s)return s;throw i}}import{createHash as zo,randomUUID as yp}from"crypto";import{mkdir as Kn,readFile as Lt,writeFile as hn}from"fs/promises";import{dirname as Go,extname as Ip,join as Xe}from"path";var up={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 mp(n){let e=typeof n=="string"?n:(()=>{try{return JSON.stringify(n)}catch{return String(n??"")}})();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 oa(n,e){let t=e??mp(n);return{kind:t,...up[t]}}import{createHash as fp,randomUUID as hp}from"crypto";var ra=n=>`${n}-${hp()}`;function Gr(n,...e){return`${n}-${fp("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Wr(n){return{schemaVersion:1,submissionIds:[ra("submission")],jobId:n.jobId,threadId:n.threadId,artifactIds:[...new Set(n.artifactIds??[])]}}function Vn(n,e=[],t){return{...n,outcomeId:n.outcomeId??ra("outcome"),imprintEvidenceIds:[...new Set([...n.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function ia(n){try{return new URL(n).pathname||"/"}catch{return"/"}}function gp(n){let e=[];for(let t of n){if(t.anchor.type==="opaque"){let d=t.anchor;e.some(c=>c.anchor.type==="opaque"&&c.anchor.adapter===d.adapter&&c.anchor.key===d.key)||e.push(t);continue}let o=t.anchor,r=new Set([o.runtimeSelector,o.structuralSelector,...o.legacySelectors??[]].filter(d=>!!d));if(r.size===0)continue;let i=e.filter(d=>d.anchor.type==="dom"&&d.anchor.pathname===o.pathname&&[d.anchor.runtimeSelector,d.anchor.structuralSelector,...d.anchor.legacySelectors??[]].some(c=>!!(c&&r.has(c)))),s=o.runtimeSelector,a=o.structuralSelector;for(let d of i)d.anchor.type==="dom"&&(s??=d.anchor.runtimeSelector,a??=d.anchor.structuralSelector,e.splice(e.indexOf(d),1));e.push({anchor:{type:"dom",pathname:o.pathname,...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})}return e}function Vr(n,e=[]){let t=ia(n.url),o=[],r=(i,s,a)=>{!s&&!a||o.push({anchor:{type:"dom",pathname:i||"/",...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})};for(let i of n.annotations){if(i.target){o.push({anchor:{type:"opaque",adapter:i.target.adapter,key:i.target.key}});continue}i.linkedSelector&&r(i.pathname??t,i.linkedSelector,i.elements[0]?.selector)}for(let i of n.styleModifications)r(i.pathname??t,i.selector,i.durableSelector);for(let i of n.textModifications??[])r(i.pathname??t,i.selector,i.durableSelector);for(let i of n.domModifications??[])r(i.pathname??t,i.selector,i.durableSelector);return o.length===0&&e.length>0&&r(t,e.find(i=>i.includes("[data-pm=")),e.find(i=>!i.includes("[data-pm="))),gp(o)}function sa(n){return Vr(n).flatMap(e=>{if(e.anchor.type==="opaque")return[`${e.anchor.adapter}:${e.anchor.key}`];let t=e.anchor.structuralSelector??e.anchor.runtimeSelector;return t?[`${e.anchor.pathname}:${t}`]:[]})}function aa(n,e){let t=ia(n.url);return[...new Set((e??[]).map(o=>`${t}:${o}`))]}function da(n,e){return[...new Set([`screenshot:${e}`,...n.annotations.map(t=>`annotation:${t.id}`),...n.annotations.flatMap(t=>(t.attachments??[]).map(o=>`attachment:${o.id}`))])]}function Uo(n,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Gr("submission",n,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:n,artifactIds:[...(e.annotationIds??[]).map(o=>`annotation:${o}`),...e.screenshotPath?[Gr("artifact",n,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Gr("outcome",n,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Kr(n){let e=n.lifecycleVersion!==1;n.lifecycleVersion=1;for(let t of n.messages)e=Uo(n.id,t)||e;return e}function ca(n){let e=n.messages.at(-1),t=[...n.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:n.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:n.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let o=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:n.id,status:o?"waiting_input":"resolved",label:o?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var wp={version:1,threads:{}},la=["feedbackContext","annotationSnapshot","requestItems","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Hn={version:2,updatedAt:0,files:{},activeWorkspaceGeneration:0};function Yr(n){if(!n.startsWith("/"))return{pathname:"/",selector:n};let e=n.indexOf(":");return e<0?{pathname:"/",selector:n}:{pathname:n.slice(0,e)||"/",selector:n.slice(e+1)}}function Ft(n){return n.type==="opaque"?[n.key,...n.legacyKeys??[]]:[n.runtimeSelector,n.structuralSelector,...n.legacySelectors??[]].filter(e=>!!e)}function Hr(n){return n.type==="opaque"?Ft(n).map(e=>`${n.adapter}:${e}`):Ft(n).map(e=>`${n.pathname}:${e}`)}function Xn(n){if(n.length===0)return null;if(n[0].startsWith("codex-session:")){let s=n.filter(a=>a.startsWith("codex-session:")).map(a=>a.slice(14)).filter(Boolean);return s[0]?{anchor:{type:"opaque",adapter:"codex-session",key:s[0],...s.length>1?{legacyKeys:s.slice(1)}:{}}}:null}let e=n.map(Yr),t=e[0].pathname,o=e.filter(s=>s.pathname===t).map(s=>s.selector);if(o.length===0)return null;let r=o.find(s=>s.includes("[data-pm=")),i=o.find(s=>s!==r);return{anchor:{type:"dom",pathname:t,...r?{runtimeSelector:r}:{},...i?{structuralSelector:i}:{},...!r&&!i&&o[0]?{structuralSelector:o[0]}:{}}}}function Qr(n,e=[],t=[]){if(t.length>0)return t.filter(o=>Ft(o.anchor).length>0);if(n.length===1){let o=Xn([n[0],...e]);return o?[o]:[]}return[...new Set(n)].flatMap(o=>{let r=Xn([o]);return r?[r]:[]})}function Xr(n,e=Date.now()){return{id:`target-${yp()}`,anchor:n.anchor,createdAt:e,updatedAt:e}}function Qn(n,e){if(n.anchor.type!==e.anchor.type||n.anchor.type==="opaque"&&e.anchor.type==="opaque"&&n.anchor.adapter!==e.anchor.adapter||n.anchor.type==="dom"&&e.anchor.type==="dom"&&n.anchor.pathname!==e.anchor.pathname)return null;if(n.anchor.type==="opaque"&&e.anchor.type==="opaque"){let i=new Set(Ft(e.anchor));return Ft(n.anchor).some(s=>i.has(s))?["adapter_key"]:null}if(n.anchor.type!=="dom"||e.anchor.type!=="dom")return null;let t=[];n.anchor.runtimeSelector&&n.anchor.runtimeSelector===e.anchor.runtimeSelector&&t.push("runtime_selector"),n.anchor.structuralSelector&&n.anchor.structuralSelector===e.anchor.structuralSelector&&t.push("structural_selector");let o=new Set(Ft(e.anchor));return Ft(n.anchor).some(i=>o.has(i))?(t.length===0&&t.push("legacy_selector"),t):null}function vp(n,e){return Qn(n,e)!==null}function bp(n){return JSON.stringify(n,null,2)}function xp(n){return Object.fromEntries(la.flatMap(e=>n[e]===void 0?[]:[[e,n[e]]]))}function Sp(n){let e={...n};for(let t of la)delete e[t];return e}function gn(n){let e=n;if(n.error){let t=oa(n.error,n.errorKind);(n.error!==t.message||n.errorKind!==t.kind||n.responseText!==void 0)&&(e={...n,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=an(e.result,!1),o=an(e.turn?.result,!1);(t!==e.result||o!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...o?{result:o}:{}}}:{}})}return e}var Wo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();this.continuationChain=Promise.resolve();let t=Xe(e,".popmelt");this.legacyFilePath=Xe(t,"threads.json"),this.threadsDir=Xe(t,"threads"),this.indexPath=Xe(this.threadsDir,"index.json"),this.artifactsDir=Xe(t,"artifacts","thread-messages"),this.mediaDir=Xe(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Lt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[r,i]of Object.entries(e.files)){let s=await this.readThread(Xe(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let o=!1;for(let r of Object.values(t))o=Kr(r)||o;return o=this.migrateTargetBindings()||o,o&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Lt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,o])=>[t,{...o,messages:o.messages.map(gn)}]))},this.index={...Hn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Kr(t);return this.migrateTargetBindings(),await this.persistAll(),this.cache}}catch{}return this.cache={...wp,threads:{}},this.index={...Hn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async isTargetBindingContinuationEligible(e,t){let o=await this.load(),r=this.getActiveWorkspaceGeneration(),i=o.threads[e],s=i?.targetBindings?.find(c=>c.id===t);if(!i||!s||i.archivedAt!==void 0||(i.workspaceGeneration??0)!==r)return!1;let a={anchor:s.anchor},d=Object.values(o.threads).flatMap(c=>c.archivedAt!==void 0?[]:(c.workspaceGeneration??0)!==r?[]:(c.targetBindings??[]).filter(y=>vp(y,a)));return d.length===1&&d[0].id===t}async findContinuationThread(e,t,o=[],r=[],i){return(await this.findContinuationTarget(e,o,r,t,i)).match?.thread??null}async findContinuationTarget(e,t,o,r,i){let s=await this.load(),a=this.getActiveWorkspaceGeneration(),d=r?s.threads[r]:void 0,c=r?d?d.archivedAt!==void 0?"archived":(d.workspaceGeneration??0)!==a?"stale_generation":void 0:"missing_thread":void 0,y=d&&d.archivedAt===void 0&&(d.workspaceGeneration??0)===a,w=Qr(e,y?t:[],o);if(w.length!==1)return{match:null,decision:{action:"created",basis:w.length>1?"batch":"new_target",...c?{rejectedPreference:c}:{},matchCount:0}};if(y){let b=d.targetBindings??[];if(i){let p=b.find(v=>v.id===i);if(!p)return{match:null,decision:{action:"created",basis:"new_target",rejectedPreference:"missing_binding",matchCount:0}};let I=Qn(p,w[0]);return I?{match:{thread:d,binding:p},decision:{action:"continued",basis:"preferred",evidence:["binding_id",...I],matchCount:1}}:{match:null,decision:{action:"created",basis:"new_target",rejectedPreference:"observation_mismatch",matchCount:0}}}if(b.length===1){let p=b[0],I=Qn(p,w[0]);return{match:{thread:d,binding:p},decision:{action:"continued",basis:"preferred",...I?{evidence:I}:{},matchCount:1}}}let h=b.flatMap(p=>{let I=Qn(p,w[0]);return I?[{binding:p,evidence:I}]:[]});if(h.length===1){let p=h[0];return{match:{thread:d,binding:p.binding},decision:{action:"continued",basis:"preferred",evidence:p.evidence,matchCount:1}}}return{match:null,decision:{action:"created",basis:h.length>1?"ambiguous":"new_target",...h.length===0?{rejectedPreference:"observation_mismatch"}:{},matchCount:h.length}}}let g=Object.values(s.threads).flatMap(b=>b.archivedAt!==void 0?[]:(b.workspaceGeneration??0)!==a?[]:(b.targetBindings??[]).flatMap(h=>{let p=Qn(h,w[0]);return p?[{thread:b,binding:h,evidence:p}]:[]})),S=g.length===1?g[0]:null;return{match:S,decision:S?{action:"continued",basis:"unique_match",evidence:S.evidence,...c?{rejectedPreference:c}:{},matchCount:1}:{action:"created",basis:g.length>1?"ambiguous":"new_target",...c?{rejectedPreference:c}:{},matchCount:g.length}}}async createThread(e,t,o=[]){await this.load();let r=Qr(t,[],o);return this.createThreadRecord(e,t,r)}async createThreadRecord(e,t,o){let r=await this.load(),i={id:e,lifecycleVersion:1,workspaceGeneration:this.getActiveWorkspaceGeneration(),createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,targetBindings:o.map(s=>Xr(s)),messages:[]};return r.threads[e]=i,await this.persistThread(i),i}async findOrCreateContinuationThread(e,t,o,r=[],i=[],s){return this.serializeContinuationMutation(async()=>{await this.load();let a=Qr(e,r,i),d=await this.findContinuationTarget(e,r,a,o,s),c=d.match;if(c)return c.binding.anchor=a[0].anchor,c.binding.updatedAt=Date.now(),c.thread.updatedAt=Date.now(),await this.persistThread(c.thread),{thread:c.thread,decision:d.decision,targetBindings:[c.binding]};let y=await this.createThreadRecord(t,e,a);return{thread:y,decision:d.decision,targetBindings:y.targetBindings??[]}})}serializeContinuationMutation(e){let t=this.continuationChain.then(e);return this.continuationChain=t.then(()=>{},()=>{}),t}async appendMessage(e,t){let r=(await this.load()).threads[e];r&&(Uo(e,t),r.messages.push(gn(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;Uo(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,gn(t)):r.messages.push(gn(t)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,t,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(a=>a.jobId===t);if(s.length===0)return!1;for(let a of s)if(Object.assign(a,o),a.error){let d=gn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,t,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(a=>a.role==="assistant"&&a.jobId===t);return s?(Object.assign(s,o),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,t){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of t)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async addElementSelectorAliases(e,t){let r=(await this.load()).threads[e];if(!r||r.elementIdentifiers.length!==1)return;let i=r.targetBindings?.[0],s=Xn(t);!i||!s||(i.anchor=s.anchor,i.updatedAt=Date.now(),r.updatedAt=Date.now(),await this.persistThread(r))}async archiveThread(e){let o=(await this.load()).threads[e];return o?(o.archivedAt=o.archivedAt??Date.now(),o.updatedAt=Date.now(),await this.persistThread(o),!0):!1}async advanceWorkspaceGeneration(){return this.serializeContinuationMutation(async()=>{await this.load();let e=this.index??{...Hn,files:{}},t=(e.activeWorkspaceGeneration??0)+1;return e.activeWorkspaceGeneration=t,e.updatedAt=Date.now(),this.index=e,this.writeChain=this.writeChain.then(async()=>{await Kn(this.threadsDir,{recursive:!0}),await hn(this.indexPath,JSON.stringify(e,null,2))}),await this.writeChain,t})}async listRecent(e=5){let t=await this.load(),o=this.getActiveWorkspaceGeneration(),r=Object.values(t.threads).filter(s=>s.archivedAt===void 0&&(s.workspaceGeneration??0)===o),i=new Map;for(let s of r)for(let a of s.targetBindings??[]){let d=`${s.id}:${a.id}`;for(let c of Hr(a.anchor)){let y=i.get(c)??new Set;y.add(d),i.set(c,y)}}return r.sort((s,a)=>a.updatedAt-s.updatedAt),r.slice(0,e).map(s=>{let a=s.messages.find(m=>m.role==="human"),d=s.messages.find(m=>m.annotationSnapshot?.color)?.annotationSnapshot?.color,c=a?.feedbackSummary||"[thread]",w=a?.requestItems?.find(m=>m.kind==="changes"&&m.annotationNumber!==void 0)?.annotationNumber,g=s.messages.filter(m=>m.role==="assistant"),S=m=>{if(m.role!=="assistant")return;if(m.question)return m.question;let f=m.imprintSummary?.grounding;if(f?.question&&!m.imprintSummary?.resolvedAction)return f.question},b=s.messages.findLastIndex(m=>!!S(m)),h=s.messages.findLastIndex(m=>m.role==="human"),p=b>h?S(s.messages[b]):void 0,I=s.messages.at(-1)?.role,v=Array.from(new Set(s.messages.slice(0,Math.max(0,h)).filter(m=>m.role==="assistant"&&!!m.jobId).map(m=>m.jobId))),u=g.some(m=>!!m.responseText||!!m.question||!!m.result||!!m.memoryReviewCard||!!m.memoryReceipt),x=g.some(m=>!!m.error);return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:c,messageCount:s.messages.length,hasReply:u,hasError:x,lastMessageRole:I,pendingQuestion:p,acknowledgedJobIds:v,elementIdentifiers:s.elementIdentifiers,elementSelectorAliases:[...new Set([...s.elementSelectorAliases??[],...(s.targetBindings??[]).flatMap(m=>Hr(m.anchor))])],targetBindings:s.targetBindings?.map(m=>({...m,continuationEligible:Hr(m.anchor).every(f=>(i.get(f)?.size??0)===1)})),color:d,annotationNumber:w,lifecycle:ca(s)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let o of Object.values(e.threads)){if(o.archivedAt!==void 0)continue;let r=o.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=Vn(r.lifecycle);r.queued&&await this.updateMessage(o.id,r.jobId,{queued:!1}),await this.appendMessage(o.id,{role:"assistant",timestamp:Date.now(),jobId:r.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:i}),t+=1}return t}async getThreadHistory(e,t=6){let o=await this.getThread(e);return!o||o.messages.length===0?[]:o.messages.length<=t?o.messages:[o.messages[0],...o.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await Lt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let{version:o,messages:r,...i}=t,s=await Promise.all(r.map(async({detailArtifact:a,...d})=>{let c={};if(a?.path)try{let y=await Lt(Xe(Go(this.legacyFilePath),a.path),"utf8");zo("sha256").update(y).digest("hex")===a.sha256&&(c=JSON.parse(y))}catch{}return gn({...d,...c})}));return{...i,messages:s}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=xp(e),o=Sp(e);if(Object.keys(t).length===0)return o;let r=bp(t),i=zo("sha256").update(r).digest("hex"),s=Xe("artifacts","thread-messages",`${i}.json`);await Kn(this.artifactsDir,{recursive:!0});try{await Lt(Xe(Go(this.legacyFilePath),s),"utf8")}catch{await hn(Xe(Go(this.legacyFilePath),s),r)}return{...o,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async o=>{if(Go(o)===this.mediaDir)return o;try{let r=await Lt(o),i=zo("sha256").update(r).digest("hex"),s=Xe(this.mediaDir,`${i}${Ip(o)||".bin"}`);await Kn(this.mediaDir,{recursive:!0});try{await Lt(s)}catch{await hn(s,r)}return s}catch{return o}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([o,r])=>[o,await t(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([o,r])=>[o,await Promise.all(r.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([o,r])=>[o,await Promise.all(r.map(async i=>({...i,path:await t(i.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await Kn(this.threadsDir,{recursive:!0});let t=this.index??{...Hn,files:{}},o=t.files[e.id]??`${zo("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 hn(Xe(this.threadsDir,o),JSON.stringify(i,null,2)),t.files[e.id]=o,t.updatedAt=Date.now(),this.index=t,await hn(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}getActiveWorkspaceGeneration(){return this.index?.activeWorkspaceGeneration??0}migrateTargetBindings(){if(!this.cache)return!1;let e=!1;for(let t of Object.values(this.cache.threads)){if(t.targetBindings){for(let i of t.targetBindings){if(i.anchor.type!=="dom"||!i.anchor.structuralSelector?.startsWith("codex-session:"))continue;let s=Xn([i.anchor.structuralSelector]);s&&(i.anchor=s.anchor,i.updatedAt=Date.now(),e=!0)}continue}let o=(t.elementIdentityIds??[]).flatMap(i=>this.index?.elementIdentities?.[i]?.aliases??[]),r=t.elementIdentifiers.flatMap(i=>{if(i.startsWith("codex-session:")){let g=Xn([i]);return g?[Xr(g)]:[]}let s=Yr(i),a=t.elementIdentifiers.length===1?[...t.elementSelectorAliases??[],...o].map(Yr).filter(g=>g.pathname===s.pathname).map(g=>g.selector):[],d=[s.selector,...a].find(g=>g.includes("[data-pm=")),c=[s.selector,...a].find(g=>!g.includes("[data-pm=")),y=new Set([d,c].filter(Boolean)),w=[...new Set(a)].filter(g=>!y.has(g));return[Xr({anchor:{type:"dom",pathname:s.pathname,...d?{runtimeSelector:d}:{},...c?{structuralSelector:c}:{},...w.length>0?{legacySelectors:w}:{}}})]});t.targetBindings=r,delete t.elementIdentityIds,delete t.elementSelectorAliases,e=!0}return this.index?.elementIdentities&&(delete this.index.elementIdentities,e=!0),e}isThreadInActiveWorkspace(e){if(!e)return!0;let t=this.cache?.threads[e];return!!t&&t.archivedAt===void 0&&(t.workspaceGeneration??0)===this.getActiveWorkspaceGeneration()}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 Kn(this.threadsDir,{recursive:!0}),this.index=this.index??{...Hn,files:{}},await hn(this.indexPath,JSON.stringify(this.index,null,2)))}}};import{mkdir as Tp,open as kp,readFile as Pp,rename as Rp,unlink as Ap}from"fs/promises";import{dirname as Mp,join as jp}from"path";var pa={schemaVersion:1,theme:"auto",updatedAt:null};function ua(n){return n==="light"||n==="dark"||n==="auto"?n:null}async function Ep(n,e){await Tp(Mp(n),{recursive:!0});let t=`${n}.${process.pid}.${Date.now()}.tmp`;try{let o=await kp(t,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
174
+ `,"utf8"),await o.sync()}finally{await o.close()}await Rp(t,n)}catch(o){throw await Ap(t).catch(()=>{}),o}}var Vo=class{constructor(e){this.path=jp(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Pp(this.path,"utf8")),t=ua(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...pa}}}catch{return{exists:!1,preferences:{...pa}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Ep(this.path,t),t}};function ma(n){return ua(n)!==null}var Fp=1111,Up=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],zp=1800*1e3,Gp=3600*1e3,ha=45e3,Wp=5e3,Vp=1e4,Kp=2*1024*1024;function ga(n){return n.length<=1?n[0]??"":["The developer sent these queued steering messages while you were working:","",...n.map((e,t)=>`${t+1}. ${e}`)].join(`
175
+ `)}function Yn(n){return[...new Set(n.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function ya(n){let e=n.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let t=n[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let o=n.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return o?.imprintSummary?.grounding?[o.imprintSummary.grounding.explanationId]:[]}function Hp(n,e){if(e.size===1)return[...n].reverse().find(t=>{let o=t.imprintSummary;return t.role==="assistant"&&!!o?.grounding&&!o?.resolvedAction&&e.has(o.grounding.explanationId)})}function xa(n){if(!n)return!1;try{let e=new URL(n);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Qp(n,e,t){let o=[...t];for(let r of n)if(r.type==="tool_use"){let i=r.tool||"",s=r.file??void 0,a=r.content??void 0,d=s?s.split("/").pop()??s:void 0,c;switch(i){case"Read":c=d?`Reading ${d}`:"Reading file";break;case"Edit":c=d?`Editing ${d}`:"Editing file";break;case"Write":c=d?`Writing ${d}`:"Writing file";break;case"Bash":c=a?a.split(`
176
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":c="Searching files";break;case"Grep":c="Searching code";break;case"WebFetch":c="Fetching page";break;case"WebSearch":c="Searching web";break;default:c=i?`Using ${i}`:"tool";break}let y=s??a??void 0,w=s?Zr(s)?s:Lp(e,s):void 0,g=o[o.length-1];g&&g.kind==="tool_group"&&g.tool===i?g.items.push({label:c,detail:y,...w?{filePath:w}:{}}):o.push({kind:"tool_group",tool:i,items:[{label:c,detail:y,...w?{filePath:w}:{}}]})}return o}function Xp(n,e){if(n.processedIds.length===0&&n.success)return"No accepted decisions were ready for model projection.";if(n.success&&n.proposalId)return"";let t=[];return n.success?t.push("Model suggestion ready."):t.push("Model projection failed."),n.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.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"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),n.error&&(t.push(""),t.push(`Error: ${n.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
177
+ `)}function Yp(n,e=96){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Ia(n){let e=n.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${a}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}${d.token?` [${d.token}]`:""}`)}),t=(n.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),o=(n.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=n.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;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,...o,...t,...r].map(s=>Yp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function Zp(n,e){let t=n.headers.origin;xa(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function N(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}var eu=16384,tu=131072;async function Fe(n,e=eu){let t=[],o=0;for await(let i of n){let s=typeof i=="string"?Buffer.from(i):i;if(o+=s.length,o>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let r=JSON.parse(Buffer.concat(t).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function nu(n,e){let t=[],o=0;for await(let r of n){let i=typeof r=="string"?Buffer.from(r):r;if(o+=i.length,o>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function ou(n,e){let t=n.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function ru(n,e){if(!n)return e;let t=n.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,o,r,i]=t;return`\x1B[38;2;${parseInt(o,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Zn(n,e){try{n.res.write(`event: ${e.type}
178
178
  data: ${JSON.stringify(e)}
179
179
 
180
- `)}catch{}}function yn(n){return n==="claude"||n==="codex"||n==="copilot"||n==="omp"?n:void 0}async function In(n){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),o=await fetch(`http://127.0.0.1:${n}/status`,{signal:e.signal});return clearTimeout(t),o.ok?await o.json():null}catch{return null}}var ya=3e3;function ru(n){let e=Array.isArray(n.activeJobs)?n.activeJobs:[],t=n.leases&&typeof n.leases=="object"?n.leases:void 0;return n.activeJob!=null||e.length>0||typeof n.queueDepth=="number"&&n.queueDepth>0||typeof n.projectionQueueDepth=="number"&&n.projectionQueueDepth>0||typeof t?.count=="number"&&t.count>0}async function iu(n,e){for(let t=n;t<n+9;t++){let o=await In(t);if(o?.projectId!==e||o.restartMode!=="detached")continue;if(ru(o))throw new Error(`[Bridge] A detached bridge for this project is active on port ${t}. Stop its current work before starting an embedded bridge.`);if(!(await fetch(`http://127.0.0.1:${t}/shutdown`,{method:"POST"})).ok)throw new Error(`[Bridge] Could not replace the detached bridge for this project on port ${t}.`);let i=Date.now()+ya;for(;Date.now()<i;)if(await new Promise(s=>setTimeout(s,50)),!await In(t))return;throw new Error(`[Bridge] Detached bridge on port ${t} did not stop within ${ya/1e3}s.`)}}function su(n,e){return new Promise((t,o)=>{let r=s=>{n.removeListener("listening",i),o(s)},i=()=>{n.removeListener("error",r),t()};n.once("error",r),n.once("listening",i),n.listen(e,"127.0.0.1")})}async function ba(n={}){let e=new Date().toISOString(),t=n.port??Lp,o=n.projectRoot??process.cwd(),r=await Op(o).catch(()=>o),i=zt(r),s=await Fo(r),a=n.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=n.tempDir??it(Bp(),"popmelt-bridge"),c=n.maxTurns??40,I=n.maxBudgetUsd??1,v=[...n.allowedTools??Fp],g=n.claudePath??"claude",k=n.copilotPath??"copilot",b=n.ompPath??"omp",h=n.provider??"codex",p=n.timeoutMs,y=n.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,w=n.restartMode??"embedded";w==="embedded"&&await iu(t,i);let u=t,x={},m={claude:g,codex:"codex",copilot:k,omp:b};for(let[l,S]of Object.entries(m))try{let O=S.includes("/")?S:Ep("which",[S],{encoding:"utf-8"}).trim();x[l]={available:!0,path:O}}catch{x[l]={available:!1,path:null}}function f(l,S){return new Promise(O=>{let T=ua(S,["--version"],{stdio:["ignore","ignore","ignore"]}),C=!1,A=D=>{C||(C=!0,O(D))},q=setTimeout(()=>{T.kill("SIGTERM"),A(!0)},5e3);T.on("error",()=>{clearTimeout(q),A(!1)}),T.on("close",D=>{clearTimeout(q),A(D===0)})})}await Promise.all([(async()=>{x.claude&&(x.claude.models=x.claude.available&&x.claude.path?await Ks(x.claude.path).catch(()=>Bo):Bo)})(),(async()=>{x.codex&&(x.codex.models=x.codex.available&&x.codex.path?await Vs(x.codex.path).catch(()=>Un):Un)})(),(async()=>{x.copilot&&(x.copilot.models=x.copilot.available&&x.copilot.path?await Ws(x.copilot.path).catch(()=>[zn]):[zn])})(),(async()=>{x.omp&&(x.omp.models=x.omp.available?await qr(x.omp.path??b).catch(()=>[qt]):[qt])})()]),x.omp?.models&&x.codex?.models&&(x.omp.models=Jr(x.omp.models,x.codex.models));let M=null,$=()=>{if(!x.omp?.available)return Promise.resolve();if(M)return M;let l=x.omp.models;return M=qr(x.omp.path??b).then(S=>{x.omp&&(x.omp.models=Jr(S,x.codex?.models??[]))}).catch(()=>{x.omp&&!l?.length&&(x.omp.models=[qt])}).finally(()=>{M=null}),M},[E,F,Y]=await Promise.all([Er(r),_r(r),Cr(r,x.copilot?.path??k)]);x.claude&&(x.claude.mcp=E),x.codex&&(x.codex.mcp=F),x.copilot&&(x.copilot.mcp=Y),E.found&&E.name&&v.push(`mcp__${E.name}__*`),await _p(d,{recursive:!0}),Ia(d).catch(()=>{});let L=new Jo(1),R=new Co,J=new Mo(ma),W=null,ee=0,H=!1,ie=()=>{ee+=1,H=!1,W&&clearTimeout(W),W=null},P=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},j=()=>{if(w!=="detached"||J.size>0||H)return;H=!0;let l=++ee,S=Date.now()+Wp,O=()=>{if(l!==ee)return;if(J.size>0){ie();return}if(!(L.isRunning||L.depth>0||R.isRunning||R.depth>0)||Date.now()>=S){H=!1,W=setTimeout(P,50),W.unref?.();return}W=setTimeout(O,250),W.unref?.()};O()},B=new Set,_=new Wo(r),Q=await _.recoverInterruptedTurns();Q>0&&console.warn(`[Popmelt] Recovered ${Q} interrupted thread turn(s) from durable history.`);let de=new Po(r);de.sweep();let Z=new sn(r),se=new kt(r,i);try{let l=await se.store.migrateTopology();l.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${l.relationMutations} relation mutation(s)).`)}catch(l){console.warn(`[Popmelt] Imprint topology migration deferred: ${l instanceof Error?l.message:String(l)}`)}let xe=new Vo(r),qe=new xo(r),pe=new _o(r,{claudePath:g,provider:h,timeoutMs:p,loadProjectableDecisions:l=>Z.getProjectableDecisions(l),onEvent:l=>{for(let S of B)Zn(S,l)}}),Te=new go({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:_,memoryService:Z,imprintService:se,loadConcreteModel:()=>pe.loadModel()});Z.beginAutomaticInitialization({writerVersion:mt}).then(async l=>{l.state==="ready"?(await Z.migrateImprintSnapshot(),await Z.syncImprintGraph(),await pe.applyCanonicalEntries(await Z.getCanonicalModelEntries()),(h==="claude"||h==="codex")&&(await pe.getUnprojectedPatternDecisions()).length>0&&await bt({provider:h,reason:"Project accepted decisions that were waiting when the bridge restarted"})):l.state==="degraded"&&console.warn(`[\u22B9 ${u}] Product memory is degraded; legacy preview remains available: ${l.error}`)});let Ce=20,Ue=300*1e3,De=[];function st(){let l=Date.now()-Ue;for(;De.length>0&&(De[0].completedAt<l||De.length>Ce);)De.shift()}let Me=new Map;L.addListener((l,S,O)=>{for(let T of B)(!O||!T.sourceId||T.sourceId===O)&&Zn(T,l)}),R.addListener((l,S,O)=>{for(let T of B)(!O||!T.sourceId||T.sourceId===O)&&Zn(T,l)}),R.setProcessor(async l=>{let S=l.provider??h;try{let O=await pe.run({provider:S,model:l.model,threadId:l.threadId,presentationJobId:l.id,agentSettings:l.agentSettings});if(l.status==="cancelled")return;let T=await pe.loadRuns(),C=O.runId?T.runs.find(q=>q.id===O.runId):void 0;if(O.success&&O.proposalId){let q=await pe.findModelProposal(O.proposalId),D=await pe.loadModel(),z=q?ys(q,D):null;if(q&&z){let U=q.decisionIds.map(G=>({decisionId:G,status:"projected"}));await Z.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:z.map(G=>({path:G.path,value:G.value,decisionIds:G.decisionIds})),coverage:U}),await pe.applySelectedModelProposal(q.id,z.map(G=>({path:G.path,value:G.value})),z.map(G=>({group:G.path[0]==="rules"||G.path[0]==="components"||G.path[0]==="tokens"?G.path[0]:"model",label:G.label??G.id,detail:G.rationale,path:G.path,value:G.value})),"automatic")}}let A=Qp(O,C);if(l.threadId&&(await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:A,model:l.model,provider:S})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:A,model:l.model,provider:S})),O.success)l.status="done",l.result=A,R.broadcast({type:"done",jobId:l.id,success:!0,responseText:A,threadId:l.threadId},l.id,l.sourceId),De.push({id:l.id,status:"done",completedAt:Date.now(),threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st();else{if(l.status="error",l.error=O.error??"Projection failed",l.threadId){let q=`Model projection failed.
180
+ `)}catch{}}function yn(n){return n==="claude"||n==="codex"||n==="copilot"||n==="omp"?n:void 0}async function In(n){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),o=await fetch(`http://127.0.0.1:${n}/status`,{signal:e.signal});return clearTimeout(t),o.ok?await o.json():null}catch{return null}}var wa=3e3;function iu(n){let e=Array.isArray(n.activeJobs)?n.activeJobs:[],t=n.leases&&typeof n.leases=="object"?n.leases:void 0;return n.activeJob!=null||e.length>0||typeof n.queueDepth=="number"&&n.queueDepth>0||typeof n.projectionQueueDepth=="number"&&n.projectionQueueDepth>0||typeof t?.count=="number"&&t.count>0}async function su(n,e){for(let t=n;t<n+9;t++){let o=await In(t);if(o?.projectId!==e||o.restartMode!=="detached")continue;if(iu(o))throw new Error(`[Bridge] A detached bridge for this project is active on port ${t}. Stop its current work before starting an embedded bridge.`);if(!(await fetch(`http://127.0.0.1:${t}/shutdown`,{method:"POST"})).ok)throw new Error(`[Bridge] Could not replace the detached bridge for this project on port ${t}.`);let i=Date.now()+wa;for(;Date.now()<i;)if(await new Promise(s=>setTimeout(s,50)),!await In(t))return;throw new Error(`[Bridge] Detached bridge on port ${t} did not stop within ${wa/1e3}s.`)}}function au(n,e){return new Promise((t,o)=>{let r=s=>{n.removeListener("listening",i),o(s)},i=()=>{n.removeListener("error",r),t()};n.once("error",r),n.once("listening",i),n.listen(e,"127.0.0.1")})}async function Sa(n={}){let e=new Date().toISOString(),t=n.port??Fp,o=n.projectRoot??process.cwd(),r=await Dp(o).catch(()=>o),i=zt(r),s=await Fo(r),a=n.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=n.tempDir??it(Jp(),"popmelt-bridge"),c=n.maxTurns??40,y=n.maxBudgetUsd??1,w=[...n.allowedTools??Up],g=n.claudePath??"claude",S=n.copilotPath??"copilot",b=n.ompPath??"omp",h=n.provider??"codex",p=n.timeoutMs,I=n.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,v=n.restartMode??"embedded";v==="embedded"&&await su(t,i);let u=t,x={},m={claude:g,codex:"codex",copilot:S,omp:b};for(let[l,T]of Object.entries(m))try{let O=T.includes("/")?T:_p("which",[T],{encoding:"utf-8"}).trim();x[l]={available:!0,path:O}}catch{x[l]={available:!1,path:null}}function f(l,T){return new Promise(O=>{let k=fa(T,["--version"],{stdio:["ignore","ignore","ignore"]}),C=!1,A=D=>{C||(C=!0,O(D))},q=setTimeout(()=>{k.kill("SIGTERM"),A(!0)},5e3);k.on("error",()=>{clearTimeout(q),A(!1)}),k.on("close",D=>{clearTimeout(q),A(D===0)})})}await Promise.all([(async()=>{x.claude&&(x.claude.models=x.claude.available&&x.claude.path?await Qs(x.claude.path).catch(()=>Bo):Bo)})(),(async()=>{x.codex&&(x.codex.models=x.codex.available&&x.codex.path?await Hs(x.codex.path).catch(()=>Un):Un)})(),(async()=>{x.copilot&&(x.copilot.models=x.copilot.available&&x.copilot.path?await Ks(x.copilot.path).catch(()=>[zn]):[zn])})(),(async()=>{x.omp&&(x.omp.models=x.omp.available?await Lr(x.omp.path??b).catch(()=>[qt]):[qt])})()]),x.omp?.models&&x.codex?.models&&(x.omp.models=qr(x.omp.models,x.codex.models));let M=null,$=()=>{if(!x.omp?.available)return Promise.resolve();if(M)return M;let l=x.omp.models;return M=Lr(x.omp.path??b).then(T=>{x.omp&&(x.omp.models=qr(T,x.codex?.models??[]))}).catch(()=>{x.omp&&!l?.length&&(x.omp.models=[qt])}).finally(()=>{M=null}),M},[E,F,Y]=await Promise.all([Er(r),_r(r),Cr(r,x.copilot?.path??S)]);x.claude&&(x.claude.mcp=E),x.codex&&(x.codex.mcp=F),x.copilot&&(x.copilot.mcp=Y),E.found&&E.name&&w.push(`mcp__${E.name}__*`),await Cp(d,{recursive:!0}),va(d).catch(()=>{});let L=new Jo(1),R=new Co,J=new Mo(ha),W=null,ee=0,H=!1,ie=()=>{ee+=1,H=!1,W&&clearTimeout(W),W=null},P=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},j=()=>{if(v!=="detached"||J.size>0||H)return;H=!0;let l=++ee,T=Date.now()+Vp,O=()=>{if(l!==ee)return;if(J.size>0){ie();return}if(!(L.isRunning||L.depth>0||R.isRunning||R.depth>0)||Date.now()>=T){H=!1,W=setTimeout(P,50),W.unref?.();return}W=setTimeout(O,250),W.unref?.()};O()},B=new Set,_=new Wo(r),Q=await _.recoverInterruptedTurns();Q>0&&console.warn(`[Popmelt] Recovered ${Q} interrupted thread turn(s) from durable history.`);let de=new Po(r);de.sweep();let Z=new sn(r),se=new kt(r,i);try{let l=await se.store.migrateTopology();l.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${l.relationMutations} relation mutation(s)).`)}catch(l){console.warn(`[Popmelt] Imprint topology migration deferred: ${l instanceof Error?l.message:String(l)}`)}let xe=new Vo(r),qe=new xo(r),pe=new _o(r,{claudePath:g,provider:h,timeoutMs:p,loadProjectableDecisions:l=>Z.getProjectableDecisions(l),onEvent:l=>{for(let T of B)Zn(T,l)}}),Te=new go({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:_,memoryService:Z,imprintService:se,loadConcreteModel:()=>pe.loadModel()});Z.beginAutomaticInitialization({writerVersion:mt}).then(async l=>{l.state==="ready"?(await Z.migrateImprintSnapshot(),await Z.syncImprintGraph(),await pe.applyCanonicalEntries(await Z.getCanonicalModelEntries()),(h==="claude"||h==="codex")&&(await pe.getUnprojectedPatternDecisions()).length>0&&await bt({provider:h,reason:"Project accepted decisions that were waiting when the bridge restarted"})):l.state==="degraded"&&console.warn(`[\u22B9 ${u}] Product memory is degraded; legacy preview remains available: ${l.error}`)});let Ce=20,Ue=300*1e3,De=[];function st(){let l=Date.now()-Ue;for(;De.length>0&&(De[0].completedAt<l||De.length>Ce);)De.shift()}let Me=new Map;L.addListener((l,T,O)=>{for(let k of B)(!O||!k.sourceId||k.sourceId===O)&&Zn(k,l)}),R.addListener((l,T,O)=>{for(let k of B)(!O||!k.sourceId||k.sourceId===O)&&Zn(k,l)}),R.setProcessor(async l=>{let T=l.provider??h;try{let O=await pe.run({provider:T,model:l.model,threadId:l.threadId,presentationJobId:l.id,agentSettings:l.agentSettings});if(l.status==="cancelled")return;let k=await pe.loadRuns(),C=O.runId?k.runs.find(q=>q.id===O.runId):void 0;if(O.success&&O.proposalId){let q=await pe.findModelProposal(O.proposalId),D=await pe.loadModel(),z=q?Is(q,D):null;if(q&&z){let U=q.decisionIds.map(G=>({decisionId:G,status:"projected"}));await Z.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:z.map(G=>({path:G.path,value:G.value,decisionIds:G.decisionIds})),coverage:U}),await pe.applySelectedModelProposal(q.id,z.map(G=>({path:G.path,value:G.value})),z.map(G=>({group:G.path[0]==="rules"||G.path[0]==="components"||G.path[0]==="tokens"?G.path[0]:"model",label:G.label??G.id,detail:G.rationale,path:G.path,value:G.value})),"automatic")}}let A=Xp(O,C);if(l.threadId&&(await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:A,model:l.model,provider:T})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:A,model:l.model,provider:T})),O.success)l.status="done",l.result=A,R.broadcast({type:"done",jobId:l.id,success:!0,responseText:A,threadId:l.threadId},l.id,l.sourceId),De.push({id:l.id,status:"done",completedAt:Date.now(),threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st();else{if(l.status="error",l.error=O.error??"Projection failed",l.threadId){let q=`Model projection failed.
181
181
 
182
- ${l.error}`;await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:q,error:l.error,model:l.model,provider:S})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:q,error:l.error,model:l.model,provider:S})}R.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:l.error,provider:S,model:l.model},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:l.error,threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st()}}catch(O){if(l.status==="cancelled")return;if(l.status="error",l.error=O instanceof Error?O.message:String(O),l.threadId){let T=`Model projection failed.
182
+ ${l.error}`;await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:q,error:l.error,model:l.model,provider:T})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:q,error:l.error,model:l.model,provider:T})}R.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:l.error,provider:T,model:l.model},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:l.error,threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st()}}catch(O){if(l.status==="cancelled")return;if(l.status="error",l.error=O instanceof Error?O.message:String(O),l.threadId){let k=`Model projection failed.
183
183
 
184
- ${l.error}`;await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:T,error:l.error,model:l.model,provider:S})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:T,error:l.error,model:l.model,provider:S})}R.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:l.error,provider:S,model:l.model},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:l.error,threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st()}}),L.setProcessor(async l=>{let S=l,O=S._replyPrompt,T=S._replyText,C=S._replyImagePaths,A=l.provider??h,q=!!(l.surfacedProposalIds?.length&&O),D=!q&&!["synthesize","project_model"].includes(l.kind??"");l.threadId&&T!==void 0&&await _.updateMessage(l.threadId,l.id,{queued:!1});let z;if(l.threadId){let ne=await _.getThread(l.threadId);if(ne){for(let we=ne.messages.length-1;we>=0;we--)if(ne.messages[we].sessionId){z=ne.messages[we].sessionId;break}}}if(q&&(z=void 0),A==="omp"&&z)try{if(!Yr(z))throw new Error("not a session file");await wa(z)}catch{z=void 0}let U;if(z&&O){if(U=T??O,C&&C.length>0){U+=`
184
+ ${l.error}`;await _.updateMessage(l.threadId,l.id,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:k,error:l.error,model:l.model,provider:T})||await _.appendMessage(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:k,error:l.error,model:l.model,provider:T})}R.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:l.error,provider:T,model:l.model},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:l.error,threadId:l.threadId,annotationIds:l.annotationIds,color:"#000000",kind:"project_model"}),st()}}),L.setProcessor(async l=>{let T=l,O=T._replyPrompt,k=T._replyText,C=T._replyImagePaths,A=l.provider??h,q=!!(l.surfacedProposalIds?.length&&O),D=!q&&!["synthesize","project_model"].includes(l.kind??"");l.threadId&&k!==void 0&&await _.updateMessage(l.threadId,l.id,{queued:!1});let z;if(l.threadId){let ne=await _.getThread(l.threadId);if(ne){for(let we=ne.messages.length-1;we>=0;we--)if(ne.messages[we].sessionId){z=ne.messages[we].sessionId;break}}}if(q&&(z=void 0),A==="omp"&&z)try{if(!Zr(z))throw new Error("not a session file");await ba(z)}catch{z=void 0}let U;if(z&&O){if(U=k??O,C&&C.length>0){U+=`
185
185
 
186
186
  The developer attached reference images with their reply:`;for(let ne of C)U+=`
187
187
  Attached image: use the Read tool to view the image at: ${ne}`}l.kind==="synthesize"?U+=`
@@ -192,20 +192,20 @@ Follow the developer's instructions. If they ask for changes, apply them to the
192
192
 
193
193
  After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(A!=="codex"?`
194
194
 
195
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${l.screenshotPath}`:"");else{let ne=!O&&l.threadId?await _.getThreadHistory(l.threadId):void 0,we=O?null:await pe.loadModel();U=O??Js(l.screenshotPath,l.feedback,{threadHistory:ne&&ne.length>0?ne:void 0,provider:A,imagePaths:l.imagePaths,attachmentFiles:l.attachmentFiles,designModel:we??void 0,screenshotPaths:l.screenshotPaths})}U+=Sn(l.memoryReview),D&&(U+=Qt(l.imprintContext,{requestText:T??Xt(l.feedback)})),l.threadId&&!q&&(U+=`
195
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${l.screenshotPath}`:"");else{let ne=!O&&l.threadId?await _.getThreadHistory(l.threadId):void 0,we=O?null:await pe.loadModel();U=O??Ls(l.screenshotPath,l.feedback,{threadHistory:ne&&ne.length>0?ne:void 0,provider:A,imagePaths:l.imagePaths,attachmentFiles:l.attachmentFiles,designModel:we??void 0,screenshotPaths:l.screenshotPaths})}U+=Sn(l.memoryReview),D&&(U+=Qt(l.imprintContext,{requestText:k??Xt(l.feedback)})),l.threadId&&!q&&(U+=`
196
196
 
197
- ${Ns}`),U+=`
197
+ ${Bs}`),U+=`
198
198
 
199
- ${Ds}`;let G=ou(l.color,`[\u22B9 ${u}:${l.id}]`),ge=l.screenshotPaths&&Object.keys(l.screenshotPaths).length>0?`${Object.keys(l.screenshotPaths).length} pages [${Object.keys(l.screenshotPaths).join(", ")}]`:l.screenshotPath;console.log(`${G} Reviewing ${ge} (provider: ${A})${l.threadId?` (thread: ${l.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let K=new No(l.id),ye=new Ao(l.id,l.imprintContext),ue=(ne,we)=>{if(ne.type==="delta"&&"text"in ne){let Ye=ye.push(ne.text),He=K.push(Ye.visibleText);He.visibleText&&(L.accumulateText(we,"response",He.visibleText),L.broadcast({...ne,text:He.visibleText},we,l.sourceId));for(let Be of He.orientations)L.broadcast({type:"orientation",jobId:we,orientation:Be},we,l.sourceId);for(let Be of Ye.usages)L.broadcast({type:"imprint_used",jobId:we,usage:Be},we,l.sourceId);return}else ne.type==="thinking"&&"text"in ne&&L.accumulateText(we,"thinking",ne.text);L.broadcast(ne,we,l.sourceId)},{process:ce,result:te}=A==="codex"?bo(l.id,{prompt:U,projectRoot:r,screenshotPath:l.screenshotPath,resumeSessionId:z,model:l.model,sandboxMode:q?"read-only":void 0,configOverrides:oo(l.agentSettings),onEvent:ue}):A==="copilot"?is(l.id,{prompt:U,projectRoot:r,resumeSessionId:z,model:l.model,timeoutMs:p,copilotPath:x.copilot?.path??k,onEvent:ue}):A==="omp"?$s(l.id,{prompt:U,projectRoot:r,resumeSessionId:z,model:l.model,reasoningEffort:l.agentSettings?.reasoningEffort,serviceTier:l.agentSettings?.serviceTier,timeoutMs:p,ompPath:x.omp?.path??b,onEvent:ue}):yo(l.id,{prompt:U,projectRoot:r,maxTurns:c,maxBudgetUsd:I,allowedTools:q?["Read"]:v,claudePath:g,resumeSessionId:z,model:l.model,reasoningEffort:l.agentSettings?.reasoningEffort,timeoutMs:p,onEvent:ue});L.setActiveProcess(l.id,ce);let ae=await te,ke=[...(ae.fileEdits??[]).map(ne=>ne.file_path),...(ae.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],Re=ye.finalize(ae.text),Ie=Br(Re.visibleText,l.id),Ke=K.finalize(Re.visibleText),Pe=Ie.visibleText,X=Fs(Pe),ve=D?Ht(Pe,{context:l.imprintContext,requestText:T??Xt(l.feedback),applicationOccurred:ke.length>0||X.some(ne=>ne.status==="resolved")}):{visibleText:Pe,draft:void 0,error:void 0},xt=ve.visibleText,Ae=D?ve.error?{state:ve.error.includes("missing")?"missing":"invalid",reason:ve.error}:ve.draft?.decision==="none"?{state:"none",reason:ve.draft.reason}:ve.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ne of Ke.orientations)L.broadcast({type:"orientation",jobId:l.id,orientation:ne},l.id,l.sourceId);for(let ne of Re.usages)L.broadcast({type:"imprint_used",jobId:l.id,usage:ne},l.id,l.sourceId);if(l.result=xt,ae.success){console.log(`${G} Iteration complete`),ae.fileEdits&&ae.fileEdits.length>0&&console.log(`${G} Captured ${ae.fileEdits.length} file edit(s): ${ae.fileEdits.map(le=>`${le.tool} ${le.file_path}`).join(", ")}`),ae.editEvents&&ae.editEvents.length>0&&console.log(`${G} Captured ${ae.editEvents.length} edit event(s): ${ae.editEvents.map(le=>`${le.operation} ${le.filePath}`).join(", ")}`),l.status="done";let ne=qs(Pe),we=X;if(we.length>0&&l.annotationIds&&l.annotationIds.length>0){let le=new Set(l.annotationIds);we.every(dt=>le.has(dt.annotationId))||(we=we.map((dt,jt)=>({...dt,annotationId:l.annotationIds[jt%l.annotationIds.length]})))}let Ye=ae.fileEdits&&ae.fileEdits.length>0?ae.fileEdits.map(le=>`${le.tool} ${le.file_path.split("/").pop()}`):ae.toolsUsed,He=L.getBufferedEvents(l.id),Be=Hp(He?.events??[],r,Ie.segments),$e,at=js(Pe),V=Ms(Pe);if(V)if(!(l.memoryReview?.packets.some(me=>me.proposalId===V.proposalId)||l.surfacedProposalIds?.includes(V.proposalId)))$e={status:"rejected",action:V.action,proposalId:V.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{$e=await Z.commitConversationalReview(V)}catch(me){$e={status:"rejected",action:V.action,proposalId:V.proposalId,message:me instanceof Error?me.message:String(me)}}let be=Us(Pe,ke.length),he,Qe,Ut,to,no=l.imprintContext?.pendingGroundingExplanationIds??[];if(ve.draft){let le=ve.draft.decision==="recognize"?[ve.draft.explanationId]:[],me=ve.draft.decision==="recognize"?le:[...ve.draft.usedExplanationIds??[],...ve.draft.appliedExplanationIds??[]],dt=ve.draft.decision==="recognize"?[]:ve.draft.appliedExplanationIds??[];me.length>0&&(Ut=[...new Set(me)]),dt.length>0&&(to=[...new Set(dt)])}ve.draft?.decision==="none"&&se.recordNoop(ve.draft.reason);let Mt=ve.draft?.decision==="recognize"?ve.draft:void 0;if(Mt&&!V&&!at){let le=l.imprintContext?.explanations.find(me=>me.id===Mt.explanationId&&me.state==="grounded");le?Qe={explanationId:le.id,title:Mt.summary.title,detail:Mt.summary.detail,statement:le.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let bn=ve.draft?.decision==="mutate"||ve.draft?.decision==="apply"?ve.draft:void 0;if(l.threadId&&bn&&!V&&!at)try{he=await se.capture(bn,{threadId:l.threadId,jobId:l.id,concreteModel:await pe.loadModel(),pendingGroundingExplanationIds:no,applicationOccurred:ke.length>0||we.some(le=>le.status==="resolved")}),he?(Ae={state:"mutated"},await Z.recordImprintEvidence({summary:he,threadId:l.threadId,jobId:l.id}).catch(le=>console.warn(`${G} Canonical Imprint evidence linkage failed:`,le))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(le){Ae={state:"invalid",reason:le instanceof Error?le.message:String(le)},console.warn(`${G} Continuous imprint update failed; the thread result remains available:`,le instanceof Error?le.message:String(le))}else bn&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ve.error&&console.warn(`${G} Ignored invalid imprint block: ${ve.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&se.recordAssessmentFailure(Ae.state);let xn=he?.transactionId;if(l.threadId&&he&&!he.grounding){let le=await _.getThread(l.threadId),me=new Set(he.changes.map(jt=>jt.explanationId)),dt=le?Kp(le.messages,me):void 0;if(dt?.imprintSummary){let jt=dt.imprintSummary;await _.updateAssistantMessage(l.threadId,dt.jobId,{imprintSummary:{...jt,detail:he.detail,changes:he.changes,additionalObservationCount:(jt.additionalObservationCount??0)+1,coalescedTransactionIds:[...jt.coalescedTransactionIds??[],he.transactionId]}}),he=void 0}}let oe=_n({question:ne,resolutions:we,changedFiles:ke,decisionRequired:!!at,imprintTransactionId:xn,groundingRequired:!!he?.grounding}),Je=Be?.flatMap(le=>le.kind==="orientation"?[le.orientation]:[])??[],Le=l.lifecycle?Vn(l.lifecycle,xn?[xn]:[],Ae):void 0;if(l.threadId){let le=q?at?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":xt;await _.appendMessageBeforeQueuedReplies(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:le,resolutions:!q&&we.length>0?we:void 0,question:q?void 0:ne??void 0,sessionId:ae.sessionId,toolsUsed:q?void 0:Ye,editEvents:!q&&ae.editEvents&&ae.editEvents.length>0?ae.editEvents:void 0,segments:!q&&Be&&Be.length>0?Be:void 0,turn:{phase:"complete",orientation:Je,result:oe},result:oe,memoryReviewCard:at??void 0,memoryReceipt:$e,imprintSummary:he,imprintRecognition:Qe,imprintUsedExplanationIds:Ut,imprintAppliedExplanationIds:to,modelDetails:be.length>0?be:void 0,model:l.model,provider:A,...Le?{lifecycle:Le}:{}})}if(l.threadId&&!V&&!l.surfacedProposalIds?.length&&l.kind!=="project_model"){let le=l.feedback.annotations.flatMap(me=>me.linkedSelector?[me.pathname?`${me.pathname}:${me.linkedSelector}`:me.linkedSelector]:[]);try{await Z.captureCompletedJob({jobId:l.id,threadId:l.threadId,createdAt:l.createdAt,completedAt:Date.now(),requestSummary:T??(Xt(l.feedback)||"[request unavailable]"),responseSummary:ne??xt,outcome:ne?"question_asked":we.some(me=>me.status==="resolved")?"completed":"no_change",execution:{provider:A,model:l.model,sessionId:ae.sessionId},subjectHints:le,filePaths:[...(ae.fileEdits??[]).map(me=>me.file_path),...(ae.editEvents??[]).flatMap(me=>me.filePath?[me.filePath]:[])].map(me=>Yr(me)?Jp(r,me):me),resolutions:we.map(me=>({status:me.status,summary:me.summary})),governingDecisionIds:l.memoryReview?.acceptedTruth?.decisions.map(me=>me.id),submissionIds:Le?.submissionIds,outcomeId:Le?.outcomeId,imprintEvidenceIds:Le?.imprintEvidenceIds,imprintAssessment:Le?.imprintAssessment})}catch(me){console.warn(`${G} Canonical memory capture failed; iteration remains available in legacy history:`,me instanceof Error?me.message:String(me))}}$e?.status==="committed"&&$e.decisionId&&(A==="claude"||A==="codex")&&await bt({provider:A,model:l.model,agentSettings:l.agentSettings,threadId:l.threadId,annotationIds:l.annotationIds,sourceId:l.sourceId,reason:`Project accepted decision ${$e.decisionId}`}),ne&&(console.log(`${G} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${B.size} SSE clients (threadId=${l.threadId??l.id}, annotationIds=${l.annotationIds?.join(",")??"none"})`),L.broadcast({type:"question",jobId:l.id,threadId:l.threadId??l.id,question:ne,annotationIds:l.annotationIds},l.id,l.sourceId)),be.length>0&&(console.log(`${G} Applied model gap(s): ${be.map(le=>`${le.category}/${le.element}`).join(", ")}`),L.broadcast({type:"novel_patterns",jobId:l.id,patterns:be,threadId:l.threadId},l.id,l.sourceId)),L.broadcast({type:"done",jobId:l.id,success:!0,resolutions:we.length>0?we:void 0,responseText:xt,threadId:l.threadId,annotationIds:l.annotationIds,result:oe},l.id,l.sourceId),De.push({id:l.id,status:"done",completedAt:Date.now(),threadId:l.threadId,annotationIds:l.annotationIds})}else console.error(`${G} Error: ${ae.error}`),l.status="error",l.error=ae.error,l.threadId&&await _.appendMessageBeforeQueuedReplies(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,error:ae.error||"Unknown error",model:l.model,provider:A,...l.lifecycle?{lifecycle:Vn(l.lifecycle)}:{}}),L.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:ae.error||"Unknown error",provider:A,model:l.model,recoverable:ae.recoverableError,code:ae.errorCode},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:ae.error,threadId:l.threadId,annotationIds:l.annotationIds});st()});let tt=Np(async(l,S)=>{if(Yp(l,S),l.method==="OPTIONS"){S.writeHead(204),S.end();return}let O=l.url||"/",T=O.split("?")[0],C=new URL(O,`http://127.0.0.1:${u}`),A=C.pathname,q=nu(l,C);if(q&&q!==i){N(S,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:q,projectName:Ho(r)});return}if(A.startsWith("/ambient/")&&q!==i){N(S,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:q});return}if(l.headers.origin){if(!va(l.headers.origin)){N(S,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(q!==i){N(S,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:q,projectName:Ho(r)});return}}try{if(A.startsWith("/ambient/"))await ze(l,S,A);else if(l.method==="POST"&&A==="/draft-attachments"){let D=C.searchParams.get("annotationId")?.trim()??"",z=C.searchParams.get("name")?.trim()??"",U=C.searchParams.get("kind"),G=String(l.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!D||D.length>128||!/^[a-z0-9_-]+$/i.test(D)){N(S,400,{error:"A valid annotationId is required."});return}if(U!=="svg"&&U!=="text"||U==="svg"&&G!=="image/svg+xml"||U==="text"&&G!=="text/plain"){N(S,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await tu(l,Vp);if(ge.length===0){N(S,400,{error:"Attachment is empty."});return}let K=await de.stage({annotationId:D,name:z,mimeType:G,kind:U,data:ge});N(S,201,{attachment:{id:K.id,name:K.name,mimeType:K.mimeType,size:K.size,kind:K.kind}})}else if(l.method==="POST"&&A==="/draft-attachments/claim"){let D=await Fe(l),z=Array.isArray(D.ids)?D.ids.filter(U=>typeof U=="string").slice(0,100):[];await de.claim(z),N(S,200,{ok:!0})}else if(l.method==="DELETE"&&A.startsWith("/draft-attachments/"))await de.release([A.slice(19)]),N(S,200,{ok:!0});else if(l.method==="POST"&&A==="/send")await wt(l,S);else if(l.method==="POST"&&A==="/capture/native"){if(!y){N(S,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let D=await Fe(l),z=typeof D.pageUrl=="string"?D.pageUrl:"",U=D.clip&&typeof D.clip=="object"&&!Array.isArray(D.clip)?D.clip:null;if(!z||!U){N(S,400,{error:"pageUrl and clip are required."});return}let G=await Es(y,{pageUrl:z,clip:{x:Number(U.x),y:Number(U.y),width:Number(U.width),height:Number(U.height)},scale:typeof D.scale=="number"?D.scale:1});S.writeHead(200,{"Content-Type":"image/webp","Content-Length":G.length,"Cache-Control":"no-store"}),S.end(G)}else if(l.method==="GET"&&A==="/events")Qo(l,S);else if(l.method==="GET"&&A==="/status")await Xo(l,S,q);else if(l.method==="GET"&&A==="/ui-preferences")await We(S);else if(l.method==="PATCH"&&A==="/ui-preferences")await Ve(l,S);else if(l.method==="PATCH"&&A==="/config")await wn(l,S);else if(l.method==="POST"&&A==="/leases"){if(w!=="detached"){N(S,409,{error:"Bridge leases are only available for detached bridges."});return}try{let D=await Fe(l),z=typeof D.leaseId=="string"?D.leaseId.trim():"",U=typeof D.ownerPid=="number"&&Number.isInteger(D.ownerPid)&&D.ownerPid>0?D.ownerPid:void 0;if(!z||z.length>128){N(S,400,{error:"A valid leaseId is required."});return}ie();let G=J.acquire(z,U);N(S,201,{ok:!0,lease:G,ttlMs:ma})}catch{N(S,400,{error:"Invalid lease request."})}}else if(A.startsWith("/leases/")&&(l.method==="PATCH"||l.method==="DELETE")){if(w!=="detached"){N(S,409,{error:"Bridge leases are only available for detached bridges."});return}let D="";try{D=decodeURIComponent(A.slice(8))}catch{N(S,400,{error:"Invalid lease id."});return}if(!D){N(S,400,{error:"A lease id is required."});return}if(l.method==="PATCH"){let z=J.heartbeat(D);if(!z){N(S,404,{error:"Lease not found."});return}N(S,200,{ok:!0,lease:z})}else{let z=J.release(D);N(S,z.found?200:404,{ok:z.found}),z.becameEmpty&&j()}}else if(l.method==="POST"&&A==="/shutdown"){if(w!=="detached"){N(S,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:w});return}N(S,200,{ok:!0}),setTimeout(P,100)}else if(l.method==="POST"&&A==="/restart"){if(w!=="detached"){N(S,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:w});return}N(S,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let D of B)try{D.res.end()}catch{}tt.close(()=>{ua(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(l.method==="GET"&&A==="/capabilities")C.searchParams.get("refresh")==="omp"&&await $(),N(S,200,{providers:x});else if(A.startsWith("/imprint/"))await It(l,S,A);else if(A.startsWith("/memory/"))await ut(l,S,A);else if(l.method==="POST"&&A==="/mcp/install")await Pa(l,S);else if(l.method==="POST"&&A==="/reply")await Rt(l,S);else if(l.method==="POST"&&A==="/cancel")vt(l,S);else if(l.method==="POST"&&A==="/materialize")N(S,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(l.method==="GET"&&A==="/materialization-runs")N(S,410,{error:"Use /projection-runs."});else if(l.method==="GET"&&A==="/projection-runs"){let D=await pe.loadRuns();N(S,200,D)}else if(l.method==="GET"&&A==="/projection/proposals"){let D=await pe.loadModelProposals();N(S,200,D)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/apply-selected")){let D=A.slice(22,-15);await Yo(D,l,S)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/apply")){let D=A.slice(22,-6);await At(D,S)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/dismiss")){let D=A.slice(22,-8);await eo(D,l,S)}else if(A.startsWith("/model/proposals/"))N(S,410,{error:"Use /projection/proposals."});else if(A==="/model/component"||A==="/model/token")N(S,410,{error:"Direct model editing was removed. Project understanding changes through collaboration and canonical projection."});else if(l.method==="POST"&&A==="/model/consolidate")N(S,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(l.method==="POST"&&A==="/model/synthesize")N(S,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(l.method==="GET"&&A==="/model"){let D=await pe.loadModel();N(S,200,{model:D})}else if(l.method==="GET"&&A.startsWith("/jobs/")&&A.endsWith("/events")){let D=A.slice(6,A.length-7),z=parseInt(C.searchParams.get("afterSeq")??"-1",10),U=L.getBufferedEvents(D,isNaN(z)?-1:z);U?N(S,200,U):N(S,404,{error:"Unknown job"})}else if(l.method==="GET"&&T.startsWith("/files/"))await Ra(T.slice(7),S);else if(l.method==="GET"&&A==="/threads/recent"){let D=Math.min(Math.max(parseInt(C.searchParams.get("limit")??"5",10)||5,1),200),z=await _.listRecent(D);N(S,200,z)}else if(l.method==="POST"&&A==="/workspace/clear"){let D=[...L.cancelAll(),...R.cancelAll()];for(let U of D)U.threadId&&await _.appendMessage(U.threadId,{role:"assistant",timestamp:Date.now(),jobId:U.id,cancelled:!0});De.length=0;let z=await _.advanceWorkspaceGeneration();for(let U of B)Zn(U,{type:"workspace_cleared",workspaceGeneration:z});N(S,200,{cleared:!0,workspaceGeneration:z})}else if(l.method==="GET"&&A.startsWith("/decision/")){let D=A.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(D))N(S,400,{error:"Invalid decision id"});else{let z=await _.getThread(D),U=[...z?.messages??[]].reverse().find(G=>G.annotationSnapshot);if(z&&U?.annotationSnapshot){let G=[...z.messages].reverse().find(ge=>ge.resolutions?.length);N(S,200,{decision:{id:z.id,createdAt:U.timestamp,url:U.annotationSnapshot.url,viewport:U.annotationSnapshot.viewport,color:U.annotationSnapshot.color,annotations:U.annotationSnapshot.annotations,resolutions:G?.resolutions??[]},authority:"thread_snapshot"})}else{let G=await qe.loadDecision(D);G?N(S,200,{decision:G,authority:"legacy_archive"}):N(S,404,{error:"Decision not found"})}}}else if(l.method==="GET"&&A.startsWith("/thread/")){let D=A.slice(8);await Aa(D,S)}else if(l.method==="POST"&&A.startsWith("/thread/")&&A.endsWith("/archive")){let D=A.slice(8,-8);await ei(D,S)}else if(l.method==="DELETE"&&A.startsWith("/thread/")){let D=A.slice(8);await ei(D,S)}else N(S,404,{error:"Not found"})}catch(D){console.error("[Bridge] Request error:",D),N(S,500,{error:D instanceof Error?D.message:"Internal error"})}});async function ze(l,S,O){if(l.method!=="POST"){N(S,405,{error:"Ambient endpoints accept POST requests only."});return}let T=await Fe(l,eu),C=typeof T.sessionId=="string"?T.sessionId.trim():"",A=typeof T.turnId=="string"?T.turnId.trim():"",q=typeof T.executionOwner=="string"?T.executionOwner:void 0,D=Ji(T.knowledgeView);if(O==="/ambient/context"){let z=typeof T.query=="string"?T.query.trim():"";if(!z){N(S,400,{error:"query is required."});return}let U=Array.isArray(T.subjectHints)?T.subjectHints.filter(G=>typeof G=="string"&&!!G.trim()).slice(0,20):void 0;N(S,200,await Te.expandContext({query:z,subjectHints:U,knowledgeView:D}));return}if(O==="/ambient/turns/assess"){let z=typeof T.threadId=="string"?T.threadId.trim():"",U=typeof T.jobId=="string"?T.jobId.trim():"",G=typeof T.assessmentText=="string"?T.assessmentText.trim():"";if(!z||!U||!G){N(S,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(T.semanticCandidates)?T.semanticCandidates.flatMap(ye=>{if(!ye||typeof ye!="object"||Array.isArray(ye))return[];let ue=ye,ce=typeof ue.claim=="string"?ue.claim.trim():"",te=typeof ue.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(ue.proposedKind)?ue.proposedKind:void 0;return ce?[{claim:ce,rationale:typeof ue.rationale=="string"?ue.rationale.trim():void 0,proposedKind:te,sourceText:typeof ue.sourceText=="string"?ue.sourceText.trim():void 0}]:[]}).slice(0,8):[],K=await Te.assess({threadId:z,jobId:U,assessmentText:G,semanticCandidates:ge});N(S,K.status==="committed"||K.status==="assessed"?200:K.status==="rejected"?422:404,K);return}if(!C||!A||C.length>256||A.length>256){N(S,400,{error:"Valid sessionId and turnId values are required."});return}if(O==="/ambient/turns/prepare"){let z=typeof T.prompt=="string"?T.prompt.trim():"";if(!z){N(S,400,{error:"prompt is required."});return}N(S,200,await Te.prepare({sessionId:C,turnId:A,prompt:z,model:typeof T.model=="string"?T.model:void 0,executionOwner:q,knowledgeView:D}));return}if(O==="/ambient/turns/event"){let z=typeof T.toolName=="string"?T.toolName.trim():"";if(!z){N(S,400,{error:"toolName is required."});return}N(S,200,await Te.recordEvent({sessionId:C,turnId:A,executionOwner:q,toolName:z,toolUseId:typeof T.toolUseId=="string"?T.toolUseId:void 0,toolInput:T.toolInput,toolResponse:T.toolResponse}));return}if(O==="/ambient/turns/complete"){N(S,200,await Te.complete({sessionId:C,turnId:A,executionOwner:q,lastAssistantMessage:typeof T.lastAssistantMessage=="string"?T.lastAssistantMessage:void 0,model:typeof T.model=="string"?T.model:void 0}));return}N(S,404,{error:"Ambient endpoint not found."})}async function ut(l,S,O){try{if(l.method==="GET"&&O==="/memory/status"){N(S,200,await Z.status());return}if(l.method==="GET"&&O==="/memory/diagnostics"){N(S,200,await Z.diagnostics());return}if(l.method==="GET"&&O==="/memory/model-view"){N(S,200,await Z.getModelView());return}if(l.method==="GET"&&O==="/memory/imprint-view"){let T=await _.load(),C=[...new Set(Object.values(T.threads).flatMap(A=>Yn(A.messages)))];N(S,200,await Z.getImprintView(C,new Set(Object.keys(T.threads))));return}if(l.method==="POST"&&O==="/memory/constraints"){let T=await Fe(l),C=typeof T.reactComponent=="string"?T.reactComponent.trim():"",A=await Z.getModelView(),q=C?A.entries.filter(D=>D.key===`components.${C}`||D.key.startsWith(`components.${C}.`)):[];N(S,200,{modelEntries:q});return}if(l.method==="POST"&&O==="/memory/conversation-action"){let T=await Fe(l),C=typeof T.threadId=="string"?T.threadId:"",A=typeof T.proposalId=="string"?T.proposalId:"",q=String(T.action);if(!C||!A||!["accept","edit_and_accept","reject","defer"].includes(q)){N(S,400,{error:"A valid thread, proposal, and review action are required."});return}let D=await _.getThread(C),z=D?.messages.find(Ie=>Ie.memoryReviewCard?.proposalId===A)?.memoryReviewCard,U=D?.messages.flatMap(Ie=>Ie.memoryReview?.packets??[]).find(Ie=>Ie.proposalId===A),G=D?.elementIdentifiers.some(Ie=>Ie.startsWith("codex-session:"))?(await Z.findPendingProposalsForThread(C)).find(Ie=>Ie.proposalId===A):void 0,ge=typeof T.kind=="string"&&["principle","preference","rule","constraint"].includes(T.kind)?T.kind:void 0,K=z?.kind??U?.proposedKind??G?.proposedKind??ge;if(!D||!z&&!U&&!G){N(S,409,{error:"This decision candidate was not surfaced in the thread."});return}if((q==="accept"||q==="edit_and_accept")&&!K){N(S,400,{error:"The decision kind is required to accept this candidate."});return}let ye=await pe.findModelProposalsByThread(C),ue=(await Promise.all(ye.map(async Ie=>({proposal:Ie,matches:(await Promise.all(Ie.decisionIds.map(Ke=>Z.findPendingProposalForLegacyDecision(Ke)))).some(Ke=>Ke?.proposalId===A)})))).find(Ie=>Ie.matches)?.proposal,ce={proposalId:A,action:q,kind:K,claim:q==="edit_and_accept"&&typeof T.claim=="string"?T.claim.trim():void 0,reason:q==="defer"?void 0:`The owner explicitly chose ${q.replaceAll("_"," ")} from the decision review card.`,taskContext:q==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:q==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){N(S,400,{error:"Edited decision wording is required."});return}let te=await Z.commitConversationalReview(ce),ae=`memory-${yt().slice(0,8)}`,ke=q==="accept"?"> Accepted decision":q==="edit_and_accept"?"> Edited and accepted decision":q==="reject"?"> Rejected decision":"> Deferred decision";await _.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:ae,replyToQuestion:ke}),await _.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:ae,responseText:"",memoryReceipt:te,provider:yn(typeof T.provider=="string"?T.provider:void 0),model:typeof T.model=="string"?T.model:void 0}),te.status==="committed"&&ue&&await pe.dismissModelProposal(ue.id);let Re=yn(typeof T.provider=="string"?T.provider:void 0);te.status==="committed"&&te.decisionId&&(Re==="claude"||Re==="codex")&&await bt({provider:Re,model:typeof T.model=="string"?T.model:void 0,agentSettings:Gt(T),threadId:C,reason:`Project accepted decision ${te.decisionId}`}),N(S,te.status==="committed"?200:409,{receipt:te});return}if(l.method==="POST"&&O==="/memory/analyze"){let T=await Fe(l),C=await Z.analyzeLegacy({projectKey:typeof T.projectKey=="string"?T.projectKey:void 0}),A=Object.fromEntries([...new Set(C.issues.map(q=>q.code))].map(q=>[q,C.issues.filter(D=>D.code===q).length]));N(S,200,{...C,issues:void 0,issueCounts:A});return}if(l.method==="POST"&&O==="/memory/review"){let T=await Fe(l),C=await Z.review(fr(T.query),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,200,C);return}if(l.method==="POST"&&O==="/memory/context"){let T=await Fe(l),C=await Z.contextualize(fr(T.query),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,200,C);return}if(l.method==="POST"&&O==="/memory/initialize"){let T=await Fe(l),C=await Z.initializeFromLegacy({confirmed:T.confirm===!0,projectKey:typeof T.projectKey=="string"?T.projectKey:void 0,writerVersion:mt});N(S,201,{status:C.status,report:{source:C.report.source,imported:C.report.imported,unresolvedAcceptance:C.report.unresolvedAcceptance,deferredModelEntries:C.report.deferredModelEntries,proofCases:C.report.proofCases,schemaIssues:C.report.schemaIssues}});return}if(l.method==="POST"&&O==="/memory/plan"){let T=await Fe(l),C=await Z.planReview(mr(T.command),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,C.result.ok?200:422,C);return}if(l.method==="POST"&&O==="/memory/commit"){let T=await Fe(l),C=T.transaction&&typeof T.transaction=="object"&&!Array.isArray(T.transaction)?T.transaction:{},A=await Z.commitReview(mr(T.command),{transactionId:typeof C.transactionId=="string"?C.transactionId:"",committedAt:typeof C.committedAt=="string"?C.committedAt:""});N(S,200,{status:await Z.status(),journal:A.report});return}if(l.method==="POST"&&O==="/memory/recover"){let T=await Fe(l),C=await Z.recover(T.confirm===!0);N(S,200,{status:await Z.status(),journal:C.report});return}N(S,404,{error:"Memory endpoint not found."})}catch(T){let C=T instanceof Error?T.message:String(T),A=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(C),q=/required|invalid|unsupported|expected|must be|confirmation/i.test(C);if(A||q){N(S,A?409:400,{error:C});return}throw T}}async function It(l,S,O){if(l.method==="GET"&&O==="/imprint/status"){let[T,C]=await Promise.all([se.store.load(),_.load()]),A=[...new Set(Object.values(C.threads).flatMap(q=>Yn(q.messages)))].filter(q=>T.graph.explanations.some(D=>D.id===q&&D.state==="testing"));N(S,200,{state:"ready",head:T.graph.head,updatedAt:T.graph.updatedAt,explanationCount:T.graph.explanations.filter(q=>q.state!=="retired").length,concreteCount:T.graph.concrete.length,relationCount:T.graph.relations.length,pendingGroundingCount:A.length,recoveredTransactions:T.recoveredTransactions,admission:se.diagnostics(),admissionWindowStartedAt:e});return}if(l.method==="POST"&&O==="/imprint/action"){let T=await Fe(l),C=typeof T.threadId=="string"?T.threadId:"",A=typeof T.transactionId=="string"?T.transactionId:"",q=String(T.action);if(!C||!A||!["yes","this_time","no"].includes(q)){N(S,400,{error:"A valid thread, imprint update, and action are required."});return}let z=await _.getThread(C),U=[...z?.messages??[]].reverse().find(ce=>ce.role==="assistant"&&ce.imprintSummary?.transactionId===A),G=U?.imprintSummary;if(!z||!U||!G){N(S,409,{error:"This imprint summary is not available in the thread."});return}if(G.resolvedAction){N(S,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${yt().slice(0,8)}`;await se.applyGroundingAction({summary:G,action:q,threadId:C,jobId:ge}),q!=="no"&&await Z.recordImprintEvidence({summary:G,action:q,threadId:C,jobId:ge}).catch(ce=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ce));let K=an(U.result,!!U.question),ye=U.turn?{...U.turn,result:an(U.turn.result,!!U.question)}:void 0;await _.updateAssistantMessage(C,U.jobId,{imprintSummary:{...G,resolvedAction:q},...K?{result:K}:{},...ye?{turn:ye}:{}});let ue={yes:"> Yes",this_time:"> This time",no:"> No"};if(await _.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:ge,replyToQuestion:ue[q]}),q==="no"){let ce="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",te=_n({question:ce});await _.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:ge,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ce,turn:{phase:"complete",orientation:[],result:te},result:te})}N(S,200,{ok:!0,action:q});return}N(S,404,{error:"Imprint endpoint not found."})}async function wt(l,S){let{screenshot:O,feedback:T,color:C,provider:A,model:q,reasoningEffort:D,serviceTier:z,sourceId:U,continuationThreadId:G,continuationTargetBindingId:ge,continuationSelectorAliases:K,pastedImages:ye,pageScreenshots:ue}=await Dr(l),ce=C,te;try{te=JSON.parse(T)}catch{N(S,400,{error:"Invalid feedback JSON"});return}let ae=te.annotations.flatMap(oe=>(oe.attachments??[]).map(Je=>({id:Je.id,annotationId:oe.id}))),ke;try{ke=ae.length>0?await de.promote(ae):void 0}catch(oe){N(S,409,{error:oe instanceof Error?oe.message:"Draft attachment unavailable."});return}let Re=yt().slice(0,8),Ie={};if(ue.length>0)for(let oe of ue){let Je=encodeURIComponent(oe.pathname),Le=it(d,`screenshot-${Re}-${Je}.webp`);await Ko(Le,oe.data),Ie[oe.pathname]=Le}let Ke=it(d,`screenshot-${Re}.webp`);await Ko(Ke,O);let Pe={};if(ye.length>0)for(let oe of ye){let Je=it(d,`pasted-${Re}-${oe.annotationId}-${oe.index}.webp`);await Ko(Je,oe.data),Pe[oe.annotationId]||(Pe[oe.annotationId]=[]),Pe[oe.annotationId].push(Je)}let X=ra(te),ve=ia(te,K),xt=Wr(te,K),Ae,ne=!1,we;if(X.length>0){let oe=await _.findOrCreateContinuationThread(X,`thread-${yt()}`,G,ve,xt,ge);Ae=oe.thread.id,we=oe.decision,ne=we.action==="continued",console.log(`[Continuation] ${JSON.stringify({event:"continuation_resolution",...we,...G?{preferredThreadId:G}:{},...ge?{preferredTargetBindingId:ge}:{},resolvedThreadId:Ae,...oe.targetBindings[0]?.id?{resolvedTargetBindingId:oe.targetBindings[0].id}:{}})}`),ne&&(ce=oe.thread.messages.find(Je=>Je.annotationSnapshot?.color)?.annotationSnapshot?.color??ce)}else Ae=(await _.createThread(`thread-${yt()}`,[])).id;let Ye=ne||(await _.findContinuationThread(X))?.id===Ae,He=te.annotations.map(oe=>oe.id),Be=Object.keys(Ie).length>0,$e=await io(Z,te,X,oe=>console.warn(`[\u22B9 ${u}:${Re}] Contextual memory unavailable; continuing without it:`,oe instanceof Error?oe.message:String(oe))),at=(await _.getThread(Ae))?.messages??[],V=await se.contextualize({text:Xt(te),subjectHints:us(te,X),pendingGroundingExplanationIds:Yn(at),correctionExplanationIds:ha(at)}).catch(oe=>{console.warn(`[\u22B9 ${u}:${Re}] Imprint context unavailable; continuing without it:`,oe instanceof Error?oe.message:String(oe))}),be=Gr({jobId:Re,threadId:Ae,artifactIds:sa(te,Re)}),he={id:Re,status:"queued",screenshotPath:Ke,feedback:te,createdAt:Date.now(),color:ce,threadId:Ae,annotationIds:He,provider:yn(A),model:q||void 0,agentSettings:Gt({reasoningEffort:D,serviceTier:z}),...Object.keys(Pe).length>0?{imagePaths:Pe}:{},...ke&&Object.keys(ke).length>0?{attachmentFiles:ke}:{},sourceId:U||void 0,...Be?{screenshotPaths:Ie}:{},...$e?{memoryReview:$e}:{},...V?{imprintContext:V}:{},lifecycle:be},Qe=new Set(te.annotations.map(oe=>oe.pathname).filter(Boolean)),Ut;if(Qe.size>1){let oe=new Map;for(let Je of te.annotations){let Le=Je.pathname||"(unknown)";oe.has(Le)||oe.set(Le,[]),oe.get(Le).push(Je.instruction||ga({...te,annotations:[Je]}))}Ut=[...oe.entries()].map(([Je,Le])=>`\`${Je}\`
199
+ ${Ns}`;let G=ru(l.color,`[\u22B9 ${u}:${l.id}]`),ge=l.screenshotPaths&&Object.keys(l.screenshotPaths).length>0?`${Object.keys(l.screenshotPaths).length} pages [${Object.keys(l.screenshotPaths).join(", ")}]`:l.screenshotPath;console.log(`${G} Reviewing ${ge} (provider: ${A})${l.threadId?` (thread: ${l.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let K=new No(l.id),ye=new Ao(l.id,l.imprintContext),ue=(ne,we)=>{if(ne.type==="delta"&&"text"in ne){let Ye=ye.push(ne.text),He=K.push(Ye.visibleText);He.visibleText&&(L.accumulateText(we,"response",He.visibleText),L.broadcast({...ne,text:He.visibleText},we,l.sourceId));for(let Be of He.orientations)L.broadcast({type:"orientation",jobId:we,orientation:Be},we,l.sourceId);for(let Be of Ye.usages)L.broadcast({type:"imprint_used",jobId:we,usage:Be},we,l.sourceId);return}else ne.type==="thinking"&&"text"in ne&&L.accumulateText(we,"thinking",ne.text);L.broadcast(ne,we,l.sourceId)},{process:ce,result:te}=A==="codex"?bo(l.id,{prompt:U,projectRoot:r,screenshotPath:l.screenshotPath,resumeSessionId:z,model:l.model,sandboxMode:q?"read-only":void 0,configOverrides:oo(l.agentSettings),onEvent:ue}):A==="copilot"?ss(l.id,{prompt:U,projectRoot:r,resumeSessionId:z,model:l.model,timeoutMs:p,copilotPath:x.copilot?.path??S,onEvent:ue}):A==="omp"?Os(l.id,{prompt:U,projectRoot:r,resumeSessionId:z,model:l.model,reasoningEffort:l.agentSettings?.reasoningEffort,serviceTier:l.agentSettings?.serviceTier,timeoutMs:p,ompPath:x.omp?.path??b,onEvent:ue}):yo(l.id,{prompt:U,projectRoot:r,maxTurns:c,maxBudgetUsd:y,allowedTools:q?["Read"]:w,claudePath:g,resumeSessionId:z,model:l.model,reasoningEffort:l.agentSettings?.reasoningEffort,timeoutMs:p,onEvent:ue});L.setActiveProcess(l.id,ce);let ae=await te,ke=[...(ae.fileEdits??[]).map(ne=>ne.file_path),...(ae.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],Re=ye.finalize(ae.text),Ie=Br(Re.visibleText,l.id),Ke=K.finalize(Re.visibleText),Pe=Ie.visibleText,X=zs(Pe),ve=D?Ht(Pe,{context:l.imprintContext,requestText:k??Xt(l.feedback),applicationOccurred:ke.length>0||X.some(ne=>ne.status==="resolved")}):{visibleText:Pe,draft:void 0,error:void 0},xt=ve.visibleText,Ae=D?ve.error?{state:ve.error.includes("missing")?"missing":"invalid",reason:ve.error}:ve.draft?.decision==="none"?{state:"none",reason:ve.draft.reason}:ve.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ne of Ke.orientations)L.broadcast({type:"orientation",jobId:l.id,orientation:ne},l.id,l.sourceId);for(let ne of Re.usages)L.broadcast({type:"imprint_used",jobId:l.id,usage:ne},l.id,l.sourceId);if(l.result=xt,ae.success){console.log(`${G} Iteration complete`),ae.fileEdits&&ae.fileEdits.length>0&&console.log(`${G} Captured ${ae.fileEdits.length} file edit(s): ${ae.fileEdits.map(le=>`${le.tool} ${le.file_path}`).join(", ")}`),ae.editEvents&&ae.editEvents.length>0&&console.log(`${G} Captured ${ae.editEvents.length} edit event(s): ${ae.editEvents.map(le=>`${le.operation} ${le.filePath}`).join(", ")}`),l.status="done";let ne=Fs(Pe),we=X;if(we.length>0&&l.annotationIds&&l.annotationIds.length>0){let le=new Set(l.annotationIds);we.every(dt=>le.has(dt.annotationId))||(we=we.map((dt,jt)=>({...dt,annotationId:l.annotationIds[jt%l.annotationIds.length]})))}let Ye=ae.fileEdits&&ae.fileEdits.length>0?ae.fileEdits.map(le=>`${le.tool} ${le.file_path.split("/").pop()}`):ae.toolsUsed,He=L.getBufferedEvents(l.id),Be=Qp(He?.events??[],r,Ie.segments),$e,at=Es(Pe),V=js(Pe);if(V)if(!(l.memoryReview?.packets.some(me=>me.proposalId===V.proposalId)||l.surfacedProposalIds?.includes(V.proposalId)))$e={status:"rejected",action:V.action,proposalId:V.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{$e=await Z.commitConversationalReview(V)}catch(me){$e={status:"rejected",action:V.action,proposalId:V.proposalId,message:me instanceof Error?me.message:String(me)}}let be=Gs(Pe,ke.length),he,Qe,Ut,to,no=l.imprintContext?.pendingGroundingExplanationIds??[];if(ve.draft){let le=ve.draft.decision==="recognize"?[ve.draft.explanationId]:[],me=ve.draft.decision==="recognize"?le:[...ve.draft.usedExplanationIds??[],...ve.draft.appliedExplanationIds??[]],dt=ve.draft.decision==="recognize"?[]:ve.draft.appliedExplanationIds??[];me.length>0&&(Ut=[...new Set(me)]),dt.length>0&&(to=[...new Set(dt)])}ve.draft?.decision==="none"&&se.recordNoop(ve.draft.reason);let Mt=ve.draft?.decision==="recognize"?ve.draft:void 0;if(Mt&&!V&&!at){let le=l.imprintContext?.explanations.find(me=>me.id===Mt.explanationId&&me.state==="grounded");le?Qe={explanationId:le.id,title:Mt.summary.title,detail:Mt.summary.detail,statement:le.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let bn=ve.draft?.decision==="mutate"||ve.draft?.decision==="apply"?ve.draft:void 0;if(l.threadId&&bn&&!V&&!at)try{he=await se.capture(bn,{threadId:l.threadId,jobId:l.id,concreteModel:await pe.loadModel(),pendingGroundingExplanationIds:no,applicationOccurred:ke.length>0||we.some(le=>le.status==="resolved")}),he?(Ae={state:"mutated"},await Z.recordImprintEvidence({summary:he,threadId:l.threadId,jobId:l.id}).catch(le=>console.warn(`${G} Canonical Imprint evidence linkage failed:`,le))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(le){Ae={state:"invalid",reason:le instanceof Error?le.message:String(le)},console.warn(`${G} Continuous imprint update failed; the thread result remains available:`,le instanceof Error?le.message:String(le))}else bn&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ve.error&&console.warn(`${G} Ignored invalid imprint block: ${ve.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&se.recordAssessmentFailure(Ae.state);let xn=he?.transactionId;if(l.threadId&&he&&!he.grounding){let le=await _.getThread(l.threadId),me=new Set(he.changes.map(jt=>jt.explanationId)),dt=le?Hp(le.messages,me):void 0;if(dt?.imprintSummary){let jt=dt.imprintSummary;await _.updateAssistantMessage(l.threadId,dt.jobId,{imprintSummary:{...jt,detail:he.detail,changes:he.changes,additionalObservationCount:(jt.additionalObservationCount??0)+1,coalescedTransactionIds:[...jt.coalescedTransactionIds??[],he.transactionId]}}),he=void 0}}let oe=_n({question:ne,resolutions:we,changedFiles:ke,decisionRequired:!!at,imprintTransactionId:xn,groundingRequired:!!he?.grounding}),Je=Be?.flatMap(le=>le.kind==="orientation"?[le.orientation]:[])??[],Le=l.lifecycle?Vn(l.lifecycle,xn?[xn]:[],Ae):void 0;if(l.threadId){let le=q?at?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":xt;await _.appendMessageBeforeQueuedReplies(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,responseText:le,resolutions:!q&&we.length>0?we:void 0,question:q?void 0:ne??void 0,sessionId:ae.sessionId,toolsUsed:q?void 0:Ye,editEvents:!q&&ae.editEvents&&ae.editEvents.length>0?ae.editEvents:void 0,segments:!q&&Be&&Be.length>0?Be:void 0,turn:{phase:"complete",orientation:Je,result:oe},result:oe,memoryReviewCard:at??void 0,memoryReceipt:$e,imprintSummary:he,imprintRecognition:Qe,imprintUsedExplanationIds:Ut,imprintAppliedExplanationIds:to,modelDetails:be.length>0?be:void 0,model:l.model,provider:A,...Le?{lifecycle:Le}:{}})}if(l.threadId&&!V&&!l.surfacedProposalIds?.length&&l.kind!=="project_model"){let le=l.feedback.annotations.flatMap(me=>me.linkedSelector?[me.pathname?`${me.pathname}:${me.linkedSelector}`:me.linkedSelector]:[]);try{await Z.captureCompletedJob({jobId:l.id,threadId:l.threadId,createdAt:l.createdAt,completedAt:Date.now(),requestSummary:k??(Xt(l.feedback)||"[request unavailable]"),responseSummary:ne??xt,outcome:ne?"question_asked":we.some(me=>me.status==="resolved")?"completed":"no_change",execution:{provider:A,model:l.model,sessionId:ae.sessionId},subjectHints:le,filePaths:[...(ae.fileEdits??[]).map(me=>me.file_path),...(ae.editEvents??[]).flatMap(me=>me.filePath?[me.filePath]:[])].map(me=>Zr(me)?qp(r,me):me),resolutions:we.map(me=>({status:me.status,summary:me.summary})),governingDecisionIds:l.memoryReview?.acceptedTruth?.decisions.map(me=>me.id),submissionIds:Le?.submissionIds,outcomeId:Le?.outcomeId,imprintEvidenceIds:Le?.imprintEvidenceIds,imprintAssessment:Le?.imprintAssessment})}catch(me){console.warn(`${G} Canonical memory capture failed; iteration remains available in legacy history:`,me instanceof Error?me.message:String(me))}}$e?.status==="committed"&&$e.decisionId&&(A==="claude"||A==="codex")&&await bt({provider:A,model:l.model,agentSettings:l.agentSettings,threadId:l.threadId,annotationIds:l.annotationIds,sourceId:l.sourceId,reason:`Project accepted decision ${$e.decisionId}`}),ne&&(console.log(`${G} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${B.size} SSE clients (threadId=${l.threadId??l.id}, annotationIds=${l.annotationIds?.join(",")??"none"})`),L.broadcast({type:"question",jobId:l.id,threadId:l.threadId??l.id,question:ne,annotationIds:l.annotationIds},l.id,l.sourceId)),be.length>0&&(console.log(`${G} Applied model gap(s): ${be.map(le=>`${le.category}/${le.element}`).join(", ")}`),L.broadcast({type:"novel_patterns",jobId:l.id,patterns:be,threadId:l.threadId},l.id,l.sourceId)),L.broadcast({type:"done",jobId:l.id,success:!0,resolutions:we.length>0?we:void 0,responseText:xt,threadId:l.threadId,annotationIds:l.annotationIds,result:oe},l.id,l.sourceId),De.push({id:l.id,status:"done",completedAt:Date.now(),threadId:l.threadId,annotationIds:l.annotationIds})}else console.error(`${G} Error: ${ae.error}`),l.status="error",l.error=ae.error,l.threadId&&await _.appendMessageBeforeQueuedReplies(l.threadId,{role:"assistant",timestamp:Date.now(),jobId:l.id,error:ae.error||"Unknown error",model:l.model,provider:A,...l.lifecycle?{lifecycle:Vn(l.lifecycle)}:{}}),L.broadcast({type:"error",jobId:l.id,threadId:l.threadId,message:ae.error||"Unknown error",provider:A,model:l.model,recoverable:ae.recoverableError,code:ae.errorCode},l.id,l.sourceId),De.push({id:l.id,status:"error",completedAt:Date.now(),error:ae.error,threadId:l.threadId,annotationIds:l.annotationIds});st()});let tt=Bp(async(l,T)=>{if(Zp(l,T),l.method==="OPTIONS"){T.writeHead(204),T.end();return}let O=l.url||"/",k=O.split("?")[0],C=new URL(O,`http://127.0.0.1:${u}`),A=C.pathname,q=ou(l,C);if(q&&q!==i){N(T,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:q,projectName:Ho(r)});return}if(A.startsWith("/ambient/")&&q!==i){N(T,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:q});return}if(l.headers.origin){if(!xa(l.headers.origin)){N(T,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(q!==i){N(T,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:q,projectName:Ho(r)});return}}try{if(A.startsWith("/ambient/"))await ze(l,T,A);else if(l.method==="POST"&&A==="/draft-attachments"){let D=C.searchParams.get("annotationId")?.trim()??"",z=C.searchParams.get("name")?.trim()??"",U=C.searchParams.get("kind"),G=String(l.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!D||D.length>128||!/^[a-z0-9_-]+$/i.test(D)){N(T,400,{error:"A valid annotationId is required."});return}if(U!=="svg"&&U!=="text"||U==="svg"&&G!=="image/svg+xml"||U==="text"&&G!=="text/plain"){N(T,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await nu(l,Kp);if(ge.length===0){N(T,400,{error:"Attachment is empty."});return}let K=await de.stage({annotationId:D,name:z,mimeType:G,kind:U,data:ge});N(T,201,{attachment:{id:K.id,name:K.name,mimeType:K.mimeType,size:K.size,kind:K.kind}})}else if(l.method==="POST"&&A==="/draft-attachments/claim"){let D=await Fe(l),z=Array.isArray(D.ids)?D.ids.filter(U=>typeof U=="string").slice(0,100):[];await de.claim(z),N(T,200,{ok:!0})}else if(l.method==="DELETE"&&A.startsWith("/draft-attachments/"))await de.release([A.slice(19)]),N(T,200,{ok:!0});else if(l.method==="POST"&&A==="/send")await wt(l,T);else if(l.method==="POST"&&A==="/capture/native"){if(!I){N(T,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let D=await Fe(l),z=typeof D.pageUrl=="string"?D.pageUrl:"",U=D.clip&&typeof D.clip=="object"&&!Array.isArray(D.clip)?D.clip:null;if(!z||!U){N(T,400,{error:"pageUrl and clip are required."});return}let G=await _s(I,{pageUrl:z,clip:{x:Number(U.x),y:Number(U.y),width:Number(U.width),height:Number(U.height)},scale:typeof D.scale=="number"?D.scale:1});T.writeHead(200,{"Content-Type":"image/webp","Content-Length":G.length,"Cache-Control":"no-store"}),T.end(G)}else if(l.method==="GET"&&A==="/events")Qo(l,T);else if(l.method==="GET"&&A==="/status")await Xo(l,T,q);else if(l.method==="GET"&&A==="/ui-preferences")await We(T);else if(l.method==="PATCH"&&A==="/ui-preferences")await Ve(l,T);else if(l.method==="PATCH"&&A==="/config")await wn(l,T);else if(l.method==="POST"&&A==="/leases"){if(v!=="detached"){N(T,409,{error:"Bridge leases are only available for detached bridges."});return}try{let D=await Fe(l),z=typeof D.leaseId=="string"?D.leaseId.trim():"",U=typeof D.ownerPid=="number"&&Number.isInteger(D.ownerPid)&&D.ownerPid>0?D.ownerPid:void 0;if(!z||z.length>128){N(T,400,{error:"A valid leaseId is required."});return}ie();let G=J.acquire(z,U);N(T,201,{ok:!0,lease:G,ttlMs:ha})}catch{N(T,400,{error:"Invalid lease request."})}}else if(A.startsWith("/leases/")&&(l.method==="PATCH"||l.method==="DELETE")){if(v!=="detached"){N(T,409,{error:"Bridge leases are only available for detached bridges."});return}let D="";try{D=decodeURIComponent(A.slice(8))}catch{N(T,400,{error:"Invalid lease id."});return}if(!D){N(T,400,{error:"A lease id is required."});return}if(l.method==="PATCH"){let z=J.heartbeat(D);if(!z){N(T,404,{error:"Lease not found."});return}N(T,200,{ok:!0,lease:z})}else{let z=J.release(D);N(T,z.found?200:404,{ok:z.found}),z.becameEmpty&&j()}}else if(l.method==="POST"&&A==="/shutdown"){if(v!=="detached"){N(T,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:v});return}N(T,200,{ok:!0}),setTimeout(P,100)}else if(l.method==="POST"&&A==="/restart"){if(v!=="detached"){N(T,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:v});return}N(T,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let D of B)try{D.res.end()}catch{}tt.close(()=>{fa(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(l.method==="GET"&&A==="/capabilities")C.searchParams.get("refresh")==="omp"&&await $(),N(T,200,{providers:x});else if(A.startsWith("/imprint/"))await It(l,T,A);else if(A.startsWith("/memory/"))await ut(l,T,A);else if(l.method==="POST"&&A==="/mcp/install")await Aa(l,T);else if(l.method==="POST"&&A==="/reply")await Rt(l,T);else if(l.method==="POST"&&A==="/cancel")vt(l,T);else if(l.method==="POST"&&A==="/materialize")N(T,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(l.method==="GET"&&A==="/materialization-runs")N(T,410,{error:"Use /projection-runs."});else if(l.method==="GET"&&A==="/projection-runs"){let D=await pe.loadRuns();N(T,200,D)}else if(l.method==="GET"&&A==="/projection/proposals"){let D=await pe.loadModelProposals();N(T,200,D)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/apply-selected")){let D=A.slice(22,-15);await Yo(D,l,T)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/apply")){let D=A.slice(22,-6);await At(D,T)}else if(l.method==="POST"&&A.startsWith("/projection/proposals/")&&A.endsWith("/dismiss")){let D=A.slice(22,-8);await eo(D,l,T)}else if(A.startsWith("/model/proposals/"))N(T,410,{error:"Use /projection/proposals."});else if(A==="/model/component"||A==="/model/token")N(T,410,{error:"Direct model editing was removed. Project understanding changes through collaboration and canonical projection."});else if(l.method==="POST"&&A==="/model/consolidate")N(T,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(l.method==="POST"&&A==="/model/synthesize")N(T,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(l.method==="GET"&&A==="/model"){let D=await pe.loadModel();N(T,200,{model:D})}else if(l.method==="GET"&&A.startsWith("/jobs/")&&A.endsWith("/events")){let D=A.slice(6,A.length-7),z=parseInt(C.searchParams.get("afterSeq")??"-1",10),U=L.getBufferedEvents(D,isNaN(z)?-1:z);U?N(T,200,U):N(T,404,{error:"Unknown job"})}else if(l.method==="GET"&&k.startsWith("/files/"))await Ma(k.slice(7),T);else if(l.method==="GET"&&A==="/threads/recent"){let D=Math.min(Math.max(parseInt(C.searchParams.get("limit")??"5",10)||5,1),200),z=await _.listRecent(D);N(T,200,z)}else if(l.method==="POST"&&A==="/workspace/clear"){let D=[...L.cancelAll(),...R.cancelAll()];for(let U of D)U.threadId&&await _.appendMessage(U.threadId,{role:"assistant",timestamp:Date.now(),jobId:U.id,cancelled:!0});De.length=0;let z=await _.advanceWorkspaceGeneration();for(let U of B)Zn(U,{type:"workspace_cleared",workspaceGeneration:z});N(T,200,{cleared:!0,workspaceGeneration:z})}else if(l.method==="GET"&&A.startsWith("/decision/")){let D=A.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(D))N(T,400,{error:"Invalid decision id"});else{let z=await _.getThread(D),U=[...z?.messages??[]].reverse().find(G=>G.annotationSnapshot);if(z&&U?.annotationSnapshot){let G=[...z.messages].reverse().find(ge=>ge.resolutions?.length);N(T,200,{decision:{id:z.id,createdAt:U.timestamp,url:U.annotationSnapshot.url,viewport:U.annotationSnapshot.viewport,color:U.annotationSnapshot.color,annotations:U.annotationSnapshot.annotations,resolutions:G?.resolutions??[]},authority:"thread_snapshot"})}else{let G=await qe.loadDecision(D);G?N(T,200,{decision:G,authority:"legacy_archive"}):N(T,404,{error:"Decision not found"})}}}else if(l.method==="GET"&&A.startsWith("/thread/")){let D=A.slice(8);await ja(D,T)}else if(l.method==="POST"&&A.startsWith("/thread/")&&A.endsWith("/archive")){let D=A.slice(8,-8);await ti(D,T)}else if(l.method==="DELETE"&&A.startsWith("/thread/")){let D=A.slice(8);await ti(D,T)}else N(T,404,{error:"Not found"})}catch(D){console.error("[Bridge] Request error:",D),N(T,500,{error:D instanceof Error?D.message:"Internal error"})}});async function ze(l,T,O){if(l.method!=="POST"){N(T,405,{error:"Ambient endpoints accept POST requests only."});return}let k=await Fe(l,tu),C=typeof k.sessionId=="string"?k.sessionId.trim():"",A=typeof k.turnId=="string"?k.turnId.trim():"",q=typeof k.executionOwner=="string"?k.executionOwner:void 0,D=qi(k.knowledgeView);if(O==="/ambient/context"){let z=typeof k.query=="string"?k.query.trim():"";if(!z){N(T,400,{error:"query is required."});return}let U=Array.isArray(k.subjectHints)?k.subjectHints.filter(G=>typeof G=="string"&&!!G.trim()).slice(0,20):void 0;N(T,200,await Te.expandContext({query:z,subjectHints:U,knowledgeView:D}));return}if(O==="/ambient/turns/assess"){let z=typeof k.threadId=="string"?k.threadId.trim():"",U=typeof k.jobId=="string"?k.jobId.trim():"",G=typeof k.assessmentText=="string"?k.assessmentText.trim():"";if(!z||!U||!G){N(T,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(k.semanticCandidates)?k.semanticCandidates.flatMap(ye=>{if(!ye||typeof ye!="object"||Array.isArray(ye))return[];let ue=ye,ce=typeof ue.claim=="string"?ue.claim.trim():"",te=typeof ue.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(ue.proposedKind)?ue.proposedKind:void 0;return ce?[{claim:ce,rationale:typeof ue.rationale=="string"?ue.rationale.trim():void 0,proposedKind:te,sourceText:typeof ue.sourceText=="string"?ue.sourceText.trim():void 0}]:[]}).slice(0,8):[],K=await Te.assess({threadId:z,jobId:U,assessmentText:G,semanticCandidates:ge});N(T,K.status==="committed"||K.status==="assessed"?200:K.status==="rejected"?422:404,K);return}if(!C||!A||C.length>256||A.length>256){N(T,400,{error:"Valid sessionId and turnId values are required."});return}if(O==="/ambient/turns/prepare"){let z=typeof k.prompt=="string"?k.prompt.trim():"";if(!z){N(T,400,{error:"prompt is required."});return}N(T,200,await Te.prepare({sessionId:C,turnId:A,prompt:z,model:typeof k.model=="string"?k.model:void 0,executionOwner:q,knowledgeView:D}));return}if(O==="/ambient/turns/event"){let z=typeof k.toolName=="string"?k.toolName.trim():"";if(!z){N(T,400,{error:"toolName is required."});return}N(T,200,await Te.recordEvent({sessionId:C,turnId:A,executionOwner:q,toolName:z,toolUseId:typeof k.toolUseId=="string"?k.toolUseId:void 0,toolInput:k.toolInput,toolResponse:k.toolResponse}));return}if(O==="/ambient/turns/complete"){N(T,200,await Te.complete({sessionId:C,turnId:A,executionOwner:q,lastAssistantMessage:typeof k.lastAssistantMessage=="string"?k.lastAssistantMessage:void 0,model:typeof k.model=="string"?k.model:void 0}));return}N(T,404,{error:"Ambient endpoint not found."})}async function ut(l,T,O){try{if(l.method==="GET"&&O==="/memory/status"){N(T,200,await Z.status());return}if(l.method==="GET"&&O==="/memory/diagnostics"){N(T,200,await Z.diagnostics());return}if(l.method==="GET"&&O==="/memory/model-view"){N(T,200,await Z.getModelView());return}if(l.method==="GET"&&O==="/memory/imprint-view"){let k=await _.load(),C=[...new Set(Object.values(k.threads).flatMap(A=>Yn(A.messages)))];N(T,200,await Z.getImprintView(C,new Set(Object.keys(k.threads))));return}if(l.method==="POST"&&O==="/memory/constraints"){let k=await Fe(l),C=typeof k.reactComponent=="string"?k.reactComponent.trim():"",A=await Z.getModelView(),q=C?A.entries.filter(D=>D.key===`components.${C}`||D.key.startsWith(`components.${C}.`)):[];N(T,200,{modelEntries:q});return}if(l.method==="POST"&&O==="/memory/conversation-action"){let k=await Fe(l),C=typeof k.threadId=="string"?k.threadId:"",A=typeof k.proposalId=="string"?k.proposalId:"",q=String(k.action);if(!C||!A||!["accept","edit_and_accept","reject","defer"].includes(q)){N(T,400,{error:"A valid thread, proposal, and review action are required."});return}let D=await _.getThread(C),z=D?.messages.find(Ie=>Ie.memoryReviewCard?.proposalId===A)?.memoryReviewCard,U=D?.messages.flatMap(Ie=>Ie.memoryReview?.packets??[]).find(Ie=>Ie.proposalId===A),G=D?.elementIdentifiers.some(Ie=>Ie.startsWith("codex-session:"))?(await Z.findPendingProposalsForThread(C)).find(Ie=>Ie.proposalId===A):void 0,ge=typeof k.kind=="string"&&["principle","preference","rule","constraint"].includes(k.kind)?k.kind:void 0,K=z?.kind??U?.proposedKind??G?.proposedKind??ge;if(!D||!z&&!U&&!G){N(T,409,{error:"This decision candidate was not surfaced in the thread."});return}if((q==="accept"||q==="edit_and_accept")&&!K){N(T,400,{error:"The decision kind is required to accept this candidate."});return}let ye=await pe.findModelProposalsByThread(C),ue=(await Promise.all(ye.map(async Ie=>({proposal:Ie,matches:(await Promise.all(Ie.decisionIds.map(Ke=>Z.findPendingProposalForLegacyDecision(Ke)))).some(Ke=>Ke?.proposalId===A)})))).find(Ie=>Ie.matches)?.proposal,ce={proposalId:A,action:q,kind:K,claim:q==="edit_and_accept"&&typeof k.claim=="string"?k.claim.trim():void 0,reason:q==="defer"?void 0:`The owner explicitly chose ${q.replaceAll("_"," ")} from the decision review card.`,taskContext:q==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:q==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){N(T,400,{error:"Edited decision wording is required."});return}let te=await Z.commitConversationalReview(ce),ae=`memory-${yt().slice(0,8)}`,ke=q==="accept"?"> Accepted decision":q==="edit_and_accept"?"> Edited and accepted decision":q==="reject"?"> Rejected decision":"> Deferred decision";await _.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:ae,replyToQuestion:ke}),await _.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:ae,responseText:"",memoryReceipt:te,provider:yn(typeof k.provider=="string"?k.provider:void 0),model:typeof k.model=="string"?k.model:void 0}),te.status==="committed"&&ue&&await pe.dismissModelProposal(ue.id);let Re=yn(typeof k.provider=="string"?k.provider:void 0);te.status==="committed"&&te.decisionId&&(Re==="claude"||Re==="codex")&&await bt({provider:Re,model:typeof k.model=="string"?k.model:void 0,agentSettings:Gt(k),threadId:C,reason:`Project accepted decision ${te.decisionId}`}),N(T,te.status==="committed"?200:409,{receipt:te});return}if(l.method==="POST"&&O==="/memory/analyze"){let k=await Fe(l),C=await Z.analyzeLegacy({projectKey:typeof k.projectKey=="string"?k.projectKey:void 0}),A=Object.fromEntries([...new Set(C.issues.map(q=>q.code))].map(q=>[q,C.issues.filter(D=>D.code===q).length]));N(T,200,{...C,issues:void 0,issueCounts:A});return}if(l.method==="POST"&&O==="/memory/review"){let k=await Fe(l),C=await Z.review(fr(k.query),{projectKey:typeof k.projectKey=="string"?k.projectKey:void 0});N(T,200,C);return}if(l.method==="POST"&&O==="/memory/context"){let k=await Fe(l),C=await Z.contextualize(fr(k.query),{projectKey:typeof k.projectKey=="string"?k.projectKey:void 0});N(T,200,C);return}if(l.method==="POST"&&O==="/memory/initialize"){let k=await Fe(l),C=await Z.initializeFromLegacy({confirmed:k.confirm===!0,projectKey:typeof k.projectKey=="string"?k.projectKey:void 0,writerVersion:mt});N(T,201,{status:C.status,report:{source:C.report.source,imported:C.report.imported,unresolvedAcceptance:C.report.unresolvedAcceptance,deferredModelEntries:C.report.deferredModelEntries,proofCases:C.report.proofCases,schemaIssues:C.report.schemaIssues}});return}if(l.method==="POST"&&O==="/memory/plan"){let k=await Fe(l),C=await Z.planReview(mr(k.command),{projectKey:typeof k.projectKey=="string"?k.projectKey:void 0});N(T,C.result.ok?200:422,C);return}if(l.method==="POST"&&O==="/memory/commit"){let k=await Fe(l),C=k.transaction&&typeof k.transaction=="object"&&!Array.isArray(k.transaction)?k.transaction:{},A=await Z.commitReview(mr(k.command),{transactionId:typeof C.transactionId=="string"?C.transactionId:"",committedAt:typeof C.committedAt=="string"?C.committedAt:""});N(T,200,{status:await Z.status(),journal:A.report});return}if(l.method==="POST"&&O==="/memory/recover"){let k=await Fe(l),C=await Z.recover(k.confirm===!0);N(T,200,{status:await Z.status(),journal:C.report});return}N(T,404,{error:"Memory endpoint not found."})}catch(k){let C=k instanceof Error?k.message:String(k),A=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(C),q=/required|invalid|unsupported|expected|must be|confirmation/i.test(C);if(A||q){N(T,A?409:400,{error:C});return}throw k}}async function It(l,T,O){if(l.method==="GET"&&O==="/imprint/status"){let[k,C]=await Promise.all([se.store.load(),_.load()]),A=[...new Set(Object.values(C.threads).flatMap(q=>Yn(q.messages)))].filter(q=>k.graph.explanations.some(D=>D.id===q&&D.state==="testing"));N(T,200,{state:"ready",head:k.graph.head,updatedAt:k.graph.updatedAt,explanationCount:k.graph.explanations.filter(q=>q.state!=="retired").length,concreteCount:k.graph.concrete.length,relationCount:k.graph.relations.length,pendingGroundingCount:A.length,recoveredTransactions:k.recoveredTransactions,admission:se.diagnostics(),admissionWindowStartedAt:e});return}if(l.method==="POST"&&O==="/imprint/action"){let k=await Fe(l),C=typeof k.threadId=="string"?k.threadId:"",A=typeof k.transactionId=="string"?k.transactionId:"",q=String(k.action);if(!C||!A||!["yes","this_time","no"].includes(q)){N(T,400,{error:"A valid thread, imprint update, and action are required."});return}let z=await _.getThread(C),U=[...z?.messages??[]].reverse().find(ce=>ce.role==="assistant"&&ce.imprintSummary?.transactionId===A),G=U?.imprintSummary;if(!z||!U||!G){N(T,409,{error:"This imprint summary is not available in the thread."});return}if(G.resolvedAction){N(T,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${yt().slice(0,8)}`;await se.applyGroundingAction({summary:G,action:q,threadId:C,jobId:ge}),q!=="no"&&await Z.recordImprintEvidence({summary:G,action:q,threadId:C,jobId:ge}).catch(ce=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ce));let K=an(U.result,!!U.question),ye=U.turn?{...U.turn,result:an(U.turn.result,!!U.question)}:void 0;await _.updateAssistantMessage(C,U.jobId,{imprintSummary:{...G,resolvedAction:q},...K?{result:K}:{},...ye?{turn:ye}:{}});let ue={yes:"> Yes",this_time:"> This time",no:"> No"};if(await _.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:ge,replyToQuestion:ue[q]}),q==="no"){let ce="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",te=_n({question:ce});await _.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:ge,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ce,turn:{phase:"complete",orientation:[],result:te},result:te})}N(T,200,{ok:!0,action:q});return}N(T,404,{error:"Imprint endpoint not found."})}async function wt(l,T){let{screenshot:O,feedback:k,color:C,provider:A,model:q,reasoningEffort:D,serviceTier:z,sourceId:U,continuationThreadId:G,continuationTargetBindingId:ge,continuationSelectorAliases:K,pastedImages:ye,pageScreenshots:ue}=await Dr(l),ce=C,te;try{te=JSON.parse(k)}catch{N(T,400,{error:"Invalid feedback JSON"});return}let ae=te.annotations.flatMap(oe=>(oe.attachments??[]).map(Je=>({id:Je.id,annotationId:oe.id}))),ke;try{ke=ae.length>0?await de.promote(ae):void 0}catch(oe){N(T,409,{error:oe instanceof Error?oe.message:"Draft attachment unavailable."});return}let Re=yt().slice(0,8),Ie={};if(ue.length>0)for(let oe of ue){let Je=encodeURIComponent(oe.pathname),Le=it(d,`screenshot-${Re}-${Je}.webp`);await Ko(Le,oe.data),Ie[oe.pathname]=Le}let Ke=it(d,`screenshot-${Re}.webp`);await Ko(Ke,O);let Pe={};if(ye.length>0)for(let oe of ye){let Je=it(d,`pasted-${Re}-${oe.annotationId}-${oe.index}.webp`);await Ko(Je,oe.data),Pe[oe.annotationId]||(Pe[oe.annotationId]=[]),Pe[oe.annotationId].push(Je)}let X=sa(te),ve=aa(te,K),xt=Vr(te,K),Ae,ne=!1,we;if(X.length>0){let oe=await _.findOrCreateContinuationThread(X,`thread-${yt()}`,G,ve,xt,ge);Ae=oe.thread.id,we=oe.decision,ne=we.action==="continued",console.log(`[Continuation] ${JSON.stringify({event:"continuation_resolution",...we,...G?{preferredThreadId:G}:{},...ge?{preferredTargetBindingId:ge}:{},resolvedThreadId:Ae,...oe.targetBindings[0]?.id?{resolvedTargetBindingId:oe.targetBindings[0].id}:{}})}`),ne&&(ce=oe.thread.messages.find(Je=>Je.annotationSnapshot?.color)?.annotationSnapshot?.color??ce)}else Ae=(await _.createThread(`thread-${yt()}`,[])).id;let Ye=ne||(await _.findContinuationThread(X))?.id===Ae,He=te.annotations.map(oe=>oe.id),Be=Object.keys(Ie).length>0,$e=await io(Z,te,X,oe=>console.warn(`[\u22B9 ${u}:${Re}] Contextual memory unavailable; continuing without it:`,oe instanceof Error?oe.message:String(oe))),at=(await _.getThread(Ae))?.messages??[],V=await se.contextualize({text:Xt(te),subjectHints:ms(te,X),pendingGroundingExplanationIds:Yn(at),correctionExplanationIds:ya(at)}).catch(oe=>{console.warn(`[\u22B9 ${u}:${Re}] Imprint context unavailable; continuing without it:`,oe instanceof Error?oe.message:String(oe))}),be=Wr({jobId:Re,threadId:Ae,artifactIds:da(te,Re)}),he={id:Re,status:"queued",screenshotPath:Ke,feedback:te,createdAt:Date.now(),color:ce,threadId:Ae,annotationIds:He,provider:yn(A),model:q||void 0,agentSettings:Gt({reasoningEffort:D,serviceTier:z}),...Object.keys(Pe).length>0?{imagePaths:Pe}:{},...ke&&Object.keys(ke).length>0?{attachmentFiles:ke}:{},sourceId:U||void 0,...Be?{screenshotPaths:Ie}:{},...$e?{memoryReview:$e}:{},...V?{imprintContext:V}:{},lifecycle:be},Qe=new Set(te.annotations.map(oe=>oe.pathname).filter(Boolean)),Ut;if(Qe.size>1){let oe=new Map;for(let Je of te.annotations){let Le=Je.pathname||"(unknown)";oe.has(Le)||oe.set(Le,[]),oe.get(Le).push(Je.instruction||Ia({...te,annotations:[Je]}))}Ut=[...oe.entries()].map(([Je,Le])=>`\`${Je}\`
200
200
  ${Le.map(le=>`- ${le}`).join(`
201
201
  `)}`).join(`
202
- `)}else Ut=ga(te);let to=Ln(te,Object.keys(Pe).length>0?Pe:void 0,ke),no=ci(te),Mt=di(te);await _.appendMessage(Ae,{role:"human",timestamp:Date.now(),jobId:Re,screenshotPath:Ke,...Be?{screenshotPaths:Ie}:{},...Object.keys(Pe).length>0?{imagePaths:Pe}:{},...ke&&Object.keys(ke).length>0?{attachmentFiles:ke}:{},annotationIds:He,annotationSnapshot:{url:te.url,viewport:te.viewport,annotations:te.annotations,color:ce||void 0},feedbackSummary:Ut,...no?{requestText:no}:{},...Mt.length>0?{requestItems:Mt}:{},feedbackContext:to||void 0,...$e?{memoryReview:$e}:{},...V?{imprintContext:V}:{},lifecycle:be});let bn=L.enqueue(he),xn=await Promise.all(((await _.getThread(Ae))?.targetBindings??[]).map(async oe=>({...oe,continuationEligible:await _.isTargetBindingContinuationEligible(Ae,oe.id)})));N(S,200,{jobId:Re,position:bn,threadId:Ae,color:ce||void 0,continuedThread:ne,continuationDecision:we,continuationEligible:Ye,targetBindings:xn})}async function Rt(l,S){let O=l.headers["content-type"]||"",T,C,A,q,D,z,U,G,ge=[];if(O.includes("multipart/form-data")){let V=await Dr(l),be=V.feedback?JSON.parse(V.feedback):{};T=be.threadId,C=be.reply,A=be.color,q=be.provider,D=be.model,z=Gt(be),U=be.sourceId||V.sourceId,G=typeof be.memoryReviewProposalId=="string"?be.memoryReviewProposalId:void 0;for(let he of V.pastedImages)ge.push(he.data)}else{let V=[];for await(let Qe of l)V.push(typeof Qe=="string"?Buffer.from(Qe):Qe);let be=Buffer.concat(V).toString("utf-8"),he;try{he=JSON.parse(be)}catch{N(S,400,{error:"Invalid JSON"});return}T=he.threadId,C=he.reply,A=he.color,q=he.provider,D=he.model,z=Gt(he),U=he.sourceId,G=he.memoryReviewProposalId}if(!T||!C){N(S,400,{error:"Missing threadId or reply"});return}let K=await _.getThread(T);if(!K){N(S,404,{error:"Thread not found"});return}let ye;if(G){let V=await pe.findModelProposalsByThread(T);if(ye=(await Promise.all(V.flatMap(he=>he.authorityStatus==="accepted"?[]:he.decisionIds.map(async Qe=>({modelProposalId:he.id,underlying:await Z.findPendingProposalForLegacyDecision(Qe)}))))).filter(he=>!!he.underlying).find(he=>he.underlying.proposalId===G),!ye){N(S,409,{error:"The requested memory decision is not pending in this thread."});return}}let ue="";{let V=await _.getThreadHistory(T);for(let be=V.length-1;be>=0;be--)if(V[be].screenshotPath){ue=V[be].screenshotPath;break}}let ce=await ka(T);if(!ue&&!ce){N(S,400,{error:"No screenshot available"});return}let te=L.hasActiveThread(T),ae=te?L.getQueuedThreadJob(T,V=>V._replyText!==void 0||V._replyPrompt!==void 0):null,ke=ae?.id??yt().slice(0,8),Re=Gr({jobId:ke,threadId:T}),Ie=[],Ke=`${ke}-${Date.now()}`;for(let V=0;V<ge.length;V++){let be=it(d,`reply-${Ke}-${V}.webp`);await Ko(be,ge[V]),Ie.push(be)}await _.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:ke,replyToQuestion:C,screenshotPath:ue,...te?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{},lifecycle:{...Re,artifactIds:Ie.map((V,be)=>`reply-image:${ke}:${be}`)}});let Pe=await _.getThreadHistory(T),X=[...Pe].reverse().find(V=>V.memoryReview)?.memoryReview,ve=await se.contextualize({text:C,subjectHints:ms(Pe,K.elementIdentifiers),pendingGroundingExplanationIds:Yn(Pe),correctionExplanationIds:ha(Pe)}).catch(V=>{console.warn(`[\u22B9 ${u}:${ke}] Imprint context unavailable for reply; continuing without it:`,V instanceof Error?V.message:String(V))});ve&&await _.updateMessage(T,ke,{imprintContext:ve});let xt=new Set(Pe.flatMap(V=>V.memoryReceipt?.status==="committed"?[V.memoryReceipt.proposalId]:[])),Ae=[...Pe].reverse().find(V=>V.memoryReviewCard&&!xt.has(V.memoryReviewCard.proposalId))?.memoryReviewCard,ne=[];for(let V of Pe)if(V.annotationIds)for(let be of V.annotationIds)ne.includes(be)||ne.push(be);let we=yn(q),Ye=ye,He=Ye?[Ye.underlying.proposalId]:Ae?[Ae.proposalId]:[],Be=Ls(ue,Pe,we,Ie.length>0?Ie:void 0);if(Ye?Be+=["","## Decision review card",`Privately review proposal ${Ye.underlying.proposalId}: ${Ye.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(`
202
+ `)}else Ut=Ia(te);let to=Ln(te,Object.keys(Pe).length>0?Pe:void 0,ke),no=li(te),Mt=ci(te);await _.appendMessage(Ae,{role:"human",timestamp:Date.now(),jobId:Re,screenshotPath:Ke,...Be?{screenshotPaths:Ie}:{},...Object.keys(Pe).length>0?{imagePaths:Pe}:{},...ke&&Object.keys(ke).length>0?{attachmentFiles:ke}:{},annotationIds:He,annotationSnapshot:{url:te.url,viewport:te.viewport,annotations:te.annotations,color:ce||void 0},feedbackSummary:Ut,...no?{requestText:no}:{},...Mt.length>0?{requestItems:Mt}:{},feedbackContext:to||void 0,...$e?{memoryReview:$e}:{},...V?{imprintContext:V}:{},lifecycle:be});let bn=L.enqueue(he),xn=await Promise.all(((await _.getThread(Ae))?.targetBindings??[]).map(async oe=>({...oe,continuationEligible:await _.isTargetBindingContinuationEligible(Ae,oe.id)})));N(T,200,{jobId:Re,position:bn,threadId:Ae,color:ce||void 0,continuedThread:ne,continuationDecision:we,continuationEligible:Ye,targetBindings:xn})}async function Rt(l,T){let O=l.headers["content-type"]||"",k,C,A,q,D,z,U,G,ge=[];if(O.includes("multipart/form-data")){let V=await Dr(l),be=V.feedback?JSON.parse(V.feedback):{};k=be.threadId,C=be.reply,A=be.color,q=be.provider,D=be.model,z=Gt(be),U=be.sourceId||V.sourceId,G=typeof be.memoryReviewProposalId=="string"?be.memoryReviewProposalId:void 0;for(let he of V.pastedImages)ge.push(he.data)}else{let V=[];for await(let Qe of l)V.push(typeof Qe=="string"?Buffer.from(Qe):Qe);let be=Buffer.concat(V).toString("utf-8"),he;try{he=JSON.parse(be)}catch{N(T,400,{error:"Invalid JSON"});return}k=he.threadId,C=he.reply,A=he.color,q=he.provider,D=he.model,z=Gt(he),U=he.sourceId,G=he.memoryReviewProposalId}if(!k||!C){N(T,400,{error:"Missing threadId or reply"});return}let K=await _.getThread(k);if(!K){N(T,404,{error:"Thread not found"});return}let ye;if(G){let V=await pe.findModelProposalsByThread(k);if(ye=(await Promise.all(V.flatMap(he=>he.authorityStatus==="accepted"?[]:he.decisionIds.map(async Qe=>({modelProposalId:he.id,underlying:await Z.findPendingProposalForLegacyDecision(Qe)}))))).filter(he=>!!he.underlying).find(he=>he.underlying.proposalId===G),!ye){N(T,409,{error:"The requested memory decision is not pending in this thread."});return}}let ue="";{let V=await _.getThreadHistory(k);for(let be=V.length-1;be>=0;be--)if(V[be].screenshotPath){ue=V[be].screenshotPath;break}}let ce=await Ra(k);if(!ue&&!ce){N(T,400,{error:"No screenshot available"});return}let te=L.hasActiveThread(k),ae=te?L.getQueuedThreadJob(k,V=>V._replyText!==void 0||V._replyPrompt!==void 0):null,ke=ae?.id??yt().slice(0,8),Re=Wr({jobId:ke,threadId:k}),Ie=[],Ke=`${ke}-${Date.now()}`;for(let V=0;V<ge.length;V++){let be=it(d,`reply-${Ke}-${V}.webp`);await Ko(be,ge[V]),Ie.push(be)}await _.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:ke,replyToQuestion:C,screenshotPath:ue,...te?{queued:!0}:{},...Ie.length>0?{replyImagePaths:Ie}:{},lifecycle:{...Re,artifactIds:Ie.map((V,be)=>`reply-image:${ke}:${be}`)}});let Pe=await _.getThreadHistory(k),X=[...Pe].reverse().find(V=>V.memoryReview)?.memoryReview,ve=await se.contextualize({text:C,subjectHints:fs(Pe,K.elementIdentifiers),pendingGroundingExplanationIds:Yn(Pe),correctionExplanationIds:ya(Pe)}).catch(V=>{console.warn(`[\u22B9 ${u}:${ke}] Imprint context unavailable for reply; continuing without it:`,V instanceof Error?V.message:String(V))});ve&&await _.updateMessage(k,ke,{imprintContext:ve});let xt=new Set(Pe.flatMap(V=>V.memoryReceipt?.status==="committed"?[V.memoryReceipt.proposalId]:[])),Ae=[...Pe].reverse().find(V=>V.memoryReviewCard&&!xt.has(V.memoryReviewCard.proposalId))?.memoryReviewCard,ne=[];for(let V of Pe)if(V.annotationIds)for(let be of V.annotationIds)ne.includes(be)||ne.push(be);let we=yn(q),Ye=ye,He=Ye?[Ye.underlying.proposalId]:Ae?[Ae.proposalId]:[],Be=Us(ue,Pe,we,Ie.length>0?Ie:void 0);if(Ye?Be+=["","## Decision review card",`Privately review proposal ${Ye.underlying.proposalId}: ${Ye.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(`
203
203
  `):Ae&&(Be+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Ae)}`,"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(`
204
- `)),ae){let V=ae,he=[...V._replyTexts??(V._replyText?[V._replyText]:[]),C],Qe=[...V._replyImagePaths??[],...Ie];V._replyTexts=he,V._replyText=fa(he),V._replyImagePaths=Qe.length>0?Qe:void 0,V._replyPrompt=Be,V.annotationIds=ne.length>0?ne:V.annotationIds,V.agentSettings=z??V.agentSettings,V.memoryReview=X??V.memoryReview,V.imprintContext=ve??V.imprintContext,V.surfacedProposalIds=[...new Set([...V.surfacedProposalIds??[],...He])],V.lifecycle={...V.lifecycle??Re,submissionIds:[...new Set([...V.lifecycle?.submissionIds??[],...Re.submissionIds])],artifactIds:[...new Set([...V.lifecycle?.artifactIds??[],...Re.artifactIds])]},N(S,200,{jobId:ke,position:1,threadId:T,bundled:!0});return}let $e={id:ke,status:"queued",screenshotPath:ue,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:A,threadId:T,annotationIds:ne.length>0?ne:void 0,provider:we,model:D||void 0,agentSettings:z,sourceId:U||void 0,...X?{memoryReview:X}:{},...ve?{imprintContext:ve}:{},...He.length?{surfacedProposalIds:He}:{},lifecycle:Re};ce&&($e.kind=ce),$e._replyPrompt=Be,$e._replyTexts=[C],$e._replyText=fa([C]),Ie.length>0&&($e._replyImagePaths=Ie);let at=te?L.enqueueNext($e):L.enqueue($e);N(S,200,{jobId:ke,position:at,threadId:T})}function Qo(l,S){S.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),S.write(`event: connected
204
+ `)),ae){let V=ae,he=[...V._replyTexts??(V._replyText?[V._replyText]:[]),C],Qe=[...V._replyImagePaths??[],...Ie];V._replyTexts=he,V._replyText=ga(he),V._replyImagePaths=Qe.length>0?Qe:void 0,V._replyPrompt=Be,V.annotationIds=ne.length>0?ne:V.annotationIds,V.agentSettings=z??V.agentSettings,V.memoryReview=X??V.memoryReview,V.imprintContext=ve??V.imprintContext,V.surfacedProposalIds=[...new Set([...V.surfacedProposalIds??[],...He])],V.lifecycle={...V.lifecycle??Re,submissionIds:[...new Set([...V.lifecycle?.submissionIds??[],...Re.submissionIds])],artifactIds:[...new Set([...V.lifecycle?.artifactIds??[],...Re.artifactIds])]},N(T,200,{jobId:ke,position:1,threadId:k,bundled:!0});return}let $e={id:ke,status:"queued",screenshotPath:ue,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:A,threadId:k,annotationIds:ne.length>0?ne:void 0,provider:we,model:D||void 0,agentSettings:z,sourceId:U||void 0,...X?{memoryReview:X}:{},...ve?{imprintContext:ve}:{},...He.length?{surfacedProposalIds:He}:{},lifecycle:Re};ce&&($e.kind=ce),$e._replyPrompt=Be,$e._replyTexts=[C],$e._replyText=ga([C]),Ie.length>0&&($e._replyImagePaths=Ie);let at=te?L.enqueueNext($e):L.enqueue($e);N(T,200,{jobId:ke,position:at,threadId:k})}function Qo(l,T){T.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),T.write(`event: connected
205
205
  data: {"status":"connected"}
206
206
 
207
- `);let T=new URL(l.url||"/",`http://127.0.0.1:${u}`).searchParams.get("sourceId")||void 0,C={id:yt().slice(0,8),res:S,sourceId:T};B.add(C),l.on("close",()=>{B.delete(C)})}async function Xo(l,S,O){a??=Xs(l.headers),st();let T=[...L.allActive,...R.allActive.map(X=>({id:X.id,status:X.status,threadId:X.threadId,annotationIds:X.annotationIds??[],color:"#000000",kind:"project_model",standalone:X.standalone}))],[C,A,q,D,z]=await Promise.allSettled([pe.loadRuns(),pe.loadModelProposals(),Z.status(),se.store.load(),_.load()]),U=[],G=X=>X.reason instanceof Error?X.reason.message:String(X.reason);C.status==="rejected"&&U.push({subsystem:"projection",message:G(C)}),A.status==="rejected"&&U.push({subsystem:"projection",message:G(A)}),q.status==="rejected"?U.push({subsystem:"memory",message:G(q)}):q.value.state==="degraded"&&U.push({subsystem:"memory",message:q.value.error??"Product memory is degraded."}),D.status==="rejected"&&U.push({subsystem:"imprint",message:G(D)}),z.status==="rejected"&&U.push({subsystem:"threads",message:G(z)});let ge=C.status==="fulfilled"?C.value.runs:[],K=A.status==="fulfilled"?A.value.proposals:[],ye=Ys(ge,K),ue=ye.actionableProposals.map(X=>({id:X.id,status:X.status,title:X.title,summary:X.summary,decisionIds:X.decisionIds,threadId:X.threadId,runId:X.runId,presentationJobId:X.presentationJobId,authorityStatus:X.authorityStatus,underlyingProposalId:X.underlyingProposalId,createdAt:X.createdAt,updatedAt:X.updatedAt,appliedAt:X.appliedAt,dismissedAt:X.dismissedAt,error:X.error})),ce=q.status==="fulfilled"?q.value:{initialized:!1,state:"degraded",error:G(q)},te=z.status==="fulfilled"?[...new Set(Object.values(z.value.threads).flatMap(X=>Yn(X.messages)))]:[],ae=D.status==="fulfilled"?te.filter(X=>D.value.graph.explanations.some(ve=>ve.id===X&&ve.state==="testing")):[],ke=D.status==="fulfilled"?{state:"ready",head:D.value.graph.head,updatedAt:D.value.graph.updatedAt,explanationCount:D.value.graph.explanations.filter(X=>X.state!=="retired").length,concreteCount:D.value.graph.concrete.length,relationCount:D.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:D.value.recoveredTransactions,admission:se.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:G(D),pendingGroundingCount:ae.length,admission:se.diagnostics(),admissionWindowStartedAt:e},Re=U.length>0?"degraded":ce.state==="absent"||ce.state==="initializing"?"initializing":"healthy",Ie=T.filter(X=>_.isThreadInActiveWorkspace(X.threadId)),Ke=De.filter(X=>_.isThreadInActiveWorkspace(X.threadId)),Pe=new Date().toISOString();N(S,200,{ok:!0,schemaVersion:3,generatedAt:Pe,serverStartedAt:e,health:{state:Re,issues:U},version:mt,restartMode:w,projectId:i,workspaceGeneration:_.getActiveWorkspaceGeneration(),storeId:s.storeId,projectName:Ho(r),projectRoot:r,requestProjectId:O,projectIdVerified:O===i,devOrigin:a,capture:{native:{configured:!!y,endpoint:y?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:Ie[0]?{id:Ie[0].id,status:Ie[0].status}:null,activeJobs:Ie.map(X=>({id:X.id,status:X.status,threadId:X.threadId,annotationIds:X.annotationIds,color:X.color,kind:X.kind,standalone:"standalone"in X?X.standalone:void 0})),queueDepth:L.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:J.isActivated,count:J.size,nextExpiryAt:J.nextExpiryAt,shutdownPending:H},projection:{state:C.status==="fulfilled"&&A.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:ye.recentRuns,recentAppliedRuns:ye.recentAppliedRuns,actionableProposalCounts:ye.actionableProposalCounts,actionableProposals:ue},memory:ce,imprint:ke,recentJobsRetentionMs:Ue,recentJobs:Ke})}async function wn(l,S){let O=await new Promise(T=>{let C="";l.on("data",A=>{C+=A.toString()}),l.on("end",()=>T(C))});try{let T=JSON.parse(O);typeof T.devOrigin=="string"&&(a=T.devOrigin||null),N(S,200,{ok:!0,devOrigin:a})}catch{N(S,400,{error:"Invalid JSON"})}}async function We(l){let S=await xe.load();N(l,200,{ok:!0,...S})}async function Ve(l,S){let O=await Fe(l);if(!pa(O.theme)){N(S,400,{error:"theme must be light, dark, or auto"});return}let T=await xe.setTheme(O.theme);N(S,200,{ok:!0,exists:!0,preferences:T})}async function vt(l,S){let T=new URL(l.url||"/",`http://127.0.0.1:${u}`).searchParams.get("jobId"),C=T?L.allActive.filter(G=>G.id===T):L.allActive,A=T?R.allActive.filter(G=>G.id===T):R.allActive,q=[...C.map(G=>G.threadId),...A.map(G=>G.threadId)].filter(Boolean),D=T?L.cancelJob(T):L.cancelActive(),z=T?R.cancelJob(T):R.cancelActive(),U=!!(D||z);for(let G of q)await _.appendMessage(G,{role:"assistant",timestamp:Date.now(),jobId:T||z?.id||"",cancelled:!0});N(S,200,{cancelled:U})}async function bt(l){let S=yt().slice(0,8),O=l.threadId,T=!O;O||(O=(await _.createThread(`thread-${yt()}`,[])).id,Me.set(O,"project_model")),T&&await _.appendMessage(O,{role:"human",timestamp:Date.now(),jobId:S,feedbackSummary:l.reason}),await _.appendMessage(O,{role:"assistant",timestamp:Date.now(),jobId:S,responseText:T?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:l.model,provider:l.provider});let C={id:S,status:"queued",createdAt:Date.now(),provider:l.provider,model:l.model,agentSettings:l.agentSettings,threadId:O,annotationIds:l.annotationIds,sourceId:l.sourceId,standalone:T},A=R.enqueue(C);return{jobId:S,position:A,threadId:O}}async function At(l,S){let O=decodeURIComponent(l),T=await pe.findModelProposal(O);if(!T){N(S,404,{error:"Model proposal not found"});return}N(S,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:T})}async function Yo(l,S,O){let T=decodeURIComponent(l),C=[];for await(let K of S)C.push(typeof K=="string"?Buffer.from(K):K);let A;try{A=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{N(O,400,{error:"Invalid JSON"});return}let q=(A.changes??[]).flatMap(K=>{if(!Array.isArray(K.path)||K.path.length===0)return[];let ye=K.path.filter(ce=>typeof ce=="string"||typeof ce=="number");if(ye.length!==K.path.length)return[];let ue=Array.isArray(K.decisionIds)?K.decisionIds.filter(ce=>typeof ce=="string"):void 0;return[{path:ye,value:K.value,remove:K.remove===!0,decisionIds:ue}]});if(q.length===0){N(O,400,{error:"No selected model changes"});return}let D=(A.changeSummaries??[]).flatMap(K=>{if(!K||typeof K!="object")return[];let ye=Array.isArray(K.path)?K.path.filter(ue=>typeof ue=="string"||typeof ue=="number"):void 0;return Array.isArray(K.path)&&ye?.length!==K.path.length?[]:[{group:typeof K.group=="string"?K.group:void 0,label:typeof K.label=="string"?K.label:void 0,detail:typeof K.detail=="string"?K.detail:void 0,path:ye,value:K.value,currentValue:K.currentValue}]}),z=await pe.findModelProposal(T);if(!z){N(O,404,{error:"Model proposal not found"});return}if(z.authorityStatus!=="accepted"){N(O,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(z.status!=="pending"){N(O,409,{error:`Model proposal is already ${z.status}.`});return}let U=z.decisionIds.map(K=>{let ye=z.changes?.filter(te=>te.decisionIds.includes(K)).length??0,ue=q.filter(te=>te.decisionIds?.includes(K)).length,ce=ue===0?"unprojected":ye>ue?"partially_projected":"projected";return{decisionId:K,status:ce}}),G=await Z.applyModelProjection({runId:z.runId??z.id,presentationJobId:z.presentationJobId,decisionIds:z.decisionIds,changes:q.map(K=>({path:K.path,value:K.value,decisionIds:K.decisionIds})),coverage:U}),ge=await pe.applySelectedModelProposal(T,q,D);if(!ge){N(O,404,{error:"Model proposal not found"});return}if(ge.threadId){let K=yn(A.provider),ye=typeof A.model=="string"&&A.model?A.model:void 0;await _.appendMessage(ge.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ge.id}`,responseText:"",provider:K,model:ye})}N(O,200,{proposal:ge,projection:G})}async function eo(l,S,O){let T=decodeURIComponent(l),{provider:C,model:A}=await Ta(S),q=await pe.dismissModelProposal(T);if(!q){N(O,404,{error:"Model proposal not found"});return}q.threadId&&await _.appendMessage(q.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${q.id}`,responseText:"",provider:C,model:A}),N(O,200,{proposal:q})}async function Ta(l){try{let S=[];for await(let T of l)S.push(typeof T=="string"?Buffer.from(T):T);if(S.length===0)return{};let O=JSON.parse(Buffer.concat(S).toString());return{provider:yn(typeof O.provider=="string"?O.provider:void 0),model:typeof O.model=="string"&&O.model?O.model:void 0,agentSettings:Gt(O)}}catch{return{}}}async function ka(l){let S=Me.get(l);if(S)return S;let C=(await _.getThread(l))?.messages.find(A=>A.role==="human")?.feedbackSummary??"";if(C.startsWith("Synthesize rules"))return Me.set(l,"synthesize"),"synthesize";if(C.startsWith("Materialize model")||C.startsWith("Project model"))return Me.set(l,"project_model"),"project_model"}async function Pa(l,S){let O=[];for await(let z of l)O.push(typeof z=="string"?Buffer.from(z):z);let T;if(O.length>0)try{T=JSON.parse(Buffer.concat(O).toString("utf-8")).serverUrl}catch{}let C=[];x.claude?.available&&x.claude.mcp&&!x.claude.mcp.found&&C.push(await Ps(T)),x.codex?.available&&x.codex.mcp&&!x.codex.mcp.found&&C.push(await Rs(T)),x.copilot?.available&&x.copilot.mcp&&!x.copilot.mcp.found&&C.push(await As(T,x.copilot.path??k));let[A,q,D]=await Promise.all([Er(r),_r(r),Cr(r,x.copilot?.path??k)]);x.claude&&(x.claude.mcp=A),x.codex&&(x.codex.mcp=q),x.copilot&&(x.copilot.mcp=D),N(S,200,{results:C,capabilities:{providers:x}})}async function Ra(l,S){if(!l||l.includes("/")||l.includes("\\")||l.includes("..")){N(S,400,{error:"Invalid filename"});return}try{let O=[it(d,l),it(r,".popmelt","artifacts","thread-media",l),it(r,".popmelt","artifacts","eval-screenshots",l),it(r,".popmelt","evals","screenshots",l),it(r,".popmelt","screenshots",l)],T;for(let q of O)try{T=await Cp(q);break}catch{}if(!T)throw new Error("File not found");let C=l.split(".").pop()?.toLowerCase(),A=C==="png"?"image/png":C==="webp"?"image/webp":C==="jpg"||C==="jpeg"?"image/jpeg":C==="svg"?"image/svg+xml":C==="txt"?"text/plain; charset=utf-8":"application/octet-stream";S.writeHead(200,{"Content-Type":A,"Cache-Control":"public, max-age=3600"}),S.end(T)}catch{N(S,404,{error:"File not found"})}}function vn(l){return`/files/${Ho(l)}`}async function Aa(l,S){let O=await _.getThread(l);if(!O){N(S,404,{error:"Thread not found"});return}let T=O.messages.filter(U=>U.role==="assistant"&&U.responseText?.includes("Model suggestion ready")),C=await(T.length>0?pe.findModelProposalsByThread(l):Promise.resolve([])),A=await Promise.all(C.map(async(U,G)=>{if(U.authorityStatus==="accepted")return U;let ge=(await Promise.all(U.decisionIds.map(K=>Z.findPendingProposalForLegacyDecision(K)))).find(Boolean);return{...U,authorityStatus:"legacy_untrusted",presentationJobId:U.presentationJobId??T[G]?.jobId??T.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),q=[...A].sort((U,G)=>G.updatedAt-U.updatedAt)[0]??null,D=O.elementIdentifiers.some(U=>U.startsWith("codex-session:"))?await Z.findPendingProposalsForThread(l):[],z=O.messages.map(({screenshotPath:U,screenshotPaths:G,imagePaths:ge,attachmentFiles:K,replyImagePaths:ye,...ue})=>({...ue,...U?{screenshotUrl:vn(U)}:{},...G?{screenshotUrls:Object.fromEntries(Object.entries(G).map(([ce,te])=>[ce,vn(te)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([ce,te])=>[ce,te.map(vn)]))}:{},...K?{attachments:Object.fromEntries(Object.entries(K).map(([ce,te])=>[ce,te.map(({path:ae,...ke})=>({...ke,url:vn(ae)}))]))}:{},...ye?{replyImageUrls:ye.map(vn)}:{}}));N(S,200,{id:O.id,createdAt:O.createdAt,messages:z,modelProposal:q,modelProposals:A,decisionCandidates:D})}async function ei(l,S){let O=decodeURIComponent(l);if(!await _.archiveThread(O)){N(S,404,{archived:!1,error:"Thread not found"});return}N(S,200,{archived:!0})}let ti=9,ni=!1;for(let l=t;l<t+ti;l++)try{await su(tt,l),u=l,ni=!0,console.log(`[\u22B9 is watching :${u}]`);break}catch(S){if(S.code==="EADDRINUSE"){let O=await In(l);if(Wn(O,{projectId:i,version:mt,restartMode:w}))return console.log(`[\u22B9 already watching :${l}]`),{port:l,projectId:i,close:async()=>{}};continue}throw S}if(!ni)throw new Error(`[Bridge] All ports ${t}\u2013${t+ti-1} in use`);for(let[l,S]of Object.entries(x))!S.available||!S.path||f(l,S.path).then(O=>{if(O)console.log(`[Bridge] ${l} warmed up`);else{console.warn(`[Bridge] ${l} warm-up failed \u2014 marking unavailable`),S.available=!1,S.path=null;for(let T of B)Zn(T,{type:"capabilities_changed",data:{}})}});let Ma=setInterval(()=>{Ia(d).catch(()=>{}),de.sweep().catch(()=>{})},Up),oi=setInterval(()=>{J.expireStale().becameEmpty&&j()},Gp);return oi.unref?.(),{port:u,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(Ma),clearInterval(oi),ie(),J.clear(),await de.cleanupPartials(),await L.destroyAsync(),R.destroy();for(let l of B)try{l.res.end()}catch{}return B.clear(),new Promise(l=>{tt.close(()=>l()),tt.closeAllConnections?.()})}}}async function Ia(n){try{let e=await $p(n),t=Date.now();for(let o of e){let r=it(n,o);try{let i=await wa(r);t-i.mtimeMs>zp&&await Dp(r)}catch{}}}catch{}}var gu=1111,xa=3e4,yu=8e3;async function Iu(n){return mu(n).catch(()=>n)}async function Sa(n,e){let o=(await uu(e,"utf8").catch(()=>"")).slice(-yu).trim();return new Error(o?`${n}
207
+ `);let k=new URL(l.url||"/",`http://127.0.0.1:${u}`).searchParams.get("sourceId")||void 0,C={id:yt().slice(0,8),res:T,sourceId:k};B.add(C),l.on("close",()=>{B.delete(C)})}async function Xo(l,T,O){a??=Zs(l.headers),st();let k=[...L.allActive,...R.allActive.map(X=>({id:X.id,status:X.status,threadId:X.threadId,annotationIds:X.annotationIds??[],color:"#000000",kind:"project_model",standalone:X.standalone}))],[C,A,q,D,z]=await Promise.allSettled([pe.loadRuns(),pe.loadModelProposals(),Z.status(),se.store.load(),_.load()]),U=[],G=X=>X.reason instanceof Error?X.reason.message:String(X.reason);C.status==="rejected"&&U.push({subsystem:"projection",message:G(C)}),A.status==="rejected"&&U.push({subsystem:"projection",message:G(A)}),q.status==="rejected"?U.push({subsystem:"memory",message:G(q)}):q.value.state==="degraded"&&U.push({subsystem:"memory",message:q.value.error??"Product memory is degraded."}),D.status==="rejected"&&U.push({subsystem:"imprint",message:G(D)}),z.status==="rejected"&&U.push({subsystem:"threads",message:G(z)});let ge=C.status==="fulfilled"?C.value.runs:[],K=A.status==="fulfilled"?A.value.proposals:[],ye=ea(ge,K),ue=ye.actionableProposals.map(X=>({id:X.id,status:X.status,title:X.title,summary:X.summary,decisionIds:X.decisionIds,threadId:X.threadId,runId:X.runId,presentationJobId:X.presentationJobId,authorityStatus:X.authorityStatus,underlyingProposalId:X.underlyingProposalId,createdAt:X.createdAt,updatedAt:X.updatedAt,appliedAt:X.appliedAt,dismissedAt:X.dismissedAt,error:X.error})),ce=q.status==="fulfilled"?q.value:{initialized:!1,state:"degraded",error:G(q)},te=z.status==="fulfilled"?[...new Set(Object.values(z.value.threads).flatMap(X=>Yn(X.messages)))]:[],ae=D.status==="fulfilled"?te.filter(X=>D.value.graph.explanations.some(ve=>ve.id===X&&ve.state==="testing")):[],ke=D.status==="fulfilled"?{state:"ready",head:D.value.graph.head,updatedAt:D.value.graph.updatedAt,explanationCount:D.value.graph.explanations.filter(X=>X.state!=="retired").length,concreteCount:D.value.graph.concrete.length,relationCount:D.value.graph.relations.length,pendingGroundingCount:ae.length,recoveredTransactions:D.value.recoveredTransactions,admission:se.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:G(D),pendingGroundingCount:ae.length,admission:se.diagnostics(),admissionWindowStartedAt:e},Re=U.length>0?"degraded":ce.state==="absent"||ce.state==="initializing"?"initializing":"healthy",Ie=k.filter(X=>_.isThreadInActiveWorkspace(X.threadId)),Ke=De.filter(X=>_.isThreadInActiveWorkspace(X.threadId)),Pe=new Date().toISOString();N(T,200,{ok:!0,schemaVersion:3,generatedAt:Pe,serverStartedAt:e,health:{state:Re,issues:U},version:mt,restartMode:v,projectId:i,workspaceGeneration:_.getActiveWorkspaceGeneration(),storeId:s.storeId,projectName:Ho(r),projectRoot:r,requestProjectId:O,projectIdVerified:O===i,devOrigin:a,capture:{native:{configured:!!I,endpoint:I?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:Ie[0]?{id:Ie[0].id,status:Ie[0].status}:null,activeJobs:Ie.map(X=>({id:X.id,status:X.status,threadId:X.threadId,annotationIds:X.annotationIds,color:X.color,kind:X.kind,standalone:"standalone"in X?X.standalone:void 0})),queueDepth:L.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:J.isActivated,count:J.size,nextExpiryAt:J.nextExpiryAt,shutdownPending:H},projection:{state:C.status==="fulfilled"&&A.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:ye.recentRuns,recentAppliedRuns:ye.recentAppliedRuns,actionableProposalCounts:ye.actionableProposalCounts,actionableProposals:ue},memory:ce,imprint:ke,recentJobsRetentionMs:Ue,recentJobs:Ke})}async function wn(l,T){let O=await new Promise(k=>{let C="";l.on("data",A=>{C+=A.toString()}),l.on("end",()=>k(C))});try{let k=JSON.parse(O);typeof k.devOrigin=="string"&&(a=k.devOrigin||null),N(T,200,{ok:!0,devOrigin:a})}catch{N(T,400,{error:"Invalid JSON"})}}async function We(l){let T=await xe.load();N(l,200,{ok:!0,...T})}async function Ve(l,T){let O=await Fe(l);if(!ma(O.theme)){N(T,400,{error:"theme must be light, dark, or auto"});return}let k=await xe.setTheme(O.theme);N(T,200,{ok:!0,exists:!0,preferences:k})}async function vt(l,T){let k=new URL(l.url||"/",`http://127.0.0.1:${u}`).searchParams.get("jobId"),C=k?L.allActive.filter(G=>G.id===k):L.allActive,A=k?R.allActive.filter(G=>G.id===k):R.allActive,q=[...C.map(G=>G.threadId),...A.map(G=>G.threadId)].filter(Boolean),D=k?L.cancelJob(k):L.cancelActive(),z=k?R.cancelJob(k):R.cancelActive(),U=!!(D||z);for(let G of q)await _.appendMessage(G,{role:"assistant",timestamp:Date.now(),jobId:k||z?.id||"",cancelled:!0});N(T,200,{cancelled:U})}async function bt(l){let T=yt().slice(0,8),O=l.threadId,k=!O;O||(O=(await _.createThread(`thread-${yt()}`,[])).id,Me.set(O,"project_model")),k&&await _.appendMessage(O,{role:"human",timestamp:Date.now(),jobId:T,feedbackSummary:l.reason}),await _.appendMessage(O,{role:"assistant",timestamp:Date.now(),jobId:T,responseText:k?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:l.model,provider:l.provider});let C={id:T,status:"queued",createdAt:Date.now(),provider:l.provider,model:l.model,agentSettings:l.agentSettings,threadId:O,annotationIds:l.annotationIds,sourceId:l.sourceId,standalone:k},A=R.enqueue(C);return{jobId:T,position:A,threadId:O}}async function At(l,T){let O=decodeURIComponent(l),k=await pe.findModelProposal(O);if(!k){N(T,404,{error:"Model proposal not found"});return}N(T,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:k})}async function Yo(l,T,O){let k=decodeURIComponent(l),C=[];for await(let K of T)C.push(typeof K=="string"?Buffer.from(K):K);let A;try{A=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{N(O,400,{error:"Invalid JSON"});return}let q=(A.changes??[]).flatMap(K=>{if(!Array.isArray(K.path)||K.path.length===0)return[];let ye=K.path.filter(ce=>typeof ce=="string"||typeof ce=="number");if(ye.length!==K.path.length)return[];let ue=Array.isArray(K.decisionIds)?K.decisionIds.filter(ce=>typeof ce=="string"):void 0;return[{path:ye,value:K.value,remove:K.remove===!0,decisionIds:ue}]});if(q.length===0){N(O,400,{error:"No selected model changes"});return}let D=(A.changeSummaries??[]).flatMap(K=>{if(!K||typeof K!="object")return[];let ye=Array.isArray(K.path)?K.path.filter(ue=>typeof ue=="string"||typeof ue=="number"):void 0;return Array.isArray(K.path)&&ye?.length!==K.path.length?[]:[{group:typeof K.group=="string"?K.group:void 0,label:typeof K.label=="string"?K.label:void 0,detail:typeof K.detail=="string"?K.detail:void 0,path:ye,value:K.value,currentValue:K.currentValue}]}),z=await pe.findModelProposal(k);if(!z){N(O,404,{error:"Model proposal not found"});return}if(z.authorityStatus!=="accepted"){N(O,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(z.status!=="pending"){N(O,409,{error:`Model proposal is already ${z.status}.`});return}let U=z.decisionIds.map(K=>{let ye=z.changes?.filter(te=>te.decisionIds.includes(K)).length??0,ue=q.filter(te=>te.decisionIds?.includes(K)).length,ce=ue===0?"unprojected":ye>ue?"partially_projected":"projected";return{decisionId:K,status:ce}}),G=await Z.applyModelProjection({runId:z.runId??z.id,presentationJobId:z.presentationJobId,decisionIds:z.decisionIds,changes:q.map(K=>({path:K.path,value:K.value,decisionIds:K.decisionIds})),coverage:U}),ge=await pe.applySelectedModelProposal(k,q,D);if(!ge){N(O,404,{error:"Model proposal not found"});return}if(ge.threadId){let K=yn(A.provider),ye=typeof A.model=="string"&&A.model?A.model:void 0;await _.appendMessage(ge.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ge.id}`,responseText:"",provider:K,model:ye})}N(O,200,{proposal:ge,projection:G})}async function eo(l,T,O){let k=decodeURIComponent(l),{provider:C,model:A}=await Pa(T),q=await pe.dismissModelProposal(k);if(!q){N(O,404,{error:"Model proposal not found"});return}q.threadId&&await _.appendMessage(q.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${q.id}`,responseText:"",provider:C,model:A}),N(O,200,{proposal:q})}async function Pa(l){try{let T=[];for await(let k of l)T.push(typeof k=="string"?Buffer.from(k):k);if(T.length===0)return{};let O=JSON.parse(Buffer.concat(T).toString());return{provider:yn(typeof O.provider=="string"?O.provider:void 0),model:typeof O.model=="string"&&O.model?O.model:void 0,agentSettings:Gt(O)}}catch{return{}}}async function Ra(l){let T=Me.get(l);if(T)return T;let C=(await _.getThread(l))?.messages.find(A=>A.role==="human")?.feedbackSummary??"";if(C.startsWith("Synthesize rules"))return Me.set(l,"synthesize"),"synthesize";if(C.startsWith("Materialize model")||C.startsWith("Project model"))return Me.set(l,"project_model"),"project_model"}async function Aa(l,T){let O=[];for await(let z of l)O.push(typeof z=="string"?Buffer.from(z):z);let k;if(O.length>0)try{k=JSON.parse(Buffer.concat(O).toString("utf-8")).serverUrl}catch{}let C=[];x.claude?.available&&x.claude.mcp&&!x.claude.mcp.found&&C.push(await Rs(k)),x.codex?.available&&x.codex.mcp&&!x.codex.mcp.found&&C.push(await As(k)),x.copilot?.available&&x.copilot.mcp&&!x.copilot.mcp.found&&C.push(await Ms(k,x.copilot.path??S));let[A,q,D]=await Promise.all([Er(r),_r(r),Cr(r,x.copilot?.path??S)]);x.claude&&(x.claude.mcp=A),x.codex&&(x.codex.mcp=q),x.copilot&&(x.copilot.mcp=D),N(T,200,{results:C,capabilities:{providers:x}})}async function Ma(l,T){if(!l||l.includes("/")||l.includes("\\")||l.includes("..")){N(T,400,{error:"Invalid filename"});return}try{let O=[it(d,l),it(r,".popmelt","artifacts","thread-media",l),it(r,".popmelt","artifacts","eval-screenshots",l),it(r,".popmelt","evals","screenshots",l),it(r,".popmelt","screenshots",l)],k;for(let q of O)try{k=await $p(q);break}catch{}if(!k)throw new Error("File not found");let C=l.split(".").pop()?.toLowerCase(),A=C==="png"?"image/png":C==="webp"?"image/webp":C==="jpg"||C==="jpeg"?"image/jpeg":C==="svg"?"image/svg+xml":C==="txt"?"text/plain; charset=utf-8":"application/octet-stream";T.writeHead(200,{"Content-Type":A,"Cache-Control":"public, max-age=3600"}),T.end(k)}catch{N(T,404,{error:"File not found"})}}function vn(l){return`/files/${Ho(l)}`}async function ja(l,T){let O=await _.getThread(l);if(!O){N(T,404,{error:"Thread not found"});return}let k=O.messages.filter(U=>U.role==="assistant"&&U.responseText?.includes("Model suggestion ready")),C=await(k.length>0?pe.findModelProposalsByThread(l):Promise.resolve([])),A=await Promise.all(C.map(async(U,G)=>{if(U.authorityStatus==="accepted")return U;let ge=(await Promise.all(U.decisionIds.map(K=>Z.findPendingProposalForLegacyDecision(K)))).find(Boolean);return{...U,authorityStatus:"legacy_untrusted",presentationJobId:U.presentationJobId??k[G]?.jobId??k.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),q=[...A].sort((U,G)=>G.updatedAt-U.updatedAt)[0]??null,D=O.elementIdentifiers.some(U=>U.startsWith("codex-session:"))?await Z.findPendingProposalsForThread(l):[],z=O.messages.map(({screenshotPath:U,screenshotPaths:G,imagePaths:ge,attachmentFiles:K,replyImagePaths:ye,...ue})=>({...ue,...U?{screenshotUrl:vn(U)}:{},...G?{screenshotUrls:Object.fromEntries(Object.entries(G).map(([ce,te])=>[ce,vn(te)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([ce,te])=>[ce,te.map(vn)]))}:{},...K?{attachments:Object.fromEntries(Object.entries(K).map(([ce,te])=>[ce,te.map(({path:ae,...ke})=>({...ke,url:vn(ae)}))]))}:{},...ye?{replyImageUrls:ye.map(vn)}:{}}));N(T,200,{id:O.id,createdAt:O.createdAt,messages:z,modelProposal:q,modelProposals:A,decisionCandidates:D})}async function ti(l,T){let O=decodeURIComponent(l);if(!await _.archiveThread(O)){N(T,404,{archived:!1,error:"Thread not found"});return}N(T,200,{archived:!0})}let ni=9,oi=!1;for(let l=t;l<t+ni;l++)try{await au(tt,l),u=l,oi=!0,console.log(`[\u22B9 is watching :${u}]`);break}catch(T){if(T.code==="EADDRINUSE"){let O=await In(l);if(Wn(O,{projectId:i,version:mt,restartMode:v}))return console.log(`[\u22B9 already watching :${l}]`),{port:l,projectId:i,close:async()=>{}};continue}throw T}if(!oi)throw new Error(`[Bridge] All ports ${t}\u2013${t+ni-1} in use`);for(let[l,T]of Object.entries(x))!T.available||!T.path||f(l,T.path).then(O=>{if(O)console.log(`[Bridge] ${l} warmed up`);else{console.warn(`[Bridge] ${l} warm-up failed \u2014 marking unavailable`),T.available=!1,T.path=null;for(let k of B)Zn(k,{type:"capabilities_changed",data:{}})}});let Ea=setInterval(()=>{va(d).catch(()=>{}),de.sweep().catch(()=>{})},zp),ri=setInterval(()=>{J.expireStale().becameEmpty&&j()},Wp);return ri.unref?.(),{port:u,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(Ea),clearInterval(ri),ie(),J.clear(),await de.cleanupPartials(),await L.destroyAsync(),R.destroy();for(let l of B)try{l.res.end()}catch{}return B.clear(),new Promise(l=>{tt.close(()=>l()),tt.closeAllConnections?.()})}}}async function va(n){try{let e=await Op(n),t=Date.now();for(let o of e){let r=it(n,o);try{let i=await ba(r);t-i.mtimeMs>Gp&&await Np(r)}catch{}}}catch{}}var yu=1111,Ta=3e4,Iu=8e3;async function wu(n){return fu(n).catch(()=>n)}async function ka(n,e){let o=(await mu(e,"utf8").catch(()=>"")).slice(-Iu).trim();return new Error(o?`${n}
208
208
  Bridge log (${e}):
209
- ${o}`:n)}async function dg(n){if(process.env.NODE_ENV==="production"&&!n?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(n?.detached){let t=await wu(n);if(n.manageLease===!1)return t;let o=await ri({port:t.port,projectId:t.projectId});if(!o)return console.warn("[popmelt] detached bridge started without a process lease"),t;let r=ii(o);return{...t,close:async()=>{r(),await o.release()}}}let e=await ba(n);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function wu(n){let e=n.port??gu,t=await Iu(n.projectRoot??process.cwd()),o=zt(t),r=await Fo(t);for(let g=e;g<e+10;g++){let k=await In(g);if(k&&k.projectId===o){if(k.version&&k.version!==mt){if(k.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${g}/shutdown`,{method:"POST"})}catch{}await new Promise(h=>setTimeout(h,500));break}continue}if(!Wn(k,{projectId:o,version:mt,restartMode:"detached"}))continue;let b=n.devOrigin;if(b&&k.devOrigin!==b)try{await fetch(`http://127.0.0.1:${g}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=o,{port:g,projectId:o,storeId:r.storeId,close:async()=>{}}}}let i=Zr(fu(hu(import.meta.url)),"bridge-entry.mjs"),s=Zr(t,".popmelt"),a=Zr(s,"bridge.log");await pu(s,{recursive:!0}),await lu(a,`
209
+ ${o}`:n)}async function cg(n){if(process.env.NODE_ENV==="production"&&!n?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(n?.detached){let t=await vu(n);if(n.manageLease===!1)return t;let o=await ii({port:t.port,projectId:t.projectId});if(!o)return console.warn("[popmelt] detached bridge started without a process lease"),t;let r=si(o);return{...t,close:async()=>{r(),await o.release()}}}let e=await Sa(n);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function vu(n){let e=n.port??yu,t=await wu(n.projectRoot??process.cwd()),o=zt(t),r=await Fo(t);for(let g=e;g<e+10;g++){let S=await In(g);if(S&&S.projectId===o){if(S.version&&S.version!==mt){if(S.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${g}/shutdown`,{method:"POST"})}catch{}await new Promise(h=>setTimeout(h,500));break}continue}if(!Wn(S,{projectId:o,version:mt,restartMode:"detached"}))continue;let b=n.devOrigin;if(b&&S.devOrigin!==b)try{await fetch(`http://127.0.0.1:${g}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:b})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=o,{port:g,projectId:o,storeId:r.storeId,close:async()=>{}}}}let i=ei(hu(gu(import.meta.url)),"bridge-entry.mjs"),s=ei(t,".popmelt"),a=ei(s,"bridge.log");await uu(s,{recursive:!0}),await pu(a,`
210
210
  [${new Date().toISOString()}] Starting detached bridge
211
- `);let d=cu(a,"a"),c;try{c=au(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:n.devOrigin??"",POPMELT_COPILOT_PATH:n.copilotPath??""}})}finally{du(d)}let I=null;c.once("error",g=>{I=`spawn error: ${g.message}`}),c.once("exit",(g,k)=>{I=`child exited before becoming healthy (${k?`signal ${k}`:`code ${g??"unknown"}`})`}),c.unref();let v=Date.now()+xa;for(;Date.now()<v;){if(await new Promise(g=>setTimeout(g,100)),I)throw await Sa(`[Bridge] Detached bridge ${I}`,a);for(let g=e;g<e+10;g++){let k=await In(g);if(Wn(k,{projectId:o,version:mt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=o,{port:g,projectId:o,storeId:r.storeId,close:async()=>{}}}}throw c.kill("SIGTERM"),await Sa(`[Bridge] Detached bridge failed to start within ${xa/1e3}s (port ${e})`,a)}export{kt as ImprintService,Kt as ImprintStore,Qt as formatImprintPrompt,er as imprintExplanationRef,Ht as parseImprintDraft,Na as qualifyImprintRelation,dg as startPopmelt};
211
+ `);let d=lu(a,"a"),c;try{c=du(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:n.devOrigin??"",POPMELT_COPILOT_PATH:n.copilotPath??""}})}finally{cu(d)}let y=null;c.once("error",g=>{y=`spawn error: ${g.message}`}),c.once("exit",(g,S)=>{y=`child exited before becoming healthy (${S?`signal ${S}`:`code ${g??"unknown"}`})`}),c.unref();let w=Date.now()+Ta;for(;Date.now()<w;){if(await new Promise(g=>setTimeout(g,100)),y)throw await ka(`[Bridge] Detached bridge ${y}`,a);for(let g=e;g<e+10;g++){let S=await In(g);if(Wn(S,{projectId:o,version:mt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=o,{port:g,projectId:o,storeId:r.storeId,close:async()=>{}}}}throw c.kill("SIGTERM"),await ka(`[Bridge] Detached bridge failed to start within ${Ta/1e3}s (port ${e})`,a)}export{kt as ImprintService,Kt as ImprintStore,Qt as formatImprintPrompt,er as imprintExplanationRef,Ht as parseImprintDraft,Ja as qualifyImprintRelation,cg as startPopmelt};