@popmelt.com/core 0.12.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,30 +1,30 @@
1
- import{spawn as Tp}from"child_process";import{closeSync as kp,openSync as Rp}from"fs";import{appendFile as Pp,mkdir as Ap,readFile as jp,realpath as Mp}from"fs/promises";import{dirname as Ep,join as Nr}from"path";import{fileURLToPath as _p}from"url";function Nt(o){return da(o).slice(0,12)}var aa=[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 da(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):ca(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let y=7;y>=0;y--)e.push(t/Math.pow(2,y*8)&255);let n=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,d=2600822924,l=528734635,v=1541459225,S=new Array(64);for(let y=0;y<e.length;y+=64){for(let h=0;h<16;h++){let m=y+h*4;S[h]=(e[m]<<24|e[m+1]<<16|e[m+2]<<8|e[m+3])>>>0}for(let h=16;h<64;h++){let m=et(S[h-15],7)^et(S[h-15],18)^S[h-15]>>>3,M=et(S[h-2],17)^et(S[h-2],19)^S[h-2]>>>10;S[h]=S[h-16]+m+S[h-7]+M>>>0}let k=n,T=r,g=i,u=s,I=a,f=d,p=l,j=v;for(let h=0;h<64;h++){let m=et(I,6)^et(I,11)^et(I,25),M=I&f^~I&p,D=j+m+M+aa[h]+S[h]>>>0,P=et(k,2)^et(k,13)^et(k,22),A=k&T^k&g^T&g,Q=P+A>>>0;j=p,p=f,f=I,I=u+D>>>0,u=g,g=T,T=k,k=D+Q>>>0}n=n+k>>>0,r=r+T>>>0,i=i+g>>>0,s=s+u>>>0,a=a+I>>>0,d=d+f>>>0,l=l+p>>>0,v=v+j>>>0}return[n,r,i,s,a,d,l,v].map(y=>y.toString(16).padStart(8,"0")).join("")}function et(o,e){return o>>>e|o<<32-e}function ca(o){let e=[];for(let t=0;t<o.length;t++){let n=o.charCodeAt(t);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}var Lr={name:"@popmelt.com/core",version:"0.12.2",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint . && 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"}},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"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.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",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var st=Lr.version;import{execFileSync as zl,spawn as Bs}from"child_process";import{randomUUID as pt}from"crypto";import{mkdir as Gl,readFile as Wl,readdir as Vl,realpath as Kl,stat as Hl,unlink as Ql,writeFile as Oo}from"fs/promises";import{createServer as Xl}from"http";import{tmpdir as Yl}from"os";import{basename as Do,isAbsolute as Gs,join as Ye,relative as Zl,resolve as ep}from"path";function pa(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function Ur(o){let e=o.annotations.flatMap(r=>{let i=pa(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{spawn as Cp}from"child_process";import{closeSync as $p,openSync as Op}from"fs";import{appendFile as Dp,mkdir as Np,readFile as Bp,realpath as Jp}from"fs/promises";import{dirname as qp,join as Wr}from"path";import{fileURLToPath as Lp}from"url";function Jt(o){return ga(o).slice(0,12)}var ha=[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 ga(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):ya(o),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 n=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,d=2600822924,l=528734635,w=1541459225,b=new Array(64);for(let g=0;g<e.length;g+=64){for(let m=0;m<16;m++){let f=g+m*4;b[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=tt(b[m-15],7)^tt(b[m-15],18)^b[m-15]>>>3,j=tt(b[m-2],17)^tt(b[m-2],19)^b[m-2]>>>10;b[m]=b[m-16]+f+b[m-7]+j>>>0}let k=n,x=r,h=i,u=s,y=a,I=d,p=l,A=w;for(let m=0;m<64;m++){let f=tt(y,6)^tt(y,11)^tt(y,25),j=y&I^~y&p,$=A+f+j+ha[m]+b[m]>>>0,R=tt(k,2)^tt(k,13)^tt(k,22),_=k&x^k&h^x&h,X=R+_>>>0;A=p,p=I,I=y,y=u+$>>>0,u=h,h=x,x=k,k=$+X>>>0}n=n+k>>>0,r=r+x>>>0,i=i+h>>>0,s=s+u>>>0,a=a+y>>>0,d=d+I>>>0,l=l+p>>>0,w=w+A>>>0}return[n,r,i,s,a,d,l,w].map(g=>g.toString(16).padStart(8,"0")).join("")}function tt(o,e){return o>>>e|o<<32-e}function ya(o){let e=[];for(let t=0;t<o.length;t++){let n=o.charCodeAt(t);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}var Xr={name:"@popmelt.com/core",version:"0.14.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"}},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"},peerDependenciesMeta:{next:{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/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",tsup:"^8.5.1",typescript:"^5.8.3",vite:"7.3.6",vitest:"^3.2.4"}};var st=Xr.version;import{execFileSync as Zl,spawn as Ys}from"child_process";import{randomUUID as pt}from"crypto";import{mkdir as ep,readFile as tp,readdir as np,realpath as op,stat as rp,unlink as ip,writeFile as Fo}from"fs/promises";import{createServer as sp}from"http";import{tmpdir as ap}from"os";import{basename as Uo,isAbsolute as ia,join as Ye,relative as dp,resolve as cp}from"path";function Yr(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function Vo(o,e){let t=o?.tagName?.toLowerCase(),n=o?.id?`#${o.id}`:"",r=o?.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"",i=t?`${t}${n}${r}`:e;return o?.reactComponent?`<${o.reactComponent}> ${i}`:i}function wa(o){let e=o.elements?.[0]?.reactComponent||o.elements?.[0]?.tagName||o.linkedSelector,t=o.type&&o.type!=="annotation"?`${o.type} annotation`:"Annotation";return e?`${t} on ${e}`:t}function Zr(o){let e=o.annotations.map(r=>({kind:"annotation",annotationId:r.id,pathname:r.pathname,text:Yr(r)??wa(r)})),t=new Map,n=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:Vo(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 o.styleModifications??[])for(let i of r.changes)n({...r,text:`${i.property}: ${i.original||"unset"} \u2192 ${i.modified||"unset"}${i.token?` (${i.token})`:""}`});for(let r of o.textModifications??[])n({...r,text:`Text: ${r.original||"empty"} \u2192 ${r.modified||"empty"}`});for(let r of o.domModifications??[])n({...r,text:r.operation==="copy"?"Copied element":"Moved element"});return o.spacingTokenChanges?.length&&e.push({kind:"changes",elementKey:"spacing-tokens",elementLabel:"Spacing tokens",changes:o.spacingTokenChanges.map(r=>`${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`)}),e}function ei(o){let e=o.annotations.flatMap(r=>{let i=Yr(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 n=new Map;for(let r of e){let i=r.pathname||"(unknown)",s=n.get(i)??[];s.push(r.instruction),n.set(i,s)}return[...n.entries()].map(([r,i])=>`\`${r}\`
4
4
  ${i.map(s=>`- ${s}`).join(`
5
5
  `)}`).join(`
6
- `)}var ua=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),ma=new Set(["default","flex","fast","priority"]);function Bt(o){let e=typeof o.reasoningEffort=="string"&&ua.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&ma.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Un(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{createHash as Ed,randomUUID as _d}from"crypto";import{isAbsolute as Cd,relative as $d}from"path";import{randomUUID as dt}from"crypto";function Go(o,e){return{storeId:o,explanationId:e}}function fa(o,e){let{fromId:t,toId:n,toStoreId:r,...i}=e;return{...i,from:Go(o,t),to:Go(r??o,n)}}var Fr={project:0,route:1,component:2,selector:2,file:3},zr={intention:0,principle:1,pattern:2};function Jt(o,e){let t=Fr[o.scope.kind]-Fr[e.scope.kind];return t!==0?t:zr[o.kind]-zr[e.kind]}function Gr(o){return o==="expresses"||o==="excepts"}function ha(o,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=o.explanations.find(i=>i.id===e.fromId),n=o.explanations.find(i=>i.id===e.toId);if(!t||!n)return;let r=Jt(t,n);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function kt(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let r=ha(o,n);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 ga}from"crypto";import{mkdir as ya,open as Ia,readFile as Wr,readdir as wa,rename as va,unlink as ba}from"fs/promises";import{dirname as xa,join as qt}from"path";function Le(o){return structuredClone(o)}function Vr(o){return ga("sha256").update(JSON.stringify(o)).digest("hex")}async function Rt(o,e){await ya(xa(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Ia(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
7
- `,"utf8"),await n.sync()}finally{await n.close()}try{await va(t,o)}catch(r){throw await ba(t).catch(()=>{}),r}}function Sa(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Ta(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=Le(e):o.explanations.push(Le(e))}function Fn(o,e){let t=Le(o);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(r=>r.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(Le(n.explanation))}else if(n.op==="replace_explanation")Ta(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(r=>r.id!==n.explanationId),t.relations=t.relations.filter(r=>r.fromId!==n.explanationId&&(r.toStoreId!==void 0||r.toId!==n.explanationId));else if(n.op==="add_concrete")t.concrete.some(r=>r.id===n.concrete.id)||t.concrete.push(Le(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(r=>r.id!==n.concreteId),t.relations=t.relations.filter(r=>r.fromId!==n.concreteId&&(r.toStoreId!==void 0||r.toId!==n.concreteId));else if(n.op==="add_evidence"){let r=t.explanations.find(i=>i.id===n.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);r.evidence.some(i=>i.id===n.evidence.id)||(r.evidence.push(Le(n.evidence)),r.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let r=t.explanations.find(i=>i.id===n.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(r,Le(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let r=n.relation,i=t.explanations.find(v=>v.id===r.fromId),s=!!r.toStoreId,a=s?void 0:t.explanations.find(v=>v.id===r.toId),d=t.concrete.some(v=>v.id===r.fromId),l=!s&&t.concrete.some(v=>v.id===r.toId);if(Gr(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(S=>S.type===r.type&&S.fromId===r.fromId&&S.toStoreId===r.toStoreId&&S.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`);if(r.type==="expresses"&&i&&a){if(Jt(i,a)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let S=new Map;for(let T of t.relations)T.type!=="expresses"||T.toStoreId||S.set(T.fromId,[...S.get(T.fromId)??[],T.toId]);let y=[r.toId],k=new Set;for(;y.length;){let T=y.pop();if(T===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);k.has(T)||(k.add(T),y.push(...S.get(T)??[]))}}}else if(!i||!a&&!l)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);t.relations.some(v=>v.id===r.id)||t.relations.push(Le(r))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==n.relationId));return t}function ka(o,e){let t=[],n=Le(o);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=n.explanations.find(s=>s.id===r.explanationId);i&&t.unshift({op:"add_explanation",explanation:Le(i)})}else if(r.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=n.concrete.find(s=>s.id===r.concreteId);i&&t.unshift({op:"add_concrete",concrete:Le(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=n.explanations.find(a=>a.id===i);s&&t.unshift({op:"replace_explanation",explanation:Le(s)})}else if(r.op==="add_relation")t.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=n.relations.find(s=>s.id===r.relationId);i&&t.unshift({op:"add_relation",relation:Le(i)})}n=Fn(n,[r])}return t}function Kr(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,...o.relation.toStoreId?[]:[o.relation.toId]]:[]}var Lt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=qt(e,".popmelt","imprint"),this.manifestPath=qt(this.imprintDir,"manifest.json"),this.graphPath=qt(this.imprintDir,"graph.json"),this.journalDir=qt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await Wr(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(),n=(await wa(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=Sa(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<n.length;a++){let d=JSON.parse(await Wr(qt(this.journalDir,n[a]),"utf8")),{hash:l,...v}=d;if(d.sequence!==a+1||d.previousHash!==s||l!==Vr(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Fn(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:kt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=kt(t.graph),r=new Map(n.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 Rt(this.graphPath,n),await Rt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(S=>S.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=n.graph.head.sequence+1,i=ka(n.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:Le(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:Vr(s)},d=Fn(n.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Rt(qt(this.journalDir,l),a);let v={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Rt(this.graphPath,d),await Rt(this.manifestPath,v),t={graph:d,transaction:a}}),await this.writeChain,t}async undo(e,t,n,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(Kr));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(v=>Kr(v).some(S=>a.has(S)))))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:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Rt(this.graphPath,e.graph),await Rt(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 Ra=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Pa=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"]),Aa=[/\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],ja=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Vo(o){return!!(o&&ja.test(o))}function Ma(o){return o.scope.kind==="project"||Vo(`${o.statement} ${o.rationale}`)}function Ea(o){let e=o?.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 _a(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ca(o){return o.length>4&&o.endsWith("ies")?[o,`${o.slice(0,-3)}y`]:o.length>3&&o.endsWith("s")&&!o.endsWith("ss")?[o,o.slice(0,-1)]:[o]}function at(o){return new Set(_a(o).split(" ").filter(e=>e.length>2&&!Pa.has(e)).flatMap(Ca))}function Hr(o){return o.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function $a(o){if(o)for(let e of Aa){let t=e.exec(o);if(!t||t.index<=0)continue;let n=Hr(o.slice(0,t.index)),r=Hr(o.slice(t.index+t[0].length));if(n&&r)return{target:n,reference:r}}}function gt(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Wo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function yt(o,e,t){return{id:dt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ve(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Qr(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Xr(o,e,t){if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o,s=ve(i.explanationId,100),a=ve(i.clientId,100),d=ve(i.storeId,100);if(s&&a)throw new Error("relation endpoint must use either explanationId or clientId, not both");let l=s||a;return l?{explanationId:l,...d?{storeId:d}:{}}:void 0}let n=ve(e,100),r=ve(t,100);return n?{explanationId:n,...r?{storeId:r}:{}}:void 0}function Yr(o,e){if(!o||!e.trim())return{found:!1};let t=o;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let r=Number(n);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,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Ut(o,e={}){let t=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.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=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(d);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let v=l;i=v.imprint,s=Array.isArray(v.annotations)?v.annotations:[]}catch{return{visibleText:n,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 g=String(a.reason);if(!Ra.has(g))throw new Error("imprint no-op reason is invalid");if(g==="task_specific_detail"&&s.some(M=>{if(!M||typeof M!="object"||Array.isArray(M))return!1;let D=M;return(D.finalScope??D.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let u=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()):[],f=new Set(e.context?.explanations.map(M=>M.id)??[]);if([...new Set([...u,...I])].some(M=>!f.has(M)))throw new Error("imprint use must cite only surfaced explanations");let j=[...new Set([...u,...e.applicationOccurred?[]:I])],h=e.applicationOccurred?I:[],m;if(h.length){m=h;let M=new Set(e.context?.pendingGroundingExplanationIds??[]),D=h.filter(P=>{let A=e.context?.explanations.find(Q=>Q.id===P);return f.has(P)&&A&&(A.state==="emerging"||A.state==="testing")&&!M.has(P)});if(D.length){let P=a.grounding,A=typeof P?.explanationId=="string"&&D.includes(P.explanationId)?P.explanationId:D[0],Q=ve(P?.question,300);return{draft:{decision:"apply",summary:{title:ve(a.summary?.title,120)||"Applied shared understanding",detail:ve(a.summary?.detail,500)||ve(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:h,grounding:{explanationId:A,question:Q||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(g==="duplicate"){let M=ve(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!M)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let P=e.context?.explanations.find(A=>A.id===M);if(!P)throw new Error("duplicate assessment must cite a surfaced explanation");if(Vo(e.requestText)&&!Ma(P))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:g,duplicateOfExplanationId:M,scopeComparison:D,...j.length?{usedExplanationIds:j}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:g,...j.length?{usedExplanationIds:j}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}if(a.decision==="recognize"){let g=ve(a.explanationId,100);if(!g)throw new Error("recognition requires explanationId");let u=e.context?.explanations.find(p=>p.id===g);if(!u)throw new Error("recognition must cite a surfaced explanation");if(u.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let I=a.summary,f={title:ve(I?.title,120),detail:ve(I?.detail,500)};if(!f.title||!f.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:g,summary:f},visibleText:n}}if(a.decision==="apply"){let g=a.summary,u={title:ve(g?.title,120),detail:ve(g?.detail,500)};if(!u.title||!u.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 f=new Map(e.context?.explanations.map(M=>[M.id,M])??[]);if(I.some(M=>!f.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:n};let p=new Set(e.context?.pendingGroundingExplanationIds??[]),j=I.filter(M=>{let D=f.get(M);return D&&(D.state==="emerging"||D.state==="testing")&&!p.has(M)});if(!j.length){if(I.every(D=>f.get(D)?.state==="grounded"||p.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:I},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let h=a.grounding,m=typeof h?.explanationId=="string"&&j.includes(h.explanationId)?h.explanationId:j[0];return{draft:{decision:"apply",summary:u,appliedExplanationIds:I,grounding:{explanationId:m,question:ve(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,l=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let v={kind:l,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!v.title||!v.detail)throw new Error("summary title and detail are required");let S=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(g=>typeof g=="string"&&!!g.trim()):[],y=[];for(let g of Array.isArray(a.mutations)?a.mutations:[]){if(!g||typeof g!="object")continue;let u=g;if(u.op==="add"&&["intention","principle","pattern"].includes(String(u.kind))){let I=ve(u.statement),f=ve(u.rationale);if(!I||!f)continue;y.push({op:"add",clientId:ve(u.clientId,100)||void 0,kind:u.kind,statement:I,rationale:f,scope:Qr(u.scope),rootReason:ve(u.rootReason,300)||void 0})}else if(u.op==="revise"&&typeof u.explanationId=="string"){let I={op:"revise",explanationId:u.explanationId,statement:ve(u.statement)||void 0,rationale:ve(u.rationale)||void 0,scope:Qr(u.scope),reopenGrounding:u.reopenGrounding===!0};(I.statement||I.rationale||I.scope||I.reopenGrounding)&&y.push(I)}else if(u.op==="evidence"&&typeof u.explanationId=="string"&&["supports","challenges","excepts"].includes(String(u.stance))){let I=ve(u.summary);I&&y.push({op:"evidence",explanationId:u.explanationId,stance:u.stance,summary:I})}else if(u.op==="relation"){if(!["expresses","excepts"].includes(String(u.type)))throw new Error("relation type is invalid");let I=ve(u.rationale),f=Xr(u.from,u.fromId,u.fromStoreId),p=Xr(u.to,u.toId,u.toStoreId);if(!I)throw new Error("relation rationale is required");if(!f||!p)throw new Error("relation endpoints require an explanationId or clientId");y.push({op:"relation",type:u.type,from:f,to:p,rationale:I})}else if(u.op==="supersede"&&typeof u.explanationId=="string"&&typeof u.replacementId=="string"){let I=ve(u.reason);I&&y.push({op:"supersede",explanationId:u.explanationId,replacementId:u.replacementId,reason:I})}else if(u.op==="bind_concrete"&&typeof u.explanationId=="string"){let I=ve(u.modelPath,300);I&&y.push({op:"bind_concrete",explanationId:u.explanationId,modelPath:I,rationale:ve(u.rationale)})}else u.op==="retire"&&typeof u.explanationId=="string"&&y.push({op:"retire",explanationId:u.explanationId,reason:ve(u.reason)})}let k=a.grounding,T=k&&typeof k.explanationId=="string"&&ve(k.question)?{explanationId:k.explanationId,question:ve(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:v,appliedExplanationIds:S,mutations:y,grounding:T},visibleText:n}}catch(a){return{visibleText:n,error:a instanceof Error?a.message:String(a)}}}function Ft(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),r=new Set(o?.correctionExplanationIds??[]),i=Vo(e.requestText),s=o?.retrievalIntent,a=o?.historicalCaveats??[],d=t.find(y=>y.storeId&&!y.readOnly)?.storeId,l=(y,k)=>{let T=y[k];return T?`[${T.storeId}] ${T.explanationId}`:k==="from"?y.fromId:y.toId},v=!!o?.relations?.some(y=>y.from&&y.to&&y.from.storeId!==y.to.storeId),S=t.some(y=>y.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((y,k)=>[`${k+1}. [${y.state}; ${y.kind}] ${y.statement}`,` - Why: ${y.rationale}`,` - Scope: ${y.scope.kind} ${y.scope.values.join(", ")}`,` - Explanation: ${y.id}`,...y.storeId?[` - Store: ${y.storeId}${y.readOnly?" (read-only)":" (writable primary)"}`]:[],...n.has(y.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(y.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...y.concrete.map(T=>` - Concrete terminal: ${T.modelPath} = ${JSON.stringify(T.value)}`)].join(`
8
- `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(y=>`- ${y.storeId?`[owned by ${y.storeId}${y.readOnly?"; read-only":""}] `:""}${l(y,"from")} --${y.type}--> ${l(y,"to")}: ${y.rationale}`)]:[],...S||v?["","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((y,k)=>[`${k+1}. [challenged; ${y.kind}] ${y.statement}`,` - Why it was previously proposed: ${y.rationale}`,` - Scope: ${y.scope.kind} ${y.scope.values.join(", ")}`,` - Historical explanation: ${y.id}`,...y.storeId?[` - Store: ${y.storeId}${y.readOnly?" (read-only)":" (writable primary)"}`]:[]].join(`
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(y=>y.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."]:[],...o?.unavailableStoreIds?.length?["",`Some mounted Imprint knowledge was unavailable during this bounded read: ${o.unavailableStoreIds.join(", ")}. Do not infer its contents.`]:[],...o?.unavailableTopologyStoreIds?.length?["",`Some mounted Imprint topology was unavailable during this bounded read: ${o.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 It=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Lt(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??""}`,n=this.contextualGraphCache?.headKey===t?this.contextualGraphCache.graph:void 0;return n||(n=(await this.store.load()).graph,this.contextualGraphCache={headKey:t,graph:n}),n}async explanationsByIds(e){if(!e.length)return[];let t=await this.contextualGraph(),n=new Map(t.explanations.map(r=>[r.id,r]));return[...new Set(e)].flatMap(r=>{let i=n.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=at(e.text??""),n=at((e.subjectHints??[]).join(" ")),r=$a(e.text),i=at(r?.target??""),s=at(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!a.size&&!d.size)return;let l=await this.contextualGraph(),v=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||d.has(h.id))).map(h=>{let m=at([h.statement,h.rationale].join(" ")),M=at(h.scope.values.join(" ")),D=gt(m,t),P=gt(M,t),A=gt(M,n),Q=gt(m,n),z=D+P*.2+A*.25+Q*.75+(h.state==="grounded"?.08:0)+(a.has(h.id)?1:0)+(d.has(h.id)?1:0),E=a.has(h.id)||d.has(h.id)||D>=.12||P>=.5||A>=.2||Q>=.2;return{item:h,score:z,relevant:E}}).filter(h=>h.relevant&&h.score>=.18).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)),S=Math.max(1,e.maxExplanations??6),y=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let M=gt(at(`${m.statement} ${m.rationale}`),h),D=gt(at(m.scope.values.join(" ")),h);return{item:m,score:M+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,M)=>M.score-m.score||M.item.updatedAt.localeCompare(m.item.updatedAt)),k=[],T=h=>{k.length<S&&!k.some(m=>m.id===h.id)&&k.push(h)};if(r&&(y(i).slice(0,2).forEach(({item:h})=>T(h)),y(s).slice(0,2).forEach(({item:h})=>T(h))),v.forEach(({item:h})=>T(h)),!k.length)return;let g=new Set(k.map(h=>h.id)),u=new Set(l.relations.flatMap(h=>h.toStoreId?[]:g.has(h.fromId)?[h.toId]:g.has(h.toId)?[h.fromId]:[])),I=new Set(l.explanations.flatMap(h=>u.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),f=l.explanations.filter(h=>I.has(h.id)&&!g.has(h.id)).sort((h,m)=>m.updatedAt.localeCompare(h.updatedAt)).slice(0,4),p=[...k,...f];for(let h of f)g.add(h.id);let j=r?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=at(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),M=gt(m,i),D=gt(m,s);return{item:h,score:M+D,targetScore:M,referenceScore:D}}).filter(h=>h.targetScore>=.12&&h.referenceScore>=.12).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)).slice(0,3).map(({item:h})=>({id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state})):[];return{explanations:p.map(h=>{let m=new Set(l.relations.filter(M=>!M.toStoreId&&M.toId===h.id&&M.type==="expresses").map(M=>M.fromId));return{id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state,concrete:l.concrete.filter(M=>m.has(M.id)).map(M=>({id:M.id,modelPath:M.modelPath,value:M.value}))}}),truncated:v.length>k.length||f.length<I.size,...r?{retrievalIntent:r}:{},...j.length?{historicalCaveats:j}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},relations:l.relations.filter(h=>!h.toStoreId&&g.has(h.fromId)&&g.has(h.toId)).map(h=>({id:h.id,type:h.type,fromId:h.fromId,toId:h.toId,rationale:h.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],r=t.applicationOccurred?n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(n.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(x=>[x.id,x])),l=new Map,v=new Map,S=[],y=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),T=new Set(n.flatMap(x=>x.op==="revise"&&n.some(O=>O.op==="evidence"&&O.stance==="challenges"&&O.explanationId===x.explanationId)?[x.explanationId]:[])),g=new Set(n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),u=t.storeId?.trim(),I=x=>d.has(x)||g.has(x),f=new Map((t.context?.explanations??[]).flatMap(x=>x.storeId?[[`${x.storeId}:${x.id}`,x]]:[])),p=x=>x.storeId??u,j=x=>{let O=p(x.from),q=p(x.to);return u&&O!==u||!u&&(x.from.storeId||x.to.storeId)||!I(x.from.explanationId)?!1:!q||q===u?I(x.to.explanationId):!!f.get(`${q}:${x.to.explanationId}`)?.memoryId},h=new Set;for(let x of n)x.op==="relation"&&(p(x.from)!==p(x.to)||x.from.explanationId!==x.to.explanationId)&&j(x)?(h.add(x.from.explanationId),p(x.to)===u&&h.add(x.to.explanationId)):x.op==="supersede"&&x.explanationId!==x.replacementId&&I(x.explanationId)&&I(x.replacementId)?(h.add(x.explanationId),h.add(x.replacementId)):x.op==="bind_concrete"&&I(x.explanationId)&&Yr(t.concreteModel,x.modelPath).found&&h.add(x.explanationId);let m=a.graph.explanations.length===0;for(let x of n){if(x.op!=="add")continue;let O=!!(x.clientId&&h.has(x.clientId)),q=!!x.rootReason?.trim()||m;if(!O&&!q)continue;m&&(m=!1);let J=dt();x.clientId&&l.set(x.clientId,J);let H=x.clientId?i.includes(x.clientId):!1,he={id:J,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:Wo(x.scope),state:H?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[yt(t,"supports",e.summary.detail)]};d.set(J,he),y.add(J),S.push({op:"add_explanation",explanation:he})}let M=x=>l.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let O=M(x.explanationId),q=d.get(O);if(q?.state!=="grounded")continue;let J=dt(),H={id:J,kind:q.kind,statement:x.statement??q.statement,rationale:x.rationale??q.rationale,scope:x.scope?Wo(x.scope):q.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[yt(t,"supports",e.summary.detail)]};d.set(J,H),v.set(O,J),y.add(J),S.push({op:"add_explanation",explanation:H});let he=Jt(q,H);he!==0&&S.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:he>0?O:J,toId:he>0?J:O,rationale:x.rationale??e.summary.detail,createdAt:s}})}let D=x=>{let O=M(x);return v.get(O)??O};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let q=D(x.explanationId);if(!d.has(q))continue;let J=Yr(t.concreteModel,x.modelPath);if(!J.found)continue;let H=a.graph.concrete.find(he=>he.modelPath===x.modelPath&&JSON.stringify(he.value)===JSON.stringify(J.value));H||(H={id:dt(),modelPath:x.modelPath,value:structuredClone(J.value),createdAt:s,updatedAt:s},S.push({op:"add_concrete",concrete:H})),S.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:H.id,toId:q,rationale:x.rationale,createdAt:s}}),y.add(q);continue}if(x.op==="relation"){if(!j(x))continue;let q=p(x.from),J=p(x.to);if(u&&q!==u)continue;let H=D(x.from.explanationId),he=J===u?D(x.to.explanationId):x.to.explanationId,$e=d.get(H),se=J===u?d.get(he):f.get(`${J}:${he}`);if(!$e||!se||J===u&&H===he)continue;if(x.type==="expresses"&&Jt($e,se)<0){if(J!==u)continue;[H,he]=[he,H]}S.push({op:"add_relation",relation:{id:dt(),type:x.type,fromId:H,...J&&J!==u?{toStoreId:J}:{},toId:he,rationale:x.rationale,createdAt:s}}),y.add(H),J===u&&y.add(he);continue}if(x.op==="supersede"){let q=D(x.explanationId),J=D(x.replacementId);if(!d.has(q)||!d.has(J)||q===J)continue;S.push({op:"add_evidence",explanationId:q,evidence:yt(t,"challenges",x.reason)}),S.push({op:"revise_explanation",explanationId:q,patch:{state:"challenged",supersededBy:J},updatedAt:s}),y.add(q),y.add(J);continue}let O=D(x.explanationId);if(d.has(O))if(y.add(O),x.op==="revise"){if(v.has(M(x.explanationId)))continue;let q=d.get(O);if(!q||q.state!=="emerging"&&q.state!=="testing")continue;let J={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Wo(x.scope)}:{},...x.reopenGrounding||T.has(x.explanationId)?{state:"testing"}:{}};S.push({op:"revise_explanation",explanationId:O,patch:J,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&T.has(x.explanationId))continue;S.push({op:"add_evidence",explanationId:O,evidence:yt(t,x.stance,x.summary)}),x.stance==="challenges"&&S.push({op:"revise_explanation",explanationId:O,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(S.push({op:"add_evidence",explanationId:O,evidence:yt(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),S.push({op:"revise_explanation",explanationId:O,patch:{state:"retired"},updatedAt:s}))}for(let x of i){let O=D(x),q=d.get(O);!q||q.state==="grounded"||q.state==="retired"||k.has(O)&&!y.has(O)||(y.has(O)||(y.add(O),S.push({op:"add_evidence",explanationId:O,evidence:{...yt(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),q.state==="emerging"&&S.push({op:"revise_explanation",explanationId:O,patch:{state:"testing"},updatedAt:s}))}let P=new Set(a.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toStoreId??""}:${x.toId}`)),A=S.filter(x=>{if(x.op!=="add_relation")return!0;let O=`${x.relation.type}:${x.relation.fromId}:${x.relation.toStoreId??""}:${x.relation.toId}`;return P.has(O)?!1:(P.add(O),!0)});if(!A.length)return;let Q=dt(),z=await this.store.commit({transactionId:Q,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:A}),E=new Map(z.graph.explanations.map(x=>[x.id,x])),G=[...y].flatMap(x=>{let O=E.get(x);if(!O)return[];let q=!a.graph.explanations.some(H=>H.id===x),J=O.state==="challenged"||O.state==="retired";return[{explanationId:x,action:q?"added":J?"challenged":"revised",statement:O.statement,state:O.state}]}),W=i.map(D).find(x=>E.get(x)?.state==="testing"&&!k.has(x)),ue=e.grounding?D(e.grounding.explanationId):W,X=ue?E.get(ue):void 0,re=X?.state==="testing"&&!k.has(X.id)?{explanationId:X.id,question:e.grounding?.question||Ea(X),state:"testing"}:void 0;return{transactionId:Q,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:G,...re?{grounding:re}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===n);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:n,evidence:{...yt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:n,evidence:{...yt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:n,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:dt(),committedAt:t,source:s,summary:d,mutations:a}),"applied"}};function zt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
11
- `)}async function zn(o,e,t,n){let r=zt(e);if(!(!r&&t.length===0))try{let i=await o.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(l=>l.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){n?.(i);return}}function fn(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((n,r)=>["",`${r+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,...n.storeId?[` - Store: ${n.storeId}${n.readOnly?" (read-only)":" (writable primary)"}`]:[],` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((n,r)=>["",`${r+1}. ${n.claim}`,...n.storeId?[` - Store: ${n.storeId}${n.readOnly?" (read-only)":" (writable primary)"}`]:[]," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.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.",...o.packets.some(n=>n.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."]:[],"",o.packets.some(n=>n.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."]:[],...o.unavailableStoreIds?.length?["",`Some mounted knowledge was unavailable during this bounded read: ${o.unavailableStoreIds.join(", ")}. Continue with the available context and expand intentionally if the missing store is material.`]:[]].join(`
12
- `)}import{mkdir as ui,readFile as wn,writeFile as mi}from"fs/promises";import{join as Kt}from"path";var Oa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ko(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Gn(o){return new Set(Ko(o).split(" ").filter(e=>e.length>2&&!Oa.has(e)))}function Zr(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Da(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Ko).filter(Boolean),r=Gn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){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(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=Ko(l.value);for(let k of n){let T=v===k?95:v.includes(k)||k.includes(v)?75:0;T>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=90?"exact":"strong",matchedBy:l.by,score:T})}let y=["/","#","[","]","="].some(k=>l.value.includes(k))?0:Math.round(Zr(Gn(v),r)*55);y>=30&&y>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:y>=45?"strong":"weak",matchedBy:"semantic",score:y})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function Na(o){return Math.ceil(JSON.stringify(o).length/4)}function Gt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ba(o,e){let t=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!t.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let n=t.filter(i=>i.state==="completed"),r=n.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":n.length?"partial":"unknown",attemptIds:t.map(i=>i.id)}}function Ja(o,e,t){let n=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=t.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===o),i=n[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:n.map(a=>a.id)}}function ei(o,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),r=o.records.filter(m=>m.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"),a=i?s.filter(m=>i.has(m.id)):s,d=o.records.filter(m=>m.recordType==="implementation_attempt"),l=o.records.filter(m=>m.recordType==="verification_attempt"),v=o.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),S=o.records.filter(m=>m.recordType==="evidence"),y=o.records.filter(m=>m.recordType==="model_entry"),k=Da(r,e),T=new Map(k.map(m=>[m.subjectId,m.score])),g=Gn([e.action,e.text].filter(Boolean).join(" ")),u=a.flatMap(m=>{let M=Math.max(0,...m.subjects.map(A=>T.get(A.subjectId)??0)),D=Math.round(Zr(Gn(m.claim),g)*35),P=M+D;return P>=50?[{decision:m,score:P}]:[]}).sort((m,M)=>M.score-m.score||m.decision.id.localeCompare(M.decision.id)),I=new Map;for(let m of u.slice(0,n))I.set(m.decision.id,m.decision);for(let m of o.relationships){if(!Gt(m,"excepts")&&!Gt(m,"contradicts"))continue;let M=s.find(P=>P.id===m.from.entityId),D=s.find(P=>P.id===m.to.entityId);!M||!D||!I.has(M.id)&&!I.has(D.id)||(I.size<n&&I.set(M.id,M),I.size<n&&I.set(D.id,D))}let f=[...I.values()],p=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&I.has(m.from.entityId)&&I.has(m.to.entityId),j=(m,M=!1)=>{let D=new Set(m.map(O=>O.id)),P=v.filter(O=>O.target.entityType==="decision"&&D.has(O.target.entityId)),A=new Set(o.relationships.filter(O=>Gt(O,"excepts")&&D.has(O.from.entityId)&&D.has(O.to.entityId)).flatMap(O=>[O.from.entityId,O.to.entityId])),z=o.relationships.filter(O=>Gt(O,"contradicts")&&D.has(O.from.entityId)&&D.has(O.to.entityId)).map(O=>({id:O.id,decisionIds:[O.from.entityId,O.to.entityId],unresolvedQuestion:O.reason,expansionRefs:[{kind:"record",id:O.id}]})),E=new Set(z.flatMap(O=>O.decisionIds)),G=S.filter(O=>O.sourceRefs.some(q=>q.kind==="record"&&D.has(q.id))||o.relationships.some(q=>q.relationshipType==="supports"&&q.from.entityType==="evidence"&&q.from.entityId===O.id&&q.to.entityType==="decision"&&D.has(q.to.entityId))),W=Math.max(0,u.length-m.length),ue=o.relationships.some(O=>Gt(O,"contradicts")&&p(O)&&(!D.has(O.from.entityId)||!D.has(O.to.entityId))),X=M||W>0||ue,re=[];k.length===0&&(e.subjectHints?.length??0)>0?re.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):m.length===0&&re.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),z.length&&re.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:z.flatMap(O=>O.expansionRefs)}),G.some(O=>O.availability!=="available")&&re.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:G.map(O=>({kind:"record",id:O.id}))}),X&&re.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let x={contractVersion:1,projectId:o.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:O,...q})=>q),modelEntries:y.filter(O=>O.decisionIds.some(q=>D.has(q))).map(O=>({id:O.id,key:O.key,value:O.value,decisionIds:O.decisionIds})),decisions:m.map(O=>({id:O.id,kind:O.kind,claim:O.claim,subjectIds:O.subjects.map(q=>q.subjectId),authority:O.authority,effectiveState:E.has(O.id)?"conflicted":A.has(O.id)?"excepted":"active",freshness:P.filter(q=>q.target.entityId===O.id).map(q=>q.signalType),expansionRef:{kind:"record",id:O.id}})),conflicts:z,uncertainties:re,implementation:m.map(O=>Ba(O.id,d)),verification:m.map(O=>Ja(O.id,l,P)),evidence:G.map(O=>({evidenceId:O.id,summary:O.summary,availability:O.availability,sourceRefs:O.sourceRefs})),completeness:{status:X?"truncated":"complete",omittedDecisionCount:W,omittedEvidenceCount:0,conflictsComplete:!ue}};return x.budget.estimatedTokens=Na(x),x},h=j(f);for(;h.budget.estimatedTokens>t&&f.length>0;){let m=f.pop(),M=o.relationships.filter(D=>Gt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);f=f.filter(D=>!M.includes(D.id)),h=j(f,!0)}return h}var qa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ho(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Wn(o){return new Set(Ho(o).split(" ").filter(e=>e.length>2&&!qa.has(e)))}function ti(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function La(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function Ua(o,e){let t=new Map,n=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Ho).filter(Boolean),i=Wn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(n.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 La(s)){let l=Ho(d.value);for(let y of r){let k=l===y?95:l.includes(y)||y.includes(l)?75:0;k>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:d.by,score:k})}let S=["/","#","[","]","="].some(y=>d.value.includes(y))?0:Math.round(ti(Wn(l),i)*55);S>=30&&S>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:S>=45?"strong":"weak",matchedBy:"query_text",score:S})}a&&t.set(s.id,a)}return t}function Fa(o,e){let t=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(o.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"&&n.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 za(o){return Math.ceil(JSON.stringify(o).length/4)}function Qo(o,e){let t=o.records.filter(u=>u.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(u=>{if(u.recordType!=="proposal"||r&&!r.has(u.id))return!1;if(u.state==="pending")return!0;if(u.state!=="deferred")return!1;let I=[...o.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===u.id&&f.toState==="deferred"&&f.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(n)>=Date.parse(I.revisitAfter)):!1}),s=o.records.filter(u=>u.recordType==="implementation_attempt"),a=Ua(t,e),d=[...a.values()].sort((u,I)=>I.score-u.score),l=Wn([e.action,e.text].filter(Boolean).join(" ")),v=i.flatMap(u=>{let I=u.subjects.map(h=>a.get(h.subjectId)).filter(h=>!!h),f=Math.max(0,...I.map(h=>h.score)),p=Math.round(ti(Wn(u.claim),l)*35),j=f+p;return j>=50?[{proposal:u,proposalMatches:I,score:j}]:[]}).sort((u,I)=>I.score-u.score||u.proposal.id.localeCompare(I.proposal.id)),S=Math.max(1,e.maxPackets??3),y=Math.max(200,e.maxEstimatedTokens??1200),k=[],T=0;for(let u of v){if(k.length>=S)break;let I=u.proposal.sourceRefs.slice(0,4),f={contractVersion:1,packetId:`review:${u.proposal.id}`,projectId:o.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:u.proposalMatches.length?`Historical proposal intersects ${u.proposalMatches.map(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:u.proposalMatches.map(({score:j,...h})=>h)},proposal:{id:u.proposal.id,claim:u.proposal.claim,state:u.proposal.state,proposedKind:u.proposal.proposedKind,subjectIds:u.proposal.subjects.map(j=>j.subjectId),origin:u.proposal.origin.mode},authority:"unaccepted",presentation:u.score>=100&&["constraint","rule"].includes(u.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Fa(u.proposal,s),evidence:{sourceCount:u.proposal.sourceRefs.length,sourceRefs:I},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:u.proposal.id},...I]},p={...f,estimatedTokens:za(f)};if(T+p.estimatedTokens>y)break;k.push(p),T+=p.estimatedTokens}let g=Math.max(0,v.length-k.length);return{packets:k,subjectMatches:d.map(({score:u,...I})=>I),completeness:{status:g>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:g,maxEstimatedTokens:y,estimatedTokens:T},uncertainty:a.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var Ga=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Wt(o){return Ga.test(o)}function Wa(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function oe(o,e,t,n){o.push({path:e,code:t,message:n,severity:"error"})}function Xo(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Ce(o,e,t){Wt(t)||oe(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function He(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&oe(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Pt(o,e,t,n=!1){n&&t.level==="contributor"&&oe(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&oe(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Va={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),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"])},Ka=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ha(o,e,t){Ce(o,`${t}.id`,e.id),Ce(o,`${t}.projectId`,e.projectId),Ce(o,`${t}.participantId`,e.participantId),Ce(o,`${t}.entity.entityId`,e.entity.entityId),He(o,`${t}.createdAt`,e.createdAt),Pt(o,`${t}.authority`,e.authority);let n=Va[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(r)&&oe(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Ka.has(i)&&(Pt(o,`${t}.authority`,e.authority,!0),e.reason?.trim()||oe(o,`${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)&&oe(o,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&oe(o,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&He(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Qa(o,e,t,n){Ce(o,`${t}.id`,e.id),Ce(o,`${t}.projectId`,e.projectId),Ce(o,`${t}.participantId`,e.participantId),He(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&oe(o,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&oe(o,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&oe(o,`${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)&&oe(o,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Pt(o,`${t}.authority`,e.authority,!0),e.claim.trim()||oe(o,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Xo(o,`${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())&&oe(o,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),He(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&oe(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&oe(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&oe(o,`${t}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),He(o,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),He(o,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&oe(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(He(o,`${t}.appliedAt`,e.appliedAt),Pt(o,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&oe(o,`${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())&&oe(o,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&oe(o,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Xo(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Xo(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Xa(o,e,t){if(Ce(o,`${t}.id`,e.id),Ce(o,`${t}.projectId`,e.projectId),Ce(o,`${t}.participantId`,e.participantId),Ce(o,`${t}.from.entityId`,e.from.entityId),Ce(o,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&oe(o,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&oe(o,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),He(o,`${t}.createdAt`,e.createdAt),e.reason.trim()||oe(o,`${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&&oe(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?oe(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Pt(o,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&oe(o,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&oe(o,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))&&oe(o,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&oe(o,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function At(o){let e=[];Ce(e,"manifest.projectId",o.manifest.projectId),He(e,"manifest.createdAt",o.manifest.createdAt),He(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(g,u)=>{let I=t.get(g);I?oe(e,u,"duplicate_id",`ID is already used at ${I}.`):t.set(g,u)};o.records.forEach((g,u)=>{let I=`records[${u}]`;n(g.id,I),Qa(e,g,I,o.manifest.projectId)}),o.events.forEach((g,u)=>{let I=`events[${u}]`;n(g.id,I),Ha(e,g,I),g.projectId!==o.manifest.projectId&&oe(e,`${I}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((g,u)=>{let I=`relationships[${u}]`;n(g.id,I),Xa(e,g,I),g.projectId!==o.manifest.projectId&&oe(e,`${I}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((g,u)=>{n(g.id,`artifacts[${u}]`),Ce(e,`artifacts[${u}].id`,g.id)}),o.tombstones.forEach((g,u)=>{let I=`tombstones[${u}]`;n(g.id,I),Ce(e,`${I}.id`,g.id),Ce(e,`${I}.objectId`,g.objectId),Ce(e,`${I}.deletedById`,g.deletedById),He(e,`${I}.deletedAt`,g.deletedAt),Pt(e,`${I}.authority`,g.authority,!0)});let r=new Set(o.records.map(g=>`${g.recordType}:${g.id}`)),i=new Set(o.tombstones.map(g=>`${g.objectType}:${g.objectId}`)),s=(g,u)=>{if(g.storeId)return;let I=`${g.entityType}:${g.entityId}`;!r.has(I)&&!i.has(I)&&oe(e,u,"dangling_entity_reference",`No record or tombstone exists for ${I}.`)};o.events.forEach((g,u)=>s(g.entity,`events[${u}].entity`)),o.relationships.forEach((g,u)=>{s(g.from,`relationships[${u}].from`),s(g.to,`relationships[${u}].to`)});let a=new Set(o.artifacts.map(g=>g.id)),d=(g,u)=>{a.has(g)||oe(e,u,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(g,u,I)=>{!r.has(`${g}:${u}`)&&!i.has(`${g}:${u}`)&&oe(e,I,"dangling_entity_reference",`No ${g} record or tombstone exists.`)};o.records.forEach((g,u)=>{let I=`records[${u}]`;switch(g.recordType){case"authority_grant":l("participant",g.granteeId,`${I}.granteeId`),l("participant",g.grantedById,`${I}.grantedById`),g.subjectIds.forEach((f,p)=>l("subject",f,`${I}.subjectIds[${p}]`));break;case"observation":g.captureContext.subjectIds.forEach((f,p)=>l("subject",f,`${I}.captureContext.subjectIds[${p}]`)),g.captureContext.artifactIds.forEach((f,p)=>d(f,`${I}.captureContext.artifactIds[${p}]`));break;case"proposal":case"decision":g.subjects.forEach((f,p)=>l("subject",f.subjectId,`${I}.subjects[${p}].subjectId`));break;case"thread":g.messageArtifactIds.forEach((f,p)=>d(f,`${I}.messageArtifactIds[${p}]`)),g.resultRefs.forEach((f,p)=>s(f,`${I}.resultRefs[${p}]`));break;case"iteration":g.threadIds.forEach((f,p)=>l("thread",f,`${I}.threadIds[${p}]`)),g.artifactIds.forEach((f,p)=>d(f,`${I}.artifactIds[${p}]`));break;case"evidence":g.artifactIds.forEach((f,p)=>d(f,`${I}.artifactIds[${p}]`));break;case"advisory_explanation":g.subjectIds.forEach((f,p)=>l("subject",f,`${I}.subjectIds[${p}]`)),g.evidenceIds.forEach((f,p)=>l("evidence",f,`${I}.evidenceIds[${p}]`)),g.supersededById&&l("advisory_explanation",g.supersededById,`${I}.supersededById`);break;case"implementation_attempt":g.iterationIds.forEach((f,p)=>l("iteration",f,`${I}.iterationIds[${p}]`)),g.coverageClaims.forEach((f,p)=>l("decision",f.decisionId,`${I}.coverageClaims[${p}].decisionId`)),g.artifactIds.forEach((f,p)=>d(f,`${I}.artifactIds[${p}]`));break;case"eval_spec":g.replacesSpecId&&l("eval_spec",g.replacesSpecId,`${I}.replacesSpecId`),g.decisionIds.forEach((f,p)=>l("decision",f,`${I}.decisionIds[${p}]`)),g.subjectIds.forEach((f,p)=>l("subject",f,`${I}.subjectIds[${p}]`)),(g.dependencies??[]).forEach((f,p)=>{f.kind==="subject"&&f.subjectId&&l("subject",f.subjectId,`${I}.dependencies[${p}].subjectId`)}),(g.scenarios??[]).forEach((f,p)=>{f.subjectIds?.forEach((j,h)=>l("subject",j,`${I}.scenarios[${p}].subjectIds[${h}]`))}),g.targets.forEach((f,p)=>l(f.entityType,f.entityId,`${I}.targets[${p}]`));break;case"verification_attempt":g.evalSpecId&&l("eval_spec",g.evalSpecId,`${I}.evalSpecId`),g.targets.forEach((f,p)=>l(f.entityType,f.entityId,`${I}.targets[${p}]`)),g.evidenceIds.forEach((f,p)=>l("evidence",f,`${I}.evidenceIds[${p}]`));break;case"model_entry":g.subjectIds.forEach((f,p)=>l("subject",f,`${I}.subjectIds[${p}]`)),g.decisionIds.forEach((f,p)=>l("decision",f,`${I}.decisionIds[${p}]`));break;case"model_projection":Pt(e,`${I}.authority`,g.authority,!0),l("participant",g.appliedById,`${I}.appliedById`),g.decisionIds.forEach((f,p)=>l("decision",f,`${I}.decisionIds[${p}]`)),g.entryIds.forEach((f,p)=>l("model_entry",f,`${I}.entryIds[${p}]`)),g.coverage.forEach((f,p)=>l("decision",f.decisionId,`${I}.coverage[${p}].decisionId`));break;case"freshness_signal":s(g.target,`${I}.target`),g.evidenceIds.forEach((f,p)=>l("evidence",f,`${I}.evidenceIds[${p}]`));break;default:break}});let v=new Map(o.events.map(g=>[g.id,g])),S=new Map(o.records.map(g=>[`${g.recordType}:${g.id}`,g])),y=new Map;o.events.forEach((g,u)=>{let I=`${g.entity.entityType}:${g.entity.entityId}:${g.fromState??"null"}`,f=y.get(I)??new Set;f.add(g.toState),y.set(I,f),f.size>1&&oe(e,`events[${u}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(o.records.flatMap(g=>g.recordType==="authority_grant"?[[g.id,g]]:[])),T=(g,u,I,f,p)=>{if(g.level!=="delegate"||!g.grantId)return;let j=k.get(g.grantId);if(!j){oe(e,p,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==u||j.level!=="delegate")&&oe(e,p,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(I);(h<Date.parse(j.startsAt)||j.endsAt&&h>Date.parse(j.endsAt)||j.revokedAt&&h>=Date.parse(j.revokedAt))&&oe(e,p,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&f.length&&!f.every(m=>j.subjectIds.includes(m))&&oe(e,p,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let g of o.records)g.recordType==="decision"&&T(g.authority,g.acceptedById,g.createdAt,g.subjects.map(u=>u.subjectId),`records:${g.id}.authority`);o.events.forEach((g,u)=>{let I=S.get(`${g.entity.entityType}:${g.entity.entityId}`),f=I&&"subjects"in I?I.subjects.map(p=>p.subjectId):[];T(g.authority,g.participantId,g.createdAt,f,`events[${u}].authority`)}),o.relationships.forEach((g,u)=>{if(!g.authority)return;let I=[g.from,g.to].flatMap(f=>{let p=S.get(`${f.entityType}:${f.entityId}`);return p&&"subjects"in p?p.subjects.map(j=>j.subjectId):[]});T(g.authority,g.participantId,g.createdAt,I,`relationships[${u}].authority`)});for(let g of o.records){if(g.recordType!=="decision")continue;let u=v.get(g.acceptanceEventId);(!u||u.entity.entityType!=="proposal"||u.entity.entityId!==g.proposalId||u.toState!=="accepted")&&oe(e,`records:${g.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),u&&u.participantId!==g.acceptedById&&oe(e,`records:${g.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),S.has(`proposal:${g.proposalId}`)||oe(e,`records:${g.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),g.state==="superseded"&&(o.relationships.some(f=>f.relationshipType==="supersedes"&&f.to.entityType==="decision"&&f.to.entityId===g.id)||oe(e,`records:${g.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),g.state==="revoked"&&(o.events.some(f=>f.entity.entityType==="decision"&&f.entity.entityId===g.id&&f.toState==="revoked"&&!!f.reason?.trim())||oe(e,`records:${g.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let g of o.records){if(g.recordType!=="proposal"||g.state!=="accepted")continue;o.records.some(I=>I.recordType==="decision"&&I.proposalId===g.id)||oe(e,`records:${g.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Wa(e)}function hn(o,e,t,n){return{id:n,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function ni(o,e,t,n,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,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 Ya(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Vn(o,e){let t=[],n=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.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."}),Wt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Ya(e))Wt(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||!n)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={...hn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=ni(o,n,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.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={...hn(o,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...hn(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=ni(o,i,e,a.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[i,d],events:[s,a],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.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={...hn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let r={...hn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.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:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}import{createHash as Za}from"crypto";import{readFile as ed,readdir as td,realpath as nd}from"fs/promises";import{join as gn,relative as od}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 Vt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ge(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function oi(...o){return o.find(e=>!!e?.trim())?.trim()}function pe(o,e,t,n){let i=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Za("sha256").update(`${o}\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 Yo(o,e){try{return JSON.parse(await ed(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function id(o){let e=Vt(o);if(!e)return 0;let t=0,n=r=>{let i=Vt(r);if(!i){t+=1;return}for(let s of Object.values(i))n(s)};for(let r of Object.values(e))n(r);return t}function sd(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function yn(o){let e=[],t=await nd(o.projectRoot).catch(()=>o.projectRoot),n=gn(t,".popmelt"),r=await Yo(gn(n,"threads.json"),e),i=await Yo(gn(n,"model.json"),e),s=Vt(r),a=Vt(s?.threads)??{},d=Object.entries(a).map(([q,J])=>({key:q,value:Vt(J)})).filter(q=>!!q.value),l=gn(n,"decisions"),v=await td(l).catch(()=>[]),S=[];for(let q of v.filter(J=>J.endsWith(".json")).sort()){let J=Vt(await Yo(gn(l,q),e));J&&S.push({file:q,value:J})}let y=d.flatMap(({value:q})=>[q.createdAt,q.updatedAt]).filter(q=>typeof q=="number"&&Number.isFinite(q)),k=y.length?Math.min(...y):0,T=o.projectKey??t;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let g=pe(T,"project",T,k),u=pe(T,"participant","legacy-owner",k),I=pe(T,"participant","legacy-agent",k),f=pe(T,"subject","project",k),p=Ge(Math.max(k,...y)),j=[],h=[],m=new Map,M=new Map,D=new Map(S.map(q=>[q.value.id??q.file.replace(/^d-|\.json$/g,""),q.value])),P=new Map,A=(q,J,H,he,$e)=>{let se=m.get(H);if(se)return se;let Je=pe(T,"artifact",q,he);return h.push({id:Je,kind:J,mediaType:$e,location:H,availability:"available"}),m.set(H,Je),Je};for(let{file:q,value:J}of S){let H=J.id??q.replace(/^d-|\.json$/g,""),he=J.createdAt??k,$e=[A(`${H}:envelope`,"other",`.popmelt/decisions/${q}`,he,"application/json")];J.screenshotPath&&$e.push(A(`${H}:screenshot`,"screenshot",`.popmelt/${J.screenshotPath.replace(/^\.popmelt\//,"")}`,he,J.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[se,Je]of(J.pastedImagePaths??[]).entries())$e.push(A(`${H}:image:${se}`,"image",Je,he));P.set(H,$e)}let Q=(q,J,H)=>({id:q,schemaVersion:1,projectId:g,createdAt:p,participantId:J,sourceRefs:H}),z=(q,J)=>{j.push(J);let H=M.get(q)??[];H.push(J.id),M.set(q,H)},E=[{...Q(u,u,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...Q(I,I,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(...E),j.push({...Q(f,u,[]),recordType:"subject",subjectType:"project",label:od(process.cwd(),t)||t,aliases:[],locators:[{id:pe(T,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:Ge(k),sourceRefs:[]}]});let G=new Map,W=(q,J)=>{let H=G.get(q);if(H)return H;let he=pe(T,"subject",q,J),$e={...Q(he,u,[{kind:"external",id:q}]),createdAt:Ge(J),recordType:"subject",subjectType:"element",label:q,aliases:[],locators:[{id:pe(T,"locator",q,J),kind:"dom_selector",value:q,status:"current",validFrom:Ge(J),sourceRefs:[{kind:"external",id:q}]}]};return j.push($e),G.set(q,he),he};for(let{key:q,value:J}of d){let H=J.id??q,he=J.createdAt??k,$e=pe(T,"thread",H,he),se={kind:"thread",id:H},Je=[],vt=[],pn=Array.isArray(J.messages)?J.messages:[],Pe,ot,bt=0;pn.forEach((ke,ut)=>{let qe=ke.timestamp??he,rt=pe(T,"artifact",`${H}:message:${ut}`,qe);if(Je.push(rt),h.push({id:rt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${H}/messages/${ut}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${H}/messages/${ut}`,rt),ke.screenshotPath&&A(`${H}:message:${ut}:screenshot`,"screenshot",ke.screenshotPath,qe),ke.role==="human"){Pe=ke;let Oe=ke.feedbackSummary??ke.replyToQuestion;if(Oe?.trim()){let Fe=pe(T,"observation",`${H}:${ut}`,qe),ht=J.elementIdentifiers??[],Ot={...Q(Fe,u,[se,{kind:"message",id:rt}]),createdAt:Ge(qe),recordType:"observation",state:"open",statement:Oe,captureContext:{subjectIds:ht.map(St=>W(St,he)),artifactIds:[rt]},resolvedByIds:[]};z(H,Ot),ot=Fe,vt.push({entityType:"observation",entityId:Fe})}return}if(ke.role!=="assistant")return;let mt=ke.jobId??`${H}:${ut}`,ft=pe(T,"iteration",mt,qe),xt=D.get(mt),Bo=ke.cancelled?"cancelled":ke.error?"failed":ke.question?"question_asked":(ke.resolutions?.length??0)>0?"completed":"no_change",Jo={...Q(ft,I,[se,{kind:"message",id:rt},...(P.get(mt)??[]).map(Oe=>({kind:"artifact",id:Oe}))]),createdAt:Ge(qe),recordType:"iteration",threadIds:[$e],startedAt:Ge(Pe?.timestamp,qe),completedAt:Ge(qe),requestSummary:oi(Pe?.feedbackSummary,Pe?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ke.question??ke.error??ke.responseText?.slice(0,1e3),outcome:Bo,execution:{provider:ke.provider??xt?.provider,model:ke.model??xt?.model,sessionId:ke.sessionId??xt?.sessionId},artifactIds:[rt,...P.get(mt)??[]]};z(H,Jo),vt.push({entityType:"iteration",entityId:ft});let un=ke.resolutions??xt?.resolutions??[];for(let[Oe,Fe]of un.entries()){if(Fe.status!=="resolved"||!Fe.summary?.trim())continue;let ht=J.elementIdentifiers??[],Ot=(ht.length?ht:[t]).map(qn=>({subjectId:qn===t?f:W(qn,he),role:"governed"})),St=pe(T,"proposal",`${mt}:${Fe.annotationId??"resolution"}:${Oe}`,qe),qo={...Q(St,I,[se,{kind:"iteration",id:ft}]),createdAt:Ge(qe),recordType:"proposal",state:"pending",claim:Fe.summary,subjects:Ot,subjectSemantics:Ot.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:oi(Pe?.feedbackSummary,Pe?.replyToQuestion,Fe.summary),iterationId:ft,inferredById:I}};z(H,qo),vt.push({entityType:"proposal",entityId:St}),e.push({severity:"warning",code:"acceptance_unresolved",source:H,message:`Proposal ${St} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(un.some(Oe=>Oe.status==="resolved")||xt?.gitDiff){let Oe=pe(T,"implementation",mt,qe),Fe={...Q(Oe,I,[se,{kind:"iteration",id:ft}]),createdAt:Ge(qe),recordType:"implementation_attempt",state:"completed",iterationIds:[ft],coverageClaims:[],summary:un.map(ht=>ht.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};z(H,Fe),vt.push({entityType:"implementation_attempt",entityId:Oe}),bt+=1}ot&&(ot=void 0)});let $t=pn.at(-1),No={...Q($e,u,[se]),createdAt:Ge(he),recordType:"thread",state:$t?.question?"open":"resolved",messageArtifactIds:Je,outcome:$t?.question?"question_unresolved":bt?"implementation_only":"no_outcome",resultRefs:vt};j.push(No),M.set(H,[$e,...M.get(H)??[]])}let ue=id(i);ue&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ue} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:g,createdAt:Ge(k),updatedAt:p,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:j,events:[],relationships:[],artifacts:h,tombstones:[]},re=At(X),O=(o.proofCaseIds??rd).map(q=>({legacyId:q,threadFound:d.some(({key:J,value:H})=>(H.id??J)===q),decisionEnvelopeFound:D.has(q),recordIds:M.get(q)??[]}));return{bundle:X,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((q,J)=>q+(J.value.messages?.length??0),0),decisionEnvelopes:S.length,modelEntries:ue,artifactsReferenced:h.length},imported:sd(j),unresolvedAcceptance:e.filter(q=>q.code==="acceptance_unresolved").length,deferredModelEntries:ue,proofCases:O,issues:e,schemaIssues:re.issues}}}var ad=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function ri(o,e){let t=o.records.find(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),n=o.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=ad(),l=d.records,v=o.records.find(p=>p.recordType==="thread"&&p.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));v||(v={id:pe(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.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(p=>p.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(v));let S=[];for(let p of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===p&&m.status==="current"));j||(j={id:pe(r,"live-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"element",label:p,aliases:[],locators:[{id:pe(r,"live-locator",p,e.createdAt),kind:"dom_selector",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},l.push(j)),S.push(j)}for(let p of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=o.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===p&&m.status==="current"));j||(j={id:pe(r,"live-file-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"file",label:p,aliases:[],locators:[{id:pe(r,"live-file-locator",p,e.createdAt),kind:"source_file",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},l.push(j)),S.push(j)}let y=(e.semanticCandidates??[]).filter(p=>p.claim.trim()),k;if(y.length>0){k=pe(r,"live-observation",i,e.createdAt);let p={id:k,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:y.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:S.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};l.push(p)}let T=pe(r,"live-iteration",i,e.completedAt),g={id:T,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(p=>({kind:"external",id:p,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(p=>({kind:"external",id:p,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[v.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}:{}};l.push(g);let u=[],I=e.resolutions.filter(p=>p.status==="resolved"&&p.summary.trim()),f=S.length>0?S:o.records.filter(p=>p.recordType==="subject"&&p.subjectType==="project").slice(0,1);if(y.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[p,j]of y.entries()){let h=pe(r,"live-proposal",`${i}:${p}`,e.completedAt),m=f.map(D=>({subjectId:D.id,role:"governed"})),M={id:h,schemaVersion:1,projectId:o.manifest.projectId,createdAt:a,participantId:n.id,sourceRefs:[{kind:"iteration",id:T},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:j.claim.trim(),rationale:j.rationale?.trim()||void 0,proposedKind:j.proposedKind,subjects:m,subjectSemantics:m.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:j.sourceText?.trim()||e.requestSummary,iterationId:T,inferredById:n.id}};l.push(M),u.push(h)}if(I.length>0){let p=new Set(e.governingDecisionIds??[]),j=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&p.has(m.id)),h={id:pe(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:a,participantId:n.id,sourceRefs:[{kind:"iteration",id:T}],recordType:"implementation_attempt",state:"completed",iterationIds:[T],coverageClaims:j.map(m=>({decisionId:m.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${I.map(M=>M.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:T}]})),summary:I.map(m=>m.summary).join(" "),artifactIds:[]};l.push(h)}return{mutation:d,iterationId:T,proposalIds:u,observationId:k}}import{createHash as dd}from"crypto";import{mkdir as ii,open as Zo,readFile as er,readdir as cd,rename as ld,unlink as tr}from"fs/promises";import{join as ct}from"path";var pd={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Kn(o){return dd("sha256").update(JSON.stringify(o)).digest("hex")}function si(o){return Kn(o)}function ai(o,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let r=o.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(r<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let i=o.records[r];if(i.projectId!==n.projectId||i.createdAt!==n.createdAt||i.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);o.records[r]=structuredClone(n)}for(let n of e.projectionUpdates){let r=o.records.find(i=>i.recordType===n.entityType&&i.id===n.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(r.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${r.state}`);r.state=n.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=t,o}function ud(o,e,t){return ai(structuredClone(o),e,t)}async function jt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Zo(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
13
- `,"utf8"),await n.sync()}finally{await n.close()}try{await ld(t,o)}catch(r){throw await tr(t).catch(()=>{}),r}}async function In(o){return JSON.parse(await er(o,"utf8"))}var Hn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=ct(e,".popmelt","memory"),this.journalDir=ct(this.memoryDir,"journal"),this.manifestPath=ct(this.memoryDir,"manifest.json"),this.checkpointPath=ct(this.memoryDir,"checkpoint.json"),this.lockPath=ct(this.memoryDir,"writer.lock")}async readHead(){let e=await In(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=At(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await ii(this.journalDir,{recursive:!0});try{throw await er(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await er(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 n=Kn(e),r={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await jt(this.checkpointPath,r),await jt(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 jt(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=Kn(e.bundle),n=`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 jt(ct(this.memoryDir,n),r),e.manifest.checkpoint={file:n,sequence:r.sequence,hash:t},await jt(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(!Wt(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 n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let r=n.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...i,hash:si(i)},a=ud(n.bundle,e,t.committedAt),d=At(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await jt(ct(this.journalDir,l),s),n.manifest.head={sequence:r,hash:s.hash},n.manifest.updatedAt=t.committedAt,await jt(this.manifestPath,n.manifest),{bundle:a,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...pd,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await In(this.manifestPath),t=await In(ct(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!==Kn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await cd(this.journalDir),r=n.filter(y=>y.endsWith(".tmp")),s=n.filter(y=>/^\d{12}-[0-9a-f-]+\.json$/i.test(y)).sort().filter(y=>Number(y.slice(0,12))>t.sequence),a=structuredClone(t.bundle),d=t.sequence,l=t.journalHash??null,v=new Set;for(let y of s){let k=await In(ct(this.journalDir,y)),{hash:T,...g}=k;if(T!==si(g))throw new Error(`Journal hash mismatch: ${y}`);if(k.sequence!==d+1)throw new Error(`Journal sequence gap at ${y}`);if(k.previousHash!==l)throw new Error(`Journal chain mismatch at ${y}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${y}`);if(v.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);ai(a,k.mutation,k.committedAt),d=k.sequence,l=k.hash,v.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!==l)throw new Error("Journal manifest head hash mismatch.");let S=At(a);if(!S.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(S.issues)}`);return{bundle:a,manifest:e,transactionIds:v,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await ii(this.memoryDir,{recursive:!0});let t;try{t=await Zo(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let r=await In(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 tr(this.lockPath),t=await Zo(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await tr(this.lockPath).catch(()=>{})}}};import{createHash as md}from"crypto";import{mkdir as fd,open as hd,readFile as gd,rename as yd,unlink as Id}from"fs/promises";import{join as di}from"path";function ci(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function li(o){return md("sha256").update(JSON.stringify(o)).digest("hex")}async function wd(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await hd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
14
- `,"utf8"),await n.sync()}finally{await n.close()}try{await yd(t,o)}catch(r){throw await Id(t).catch(()=>{}),r}}function vd(o,e,t=new Date().toISOString()){let n={},r={},i={},s=(d,l,v)=>{let S=d[l]??=[];S.includes(v)||S.push(v)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(S=>S.status==="current").map(S=>S.value)]){let S=ci(v);S&&s(n,S,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let a={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:li(a)}}function pi(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[ci(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>o.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>o.proposalIdsBySubject[n]??[]))]}}var Qn=class{constructor(e){this.indexDir=di(e,".popmelt","memory","indexes"),this.indexPath=di(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await gd(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===li(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let n=vd(e,t);return await fd(this.indexDir,{recursive:!0}),await wd(this.indexPath,n),n}};import{randomBytes as bd}from"crypto";function Se(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=bd(10).toString("hex"),r=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${r}${n.slice(4,7)}-${n.slice(7,19)}`}var bn="popmelt:imprint",fi="popmelt:imprint-evidence",Ht="popmelt:imprint-relation";function vn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===bn)?.id}function nr(o){let e=new Set;return o.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function Xn(o,e){if(!o)return[];let t=new Set(o.relations.flatMap(n=>n.type==="expresses"&&!n.toStoreId&&n.toId===e?[n.fromId]:[]));return o.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function or(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var Yt=class{constructor(e){this.projectRoot=e;this.store=new Hn(e),this.indexStore=new Qn(e),this.manifestPath=Kt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await wn(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 n=await yn({...e,projectRoot:this.projectRoot});if(n.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(n.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 yn({...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=Kt(this.projectRoot,".popmelt","memory","migrations"),t=Kt(e,"imprint-advisories-v2.json");try{let p=JSON.parse(await wn(t,"utf8"));return{migrated:!1,explanations:p.explanations??0,evidence:p.evidence??0}}catch{}let n;try{n=kt(JSON.parse(await wn(Kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await ui(e,{recursive:!0}),await mi(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(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),a=r.bundle.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.status==="active")??i,d=r.bundle.records.find(p=>p.recordType==="subject"&&p.subjectType==="project");if(!a||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,v=new Set(r.bundle.records.map(p=>p.id)),S=new Set(r.bundle.relationships.flatMap(p=>p.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Ht?[j.id]:[]))),y=new Map,k=r.bundle.records.filter(p=>p.recordType==="advisory_explanation");for(let p of n.explanations){let j=k.find(h=>vn(h)===p.id);y.set(p.id,j?.id??pe(l,"imprint-explanation",p.id,Date.parse(p.createdAt)))}let T=[],g=[],u=[],I=0;for(let p of n.explanations){let j=y.get(p.id),h=k.find(P=>P.id===j),m=[],M=p.evidence.length?p.evidence:[{id:`fallback:${p.id}`,kind:"observation",stance:"supports",summary:p.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:p.createdAt}];for(let P of M){let A=pe(l,"imprint-evidence-record",P.id,Date.parse(P.createdAt));m.push(A),!v.has(A)&&(T.push({id:A,schemaVersion:1,projectId:l,createdAt:P.createdAt,participantId:a.id,sourceRefs:nr([{kind:"external",id:P.id,uri:fi},{kind:"external",id:p.id,uri:bn},{kind:"thread",id:P.threadId},{kind:"message",id:P.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(P.kind)?"user_feedback":"judgment",summary:P.summary,availability:"available",artifactIds:[]}),u.push({id:pe(l,"imprint-evidence-link",`${p.id}:${P.id}`,Date.parse(P.createdAt)),schemaVersion:1,projectId:l,createdAt:P.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:P.id,uri:fi}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:A},reason:"This advisory explanation was derived from collaboration evidence."}),I+=1)}let D={id:j,schemaVersion:1,projectId:l,createdAt:h?.createdAt??p.createdAt,participantId:h?.participantId??a.id,sourceRefs:nr([...h?.sourceRefs??[],{kind:"external",id:p.id,uri:bn}]),recordType:"advisory_explanation",kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),subjectIds:[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:Xn(n,p.id),supersededById:p.supersededBy?y.get(p.supersededBy):void 0,updatedAt:p.updatedAt};h?g.push(D):T.push(D)}for(let p of n.relations){let j=or(p.type);if(!j||p.toStoreId)continue;let h=y.get(p.fromId),m=y.get(p.toId);!h||!m||S.has(p.id)||u.push({id:pe(l,"imprint-relation",p.id,Date.parse(p.createdAt)),schemaVersion:1,projectId:l,createdAt:p.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:p.id,uri:Ht}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:h},to:{entityType:"advisory_explanation",entityId:m},reason:p.rationale||"The Imprint graph connected these explanations."})}let f=new Date().toISOString();if(T.length||g.length||u.length)try{let p=await this.store.commit({records:T,recordReplacements:g,events:[],relationships:u,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:pe(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:f});await this.refreshIndex(p)}catch(p){if(!(p instanceof Error)||!p.message.includes("Transaction already exists"))throw p}return await ui(e,{recursive:!0}),await mi(t,JSON.stringify({version:2,migratedAt:f,explanations:n.explanations.length,evidence:I,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:I}}async review(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,selection:Qo(n.bundle,r)}}async contextualize(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:ei(n.bundle,r),reviewSelection:Qo(n.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:vn(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 n=await this.loadSource(t);return{source:n.source,result:Vn(n.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 yn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.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 n=await this.store.load(),r=Vn(n.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(),n=t.bundle.records.find(y=>y.recordType==="proposal"&&y.id===e.proposalId),r=t.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active");if(!n||n.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.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:n.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:Se(i),decisionId:Se(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:Se(i),replacementProposalId:Se(i),acceptanceEventId:Se(i),decisionId:Se(i),relationshipId:Se(i),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:Se(i),reason:e.reason}:{...a,action:"defer",eventId:Se(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(y=>y.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=Vn(t.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(y=>y.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:Se(i),committedAt:s});await this.refreshIndex(v);let S=l.plan.resultRefs.find(y=>y.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:S,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:v.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(),n=ri(t.bundle,e),r=pe(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(n.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.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=kt(JSON.parse(await wn(Kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),r=n.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),i=n.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="ai"&&f.status==="active"),s=e.action?r:i??r,a=n.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),v=n.bundle.manifest.projectId,S=[],y=[],k=[],T=n.bundle.records.filter(f=>f.recordType==="advisory_explanation"),g=new Map(T.flatMap(f=>{let p=vn(f);return p?[[p,f.id]]:[]}));for(let f of e.summary.changes)if(!g.has(f.explanationId)){let p=t?.explanations.find(j=>j.id===f.explanationId);g.set(f.explanationId,pe(v,"imprint-explanation",f.explanationId,Date.parse(p?.createdAt??d)))}for(let f of e.summary.changes){let p={kind:"external",id:f.explanationId,uri:bn},j=g.get(f.explanationId),h=T.find(P=>P.id===j),m=t?.explanations.find(P=>P.id===f.explanationId),M={id:pe(v,"imprint-live-evidence",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,participantId:s.id,sourceRefs:[p,{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:[]};S.push(M);let D={id:j,schemaVersion:1,projectId:v,createdAt:h?.createdAt??m?.createdAt??d,participantId:h?.participantId??s.id,sourceRefs:nr([...h?.sourceRefs??[],p,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??h?.kind??"pattern",state:m?.state??f.state,statement:m?.statement??f.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[a.id],evidenceIds:[...new Set([...h?.evidenceIds??[],M.id])],concreteBindings:m?Xn(t,f.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?g.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??d};h?y.push(D):S.push(D),k.push({id:pe(v,"imprint-live-evidence-link",`${e.summary.transactionId}:${f.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,participantId:s.id,sourceRefs:[p],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.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 u=new Set(n.bundle.relationships.flatMap(f=>f.sourceRefs.flatMap(p=>p.kind==="external"&&p.uri===Ht?[p.id]:[])));for(let f of t?.relations??[]){let p=or(f.type);if(!p)continue;let j=g.get(f.fromId),h=f.toStoreId?e.qualifiedExplanationMemoryIds?.[`${f.toStoreId}:${f.toId}`]:g.get(f.toId);!j||!h||u.has(f.id)||k.push({id:pe(v,"imprint-relation",f.id,Date.parse(f.createdAt)),schemaVersion:1,projectId:v,createdAt:f.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:f.id,uri:Ht}],recordType:"relationship",relationshipType:p,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:h,...f.toStoreId?{storeId:f.toStoreId}:{}},reason:f.rationale||"The Imprint graph connected these explanations."})}let I=pe(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let f=await this.store.commit({records:S,recordReplacements:y,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:I,committedAt:d});await this.refreshIndex(f)}catch(f){if(!(f instanceof Error)||!f.message.includes("Transaction already exists"))throw f}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=kt(JSON.parse(await wn(Kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),i=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??n;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let a=t.bundle.manifest.projectId,d=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(d.flatMap(m=>{let M=vn(m);return M?[[M,m]]:[]})),v=new Map([...[...l].map(([m,M])=>[m,M.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,pe(a,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),S=[],y=[],k=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let M=l.get(m.id);if(!M){S.push({id:v.get(m.id),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:bn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Xn(e,m.id),supersededById:m.supersededBy?v.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(M),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:Xn(e,m.id),supersededById:m.supersededBy?v.get(m.supersededBy):void 0,updatedAt:m.updatedAt},P=A=>JSON.stringify({kind:A.kind,state:A.state,statement:A.statement,rationale:A.rationale,scope:A.scope,concreteBindings:A.concreteBindings,supersededById:A.supersededById,updatedAt:A.updatedAt});P(M)!==P(D)&&y.push(D)}for(let[m,M]of l)k.has(m)||M.state==="retired"||y.push({...structuredClone(M),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let T=new Set(t.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),g=new Map(t.bundle.relationships.flatMap(m=>{if(T.has(m.id))return[];let M=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Ht)?.id;return M?[[M,m]]:[]})),u=[],I=new Set;for(let m of e.relations){let M=or(m.type);if(!M||m.toStoreId)continue;let D=v.get(m.fromId),P=v.get(m.toId);if(!D||!P)continue;let A=g.get(m.id);A&&A.relationshipType===M&&A.from.entityType==="advisory_explanation"&&A.from.entityId===D&&A.to.entityType==="advisory_explanation"&&A.to.entityId===P||(A&&I.add(m.id),u.push({id:pe(a,"imprint-relation",`${m.id}:${M}:${D}:${P}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Ht}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:P},reason:m.rationale||"The Imprint graph connected these explanations."}))}let f=new Set(e.relations.map(m=>m.id)),p=n?[...g].filter(([m])=>!f.has(m)||I.has(m)).map(([,m])=>({id:pe(a,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!S.length&&!y.length&&!u.length&&!p.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let j=e.updatedAt,h=pe(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let m=await this.store.commit({records:S,recordReplacements:y,events:[],relationships:u,artifacts:[],tombstones:p,projectionUpdates:[]},{transactionId:h,committedAt:j});return await this.refreshIndex(m),{status:"synced",relationships:u.length+p.length,explanations:S.length+y.length,headSequence:m.report.headSequence}}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m;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 n={};for(let r of t.bundle.records)n[r.recordType]=(n[r.recordType]??0)+1;return{status:e,journal:t.report,records:n,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(),n=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"&&!n.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]:[])),n=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))&&n.set(r.key,r);return[...n.values()]}async getImprintView(e=[],t){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let r=await this.store.load(),i=r.bundle.records.filter(u=>u.recordType==="advisory_explanation"),s=new Map(i.map(u=>[u.id,u])),a=new Map(i.flatMap(u=>{let I=vn(u);return I?[[I,u.id]]:[]})),d=new Set(e.map(u=>a.get(u)??u)),l=new Map(r.bundle.records.flatMap(u=>u.recordType==="participant"?[[u.id,u.kind]]:[])),v=new Map(r.bundle.records.flatMap(u=>u.recordType==="evidence"?[[u.id,u]]:[])),S=new Set(r.bundle.tombstones.flatMap(u=>u.objectType==="relationship"?[u.objectId]:[])),y=new Set(["expresses","operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},T=i.map(u=>{let I=u.evidenceIds.flatMap(h=>{let m=v.get(h);if(!m)return[];let M=m.sourceRefs.find(Q=>Q.kind==="thread")?.id,D=m.sourceRefs.find(Q=>Q.kind==="message")?.id,P=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",A=l.get(m.participantId)??"unknown";return[{id:m.id,kind:P,summary:m.summary,createdAt:m.createdAt,participantKind:A,threadId:M,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),f=r.bundle.relationships.flatMap(h=>{if(S.has(h.id))return[];if(!y.has(h.relationshipType))return[];let m=h.from.entityType==="advisory_explanation"&&h.from.entityId===u.id&&h.to.entityType==="advisory_explanation",M=h.to.entityType==="advisory_explanation"&&h.to.entityId===u.id&&h.from.entityType==="advisory_explanation";if(!m&&!M)return[];let D=m?h.to.entityId:h.from.entityId,P=s.get(D);return P?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:P.id,statement:P.statement,rationale:h.reason}]:[]}),p=[...(u.supersededById?[u.supersededById]:[]).flatMap(h=>{let m=s.get(h);return m?[{id:`supersedes:${u.id}:${m.id}`,type:"supersedes",direction:"incoming",explanationId:m.id,statement:m.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...i.flatMap(h=>h.supersededById===u.id?[{id:`supersedes:${h.id}:${u.id}`,type:"supersedes",direction:"outgoing",explanationId:h.id,statement:h.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...u.sourceRefs.flatMap(h=>h.kind==="thread"?[h.id]:[]),...I.flatMap(h=>h.threadId?[h.threadId]:[])])].filter(h=>!t||t.has(h));return{id:u.id,kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),createdAt:u.createdAt,updatedAt:u.updatedAt,evidenceCount:I.length,recentEvidence:I.slice(0,4),concrete:u.concreteBindings.map(h=>({...structuredClone(h)})),relations:[...f,...p],sourceThreadIds:j,needsGrounding:u.state==="testing"&&d.has(u.id)}}).sort((u,I)=>Number(I.needsGrounding)-Number(u.needsGrounding)||k[u.state]-k[I.state]||I.updatedAt.localeCompare(u.updatedAt)),g={total:T.filter(u=>u.state!=="retired").length,emerging:T.filter(u=>u.state==="emerging").length,testing:T.filter(u=>u.state==="testing").length,grounded:T.filter(u=>u.state==="grounded").length,challenged:T.filter(u=>u.state==="challenged").length,retired:T.filter(u=>u.state==="retired").length,needsGrounding:T.filter(u=>u.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:g,explanations:T}}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]:[])),n=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))a.decisionIds.some(d=>t.has(d))&&n.set(a.key,a);let r=[...n.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(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===a.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(l=>l.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(),n=t.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active"),r=t.bundle.records.find(P=>P.recordType==="subject"&&P.subjectType==="project");if(!n||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=Se(i),d=Se(i),l=Se(i),v=Se(i),S=Se(i),y=new Set(t.bundle.records.flatMap(P=>P.recordType==="model_entry"&&P.key===e.key?P.decisionIds:[])),k=t.bundle.records.filter(P=>P.recordType==="decision"&&P.state==="active"&&y.has(P.id)),T={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},g=[{subjectId:r.id,role:"governed"}],u={...T,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:g,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},I={...T,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."},f={...T,id:l,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:g,noChange:!1,effectiveAt:s},p={...T,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},j={...T,id:S,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},h={...T,id:Se(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},m=k.map(P=>({...T,id:Se(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:P.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(P=>({...T,id:Se(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:P.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[u,f,p,j],events:[I,...m],relationships:[h,...M],artifacts:[],tombstones:[],projectionUpdates:k.map(P=>({entityType:"decision",entityId:P.id,fromState:"active",state:"superseded"}))},{transactionId:Se(i),committedAt:s});return await this.refreshIndex(D),{decisionId:l,entryId:v}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=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=n.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(),n=t.bundle.records.find(T=>T.recordType==="model_projection"&&T.state==="applied"&&T.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let r=t.bundle.records.filter(T=>T.recordType==="decision"&&e.decisionIds.includes(T.id)&&T.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(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=Se(s),l=e.changes.map(T=>{let g=T.decisionIds?.filter(f=>e.decisionIds.includes(f)),u=g?.length?g:e.decisionIds,I=[...new Set(r.filter(f=>u.includes(f.id)).flatMap(f=>f.subjects.map(p=>p.subjectId)))];return{id:Se(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:u.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:T.path.map(String).join("."),subjectIds:I,decisionIds:u,value:T.value}}),v=new Set(l.flatMap(T=>T.decisionIds)),S={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(T=>({kind:"record",id:T})),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:l.map(T=>T.id),coverage:e.decisionIds.map(T=>e.coverage?.find(g=>g.decisionId===T)??{decisionId:T,status:v.has(T)?"projected":"unprojected"})},y=l.flatMap(T=>T.decisionIds.map(g=>({id:Se(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:S.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:T.id},to:{entityType:"decision",entityId:g},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...l,S],events:[],relationships:y,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Se(s),committedAt:a});return await this.refreshIndex(k),{projectionId:d,entryIds:l.map(T=>T.id),headSequence:k.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await yn({...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 n=await this.store.load(),r={source:"journal",bundle:n.bundle,journal:n.report};return this.contextualSourceCache={headKey:t,value:r},r}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=pi(n,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 Xt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Re(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Qt(o,e,t){let n=Re(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function rr(o){let e=Xt(o),t=Xt(e.authority),n=t.level,r=t.mode,i=Qt(n,"authority.level",["owner","delegate","contributor"]),s=Qt(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Re(e.proposalId,"proposalId"),participantId:Re(e.participantId,"participantId"),occurredAt:Re(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:Re(e.eventId,"eventId"),decisionId:Re(e.decisionId,"decisionId"),kind:Qt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Re(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Re(e.eventId,"eventId"),reason:Re(e.reason,"reason")};case"defer":{let d=Xt(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:Re(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Re(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Qt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...a,action:"edit_and_accept",withdrawalEventId:Re(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Re(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Re(e.acceptanceEventId,"acceptanceEventId"),decisionId:Re(e.decisionId,"decisionId"),relationshipId:Re(e.relationshipId,"relationshipId"),claim:Re(e.claim,"claim"),kind:Qt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Xt(d);return{subjectId:Re(l.subjectId,"subjectId"),role:Qt(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Re(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function ir(o){let e=Xt(o),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Re(a,s))}},n=(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:Xt(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:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(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 xd=1400,Sd=6,Td=2,sr=6;function hi(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.projectRoot=="string"&&!!e.projectRoot.trim()&&typeof e.projectId=="string"&&!!e.projectId.trim()}function Ii(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!hi(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(hi):[],n=new Set([e.primary.storeId]);return{primary:e.primary,mounted:t.filter(r=>n.has(r.storeId)?!1:(n.add(r.storeId),!0))}}function gi(o){return[o.primary,...o.mounted]}function xn(o){let e=[],t=Math.max(0,...o.map(n=>n.length));for(let n=0;n<t;n++)for(let r of o)r[n]!==void 0&&e.push(r[n]);return e}function yi(o){return Math.ceil(JSON.stringify(o).length/4)}function kd(o,e,t){return{...o,...o.acceptedTruth?{acceptedTruth:{...o.acceptedTruth,decisions:o.acceptedTruth.decisions.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),conflicts:o.acceptedTruth.conflicts.map(n=>({...n,storeId:e.storeId}))}}:{},packets:o.packets.map(n=>({...n,presentation:t?"advisory":n.presentation,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Rd(o,e,t,n){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let r=o.map(({store:S,context:y})=>kd(y,S,S.storeId!==t)),i=xn(r.map(S=>S.acceptedTruth?.decisions??[])).slice(0,Sd),s=new Set(i.map(S=>`${S.storeId}:${S.id}`)),a=r.flatMap(S=>S.acceptedTruth?.conflicts??[]).filter(S=>S.decisionIds.every(y=>s.has(`${S.storeId}:${y}`))),d=xn(r.map(S=>S.packets)).slice(0,Td),l=i.length<r.reduce((S,y)=>S+(y.acceptedTruth?.decisions.length??0),0)||d.length<r.reduce((S,y)=>S+y.packets.length,0),v={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:l||r.some(S=>S.acceptedTruth?.truncated)}}:{},packets:d,truncated:l||e.length>0||r.some(S=>S.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;yi(v)>xd;){if(v.packets.length)v.packets.pop();else if(v.acceptedTruth?.decisions.length)v.acceptedTruth.decisions.pop();else break;v.truncated=!0,v.acceptedTruth&&(v.acceptedTruth.truncated=!0)}if(v.estimatedTokens=yi(v),!(!v.packets.length&&!v.acceptedTruth?.decisions.length))return v}function wi(o,e,t){return{...o,explanations:o.explanations.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),relations:o.relations?.map(n=>({...n,storeId:e.storeId,readOnly:t,from:n.from??{storeId:e.storeId,explanationId:n.fromId},to:n.to??{storeId:n.toStoreId??e.storeId,explanationId:n.toId}})),historicalCaveats:o.historicalCaveats?.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Te(o,e){return`${o}:${e}`}function Pd(o){let e=o.from??{storeId:o.storeId??"",explanationId:o.fromId},t=o.to??{storeId:o.storeId??"",explanationId:o.toId};return`${o.storeId??""}:${o.type}:${Te(e.storeId,e.explanationId)}:${Te(t.storeId,t.explanationId)}`}function Ad(o,e){let t=new Map;for(let{store:n,topology:r}of o)for(let i of r.explanations)t.set(Te(n.storeId,i.memoryId),i.explanationId);return o.flatMap(({store:n,topology:r})=>r.relations.flatMap(i=>{let s=i.from.storeId??n.storeId,a=i.to.storeId??n.storeId,d=t.get(Te(s,i.from.memoryId)),l=t.get(Te(a,i.to.memoryId));return!d||!l?[]:[{id:i.id,type:i.type,fromId:d,toId:l,rationale:i.rationale,storeId:n.storeId,readOnly:n.storeId!==e,from:{storeId:s,explanationId:d},to:{storeId:a,explanationId:l}}]}))}function jd(o){let e=new Set;return o.filter(t=>{let n=Pd(t);return e.has(n)?!1:(e.add(n),!0)})}function Md(o,e,t,n,r=[],i=[],s=[]){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let a=o.map(({store:p,context:j})=>wi(j,p,p.storeId!==t)),d=xn(a.map(p=>p.explanations)),l=jd([...a.flatMap(p=>p.relations??[]),...r]),v=new Map([...d,...i].map(p=>[Te(p.storeId??"",p.id),p])),S=[],y=new Set,k=p=>{if(!p||S.length>=sr)return;let j=Te(p.storeId??"",p.id);y.has(j)||(y.add(j),S.push(p))};for(let p of d.slice(0,sr)){let j=Te(p.storeId??"",p.id),h=l.flatMap(m=>m.from&&Te(m.from.storeId,m.from.explanationId)===j?[v.get(Te(m.to.storeId,m.to.explanationId))]:m.to&&Te(m.to.storeId,m.to.explanationId)===j?[v.get(Te(m.from.storeId,m.from.explanationId))]:[]).find(Boolean);h&&(k(p),k(h))}d.forEach(k),i.forEach(k);let T=S,g=l.filter(p=>{let j=p.from,h=p.to;return!!(j&&h&&y.has(Te(j.storeId,j.explanationId))&&y.has(Te(h.storeId,h.explanationId)))}),u=new Set([...d.map(p=>Te(p.storeId??"",p.id)),...i.map(p=>Te(p.storeId??"",p.id))]).size,I=[...new Set(a.flatMap(p=>p.pendingGroundingExplanationIds??[]))],f=[...new Set(a.flatMap(p=>p.correctionExplanationIds??[]))];return{explanations:T,relations:g,truncated:T.length<u||e.length>0||a.some(p=>p.truncated),...a.find(p=>p.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(p=>p.retrievalIntent).retrievalIntent}:{},historicalCaveats:xn(a.map(p=>p.historicalCaveats??[])).slice(0,3),...I.length?{pendingGroundingExplanationIds:I}:{},...f.length?{correctionExplanationIds:f}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var Yn=class{constructor(e,t,n=r=>({memory:new Yt(r.projectRoot),imprint:new It(r.projectRoot,r.projectId)})){this.primary=e;this.createReader=n;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 n=this.createReader(e);return this.readers.set(e.storeId,n),n}async memoryContext(e,t,n){let r=performance.now(),i=gi(this.normalized(e)),s=await Promise.allSettled(i.map(async l=>{let v,S=await zn(this.reader(l).memory,t,n,y=>{v=y});if(v)throw v;return{store:l,context:S}})),a=s.flatMap(l=>l.status==="fulfilled"&&l.value.context?[l.value]:[]),d=s.flatMap((l,v)=>l.status==="rejected"?[i[v].storeId]:[]);return this.record(i.length,d.length,r),Rd(a,d,this.primary.storeId,i.length>1)}async imprintContext(e,t){let n=performance.now(),r=gi(this.normalized(e)),i=r.length>1,s=r.map(async E=>({store:E,context:await this.reader(E).imprint.contextualize(E.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async E=>({store:E,topology:await(this.reader(E).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[d,l]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),v=d.flatMap(E=>E.status==="fulfilled"&&E.value.context?[E.value]:[]),S=d.flatMap((E,G)=>E.status==="rejected"?[r[G].storeId]:[]),y=l.flatMap(E=>E.status==="fulfilled"?[E.value]:[]),k=l.flatMap((E,G)=>E.status==="rejected"?[r[G].storeId]:[]),T=new Map(y.flatMap(({store:E,topology:G})=>G.explanations.map(W=>[Te(E.storeId,W.explanationId),W.memoryId]))),g=v.map(({store:E,context:G})=>({store:E,context:{...G,explanations:G.explanations.map(W=>({...W,memoryId:T.get(Te(E.storeId,W.id))}))}})),u=Ad(y,this.primary.storeId),I=g.map(({store:E,context:G})=>wi(G,E,E.storeId!==this.primary.storeId)),f=xn(I.map(E=>E.explanations)).slice(0,sr),p=new Set(f.map(E=>Te(E.storeId??"",E.id))),j=new Set(I.flatMap(E=>E.explanations.map(G=>Te(G.storeId??"",G.id)))),h=new Map,m=(E,G)=>{if(j.has(Te(E,G)))return;let W=h.get(E)??new Set;W.add(G),h.set(E,W)};for(let E of u){if(!E.from||!E.to)continue;let G=Te(E.from.storeId,E.from.explanationId),W=Te(E.to.storeId,E.to.explanationId);p.has(G)&&m(E.to.storeId,E.to.explanationId),p.has(W)&&m(E.from.storeId,E.from.explanationId)}let M=new Map(r.map(E=>[E.storeId,E])),D=[...h].map(async([E,G])=>{let W=M.get(E),ue=W?this.reader(W).imprint.explanationsByIds:void 0;if(!W||!ue)return{storeId:E,explanations:[]};let X=await ue.call(this.reader(W).imprint,[...G]);return{storeId:E,explanations:X.map(re=>({...re,memoryId:T.get(Te(E,re.id)),storeId:E,storeRoot:W.projectRoot,readOnly:E!==this.primary.storeId}))}}),P=await Promise.allSettled(D),A=P.flatMap(E=>E.status==="fulfilled"?E.value.explanations:[]),Q=P.flatMap((E,G)=>E.status==="rejected"?[[...h.keys()][G]]:[]),z=[...new Set([...k,...Q])];return this.record(r.length,new Set([...S,...z]).size,n),Md(g,S,this.primary.storeId,i,u,A,z)}record(e,t,n){this.state.reads+=1,this.state.storeReads+=e,this.state.failedStoreReads+=t,this.state.lastDurationMs=Math.max(0,performance.now()-n)}};function Zt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function Sn(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:n,outcomes:t}}var Mt=1,ar="bridge";function vi(o){return`codex-session:${o}`}function Od(o,e){return`codex-${Ed("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function bi(o){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:o,elements:[]}],styleModifications:[]}}function xi(o,e){let t=new Set,n=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(Cd(s)?$d(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)&&n(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,l]of Object.entries(i))r(l,d,a+1)}};for(let i of o)r(i.toolInput);return[...t]}function Zn(o){return o?Math.ceil(o.length/4):0}function Si(o,e,t,n,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 ${o}.`,"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=fn(n),d=Ti(r,i),l=[s,a,d].filter(Boolean).join(`
16
- `);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:Zn(s),memoryEstimatedTokens:Zn(a),imprintEstimatedTokens:Zn(d),totalEstimatedTokens:Zn(l)}}}function Ti(o,e){return o?Ft(o,{requestText:e}).split(`
6
+ `)}var va=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),ba=new Set(["default","flex","fast","priority"]);function qt(o){let e=typeof o.reasoningEffort=="string"&&va.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&ba.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Qn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{createHash as Jd,randomUUID as qd}from"crypto";import{isAbsolute as Ld,relative as Fd}from"path";import{randomUUID as dt}from"crypto";function Ho(o,e){return{storeId:o,explanationId:e}}function xa(o,e){let{fromId:t,toId:n,toStoreId:r,...i}=e;return{...i,from:Ho(o,t),to:Ho(r??o,n)}}var ti={project:0,route:1,component:2,selector:2,file:3},ni={intention:0,principle:1,pattern:2};function Lt(o,e){let t=ti[o.scope.kind]-ti[e.scope.kind];return t!==0?t:ni[o.kind]-ni[e.kind]}function oi(o){return o==="expresses"||o==="excepts"}function Sa(o,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=o.explanations.find(i=>i.id===e.fromId),n=o.explanations.find(i=>i.id===e.toId);if(!t||!n)return;let r=Lt(t,n);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function At(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let r=Sa(o,n);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 Ta}from"crypto";import{mkdir as ka,open as Ra,readFile as ri,readdir as Pa,rename as Aa,unlink as ja}from"fs/promises";import{dirname as Ma,join as Ft}from"path";function qe(o){return structuredClone(o)}function ii(o){return Ta("sha256").update(JSON.stringify(o)).digest("hex")}async function jt(o,e){await ka(Ma(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Ra(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
7
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await Aa(t,o)}catch(r){throw await ja(t).catch(()=>{}),r}}function Ea(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function _a(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=qe(e):o.explanations.push(qe(e))}function Xn(o,e){let t=qe(o);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(r=>r.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(qe(n.explanation))}else if(n.op==="replace_explanation")_a(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(r=>r.id!==n.explanationId),t.relations=t.relations.filter(r=>r.fromId!==n.explanationId&&(r.toStoreId!==void 0||r.toId!==n.explanationId));else if(n.op==="add_concrete")t.concrete.some(r=>r.id===n.concrete.id)||t.concrete.push(qe(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(r=>r.id!==n.concreteId),t.relations=t.relations.filter(r=>r.fromId!==n.concreteId&&(r.toStoreId!==void 0||r.toId!==n.concreteId));else if(n.op==="add_evidence"){let r=t.explanations.find(i=>i.id===n.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);r.evidence.some(i=>i.id===n.evidence.id)||(r.evidence.push(qe(n.evidence)),r.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let r=t.explanations.find(i=>i.id===n.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(r,qe(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let r=n.relation,i=t.explanations.find(w=>w.id===r.fromId),s=!!r.toStoreId,a=s?void 0:t.explanations.find(w=>w.id===r.toId),d=t.concrete.some(w=>w.id===r.fromId),l=!s&&t.concrete.some(w=>w.id===r.toId);if(oi(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(b=>b.type===r.type&&b.fromId===r.fromId&&b.toStoreId===r.toStoreId&&b.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`);if(r.type==="expresses"&&i&&a){if(Lt(i,a)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let b=new Map;for(let x of t.relations)x.type!=="expresses"||x.toStoreId||b.set(x.fromId,[...b.get(x.fromId)??[],x.toId]);let g=[r.toId],k=new Set;for(;g.length;){let x=g.pop();if(x===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);k.has(x)||(k.add(x),g.push(...b.get(x)??[]))}}}else if(!i||!a&&!l)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);t.relations.some(w=>w.id===r.id)||t.relations.push(qe(r))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==n.relationId));return t}function Ca(o,e){let t=[],n=qe(o);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=n.explanations.find(s=>s.id===r.explanationId);i&&t.unshift({op:"add_explanation",explanation:qe(i)})}else if(r.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=n.concrete.find(s=>s.id===r.concreteId);i&&t.unshift({op:"add_concrete",concrete:qe(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=n.explanations.find(a=>a.id===i);s&&t.unshift({op:"replace_explanation",explanation:qe(s)})}else if(r.op==="add_relation")t.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=n.relations.find(s=>s.id===r.relationId);i&&t.unshift({op:"add_relation",relation:qe(i)})}n=Xn(n,[r])}return t}function si(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,...o.relation.toStoreId?[]:[o.relation.toId]]:[]}var Ut=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Ft(e,".popmelt","imprint"),this.manifestPath=Ft(this.imprintDir,"manifest.json"),this.graphPath=Ft(this.imprintDir,"graph.json"),this.journalDir=Ft(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await ri(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(),n=(await Pa(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=Ea(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<n.length;a++){let d=JSON.parse(await ri(Ft(this.journalDir,n[a]),"utf8")),{hash:l,...w}=d;if(d.sequence!==a+1||d.previousHash!==s||l!==ii(w))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Xn(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:At(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=At(t.graph),r=new Map(n.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 jt(this.graphPath,n),await jt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(b=>b.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=n.graph.head.sequence+1,i=Ca(n.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:qe(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:ii(s)},d=Xn(n.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await jt(Ft(this.journalDir,l),a);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await jt(this.graphPath,d),await jt(this.manifestPath,w),t={graph:d,transaction:a}}),await this.writeChain,t}async undo(e,t,n,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(si));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>si(w).some(b=>a.has(b)))))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:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await jt(this.graphPath,e.graph),await jt(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 $a=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Oa=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"]),Da=[/\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],Na=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Xo(o){return!!(o&&Na.test(o))}function Ba(o){return o.scope.kind==="project"||Xo(`${o.statement} ${o.rationale}`)}function Ja(o){let e=o?.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 qa(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function La(o){return o.length>4&&o.endsWith("ies")?[o,`${o.slice(0,-3)}y`]:o.length>3&&o.endsWith("s")&&!o.endsWith("ss")?[o,o.slice(0,-1)]:[o]}function at(o){return new Set(qa(o).split(" ").filter(e=>e.length>2&&!Oa.has(e)).flatMap(La))}function ai(o){return o.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function Fa(o){if(o)for(let e of Da){let t=e.exec(o);if(!t||t.index<=0)continue;let n=ai(o.slice(0,t.index)),r=ai(o.slice(t.index+t[0].length));if(n&&r)return{target:n,reference:r}}}function yt(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Qo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function It(o,e,t){return{id:dt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ve(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function di(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function ci(o,e,t){if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o,s=ve(i.explanationId,100),a=ve(i.clientId,100),d=ve(i.storeId,100);if(s&&a)throw new Error("relation endpoint must use either explanationId or clientId, not both");let l=s||a;return l?{explanationId:l,...d?{storeId:d}:{}}:void 0}let n=ve(e,100),r=ve(t,100);return n?{explanationId:n,...r?{storeId:r}:{}}:void 0}function li(o,e){if(!o||!e.trim())return{found:!1};let t=o;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let r=Number(n);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,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function zt(o,e={}){let t=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.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=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(d);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let w=l;i=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:n,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(!$a.has(h))throw new Error("imprint no-op reason is invalid");if(h==="task_specific_detail"&&s.some(j=>{if(!j||typeof j!="object"||Array.isArray(j))return!1;let $=j;return($.finalScope??$.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let u=Array.isArray(a.usedExplanationIds)?a.usedExplanationIds.filter(j=>typeof j=="string"&&!!j.trim()):[],y=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(j=>typeof j=="string"&&!!j.trim()):[],I=new Set(e.context?.explanations.map(j=>j.id)??[]);if([...new Set([...u,...y])].some(j=>!I.has(j)))throw new Error("imprint use must cite only surfaced explanations");let A=[...new Set([...u,...e.applicationOccurred?[]:y])],m=e.applicationOccurred?y:[],f;if(m.length){f=m;let j=new Set(e.context?.pendingGroundingExplanationIds??[]),$=m.filter(R=>{let _=e.context?.explanations.find(X=>X.id===R);return I.has(R)&&_&&(_.state==="emerging"||_.state==="testing")&&!j.has(R)});if($.length){let R=a.grounding,_=typeof R?.explanationId=="string"&&$.includes(R.explanationId)?R.explanationId:$[0],X=ve(R?.question,300);return{draft:{decision:"apply",summary:{title:ve(a.summary?.title,120)||"Applied shared understanding",detail:ve(a.summary?.detail,500)||ve(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:m,grounding:{explanationId:_,question:X||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(h==="duplicate"){let j=ve(a.duplicateOfExplanationId,100),$=a.scopeComparison;if(!j)throw new Error("duplicate assessment requires duplicateOfExplanationId");if($!=="equivalent"&&$!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let R=e.context?.explanations.find(_=>_.id===j);if(!R)throw new Error("duplicate assessment must cite a surfaced explanation");if(Xo(e.requestText)&&!Ba(R))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:h,duplicateOfExplanationId:j,scopeComparison:$,...A.length?{usedExplanationIds:A}:{},...f?{appliedExplanationIds:f}:{}},visibleText:n}}return{draft:{decision:"none",reason:h,...A.length?{usedExplanationIds:A}:{},...f?{appliedExplanationIds:f}:{}},visibleText:n}}if(a.decision==="recognize"){let h=ve(a.explanationId,100);if(!h)throw new Error("recognition requires explanationId");let u=e.context?.explanations.find(p=>p.id===h);if(!u)throw new Error("recognition must cite a surfaced explanation");if(u.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let y=a.summary,I={title:ve(y?.title,120),detail:ve(y?.detail,500)};if(!I.title||!I.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:h,summary:I},visibleText:n}}if(a.decision==="apply"){let h=a.summary,u={title:ve(h?.title,120),detail:ve(h?.detail,500)};if(!u.title||!u.detail)throw new Error("application summary title and detail are required");let y=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(j=>typeof j=="string"&&!!j.trim()):[];if(!y.length)throw new Error("application requires appliedExplanationIds");let I=new Map(e.context?.explanations.map(j=>[j.id,j])??[]);if(y.some(j=>!I.has(j)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(y)]},visibleText:n};let p=new Set(e.context?.pendingGroundingExplanationIds??[]),A=y.filter(j=>{let $=I.get(j);return $&&($.state==="emerging"||$.state==="testing")&&!p.has(j)});if(!A.length){if(y.every($=>I.get($)?.state==="grounded"||p.has($)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:y},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let m=a.grounding,f=typeof m?.explanationId=="string"&&A.includes(m.explanationId)?m.explanationId:A[0];return{draft:{decision:"apply",summary:u,appliedExplanationIds:y,grounding:{explanationId:f,question:ve(m?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,l=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let w={kind:l,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let b=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 u=h;if(u.op==="add"&&["intention","principle","pattern"].includes(String(u.kind))){let y=ve(u.statement),I=ve(u.rationale);if(!y||!I)continue;g.push({op:"add",clientId:ve(u.clientId,100)||void 0,kind:u.kind,statement:y,rationale:I,scope:di(u.scope),rootReason:ve(u.rootReason,300)||void 0})}else if(u.op==="revise"&&typeof u.explanationId=="string"){let y={op:"revise",explanationId:u.explanationId,statement:ve(u.statement)||void 0,rationale:ve(u.rationale)||void 0,scope:di(u.scope),reopenGrounding:u.reopenGrounding===!0};(y.statement||y.rationale||y.scope||y.reopenGrounding)&&g.push(y)}else if(u.op==="evidence"&&typeof u.explanationId=="string"&&["supports","challenges","excepts"].includes(String(u.stance))){let y=ve(u.summary);y&&g.push({op:"evidence",explanationId:u.explanationId,stance:u.stance,summary:y})}else if(u.op==="relation"){if(!["expresses","excepts"].includes(String(u.type)))throw new Error("relation type is invalid");let y=ve(u.rationale),I=ci(u.from,u.fromId,u.fromStoreId),p=ci(u.to,u.toId,u.toStoreId);if(!y)throw new Error("relation rationale is required");if(!I||!p)throw new Error("relation endpoints require an explanationId or clientId");g.push({op:"relation",type:u.type,from:I,to:p,rationale:y})}else if(u.op==="supersede"&&typeof u.explanationId=="string"&&typeof u.replacementId=="string"){let y=ve(u.reason);y&&g.push({op:"supersede",explanationId:u.explanationId,replacementId:u.replacementId,reason:y})}else if(u.op==="bind_concrete"&&typeof u.explanationId=="string"){let y=ve(u.modelPath,300);y&&g.push({op:"bind_concrete",explanationId:u.explanationId,modelPath:y,rationale:ve(u.rationale)})}else u.op==="retire"&&typeof u.explanationId=="string"&&g.push({op:"retire",explanationId:u.explanationId,reason:ve(u.reason)})}let k=a.grounding,x=k&&typeof k.explanationId=="string"&&ve(k.question)?{explanationId:k.explanationId,question:ve(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:b,mutations:g,grounding:x},visibleText:n}}catch(a){return{visibleText:n,error:a instanceof Error?a.message:String(a)}}}function Gt(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),r=new Set(o?.correctionExplanationIds??[]),i=Xo(e.requestText),s=o?.retrievalIntent,a=o?.historicalCaveats??[],d=t.find(g=>g.storeId&&!g.readOnly)?.storeId,l=(g,k)=>{let x=g[k];return x?`[${x.storeId}] ${x.explanationId}`:k==="from"?g.fromId:g.toId},w=!!o?.relations?.some(g=>g.from&&g.to&&g.from.storeId!==g.to.storeId),b=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)"}`]:[],...n.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(x=>` - Concrete terminal: ${x.modelPath} = ${JSON.stringify(x.value)}`)].join(`
8
+ `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(g=>`- ${g.storeId?`[owned by ${g.storeId}${g.readOnly?"; read-only":""}] `:""}${l(g,"from")} --${g.type}--> ${l(g,"to")}: ${g.rationale}`)]:[],...b||w?["","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(`
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."]:[],...o?.unavailableStoreIds?.length?["",`Some mounted Imprint knowledge was unavailable during this bounded read: ${o.unavailableStoreIds.join(", ")}. Do not infer its contents.`]:[],...o?.unavailableTopologyStoreIds?.length?["",`Some mounted Imprint topology was unavailable during this bounded read: ${o.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 wt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Ut(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??""}`,n=this.contextualGraphCache?.headKey===t?this.contextualGraphCache.graph:void 0;return n||(n=(await this.store.load()).graph,this.contextualGraphCache={headKey:t,graph:n}),n}async explanationsByIds(e){if(!e.length)return[];let t=await this.contextualGraph(),n=new Map(t.explanations.map(r=>[r.id,r]));return[...new Set(e)].flatMap(r=>{let i=n.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=at(e.text??""),n=at((e.subjectHints??[]).join(" ")),r=Fa(e.text),i=at(r?.target??""),s=at(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!a.size&&!d.size)return;let l=await this.contextualGraph(),w=l.explanations.filter(m=>m.state!=="retired"&&(m.state!=="challenged"||d.has(m.id))).map(m=>{let f=at([m.statement,m.rationale].join(" ")),j=at(m.scope.values.join(" ")),$=yt(f,t),R=yt(j,t),_=yt(j,n),X=yt(f,n),G=$+R*.2+_*.25+X*.75+(m.state==="grounded"?.08:0)+(a.has(m.id)?1:0)+(d.has(m.id)?1:0),M=a.has(m.id)||d.has(m.id)||$>=.12||R>=.5||_>=.2||X>=.2;return{item:m,score:G,relevant:M}}).filter(m=>m.relevant&&m.score>=.18).sort((m,f)=>f.score-m.score||f.item.updatedAt.localeCompare(m.item.updatedAt)),b=Math.max(1,e.maxExplanations??6),g=m=>l.explanations.filter(f=>f.state!=="retired"&&f.state!=="challenged").map(f=>{let j=yt(at(`${f.statement} ${f.rationale}`),m),$=yt(at(f.scope.values.join(" ")),m);return{item:f,score:j+$*.35+(f.state==="grounded"?.08:0)}}).filter(f=>f.score>=.18).sort((f,j)=>j.score-f.score||j.item.updatedAt.localeCompare(f.item.updatedAt)),k=[],x=m=>{k.length<b&&!k.some(f=>f.id===m.id)&&k.push(m)};if(r&&(g(i).slice(0,2).forEach(({item:m})=>x(m)),g(s).slice(0,2).forEach(({item:m})=>x(m))),w.forEach(({item:m})=>x(m)),!k.length)return;let h=new Set(k.map(m=>m.id)),u=new Set(l.relations.flatMap(m=>m.toStoreId?[]:h.has(m.fromId)?[m.toId]:h.has(m.toId)?[m.fromId]:[])),y=new Set(l.explanations.flatMap(m=>u.has(m.id)&&m.state!=="retired"&&m.state!=="challenged"?[m.id]:[])),I=l.explanations.filter(m=>y.has(m.id)&&!h.has(m.id)).sort((m,f)=>f.updatedAt.localeCompare(m.updatedAt)).slice(0,4),p=[...k,...I];for(let m of I)h.add(m.id);let A=r?l.explanations.filter(m=>m.state==="challenged").map(m=>{let f=at(`${m.statement} ${m.rationale} ${m.scope.values.join(" ")}`),j=yt(f,i),$=yt(f,s);return{item:m,score:j+$,targetScore:j,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:p.map(m=>{let f=new Set(l.relations.filter(j=>!j.toStoreId&&j.toId===m.id&&j.type==="expresses").map(j=>j.fromId));return{id:m.id,kind:m.kind,statement:m.statement,rationale:m.rationale,scope:m.scope,state:m.state,concrete:l.concrete.filter(j=>f.has(j.id)).map(j=>({id:j.id,modelPath:j.modelPath,value:j.value}))}}),truncated:w.length>k.length||I.length<y.size,...r?{retrievalIntent:r}:{},...A.length?{historicalCaveats:A}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},relations:l.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 n=e.decision==="mutate"?e.mutations:[],r=t.applicationOccurred?n.flatMap(v=>v.op==="add"&&v.clientId?[v.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(n.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(v=>[v.id,v])),l=new Map,w=new Map,b=[],g=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),x=new Set(n.flatMap(v=>v.op==="revise"&&n.some(E=>E.op==="evidence"&&E.stance==="challenges"&&E.explanationId===v.explanationId)?[v.explanationId]:[])),h=new Set(n.flatMap(v=>v.op==="add"&&v.clientId?[v.clientId]:[])),u=t.storeId?.trim(),y=v=>d.has(v)||h.has(v),I=new Map((t.context?.explanations??[]).flatMap(v=>v.storeId?[[`${v.storeId}:${v.id}`,v]]:[])),p=v=>v.storeId??u,A=v=>{let E=p(v.from),J=p(v.to);return u&&E!==u||!u&&(v.from.storeId||v.to.storeId)||!y(v.from.explanationId)?!1:!J||J===u?y(v.to.explanationId):!!I.get(`${J}:${v.to.explanationId}`)?.memoryId},m=new Set;for(let v of n)v.op==="relation"&&(p(v.from)!==p(v.to)||v.from.explanationId!==v.to.explanationId)&&A(v)?(m.add(v.from.explanationId),p(v.to)===u&&m.add(v.to.explanationId)):v.op==="supersede"&&v.explanationId!==v.replacementId&&y(v.explanationId)&&y(v.replacementId)?(m.add(v.explanationId),m.add(v.replacementId)):v.op==="bind_concrete"&&y(v.explanationId)&&li(t.concreteModel,v.modelPath).found&&m.add(v.explanationId);let f=a.graph.explanations.length===0;for(let v of n){if(v.op!=="add")continue;let E=!!(v.clientId&&m.has(v.clientId)),J=!!v.rootReason?.trim()||f;if(!E&&!J)continue;f&&(f=!1);let q=dt();v.clientId&&l.set(v.clientId,q);let H=v.clientId?i.includes(v.clientId):!1,ge={id:q,kind:v.kind,statement:v.statement,rationale:v.rationale,scope:Qo(v.scope),state:H?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[It(t,"supports",e.summary.detail)]};d.set(q,ge),g.add(q),b.push({op:"add_explanation",explanation:ge})}let j=v=>l.get(v)??v;for(let v of n){if(v.op!=="revise")continue;let E=j(v.explanationId),J=d.get(E);if(J?.state!=="grounded")continue;let q=dt(),H={id:q,kind:J.kind,statement:v.statement??J.statement,rationale:v.rationale??J.rationale,scope:v.scope?Qo(v.scope):J.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[It(t,"supports",e.summary.detail)]};d.set(q,H),w.set(E,q),g.add(q),b.push({op:"add_explanation",explanation:H});let ge=Lt(J,H);ge!==0&&b.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:ge>0?E:q,toId:ge>0?q:E,rationale:v.rationale??e.summary.detail,createdAt:s}})}let $=v=>{let E=j(v);return w.get(E)??E};for(let v of n){if(v.op==="add")continue;if(v.op==="bind_concrete"){let J=$(v.explanationId);if(!d.has(J))continue;let q=li(t.concreteModel,v.modelPath);if(!q.found)continue;let H=a.graph.concrete.find(ge=>ge.modelPath===v.modelPath&&JSON.stringify(ge.value)===JSON.stringify(q.value));H||(H={id:dt(),modelPath:v.modelPath,value:structuredClone(q.value),createdAt:s,updatedAt:s},b.push({op:"add_concrete",concrete:H})),b.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:H.id,toId:J,rationale:v.rationale,createdAt:s}}),g.add(J);continue}if(v.op==="relation"){if(!A(v))continue;let J=p(v.from),q=p(v.to);if(u&&J!==u)continue;let H=$(v.from.explanationId),ge=q===u?$(v.to.explanationId):v.to.explanationId,_e=d.get(H),ue=q===u?d.get(ge):I.get(`${q}:${ge}`);if(!_e||!ue||q===u&&H===ge)continue;if(v.type==="expresses"&&Lt(_e,ue)<0){if(q!==u)continue;[H,ge]=[ge,H]}b.push({op:"add_relation",relation:{id:dt(),type:v.type,fromId:H,...q&&q!==u?{toStoreId:q}:{},toId:ge,rationale:v.rationale,createdAt:s}}),g.add(H),q===u&&g.add(ge);continue}if(v.op==="supersede"){let J=$(v.explanationId),q=$(v.replacementId);if(!d.has(J)||!d.has(q)||J===q)continue;b.push({op:"add_evidence",explanationId:J,evidence:It(t,"challenges",v.reason)}),b.push({op:"revise_explanation",explanationId:J,patch:{state:"challenged",supersededBy:q},updatedAt:s}),g.add(J),g.add(q);continue}let E=$(v.explanationId);if(d.has(E))if(g.add(E),v.op==="revise"){if(w.has(j(v.explanationId)))continue;let J=d.get(E);if(!J||J.state!=="emerging"&&J.state!=="testing")continue;let q={...v.statement?{statement:v.statement}:{},...v.rationale?{rationale:v.rationale}:{},...v.scope?{scope:Qo(v.scope)}:{},...v.reopenGrounding||x.has(v.explanationId)?{state:"testing"}:{}};b.push({op:"revise_explanation",explanationId:E,patch:q,updatedAt:s})}else if(v.op==="evidence"){if(v.stance==="challenges"&&x.has(v.explanationId))continue;b.push({op:"add_evidence",explanationId:E,evidence:It(t,v.stance,v.summary)}),v.stance==="challenges"&&b.push({op:"revise_explanation",explanationId:E,patch:{state:"challenged"},updatedAt:s})}else v.op==="retire"&&(b.push({op:"add_evidence",explanationId:E,evidence:It(t,"challenges",v.reason||"Retired after contradictory collaboration evidence.")}),b.push({op:"revise_explanation",explanationId:E,patch:{state:"retired"},updatedAt:s}))}for(let v of i){let E=$(v),J=d.get(E);!J||J.state==="grounded"||J.state==="retired"||k.has(E)&&!g.has(E)||(g.has(E)||(g.add(E),b.push({op:"add_evidence",explanationId:E,evidence:{...It(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),J.state==="emerging"&&b.push({op:"revise_explanation",explanationId:E,patch:{state:"testing"},updatedAt:s}))}let R=new Set(a.graph.relations.map(v=>`${v.type}:${v.fromId}:${v.toStoreId??""}:${v.toId}`)),_=b.filter(v=>{if(v.op!=="add_relation")return!0;let E=`${v.relation.type}:${v.relation.fromId}:${v.relation.toStoreId??""}:${v.relation.toId}`;return R.has(E)?!1:(R.add(E),!0)});if(!_.length)return;let X=dt(),G=await this.store.commit({transactionId:X,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:_}),M=new Map(G.graph.explanations.map(v=>[v.id,v])),L=[...g].flatMap(v=>{let E=M.get(v);if(!E)return[];let J=!a.graph.explanations.some(H=>H.id===v),q=E.state==="challenged"||E.state==="retired";return[{explanationId:v,action:J?"added":q?"challenged":"revised",statement:E.statement,state:E.state}]}),W=i.map($).find(v=>M.get(v)?.state==="testing"&&!k.has(v)),ie=e.grounding?$(e.grounding.explanationId):W,Q=ie?M.get(ie):void 0,ee=Q?.state==="testing"&&!k.has(Q.id)?{explanationId:Q.id,question:e.grounding?.question||Ja(Q),state:"testing"}:void 0;return{transactionId:X,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:L,...ee?{grounding:ee}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===n);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:n,evidence:{...It(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:n,evidence:{...It(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:n,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:dt(),committedAt:t,source:s,summary:d,mutations:a}),"applied"}};function Wt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
11
+ `)}async function Yn(o,e,t,n){let r=Wt(e);if(!(!r&&t.length===0))try{let i=await o.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(l=>l.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){n?.(i);return}}function yn(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((n,r)=>["",`${r+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,...n.storeId?[` - Store: ${n.storeId}${n.readOnly?" (read-only)":" (writable primary)"}`]:[],` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((n,r)=>["",`${r+1}. ${n.claim}`,...n.storeId?[` - Store: ${n.storeId}${n.readOnly?" (read-only)":" (writable primary)"}`]:[]," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.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.",...o.packets.some(n=>n.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."]:[],"",o.packets.some(n=>n.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."]:[],...o.unavailableStoreIds?.length?["",`Some mounted knowledge was unavailable during this bounded read: ${o.unavailableStoreIds.join(", ")}. Continue with the available context and expand intentionally if the missing store is material.`]:[]].join(`
12
+ `)}import{mkdir as Ti,readFile as xn,writeFile as ki}from"fs/promises";import{join as Qt}from"path";var Ua=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Yo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Zn(o){return new Set(Yo(o).split(" ").filter(e=>e.length>2&&!Ua.has(e)))}function pi(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function za(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Yo).filter(Boolean),r=Zn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){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(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let w=Yo(l.value);for(let k of n){let x=w===k?95:w.includes(k)||k.includes(w)?75:0;x>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:l.by,score:x})}let g=["/","#","[","]","="].some(k=>l.value.includes(k))?0:Math.round(pi(Zn(w),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 Ga(o){return Math.ceil(JSON.stringify(o).length/4)}function Kt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Wa(o,e){let t=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!t.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let n=t.filter(i=>i.state==="completed"),r=n.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":n.length?"partial":"unknown",attemptIds:t.map(i=>i.id)}}function Ka(o,e,t){let n=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=t.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===o),i=n[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:n.map(a=>a.id)}}function ui(o,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),r=o.records.filter(f=>f.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(f=>f.recordType==="decision"&&f.state==="active"),a=i?s.filter(f=>i.has(f.id)):s,d=o.records.filter(f=>f.recordType==="implementation_attempt"),l=o.records.filter(f=>f.recordType==="verification_attempt"),w=o.records.filter(f=>f.recordType==="freshness_signal"&&f.state==="open"),b=o.records.filter(f=>f.recordType==="evidence"),g=o.records.filter(f=>f.recordType==="model_entry"),k=za(r,e),x=new Map(k.map(f=>[f.subjectId,f.score])),h=Zn([e.action,e.text].filter(Boolean).join(" ")),u=a.flatMap(f=>{let j=Math.max(0,...f.subjects.map(_=>x.get(_.subjectId)??0)),$=Math.round(pi(Zn(f.claim),h)*35),R=j+$;return R>=50?[{decision:f,score:R}]:[]}).sort((f,j)=>j.score-f.score||f.decision.id.localeCompare(j.decision.id)),y=new Map;for(let f of u.slice(0,n))y.set(f.decision.id,f.decision);for(let f of o.relationships){if(!Kt(f,"excepts")&&!Kt(f,"contradicts"))continue;let j=s.find(R=>R.id===f.from.entityId),$=s.find(R=>R.id===f.to.entityId);!j||!$||!y.has(j.id)&&!y.has($.id)||(y.size<n&&y.set(j.id,j),y.size<n&&y.set($.id,$))}let I=[...y.values()],p=f=>f.from.entityType==="decision"&&f.to.entityType==="decision"&&y.has(f.from.entityId)&&y.has(f.to.entityId),A=(f,j=!1)=>{let $=new Set(f.map(E=>E.id)),R=w.filter(E=>E.target.entityType==="decision"&&$.has(E.target.entityId)),_=new Set(o.relationships.filter(E=>Kt(E,"excepts")&&$.has(E.from.entityId)&&$.has(E.to.entityId)).flatMap(E=>[E.from.entityId,E.to.entityId])),G=o.relationships.filter(E=>Kt(E,"contradicts")&&$.has(E.from.entityId)&&$.has(E.to.entityId)).map(E=>({id:E.id,decisionIds:[E.from.entityId,E.to.entityId],unresolvedQuestion:E.reason,expansionRefs:[{kind:"record",id:E.id}]})),M=new Set(G.flatMap(E=>E.decisionIds)),L=b.filter(E=>E.sourceRefs.some(J=>J.kind==="record"&&$.has(J.id))||o.relationships.some(J=>J.relationshipType==="supports"&&J.from.entityType==="evidence"&&J.from.entityId===E.id&&J.to.entityType==="decision"&&$.has(J.to.entityId))),W=Math.max(0,u.length-f.length),ie=o.relationships.some(E=>Kt(E,"contradicts")&&p(E)&&(!$.has(E.from.entityId)||!$.has(E.to.entityId))),Q=j||W>0||ie,ee=[];k.length===0&&(e.subjectHints?.length??0)>0?ee.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):f.length===0&&ee.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),G.length&&ee.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:G.flatMap(E=>E.expansionRefs)}),L.some(E=>E.availability!=="available")&&ee.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:L.map(E=>({kind:"record",id:E.id}))}),Q&&ee.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let v={contractVersion:1,projectId:o.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:E,...J})=>J),modelEntries:g.filter(E=>E.decisionIds.some(J=>$.has(J))).map(E=>({id:E.id,key:E.key,value:E.value,decisionIds:E.decisionIds})),decisions:f.map(E=>({id:E.id,kind:E.kind,claim:E.claim,subjectIds:E.subjects.map(J=>J.subjectId),authority:E.authority,effectiveState:M.has(E.id)?"conflicted":_.has(E.id)?"excepted":"active",freshness:R.filter(J=>J.target.entityId===E.id).map(J=>J.signalType),expansionRef:{kind:"record",id:E.id}})),conflicts:G,uncertainties:ee,implementation:f.map(E=>Wa(E.id,d)),verification:f.map(E=>Ka(E.id,l,R)),evidence:L.map(E=>({evidenceId:E.id,summary:E.summary,availability:E.availability,sourceRefs:E.sourceRefs})),completeness:{status:Q?"truncated":"complete",omittedDecisionCount:W,omittedEvidenceCount:0,conflictsComplete:!ie}};return v.budget.estimatedTokens=Ga(v),v},m=A(I);for(;m.budget.estimatedTokens>t&&I.length>0;){let f=I.pop(),j=o.relationships.filter($=>Kt($,"contradicts")&&($.from.entityId===f.id||$.to.entityId===f.id)).flatMap($=>[$.from.entityId,$.to.entityId]);I=I.filter($=>!j.includes($.id)),m=A(I,!0)}return m}var Va=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Zo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function eo(o){return new Set(Zo(o).split(" ").filter(e=>e.length>2&&!Va.has(e)))}function mi(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Ha(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function Qa(o,e){let t=new Map,n=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Zo).filter(Boolean),i=eo([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(n.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 Ha(s)){let l=Zo(d.value);for(let g of r){let k=l===g?95:l.includes(g)||g.includes(l)?75:0;k>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:d.by,score:k})}let b=["/","#","[","]","="].some(g=>d.value.includes(g))?0:Math.round(mi(eo(l),i)*55);b>=30&&b>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"query_text",score:b})}a&&t.set(s.id,a)}return t}function Xa(o,e){let t=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(o.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"&&n.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 Ya(o){return Math.ceil(JSON.stringify(o).length/4)}function er(o,e){let t=o.records.filter(u=>u.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(u=>{if(u.recordType!=="proposal"||r&&!r.has(u.id))return!1;if(u.state==="pending")return!0;if(u.state!=="deferred")return!1;let y=[...o.events].reverse().find(I=>I.entity.entityType==="proposal"&&I.entity.entityId===u.id&&I.toState==="deferred"&&I.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(n)>=Date.parse(y.revisitAfter)):!1}),s=o.records.filter(u=>u.recordType==="implementation_attempt"),a=Qa(t,e),d=[...a.values()].sort((u,y)=>y.score-u.score),l=eo([e.action,e.text].filter(Boolean).join(" ")),w=i.flatMap(u=>{let y=u.subjects.map(m=>a.get(m.subjectId)).filter(m=>!!m),I=Math.max(0,...y.map(m=>m.score)),p=Math.round(mi(eo(u.claim),l)*35),A=I+p;return A>=50?[{proposal:u,proposalMatches:y,score:A}]:[]}).sort((u,y)=>y.score-u.score||u.proposal.id.localeCompare(y.proposal.id)),b=Math.max(1,e.maxPackets??3),g=Math.max(200,e.maxEstimatedTokens??1200),k=[],x=0;for(let u of w){if(k.length>=b)break;let y=u.proposal.sourceRefs.slice(0,4),I={contractVersion:1,packetId:`review:${u.proposal.id}`,projectId:o.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:u.proposalMatches.length?`Historical proposal intersects ${u.proposalMatches.map(A=>A.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:u.proposalMatches.map(({score:A,...m})=>m)},proposal:{id:u.proposal.id,claim:u.proposal.claim,state:u.proposal.state,proposedKind:u.proposal.proposedKind,subjectIds:u.proposal.subjects.map(A=>A.subjectId),origin:u.proposal.origin.mode},authority:"unaccepted",presentation:u.score>=100&&["constraint","rule"].includes(u.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Xa(u.proposal,s),evidence:{sourceCount:u.proposal.sourceRefs.length,sourceRefs:y},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:u.proposal.id},...y]},p={...I,estimatedTokens:Ya(I)};if(x+p.estimatedTokens>g)break;k.push(p),x+=p.estimatedTokens}let h=Math.max(0,w.length-k.length);return{packets:k,subjectMatches:d.map(({score:u,...y})=>y),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:h,maxEstimatedTokens:g,estimatedTokens:x},uncertainty:a.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var Za=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Vt(o){return Za.test(o)}function ed(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function oe(o,e,t,n){o.push({path:e,code:t,message:n,severity:"error"})}function tr(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Ee(o,e,t){Vt(t)||oe(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function He(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&oe(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Mt(o,e,t,n=!1){n&&t.level==="contributor"&&oe(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&oe(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var td={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"])},nd=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function od(o,e,t){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),Ee(o,`${t}.entity.entityId`,e.entity.entityId),He(o,`${t}.createdAt`,e.createdAt),Mt(o,`${t}.authority`,e.authority);let n=td[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(r)&&oe(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(nd.has(i)&&(Mt(o,`${t}.authority`,e.authority,!0),e.reason?.trim()||oe(o,`${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)&&oe(o,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&oe(o,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&He(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function rd(o,e,t,n){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),He(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&oe(o,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&oe(o,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&oe(o,`${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)&&oe(o,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Mt(o,`${t}.authority`,e.authority,!0),e.claim.trim()||oe(o,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&tr(o,`${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())&&oe(o,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),He(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&oe(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&oe(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&oe(o,`${t}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),He(o,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),He(o,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&oe(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(He(o,`${t}.appliedAt`,e.appliedAt),Mt(o,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&oe(o,`${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())&&oe(o,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&oe(o,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&tr(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&tr(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function id(o,e,t){if(Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),Ee(o,`${t}.from.entityId`,e.from.entityId),Ee(o,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&oe(o,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&oe(o,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),He(o,`${t}.createdAt`,e.createdAt),e.reason.trim()||oe(o,`${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&&oe(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?oe(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Mt(o,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&oe(o,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&oe(o,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))&&oe(o,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&oe(o,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Et(o){let e=[];Ee(e,"manifest.projectId",o.manifest.projectId),He(e,"manifest.createdAt",o.manifest.createdAt),He(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(h,u)=>{let y=t.get(h);y?oe(e,u,"duplicate_id",`ID is already used at ${y}.`):t.set(h,u)};o.records.forEach((h,u)=>{let y=`records[${u}]`;n(h.id,y),rd(e,h,y,o.manifest.projectId)}),o.events.forEach((h,u)=>{let y=`events[${u}]`;n(h.id,y),od(e,h,y),h.projectId!==o.manifest.projectId&&oe(e,`${y}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((h,u)=>{let y=`relationships[${u}]`;n(h.id,y),id(e,h,y),h.projectId!==o.manifest.projectId&&oe(e,`${y}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((h,u)=>{n(h.id,`artifacts[${u}]`),Ee(e,`artifacts[${u}].id`,h.id)}),o.tombstones.forEach((h,u)=>{let y=`tombstones[${u}]`;n(h.id,y),Ee(e,`${y}.id`,h.id),Ee(e,`${y}.objectId`,h.objectId),Ee(e,`${y}.deletedById`,h.deletedById),He(e,`${y}.deletedAt`,h.deletedAt),Mt(e,`${y}.authority`,h.authority,!0)});let r=new Set(o.records.map(h=>`${h.recordType}:${h.id}`)),i=new Set(o.tombstones.map(h=>`${h.objectType}:${h.objectId}`)),s=(h,u)=>{if(h.storeId)return;let y=`${h.entityType}:${h.entityId}`;!r.has(y)&&!i.has(y)&&oe(e,u,"dangling_entity_reference",`No record or tombstone exists for ${y}.`)};o.events.forEach((h,u)=>s(h.entity,`events[${u}].entity`)),o.relationships.forEach((h,u)=>{s(h.from,`relationships[${u}].from`),s(h.to,`relationships[${u}].to`)});let a=new Set(o.artifacts.map(h=>h.id)),d=(h,u)=>{a.has(h)||oe(e,u,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(h,u,y)=>{!r.has(`${h}:${u}`)&&!i.has(`${h}:${u}`)&&oe(e,y,"dangling_entity_reference",`No ${h} record or tombstone exists.`)};o.records.forEach((h,u)=>{let y=`records[${u}]`;switch(h.recordType){case"authority_grant":l("participant",h.granteeId,`${y}.granteeId`),l("participant",h.grantedById,`${y}.grantedById`),h.subjectIds.forEach((I,p)=>l("subject",I,`${y}.subjectIds[${p}]`));break;case"observation":h.captureContext.subjectIds.forEach((I,p)=>l("subject",I,`${y}.captureContext.subjectIds[${p}]`)),h.captureContext.artifactIds.forEach((I,p)=>d(I,`${y}.captureContext.artifactIds[${p}]`));break;case"proposal":case"decision":h.subjects.forEach((I,p)=>l("subject",I.subjectId,`${y}.subjects[${p}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((I,p)=>d(I,`${y}.messageArtifactIds[${p}]`)),h.resultRefs.forEach((I,p)=>s(I,`${y}.resultRefs[${p}]`));break;case"iteration":h.threadIds.forEach((I,p)=>l("thread",I,`${y}.threadIds[${p}]`)),h.artifactIds.forEach((I,p)=>d(I,`${y}.artifactIds[${p}]`));break;case"evidence":h.artifactIds.forEach((I,p)=>d(I,`${y}.artifactIds[${p}]`));break;case"advisory_explanation":h.subjectIds.forEach((I,p)=>l("subject",I,`${y}.subjectIds[${p}]`)),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${y}.evidenceIds[${p}]`)),h.supersededById&&l("advisory_explanation",h.supersededById,`${y}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((I,p)=>l("iteration",I,`${y}.iterationIds[${p}]`)),h.coverageClaims.forEach((I,p)=>l("decision",I.decisionId,`${y}.coverageClaims[${p}].decisionId`)),h.artifactIds.forEach((I,p)=>d(I,`${y}.artifactIds[${p}]`));break;case"eval_spec":h.replacesSpecId&&l("eval_spec",h.replacesSpecId,`${y}.replacesSpecId`),h.decisionIds.forEach((I,p)=>l("decision",I,`${y}.decisionIds[${p}]`)),h.subjectIds.forEach((I,p)=>l("subject",I,`${y}.subjectIds[${p}]`)),(h.dependencies??[]).forEach((I,p)=>{I.kind==="subject"&&I.subjectId&&l("subject",I.subjectId,`${y}.dependencies[${p}].subjectId`)}),(h.scenarios??[]).forEach((I,p)=>{I.subjectIds?.forEach((A,m)=>l("subject",A,`${y}.scenarios[${p}].subjectIds[${m}]`))}),h.targets.forEach((I,p)=>l(I.entityType,I.entityId,`${y}.targets[${p}]`));break;case"verification_attempt":h.evalSpecId&&l("eval_spec",h.evalSpecId,`${y}.evalSpecId`),h.targets.forEach((I,p)=>l(I.entityType,I.entityId,`${y}.targets[${p}]`)),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${y}.evidenceIds[${p}]`));break;case"model_entry":h.subjectIds.forEach((I,p)=>l("subject",I,`${y}.subjectIds[${p}]`)),h.decisionIds.forEach((I,p)=>l("decision",I,`${y}.decisionIds[${p}]`));break;case"model_projection":Mt(e,`${y}.authority`,h.authority,!0),l("participant",h.appliedById,`${y}.appliedById`),h.decisionIds.forEach((I,p)=>l("decision",I,`${y}.decisionIds[${p}]`)),h.entryIds.forEach((I,p)=>l("model_entry",I,`${y}.entryIds[${p}]`)),h.coverage.forEach((I,p)=>l("decision",I.decisionId,`${y}.coverage[${p}].decisionId`));break;case"freshness_signal":s(h.target,`${y}.target`),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${y}.evidenceIds[${p}]`));break;default:break}});let w=new Map(o.events.map(h=>[h.id,h])),b=new Map(o.records.map(h=>[`${h.recordType}:${h.id}`,h])),g=new Map;o.events.forEach((h,u)=>{let y=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,I=g.get(y)??new Set;I.add(h.toState),g.set(y,I),I.size>1&&oe(e,`events[${u}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(o.records.flatMap(h=>h.recordType==="authority_grant"?[[h.id,h]]:[])),x=(h,u,y,I,p)=>{if(h.level!=="delegate"||!h.grantId)return;let A=k.get(h.grantId);if(!A){oe(e,p,"invalid_authority_grant","Delegated authority references a missing grant.");return}(A.granteeId!==u||A.level!=="delegate")&&oe(e,p,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let m=Date.parse(y);(m<Date.parse(A.startsAt)||A.endsAt&&m>Date.parse(A.endsAt)||A.revokedAt&&m>=Date.parse(A.revokedAt))&&oe(e,p,"inactive_authority_grant","The delegated authority grant was not active at this time."),A.subjectIds.length&&I.length&&!I.every(f=>A.subjectIds.includes(f))&&oe(e,p,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let h of o.records)h.recordType==="decision"&&x(h.authority,h.acceptedById,h.createdAt,h.subjects.map(u=>u.subjectId),`records:${h.id}.authority`);o.events.forEach((h,u)=>{let y=b.get(`${h.entity.entityType}:${h.entity.entityId}`),I=y&&"subjects"in y?y.subjects.map(p=>p.subjectId):[];x(h.authority,h.participantId,h.createdAt,I,`events[${u}].authority`)}),o.relationships.forEach((h,u)=>{if(!h.authority)return;let y=[h.from,h.to].flatMap(I=>{let p=b.get(`${I.entityType}:${I.entityId}`);return p&&"subjects"in p?p.subjects.map(A=>A.subjectId):[]});x(h.authority,h.participantId,h.createdAt,y,`relationships[${u}].authority`)});for(let h of o.records){if(h.recordType!=="decision")continue;let u=w.get(h.acceptanceEventId);(!u||u.entity.entityType!=="proposal"||u.entity.entityId!==h.proposalId||u.toState!=="accepted")&&oe(e,`records:${h.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),u&&u.participantId!==h.acceptedById&&oe(e,`records:${h.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),b.has(`proposal:${h.proposalId}`)||oe(e,`records:${h.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),h.state==="superseded"&&(o.relationships.some(I=>I.relationshipType==="supersedes"&&I.to.entityType==="decision"&&I.to.entityId===h.id)||oe(e,`records:${h.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),h.state==="revoked"&&(o.events.some(I=>I.entity.entityType==="decision"&&I.entity.entityId===h.id&&I.toState==="revoked"&&!!I.reason?.trim())||oe(e,`records:${h.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let h of o.records){if(h.recordType!=="proposal"||h.state!=="accepted")continue;o.records.some(y=>y.recordType==="decision"&&y.proposalId===h.id)||oe(e,`records:${h.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ed(e)}function In(o,e,t,n){return{id:n,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function fi(o,e,t,n,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,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(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function to(o,e){let t=[],n=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.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."}),Vt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of sd(e))Vt(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||!n)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={...In(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=fi(o,n,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.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={...In(o,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...In(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=fi(o,i,e,a.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[i,d],events:[s,a],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.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={...In(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let r={...In(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.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:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}import{createHash as ad}from"crypto";import{readFile as dd,readdir as cd,realpath as ld}from"fs/promises";import{join as wn,relative as pd}from"path";var ud=["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 Ht(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ke(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function hi(...o){return o.find(e=>!!e?.trim())?.trim()}function ce(o,e,t,n){let i=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=ad("sha256").update(`${o}\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 nr(o,e){try{return JSON.parse(await dd(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function md(o){let e=Ht(o);if(!e)return 0;let t=0,n=r=>{let i=Ht(r);if(!i){t+=1;return}for(let s of Object.values(i))n(s)};for(let r of Object.values(e))n(r);return t}function fd(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function vn(o){let e=[],t=await ld(o.projectRoot).catch(()=>o.projectRoot),n=wn(t,".popmelt"),r=await nr(wn(n,"threads.json"),e),i=await nr(wn(n,"model.json"),e),s=Ht(r),a=Ht(s?.threads)??{},d=Object.entries(a).map(([J,q])=>({key:J,value:Ht(q)})).filter(J=>!!J.value),l=wn(n,"decisions"),w=await cd(l).catch(()=>[]),b=[];for(let J of w.filter(q=>q.endsWith(".json")).sort()){let q=Ht(await nr(wn(l,J),e));q&&b.push({file:J,value:q})}let g=d.flatMap(({value:J})=>[J.createdAt,J.updatedAt]).filter(J=>typeof J=="number"&&Number.isFinite(J)),k=g.length?Math.min(...g):0,x=o.projectKey??t;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let h=ce(x,"project",x,k),u=ce(x,"participant","legacy-owner",k),y=ce(x,"participant","legacy-agent",k),I=ce(x,"subject","project",k),p=Ke(Math.max(k,...g)),A=[],m=[],f=new Map,j=new Map,$=new Map(b.map(J=>[J.value.id??J.file.replace(/^d-|\.json$/g,""),J.value])),R=new Map,_=(J,q,H,ge,_e)=>{let ue=f.get(H);if(ue)return ue;let Be=ce(x,"artifact",J,ge);return m.push({id:Be,kind:q,mediaType:_e,location:H,availability:"available"}),f.set(H,Be),Be};for(let{file:J,value:q}of b){let H=q.id??J.replace(/^d-|\.json$/g,""),ge=q.createdAt??k,_e=[_(`${H}:envelope`,"other",`.popmelt/decisions/${J}`,ge,"application/json")];q.screenshotPath&&_e.push(_(`${H}:screenshot`,"screenshot",`.popmelt/${q.screenshotPath.replace(/^\.popmelt\//,"")}`,ge,q.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,Be]of(q.pastedImagePaths??[]).entries())_e.push(_(`${H}:image:${ue}`,"image",Be,ge));R.set(H,_e)}let X=(J,q,H)=>({id:J,schemaVersion:1,projectId:h,createdAt:p,participantId:q,sourceRefs:H}),G=(J,q)=>{A.push(q);let H=j.get(J)??[];H.push(q.id),j.set(J,H)},M=[{...X(u,u,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...X(y,y,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];A.push(...M),A.push({...X(I,u,[]),recordType:"subject",subjectType:"project",label:pd(process.cwd(),t)||t,aliases:[],locators:[{id:ce(x,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:Ke(k),sourceRefs:[]}]});let L=new Map,W=(J,q)=>{let H=L.get(J);if(H)return H;let ge=ce(x,"subject",J,q),_e={...X(ge,u,[{kind:"external",id:J}]),createdAt:Ke(q),recordType:"subject",subjectType:"element",label:J,aliases:[],locators:[{id:ce(x,"locator",J,q),kind:"dom_selector",value:J,status:"current",validFrom:Ke(q),sourceRefs:[{kind:"external",id:J}]}]};return A.push(_e),L.set(J,ge),ge};for(let{key:J,value:q}of d){let H=q.id??J,ge=q.createdAt??k,_e=ce(x,"thread",H,ge),ue={kind:"thread",id:H},Be=[],bt=[],un=Array.isArray(q.messages)?q.messages:[],Me,rt,xt=0;un.forEach((Pe,ut)=>{let Je=Pe.timestamp??ge,it=ce(x,"artifact",`${H}:message:${ut}`,Je);if(Be.push(it),m.push({id:it,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${H}/messages/${ut}`,availability:"available"}),f.set(`.popmelt/threads.json#/threads/${H}/messages/${ut}`,it),Pe.screenshotPath&&_(`${H}:message:${ut}:screenshot`,"screenshot",Pe.screenshotPath,Je),Pe.role==="human"){Me=Pe;let Oe=Pe.feedbackSummary??Pe.replyToQuestion;if(Oe?.trim()){let Le=ce(x,"observation",`${H}:${ut}`,Je),ht=q.elementIdentifiers??[],Nt={...X(Le,u,[ue,{kind:"message",id:it}]),createdAt:Ke(Je),recordType:"observation",state:"open",statement:Oe,captureContext:{subjectIds:ht.map(kt=>W(kt,ge)),artifactIds:[it]},resolvedByIds:[]};G(H,Nt),rt=Le,bt.push({entityType:"observation",entityId:Le})}return}if(Pe.role!=="assistant")return;let mt=Pe.jobId??`${H}:${ut}`,ft=ce(x,"iteration",mt,Je),Tt=$.get(mt),Go=Pe.cancelled?"cancelled":Pe.error?"failed":Pe.question?"question_asked":(Pe.resolutions?.length??0)>0?"completed":"no_change",Wo={...X(ft,y,[ue,{kind:"message",id:it},...(R.get(mt)??[]).map(Oe=>({kind:"artifact",id:Oe}))]),createdAt:Ke(Je),recordType:"iteration",threadIds:[_e],startedAt:Ke(Me?.timestamp,Je),completedAt:Ke(Je),requestSummary:hi(Me?.feedbackSummary,Me?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Pe.question??Pe.error??Pe.responseText?.slice(0,1e3),outcome:Go,execution:{provider:Pe.provider??Tt?.provider,model:Pe.model??Tt?.model,sessionId:Pe.sessionId??Tt?.sessionId},artifactIds:[it,...R.get(mt)??[]]};G(H,Wo),bt.push({entityType:"iteration",entityId:ft});let mn=Pe.resolutions??Tt?.resolutions??[];for(let[Oe,Le]of mn.entries()){if(Le.status!=="resolved"||!Le.summary?.trim())continue;let ht=q.elementIdentifiers??[],Nt=(ht.length?ht:[t]).map(Kn=>({subjectId:Kn===t?I:W(Kn,ge),role:"governed"})),kt=ce(x,"proposal",`${mt}:${Le.annotationId??"resolution"}:${Oe}`,Je),Ko={...X(kt,y,[ue,{kind:"iteration",id:ft}]),createdAt:Ke(Je),recordType:"proposal",state:"pending",claim:Le.summary,subjects:Nt,subjectSemantics:Nt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:hi(Me?.feedbackSummary,Me?.replyToQuestion,Le.summary),iterationId:ft,inferredById:y}};G(H,Ko),bt.push({entityType:"proposal",entityId:kt}),e.push({severity:"warning",code:"acceptance_unresolved",source:H,message:`Proposal ${kt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(mn.some(Oe=>Oe.status==="resolved")||Tt?.gitDiff){let Oe=ce(x,"implementation",mt,Je),Le={...X(Oe,y,[ue,{kind:"iteration",id:ft}]),createdAt:Ke(Je),recordType:"implementation_attempt",state:"completed",iterationIds:[ft],coverageClaims:[],summary:mn.map(ht=>ht.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};G(H,Le),bt.push({entityType:"implementation_attempt",entityId:Oe}),xt+=1}rt&&(rt=void 0)});let St=un.at(-1),zo={...X(_e,u,[ue]),createdAt:Ke(ge),recordType:"thread",state:St?.question?"open":"resolved",messageArtifactIds:Be,outcome:St?.question?"question_unresolved":xt?"implementation_only":"no_outcome",resultRefs:bt};A.push(zo),j.set(H,[_e,...j.get(H)??[]])}let ie=md(i);ie&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${ie} model values were not promoted because their accepted decision provenance is unresolved.`});let Q={manifest:{formatVersion:1,projectId:h,createdAt:Ke(k),updatedAt:p,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:A,events:[],relationships:[],artifacts:m,tombstones:[]},ee=Et(Q),E=(o.proofCaseIds??ud).map(J=>({legacyId:J,threadFound:d.some(({key:q,value:H})=>(H.id??q)===J),decisionEnvelopeFound:$.has(J),recordIds:j.get(J)??[]}));return{bundle:Q,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((J,q)=>J+(q.value.messages?.length??0),0),decisionEnvelopes:b.length,modelEntries:ie,artifactsReferenced:m.length},imported:fd(A),unresolvedAcceptance:e.filter(J=>J.code==="acceptance_unresolved").length,deferredModelEntries:ie,proofCases:E,issues:e,schemaIssues:ee.issues}}}var hd=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function gi(o,e){let t=o.records.find(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),n=o.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=hd(),l=d.records,w=o.records.find(p=>p.recordType==="thread"&&p.sourceRefs.some(A=>A.kind==="thread"&&A.id===e.threadId));w||(w={id:ce(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.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(p=>p.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let b=[];for(let p of[...new Set(e.subjectHints.filter(Boolean))]){let A=o.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.value===p&&f.status==="current"));A||(A={id:ce(r,"live-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"element",label:p,aliases:[],locators:[{id:ce(r,"live-locator",p,e.createdAt),kind:"dom_selector",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},l.push(A)),b.push(A)}for(let p of[...new Set((e.filePaths??[]).filter(Boolean))]){let A=o.records.find(m=>m.recordType==="subject"&&m.locators.some(f=>f.kind==="source_file"&&f.value===p&&f.status==="current"));A||(A={id:ce(r,"live-file-subject",p,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:p}],recordType:"subject",subjectType:"file",label:p,aliases:[],locators:[{id:ce(r,"live-file-locator",p,e.createdAt),kind:"source_file",value:p,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:p}]}]},l.push(A)),b.push(A)}let g=(e.semanticCandidates??[]).filter(p=>p.claim.trim()),k;if(g.length>0){k=ce(r,"live-observation",i,e.createdAt);let p={id:k,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:g.map(A=>A.claim.trim()).join(" "),captureContext:{subjectIds:b.map(A=>A.id),artifactIds:[]},resolvedByIds:[]};l.push(p)}let x=ce(r,"live-iteration",i,e.completedAt),h={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(p=>({kind:"external",id:p,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(p=>({kind:"external",id:p,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[w.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}:{}};l.push(h);let u=[],y=e.resolutions.filter(p=>p.status==="resolved"&&p.summary.trim()),I=b.length>0?b:o.records.filter(p=>p.recordType==="subject"&&p.subjectType==="project").slice(0,1);if(g.length>0&&I.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[p,A]of g.entries()){let m=ce(r,"live-proposal",`${i}:${p}`,e.completedAt),f=I.map($=>({subjectId:$.id,role:"governed"})),j={id:m,schemaVersion:1,projectId:o.manifest.projectId,createdAt:a,participantId:n.id,sourceRefs:[{kind:"iteration",id:x},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:A.claim.trim(),rationale:A.rationale?.trim()||void 0,proposedKind:A.proposedKind,subjects:f,subjectSemantics:f.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:A.sourceText?.trim()||e.requestSummary,iterationId:x,inferredById:n.id}};l.push(j),u.push(m)}if(y.length>0){let p=new Set(e.governingDecisionIds??[]),A=o.records.filter(f=>f.recordType==="decision"&&f.state==="active"&&p.has(f.id)),m={id:ce(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:a,participantId:n.id,sourceRefs:[{kind:"iteration",id:x}],recordType:"implementation_attempt",state:"completed",iterationIds:[x],coverageClaims:A.map(f=>({decisionId:f.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${y.map(j=>j.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:x}]})),summary:y.map(f=>f.summary).join(" "),artifactIds:[]};l.push(m)}return{mutation:d,iterationId:x,proposalIds:u,observationId:k}}import{createHash as gd}from"crypto";import{mkdir as yi,open as or,readFile as rr,readdir as yd,rename as Id,unlink as ir}from"fs/promises";import{join as ct}from"path";var wd={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function no(o){return gd("sha256").update(JSON.stringify(o)).digest("hex")}function Ii(o){return no(o)}function wi(o,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let r=o.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(r<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let i=o.records[r];if(i.projectId!==n.projectId||i.createdAt!==n.createdAt||i.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);o.records[r]=structuredClone(n)}for(let n of e.projectionUpdates){let r=o.records.find(i=>i.recordType===n.entityType&&i.id===n.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(r.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${r.state}`);r.state=n.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=t,o}function vd(o,e,t){return wi(structuredClone(o),e,t)}async function _t(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await or(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
13
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await Id(t,o)}catch(r){throw await ir(t).catch(()=>{}),r}}async function bn(o){return JSON.parse(await rr(o,"utf8"))}var oo=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=ct(e,".popmelt","memory"),this.journalDir=ct(this.memoryDir,"journal"),this.manifestPath=ct(this.memoryDir,"manifest.json"),this.checkpointPath=ct(this.memoryDir,"checkpoint.json"),this.lockPath=ct(this.memoryDir,"writer.lock")}async readHead(){let e=await bn(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=Et(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await yi(this.journalDir,{recursive:!0});try{throw await rr(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await rr(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 n=no(e),r={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await _t(this.checkpointPath,r),await _t(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 _t(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=no(e.bundle),n=`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 _t(ct(this.memoryDir,n),r),e.manifest.checkpoint={file:n,sequence:r.sequence,hash:t},await _t(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(!Vt(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 n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let r=n.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...i,hash:Ii(i)},a=vd(n.bundle,e,t.committedAt),d=Et(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await _t(ct(this.journalDir,l),s),n.manifest.head={sequence:r,hash:s.hash},n.manifest.updatedAt=t.committedAt,await _t(this.manifestPath,n.manifest),{bundle:a,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...wd,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await bn(this.manifestPath),t=await bn(ct(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!==no(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await yd(this.journalDir),r=n.filter(g=>g.endsWith(".tmp")),s=n.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,l=t.journalHash??null,w=new Set;for(let g of s){let k=await bn(ct(this.journalDir,g)),{hash:x,...h}=k;if(x!==Ii(h))throw new Error(`Journal hash mismatch: ${g}`);if(k.sequence!==d+1)throw new Error(`Journal sequence gap at ${g}`);if(k.previousHash!==l)throw new Error(`Journal chain mismatch at ${g}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${g}`);if(w.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);wi(a,k.mutation,k.committedAt),d=k.sequence,l=k.hash,w.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!==l)throw new Error("Journal manifest head hash mismatch.");let b=Et(a);if(!b.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(b.issues)}`);return{bundle:a,manifest:e,transactionIds:w,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await yi(this.memoryDir,{recursive:!0});let t;try{t=await or(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let r=await bn(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 ir(this.lockPath),t=await or(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await ir(this.lockPath).catch(()=>{})}}};import{createHash as bd}from"crypto";import{mkdir as xd,open as Sd,readFile as Td,rename as kd,unlink as Rd}from"fs/promises";import{join as vi}from"path";function bi(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function xi(o){return bd("sha256").update(JSON.stringify(o)).digest("hex")}async function Pd(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Sd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
14
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await kd(t,o)}catch(r){throw await Rd(t).catch(()=>{}),r}}function Ad(o,e,t=new Date().toISOString()){let n={},r={},i={},s=(d,l,w)=>{let b=d[l]??=[];b.includes(w)||b.push(w)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let w of[l.label,...l.aliases,...l.locators.filter(b=>b.status==="current").map(b=>b.value)]){let b=bi(w);b&&s(n,b,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let a={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:xi(a)}}function Si(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[bi(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>o.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>o.proposalIdsBySubject[n]??[]))]}}var ro=class{constructor(e){this.indexDir=vi(e,".popmelt","memory","indexes"),this.indexPath=vi(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await Td(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===xi(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let n=Ad(e,t);return await xd(this.indexDir,{recursive:!0}),await Pd(this.indexPath,n),n}};import{randomBytes as jd}from"crypto";function ke(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=jd(10).toString("hex"),r=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${r}${n.slice(4,7)}-${n.slice(7,19)}`}var Tn="popmelt:imprint",Ri="popmelt:imprint-evidence",Xt="popmelt:imprint-relation";function Sn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Tn)?.id}function sr(o){let e=new Set;return o.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function io(o,e){if(!o)return[];let t=new Set(o.relations.flatMap(n=>n.type==="expresses"&&!n.toStoreId&&n.toId===e?[n.fromId]:[]));return o.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function ar(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var en=class{constructor(e){this.projectRoot=e;this.store=new oo(e),this.indexStore=new ro(e),this.manifestPath=Qt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await xn(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 n=await vn({...e,projectRoot:this.projectRoot});if(n.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(n.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 vn({...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=Qt(this.projectRoot,".popmelt","memory","migrations"),t=Qt(e,"imprint-advisories-v2.json");try{let p=JSON.parse(await xn(t,"utf8"));return{migrated:!1,explanations:p.explanations??0,evidence:p.evidence??0}}catch{}let n;try{n=At(JSON.parse(await xn(Qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await Ti(e,{recursive:!0}),await ki(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(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active"),a=r.bundle.records.find(p=>p.recordType==="participant"&&p.kind==="ai"&&p.status==="active")??i,d=r.bundle.records.find(p=>p.recordType==="subject"&&p.subjectType==="project");if(!a||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,w=new Set(r.bundle.records.map(p=>p.id)),b=new Set(r.bundle.relationships.flatMap(p=>p.sourceRefs.flatMap(A=>A.kind==="external"&&A.uri===Xt?[A.id]:[]))),g=new Map,k=r.bundle.records.filter(p=>p.recordType==="advisory_explanation");for(let p of n.explanations){let A=k.find(m=>Sn(m)===p.id);g.set(p.id,A?.id??ce(l,"imprint-explanation",p.id,Date.parse(p.createdAt)))}let x=[],h=[],u=[],y=0;for(let p of n.explanations){let A=g.get(p.id),m=k.find(R=>R.id===A),f=[],j=p.evidence.length?p.evidence:[{id:`fallback:${p.id}`,kind:"observation",stance:"supports",summary:p.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:p.createdAt}];for(let R of j){let _=ce(l,"imprint-evidence-record",R.id,Date.parse(R.createdAt));f.push(_),!w.has(_)&&(x.push({id:_,schemaVersion:1,projectId:l,createdAt:R.createdAt,participantId:a.id,sourceRefs:sr([{kind:"external",id:R.id,uri:Ri},{kind:"external",id:p.id,uri:Tn},{kind:"thread",id:R.threadId},{kind:"message",id:R.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(R.kind)?"user_feedback":"judgment",summary:R.summary,availability:"available",artifactIds:[]}),u.push({id:ce(l,"imprint-evidence-link",`${p.id}:${R.id}`,Date.parse(R.createdAt)),schemaVersion:1,projectId:l,createdAt:R.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:R.id,uri:Ri}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"evidence",entityId:_},reason:"This advisory explanation was derived from collaboration evidence."}),y+=1)}let $={id:A,schemaVersion:1,projectId:l,createdAt:m?.createdAt??p.createdAt,participantId:m?.participantId??a.id,sourceRefs:sr([...m?.sourceRefs??[],{kind:"external",id:p.id,uri:Tn}]),recordType:"advisory_explanation",kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),subjectIds:[d.id],evidenceIds:[...new Set([...m?.evidenceIds??[],...f])],concreteBindings:io(n,p.id),supersededById:p.supersededBy?g.get(p.supersededBy):void 0,updatedAt:p.updatedAt};m?h.push($):x.push($)}for(let p of n.relations){let A=ar(p.type);if(!A||p.toStoreId)continue;let m=g.get(p.fromId),f=g.get(p.toId);!m||!f||b.has(p.id)||u.push({id:ce(l,"imprint-relation",p.id,Date.parse(p.createdAt)),schemaVersion:1,projectId:l,createdAt:p.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:p.id,uri:Xt}],recordType:"relationship",relationshipType:A,from:{entityType:"advisory_explanation",entityId:m},to:{entityType:"advisory_explanation",entityId:f},reason:p.rationale||"The Imprint graph connected these explanations."})}let I=new Date().toISOString();if(x.length||h.length||u.length)try{let p=await this.store.commit({records:x,recordReplacements:h,events:[],relationships:u,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ce(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:I});await this.refreshIndex(p)}catch(p){if(!(p instanceof Error)||!p.message.includes("Transaction already exists"))throw p}return await Ti(e,{recursive:!0}),await ki(t,JSON.stringify({version:2,migratedAt:I,explanations:n.explanations.length,evidence:y,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:y}}async review(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,selection:er(n.bundle,r)}}async contextualize(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:ui(n.bundle,r),reviewSelection:er(n.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:Sn(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 n=await this.loadSource(t);return{source:n.source,result:to(n.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 vn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.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 n=await this.store.load(),r=to(n.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(),n=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(!n||n.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.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:n.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:ke(i),decisionId:ke(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:ke(i),replacementProposalId:ke(i),acceptanceEventId:ke(i),decisionId:ke(i),relationshipId:ke(i),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:ke(i),reason:e.reason}:{...a,action:"defer",eventId:ke(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(g=>g.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=to(t.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(g=>g.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:ke(i),committedAt:s});await this.refreshIndex(w);let b=l.plan.resultRefs.find(g=>g.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:b,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:w.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=gi(t.bundle,e),r=ce(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(n.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.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=At(JSON.parse(await xn(Qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),r=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),i=n.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),s=e.action?r:i??r,a=n.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),w=n.bundle.manifest.projectId,b=[],g=[],k=[],x=n.bundle.records.filter(I=>I.recordType==="advisory_explanation"),h=new Map(x.flatMap(I=>{let p=Sn(I);return p?[[p,I.id]]:[]}));for(let I of e.summary.changes)if(!h.has(I.explanationId)){let p=t?.explanations.find(A=>A.id===I.explanationId);h.set(I.explanationId,ce(w,"imprint-explanation",I.explanationId,Date.parse(p?.createdAt??d)))}for(let I of e.summary.changes){let p={kind:"external",id:I.explanationId,uri:Tn},A=h.get(I.explanationId),m=x.find(R=>R.id===A),f=t?.explanations.find(R=>R.id===I.explanationId),j={id:ce(w,"imprint-live-evidence",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[p,{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:[]};b.push(j);let $={id:A,schemaVersion:1,projectId:w,createdAt:m?.createdAt??f?.createdAt??d,participantId:m?.participantId??s.id,sourceRefs:sr([...m?.sourceRefs??[],p,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:f?.kind??m?.kind??"pattern",state:f?.state??I.state,statement:f?.statement??I.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??[],j.id])],concreteBindings:f?io(t,I.explanationId):m?.concreteBindings??[],supersededById:f?.supersededBy?h.get(f.supersededBy):m?.supersededById,updatedAt:f?.updatedAt??d};m?g.push($):b.push($),k.push({id:ce(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[p],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:$.id},to:{entityType:"evidence",entityId:j.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let u=new Set(n.bundle.relationships.flatMap(I=>I.sourceRefs.flatMap(p=>p.kind==="external"&&p.uri===Xt?[p.id]:[])));for(let I of t?.relations??[]){let p=ar(I.type);if(!p)continue;let A=h.get(I.fromId),m=I.toStoreId?e.qualifiedExplanationMemoryIds?.[`${I.toStoreId}:${I.toId}`]:h.get(I.toId);!A||!m||u.has(I.id)||k.push({id:ce(w,"imprint-relation",I.id,Date.parse(I.createdAt)),schemaVersion:1,projectId:w,createdAt:I.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:I.id,uri:Xt}],recordType:"relationship",relationshipType:p,from:{entityType:"advisory_explanation",entityId:A},to:{entityType:"advisory_explanation",entityId:m,...I.toStoreId?{storeId:I.toStoreId}:{}},reason:I.rationale||"The Imprint graph connected these explanations."})}let y=ce(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let I=await this.store.commit({records:b,recordReplacements:g,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:y,committedAt:d});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=At(JSON.parse(await xn(Qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=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")??n;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"),l=new Map(d.flatMap(f=>{let j=Sn(f);return j?[[j,f]]:[]})),w=new Map([...[...l].map(([f,j])=>[f,j.id]),...e.explanations.filter(f=>!l.has(f.id)).map(f=>[f.id,ce(a,"imprint-explanation",f.id,Date.parse(f.createdAt))])]),b=[],g=[],k=new Set(e.explanations.map(f=>f.id));for(let f of e.explanations){let j=l.get(f.id);if(!j){b.push({id:w.get(f.id),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:Tn}],recordType:"advisory_explanation",kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:io(e,f.id),supersededById:f.supersededBy?w.get(f.supersededBy):void 0,updatedAt:f.updatedAt});continue}let $={...structuredClone(j),kind:f.kind,state:f.state,statement:f.statement,rationale:f.rationale,scope:structuredClone(f.scope),concreteBindings:io(e,f.id),supersededById:f.supersededBy?w.get(f.supersededBy):void 0,updatedAt:f.updatedAt},R=_=>JSON.stringify({kind:_.kind,state:_.state,statement:_.statement,rationale:_.rationale,scope:_.scope,concreteBindings:_.concreteBindings,supersededById:_.supersededById,updatedAt:_.updatedAt});R(j)!==R($)&&g.push($)}for(let[f,j]of l)k.has(f)||j.state==="retired"||g.push({...structuredClone(j),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let x=new Set(t.bundle.tombstones.flatMap(f=>f.objectType==="relationship"?[f.objectId]:[])),h=new Map(t.bundle.relationships.flatMap(f=>{if(x.has(f.id))return[];let j=f.sourceRefs.find($=>$.kind==="external"&&$.uri===Xt)?.id;return j?[[j,f]]:[]})),u=[],y=new Set;for(let f of e.relations){let j=ar(f.type);if(!j||f.toStoreId)continue;let $=w.get(f.fromId),R=w.get(f.toId);if(!$||!R)continue;let _=h.get(f.id);_&&_.relationshipType===j&&_.from.entityType==="advisory_explanation"&&_.from.entityId===$&&_.to.entityType==="advisory_explanation"&&_.to.entityId===R||(_&&y.add(f.id),u.push({id:ce(a,"imprint-relation",`${f.id}:${j}:${$}:${R}`,Date.parse(f.createdAt)),schemaVersion:1,projectId:a,createdAt:f.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:f.id,uri:Xt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:$},to:{entityType:"advisory_explanation",entityId:R},reason:f.rationale||"The Imprint graph connected these explanations."}))}let I=new Set(e.relations.map(f=>f.id)),p=n?[...h].filter(([f])=>!I.has(f)||y.has(f)).map(([,f])=>({id:ce(a,"imprint-relationship-tombstone",f.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:f.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!b.length&&!g.length&&!u.length&&!p.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let A=e.updatedAt,m=ce(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(A));try{let f=await this.store.commit({records:b,recordReplacements:g,events:[],relationships:u,artifacts:[],tombstones:p,projectionUpdates:[]},{transactionId:m,committedAt:A});return await this.refreshIndex(f),{status:"synced",relationships:u.length+p.length,explanations:b.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 n={};for(let r of t.bundle.records)n[r.recordType]=(n[r.recordType]??0)+1;return{status:e,journal:t.report,records:n,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(),n=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"&&!n.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]:[])),n=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))&&n.set(r.key,r);return[...n.values()]}async getImprintView(e=[],t){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let r=await this.store.load(),i=r.bundle.records.filter(u=>u.recordType==="advisory_explanation"),s=new Map(i.map(u=>[u.id,u])),a=new Map(i.flatMap(u=>{let y=Sn(u);return y?[[y,u.id]]:[]})),d=new Set(e.map(u=>a.get(u)??u)),l=new Map(r.bundle.records.flatMap(u=>u.recordType==="participant"?[[u.id,u.kind]]:[])),w=new Map(r.bundle.records.flatMap(u=>u.recordType==="evidence"?[[u.id,u]]:[])),b=new Set(r.bundle.tombstones.flatMap(u=>u.objectType==="relationship"?[u.objectId]:[])),g=new Set(["expresses","operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=i.map(u=>{let y=u.evidenceIds.flatMap(m=>{let f=w.get(m);if(!f)return[];let j=f.sourceRefs.find(X=>X.kind==="thread")?.id,$=f.sourceRefs.find(X=>X.kind==="message")?.id,R=f.kind==="judgment"||f.kind==="user_feedback"||f.kind==="project_state"?f.kind:"other",_=l.get(f.participantId)??"unknown";return[{id:f.id,kind:R,summary:f.summary,createdAt:f.createdAt,participantKind:_,threadId:j,jobId:$}]}).sort((m,f)=>f.createdAt.localeCompare(m.createdAt)),I=r.bundle.relationships.flatMap(m=>{if(b.has(m.id))return[];if(!g.has(m.relationshipType))return[];let f=m.from.entityType==="advisory_explanation"&&m.from.entityId===u.id&&m.to.entityType==="advisory_explanation",j=m.to.entityType==="advisory_explanation"&&m.to.entityId===u.id&&m.from.entityType==="advisory_explanation";if(!f&&!j)return[];let $=f?m.to.entityId:m.from.entityId,R=s.get($);return R?[{id:m.id,type:m.relationshipType==="excepts"?"excepts":"expresses",direction:f?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:m.reason}]:[]}),p=[...(u.supersededById?[u.supersededById]:[]).flatMap(m=>{let f=s.get(m);return f?[{id:`supersedes:${u.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===u.id?[{id:`supersedes:${m.id}:${u.id}`,type:"supersedes",direction:"outgoing",explanationId:m.id,statement:m.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],A=[...new Set([...u.sourceRefs.flatMap(m=>m.kind==="thread"?[m.id]:[]),...y.flatMap(m=>m.threadId?[m.threadId]:[])])].filter(m=>!t||t.has(m));return{id:u.id,kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),createdAt:u.createdAt,updatedAt:u.updatedAt,evidenceCount:y.length,recentEvidence:y.slice(0,4),concrete:u.concreteBindings.map(m=>({...structuredClone(m)})),relations:[...I,...p],sourceThreadIds:A,needsGrounding:u.state==="testing"&&d.has(u.id)}}).sort((u,y)=>Number(y.needsGrounding)-Number(u.needsGrounding)||k[u.state]-k[y.state]||y.updatedAt.localeCompare(u.updatedAt)),h={total:x.filter(u=>u.state!=="retired").length,emerging:x.filter(u=>u.state==="emerging").length,testing:x.filter(u=>u.state==="testing").length,grounded:x.filter(u=>u.state==="grounded").length,challenged:x.filter(u=>u.state==="challenged").length,retired:x.filter(u=>u.state==="retired").length,needsGrounding:x.filter(u=>u.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:h,explanations:x}}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]:[])),n=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))a.decisionIds.some(d=>t.has(d))&&n.set(a.key,a);let r=[...n.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(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===a.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(l=>l.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(),n=t.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),r=t.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!n||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=ke(i),d=ke(i),l=ke(i),w=ke(i),b=ke(i),g=new Set(t.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),k=t.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&g.has(R.id)),x={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},h=[{subjectId:r.id,role:"governed"}],u={...x,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:h,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},y={...x,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."},I={...x,id:l,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:h,noChange:!1,effectiveAt:s},p={...x,id:w,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},A={...x,id:b,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},m={...x,id:ke(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},f=k.map(R=>({...x,id:ke(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:R.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),j=k.map(R=>({...x,id:ke(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:I.id},to:{entityType:"decision",entityId:R.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),$=await this.store.commit({records:[u,I,p,A],events:[y,...f],relationships:[m,...j],artifacts:[],tombstones:[],projectionUpdates:k.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:ke(i),committedAt:s});return await this.refreshIndex($),{decisionId:l,entryId:w}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=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=n.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(),n=t.bundle.records.find(x=>x.recordType==="model_projection"&&x.state==="applied"&&x.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let r=t.bundle.records.filter(x=>x.recordType==="decision"&&e.decisionIds.includes(x.id)&&x.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(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=ke(s),l=e.changes.map(x=>{let h=x.decisionIds?.filter(I=>e.decisionIds.includes(I)),u=h?.length?h:e.decisionIds,y=[...new Set(r.filter(I=>u.includes(I.id)).flatMap(I=>I.subjects.map(p=>p.subjectId)))];return{id:ke(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:u.map(I=>({kind:"record",id:I})),recordType:"model_entry",key:x.path.map(String).join("."),subjectIds:y,decisionIds:u,value:x.value}}),w=new Set(l.flatMap(x=>x.decisionIds)),b={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(x=>({kind:"record",id:x})),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:l.map(x=>x.id),coverage:e.decisionIds.map(x=>e.coverage?.find(h=>h.decisionId===x)??{decisionId:x,status:w.has(x)?"projected":"unprojected"})},g=l.flatMap(x=>x.decisionIds.map(h=>({id:ke(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:b.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x.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:[...l,b],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ke(s),committedAt:a});return await this.refreshIndex(k),{projectionId:d,entryIds:l.map(x=>x.id),headSequence:k.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await vn({...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 n=await this.store.load(),r={source:"journal",bundle:n.bundle,journal:n.report};return this.contextualSourceCache={headKey:t,value:r},r}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=Si(n,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 Zt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function je(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Yt(o,e,t){let n=je(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function dr(o){let e=Zt(o),t=Zt(e.authority),n=t.level,r=t.mode,i=Yt(n,"authority.level",["owner","delegate","contributor"]),s=Yt(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:je(e.proposalId,"proposalId"),participantId:je(e.participantId,"participantId"),occurredAt:je(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:je(e.eventId,"eventId"),decisionId:je(e.decisionId,"decisionId"),kind:Yt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:je(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:je(e.eventId,"eventId"),reason:je(e.reason,"reason")};case"defer":{let d=Zt(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:je(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>je(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Yt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...a,action:"edit_and_accept",withdrawalEventId:je(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:je(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:je(e.acceptanceEventId,"acceptanceEventId"),decisionId:je(e.decisionId,"decisionId"),relationshipId:je(e.relationshipId,"relationshipId"),claim:je(e.claim,"claim"),kind:Yt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=Zt(d);return{subjectId:je(l.subjectId,"subjectId"),role:Yt(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:je(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function cr(o){let e=Zt(o),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>je(a,s))}},n=(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:Zt(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:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(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 Md=1400,Ed=6,_d=2,lr=6;function Pi(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.projectRoot=="string"&&!!e.projectRoot.trim()&&typeof e.projectId=="string"&&!!e.projectId.trim()}function Mi(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!Pi(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(Pi):[],n=new Set([e.primary.storeId]);return{primary:e.primary,mounted:t.filter(r=>n.has(r.storeId)?!1:(n.add(r.storeId),!0))}}function Ai(o){return[o.primary,...o.mounted]}function kn(o){let e=[],t=Math.max(0,...o.map(n=>n.length));for(let n=0;n<t;n++)for(let r of o)r[n]!==void 0&&e.push(r[n]);return e}function ji(o){return Math.ceil(JSON.stringify(o).length/4)}function Cd(o,e,t){return{...o,...o.acceptedTruth?{acceptedTruth:{...o.acceptedTruth,decisions:o.acceptedTruth.decisions.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),conflicts:o.acceptedTruth.conflicts.map(n=>({...n,storeId:e.storeId}))}}:{},packets:o.packets.map(n=>({...n,presentation:t?"advisory":n.presentation,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function $d(o,e,t,n){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let r=o.map(({store:b,context:g})=>Cd(g,b,b.storeId!==t)),i=kn(r.map(b=>b.acceptedTruth?.decisions??[])).slice(0,Ed),s=new Set(i.map(b=>`${b.storeId}:${b.id}`)),a=r.flatMap(b=>b.acceptedTruth?.conflicts??[]).filter(b=>b.decisionIds.every(g=>s.has(`${b.storeId}:${g}`))),d=kn(r.map(b=>b.packets)).slice(0,_d),l=i.length<r.reduce((b,g)=>b+(g.acceptedTruth?.decisions.length??0),0)||d.length<r.reduce((b,g)=>b+g.packets.length,0),w={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:l||r.some(b=>b.acceptedTruth?.truncated)}}:{},packets:d,truncated:l||e.length>0||r.some(b=>b.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;ji(w)>Md;){if(w.packets.length)w.packets.pop();else if(w.acceptedTruth?.decisions.length)w.acceptedTruth.decisions.pop();else break;w.truncated=!0,w.acceptedTruth&&(w.acceptedTruth.truncated=!0)}if(w.estimatedTokens=ji(w),!(!w.packets.length&&!w.acceptedTruth?.decisions.length))return w}function Ei(o,e,t){return{...o,explanations:o.explanations.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t})),relations:o.relations?.map(n=>({...n,storeId:e.storeId,readOnly:t,from:n.from??{storeId:e.storeId,explanationId:n.fromId},to:n.to??{storeId:n.toStoreId??e.storeId,explanationId:n.toId}})),historicalCaveats:o.historicalCaveats?.map(n=>({...n,storeId:e.storeId,storeRoot:e.projectRoot,readOnly:t}))}}function Re(o,e){return`${o}:${e}`}function Od(o){let e=o.from??{storeId:o.storeId??"",explanationId:o.fromId},t=o.to??{storeId:o.storeId??"",explanationId:o.toId};return`${o.storeId??""}:${o.type}:${Re(e.storeId,e.explanationId)}:${Re(t.storeId,t.explanationId)}`}function Dd(o,e){let t=new Map;for(let{store:n,topology:r}of o)for(let i of r.explanations)t.set(Re(n.storeId,i.memoryId),i.explanationId);return o.flatMap(({store:n,topology:r})=>r.relations.flatMap(i=>{let s=i.from.storeId??n.storeId,a=i.to.storeId??n.storeId,d=t.get(Re(s,i.from.memoryId)),l=t.get(Re(a,i.to.memoryId));return!d||!l?[]:[{id:i.id,type:i.type,fromId:d,toId:l,rationale:i.rationale,storeId:n.storeId,readOnly:n.storeId!==e,from:{storeId:s,explanationId:d},to:{storeId:a,explanationId:l}}]}))}function Nd(o){let e=new Set;return o.filter(t=>{let n=Od(t);return e.has(n)?!1:(e.add(n),!0)})}function Bd(o,e,t,n,r=[],i=[],s=[]){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let a=o.map(({store:p,context:A})=>Ei(A,p,p.storeId!==t)),d=kn(a.map(p=>p.explanations)),l=Nd([...a.flatMap(p=>p.relations??[]),...r]),w=new Map([...d,...i].map(p=>[Re(p.storeId??"",p.id),p])),b=[],g=new Set,k=p=>{if(!p||b.length>=lr)return;let A=Re(p.storeId??"",p.id);g.has(A)||(g.add(A),b.push(p))};for(let p of d.slice(0,lr)){let A=Re(p.storeId??"",p.id),m=l.flatMap(f=>f.from&&Re(f.from.storeId,f.from.explanationId)===A?[w.get(Re(f.to.storeId,f.to.explanationId))]:f.to&&Re(f.to.storeId,f.to.explanationId)===A?[w.get(Re(f.from.storeId,f.from.explanationId))]:[]).find(Boolean);m&&(k(p),k(m))}d.forEach(k),i.forEach(k);let x=b,h=l.filter(p=>{let A=p.from,m=p.to;return!!(A&&m&&g.has(Re(A.storeId,A.explanationId))&&g.has(Re(m.storeId,m.explanationId)))}),u=new Set([...d.map(p=>Re(p.storeId??"",p.id)),...i.map(p=>Re(p.storeId??"",p.id))]).size,y=[...new Set(a.flatMap(p=>p.pendingGroundingExplanationIds??[]))],I=[...new Set(a.flatMap(p=>p.correctionExplanationIds??[]))];return{explanations:x,relations:h,truncated:x.length<u||e.length>0||a.some(p=>p.truncated),...a.find(p=>p.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(p=>p.retrievalIntent).retrievalIntent}:{},historicalCaveats:kn(a.map(p=>p.historicalCaveats??[])).slice(0,3),...y.length?{pendingGroundingExplanationIds:y}:{},...I.length?{correctionExplanationIds:I}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var so=class{constructor(e,t,n=r=>({memory:new en(r.projectRoot),imprint:new wt(r.projectRoot,r.projectId)})){this.primary=e;this.createReader=n;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 n=this.createReader(e);return this.readers.set(e.storeId,n),n}async memoryContext(e,t,n){let r=performance.now(),i=Ai(this.normalized(e)),s=await Promise.allSettled(i.map(async l=>{let w,b=await Yn(this.reader(l).memory,t,n,g=>{w=g});if(w)throw w;return{store:l,context:b}})),a=s.flatMap(l=>l.status==="fulfilled"&&l.value.context?[l.value]:[]),d=s.flatMap((l,w)=>l.status==="rejected"?[i[w].storeId]:[]);return this.record(i.length,d.length,r),$d(a,d,this.primary.storeId,i.length>1)}async imprintContext(e,t){let n=performance.now(),r=Ai(this.normalized(e)),i=r.length>1,s=r.map(async M=>({store:M,context:await this.reader(M).imprint.contextualize(M.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async M=>({store:M,topology:await(this.reader(M).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[d,l]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),w=d.flatMap(M=>M.status==="fulfilled"&&M.value.context?[M.value]:[]),b=d.flatMap((M,L)=>M.status==="rejected"?[r[L].storeId]:[]),g=l.flatMap(M=>M.status==="fulfilled"?[M.value]:[]),k=l.flatMap((M,L)=>M.status==="rejected"?[r[L].storeId]:[]),x=new Map(g.flatMap(({store:M,topology:L})=>L.explanations.map(W=>[Re(M.storeId,W.explanationId),W.memoryId]))),h=w.map(({store:M,context:L})=>({store:M,context:{...L,explanations:L.explanations.map(W=>({...W,memoryId:x.get(Re(M.storeId,W.id))}))}})),u=Dd(g,this.primary.storeId),y=h.map(({store:M,context:L})=>Ei(L,M,M.storeId!==this.primary.storeId)),I=kn(y.map(M=>M.explanations)).slice(0,lr),p=new Set(I.map(M=>Re(M.storeId??"",M.id))),A=new Set(y.flatMap(M=>M.explanations.map(L=>Re(L.storeId??"",L.id)))),m=new Map,f=(M,L)=>{if(A.has(Re(M,L)))return;let W=m.get(M)??new Set;W.add(L),m.set(M,W)};for(let M of u){if(!M.from||!M.to)continue;let L=Re(M.from.storeId,M.from.explanationId),W=Re(M.to.storeId,M.to.explanationId);p.has(L)&&f(M.to.storeId,M.to.explanationId),p.has(W)&&f(M.from.storeId,M.from.explanationId)}let j=new Map(r.map(M=>[M.storeId,M])),$=[...m].map(async([M,L])=>{let W=j.get(M),ie=W?this.reader(W).imprint.explanationsByIds:void 0;if(!W||!ie)return{storeId:M,explanations:[]};let Q=await ie.call(this.reader(W).imprint,[...L]);return{storeId:M,explanations:Q.map(ee=>({...ee,memoryId:x.get(Re(M,ee.id)),storeId:M,storeRoot:W.projectRoot,readOnly:M!==this.primary.storeId}))}}),R=await Promise.allSettled($),_=R.flatMap(M=>M.status==="fulfilled"?M.value.explanations:[]),X=R.flatMap((M,L)=>M.status==="rejected"?[[...m.keys()][L]]:[]),G=[...new Set([...k,...X])];return this.record(r.length,new Set([...b,...G]).size,n),Bd(h,b,this.primary.storeId,i,u,_,G)}record(e,t,n){this.state.reads+=1,this.state.storeReads+=e,this.state.failedStoreReads+=t,this.state.lastDurationMs=Math.max(0,performance.now()-n)}};function tn(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function Rn(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:n,outcomes:t}}var Ct=1,pr="bridge";function _i(o){return`codex-session:${o}`}function Ud(o,e){return`codex-${Jd("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function Ci(o){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:o,elements:[]}],styleModifications:[]}}function $i(o,e){let t=new Set,n=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(Ld(s)?Fd(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)&&n(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,l]of Object.entries(i))r(l,d,a+1)}};for(let i of o)r(i.toolInput);return[...t]}function ao(o){return o?Math.ceil(o.length/4):0}function Oi(o,e,t,n,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 ${o}.`,"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=yn(n),d=Di(r,i),l=[s,a,d].filter(Boolean).join(`
16
+ `);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:ao(s),memoryEstimatedTokens:ao(a),imprintEstimatedTokens:ao(d),totalEstimatedTokens:ao(l)}}}function Di(o,e){return o?Gt(o,{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 Tn(o){if(!o)return;if(o.decision==="recognize")return[o.explanationId];let e=[...new Set([...o.usedExplanationIds??[],...o.appliedExplanationIds??[]])];return e.length?e:void 0}function Dd(o,e){let t=e.flatMap((n,r)=>{let i=o[r];return i?[{packetId:`ambient:${n}`,proposalId:n,claim:i.claim.trim(),proposedKind:i.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:n}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var eo=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 Yn(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([vi(e)])}async prepare(e){if(e.executionOwner===ar)return{status:"managed_by_bridge",protocolVersion:Mt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let y=Si(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Mt,threadId:n.threadId,jobId:n.jobId,...y}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${_d()}`,[vi(e.sessionId)]));let i=Od(e.sessionId,e.turnId),s=r.messages.find(y=>y.jobId===i&&y.role==="human"),a=bi(e.prompt),d=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),l=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(y=>y.role==="assistant"&&y.imprintSummary?.grounding&&!y.imprintSummary.resolvedAction?[y.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}:{},...l?{imprintContext:l}:{}});let v={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:d,imprintContext:l,events:[]};this.turns.set(t,v);let S=Si(e.sessionId,r.id,i,d,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Mt,threadId:r.id,jobId:i,...S}}async recordEvent(e){if(e.executionOwner===ar)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(n=>n.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=xi(t.events,this.options.projectRoot).length>0,s=Ut(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:Tn(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:Tn(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(l=>l.storeId&&l.memoryId?[[`${l.storeId}:${l.id}`,l.memoryId]]:[]))}).catch(()=>{}),a={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...r?{semanticCandidates:r}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Tn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else{let l="imprint mutation failed admission or produced no durable change";a={receipt:{status:"rejected",reason:l},imprintAssessment:{state:"invalid",reason:l},imprintUsedExplanationIds:Tn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}}catch(d){let l=d instanceof Error?d.message:"imprint mutation failed";a={receipt:{status:"rejected",reason:l},imprintAssessment:{state:"invalid",reason:l},imprintUsedExplanationIds:Tn(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===ar)return{status:"managed_by_bridge",protocolVersion:Mt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Mt};let r=(await this.options.threadStore.getThread(t.threadId))?.messages.find(u=>u.role==="assistant"&&u.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:Mt,threadId:t.threadId,jobId:t.jobId};let i=xi(t.events,this.options.projectRoot),s=i.length>0,a=t.assessmentEvaluation?.imprintSummary,d=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},l=t.assessmentEvaluation?.imprintUsedExplanationIds,v=t.assessmentEvaluation?.imprintAppliedExplanationIds,S=s?"completed":"no_change",y=Sn({changedFiles:i}),k={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(u=>u.toolName),turn:{phase:"complete",orientation:[],result:y},result:y,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:l,imprintAppliedExplanationIds:v};await this.options.threadStore.appendMessage(t.threadId,k);let T=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:S,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(u=>u.id),imprintAssessment:d}),g=Dd(t.assessment?.semanticCandidates??[],T.proposalIds);return g&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:g}),{status:"completed",protocolVersion:Mt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=bi(e.query),n=await this.knowledgeViewReader.memoryContext(e.knowledgeView,t,e.subjectHints??[]),r=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints});return{memoryContext:n,imprintContext:r,formattedContext:[fn(n),Ti(r,e.query)].filter(Boolean).join(`
20
- `)}}};import{spawn as Nd}from"child_process";import{createInterface as Bd}from"readline";function kn(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
21
-
22
- ${t}`:t;return o.push(n),n}var Jd=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"]),ki=1e5;function qd(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Jd.has(t))return;let n;if(o.name==="Write"&&typeof o.input?.content=="string"?n=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(n=o.input.new_string),!!n)return n.length>ki?n.slice(0,ki)+`
23
- \u2026[truncated]`:n}function to(o,e){let{prompt:t,projectRoot:n,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs:S=3e5,onEvent:y}=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)),l&&k.push("--model",l),v&&k.push("--effort",v);for(let u of s)k.push("--allowedTools",u);let T=Nd(a,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),g=new Promise(u=>{let I,f=[],p=[],j=[],h=!1,m="",M,D,P=!1,A=setTimeout(()=>{P=!0,T.kill("SIGTERM"),setTimeout(()=>{try{T.kill("SIGKILL")}catch{}},5e3)},S),Q=Bd({input:T.stdout}),z=new Set;Q.on("line",G=>{if(G.trim())try{let W=JSON.parse(G);W.session_id&&!I&&(I=W.session_id);let ue=W.type??(W.event?.type?`event.${W.event.type}`:"unknown");if(z.add(ue),W.type==="result"&&W.result&&f.length===0){let X=typeof W.result=="string"?W.result:"";if(X){let re=kn(f,X);re&&y?.({type:"delta",jobId:o,text:re},o)}}if(W.type==="assistant"&&Array.isArray(W.message?.content)){typeof W.error=="string"&&(M=W.error);for(let X of W.message.content){if(X.type==="text"&&X.text){let re=kn(f,X.text);re&&y?.({type:"delta",jobId:o,text:re},o)}if(X.type==="tool_use"&&X.name){let re=X.input?.file_path||X.input?.path||void 0,x=qd(X);if(y?.({type:"tool_use",jobId:o,tool:X.name,...re?{file:re}:{},...x?{content:x}:{}},o),X.name==="Edit"&&X.input?.file_path){let O={tool:"Edit",file_path:X.input.file_path,old_string:X.input.old_string,new_string:X.input.new_string,replace_all:X.input.replace_all};p.push(O),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:O.file_path,oldString:typeof O.old_string=="string"?O.old_string:void 0,newString:typeof O.new_string=="string"?O.new_string:void 0,replaceAll:typeof O.replace_all=="boolean"?O.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(p.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:X.input.file_path,content:typeof X.input.content=="string"?X.input.content:void 0}))}X.type==="thinking"&&X.thinking&&y?.({type:"thinking",jobId:o,text:X.thinking},o)}}W.type==="result"&&W.is_error===!0&&(h=!0,typeof W.error=="string"&&(M=W.error),typeof W.result=="string"&&(D=W.result)),W.type==="user"&&W.tool_use_result?.file?.filePath&&y?.({type:"tool_use",jobId:o,tool:"Read",file:W.tool_use_result.file.filePath},o)}catch{}});let E=[];T.stderr?.on("data",G=>{E.push(G.toString())}),T.on("close",G=>{if(clearTimeout(A),Q.close(),f.length===0&&z.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...z].join(", ")}`),P)h=!0,m=`Timed out after ${Math.round(S/6e4)} minutes`;else if(G!==0&&G!==null){h=!0;let ue=E.join("").trim(),X=f.join("").trim(),re=f.length===0&&z.size>0?` (no text captured, event types: ${[...z].join(", ")})`:"";m=ue||D||X||`Claude process exited with code ${G}${re}`}h&&!m&&D&&(m=D);let W=Ld(m,M);u({sessionId:I,text:f.join(""),success:!h,error:h?W.message:void 0,errorCode:h?W.code:void 0,recoverableError:h?W.recoverable:void 0,fileEdits:p.length>0?p:void 0,editEvents:j.length>0?j:void 0})}),T.on("error",G=>{clearTimeout(A),h=!0,m=G.message,u({sessionId:I,text:f.join(""),success:!1,error:m,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:p.length>0?p:void 0,editEvents:j.length>0?j:void 0})})});return{process:T,result:g}}function Ld(o,e){let t=o.trim()||"Claude CLI failed",n=`${e??""} ${t}`.toLowerCase();return n.includes("authentication_failed")||n.includes("not logged in")||n.includes("please run /login")||n.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:n.includes("model")&&(n.includes("not found")||n.includes("unknown")||n.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as Fd,spawnSync as Ci}from"child_process";import{readFileSync as zd,statSync as Gd}from"fs";import{basename as Wd,extname as Vd,isAbsolute as Kd,relative as $i,resolve as Hd}from"path";import{createInterface as Qd}from"readline";function oo(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:void 0}function no(o,e){for(let t of o)if(t)for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Ri(o){let e=oo(o);if(e)return e;if(typeof o=="string")try{return oo(JSON.parse(o))}catch{return}}function dr(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Ud(o,e,t,n){return o!=="node_repl"||e!=="js"?!1:n&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(n)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function Pi(o){let e=oo(o)??{},t=oo(e.invocation),n=Ri(e.arguments)??Ri(t?.arguments),r=no([e,t],["server","server_name"]),i=no([e,t],["tool","tool_name","name"]),s=no([n,e,t],["title","display_name","description"]),a=no([n],["code","script"]),d=Ud(r,i,s,a)?"Browser":r?dr(r):i?dr(i):"MCP",l=i&&dr(i),v=s??l,S=v&&v!==d?`${d}: ${v}`:d;return{tool:d,...v?{content:v}:{},telemetryLabel:S}}function Ai(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var ji=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"]),cr=2e5,Xd=1e5,Oi=2e5;function Di(o){let e=Wd(o).toLowerCase(),t=Vd(o).toLowerCase();return ji.has(t)||ji.has(e)}function Rn(o,e){let t=Kd(e)?e:Hd(o,e),n=$i(o,t);return n===""||n.startsWith("..")?null:t}function ro(o,e){if(!Di(e))return;let t=Rn(o,e);if(t)try{let n=Gd(t);return n.isFile()?n.size>cr?{exists:!0,truncated:!0}:{exists:!0,content:zd(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Yd(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function Zd(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Mi(o){return Yd(o,["patch","diff","unifiedDiff","unified_diff"])}function lr(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Ei(o,e){let t=Ci("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Oi+65536});return t.status!==0?null:t.stdout??""}function ec(o){let e=new Set;for(let t of o.split(`
24
- `)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let r=n.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function _i(o){let e=Ei(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Ei(o,["diff","--no-ext-diff","HEAD","--"])??"",n=lr(t,Oi);return{status:e,changedFiles:ec(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function tc(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function nc(o,e){if(!Di(e))return;let t=Rn(o,e);if(!t)return;let n=$i(o,t);if(n===""||n.startsWith(".."))return;let r=Ci("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:cr+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=lr(i,cr);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function oc(o,e,t){return e.map(n=>{let r=t.has(n)?t.get(n):nc(o,n),i=ro(o,n);return{filePath:n,...r?{before:r}:{},...i?{after:i}:{}}})}function io(o,e){let{prompt:t,projectRoot:n,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(i){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let k of l)v.push("-c",k);s&&v.push("-m",s),v.push(i),v.push(t),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let k of l)v.push("-c",k);s&&v.push("-m",s),v.push(t),r&&v.push("--image",r)}let S=Fd("codex",v,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:o}}),y=new Promise(k=>{let T,g=[],u=[],I=[],f=new Map,p=new Map,j=!1,h="",m=Qd({input:S.stdout}),M=new Set;m.on("line",P=>{if(P.trim())try{let A=JSON.parse(P),Q=A.type??"unknown";if(M.add(Q),Q==="thread.started"&&A.thread_id&&!T&&(T=A.thread_id),(Q==="item.agentMessage.delta"||Q==="item/agentMessage/delta")&&A.delta?.text&&(g.push(A.delta.text),a?.({type:"delta",jobId:o,text:A.delta.text},o)),(Q==="item.reasoning.delta"||Q==="item/reasoning/delta")&&A.delta?.text&&a?.({type:"thinking",jobId:o,text:A.delta.text},o),(Q==="item.started"||Q==="item/started")&&A.item){let z=A.item.type;if(z==="command_execution"){let E=A.item.command,G=E?Ai(E):void 0,W=_i(n),ue=new Map;for(let re of W?.changedFiles??[])ue.set(re,ro(n,re));typeof A.item.id=="string"&&p.set(A.item.id,{...E?{rawCommand:E}:{},...G?{command:G}:{},...W?{beforeWorktree:W}:{},beforeSnapshots:ue});let X=G?`Bash: ${G.split(`
25
- `)[0].slice(0,80)}`:"Bash";u.push(X),a?.({type:"tool_use",jobId:o,tool:"Bash",...G?{content:G}:{}},o)}else if(z==="file_change"){let E=A.item.filename||A.item.path;E&&!f.has(E)&&f.set(E,ro(n,E)),u.push(E?`Edit ${E.split("/").pop()}`:"Edit");let G=E?Rn(n,E)??E:void 0;a?.({type:"tool_use",jobId:o,tool:"Edit",...G?{file:G}:{}},o)}else if(z==="file_read"){let E=A.item.filename||A.item.path;u.push(E?`Read ${E.split("/").pop()}`:"Read");let G=E?Rn(n,E)??E:void 0;a?.({type:"tool_use",jobId:o,tool:"Read",...G?{file:G}:{}},o)}else if(z==="web_search")u.push("WebSearch"),a?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(z==="mcp_tool_call"){let E=Pi(A.item);u.push(E.telemetryLabel),a?.({type:"tool_use",jobId:o,tool:E.tool,...E.content?{content:E.content}:{}},o)}}if((Q==="item.completed"||Q==="item/completed")&&A.item){if(A.item.type==="agent_message"){let z=A.item.text;if(typeof z=="string"&&z){let E=kn(g,z);E&&a?.({type:"delta",jobId:o,text:E},o)}}else if(A.item.type==="reasoning"){let z=A.item.text;typeof z=="string"&&z&&a?.({type:"thinking",jobId:o,text:z},o)}else if(A.item.type==="file_change"&&Array.isArray(A.item.changes))for(let z of A.item.changes){let E=z.path||z.filename,G=z.kind==="add"?"Write":"Edit";if(E){u.push(`${G} ${E.split("/").pop()}`);let W=Rn(n,E)??E;a?.({type:"tool_use",jobId:o,tool:G,file:W},o);let ue=z,X=typeof ue.kind=="string"?ue.kind:void 0,re=Zd(X),x=f.get(E),O=ro(n,E);I.push({sequence:I.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:re,filePath:E,...x?{before:x}:{},...O?{after:O}:{},...Mi(ue)?{patch:Mi(ue)}:{},...X?{rawKind:X}:{}}),f.set(E,O)}}else if(A.item.type==="command_execution"){let z=typeof A.item.id=="string"?A.item.id:void 0,E=z?p.get(z):void 0,G=typeof A.item.command=="string"?A.item.command:E?.rawCommand,W=G?Ai(G):E?.command,ue=_i(n);if(tc(E?.beforeWorktree,ue)){let X=[...new Set([...E?.beforeWorktree?.changedFiles??[],...ue?.changedFiles??[]])],re=typeof A.item.aggregated_output=="string"?lr(A.item.aggregated_output,Xd):void 0,x=typeof A.item.exit_code=="number"?A.item.exit_code:A.item.exit_code===null?null:void 0,O=typeof A.item.status=="string"?A.item.status:void 0;I.push({sequence:I.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...G?{rawCommand:G}:{},...W?{command:W}:{},...x!==void 0?{exitCode:x}:{},...O?{status:O}:{},...re?{output:re.text}:{},...re?.truncated?{outputTruncated:!0}:{},...E?.beforeWorktree?{beforeWorktree:E.beforeWorktree}:{},...ue?{afterWorktree:ue}:{},...X.length>0?{touchedFiles:oc(n,X,E?.beforeSnapshots??new Map)}:{}})}z&&p.delete(z)}}Q==="turn.failed"&&(j=!0,h=A.error?.message||A.message||"Turn failed")}catch{}});let D=[];S.stderr?.on("data",P=>{D.push(P.toString())}),S.on("close",P=>{m.close(),g.length===0&&M.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...M].join(", ")}`),P!==0&&P!==null&&(j=!0,h=D.join("")||`Codex process exited with code ${P}`),k({sessionId:T,text:g.join(""),success:!j,error:j?h:void 0,editEvents:I.length>0?I:void 0,toolsUsed:u.length>0?u:void 0})}),S.on("error",P=>{j=!0,h=P.message,k({sessionId:T,text:g.join(""),success:!1,error:h,editEvents:I.length>0?I:void 0,toolsUsed:u.length>0?u:void 0})})});return{process:S,result:y}}import{spawn as rc}from"child_process";import{createInterface as ic}from"readline";function Ni(o,e){let t=o.trim()||"Copilot CLI failed",n=t.toLowerCase();return n.includes("no authentication information")||n.includes("not authenticated")||n.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`."}:n.includes("model")&&(n.includes("not available")||n.includes("not found")||n.includes("disabled")||n.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:n.includes("mcp")&&(n.includes("blocked")||n.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."}:n.includes("permission")||n.includes("denied")||n.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function Bi(o,e){let{prompt:t,projectRoot:n,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),i&&l.push("--model",i),l.push("-p",t);let v=rc(d,l,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),S=new Promise(y=>{let k,T=[],g=[],u=!1,I="",f=!1,p=setTimeout(()=>{f=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},s),j=ic({input:v.stdout}),h=new Set,m=[];j.on("line",D=>{if(D.trim())try{let P=JSON.parse(D),A=An(P);h.add(A),m.length<5&&ac(A)&&m.push(D.slice(0,800));let Q=Pn(P,["sessionId","session_id","id"],["session","conversation","thread"]);Q&&!k&&(k=Q);let z=sc(P,T.length===0);z&&(T.push(z),a?.({type:"delta",jobId:o,text:z},o));let E=dc(P);E&&a?.({type:"thinking",jobId:o,text:E},o);let G=cc(P);G&&(g.push(G.label),a?.({type:"tool_use",jobId:o,tool:G.tool,...G.file?{file:G.file}:{},...G.content?{content:G.content}:{}},o));let W=lc(P);W&&(u=!0,I=W)}catch{}});let M=[];v.stderr?.on("data",D=>{M.push(D.toString())}),v.on("close",D=>{clearTimeout(p),j.close(),T.length===0&&h.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...h].join(", ")}`),m.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${m.join(`
26
- `)}`)),f?(u=!0,I=`Timed out after ${Math.round(s/6e4)} minutes`):D!==0&&D!==null&&(u=!0,I=M.join("").trim()||I||`Copilot process exited with code ${D}`);let P=u?Ni(I,i):null;y({sessionId:k,text:T.join(""),success:!u,error:P?.message,errorCode:P?.code,recoverableError:P?.recoverable,provider:"copilot",toolsUsed:g.length>0?g:void 0})}),v.on("error",D=>{clearTimeout(p);let P=Ni(D.message,i);y({sessionId:k,text:T.join(""),success:!1,error:P.message,errorCode:P.code,recoverableError:P.recoverable,provider:"copilot",toolsUsed:g.length>0?g:void 0})})});return{process:v,result:S}}function An(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function sc(o,e=!1){let t=An(o).toLowerCase(),n=o.update,r=n?.content;if(n?.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 We(o.delta)??We(o.content)??We(o.message);if(t==="assistant.message"&&e)return We(o.message)??We(o.content)??We(o);if(t==="result"&&e)return We(o.result)??We(o.output)??We(o.message)??We(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&pr(o))return o.text;if(typeof o.message=="string"&&pr(o))return o.message;if(typeof o.delta=="string"&&pr(o))return o.delta}function We(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(We).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let n=We(e[t]);if(n)return n}}function ac(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function dc(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function cc(o){let e=Pn(o,["tool","toolName","tool_name","name"]),t=Pn(o,["command","cmd"]),n=Pn(o,["file","path","filename","filePath"]),r=An(o);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:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(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} ${n.split("/").pop()}`,file:n}}}function lc(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&An(o).toLowerCase().includes("error"))return o.message}function Pn(o,e,t=[]){for(let n of e){let r=o[n];if(typeof r=="string")return r}for(let[n,r]of Object.entries(o)){if(!r||typeof r!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let i=Pn(r,e);if(i)return i}}function pr(o){let e=An(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readFile as pc,readdir as uc}from"fs/promises";import{join as ur}from"path";var so=class{constructor(e){let t=ur(e,".popmelt");this.decisionsDir=ur(t,"decisions")}async listDecisionIds(){try{return(await uc(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 pc(ur(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as mc,randomUUID as fc}from"crypto";import{mkdir as mr,readFile as Ji,readdir as qi,rename as ao,stat as Li,unlink as co,writeFile as lo}from"fs/promises";import{extname as hc,join as Qe}from"path";var gc=10080*60*1e3,yc=600*1e3,Ic=3600*1e3;function wc(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function vc(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var po=class{constructor(e){this.draftsDir=Qe(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Qe(e,".popmelt","artifacts","thread-media")}async stage(e){let t=fc(),n=wc(e.mimeType),r=`${t}${n}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:vc(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await mr(this.draftsDir,{recursive:!0});let a=Qe(this.draftsDir,r),d=Qe(this.draftsDir,`${t}.json`),l=`${a}.part`,v=`${d}.part`;return await lo(l,e.data),await ao(l,a),await lo(v,JSON.stringify(s,null,2)),await ao(v,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let r=await this.readManifest(n.id);if(!r)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(r.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let i=Qe(this.draftsDir,r.contentFile),s=await Ji(i),a=mc("sha256").update(s).digest("hex"),d=Qe(this.mediaDir,`${a}${hc(r.contentFile)||".bin"}`);await mr(this.mediaDir,{recursive:!0});try{await Li(d)}catch{let l=`${d}.part`;await lo(l,s),await ao(l,d)}(t[n.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 qi(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let r=Qe(this.draftsDir,n);if(n.endsWith(".part")){let a=await Li(r).catch(()=>null);a&&e-a.mtimeMs>Ic&&await co(r).catch(()=>{});return}if(!n.endsWith(".json"))return;let i=await this.readManifest(n.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>yc:e-i.lastSeenAt>gc)||await Promise.all([co(r).catch(()=>{}),co(Qe(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await qi(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>co(Qe(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Ji(Qe(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await mr(this.draftsDir,{recursive:!0});let t=Qe(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await lo(n,JSON.stringify(e,null,2)),await ao(n,t)}};import{randomUUID as bc}from"crypto";var jn="<orientation>",lt="</orientation>";function en(o,e){let t=e;for(;t<o.length&&/\s/.test(o[t]);)t++;if(t>=o.length)return{status:"incomplete",start:t};if(o[t]!=="{")return{status:"invalid",start:t};let n=0,r=!1,i=!1;for(let s=t;s<o.length;s++){let a=o[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"')r=!0;else if(a==="{")n++;else if(a==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function Ui(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function Fi(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(jn,t);if(n<0){Ui(e,o.slice(t));break}Ui(e,o.slice(t,n));let r=n+jn.length,i=en(o,r);if(i.status!=="complete"){let a=o.indexOf(lt,r);if(a>=0){t=a+lt.length;continue}t=r;continue}e.push({kind:"orientation",json:o.slice(i.start,i.end)}),t=i.end;let s=t;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(lt,s)&&(t=s+lt.length)}return e}var tn="<imprint-use>",uo="</imprint-use>";function xc(o){let e=Math.min(o.length,tn.length-1);for(let t=e;t>0;t--)if(tn.startsWith(o.slice(-t)))return t;return 0}function zi(o,e,t,n,r=Date.now()){if(!o||typeof o!="object"||Array.isArray(o))return null;let i=o,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let l=e?.explanations.find(v=>v.id===d);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return a.length===0?null:{id:bc(),jobId:t,sequence:n,timestamp:r,explanations:a}}var mo=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(n=>!this.explanationIds.has(n.id));if(t.length===0)return null;for(let n of t)this.explanationIds.add(n.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(uo.startsWith(l)&&l.length<uo.length||(l.startsWith(uo)&&(this.buffer=this.buffer.slice(d+uo.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(tn);if(r<0){let d=xc(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+tn.length,s=en(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=zi(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let l=this.takeNewExplanations(d);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",r=0;for(;r<e.length;){let i=e.indexOf(tn,r);if(i<0){n+=e.slice(r);break}n+=e.slice(r,i);let s=i+tn.length,a=en(e,s);if(a.status!=="complete"){r=s;continue}try{let v=zi(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(v){let S=this.takeNewExplanations(v);S&&t.push(S)}}catch{}let l=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+l}return{visibleText:n.trim(),usages:t}}};function wt(o,e=240){if(!o)return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function nn(o){return o?[wt(o.selector,400),wt(o.context,200),wt(o.reactComponent,120),wt(o.textContent)].filter(e=>!!e):[]}function fr(o){return[...new Set(o.filter(e=>!!e))]}function Gi(o,e){return fr([...e,...o.annotations.flatMap(t=>[wt(t.pathname,200),wt(t.linkedSelector,400),...t.elements.flatMap(nn)]),...o.styleModifications.flatMap(t=>nn(t.element)),...(o.textModifications??[]).flatMap(t=>nn(t.element)),...(o.domModifications??[]).flatMap(t=>[...nn(t.element),...nn(t.sourceElement)])])}function Wi(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return fr(t?[...e,...t.annotations.flatMap(n=>[wt(n.pathname,200),wt(n.linkedSelector,400),...n.elements.flatMap(nn)])]:e)}var fo=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,n=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:t,createdAt:r?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):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[n,r]of this.leases)r.expiresAt>e||(this.leases.delete(n),t.push(n));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 Vi}from"crypto";import{mkdir as hr,readFile as gr,writeFile as ho}from"fs/promises";import{dirname as yr,join as on}from"path";var Xe="[ProjectionWorker]",Sc={version:1,runs:[]},Tc={version:1,updatedAt:0,proposals:[]},kc=12;function Rc(o){return Array.isArray(o)?o.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 Ki(o){let e=[];for(let t of o){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Xe} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Xe} Rule count ${e.length} exceeds cap of 30`),e}function Pc(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Ac(o,e,t){let n=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let T of i){if(!T||typeof T!="object")continue;let g=T.sources;if(Array.isArray(g))for(let u of g)typeof u=="string"&&n.has(u)&&r.add(u)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},a=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(t?.rules)?t.rules:[],l=i.filter(T=>{if(!T||typeof T!="object")return!1;let g=T.id,u=typeof g=="string"?d.find(I=>I&&typeof I=="object"&&I.id===g):void 0;return JSON.stringify(u)!==JSON.stringify(T)}).length,v=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},S=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},y=Object.keys(s).filter(T=>JSON.stringify(s[T])!==JSON.stringify(v[T])).length,k=Object.keys(a).filter(T=>JSON.stringify(a[T])!==JSON.stringify(S[T])).length;return{ruleCount:l,tokenSectionCount:y,componentCount:k,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(T=>!r.has(T))}}function jc(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Mc(o,e,t){let n=o[e];if(n&&typeof n=="object")return n;let r=typeof t=="number"?[]:{};return o[String(e)]=r,r}function go(o,e,t){let n=o;for(let i=0;i<e.length-1;i++)n=Mc(n,e[i],e[i+1]);let r=e[e.length-1];n[String(r)]=jc(t)}function Hi(o,e){let t=o;for(let r=0;r<e.length-1;r++){let i=t[String(e[r])];if(!i||typeof i!="object")return;t=i}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function Ec(o,e){if(!o)return{exists:!1};let t=o;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function _c(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Qi(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=Ec(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?_c(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var yo=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=on(e,".popmelt");this.runsPath=on(n,"projection-runs.json"),this.legacyRunsPath=on(n,"materialization-runs.json"),this.proposalsPath=on(n,"projection-queue.json"),this.legacyProposalsPath=on(n,"model-proposals.json"),this.modelPath=on(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await gr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Rc(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let r=n.key.split(".");n.value===null?Hi(t,r):go(t,r,n.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(kc),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 n=await this.selectUnprojectedPatternDecisions(),r=n.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(T=>T.id);console.log(`${Xe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=Dc(r,s),d=Pc(r,n.totalCandidateDecisionCount,a);t=Vi().slice(0,8);let l={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(l);let v=!0,S,y,k;try{let T=`projection-${Date.now()}`,{provider:g,result:u}=this.spawnModelAgent(T,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:g},await this.persistRun(l);let I=await u;if(!I.success)v=!1,S=I.error,console.error(`${Xe} ${g} spawn error:`,S);else{let f=Oc(I.text,i);if(f){let p=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of f)go(p,m.path,m.value);Array.isArray(p.rules)&&(p.rules=Ki(p.rules));let j=Ac(p,i,s);if(f){let m=[...new Set(f.flatMap(M=>M.decisionIds))];j.coveredDecisionIds=m,j.uncoveredDecisionIds=i.filter(M=>!m.includes(M))}y=j;let h=await this.createModelProposal({decisionIds:i,proposedModel:p,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:g,model:e.model??this.options.model,outputStats:y,changes:f});k=h.id,console.log(`${Xe} Created model proposal ${h.id} for ${i.length} decision(s)`)}else v=!1,S="No valid bounded <model-changes> block found in response",console.error(`${Xe} ${S}`)}}catch(T){v=!1,S=T instanceof Error?T.message:String(T),console.error(`${Xe} Error:`,S)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:S,outputStats:y,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:v,error:S}),{processedIds:i,success:v,error:S,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ki(e.rules)),await ho(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Xe} 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 hr(yr(this.runsPath),{recursive:!0}),await ho(this.runsPath,JSON.stringify(t,null,2)),t):{...Sc,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??{...Tc,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(n);for(let s of r.changes??[])go(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,r)=>r.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,r)=>n.createdAt-r.createdAt||n.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,t,n,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?Hi(s,d.path):go(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:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:Vi().slice(0,8),status:"pending",title:Cc(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"}.`:$c(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()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(r=>r.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),r=null;return n.proposals=n.proposals.map(i=>i.id!==e?i:(r={...i,...t,updatedAt:Date.now()},r)),r?(n.updatedAt=Date.now(),await this.persistModelProposals(n),r):null}async persistModelProposals(e){try{await hr(yr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...r})=>r)};await ho(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(r=>r.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await hr(yr(this.runsPath),{recursive:!0}),await ho(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await gr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await gr(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,r){let i=n.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...io(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Un(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Xe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...to(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Cc(o){let t=(Array.isArray(o.rules)?o.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 n=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function $c(o,e){let t=Array.isArray(o.rules)?o.rules.length:0,n=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Oc(o,e){let t=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let r=new Set(e),i=n.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(S=>typeof S=="string"||typeof S=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(S=>typeof S=="string"&&r.has(S)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===n.length?i:null}catch{return null}}function Dc(o,e){let t=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
19
+ `)}function Pn(o){if(!o)return;if(o.decision==="recognize")return[o.explanationId];let e=[...new Set([...o.usedExplanationIds??[],...o.appliedExplanationIds??[]])];return e.length?e:void 0}function zd(o,e){let t=e.flatMap((n,r)=>{let i=o[r];return i?[{packetId:`ambient:${n}`,proposalId:n,claim:i.claim.trim(),proposedKind:i.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:n}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var co=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 so(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([_i(e)])}async prepare(e){if(e.executionOwner===pr)return{status:"managed_by_bridge",protocolVersion:Ct};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let g=Oi(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Ct,threadId:n.threadId,jobId:n.jobId,...g}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${qd()}`,[_i(e.sessionId)]));let i=Ud(e.sessionId,e.turnId),s=r.messages.find(g=>g.jobId===i&&g.role==="human"),a=Ci(e.prompt),d=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),l=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}:{},...l?{imprintContext:l}:{}});let w={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:d,imprintContext:l,events:[]};this.turns.set(t,w);let b=Oi(e.sessionId,r.id,i,d,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Ct,threadId:r.id,jobId:i,...b}}async recordEvent(e){if(e.executionOwner===pr)return{status:"ignored"};let t=this.turns.get(this.key(e.sessionId,e.turnId));return t?e.toolUseId&&t.events.some(n=>n.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=$i(t.events,this.options.projectRoot).length>0,s=zt(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:Pn(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:Pn(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(l=>l.storeId&&l.memoryId?[[`${l.storeId}:${l.id}`,l.memoryId]]:[]))}).catch(()=>{}),a={receipt:{status:"committed",transactionId:d.transactionId,changes:d.changes,...r?{semanticCandidates:r}:{}},imprintSummary:d,imprintAssessment:{state:"mutated"},imprintUsedExplanationIds:Pn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds};else{let l="imprint mutation failed admission or produced no durable change";a={receipt:{status:"rejected",reason:l},imprintAssessment:{state:"invalid",reason:l},imprintUsedExplanationIds:Pn(s.draft),imprintAppliedExplanationIds:s.draft.appliedExplanationIds}}}catch(d){let l=d instanceof Error?d.message:"imprint mutation failed";a={receipt:{status:"rejected",reason:l},imprintAssessment:{state:"invalid",reason:l},imprintUsedExplanationIds:Pn(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===pr)return{status:"managed_by_bridge",protocolVersion:Ct};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Ct};let r=(await this.options.threadStore.getThread(t.threadId))?.messages.find(u=>u.role==="assistant"&&u.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:Ct,threadId:t.threadId,jobId:t.jobId};let i=$i(t.events,this.options.projectRoot),s=i.length>0,a=t.assessmentEvaluation?.imprintSummary,d=t.assessmentEvaluation?.imprintAssessment??{state:"not_applicable"},l=t.assessmentEvaluation?.imprintUsedExplanationIds,w=t.assessmentEvaluation?.imprintAppliedExplanationIds,b=s?"completed":"no_change",g=Rn({changedFiles:i}),k={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(u=>u.toolName),turn:{phase:"complete",orientation:[],result:g},result:g,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:l,imprintAppliedExplanationIds:w};await this.options.threadStore.appendMessage(t.threadId,k);let x=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:b,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(u=>u.id),imprintAssessment:d}),h=zd(t.assessment?.semanticCandidates??[],x.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:Ct,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Ci(e.query),n=await this.knowledgeViewReader.memoryContext(e.knowledgeView,t,e.subjectHints??[]),r=await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.query,subjectHints:e.subjectHints});return{memoryContext:n,imprintContext:r,formattedContext:[yn(n),Di(r,e.query)].filter(Boolean).join(`
20
+ `)}}};import{spawn as Gd}from"child_process";import{createInterface as Wd}from"readline";function An(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
21
+
22
+ ${t}`:t;return o.push(n),n}var Kd=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"]),Ni=1e5;function Vd(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Kd.has(t))return;let n;if(o.name==="Write"&&typeof o.input?.content=="string"?n=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(n=o.input.new_string),!!n)return n.length>Ni?n.slice(0,Ni)+`
23
+ \u2026[truncated]`:n}function lo(o,e){let{prompt:t,projectRoot:n,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:d,model:l,reasoningEffort:w,timeoutMs:b=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)),l&&k.push("--model",l),w&&k.push("--effort",w);for(let u of s)k.push("--allowedTools",u);let x=Gd(a,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(u=>{let y,I=[],p=[],A=[],m=!1,f="",j,$,R=!1,_=setTimeout(()=>{R=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},b),X=Wd({input:x.stdout}),G=new Set;X.on("line",L=>{if(L.trim())try{let W=JSON.parse(L);W.session_id&&!y&&(y=W.session_id);let ie=W.type??(W.event?.type?`event.${W.event.type}`:"unknown");if(G.add(ie),W.type==="result"&&W.result&&I.length===0){let Q=typeof W.result=="string"?W.result:"";if(Q){let ee=An(I,Q);ee&&g?.({type:"delta",jobId:o,text:ee},o)}}if(W.type==="assistant"&&Array.isArray(W.message?.content)){typeof W.error=="string"&&(j=W.error);for(let Q of W.message.content){if(Q.type==="text"&&Q.text){let ee=An(I,Q.text);ee&&g?.({type:"delta",jobId:o,text:ee},o)}if(Q.type==="tool_use"&&Q.name){let ee=Q.input?.file_path||Q.input?.path||void 0,v=Vd(Q);if(g?.({type:"tool_use",jobId:o,tool:Q.name,...ee?{file:ee}:{},...v?{content:v}:{}},o),Q.name==="Edit"&&Q.input?.file_path){let E={tool:"Edit",file_path:Q.input.file_path,old_string:Q.input.old_string,new_string:Q.input.new_string,replace_all:Q.input.replace_all};p.push(E),A.push({sequence:A.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:E.file_path,oldString:typeof E.old_string=="string"?E.old_string:void 0,newString:typeof E.new_string=="string"?E.new_string:void 0,replaceAll:typeof E.replace_all=="boolean"?E.replace_all:void 0})}else Q.name==="Write"&&Q.input?.file_path&&(p.push({tool:"Write",file_path:Q.input.file_path,content:Q.input.content}),A.push({sequence:A.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:Q.input.file_path,content:typeof Q.input.content=="string"?Q.input.content:void 0}))}Q.type==="thinking"&&Q.thinking&&g?.({type:"thinking",jobId:o,text:Q.thinking},o)}}W.type==="result"&&W.is_error===!0&&(m=!0,typeof W.error=="string"&&(j=W.error),typeof W.result=="string"&&($=W.result)),W.type==="user"&&W.tool_use_result?.file?.filePath&&g?.({type:"tool_use",jobId:o,tool:"Read",file:W.tool_use_result.file.filePath},o)}catch{}});let M=[];x.stderr?.on("data",L=>{M.push(L.toString())}),x.on("close",L=>{if(clearTimeout(_),X.close(),I.length===0&&G.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...G].join(", ")}`),R)m=!0,f=`Timed out after ${Math.round(b/6e4)} minutes`;else if(L!==0&&L!==null){m=!0;let ie=M.join("").trim(),Q=I.join("").trim(),ee=I.length===0&&G.size>0?` (no text captured, event types: ${[...G].join(", ")})`:"";f=ie||$||Q||`Claude process exited with code ${L}${ee}`}m&&!f&&$&&(f=$);let W=Hd(f,j);u({sessionId:y,text:I.join(""),success:!m,error:m?W.message:void 0,errorCode:m?W.code:void 0,recoverableError:m?W.recoverable:void 0,fileEdits:p.length>0?p:void 0,editEvents:A.length>0?A:void 0})}),x.on("error",L=>{clearTimeout(_),m=!0,f=L.message,u({sessionId:y,text:I.join(""),success:!1,error:f,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:p.length>0?p:void 0,editEvents:A.length>0?A:void 0})})});return{process:x,result:h}}function Hd(o,e){let t=o.trim()||"Claude CLI failed",n=`${e??""} ${t}`.toLowerCase();return n.includes("authentication_failed")||n.includes("not logged in")||n.includes("please run /login")||n.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:n.includes("model")&&(n.includes("not found")||n.includes("unknown")||n.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as Xd,spawnSync as Gi}from"child_process";import{readFileSync as Yd,statSync as Zd}from"fs";import{basename as ec,extname as tc,isAbsolute as nc,relative as Wi,resolve as oc}from"path";import{createInterface as rc}from"readline";function uo(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:void 0}function po(o,e){for(let t of o)if(t)for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Bi(o){let e=uo(o);if(e)return e;if(typeof o=="string")try{return uo(JSON.parse(o))}catch{return}}function ur(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Qd(o,e,t,n){return o!=="node_repl"||e!=="js"?!1:n&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(n)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function Ji(o){let e=uo(o)??{},t=uo(e.invocation),n=Bi(e.arguments)??Bi(t?.arguments),r=po([e,t],["server","server_name"]),i=po([e,t],["tool","tool_name","name"]),s=po([n,e,t],["title","display_name","description"]),a=po([n],["code","script"]),d=Qd(r,i,s,a)?"Browser":r?ur(r):i?ur(i):"MCP",l=i&&ur(i),w=s??l,b=w&&w!==d?`${d}: ${w}`:d;return{tool:d,...w?{content:w}:{},telemetryLabel:b}}function qi(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var Li=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"]),mr=2e5,ic=1e5,Ki=2e5;function Vi(o){let e=ec(o).toLowerCase(),t=tc(o).toLowerCase();return Li.has(t)||Li.has(e)}function jn(o,e){let t=nc(e)?e:oc(o,e),n=Wi(o,t);return n===""||n.startsWith("..")?null:t}function mo(o,e){if(!Vi(e))return;let t=jn(o,e);if(t)try{let n=Zd(t);return n.isFile()?n.size>mr?{exists:!0,truncated:!0}:{exists:!0,content:Yd(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function sc(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function ac(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Fi(o){return sc(o,["patch","diff","unifiedDiff","unified_diff"])}function fr(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Ui(o,e){let t=Gi("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Ki+65536});return t.status!==0?null:t.stdout??""}function dc(o){let e=new Set;for(let t of o.split(`
24
+ `)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let r=n.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function zi(o){let e=Ui(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Ui(o,["diff","--no-ext-diff","HEAD","--"])??"",n=fr(t,Ki);return{status:e,changedFiles:dc(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function cc(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function lc(o,e){if(!Vi(e))return;let t=jn(o,e);if(!t)return;let n=Wi(o,t);if(n===""||n.startsWith(".."))return;let r=Gi("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:mr+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=fr(i,mr);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function pc(o,e,t){return e.map(n=>{let r=t.has(n)?t.get(n):lc(o,n),i=mo(o,n);return{filePath:n,...r?{before:r}:{},...i?{after:i}:{}}})}function fo(o,e){let{prompt:t,projectRoot:n,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,w=[];if(i){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(i),w.push(t),r&&w.push("--image",r)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(t),r&&w.push("--image",r)}let b=Xd("codex",w,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:o}}),g=new Promise(k=>{let x,h=[],u=[],y=[],I=new Map,p=new Map,A=!1,m="",f=rc({input:b.stdout}),j=new Set;f.on("line",R=>{if(R.trim())try{let _=JSON.parse(R),X=_.type??"unknown";if(j.add(X),X==="thread.started"&&_.thread_id&&!x&&(x=_.thread_id),(X==="item.agentMessage.delta"||X==="item/agentMessage/delta")&&_.delta?.text&&(h.push(_.delta.text),a?.({type:"delta",jobId:o,text:_.delta.text},o)),(X==="item.reasoning.delta"||X==="item/reasoning/delta")&&_.delta?.text&&a?.({type:"thinking",jobId:o,text:_.delta.text},o),(X==="item.started"||X==="item/started")&&_.item){let G=_.item.type;if(G==="command_execution"){let M=_.item.command,L=M?qi(M):void 0,W=zi(n),ie=new Map;for(let ee of W?.changedFiles??[])ie.set(ee,mo(n,ee));typeof _.item.id=="string"&&p.set(_.item.id,{...M?{rawCommand:M}:{},...L?{command:L}:{},...W?{beforeWorktree:W}:{},beforeSnapshots:ie});let Q=L?`Bash: ${L.split(`
25
+ `)[0].slice(0,80)}`:"Bash";u.push(Q),a?.({type:"tool_use",jobId:o,tool:"Bash",...L?{content:L}:{}},o)}else if(G==="file_change"){let M=_.item.filename||_.item.path;M&&!I.has(M)&&I.set(M,mo(n,M)),u.push(M?`Edit ${M.split("/").pop()}`:"Edit");let L=M?jn(n,M)??M:void 0;a?.({type:"tool_use",jobId:o,tool:"Edit",...L?{file:L}:{}},o)}else if(G==="file_read"){let M=_.item.filename||_.item.path;u.push(M?`Read ${M.split("/").pop()}`:"Read");let L=M?jn(n,M)??M:void 0;a?.({type:"tool_use",jobId:o,tool:"Read",...L?{file:L}:{}},o)}else if(G==="web_search")u.push("WebSearch"),a?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(G==="mcp_tool_call"){let M=Ji(_.item);u.push(M.telemetryLabel),a?.({type:"tool_use",jobId:o,tool:M.tool,...M.content?{content:M.content}:{}},o)}}if((X==="item.completed"||X==="item/completed")&&_.item){if(_.item.type==="agent_message"){let G=_.item.text;if(typeof G=="string"&&G){let M=An(h,G);M&&a?.({type:"delta",jobId:o,text:M},o)}}else if(_.item.type==="reasoning"){let G=_.item.text;typeof G=="string"&&G&&a?.({type:"thinking",jobId:o,text:G},o)}else if(_.item.type==="file_change"&&Array.isArray(_.item.changes))for(let G of _.item.changes){let M=G.path||G.filename,L=G.kind==="add"?"Write":"Edit";if(M){u.push(`${L} ${M.split("/").pop()}`);let W=jn(n,M)??M;a?.({type:"tool_use",jobId:o,tool:L,file:W},o);let ie=G,Q=typeof ie.kind=="string"?ie.kind:void 0,ee=ac(Q),v=I.get(M),E=mo(n,M);y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:ee,filePath:M,...v?{before:v}:{},...E?{after:E}:{},...Fi(ie)?{patch:Fi(ie)}:{},...Q?{rawKind:Q}:{}}),I.set(M,E)}}else if(_.item.type==="command_execution"){let G=typeof _.item.id=="string"?_.item.id:void 0,M=G?p.get(G):void 0,L=typeof _.item.command=="string"?_.item.command:M?.rawCommand,W=L?qi(L):M?.command,ie=zi(n);if(cc(M?.beforeWorktree,ie)){let Q=[...new Set([...M?.beforeWorktree?.changedFiles??[],...ie?.changedFiles??[]])],ee=typeof _.item.aggregated_output=="string"?fr(_.item.aggregated_output,ic):void 0,v=typeof _.item.exit_code=="number"?_.item.exit_code:_.item.exit_code===null?null:void 0,E=typeof _.item.status=="string"?_.item.status:void 0;y.push({sequence:y.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...L?{rawCommand:L}:{},...W?{command:W}:{},...v!==void 0?{exitCode:v}:{},...E?{status:E}:{},...ee?{output:ee.text}:{},...ee?.truncated?{outputTruncated:!0}:{},...M?.beforeWorktree?{beforeWorktree:M.beforeWorktree}:{},...ie?{afterWorktree:ie}:{},...Q.length>0?{touchedFiles:pc(n,Q,M?.beforeSnapshots??new Map)}:{}})}G&&p.delete(G)}}X==="turn.failed"&&(A=!0,m=_.error?.message||_.message||"Turn failed")}catch{}});let $=[];b.stderr?.on("data",R=>{$.push(R.toString())}),b.on("close",R=>{f.close(),h.length===0&&j.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...j].join(", ")}`),R!==0&&R!==null&&(A=!0,m=$.join("")||`Codex process exited with code ${R}`),k({sessionId:x,text:h.join(""),success:!A,error:A?m:void 0,editEvents:y.length>0?y:void 0,toolsUsed:u.length>0?u:void 0})}),b.on("error",R=>{A=!0,m=R.message,k({sessionId:x,text:h.join(""),success:!1,error:m,editEvents:y.length>0?y:void 0,toolsUsed:u.length>0?u:void 0})})});return{process:b,result:g}}import{spawn as uc}from"child_process";import{createInterface as mc}from"readline";function Hi(o,e){let t=o.trim()||"Copilot CLI failed",n=t.toLowerCase();return n.includes("no authentication information")||n.includes("not authenticated")||n.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`."}:n.includes("model")&&(n.includes("not available")||n.includes("not found")||n.includes("disabled")||n.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:n.includes("mcp")&&(n.includes("blocked")||n.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."}:n.includes("permission")||n.includes("denied")||n.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function Qi(o,e){let{prompt:t,projectRoot:n,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),i&&l.push("--model",i),l.push("-p",t);let w=uc(d,l,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),b=new Promise(g=>{let k,x=[],h=[],u=!1,y="",I=!1,p=setTimeout(()=>{I=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),A=mc({input:w.stdout}),m=new Set,f=[];A.on("line",$=>{if($.trim())try{let R=JSON.parse($),_=En(R);m.add(_),f.length<5&&hc(_)&&f.push($.slice(0,800));let X=Mn(R,["sessionId","session_id","id"],["session","conversation","thread"]);X&&!k&&(k=X);let G=fc(R,x.length===0);G&&(x.push(G),a?.({type:"delta",jobId:o,text:G},o));let M=gc(R);M&&a?.({type:"thinking",jobId:o,text:M},o);let L=yc(R);L&&(h.push(L.label),a?.({type:"tool_use",jobId:o,tool:L.tool,...L.file?{file:L.file}:{},...L.content?{content:L.content}:{}},o));let W=Ic(R);W&&(u=!0,y=W)}catch{}});let j=[];w.stderr?.on("data",$=>{j.push($.toString())}),w.on("close",$=>{clearTimeout(p),A.close(),x.length===0&&m.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...m].join(", ")}`),f.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${f.join(`
26
+ `)}`)),I?(u=!0,y=`Timed out after ${Math.round(s/6e4)} minutes`):$!==0&&$!==null&&(u=!0,y=j.join("").trim()||y||`Copilot process exited with code ${$}`);let R=u?Hi(y,i):null;g({sessionId:k,text:x.join(""),success:!u,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),w.on("error",$=>{clearTimeout(p);let R=Hi($.message,i);g({sessionId:k,text:x.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:w,result:b}}function En(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function fc(o,e=!1){let t=En(o).toLowerCase(),n=o.update,r=n?.content;if(n?.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 Ve(o.delta)??Ve(o.content)??Ve(o.message);if(t==="assistant.message"&&e)return Ve(o.message)??Ve(o.content)??Ve(o);if(t==="result"&&e)return Ve(o.result)??Ve(o.output)??Ve(o.message)??Ve(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&hr(o))return o.text;if(typeof o.message=="string"&&hr(o))return o.message;if(typeof o.delta=="string"&&hr(o))return o.delta}function Ve(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(Ve).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let n=Ve(e[t]);if(n)return n}}function hc(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function gc(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function yc(o){let e=Mn(o,["tool","toolName","tool_name","name"]),t=Mn(o,["command","cmd"]),n=Mn(o,["file","path","filename","filePath"]),r=En(o);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:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(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} ${n.split("/").pop()}`,file:n}}}function Ic(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&En(o).toLowerCase().includes("error"))return o.message}function Mn(o,e,t=[]){for(let n of e){let r=o[n];if(typeof r=="string")return r}for(let[n,r]of Object.entries(o)){if(!r||typeof r!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let i=Mn(r,e);if(i)return i}}function hr(o){let e=En(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readFile as wc,readdir as vc}from"fs/promises";import{join as gr}from"path";var ho=class{constructor(e){let t=gr(e,".popmelt");this.decisionsDir=gr(t,"decisions")}async listDecisionIds(){try{return(await vc(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 wc(gr(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as bc,randomUUID as xc}from"crypto";import{mkdir as yr,readFile as Xi,readdir as Yi,rename as go,stat as Zi,unlink as yo,writeFile as Io}from"fs/promises";import{extname as Sc,join as Qe}from"path";var Tc=10080*60*1e3,kc=600*1e3,Rc=3600*1e3;function Pc(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function Ac(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var wo=class{constructor(e){this.draftsDir=Qe(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Qe(e,".popmelt","artifacts","thread-media")}async stage(e){let t=xc(),n=Pc(e.mimeType),r=`${t}${n}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:Ac(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await yr(this.draftsDir,{recursive:!0});let a=Qe(this.draftsDir,r),d=Qe(this.draftsDir,`${t}.json`),l=`${a}.part`,w=`${d}.part`;return await Io(l,e.data),await go(l,a),await Io(w,JSON.stringify(s,null,2)),await go(w,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let r=await this.readManifest(n.id);if(!r)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(r.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let i=Qe(this.draftsDir,r.contentFile),s=await Xi(i),a=bc("sha256").update(s).digest("hex"),d=Qe(this.mediaDir,`${a}${Sc(r.contentFile)||".bin"}`);await yr(this.mediaDir,{recursive:!0});try{await Zi(d)}catch{let l=`${d}.part`;await Io(l,s),await go(l,d)}(t[n.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 Yi(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let r=Qe(this.draftsDir,n);if(n.endsWith(".part")){let a=await Zi(r).catch(()=>null);a&&e-a.mtimeMs>Rc&&await yo(r).catch(()=>{});return}if(!n.endsWith(".json"))return;let i=await this.readManifest(n.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>kc:e-i.lastSeenAt>Tc)||await Promise.all([yo(r).catch(()=>{}),yo(Qe(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Yi(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>yo(Qe(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Xi(Qe(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await yr(this.draftsDir,{recursive:!0});let t=Qe(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Io(n,JSON.stringify(e,null,2)),await go(n,t)}};import{randomUUID as jc}from"crypto";var _n="<orientation>",lt="</orientation>";function nn(o,e){let t=e;for(;t<o.length&&/\s/.test(o[t]);)t++;if(t>=o.length)return{status:"incomplete",start:t};if(o[t]!=="{")return{status:"invalid",start:t};let n=0,r=!1,i=!1;for(let s=t;s<o.length;s++){let a=o[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"')r=!0;else if(a==="{")n++;else if(a==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function es(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function ts(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(_n,t);if(n<0){es(e,o.slice(t));break}es(e,o.slice(t,n));let r=n+_n.length,i=nn(o,r);if(i.status!=="complete"){let a=o.indexOf(lt,r);if(a>=0){t=a+lt.length;continue}t=r;continue}e.push({kind:"orientation",json:o.slice(i.start,i.end)}),t=i.end;let s=t;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(lt,s)&&(t=s+lt.length)}return e}var on="<imprint-use>",vo="</imprint-use>";function Mc(o){let e=Math.min(o.length,on.length-1);for(let t=e;t>0;t--)if(on.startsWith(o.slice(-t)))return t;return 0}function ns(o,e,t,n,r=Date.now()){if(!o||typeof o!="object"||Array.isArray(o))return null;let i=o,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let l=e?.explanations.find(w=>w.id===d);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return a.length===0?null:{id:jc(),jobId:t,sequence:n,timestamp:r,explanations:a}}var bo=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(n=>!this.explanationIds.has(n.id));if(t.length===0)return null;for(let n of t)this.explanationIds.add(n.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(vo.startsWith(l)&&l.length<vo.length||(l.startsWith(vo)&&(this.buffer=this.buffer.slice(d+vo.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(on);if(r<0){let d=Mc(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+on.length,s=nn(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=ns(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let l=this.takeNewExplanations(d);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",r=0;for(;r<e.length;){let i=e.indexOf(on,r);if(i<0){n+=e.slice(r);break}n+=e.slice(r,i);let s=i+on.length,a=nn(e,s);if(a.status!=="complete"){r=s;continue}try{let w=ns(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(w){let b=this.takeNewExplanations(w);b&&t.push(b)}}catch{}let l=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+l}return{visibleText:n.trim(),usages:t}}};function vt(o,e=240){if(!o)return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function rn(o){return o?[vt(o.selector,400),vt(o.context,200),vt(o.reactComponent,120),vt(o.textContent)].filter(e=>!!e):[]}function Ir(o){return[...new Set(o.filter(e=>!!e))]}function os(o,e){return Ir([...e,...o.annotations.flatMap(t=>[vt(t.pathname,200),vt(t.linkedSelector,400),...t.elements.flatMap(rn)]),...o.styleModifications.flatMap(t=>rn(t.element)),...(o.textModifications??[]).flatMap(t=>rn(t.element)),...(o.domModifications??[]).flatMap(t=>[...rn(t.element),...rn(t.sourceElement)])])}function rs(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Ir(t?[...e,...t.annotations.flatMap(n=>[vt(n.pathname,200),vt(n.linkedSelector,400),...n.elements.flatMap(rn)])]:e)}var xo=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,n=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:t,createdAt:r?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):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[n,r]of this.leases)r.expiresAt>e||(this.leases.delete(n),t.push(n));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 is}from"crypto";import{mkdir as wr,readFile as vr,writeFile as So}from"fs/promises";import{dirname as br,join as sn}from"path";var Xe="[ProjectionWorker]",Ec={version:1,runs:[]},_c={version:1,updatedAt:0,proposals:[]},Cc=12;function $c(o){return Array.isArray(o)?o.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 ss(o){let e=[];for(let t of o){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Xe} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Xe} Rule count ${e.length} exceeds cap of 30`),e}function Oc(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Dc(o,e,t){let n=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let x of i){if(!x||typeof x!="object")continue;let h=x.sources;if(Array.isArray(h))for(let u of h)typeof u=="string"&&n.has(u)&&r.add(u)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},a=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(t?.rules)?t.rules:[],l=i.filter(x=>{if(!x||typeof x!="object")return!1;let h=x.id,u=typeof h=="string"?d.find(y=>y&&typeof y=="object"&&y.id===h):void 0;return JSON.stringify(u)!==JSON.stringify(x)}).length,w=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},b=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},g=Object.keys(s).filter(x=>JSON.stringify(s[x])!==JSON.stringify(w[x])).length,k=Object.keys(a).filter(x=>JSON.stringify(a[x])!==JSON.stringify(b[x])).length;return{ruleCount:l,tokenSectionCount:g,componentCount:k,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(x=>!r.has(x))}}function Nc(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Bc(o,e,t){let n=o[e];if(n&&typeof n=="object")return n;let r=typeof t=="number"?[]:{};return o[String(e)]=r,r}function To(o,e,t){let n=o;for(let i=0;i<e.length-1;i++)n=Bc(n,e[i],e[i+1]);let r=e[e.length-1];n[String(r)]=Nc(t)}function as(o,e){let t=o;for(let r=0;r<e.length-1;r++){let i=t[String(e[r])];if(!i||typeof i!="object")return;t=i}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function Jc(o,e){if(!o)return{exists:!1};let t=o;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function qc(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function ds(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=Jc(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?qc(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var ko=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=sn(e,".popmelt");this.runsPath=sn(n,"projection-runs.json"),this.legacyRunsPath=sn(n,"materialization-runs.json"),this.proposalsPath=sn(n,"projection-queue.json"),this.legacyProposalsPath=sn(n,"model-proposals.json"),this.modelPath=sn(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await vr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=$c(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let r=n.key.split(".");n.value===null?as(t,r):To(t,r,n.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(Cc),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 n=await this.selectUnprojectedPatternDecisions(),r=n.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(x=>x.id);console.log(`${Xe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=zc(r,s),d=Oc(r,n.totalCandidateDecisionCount,a);t=is().slice(0,8);let l={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(l);let w=!0,b,g,k;try{let x=`projection-${Date.now()}`,{provider:h,result:u}=this.spawnModelAgent(x,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:h},await this.persistRun(l);let y=await u;if(!y.success)w=!1,b=y.error,console.error(`${Xe} ${h} spawn error:`,b);else{let I=Uc(y.text,i);if(I){let p=structuredClone(s??{tokens:{},components:{},rules:[]});for(let f of I)To(p,f.path,f.value);Array.isArray(p.rules)&&(p.rules=ss(p.rules));let A=Dc(p,i,s);if(I){let f=[...new Set(I.flatMap(j=>j.decisionIds))];A.coveredDecisionIds=f,A.uncoveredDecisionIds=i.filter(j=>!f.includes(j))}g=A;let m=await this.createModelProposal({decisionIds:i,proposedModel:p,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:g,changes:I});k=m.id,console.log(`${Xe} Created model proposal ${m.id} for ${i.length} decision(s)`)}else w=!1,b="No valid bounded <model-changes> block found in response",console.error(`${Xe} ${b}`)}}catch(x){w=!1,b=x instanceof Error?x.message:String(x),console.error(`${Xe} Error:`,b)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:b,outputStats:g,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:w,error:b}),{processedIds:i,success:w,error:b,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ss(e.rules)),await So(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Xe} 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 wr(br(this.runsPath),{recursive:!0}),await So(this.runsPath,JSON.stringify(t,null,2)),t):{...Ec,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??{..._c,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(n);for(let s of r.changes??[])To(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,r)=>r.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,r)=>n.createdAt-r.createdAt||n.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,t,n,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?as(s,d.path):To(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:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:is().slice(0,8),status:"pending",title:Lc(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"}.`:Fc(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()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(r=>r.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),r=null;return n.proposals=n.proposals.map(i=>i.id!==e?i:(r={...i,...t,updatedAt:Date.now()},r)),r?(n.updatedAt=Date.now(),await this.persistModelProposals(n),r):null}async persistModelProposals(e){try{await wr(br(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...r})=>r)};await So(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(r=>r.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await wr(br(this.runsPath),{recursive:!0}),await So(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await vr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await vr(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,r){let i=n.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...fo(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Qn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Xe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...lo(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Lc(o){let t=(Array.isArray(o.rules)?o.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 n=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function Fc(o,e){let t=Array.isArray(o.rules)?o.rules.length:0,n=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Uc(o,e){let t=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let r=new Set(e),i=n.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(b=>typeof b=="string"||typeof b=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let w=Array.isArray(d.decisionIds)?d.decisionIds.filter(b=>typeof b=="string"&&r.has(b)):[];return w.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:w,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===n.length?i:null}catch{return null}}function zc(o,e){let t=o.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 Io=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,n){for(let r of this.listeners)r(e,t,n)}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 n=this.activeJob;return!n||n.id!==e?null:(n.status="cancelled",n.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:n.error,cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id),this.processNext(),n)}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 Nc}from"child_process";import{readFile as Zi}from"fs/promises";import{homedir as wr}from"os";import{join as tt}from"path";var vr=/popmelt/i;function Et(){return{found:!1,name:null,scope:null,disabled:!1}}function rn(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function Mn(o){for(let e of Object.keys(o))if(vr.test(e))return e;return null}async function wo(o){try{let e=await Zi(o,"utf-8");return JSON.parse(e)}catch{return null}}async function br(o){let e=wr(),t=await wo(tt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Mn(r.mcpServers);if(i)return rn(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[o];if(s&&typeof s=="object"){let a=s;if(a.mcpServers&&typeof a.mcpServers=="object"){let d=Mn(a.mcpServers);if(d){let l=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(v=>vr.test(v));return rn(d,"project",l)}}}}}let n=await wo(tt(o,".mcp.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Mn(r.mcpServers);if(s){let a=await Xi(o,s);return rn(s,"mcp.json",a)}}let i=Mn(r);if(i&&i!=="mcpServers"){let s=await Xi(o,i);return rn(i,"mcp.json",s)}}return Et()}async function Xi(o,e){let t=tt(o,".claude","settings.local.json"),n=await wo(t);if(n&&typeof n=="object"){let r=n;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var Bc=/^\[mcp_servers\.([^\]]+)\]/;function Jc(o){let e=o.split(`
107
- `),t=[],n=null;for(let r of e){let i=r.match(Bc);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
106
+ Include property and bindings when the decision context has class-level evidence.`}var Ro=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,n){for(let r of this.listeners)r(e,t,n)}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 n=this.activeJob;return!n||n.id!==e?null:(n.status="cancelled",n.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:n.error,cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id),this.processNext(),n)}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 Gc}from"child_process";import{readFile as ps}from"fs/promises";import{homedir as Sr}from"os";import{join as nt}from"path";var Tr=/popmelt/i;function $t(){return{found:!1,name:null,scope:null,disabled:!1}}function an(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function Cn(o){for(let e of Object.keys(o))if(Tr.test(e))return e;return null}async function Po(o){try{let e=await ps(o,"utf-8");return JSON.parse(e)}catch{return null}}async function kr(o){let e=Sr(),t=await Po(nt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Cn(r.mcpServers);if(i)return an(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[o];if(s&&typeof s=="object"){let a=s;if(a.mcpServers&&typeof a.mcpServers=="object"){let d=Cn(a.mcpServers);if(d){let l=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(w=>Tr.test(w));return an(d,"project",l)}}}}}let n=await Po(nt(o,".mcp.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Cn(r.mcpServers);if(s){let a=await cs(o,s);return an(s,"mcp.json",a)}}let i=Cn(r);if(i&&i!=="mcpServers"){let s=await cs(o,i);return an(i,"mcp.json",s)}}return $t()}async function cs(o,e){let t=nt(o,".claude","settings.local.json"),n=await Po(t);if(n&&typeof n=="object"){let r=n;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var Wc=/^\[mcp_servers\.([^\]]+)\]/;function Kc(o){let e=o.split(`
107
+ `),t=[],n=null;for(let r of e){let i=r.match(Wc);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
108
108
  `)}),n={name:i[1],bodyLines:[]}):r.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
109
109
  `)}),n=null):n&&n.bodyLines.push(r)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
110
- `)}),t}function qc(o){return/enabled\s*=\s*false/i.test(o)}async function xr(o){let e=process.env.CODEX_HOME||tt(wr(),".codex"),t=await Yi(tt(e,"config.toml"),"user");if(t.found)return t;let n=await Yi(tt(o,".codex","config.toml"),"project");return n.found?n:Et()}async function Sr(o,e="copilot"){let t=await Lc(e);if(t.found)return t;let n=process.env.COPILOT_HOME||tt(wr(),".copilot"),r=await Ir(tt(n,"mcp-config.json"),"user");if(r.found)return r;let i=await Ir(tt(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await Ir(tt(o,".github","mcp.json"),"mcp.json");return s.found?s:Et()}async function Lc(o){try{let e=await new Promise((t,n)=>{Nc(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return es(JSON.parse(e),"user")}catch{return Et()}}async function Ir(o,e){let t=await wo(o);return es(t,e)}function es(o,e){if(!o||typeof o!="object")return Et();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=Mn(n);return r?rn(r,e):Et()}async function Yi(o,e){try{let t=await Zi(o,"utf-8"),n=Jc(t);for(let r of n)if(vr.test(r.name)){let i=qc(r.body);return rn(r.name,e,i)}}catch{}return Et()}import{execFile as ts}from"child_process";import{mkdir as Uc,readFile as ns,writeFile as os}from"fs/promises";import{homedir as rs}from"os";import{dirname as Fc,join as Tr}from"path";var kr="https://mcp.popmelt.com/mcp";async function is(o=kr){let e=Tr(rs(),".claude.json"),t;try{let r=await ns(e,"utf-8");t=JSON.parse(r)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let r of Object.keys(n))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:o},await os(e,JSON.stringify(t,null,2)+`
111
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function ss(o=kr){let e=process.env.CODEX_HOME||Tr(rs(),".codex"),t=Tr(e,"config.toml"),n;try{n=await ns(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Uc(Fc(t),{recursive:!0});let r=`
110
+ `)}),t}function Vc(o){return/enabled\s*=\s*false/i.test(o)}async function Rr(o){let e=process.env.CODEX_HOME||nt(Sr(),".codex"),t=await ls(nt(e,"config.toml"),"user");if(t.found)return t;let n=await ls(nt(o,".codex","config.toml"),"project");return n.found?n:$t()}async function Pr(o,e="copilot"){let t=await Hc(e);if(t.found)return t;let n=process.env.COPILOT_HOME||nt(Sr(),".copilot"),r=await xr(nt(n,"mcp-config.json"),"user");if(r.found)return r;let i=await xr(nt(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await xr(nt(o,".github","mcp.json"),"mcp.json");return s.found?s:$t()}async function Hc(o){try{let e=await new Promise((t,n)=>{Gc(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return us(JSON.parse(e),"user")}catch{return $t()}}async function xr(o,e){let t=await Po(o);return us(t,e)}function us(o,e){if(!o||typeof o!="object")return $t();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=Cn(n);return r?an(r,e):$t()}async function ls(o,e){try{let t=await ps(o,"utf-8"),n=Kc(t);for(let r of n)if(Tr.test(r.name)){let i=Vc(r.body);return an(r.name,e,i)}}catch{}return $t()}import{execFile as ms}from"child_process";import{mkdir as Qc,readFile as fs,writeFile as hs}from"fs/promises";import{homedir as gs}from"os";import{dirname as Xc,join as Ar}from"path";var jr="https://mcp.popmelt.com/mcp";async function ys(o=jr){let e=Ar(gs(),".claude.json"),t;try{let r=await fs(e,"utf-8");t=JSON.parse(r)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let r of Object.keys(n))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:o},await hs(e,JSON.stringify(t,null,2)+`
111
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Is(o=jr){let e=process.env.CODEX_HOME||Ar(gs(),".codex"),t=Ar(e,"config.toml"),n;try{n=await fs(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Qc(Xc(t),{recursive:!0});let r=`
112
112
  [mcp_servers.popmelt]
113
113
  url = "${o}"
114
- `;return await os(t,n+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function as(o=kr,e="copilot"){let t=await zc(e);if(Gc(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,r)=>{ts(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function zc(o){try{let e=await new Promise((t,n)=>{ts(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return JSON.parse(e)}catch{return null}}function Gc(o){if(!o||typeof o!="object")return!1;let e=o,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}function ds(o){let e=o.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 n=t.action,r=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!r||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="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:n,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 cs(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),n=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!n||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:n,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 Rr(o){let t=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],r=await Wc(o),i=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),a,d,l,v,S,y,k,T,g,u,I,f,p,j,h,m=[],M=[],D=0,P=[];for(;D<r.length;){let A=r.indexOf(i,D);if(A===-1)break;let Q=A+i.length;if(r.slice(A,A+s.length).equals(s))break;let z=Q;r[z]===13&&r[z+1]===10&&(z+=2);let E=r.indexOf(`\r
114
+ `;return await hs(t,n+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function ws(o=jr,e="copilot"){let t=await Yc(e);if(Zc(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,r)=>{ms(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function Yc(o){try{let e=await new Promise((t,n)=>{ms(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return JSON.parse(e)}catch{return null}}function Zc(o){if(!o||typeof o!="object")return!1;let e=o,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}function vs(o){let e=o.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 n=t.action,r=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!r||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="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:n,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 bs(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),n=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!n||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:n,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 Mr(o){let t=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],r=await el(o),i=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),a,d,l,w,b,g,k,x,h,u,y,I,p,A,m,f,j,$=[],R=[],_=0,X=[];for(;_<r.length;){let G=r.indexOf(i,_);if(G===-1)break;let M=G+i.length;if(r.slice(G,G+s.length).equals(s))break;let L=M;r[L]===13&&r[L+1]===10&&(L+=2);let W=r.indexOf(`\r
115
115
  \r
116
- `,z);if(E===-1)break;let G=r.slice(z,E).toString("utf-8"),W=E+4,ue=r.indexOf(i,W),X=ue!==-1?ue-2:r.length;P.push({headers:G,body:r.slice(W,X)}),D=ue!==-1?ue:r.length}for(let A of P){let Q=A.headers.match(/name="([^"]+)"/);if(!Q)continue;let z=Q[1];if(z==="screenshot")a=A.body;else if(z==="feedback")d=A.body.toString("utf-8");else if(z==="color")l=A.body.toString("utf-8");else if(z==="provider")v=A.body.toString("utf-8");else if(z==="model")S=A.body.toString("utf-8");else if(z==="reasoningEffort")y=A.body.toString("utf-8");else if(z==="serviceTier")k=A.body.toString("utf-8");else if(z==="goal")T=A.body.toString("utf-8");else if(z==="pageUrl")g=A.body.toString("utf-8");else if(z==="viewport")u=A.body.toString("utf-8");else if(z==="planId")I=A.body.toString("utf-8");else if(z==="manifest")f=A.body.toString("utf-8");else if(z==="tasks")p=A.body.toString("utf-8");else if(z==="sourceId")j=A.body.toString("utf-8");else if(z==="continuationThreadId")h=A.body.toString("utf-8");else if(z.startsWith("screenshot-")){let E=z.slice(11);try{let G=decodeURIComponent(E);M.push({pathname:G,data:A.body})}catch{}}else if(z.startsWith("image-")){let E=z.split("-"),G=parseInt(E[E.length-1],10),W=E.slice(1,-1).join("-");W&&!isNaN(G)&&m.push({annotationId:W,index:G,data:A.body})}}if(!a)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:a,feedback:d,color:l,provider:v,model:S,reasoningEffort:y,serviceTier:k,goal:T,pageUrl:g,viewport:u,planId:I,manifest:f,tasks:p,sourceId:j,continuationThreadId:h,pastedImages:m,pageScreenshots:M}}function Wc(o){return new Promise((e,t)=>{let n=[];o.on("data",r=>n.push(r)),o.on("end",()=>e(Buffer.concat(n))),o.on("error",t)})}var Vc=String.raw`
116
+ `,L);if(W===-1)break;let ie=r.slice(L,W).toString("utf-8"),Q=W+4,ee=r.indexOf(i,Q),v=ee!==-1?ee-2:r.length;X.push({headers:ie,body:r.slice(Q,v)}),_=ee!==-1?ee:r.length}for(let G of X){let M=G.headers.match(/name="([^"]+)"/);if(!M)continue;let L=M[1];if(L==="screenshot")a=G.body;else if(L==="feedback")d=G.body.toString("utf-8");else if(L==="color")l=G.body.toString("utf-8");else if(L==="provider")w=G.body.toString("utf-8");else if(L==="model")b=G.body.toString("utf-8");else if(L==="reasoningEffort")g=G.body.toString("utf-8");else if(L==="serviceTier")k=G.body.toString("utf-8");else if(L==="goal")x=G.body.toString("utf-8");else if(L==="pageUrl")h=G.body.toString("utf-8");else if(L==="viewport")u=G.body.toString("utf-8");else if(L==="planId")y=G.body.toString("utf-8");else if(L==="manifest")I=G.body.toString("utf-8");else if(L==="tasks")p=G.body.toString("utf-8");else if(L==="sourceId")A=G.body.toString("utf-8");else if(L==="continuationThreadId")m=G.body.toString("utf-8");else if(L==="continuationTargetBindingId")f=G.body.toString("utf-8");else if(L==="continuationSelectorAliases")try{let W=JSON.parse(G.body.toString("utf-8"));Array.isArray(W)&&(j=W.filter(ie=>typeof ie=="string"&&ie.length>0))}catch{}else if(L.startsWith("screenshot-")){let W=L.slice(11);try{let ie=decodeURIComponent(W);R.push({pathname:ie,data:G.body})}catch{}}else if(L.startsWith("image-")){let W=L.split("-"),ie=parseInt(W[W.length-1],10),Q=W.slice(1,-1).join("-");Q&&!isNaN(ie)&&$.push({annotationId:Q,index:ie,data:G.body})}}if(!a)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:a,feedback:d,color:l,provider:w,model:b,reasoningEffort:g,serviceTier:k,goal:x,pageUrl:h,viewport:u,planId:y,manifest:I,tasks:p,sourceId:A,continuationThreadId:m,continuationTargetBindingId:f,continuationSelectorAliases:j,pastedImages:$,pageScreenshots:R}}function el(o){return new Promise((e,t)=>{let n=[];o.on("data",r=>n.push(r)),o.on("end",()=>e(Buffer.concat(n))),o.on("error",t)})}var tl=String.raw`
117
117
  (() => {
118
118
  const hidden = [];
119
119
  const visit = (root) => {
@@ -134,7 +134,7 @@ url = "${o}"
134
134
  visit(document);
135
135
  window.__popmeltNativeCaptureHidden = hidden;
136
136
  })()
137
- `,Kc=String.raw`
137
+ `,nl=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,18 +142,18 @@ url = "${o}"
142
142
  }
143
143
  delete window.__popmeltNativeCaptureHidden;
144
144
  })()
145
- `;function vo(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Hc(o,e){let t=vo(e);if(!t)return null;let n=new URL(t),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&vo(s.url)),i=r.find(s=>vo(s.url)===t);return i||(r.find(s=>{let a=new URL(vo(s.url));return a.origin===n.origin&&a.pathname===n.pathname})??null)}function Qc(o){let e={x:Number(o.x),y:Number(o.y),width:Number(o.width),height:Number(o.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 Xc(o){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",o).href,r=await fetch(n,{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 Yc(o){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let r=new e(o,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),t(r)},s=a=>{r.off("open",i),n(a)};r.once("open",i),r.once("error",s)})}function Zc(o){let e=1,t=new Map;return o.on("message",n=>{let r;try{r=JSON.parse(String(n))}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??{}))}),o.on("close",()=>{for(let[n,r]of t)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),t.delete(n)}),(n,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{t.delete(a),s(new Error(`CDP ${n} timed out`))},4e3);t.set(a,{resolve:i,reject:s,timeout:d}),o.send(JSON.stringify({id:a,method:n,params:r}),l=>{l&&(clearTimeout(d),t.delete(a),s(l))})})}async function ls(o,e){let t=Qc(e.clip),n=await Xc(o),r=Hc(n,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Yc(r.webSocketDebuggerUrl),s=Zc(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Vc,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))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{a&&await s("Runtime.evaluate",{expression:Kc,returnByValue:!0}).catch(()=>{}),i.close()}}import{randomUUID as el}from"crypto";var tl=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 En(o,e=180){if(typeof o!="string")return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function ol(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function ps(o,e,t,n=Date.now()){let r=ol(o);if(!r)return null;let i=typeof r.transition=="string"&&tl.has(r.transition)?r.transition:null,s=En(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&nl.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:el(),jobId:e,sequence:t,timestamp:n,transition:i,snapshot:{focus:s,seeking:En(r.seeking),workingHypothesis:En(r.workingHypothesis),evidencePosture:a,update:En(r.update),nextObservation:En(r.nextObservation)},contextPolicy:"exclude"}}function Pr(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Ar(o,e,t=0){let n=[],r=[],i=new Set,s=t;for(let d of Fi(o)){if(d.kind==="text"){d.text&&r.push(d);continue}try{let l=ps(JSON.parse(d.json),e,s);if(!l)continue;let v=Pr(l);if(i.has(v))continue;i.add(v),n.push(l),r.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:r.map(d=>d.kind==="text"?d.text:`
145
+ `;function Ao(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function ol(o,e){let t=Ao(e);if(!t)return null;let n=new URL(t),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Ao(s.url)),i=r.find(s=>Ao(s.url)===t);return i||(r.find(s=>{let a=new URL(Ao(s.url));return a.origin===n.origin&&a.pathname===n.pathname})??null)}function rl(o){let e={x:Number(o.x),y:Number(o.y),width:Number(o.width),height:Number(o.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 il(o){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",o).href,r=await fetch(n,{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(o){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let r=new e(o,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),t(r)},s=a=>{r.off("open",i),n(a)};r.once("open",i),r.once("error",s)})}function al(o){let e=1,t=new Map;return o.on("message",n=>{let r;try{r=JSON.parse(String(n))}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??{}))}),o.on("close",()=>{for(let[n,r]of t)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),t.delete(n)}),(n,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{t.delete(a),s(new Error(`CDP ${n} timed out`))},4e3);t.set(a,{resolve:i,reject:s,timeout:d}),o.send(JSON.stringify({id:a,method:n,params:r}),l=>{l&&(clearTimeout(d),t.delete(a),s(l))})})}async function xs(o,e){let t=rl(e.clip),n=await il(o),r=ol(n,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await sl(r.webSocketDebuggerUrl),s=al(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:tl,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))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{a&&await s("Runtime.evaluate",{expression:nl,returnByValue:!0}).catch(()=>{}),i.close()}}import{randomUUID as dl}from"crypto";var cl=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),ll=new Set(["strengthened","weakened","mixed","unknown"]);function $n(o,e=180){if(typeof o!="string")return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function pl(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Ss(o,e,t,n=Date.now()){let r=pl(o);if(!r)return null;let i=typeof r.transition=="string"&&cl.has(r.transition)?r.transition:null,s=$n(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&ll.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:dl(),jobId:e,sequence:t,timestamp:n,transition:i,snapshot:{focus:s,seeking:$n(r.seeking),workingHypothesis:$n(r.workingHypothesis),evidencePosture:a,update:$n(r.update),nextObservation:$n(r.nextObservation)},contextPolicy:"exclude"}}function Er(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function _r(o,e,t=0){let n=[],r=[],i=new Set,s=t;for(let d of ts(o)){if(d.kind==="text"){d.text&&r.push(d);continue}try{let l=Ss(JSON.parse(d.json),e,s);if(!l)continue;let w=Er(l);if(i.has(w))continue;i.add(w),n.push(l),r.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:r.map(d=>d.kind==="text"?d.text:`
146
146
 
147
147
  `).join("").replace(/\n{3,}/g,`
148
148
 
149
- `).trim(),orientations:n,segments:r}}function rl(o){let e="<orientation>",t=Math.min(o.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(o.slice(-n)))return n;return 0}var bo=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="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(lt.startsWith(l)&&l.length<lt.length||(l.startsWith(lt)&&(this.buffer=this.buffer.slice(d+lt.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(jn);if(r<0){let d=rl(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+jn.length,s=en(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.jobId,this.sequence);if(!d)continue;let l=Pr(d);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(d),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=Ar(e,this.jobId,this.sequence),n=t.orientations.filter(r=>{let i=Pr(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},us=`## Public orientation updates
149
+ `).trim(),orientations:n,segments:r}}function ul(o){let e="<orientation>",t=Math.min(o.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(o.slice(-n)))return n;return 0}var jo=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="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(lt.startsWith(l)&&l.length<lt.length||(l.startsWith(lt)&&(this.buffer=this.buffer.slice(d+lt.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(_n);if(r<0){let d=ul(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+_n.length,s=nn(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=Ss(JSON.parse(a),this.jobId,this.sequence);if(!d)continue;let l=Er(d);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(d),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=_r(e,this.jobId,this.sequence),n=t.orientations.filter(r=>{let i=Er(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},Ts=`## Public orientation updates
150
150
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
151
151
  <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>
152
152
 
153
153
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
154
154
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
155
155
 
156
- 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 ms=`## Project collaboration history
156
+ 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 ks=`## Project collaboration history
157
157
  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.
158
158
 
159
159
  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.
@@ -162,49 +162,49 @@ Search raw \`.popmelt\` records only when the supplied Imprint context is insuff
162
162
 
163
163
  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.
164
164
 
165
- 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 _n(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let r of o.annotations){let i=r.elements.map(l=>{let v=[l.selector];return l.reactComponent&&v.push(`(${l.reactComponent})`),v.join(" ")}).join(", "),s=r.instruction||"No text";n.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`);let d=t?.[r.id];if(d?.length)for(let l of d)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of o.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes){let a=s.token?` [${s.token}]`:"";n.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of o.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(".")}`:"";n.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of o.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}`;n.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of o.spacingTokenChanges){n.push(`
165
+ 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 On(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let r of o.annotations){let i=r.elements.map(l=>{let w=[l.selector];return l.reactComponent&&w.push(`(${l.reactComponent})`),w.join(" ")}).join(", "),s=r.instruction||"No text";n.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)n.push(` Attached image: use the Read tool to view ${l}`);let d=t?.[r.id];if(d?.length)for(let l of d)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of o.styleModifications){let i=Vo(r.element,r.selector);for(let s of r.changes){let a=s.token?` [${s.token}]`:"";n.push(`- ${r.selector} (${i}): ${s.property} ${s.original} \u2192 ${s.modified}${a}`)}}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of o.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(".")}`:"";n.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of o.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}`;n.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of o.spacingTokenChanges){n.push(`
166
166
  ### ${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?n.push(`- ${i.selector}${s}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):n.push(`- ${i.selector}${s}: ${i.property} ${r.originalPx}px \u2192 ${r.newPx}px`),n.push(` class="${i.className}"`)}}}if(o.inspectedElement){let r=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.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)}"`),n.push(`- ${i.join(" ")}`)}return n.join(`
167
- `)}function fs(o,e,t){let n=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${a.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),a.feedbackSummary&&n.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&n.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${a.question}"`);else{if(n.push(`### Round ${s} (assistant)`),a.responseText&&n.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&n.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&n.push(`Tools used: ${a.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.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(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let v=new Map;for(let S of s)if(typeof S=="object"&&S!==null&&"text"in S){let y=S,k=y.scope||"general";v.has(k)||v.set(k,[]),v.get(k).push(y.text)}for(let[S,y]of v){n.push(`**${S.charAt(0).toUpperCase()+S.slice(1)}**`);for(let k of y)n.push(`- ${k}`)}}else for(let v of s)typeof v=="string"&&n.push(`- ${v}`);let a=t.designModel.tokens;a&&typeof a=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(a,null,2)),n.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.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:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.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."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.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 l=d.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(d)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of a){n.push(""),n.push(`## Page: ${d}`);let v=s[d];v&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let S={...e,annotations:l,styleModifications:e.styleModifications},y=_n(S,t?.imagePaths,t?.attachmentFiles);y&&(n.push(""),n.push(y))}}else{let s=_n(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.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."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
168
- `)}function hs(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function gs(o,e,t,n){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: ${o}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let 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("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of n)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output 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(`
169
- `)}function il(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function sl(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!il(e[t]))return!1;return!0}function ys(o){let t=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let n=JSON.parse(t);return(Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.annotations)?n.annotations:[]).filter(sl)}catch{return[]}}function al(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let r=n;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 Is(o,e){return e>0?al(o):[]}import{execFile as dl}from"child_process";import{readFile as cl,readdir as ll,stat as pl}from"fs/promises";import{homedir as Cn}from"os";import{join as nt}from"path";var So=[{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()}],$n=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],On={id:"",label:"Default",source:"cli"},ul=/^\s*-\s+"([^"]+)"/;function ml(o){let e=[],t=!1;for(let n of o.split(`
170
- `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let r=n.match(ul);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:jr(i),source:"cli"})}return To([On,...e])}function fl(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,r)=>{let i=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(n=>{let r=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!r)return[];let i=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():jr(r),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,a=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function ws(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function hl(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return To(e.map(t=>({id:t,label:jr(t),source:"cli"})))}function jr(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},t=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let i=n[1]==="sonnet"?"Sonn":wl(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${i}${s}${n[4]?" Fast":""}`}let r=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return t}async function vs(o="copilot"){let e=await xo(o,["help","config"]),t=ml(e);return t.length>1?t:[On]}async function bs(o="codex"){let e=await xo(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||nt(Cn(),".codex");return Ss(nt(n,"models_cache.json"))}),t=fl(e);return t.length>0?To([...t,...$n]):$n}async function xs(o="claude"){let e=nt(Cn(),".claude"),t=[nt(Cn(),".claude","stats-cache.json"),nt(Cn(),".claude","settings.json"),nt(Cn(),".claude.json"),nt(e,"cache","changelog.md")],[n,r,i]=await Promise.all([xo(o,["--help"]).catch(()=>""),xo(o,["--version"]).catch(()=>""),gl(e).catch(()=>[])]),s=Il([...t,...i]),a=await Promise.all(s.map(l=>Ss(l).catch(()=>""))),d=hl([n,r,...a].join(`
171
- `));return To([...So,...d])}function xo(o,e,t=5e3){return new Promise((n,r)=>{dl(o,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}n(s)})})}async function Ss(o){return cl(o,"utf-8")}async function gl(o){let e=[nt(o,"projects"),nt(o,"telemetry")],t=[];for(let n of e)await Ts(n,t,4);return t.sort((n,r)=>r.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function Ts(o,e,t){if(t<0)return;let n;try{n=await ll(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async r=>{let i=nt(o,r.name);if(r.isDirectory()){await Ts(i,e,t-1);return}if(!(!r.isFile()||!yl(r.name)))try{let s=await pl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function yl(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function To(o){let e=new Set,t=[];for(let n of o)e.has(n.id)||(e.add(n.id),t.push(n));return t}function Il(o){return[...new Set(o)]}function wl(o){return o.charAt(0).toUpperCase()+o.slice(1)}var ko=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 n=t>=0?t+1:0,r=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(n=>n.threadId===e&&(!t||t(n)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let r=this.bufferEvent(t,e);for(let i of this.listeners)i(r,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let r={...t,seq:n.nextSeq++};return n.events.push(r),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),r}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(a=>a.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,t,n){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[t]+=n}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:"Cancelled by user",cancelled:!0,provider:n.provider,model:n.model},n.id,n.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 n of t)try{n.kill("SIGTERM")}catch{}await Promise.all(t.map(n=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!i){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);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 Dn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Ro(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Mr(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function ks(o){let e=Mr(Ro(o.origin));if(e)return e;let t=Mr(Ro(o.referer));if(t)return t;let n=Ro(o["x-forwarded-host"]);if(!n)return null;let r=Ro(o["x-forwarded-proto"])==="https"?"https":"http";return Mr(`${r}://${n}`)}function Rs(o,e,t=5){let n=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(n).slice(0,t),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{mkdir as vl,readFile as Ps,realpath as bl,writeFile as xl}from"fs/promises";import{join as Po}from"path";async function _r(o){return bl(o).catch(()=>o)}function As(o){return Po(o,".popmelt","store.json")}function Sl(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function Er(o){let e=await _r(o);try{let t=JSON.parse(await Ps(As(e),"utf8"));return Sl(t)?t:null}catch{return null}}async function Tl(o){let e=await _r(o),t=await Er(e);if(t)return t;let n;for(let r of[Po(e,".popmelt","memory","manifest.json"),Po(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await Ps(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){n=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Nt(e)}`,createdAt:new Date().toISOString()}}async function Ao(o){let e=await _r(o),t=await Er(e);if(t)return t;let n=await Tl(e),r=Po(e,".popmelt");await vl(r,{recursive:!0});try{return await xl(As(e),`${JSON.stringify(n,null,2)}
172
- `,{encoding:"utf8",flag:"wx"}),n}catch(i){let s=await Er(e);if(s)return s;throw i}}import{createHash as Eo}from"crypto";import{mkdir as sn,readFile as _t,unlink as Ml,writeFile as Ct}from"fs/promises";import{dirname as _o,extname as El,join as Ue}from"path";var kl={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 Rl(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function js(o,e){let t=e??Rl(o);return{kind:t,...kl[t]}}import{createHash as Pl,randomUUID as Al}from"crypto";var Ms=o=>`${o}-${Al()}`;function Cr(o,...e){return`${o}-${Pl("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function $r(o){return{schemaVersion:1,submissionIds:[Ms("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function Nn(o,e=[],t){return{...o,outcomeId:o.outcomeId??Ms("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function jl(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function jo(o,e){return e?[`${o||"/"}:${e}`]:[]}function Es(o){let e=jl(o.url);return[...new Set([...o.annotations.flatMap(t=>jo(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>jo(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>jo(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>jo(t.pathname??e,t.durableSelector??t.selector))])]}function _s(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(t=>`annotation:${t.id}`),...o.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function Mo(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Cr("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[Cr("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Cr("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Or(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=Mo(o.id,t)||e;return e}function Cs(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:o.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var _l={version:1,threads:{}},$s=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],an={version:2,updatedAt:0,files:{},activeWorkspaceGeneration:0};function Cl(o){return JSON.stringify(o,null,2)}function $l(o){return Object.fromEntries($s.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Ol(o){let e={...o};for(let t of $s)delete e[t];return e}function dn(o){let e=o;if(o.error){let t=js(o.error,o.errorKind);(o.error!==t.message||o.errorKind!==t.kind||o.responseText!==void 0)&&(e={...o,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=Zt(e.result,!1),n=Zt(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var Co=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Ue(e,".popmelt");this.legacyFilePath=Ue(t,"threads.json"),this.threadsDir=Ue(t,"threads"),this.indexPath=Ue(this.threadsDir,"index.json"),this.artifactsDir=Ue(t,"artifacts","thread-messages"),this.mediaDir=Ue(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await _t(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(Ue(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let n=!1;for(let r of Object.values(t))n=Or(r)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await _t(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(dn)}]))},this.index={...an,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Or(t);return await this.persistAll(),this.cache}}catch{}return this.cache={..._l,threads:{}},this.index={...an,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e,t){let n=[...new Set(e)];if(n.length!==1)return null;let r=await this.load(),[i]=n,s=this.getActiveWorkspaceGeneration();if(t){let d=r.threads[t];if(d&&(d.workspaceGeneration??0)===s&&d.elementIdentifiers.length>0)return d}let a=Object.values(r.threads).filter(d=>(d.workspaceGeneration??0)===s&&d.elementIdentifiers.length===1&&d.elementIdentifiers[0]===i);return a.length===1?a[0]:null}async createThread(e,t){let n=await this.load(),r={id:e,lifecycleVersion:1,workspaceGeneration:this.getActiveWorkspaceGeneration(),createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,t){let r=(await this.load()).threads[e];r&&(Mo(e,t),r.messages.push(dn(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;Mo(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,dn(t)):r.messages.push(dn(t)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,t,n){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,n),a.error){let d=dn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,t,n){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,n),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 deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async advanceWorkspaceGeneration(){await this.load();let e=this.index??{...an,files:{}},t=(e.activeWorkspaceGeneration??0)+1;return e.activeWorkspaceGeneration=t,e.updatedAt=Date.now(),this.index=e,this.writeChain=this.writeChain.then(async()=>{await sn(this.threadsDir,{recursive:!0}),await Ct(this.indexPath,JSON.stringify(e,null,2))}),await this.writeChain,t}async listRecent(e=5){let t=await this.load(),n=this.getActiveWorkspaceGeneration(),r=Object.values(t.threads).filter(i=>(i.workspaceGeneration??0)===n);return r.sort((i,s)=>s.updatedAt-i.updatedAt),r.slice(0,e).map(i=>{let s=i.messages.find(f=>f.role==="human"),a=i.messages.find(f=>f.annotationSnapshot?.color)?.annotationSnapshot?.color,d=s?.feedbackSummary||"[thread]",l=i.messages.filter(f=>f.role==="assistant"),v=f=>{if(f.role!=="assistant")return;if(f.question)return f.question;let p=f.imprintSummary?.grounding;if(p?.question&&!f.imprintSummary?.resolvedAction)return p.question},S=i.messages.findLastIndex(f=>!!v(f)),y=i.messages.findLastIndex(f=>f.role==="human"),k=S>y?v(i.messages[S]):void 0,T=i.messages.at(-1)?.role,g=Array.from(new Set(i.messages.slice(0,Math.max(0,y)).filter(f=>f.role==="assistant"&&!!f.jobId).map(f=>f.jobId))),u=l.some(f=>!!f.responseText||!!f.question||!!f.result||!!f.memoryReviewCard||!!f.memoryReceipt),I=l.some(f=>!!f.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:d,messageCount:i.messages.length,hasReply:u,hasError:I,lastMessageRole:T,pendingQuestion:k,acknowledgedJobIds:g,elementIdentifiers:i.elementIdentifiers,color:a,lifecycle:Cs(i)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let r=n.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=Nn(r.lifecycle);r.queued&&await this.updateMessage(n.id,r.jobId,{queued:!1}),await this.appendMessage(n.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 n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await _t(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let{version:n,messages:r,...i}=t,s=await Promise.all(r.map(async({detailArtifact:a,...d})=>{let l={};if(a?.path)try{let v=await _t(Ue(_o(this.legacyFilePath),a.path),"utf8");Eo("sha256").update(v).digest("hex")===a.sha256&&(l=JSON.parse(v))}catch{}return dn({...d,...l})}));return{...i,messages:s}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=$l(e),n=Ol(e);if(Object.keys(t).length===0)return n;let r=Cl(t),i=Eo("sha256").update(r).digest("hex"),s=Ue("artifacts","thread-messages",`${i}.json`);await sn(this.artifactsDir,{recursive:!0});try{await _t(Ue(_o(this.legacyFilePath),s),"utf8")}catch{await Ct(Ue(_o(this.legacyFilePath),s),r)}return{...n,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async n=>{if(_o(n)===this.mediaDir)return n;try{let r=await _t(n),i=Eo("sha256").update(r).digest("hex"),s=Ue(this.mediaDir,`${i}${El(n)||".bin"}`);await sn(this.mediaDir,{recursive:!0});try{await _t(s)}catch{await Ct(s,r)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,r])=>[n,await t(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,r])=>[n,await Promise.all(r.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,r])=>[n,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 sn(this.threadsDir,{recursive:!0});let t=this.index??{...an,files:{}},n=t.files[e.id]??`${Eo("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 Ct(Ue(this.threadsDir,n),JSON.stringify(i,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Ct(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}isThreadInActiveWorkspace(e){if(!e)return!0;let t=this.cache?.threads[e];return!!t&&(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 sn(this.threadsDir,{recursive:!0}),this.index=this.index??{...an,files:{}},await Ct(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...an,files:{}},n=t.files[e];n&&await Ml(Ue(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await sn(this.threadsDir,{recursive:!0}),await Ct(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as Dl,open as Nl,readFile as Bl,rename as Jl,unlink as ql}from"fs/promises";import{dirname as Ll,join as Ul}from"path";var Os={schemaVersion:1,theme:"auto",updatedAt:null};function Ds(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Fl(o,e){await Dl(Ll(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await Nl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
173
- `,"utf8"),await n.sync()}finally{await n.close()}await Jl(t,o)}catch(n){throw await ql(t).catch(()=>{}),n}}var $o=class{constructor(e){this.path=Ul(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Bl(this.path,"utf8")),t=Ds(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Os}}}catch{return{exists:!1,preferences:{...Os}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Fl(this.path,t),t}};function Ns(o){return Ds(o)!==null}var tp=1111,np=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],op=1800*1e3,rp=3600*1e3,Js=45e3,ip=5e3,sp=1e4,ap=2*1024*1024;function qs(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
174
- `)}function Bn(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Ls(o){let e=o.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let t=o[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=o.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function dp(o,e){if(e.size===1)return[...o].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function Ws(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function cp(o,e,t){let n=[...t];for(let r of o)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,l;switch(i){case"Read":l=d?`Reading ${d}`:"Reading file";break;case"Edit":l=d?`Editing ${d}`:"Editing file";break;case"Write":l=d?`Writing ${d}`:"Writing file";break;case"Bash":l=a?a.split(`
175
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let v=s??a??void 0,S=s?Gs(s)?s:ep(e,s):void 0,y=n[n.length-1];y&&y.kind==="tool_group"&&y.tool===i?y.items.push({label:l,detail:v,...S?{filePath:S}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:l,detail:v,...S?{filePath:S}:{}}]})}return n}function lp(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.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.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
176
- `)}function pp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Us(o){let e=o.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=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let 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,...n,...t,...r].map(s=>pp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function up(o,e){let t=o.headers.origin;Ws(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 $(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}var mp=16384,fp=131072;async function Be(o,e=mp){let t=[],n=0;for await(let i of o){let s=typeof i=="string"?Buffer.from(i):i;if(n+=s.length,n>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 hp(o,e){let t=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function gp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function yp(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,r,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Jn(o,e){try{o.res.write(`event: ${e.type}
167
+ `)}function Rs(o,e,t){let n=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${a.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),a.feedbackSummary&&n.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&n.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${a.question}"`);else{if(n.push(`### Round ${s} (assistant)`),a.responseText&&n.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let l=d.finalScope??d.inferredScope,w=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${d.annotationId}: ${d.status}${w} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&n.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&n.push(`Tools used: ${a.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.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(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let w=new Map;for(let b of s)if(typeof b=="object"&&b!==null&&"text"in b){let g=b,k=g.scope||"general";w.has(k)||w.set(k,[]),w.get(k).push(g.text)}for(let[b,g]of w){n.push(`**${b.charAt(0).toUpperCase()+b.slice(1)}**`);for(let k of g)n.push(`- ${k}`)}}else for(let w of s)typeof w=="string"&&n.push(`- ${w}`);let a=t.designModel.tokens;a&&typeof a=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(a,null,2)),n.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.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:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.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."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.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 l=d.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(d)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of a){n.push(""),n.push(`## Page: ${d}`);let w=s[d];w&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${w}`):!w&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let b={...e,annotations:l,styleModifications:e.styleModifications},g=On(b,t?.imagePaths,t?.attachmentFiles);g&&(n.push(""),n.push(g))}}else{let s=On(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.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."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.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."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
168
+ `)}function Ps(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function As(o,e,t,n){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: ${o}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let 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("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of n)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output 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(`
169
+ `)}function ml(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function fl(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!ml(e[t]))return!1;return!0}function js(o){let t=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let n=JSON.parse(t);return(Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.annotations)?n.annotations:[]).filter(fl)}catch{return[]}}function hl(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let r=n;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 Ms(o,e){return e>0?hl(o):[]}import{execFile as gl}from"child_process";import{readFile as yl,readdir as Il,stat as wl}from"fs/promises";import{homedir as Dn}from"os";import{join as ot}from"path";var Eo=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:Es()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:Es()}],Nn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Bn={id:"",label:"Default",source:"cli"},vl=/^\s*-\s+"([^"]+)"/;function bl(o){let e=[],t=!1;for(let n of o.split(`
170
+ `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let r=n.match(vl);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Cr(i),source:"cli"})}return _o([Bn,...e])}function xl(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,r)=>{let i=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(n=>{let r=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!r)return[];let i=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():Cr(r),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,a=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function Es(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Sl(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return _o(e.map(t=>({id:t,label:Cr(t),source:"cli"})))}function Cr(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},t=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let i=n[1]==="sonnet"?"Sonn":Pl(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${i}${s}${n[4]?" Fast":""}`}let r=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return t}async function _s(o="copilot"){let e=await Mo(o,["help","config"]),t=bl(e);return t.length>1?t:[Bn]}async function Cs(o="codex"){let e=await Mo(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||ot(Dn(),".codex");return Os(ot(n,"models_cache.json"))}),t=xl(e);return t.length>0?_o([...t,...Nn]):Nn}async function $s(o="claude"){let e=ot(Dn(),".claude"),t=[ot(Dn(),".claude","stats-cache.json"),ot(Dn(),".claude","settings.json"),ot(Dn(),".claude.json"),ot(e,"cache","changelog.md")],[n,r,i]=await Promise.all([Mo(o,["--help"]).catch(()=>""),Mo(o,["--version"]).catch(()=>""),Tl(e).catch(()=>[])]),s=Rl([...t,...i]),a=await Promise.all(s.map(l=>Os(l).catch(()=>""))),d=Sl([n,r,...a].join(`
171
+ `));return _o([...Eo,...d])}function Mo(o,e,t=5e3){return new Promise((n,r)=>{gl(o,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}n(s)})})}async function Os(o){return yl(o,"utf-8")}async function Tl(o){let e=[ot(o,"projects"),ot(o,"telemetry")],t=[];for(let n of e)await Ds(n,t,4);return t.sort((n,r)=>r.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function Ds(o,e,t){if(t<0)return;let n;try{n=await Il(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async r=>{let i=ot(o,r.name);if(r.isDirectory()){await Ds(i,e,t-1);return}if(!(!r.isFile()||!kl(r.name)))try{let s=await wl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function kl(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function _o(o){let e=new Set,t=[];for(let n of o)e.has(n.id)||(e.add(n.id),t.push(n));return t}function Rl(o){return[...new Set(o)]}function Pl(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Co=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 n=t>=0?t+1:0,r=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(n=>n.threadId===e&&(!t||t(n)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let r=this.bufferEvent(t,e);for(let i of this.listeners)i(r,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let r={...t,seq:n.nextSeq++};return n.events.push(r),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),r}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(a=>a.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,t,n){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[t]+=n}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:"Cancelled by user",cancelled:!0,provider:n.provider,model:n.model},n.id,n.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 n of t)try{n.kill("SIGTERM")}catch{}await Promise.all(t.map(n=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!i){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);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 Jn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function $o(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function $r(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Ns(o){let e=$r($o(o.origin));if(e)return e;let t=$r($o(o.referer));if(t)return t;let n=$o(o["x-forwarded-host"]);if(!n)return null;let r=$o(o["x-forwarded-proto"])==="https"?"https":"http";return $r(`${r}://${n}`)}function Bs(o,e,t=5){let n=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(n).slice(0,t),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{mkdir as Al,readFile as Js,realpath as jl,writeFile as Ml}from"fs/promises";import{join as Oo}from"path";async function Dr(o){return jl(o).catch(()=>o)}function qs(o){return Oo(o,".popmelt","store.json")}function El(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function Or(o){let e=await Dr(o);try{let t=JSON.parse(await Js(qs(e),"utf8"));return El(t)?t:null}catch{return null}}async function _l(o){let e=await Dr(o),t=await Or(e);if(t)return t;let n;for(let r of[Oo(e,".popmelt","memory","manifest.json"),Oo(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await Js(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){n=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Jt(e)}`,createdAt:new Date().toISOString()}}async function Do(o){let e=await Dr(o),t=await Or(e);if(t)return t;let n=await _l(e),r=Oo(e,".popmelt");await Al(r,{recursive:!0});try{return await Ml(qs(e),`${JSON.stringify(n,null,2)}
172
+ `,{encoding:"utf8",flag:"wx"}),n}catch(i){let s=await Or(e);if(s)return s;throw i}}import{createHash as Bo,randomUUID as Bl}from"crypto";import{mkdir as Ln,readFile as Ot,writeFile as dn}from"fs/promises";import{dirname as Jo,extname as Jl,join as Ge}from"path";var Cl={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 $l(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function Ls(o,e){let t=e??$l(o);return{kind:t,...Cl[t]}}import{createHash as Ol,randomUUID as Dl}from"crypto";var Fs=o=>`${o}-${Dl()}`;function Nr(o,...e){return`${o}-${Ol("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Br(o){return{schemaVersion:1,submissionIds:[Fs("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function qn(o,e=[],t){return{...o,outcomeId:o.outcomeId??Fs("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function Us(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function Nl(o){let e=[];for(let t of o){if(t.anchor.type!=="dom")continue;let n=t.anchor,r=new Set([n.runtimeSelector,n.structuralSelector,...n.legacySelectors??[]].filter(d=>!!d));if(r.size===0)continue;let i=e.filter(d=>d.anchor.type==="dom"&&d.anchor.pathname===n.pathname&&[d.anchor.runtimeSelector,d.anchor.structuralSelector,...d.anchor.legacySelectors??[]].some(l=>!!(l&&r.has(l)))),s=n.runtimeSelector,a=n.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:n.pathname,...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})}return e}function Jr(o,e=[]){let t=Us(o.url),n=[],r=(i,s,a)=>{!s&&!a||n.push({anchor:{type:"dom",pathname:i||"/",...s?{runtimeSelector:s}:{},...a?{structuralSelector:a}:{}}})};for(let i of o.annotations)i.linkedSelector&&r(i.pathname??t,i.linkedSelector,i.elements[0]?.selector);for(let i of o.styleModifications)r(i.pathname??t,i.selector,i.durableSelector);for(let i of o.textModifications??[])r(i.pathname??t,i.selector,i.durableSelector);for(let i of o.domModifications??[])r(i.pathname??t,i.selector,i.durableSelector);return n.length===0&&e.length>0&&r(t,e.find(i=>i.includes("[data-pm=")),e.find(i=>!i.includes("[data-pm="))),Nl(n)}function zs(o){return Jr(o).flatMap(e=>{if(e.anchor.type!=="dom")return[];let t=e.anchor.structuralSelector??e.anchor.runtimeSelector;return t?[`${e.anchor.pathname}:${t}`]:[]})}function Gs(o,e){let t=Us(o.url);return[...new Set((e??[]).map(n=>`${t}:${n}`))]}function Ws(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(t=>`annotation:${t.id}`),...o.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function No(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Nr("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[Nr("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Nr("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function qr(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=No(o.id,t)||e;return e}function Ks(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:o.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var ql={version:1,threads:{}},Vs=["feedbackContext","annotationSnapshot","requestItems","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Fn={version:2,updatedAt:0,files:{},activeWorkspaceGeneration:0};function zr(o){if(!o.startsWith("/"))return{pathname:"/",selector:o};let e=o.indexOf(":");return e<0?{pathname:"/",selector:o}:{pathname:o.slice(0,e)||"/",selector:o.slice(e+1)}}function Dt(o){return o.type==="opaque"?[o.key,...o.legacyKeys??[]]:[o.runtimeSelector,o.structuralSelector,...o.legacySelectors??[]].filter(e=>!!e)}function Lr(o){return o.type==="opaque"?Dt(o).map(e=>`${o.adapter}:${e}`):Dt(o).map(e=>`${o.pathname}:${e}`)}function zn(o){if(o.length===0)return null;if(o[0].startsWith("codex-session:")){let s=o.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=o.map(zr),t=e[0].pathname,n=e.filter(s=>s.pathname===t).map(s=>s.selector);if(n.length===0)return null;let r=n.find(s=>s.includes("[data-pm=")),i=n.find(s=>s!==r);return{anchor:{type:"dom",pathname:t,...r?{runtimeSelector:r}:{},...i?{structuralSelector:i}:{},...!r&&!i&&n[0]?{structuralSelector:n[0]}:{}}}}function Fr(o,e=[],t=[]){if(t.length>0)return t.filter(n=>Dt(n.anchor).length>0);if(o.length===1){let n=zn([o[0],...e]);return n?[n]:[]}return[...new Set(o)].flatMap(n=>{let r=zn([n]);return r?[r]:[]})}function Ur(o,e=Date.now()){return{id:`target-${Bl()}`,anchor:o.anchor,createdAt:e,updatedAt:e}}function Un(o,e){if(o.anchor.type!==e.anchor.type||o.anchor.type==="opaque"&&e.anchor.type==="opaque"&&o.anchor.adapter!==e.anchor.adapter||o.anchor.type==="dom"&&e.anchor.type==="dom"&&o.anchor.pathname!==e.anchor.pathname)return null;if(o.anchor.type==="opaque"&&e.anchor.type==="opaque"){let i=new Set(Dt(e.anchor));return Dt(o.anchor).some(s=>i.has(s))?["adapter_key"]:null}if(o.anchor.type!=="dom"||e.anchor.type!=="dom")return null;let t=[];o.anchor.runtimeSelector&&o.anchor.runtimeSelector===e.anchor.runtimeSelector&&t.push("runtime_selector"),o.anchor.structuralSelector&&o.anchor.structuralSelector===e.anchor.structuralSelector&&t.push("structural_selector");let n=new Set(Dt(e.anchor));return Dt(o.anchor).some(i=>n.has(i))?(t.length===0&&t.push("legacy_selector"),t):null}function Ll(o,e){return Un(o,e)!==null}function Fl(o){return JSON.stringify(o,null,2)}function Ul(o){return Object.fromEntries(Vs.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function zl(o){let e={...o};for(let t of Vs)delete e[t];return e}function cn(o){let e=o;if(o.error){let t=Ls(o.error,o.errorKind);(o.error!==t.message||o.errorKind!==t.kind||o.responseText!==void 0)&&(e={...o,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=tn(e.result,!1),n=tn(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var qo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();this.continuationChain=Promise.resolve();let t=Ge(e,".popmelt");this.legacyFilePath=Ge(t,"threads.json"),this.threadsDir=Ge(t,"threads"),this.indexPath=Ge(this.threadsDir,"index.json"),this.artifactsDir=Ge(t,"artifacts","thread-messages"),this.mediaDir=Ge(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Ot(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(Ge(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let n=!1;for(let r of Object.values(t))n=qr(r)||n;return n=this.migrateTargetBindings()||n,n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Ot(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(cn)}]))},this.index={...Fn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))qr(t);return this.migrateTargetBindings(),await this.persistAll(),this.cache}}catch{}return this.cache={...ql,threads:{}},this.index={...Fn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async isTargetBindingContinuationEligible(e,t){let n=await this.load(),r=this.getActiveWorkspaceGeneration(),i=n.threads[e],s=i?.targetBindings?.find(l=>l.id===t);if(!i||!s||i.archivedAt!==void 0||(i.workspaceGeneration??0)!==r)return!1;let a={anchor:s.anchor},d=Object.values(n.threads).flatMap(l=>l.archivedAt!==void 0?[]:(l.workspaceGeneration??0)!==r?[]:(l.targetBindings??[]).filter(w=>Ll(w,a)));return d.length===1&&d[0].id===t}async findContinuationThread(e,t,n=[],r=[],i){return(await this.findContinuationTarget(e,n,r,t,i)).match?.thread??null}async findContinuationTarget(e,t,n,r,i){let s=await this.load(),a=this.getActiveWorkspaceGeneration(),d=r?s.threads[r]:void 0,l=r?d?d.archivedAt!==void 0?"archived":(d.workspaceGeneration??0)!==a?"stale_generation":void 0:"missing_thread":void 0,w=d&&d.archivedAt===void 0&&(d.workspaceGeneration??0)===a,b=Fr(e,w?t:[],n);if(b.length!==1)return{match:null,decision:{action:"created",basis:b.length>1?"batch":"new_target",...l?{rejectedPreference:l}:{},matchCount:0}};if(w){let x=d.targetBindings??[];if(i){let u=x.find(I=>I.id===i);if(!u)return{match:null,decision:{action:"created",basis:"new_target",rejectedPreference:"missing_binding",matchCount:0}};let y=Un(u,b[0]);return y?{match:{thread:d,binding:u},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(x.length===1){let u=x[0],y=Un(u,b[0]);return{match:{thread:d,binding:u},decision:{action:"continued",basis:"preferred",...y?{evidence:y}:{},matchCount:1}}}let h=x.flatMap(u=>{let y=Un(u,b[0]);return y?[{binding:u,evidence:y}]:[]});if(h.length===1){let u=h[0];return{match:{thread:d,binding:u.binding},decision:{action:"continued",basis:"preferred",evidence:u.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(x=>x.archivedAt!==void 0?[]:(x.workspaceGeneration??0)!==a?[]:(x.targetBindings??[]).flatMap(h=>{let u=Un(h,b[0]);return u?[{thread:x,binding:h,evidence:u}]:[]})),k=g.length===1?g[0]:null;return{match:k,decision:k?{action:"continued",basis:"unique_match",evidence:k.evidence,...l?{rejectedPreference:l}:{},matchCount:1}:{action:"created",basis:g.length>1?"ambiguous":"new_target",...l?{rejectedPreference:l}:{},matchCount:g.length}}}async createThread(e,t,n=[]){await this.load();let r=Fr(t,[],n);return this.createThreadRecord(e,t,r)}async createThreadRecord(e,t,n){let r=await this.load(),i={id:e,lifecycleVersion:1,workspaceGeneration:this.getActiveWorkspaceGeneration(),createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,targetBindings:n.map(s=>Ur(s)),messages:[]};return r.threads[e]=i,await this.persistThread(i),i}async findOrCreateContinuationThread(e,t,n,r=[],i=[],s){return this.serializeContinuationMutation(async()=>{await this.load();let a=Fr(e,r,i),d=await this.findContinuationTarget(e,r,a,n,s),l=d.match;if(l)return l.binding.anchor=a[0].anchor,l.binding.updatedAt=Date.now(),l.thread.updatedAt=Date.now(),await this.persistThread(l.thread),{thread:l.thread,decision:d.decision,targetBindings:[l.binding]};let w=await this.createThreadRecord(t,e,a);return{thread:w,decision:d.decision,targetBindings:w.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&&(No(e,t),r.messages.push(cn(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;No(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,cn(t)):r.messages.push(cn(t)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,t,n){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,n),a.error){let d=cn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,t,n){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,n),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=zn(t);!i||!s||(i.anchor=s.anchor,i.updatedAt=Date.now(),r.updatedAt=Date.now(),await this.persistThread(r))}async archiveThread(e){let n=(await this.load()).threads[e];return n?(n.archivedAt=n.archivedAt??Date.now(),n.updatedAt=Date.now(),await this.persistThread(n),!0):!1}async advanceWorkspaceGeneration(){return this.serializeContinuationMutation(async()=>{await this.load();let e=this.index??{...Fn,files:{}},t=(e.activeWorkspaceGeneration??0)+1;return e.activeWorkspaceGeneration=t,e.updatedAt=Date.now(),this.index=e,this.writeChain=this.writeChain.then(async()=>{await Ln(this.threadsDir,{recursive:!0}),await dn(this.indexPath,JSON.stringify(e,null,2))}),await this.writeChain,t})}async listRecent(e=5){let t=await this.load(),n=this.getActiveWorkspaceGeneration(),r=Object.values(t.threads).filter(s=>s.archivedAt===void 0&&(s.workspaceGeneration??0)===n),i=new Map;for(let s of r)for(let a of s.targetBindings??[]){let d=`${s.id}:${a.id}`;for(let l of Lr(a.anchor)){let w=i.get(l)??new Set;w.add(d),i.set(l,w)}}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,l=a?.feedbackSummary||"[thread]",b=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},x=s.messages.findLastIndex(m=>!!k(m)),h=s.messages.findLastIndex(m=>m.role==="human"),u=x>h?k(s.messages[x]):void 0,y=s.messages.at(-1)?.role,I=Array.from(new Set(s.messages.slice(0,Math.max(0,h)).filter(m=>m.role==="assistant"&&!!m.jobId).map(m=>m.jobId))),p=g.some(m=>!!m.responseText||!!m.question||!!m.result||!!m.memoryReviewCard||!!m.memoryReceipt),A=g.some(m=>!!m.error);return{id:s.id,createdAt:s.createdAt,updatedAt:s.updatedAt,preview:l,messageCount:s.messages.length,hasReply:p,hasError:A,lastMessageRole:y,pendingQuestion:u,acknowledgedJobIds:I,elementIdentifiers:s.elementIdentifiers,elementSelectorAliases:[...new Set([...s.elementSelectorAliases??[],...(s.targetBindings??[]).flatMap(m=>Lr(m.anchor))])],targetBindings:s.targetBindings?.map(m=>({...m,continuationEligible:Lr(m.anchor).every(f=>(i.get(f)?.size??0)===1)})),color:d,annotationNumber:b,lifecycle:Ks(s)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){if(n.archivedAt!==void 0)continue;let r=n.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=qn(r.lifecycle);r.queued&&await this.updateMessage(n.id,r.jobId,{queued:!1}),await this.appendMessage(n.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 n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await Ot(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let{version:n,messages:r,...i}=t,s=await Promise.all(r.map(async({detailArtifact:a,...d})=>{let l={};if(a?.path)try{let w=await Ot(Ge(Jo(this.legacyFilePath),a.path),"utf8");Bo("sha256").update(w).digest("hex")===a.sha256&&(l=JSON.parse(w))}catch{}return cn({...d,...l})}));return{...i,messages:s}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=Ul(e),n=zl(e);if(Object.keys(t).length===0)return n;let r=Fl(t),i=Bo("sha256").update(r).digest("hex"),s=Ge("artifacts","thread-messages",`${i}.json`);await Ln(this.artifactsDir,{recursive:!0});try{await Ot(Ge(Jo(this.legacyFilePath),s),"utf8")}catch{await dn(Ge(Jo(this.legacyFilePath),s),r)}return{...n,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async n=>{if(Jo(n)===this.mediaDir)return n;try{let r=await Ot(n),i=Bo("sha256").update(r).digest("hex"),s=Ge(this.mediaDir,`${i}${Jl(n)||".bin"}`);await Ln(this.mediaDir,{recursive:!0});try{await Ot(s)}catch{await dn(s,r)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,r])=>[n,await t(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,r])=>[n,await Promise.all(r.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,r])=>[n,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 Ln(this.threadsDir,{recursive:!0});let t=this.index??{...Fn,files:{}},n=t.files[e.id]??`${Bo("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 dn(Ge(this.threadsDir,n),JSON.stringify(i,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await dn(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=zn([i.anchor.structuralSelector]);s&&(i.anchor=s.anchor,i.updatedAt=Date.now(),e=!0)}continue}let n=(t.elementIdentityIds??[]).flatMap(i=>this.index?.elementIdentities?.[i]?.aliases??[]),r=t.elementIdentifiers.flatMap(i=>{if(i.startsWith("codex-session:")){let g=zn([i]);return g?[Ur(g)]:[]}let s=zr(i),a=t.elementIdentifiers.length===1?[...t.elementSelectorAliases??[],...n].map(zr).filter(g=>g.pathname===s.pathname).map(g=>g.selector):[],d=[s.selector,...a].find(g=>g.includes("[data-pm=")),l=[s.selector,...a].find(g=>!g.includes("[data-pm=")),w=new Set([d,l].filter(Boolean)),b=[...new Set(a)].filter(g=>!w.has(g));return[Ur({anchor:{type:"dom",pathname:s.pathname,...d?{runtimeSelector:d}:{},...l?{structuralSelector:l}:{},...b.length>0?{legacySelectors:b}:{}}})]});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 Ln(this.threadsDir,{recursive:!0}),this.index=this.index??{...Fn,files:{}},await dn(this.indexPath,JSON.stringify(this.index,null,2)))}}};import{mkdir as Gl,open as Wl,readFile as Kl,rename as Vl,unlink as Hl}from"fs/promises";import{dirname as Ql,join as Xl}from"path";var Hs={schemaVersion:1,theme:"auto",updatedAt:null};function Qs(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Yl(o,e){await Gl(Ql(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await Wl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
173
+ `,"utf8"),await n.sync()}finally{await n.close()}await Vl(t,o)}catch(n){throw await Hl(t).catch(()=>{}),n}}var Lo=class{constructor(e){this.path=Xl(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Kl(this.path,"utf8")),t=Qs(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Hs}}}catch{return{exists:!1,preferences:{...Hs}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Yl(this.path,t),t}};function Xs(o){return Qs(o)!==null}var lp=1111,pp=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],up=1800*1e3,mp=3600*1e3,Zs=45e3,fp=5e3,hp=1e4,gp=2*1024*1024;function ea(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
174
+ `)}function Gn(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function ta(o){let e=o.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let t=o[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=o.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function yp(o,e){if(e.size===1)return[...o].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function sa(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Ip(o,e,t){let n=[...t];for(let r of o)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,l;switch(i){case"Read":l=d?`Reading ${d}`:"Reading file";break;case"Edit":l=d?`Editing ${d}`:"Editing file";break;case"Write":l=d?`Writing ${d}`:"Writing file";break;case"Bash":l=a?a.split(`
175
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let w=s??a??void 0,b=s?ia(s)?s:cp(e,s):void 0,g=n[n.length-1];g&&g.kind==="tool_group"&&g.tool===i?g.items.push({label:l,detail:w,...b?{filePath:b}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:l,detail:w,...b?{filePath:b}:{}}]})}return n}function wp(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.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.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
176
+ `)}function vp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function na(o){let e=o.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=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=o.annotations.map(s=>{let 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,...n,...t,...r].map(s=>vp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function bp(o,e){let t=o.headers.origin;sa(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(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}var xp=16384,Sp=131072;async function Ne(o,e=xp){let t=[],n=0;for await(let i of o){let s=typeof i=="string"?Buffer.from(i):i;if(n+=s.length,n>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 Tp(o,e){let t=[],n=0;for await(let r of o){let i=typeof r=="string"?Buffer.from(r):r;if(n+=i.length,n>e)throw new Error("Request body too large");t.push(i)}return Buffer.concat(t)}function kp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function Rp(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,r,i]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Wn(o,e){try{o.res.write(`event: ${e.type}
177
177
  data: ${JSON.stringify(e)}
178
178
 
179
- `)}catch{}}function cn(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function ln(o){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}var Fs=3e3;function Ip(o){let e=Array.isArray(o.activeJobs)?o.activeJobs:[],t=o.leases&&typeof o.leases=="object"?o.leases:void 0;return o.activeJob!=null||e.length>0||typeof o.queueDepth=="number"&&o.queueDepth>0||typeof o.projectionQueueDepth=="number"&&o.projectionQueueDepth>0||typeof t?.count=="number"&&t.count>0}async function wp(o,e){for(let t=o;t<o+9;t++){let n=await ln(t);if(n?.projectId!==e||n.restartMode!=="detached")continue;if(Ip(n))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()+Fs;for(;Date.now()<i;)if(await new Promise(s=>setTimeout(s,50)),!await ln(t))return;throw new Error(`[Bridge] Detached bridge on port ${t} did not stop within ${Fs/1e3}s.`)}}function vp(o,e){return new Promise((t,n)=>{let r=s=>{o.removeListener("listening",i),n(s)},i=()=>{o.removeListener("error",r),t()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}async function Vs(o={}){let e=new Date().toISOString(),t=o.port??tp,n=o.projectRoot??process.cwd(),r=await Kl(n).catch(()=>n),i=Nt(r),s=await Ao(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=o.tempDir??Ye(Yl(),"popmelt-bridge"),l=o.maxTurns??40,v=o.maxBudgetUsd??1,S=[...o.allowedTools??np],y=o.claudePath??"claude",k=o.copilotPath??"copilot",T=o.provider??"codex",g=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,I=o.restartMode??"embedded";I==="embedded"&&await wp(t,i);let f=t,p={},j={claude:y,codex:"codex",copilot:k};for(let[c,b]of Object.entries(j))try{let C=b.includes("/")?b:zl("which",[b],{encoding:"utf-8"}).trim();p[c]={available:!0,path:C}}catch{p[c]={available:!1,path:null}}function h(c,b){return new Promise(C=>{let w=Bs(b,["--version"],{stdio:["ignore","ignore","ignore"]}),_=!1,R=B=>{_||(_=!0,C(B))},N=setTimeout(()=>{w.kill("SIGTERM"),R(!0)},5e3);w.on("error",()=>{clearTimeout(N),R(!1)}),w.on("close",B=>{clearTimeout(N),R(B===0)})})}await Promise.all([(async()=>{p.claude&&(p.claude.models=p.claude.available&&p.claude.path?await xs(p.claude.path).catch(()=>So):So)})(),(async()=>{p.codex&&(p.codex.models=p.codex.available&&p.codex.path?await bs(p.codex.path).catch(()=>$n):$n)})(),(async()=>{p.copilot&&(p.copilot.models=p.copilot.available&&p.copilot.path?await vs(p.copilot.path).catch(()=>[On]):[On])})()]);let[m,M,D]=await Promise.all([br(r),xr(r),Sr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=m),p.codex&&(p.codex.mcp=M),p.copilot&&(p.copilot.mcp=D),m.found&&m.name&&S.push(`mcp__${m.name}__*`),await Gl(d,{recursive:!0}),zs(d).catch(()=>{});let P=new ko(1),A=new Io,Q=new fo(Js),z=null,E=0,G=!1,W=()=>{E+=1,G=!1,z&&clearTimeout(z),z=null},ue=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(I!=="detached"||Q.size>0||G)return;G=!0;let c=++E,b=Date.now()+sp,C=()=>{if(c!==E)return;if(Q.size>0){W();return}if(!(P.isRunning||P.depth>0||A.isRunning||A.depth>0)||Date.now()>=b){G=!1,z=setTimeout(ue,50),z.unref?.();return}z=setTimeout(C,250),z.unref?.()};C()},re=new Set,x=new Co(r),O=await x.recoverInterruptedTurns();O>0&&console.warn(`[Popmelt] Recovered ${O} interrupted thread turn(s) from durable history.`);let q=new po(r);q.sweep();let J=new Yt(r),H=new It(r,i);try{let c=await H.store.migrateTopology();c.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${c.relationMutations} relation mutation(s)).`)}catch(c){console.warn(`[Popmelt] Imprint topology migration deferred: ${c instanceof Error?c.message:String(c)}`)}let he=new $o(r),$e=new so(r),se=new yo(r,{claudePath:y,provider:T,timeoutMs:g,loadProjectableDecisions:c=>J.getProjectableDecisions(c),onEvent:c=>{for(let b of re)Jn(b,c)}}),Je=new eo({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:x,memoryService:J,imprintService:H,loadConcreteModel:()=>se.loadModel()});J.beginAutomaticInitialization({writerVersion:st}).then(async c=>{c.state==="ready"?(await J.migrateImprintSnapshot(),await J.syncImprintGraph(),await se.applyCanonicalEntries(await J.getCanonicalModelEntries()),T!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Oe({provider:T,reason:"Project accepted decisions that were waiting when the bridge restarted"})):c.state==="degraded"&&console.warn(`[\u22B9 ${f}] Product memory is degraded; legacy preview remains available: ${c.error}`)});let vt=20,pn=300*1e3,Pe=[];function ot(){let c=Date.now()-pn;for(;Pe.length>0&&(Pe[0].completedAt<c||Pe.length>vt);)Pe.shift()}let bt=new Map;P.addListener((c,b,C)=>{for(let w of re)(!C||!w.sourceId||w.sourceId===C)&&Jn(w,c)}),A.addListener((c,b,C)=>{for(let w of re)(!C||!w.sourceId||w.sourceId===C)&&Jn(w,c)}),A.setProcessor(async c=>{let b=c.provider??T;try{let C=await se.run({provider:b,model:c.model,threadId:c.threadId,presentationJobId:c.id,agentSettings:c.agentSettings});if(c.status==="cancelled")return;let w=await se.loadRuns(),_=C.runId?w.runs.find(N=>N.id===C.runId):void 0;if(C.success&&C.proposalId){let N=await se.findModelProposal(C.proposalId),B=await se.loadModel(),U=N?Qi(N,B):null;if(N&&U){let L=N.decisionIds.map(F=>({decisionId:F,status:"projected"}));await J.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:L}),await se.applySelectedModelProposal(N.id,U.map(F=>({path:F.path,value:F.value})),U.map(F=>({group:F.path[0]==="rules"||F.path[0]==="components"||F.path[0]==="tokens"?F.path[0]:"model",label:F.label??F.id,detail:F.rationale,path:F.path,value:F.value})),"automatic")}}let R=lp(C,_);if(c.threadId&&(await x.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:R,model:c.model,provider:b})||await x.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:R,model:c.model,provider:b})),C.success)c.status="done",c.result=R,A.broadcast({type:"done",jobId:c.id,success:!0,responseText:R,threadId:c.threadId},c.id,c.sourceId),Pe.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),ot();else{if(c.status="error",c.error=C.error??"Projection failed",c.threadId){let N=`Model projection failed.
179
+ `)}catch{}}function ln(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function pn(o){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}var oa=3e3;function Pp(o){let e=Array.isArray(o.activeJobs)?o.activeJobs:[],t=o.leases&&typeof o.leases=="object"?o.leases:void 0;return o.activeJob!=null||e.length>0||typeof o.queueDepth=="number"&&o.queueDepth>0||typeof o.projectionQueueDepth=="number"&&o.projectionQueueDepth>0||typeof t?.count=="number"&&t.count>0}async function Ap(o,e){for(let t=o;t<o+9;t++){let n=await pn(t);if(n?.projectId!==e||n.restartMode!=="detached")continue;if(Pp(n))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()+oa;for(;Date.now()<i;)if(await new Promise(s=>setTimeout(s,50)),!await pn(t))return;throw new Error(`[Bridge] Detached bridge on port ${t} did not stop within ${oa/1e3}s.`)}}function jp(o,e){return new Promise((t,n)=>{let r=s=>{o.removeListener("listening",i),n(s)},i=()=>{o.removeListener("error",r),t()};o.once("error",r),o.once("listening",i),o.listen(e,"127.0.0.1")})}async function aa(o={}){let e=new Date().toISOString(),t=o.port??lp,n=o.projectRoot??process.cwd(),r=await op(n).catch(()=>n),i=Jt(r),s=await Do(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=o.tempDir??Ye(ap(),"popmelt-bridge"),l=o.maxTurns??40,w=o.maxBudgetUsd??1,b=[...o.allowedTools??pp],g=o.claudePath??"claude",k=o.copilotPath??"copilot",x=o.provider??"codex",h=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,y=o.restartMode??"embedded";y==="embedded"&&await Ap(t,i);let I=t,p={},A={claude:g,codex:"codex",copilot:k};for(let[c,S]of Object.entries(A))try{let O=S.includes("/")?S:Zl("which",[S],{encoding:"utf-8"}).trim();p[c]={available:!0,path:O}}catch{p[c]={available:!1,path:null}}function m(c,S){return new Promise(O=>{let T=Ys(S,["--version"],{stdio:["ignore","ignore","ignore"]}),C=!1,P=D=>{C||(C=!0,O(D))},B=setTimeout(()=>{T.kill("SIGTERM"),P(!0)},5e3);T.on("error",()=>{clearTimeout(B),P(!1)}),T.on("close",D=>{clearTimeout(B),P(D===0)})})}await Promise.all([(async()=>{p.claude&&(p.claude.models=p.claude.available&&p.claude.path?await $s(p.claude.path).catch(()=>Eo):Eo)})(),(async()=>{p.codex&&(p.codex.models=p.codex.available&&p.codex.path?await Cs(p.codex.path).catch(()=>Nn):Nn)})(),(async()=>{p.copilot&&(p.copilot.models=p.copilot.available&&p.copilot.path?await _s(p.copilot.path).catch(()=>[Bn]):[Bn])})()]);let[f,j,$]=await Promise.all([kr(r),Rr(r),Pr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=f),p.codex&&(p.codex.mcp=j),p.copilot&&(p.copilot.mcp=$),f.found&&f.name&&b.push(`mcp__${f.name}__*`),await ep(d,{recursive:!0}),ra(d).catch(()=>{});let R=new Co(1),_=new Ro,X=new xo(Zs),G=null,M=0,L=!1,W=()=>{M+=1,L=!1,G&&clearTimeout(G),G=null},ie=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},Q=()=>{if(y!=="detached"||X.size>0||L)return;L=!0;let c=++M,S=Date.now()+hp,O=()=>{if(c!==M)return;if(X.size>0){W();return}if(!(R.isRunning||R.depth>0||_.isRunning||_.depth>0)||Date.now()>=S){L=!1,G=setTimeout(ie,50),G.unref?.();return}G=setTimeout(O,250),G.unref?.()};O()},ee=new Set,v=new qo(r),E=await v.recoverInterruptedTurns();E>0&&console.warn(`[Popmelt] Recovered ${E} interrupted thread turn(s) from durable history.`);let J=new wo(r);J.sweep();let q=new en(r),H=new wt(r,i);try{let c=await H.store.migrateTopology();c.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${c.relationMutations} relation mutation(s)).`)}catch(c){console.warn(`[Popmelt] Imprint topology migration deferred: ${c instanceof Error?c.message:String(c)}`)}let ge=new Lo(r),_e=new ho(r),ue=new ko(r,{claudePath:g,provider:x,timeoutMs:h,loadProjectableDecisions:c=>q.getProjectableDecisions(c),onEvent:c=>{for(let S of ee)Wn(S,c)}}),Be=new co({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:v,memoryService:q,imprintService:H,loadConcreteModel:()=>ue.loadModel()});q.beginAutomaticInitialization({writerVersion:st}).then(async c=>{c.state==="ready"?(await q.migrateImprintSnapshot(),await q.syncImprintGraph(),await ue.applyCanonicalEntries(await q.getCanonicalModelEntries()),x!=="copilot"&&(await ue.getUnprojectedPatternDecisions()).length>0&&await Oe({provider:x,reason:"Project accepted decisions that were waiting when the bridge restarted"})):c.state==="degraded"&&console.warn(`[\u22B9 ${I}] Product memory is degraded; legacy preview remains available: ${c.error}`)});let bt=20,un=300*1e3,Me=[];function rt(){let c=Date.now()-un;for(;Me.length>0&&(Me[0].completedAt<c||Me.length>bt);)Me.shift()}let xt=new Map;R.addListener((c,S,O)=>{for(let T of ee)(!O||!T.sourceId||T.sourceId===O)&&Wn(T,c)}),_.addListener((c,S,O)=>{for(let T of ee)(!O||!T.sourceId||T.sourceId===O)&&Wn(T,c)}),_.setProcessor(async c=>{let S=c.provider??x;try{let O=await ue.run({provider:S,model:c.model,threadId:c.threadId,presentationJobId:c.id,agentSettings:c.agentSettings});if(c.status==="cancelled")return;let T=await ue.loadRuns(),C=O.runId?T.runs.find(B=>B.id===O.runId):void 0;if(O.success&&O.proposalId){let B=await ue.findModelProposal(O.proposalId),D=await ue.loadModel(),z=B?ds(B,D):null;if(B&&z){let F=B.decisionIds.map(U=>({decisionId:U,status:"projected"}));await q.applyModelProjection({runId:B.runId??B.id,presentationJobId:B.presentationJobId,decisionIds:B.decisionIds,changes:z.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:F}),await ue.applySelectedModelProposal(B.id,z.map(U=>({path:U.path,value:U.value})),z.map(U=>({group:U.path[0]==="rules"||U.path[0]==="components"||U.path[0]==="tokens"?U.path[0]:"model",label:U.label??U.id,detail:U.rationale,path:U.path,value:U.value})),"automatic")}}let P=wp(O,C);if(c.threadId&&(await v.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:P,model:c.model,provider:S})||await v.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:P,model:c.model,provider:S})),O.success)c.status="done",c.result=P,_.broadcast({type:"done",jobId:c.id,success:!0,responseText:P,threadId:c.threadId},c.id,c.sourceId),Me.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),rt();else{if(c.status="error",c.error=O.error??"Projection failed",c.threadId){let B=`Model projection failed.
180
180
 
181
- ${c.error}`;await x.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:N,error:c.error,model:c.model,provider:b})||await x.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:N,error:c.error,model:c.model,provider:b})}A.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:b,model:c.model},c.id,c.sourceId),Pe.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),ot()}}catch(C){if(c.status==="cancelled")return;if(c.status="error",c.error=C instanceof Error?C.message:String(C),c.threadId){let w=`Model projection failed.
181
+ ${c.error}`;await v.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:B,error:c.error,model:c.model,provider:S})||await v.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:B,error:c.error,model:c.model,provider:S})}_.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:S,model:c.model},c.id,c.sourceId),Me.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),rt()}}catch(O){if(c.status==="cancelled")return;if(c.status="error",c.error=O instanceof Error?O.message:String(O),c.threadId){let T=`Model projection failed.
182
182
 
183
- ${c.error}`;await x.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:w,error:c.error,model:c.model,provider:b})||await x.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:w,error:c.error,model:c.model,provider:b})}A.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:b,model:c.model},c.id,c.sourceId),Pe.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),ot()}}),P.setProcessor(async c=>{let b=c,C=b._replyPrompt,w=b._replyText,_=b._replyImagePaths,R=c.provider??T,N=!!(c.surfacedProposalIds?.length&&C),B=!N&&!["synthesize","project_model"].includes(c.kind??"");c.threadId&&w!==void 0&&await x.updateMessage(c.threadId,c.id,{queued:!1});let U;if(c.threadId){let te=await x.getThread(c.threadId);if(te){for(let we=te.messages.length-1;we>=0;we--)if(te.messages[we].sessionId){U=te.messages[we].sessionId;break}}}N&&(U=void 0);let L;if(U&&C){if(L=w??C,_&&_.length>0){L+=`
183
+ ${c.error}`;await v.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:T,error:c.error,model:c.model,provider:S})||await v.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:T,error:c.error,model:c.model,provider:S})}_.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:S,model:c.model},c.id,c.sourceId),Me.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),rt()}}),R.setProcessor(async c=>{let S=c,O=S._replyPrompt,T=S._replyText,C=S._replyImagePaths,P=c.provider??x,B=!!(c.surfacedProposalIds?.length&&O),D=!B&&!["synthesize","project_model"].includes(c.kind??"");c.threadId&&T!==void 0&&await v.updateMessage(c.threadId,c.id,{queued:!1});let z;if(c.threadId){let te=await v.getThread(c.threadId);if(te){for(let ye=te.messages.length-1;ye>=0;ye--)if(te.messages[ye].sessionId){z=te.messages[ye].sessionId;break}}}B&&(z=void 0);let F;if(z&&O){if(F=T??O,C&&C.length>0){F+=`
184
184
 
185
- The developer attached reference images with their reply:`;for(let te of _)L+=`
186
- Attached image: use the Read tool to view the image at: ${te}`}c.kind==="synthesize"?L+=`
185
+ The developer attached reference images with their reply:`;for(let te of C)F+=`
186
+ Attached image: use the Read tool to view the image at: ${te}`}c.kind==="synthesize"?F+=`
187
187
 
188
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:L+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(U)L=_n(c.feedback,c.imagePaths,c.attachmentFiles)+`
188
+ Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(z)F=On(c.feedback,c.imagePaths,c.attachmentFiles)+`
189
189
 
190
190
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
191
191
 
192
- After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(R!=="codex"?`
192
+ After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(P!=="codex"?`
193
193
 
194
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${c.screenshotPath}`:"");else{let te=!C&&c.threadId?await x.getThreadHistory(c.threadId):void 0,we=C?null:await se.loadModel();L=C??fs(c.screenshotPath,c.feedback,{threadHistory:te&&te.length>0?te:void 0,provider:R,imagePaths:c.imagePaths,attachmentFiles:c.attachmentFiles,designModel:we??void 0,screenshotPaths:c.screenshotPaths})}L+=fn(c.memoryReview),B&&(L+=Ft(c.imprintContext,{requestText:w??zt(c.feedback)})),c.threadId&&!N&&(L+=`
194
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${c.screenshotPath}`:"");else{let te=!O&&c.threadId?await v.getThreadHistory(c.threadId):void 0,ye=O?null:await ue.loadModel();F=O??Rs(c.screenshotPath,c.feedback,{threadHistory:te&&te.length>0?te:void 0,provider:P,imagePaths:c.imagePaths,attachmentFiles:c.attachmentFiles,designModel:ye??void 0,screenshotPaths:c.screenshotPaths})}F+=yn(c.memoryReview),D&&(F+=Gt(c.imprintContext,{requestText:T??Wt(c.feedback)})),c.threadId&&!B&&(F+=`
195
195
 
196
- ${ms}`),L+=`
196
+ ${ks}`),F+=`
197
197
 
198
- ${us}`;let F=yp(c.color,`[\u22B9 ${f}:${c.id}]`),ge=c.screenshotPaths&&Object.keys(c.screenshotPaths).length>0?`${Object.keys(c.screenshotPaths).length} pages [${Object.keys(c.screenshotPaths).join(", ")}]`:c.screenshotPath;console.log(`${F} Reviewing ${ge} (provider: ${R})${c.threadId?` (thread: ${c.threadId})`:""}${U?` (resuming: ${U.slice(0,8)})`:""}`);let K=new bo(c.id),de=new mo(c.id,c.imprintContext),Y=(te,we)=>{if(te.type==="delta"&&"text"in te){let De=de.push(te.text),ze=K.push(De.visibleText);ze.visibleText&&(P.accumulateText(we,"response",ze.visibleText),P.broadcast({...te,text:ze.visibleText},we,c.sourceId));for(let Ne of ze.orientations)P.broadcast({type:"orientation",jobId:we,orientation:Ne},we,c.sourceId);for(let Ne of De.usages)P.broadcast({type:"imprint_used",jobId:we,usage:Ne},we,c.sourceId);return}else te.type==="thinking"&&"text"in te&&P.accumulateText(we,"thinking",te.text);P.broadcast(te,we,c.sourceId)},{process:ce,result:me}=R==="codex"?io(c.id,{prompt:L,projectRoot:r,screenshotPath:c.screenshotPath,resumeSessionId:U,model:c.model,sandboxMode:N?"read-only":void 0,configOverrides:Un(c.agentSettings),onEvent:Y}):R==="copilot"?Bi(c.id,{prompt:L,projectRoot:r,resumeSessionId:U,model:c.model,timeoutMs:g,copilotPath:p.copilot?.path??k,onEvent:Y}):to(c.id,{prompt:L,projectRoot:r,maxTurns:l,maxBudgetUsd:v,allowedTools:N?["Read"]:S,claudePath:y,resumeSessionId:U,model:c.model,reasoningEffort:c.agentSettings?.reasoningEffort,timeoutMs:g,onEvent:Y});P.setActiveProcess(c.id,ce);let ee=await me,xe=[...(ee.fileEdits??[]).map(te=>te.file_path),...(ee.editEvents??[]).flatMap(te=>te.filePath?[te.filePath]:[])],Ae=de.finalize(ee.text),ie=Ar(Ae.visibleText,c.id),Me=K.finalize(Ae.visibleText),be=ie.visibleText,Z=ys(be),ye=B?Ut(be,{context:c.imprintContext,requestText:w??zt(c.feedback),applicationOccurred:xe.length>0||Z.some(te=>te.status==="resolved")}):{visibleText:be,draft:void 0,error:void 0},it=ye.visibleText,Ee=B?ye.error?{state:ye.error.includes("missing")?"missing":"invalid",reason:ye.error}:ye.draft?.decision==="none"?{state:"none",reason:ye.draft.reason}:ye.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let te of Me.orientations)P.broadcast({type:"orientation",jobId:c.id,orientation:te},c.id,c.sourceId);for(let te of Ae.usages)P.broadcast({type:"imprint_used",jobId:c.id,usage:te},c.id,c.sourceId);if(c.result=it,ee.success){console.log(`${F} Iteration complete`),ee.fileEdits&&ee.fileEdits.length>0&&console.log(`${F} Captured ${ee.fileEdits.length} file edit(s): ${ee.fileEdits.map(ae=>`${ae.tool} ${ae.file_path}`).join(", ")}`),ee.editEvents&&ee.editEvents.length>0&&console.log(`${F} Captured ${ee.editEvents.length} edit event(s): ${ee.editEvents.map(ae=>`${ae.operation} ${ae.filePath}`).join(", ")}`),c.status="done";let te=hs(be),we=Z;if(we.length>0&&c.annotationIds&&c.annotationIds.length>0){let ae=new Set(c.annotationIds);we.every(Ze=>ae.has(Ze.annotationId))||(we=we.map((Ze,Tt)=>({...Ze,annotationId:c.annotationIds[Tt%c.annotationIds.length]})))}let De=ee.fileEdits&&ee.fileEdits.length>0?ee.fileEdits.map(ae=>`${ae.tool} ${ae.file_path.split("/").pop()}`):ee.toolsUsed,ze=P.getBufferedEvents(c.id),Ne=cp(ze?.events??[],r,ie.segments),_e,Ve=cs(be),V=ds(be);if(V)if(!(c.memoryReview?.packets.some(le=>le.proposalId===V.proposalId)||c.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 J.commitConversationalReview(V)}catch(le){_e={status:"rejected",action:V.action,proposalId:V.proposalId,message:le instanceof Error?le.message:String(le)}}let Ie=Is(be,xe.length),fe,ne,je,Ke,Lo=c.imprintContext?.pendingGroundingExplanationIds??[];if(ye.draft){let ae=ye.draft.decision==="recognize"?[ye.draft.explanationId]:[],le=ye.draft.decision==="recognize"?ae:[...ye.draft.usedExplanationIds??[],...ye.draft.appliedExplanationIds??[]],Ze=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];le.length>0&&(je=[...new Set(le)]),Ze.length>0&&(Ke=[...new Set(Ze)])}ye.draft?.decision==="none"&&H.recordNoop(ye.draft.reason);let Ln=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Ln&&!V&&!Ve){let ae=c.imprintContext?.explanations.find(le=>le.id===Ln.explanationId&&le.state==="grounded");ae?ne={explanationId:ae.id,title:Ln.summary.title,detail:Ln.summary.detail,statement:ae.statement}:Ee={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Uo=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(c.threadId&&Uo&&!V&&!Ve)try{fe=await H.capture(Uo,{threadId:c.threadId,jobId:c.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:Lo,applicationOccurred:xe.length>0||we.some(ae=>ae.status==="resolved")}),fe?(Ee={state:"mutated"},await J.recordImprintEvidence({summary:fe,threadId:c.threadId,jobId:c.id}).catch(ae=>console.warn(`${F} Canonical Imprint evidence linkage failed:`,ae))):Ee={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(ae){Ee={state:"invalid",reason:ae instanceof Error?ae.message:String(ae)},console.warn(`${F} Continuous imprint update failed; the thread result remains available:`,ae instanceof Error?ae.message:String(ae))}else Uo&&(Ee={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ye.error&&console.warn(`${F} Ignored invalid imprint block: ${ye.error}`),(Ee.state==="missing"||Ee.state==="invalid")&&H.recordAssessmentFailure(Ee.state);let Fo=fe?.transactionId;if(c.threadId&&fe&&!fe.grounding){let ae=await x.getThread(c.threadId),le=new Set(fe.changes.map(Tt=>Tt.explanationId)),Ze=ae?dp(ae.messages,le):void 0;if(Ze?.imprintSummary){let Tt=Ze.imprintSummary;await x.updateAssistantMessage(c.threadId,Ze.jobId,{imprintSummary:{...Tt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(Tt.additionalObservationCount??0)+1,coalescedTransactionIds:[...Tt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let zo=Sn({question:te,resolutions:we,changedFiles:xe,decisionRequired:!!Ve,imprintTransactionId:Fo,groundingRequired:!!fe?.grounding}),sa=Ne?.flatMap(ae=>ae.kind==="orientation"?[ae.orientation]:[])??[],Dt=c.lifecycle?Nn(c.lifecycle,Fo?[Fo]:[],Ee):void 0;if(c.threadId){let ae=N?Ve?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":it;await x.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:ae,resolutions:!N&&we.length>0?we:void 0,question:N?void 0:te??void 0,sessionId:ee.sessionId,toolsUsed:N?void 0:De,editEvents:!N&&ee.editEvents&&ee.editEvents.length>0?ee.editEvents:void 0,segments:!N&&Ne&&Ne.length>0?Ne:void 0,turn:{phase:"complete",orientation:sa,result:zo},result:zo,memoryReviewCard:Ve??void 0,memoryReceipt:_e,imprintSummary:fe,imprintRecognition:ne,imprintUsedExplanationIds:je,imprintAppliedExplanationIds:Ke,modelDetails:Ie.length>0?Ie:void 0,model:c.model,provider:R,...Dt?{lifecycle:Dt}:{}})}if(c.threadId&&!V&&!c.surfacedProposalIds?.length&&c.kind!=="project_model"){let ae=c.feedback.annotations.flatMap(le=>le.linkedSelector?[le.pathname?`${le.pathname}:${le.linkedSelector}`:le.linkedSelector]:[]);try{await J.captureCompletedJob({jobId:c.id,threadId:c.threadId,createdAt:c.createdAt,completedAt:Date.now(),requestSummary:w??(zt(c.feedback)||"[request unavailable]"),responseSummary:te??it,outcome:te?"question_asked":we.some(le=>le.status==="resolved")?"completed":"no_change",execution:{provider:R,model:c.model,sessionId:ee.sessionId},subjectHints:ae,filePaths:[...(ee.fileEdits??[]).map(le=>le.file_path),...(ee.editEvents??[]).flatMap(le=>le.filePath?[le.filePath]:[])].map(le=>Gs(le)?Zl(r,le):le),resolutions:we.map(le=>({status:le.status,summary:le.summary})),governingDecisionIds:c.memoryReview?.acceptedTruth?.decisions.map(le=>le.id),submissionIds:Dt?.submissionIds,outcomeId:Dt?.outcomeId,imprintEvidenceIds:Dt?.imprintEvidenceIds,imprintAssessment:Dt?.imprintAssessment})}catch(le){console.warn(`${F} Canonical memory capture failed; iteration remains available in legacy history:`,le instanceof Error?le.message:String(le))}}_e?.status==="committed"&&_e.decisionId&&R!=="copilot"&&await Oe({provider:R,model:c.model,agentSettings:c.agentSettings,threadId:c.threadId,annotationIds:c.annotationIds,sourceId:c.sourceId,reason:`Project accepted decision ${_e.decisionId}`}),te&&(console.log(`${F} \u{1F4AC} Question detected: "${te.slice(0,120)}" \u2192 broadcasting to ${re.size} SSE clients (threadId=${c.threadId??c.id}, annotationIds=${c.annotationIds?.join(",")??"none"})`),P.broadcast({type:"question",jobId:c.id,threadId:c.threadId??c.id,question:te,annotationIds:c.annotationIds},c.id,c.sourceId)),Ie.length>0&&(console.log(`${F} Applied model gap(s): ${Ie.map(ae=>`${ae.category}/${ae.element}`).join(", ")}`),P.broadcast({type:"novel_patterns",jobId:c.id,patterns:Ie,threadId:c.threadId},c.id,c.sourceId)),P.broadcast({type:"done",jobId:c.id,success:!0,resolutions:we.length>0?we:void 0,responseText:it,threadId:c.threadId,annotationIds:c.annotationIds,result:zo},c.id,c.sourceId),Pe.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds})}else console.error(`${F} Error: ${ee.error}`),c.status="error",c.error=ee.error,c.threadId&&await x.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,error:ee.error||"Unknown error",model:c.model,provider:R,...c.lifecycle?{lifecycle:Nn(c.lifecycle)}:{}}),P.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:ee.error||"Unknown error",provider:R,model:c.model,recoverable:ee.recoverableError,code:ee.errorCode},c.id,c.sourceId),Pe.push({id:c.id,status:"error",completedAt:Date.now(),error:ee.error,threadId:c.threadId,annotationIds:c.annotationIds});ot()});let $t=Xl(async(c,b)=>{if(up(c,b),c.method==="OPTIONS"){b.writeHead(204),b.end();return}let C=c.url||"/",w=C.split("?")[0],_=new URL(C,`http://127.0.0.1:${f}`),R=_.pathname,N=gp(c,_);if(N&&N!==i){$(b,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:Do(r)});return}if(R.startsWith("/ambient/")&&N!==i){$(b,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:N});return}if(c.headers.origin){if(!Ws(c.headers.origin)){$(b,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(N!==i){$(b,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:Do(r)});return}}try{if(R.startsWith("/ambient/"))await No(c,b,R);else if(c.method==="POST"&&R==="/draft-attachments"){let B=_.searchParams.get("annotationId")?.trim()??"",U=_.searchParams.get("name")?.trim()??"",L=_.searchParams.get("kind"),F=String(c.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!B||B.length>128||!/^[a-z0-9_-]+$/i.test(B)){$(b,400,{error:"A valid annotationId is required."});return}if(L!=="svg"&&L!=="text"||L==="svg"&&F!=="image/svg+xml"||L==="text"&&F!=="text/plain"){$(b,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await hp(c,ap);if(ge.length===0){$(b,400,{error:"Attachment is empty."});return}let K=await q.stage({annotationId:B,name:U,mimeType:F,kind:L,data:ge});$(b,201,{attachment:{id:K.id,name:K.name,mimeType:K.mimeType,size:K.size,kind:K.kind}})}else if(c.method==="POST"&&R==="/draft-attachments/claim"){let B=await Be(c),U=Array.isArray(B.ids)?B.ids.filter(L=>typeof L=="string").slice(0,100):[];await q.claim(U),$(b,200,{ok:!0})}else if(c.method==="DELETE"&&R.startsWith("/draft-attachments/"))await q.release([R.slice(19)]),$(b,200,{ok:!0});else if(c.method==="POST"&&R==="/send")await qe(c,b);else if(c.method==="POST"&&R==="/capture/native"){if(!u){$(b,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let B=await Be(c),U=typeof B.pageUrl=="string"?B.pageUrl:"",L=B.clip&&typeof B.clip=="object"&&!Array.isArray(B.clip)?B.clip:null;if(!U||!L){$(b,400,{error:"pageUrl and clip are required."});return}let F=await ls(u,{pageUrl:U,clip:{x:Number(L.x),y:Number(L.y),width:Number(L.width),height:Number(L.height)},scale:typeof B.scale=="number"?B.scale:1});b.writeHead(200,{"Content-Type":"image/webp","Content-Length":F.length,"Cache-Control":"no-store"}),b.end(F)}else if(c.method==="GET"&&R==="/events")mt(c,b);else if(c.method==="GET"&&R==="/status")await ft(c,b,N);else if(c.method==="GET"&&R==="/ui-preferences")await Bo(b);else if(c.method==="PATCH"&&R==="/ui-preferences")await Jo(c,b);else if(c.method==="PATCH"&&R==="/config")await xt(c,b);else if(c.method==="POST"&&R==="/leases"){if(I!=="detached"){$(b,409,{error:"Bridge leases are only available for detached bridges."});return}try{let B=await Be(c),U=typeof B.leaseId=="string"?B.leaseId.trim():"",L=typeof B.ownerPid=="number"&&Number.isInteger(B.ownerPid)&&B.ownerPid>0?B.ownerPid:void 0;if(!U||U.length>128){$(b,400,{error:"A valid leaseId is required."});return}W();let F=Q.acquire(U,L);$(b,201,{ok:!0,lease:F,ttlMs:Js})}catch{$(b,400,{error:"Invalid lease request."})}}else if(R.startsWith("/leases/")&&(c.method==="PATCH"||c.method==="DELETE")){if(I!=="detached"){$(b,409,{error:"Bridge leases are only available for detached bridges."});return}let B="";try{B=decodeURIComponent(R.slice(8))}catch{$(b,400,{error:"Invalid lease id."});return}if(!B){$(b,400,{error:"A lease id is required."});return}if(c.method==="PATCH"){let U=Q.heartbeat(B);if(!U){$(b,404,{error:"Lease not found."});return}$(b,200,{ok:!0,lease:U})}else{let U=Q.release(B);$(b,U.found?200:404,{ok:U.found}),U.becameEmpty&&X()}}else if(c.method==="POST"&&R==="/shutdown"){if(I!=="detached"){$(b,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:I});return}$(b,200,{ok:!0}),setTimeout(ue,100)}else if(c.method==="POST"&&R==="/restart"){if(I!=="detached"){$(b,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:I});return}$(b,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let B of re)try{B.res.end()}catch{}$t.close(()=>{Bs(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(c.method==="GET"&&R==="/capabilities")$(b,200,{providers:p});else if(R.startsWith("/imprint/"))await ut(c,b,R);else if(R.startsWith("/memory/"))await ke(c,b,R);else if(c.method==="POST"&&R==="/mcp/install")await qn(c,b);else if(c.method==="POST"&&R==="/reply")await rt(c,b);else if(c.method==="POST"&&R==="/cancel")un(c,b);else if(c.method==="POST"&&R==="/materialize")$(b,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(c.method==="GET"&&R==="/materialization-runs")$(b,410,{error:"Use /projection-runs."});else if(c.method==="GET"&&R==="/projection-runs"){let B=await se.loadRuns();$(b,200,B)}else if(c.method==="GET"&&R==="/projection/proposals"){let B=await se.loadModelProposals();$(b,200,B)}else if(c.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply-selected")){let B=R.slice(22,-15);await ht(B,c,b)}else if(c.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply")){let B=R.slice(22,-6);await Fe(B,b)}else if(c.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/dismiss")){let B=R.slice(22,-8);await Ot(B,c,b)}else if(R.startsWith("/model/proposals/"))$(b,410,{error:"Use /projection/proposals."});else if(c.method==="POST"&&R==="/model/component")await Ys(c,b);else if(c.method==="DELETE"&&R==="/model/component")await Zs(c,b);else if(c.method==="PATCH"&&R==="/model/token")await ea(c,b);else if(c.method==="DELETE"&&R==="/model/token")await ta(c,b);else if(c.method==="POST"&&R==="/model/consolidate")$(b,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="POST"&&R==="/model/synthesize")$(b,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="GET"&&R==="/model"){let B=await se.loadModel();$(b,200,{model:B})}else if(c.method==="GET"&&R.startsWith("/jobs/")&&R.endsWith("/events")){let B=R.slice(6,R.length-7),U=parseInt(_.searchParams.get("afterSeq")??"-1",10),L=P.getBufferedEvents(B,isNaN(U)?-1:U);L?$(b,200,L):$(b,404,{error:"Unknown job"})}else if(c.method==="GET"&&w.startsWith("/files/"))await na(w.slice(7),b);else if(c.method==="GET"&&R==="/threads/recent"){let B=Math.min(Math.max(parseInt(_.searchParams.get("limit")??"5",10)||5,1),20),U=await x.listRecent(B);$(b,200,U)}else if(c.method==="POST"&&R==="/workspace/clear"){let B=[...P.cancelAll(),...A.cancelAll()];for(let L of B)L.threadId&&await x.appendMessage(L.threadId,{role:"assistant",timestamp:Date.now(),jobId:L.id,cancelled:!0});Pe.length=0;let U=await x.advanceWorkspaceGeneration();for(let L of re)Jn(L,{type:"workspace_cleared",workspaceGeneration:U});$(b,200,{cleared:!0,workspaceGeneration:U})}else if(c.method==="GET"&&R.startsWith("/decision/")){let B=R.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(B))$(b,400,{error:"Invalid decision id"});else{let U=await x.getThread(B),L=[...U?.messages??[]].reverse().find(F=>F.annotationSnapshot);if(U&&L?.annotationSnapshot){let F=[...U.messages].reverse().find(ge=>ge.resolutions?.length);$(b,200,{decision:{id:U.id,createdAt:L.timestamp,url:L.annotationSnapshot.url,viewport:L.annotationSnapshot.viewport,color:L.annotationSnapshot.color,annotations:L.annotationSnapshot.annotations,resolutions:F?.resolutions??[]},authority:"thread_snapshot"})}else{let F=await $e.loadDecision(B);F?$(b,200,{decision:F,authority:"legacy_archive"}):$(b,404,{error:"Decision not found"})}}}else if(c.method==="GET"&&R.startsWith("/thread/")){let B=R.slice(8);await oa(B,b)}else if(c.method==="DELETE"&&R.startsWith("/thread/")){let B=R.slice(8);await ra(B,b)}else $(b,404,{error:"Not found"})}catch(B){console.error("[Bridge] Request error:",B),$(b,500,{error:B instanceof Error?B.message:"Internal error"})}});async function No(c,b,C){if(c.method!=="POST"){$(b,405,{error:"Ambient endpoints accept POST requests only."});return}let w=await Be(c,fp),_=typeof w.sessionId=="string"?w.sessionId.trim():"",R=typeof w.turnId=="string"?w.turnId.trim():"",N=typeof w.executionOwner=="string"?w.executionOwner:void 0,B=Ii(w.knowledgeView);if(C==="/ambient/context"){let U=typeof w.query=="string"?w.query.trim():"";if(!U){$(b,400,{error:"query is required."});return}let L=Array.isArray(w.subjectHints)?w.subjectHints.filter(F=>typeof F=="string"&&!!F.trim()).slice(0,20):void 0;$(b,200,await Je.expandContext({query:U,subjectHints:L,knowledgeView:B}));return}if(C==="/ambient/turns/assess"){let U=typeof w.threadId=="string"?w.threadId.trim():"",L=typeof w.jobId=="string"?w.jobId.trim():"",F=typeof w.assessmentText=="string"?w.assessmentText.trim():"";if(!U||!L||!F){$(b,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(w.semanticCandidates)?w.semanticCandidates.flatMap(de=>{if(!de||typeof de!="object"||Array.isArray(de))return[];let Y=de,ce=typeof Y.claim=="string"?Y.claim.trim():"",me=typeof Y.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(Y.proposedKind)?Y.proposedKind:void 0;return ce?[{claim:ce,rationale:typeof Y.rationale=="string"?Y.rationale.trim():void 0,proposedKind:me,sourceText:typeof Y.sourceText=="string"?Y.sourceText.trim():void 0}]:[]}).slice(0,8):[],K=await Je.assess({threadId:U,jobId:L,assessmentText:F,semanticCandidates:ge});$(b,K.status==="committed"||K.status==="assessed"?200:K.status==="rejected"?422:404,K);return}if(!_||!R||_.length>256||R.length>256){$(b,400,{error:"Valid sessionId and turnId values are required."});return}if(C==="/ambient/turns/prepare"){let U=typeof w.prompt=="string"?w.prompt.trim():"";if(!U){$(b,400,{error:"prompt is required."});return}$(b,200,await Je.prepare({sessionId:_,turnId:R,prompt:U,model:typeof w.model=="string"?w.model:void 0,executionOwner:N,knowledgeView:B}));return}if(C==="/ambient/turns/event"){let U=typeof w.toolName=="string"?w.toolName.trim():"";if(!U){$(b,400,{error:"toolName is required."});return}$(b,200,await Je.recordEvent({sessionId:_,turnId:R,executionOwner:N,toolName:U,toolUseId:typeof w.toolUseId=="string"?w.toolUseId:void 0,toolInput:w.toolInput,toolResponse:w.toolResponse}));return}if(C==="/ambient/turns/complete"){$(b,200,await Je.complete({sessionId:_,turnId:R,executionOwner:N,lastAssistantMessage:typeof w.lastAssistantMessage=="string"?w.lastAssistantMessage:void 0,model:typeof w.model=="string"?w.model:void 0}));return}$(b,404,{error:"Ambient endpoint not found."})}async function ke(c,b,C){try{if(c.method==="GET"&&C==="/memory/status"){$(b,200,await J.status());return}if(c.method==="GET"&&C==="/memory/diagnostics"){$(b,200,await J.diagnostics());return}if(c.method==="GET"&&C==="/memory/model-view"){$(b,200,await J.getModelView());return}if(c.method==="GET"&&C==="/memory/imprint-view"){let w=await x.load(),_=[...new Set(Object.values(w.threads).flatMap(R=>Bn(R.messages)))];$(b,200,await J.getImprintView(_,new Set(Object.keys(w.threads))));return}if(c.method==="POST"&&C==="/memory/constraints"){let w=await Be(c),_=typeof w.reactComponent=="string"?w.reactComponent.trim():"",R=await J.getModelView(),N=_?R.entries.filter(B=>B.key===`components.${_}`||B.key.startsWith(`components.${_}.`)):[];$(b,200,{modelEntries:N});return}if(c.method==="POST"&&C==="/memory/conversation-action"){let w=await Be(c),_=typeof w.threadId=="string"?w.threadId:"",R=typeof w.proposalId=="string"?w.proposalId:"",N=String(w.action);if(!_||!R||!["accept","edit_and_accept","reject","defer"].includes(N)){$(b,400,{error:"A valid thread, proposal, and review action are required."});return}let B=await x.getThread(_),U=B?.messages.find(ie=>ie.memoryReviewCard?.proposalId===R)?.memoryReviewCard,L=B?.messages.flatMap(ie=>ie.memoryReview?.packets??[]).find(ie=>ie.proposalId===R),F=B?.elementIdentifiers.some(ie=>ie.startsWith("codex-session:"))?(await J.findPendingProposalsForThread(_)).find(ie=>ie.proposalId===R):void 0,ge=typeof w.kind=="string"&&["principle","preference","rule","constraint"].includes(w.kind)?w.kind:void 0,K=U?.kind??L?.proposedKind??F?.proposedKind??ge;if(!B||!U&&!L&&!F){$(b,409,{error:"This decision candidate was not surfaced in the thread."});return}if((N==="accept"||N==="edit_and_accept")&&!K){$(b,400,{error:"The decision kind is required to accept this candidate."});return}let de=await se.findModelProposalsByThread(_),Y=(await Promise.all(de.map(async ie=>({proposal:ie,matches:(await Promise.all(ie.decisionIds.map(Me=>J.findPendingProposalForLegacyDecision(Me)))).some(Me=>Me?.proposalId===R)})))).find(ie=>ie.matches)?.proposal,ce={proposalId:R,action:N,kind:K,claim:N==="edit_and_accept"&&typeof w.claim=="string"?w.claim.trim():void 0,reason:N==="defer"?void 0:`The owner explicitly chose ${N.replaceAll("_"," ")} from the decision review card.`,taskContext:N==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:N==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){$(b,400,{error:"Edited decision wording is required."});return}let me=await J.commitConversationalReview(ce),ee=`memory-${pt().slice(0,8)}`,xe=N==="accept"?"> Accepted decision":N==="edit_and_accept"?"> Edited and accepted decision":N==="reject"?"> Rejected decision":"> Deferred decision";await x.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:ee,replyToQuestion:xe}),await x.appendMessage(_,{role:"assistant",timestamp:Date.now(),jobId:ee,responseText:"",memoryReceipt:me,provider:cn(typeof w.provider=="string"?w.provider:void 0),model:typeof w.model=="string"?w.model:void 0}),me.status==="committed"&&Y&&await se.dismissModelProposal(Y.id);let Ae=cn(typeof w.provider=="string"?w.provider:void 0);me.status==="committed"&&me.decisionId&&Ae!=="copilot"&&await Oe({provider:Ae,model:typeof w.model=="string"?w.model:void 0,agentSettings:Bt(w),threadId:_,reason:`Project accepted decision ${me.decisionId}`}),$(b,me.status==="committed"?200:409,{receipt:me});return}if(c.method==="POST"&&C==="/memory/analyze"){let w=await Be(c),_=await J.analyzeLegacy({projectKey:typeof w.projectKey=="string"?w.projectKey:void 0}),R=Object.fromEntries([...new Set(_.issues.map(N=>N.code))].map(N=>[N,_.issues.filter(B=>B.code===N).length]));$(b,200,{..._,issues:void 0,issueCounts:R});return}if(c.method==="POST"&&C==="/memory/review"){let w=await Be(c),_=await J.review(ir(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(b,200,_);return}if(c.method==="POST"&&C==="/memory/context"){let w=await Be(c),_=await J.contextualize(ir(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(b,200,_);return}if(c.method==="POST"&&C==="/memory/initialize"){let w=await Be(c),_=await J.initializeFromLegacy({confirmed:w.confirm===!0,projectKey:typeof w.projectKey=="string"?w.projectKey:void 0,writerVersion:st});$(b,201,{status:_.status,report:{source:_.report.source,imported:_.report.imported,unresolvedAcceptance:_.report.unresolvedAcceptance,deferredModelEntries:_.report.deferredModelEntries,proofCases:_.report.proofCases,schemaIssues:_.report.schemaIssues}});return}if(c.method==="POST"&&C==="/memory/plan"){let w=await Be(c),_=await J.planReview(rr(w.command),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});$(b,_.result.ok?200:422,_);return}if(c.method==="POST"&&C==="/memory/commit"){let w=await Be(c),_=w.transaction&&typeof w.transaction=="object"&&!Array.isArray(w.transaction)?w.transaction:{},R=await J.commitReview(rr(w.command),{transactionId:typeof _.transactionId=="string"?_.transactionId:"",committedAt:typeof _.committedAt=="string"?_.committedAt:""});$(b,200,{status:await J.status(),journal:R.report});return}if(c.method==="POST"&&C==="/memory/recover"){let w=await Be(c),_=await J.recover(w.confirm===!0);$(b,200,{status:await J.status(),journal:_.report});return}$(b,404,{error:"Memory endpoint not found."})}catch(w){let _=w instanceof Error?w.message:String(w),R=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(_),N=/required|invalid|unsupported|expected|must be|confirmation/i.test(_);if(R||N){$(b,R?409:400,{error:_});return}throw w}}async function ut(c,b,C){if(c.method==="GET"&&C==="/imprint/status"){let[w,_]=await Promise.all([H.store.load(),x.load()]),R=[...new Set(Object.values(_.threads).flatMap(N=>Bn(N.messages)))].filter(N=>w.graph.explanations.some(B=>B.id===N&&B.state==="testing"));$(b,200,{state:"ready",head:w.graph.head,updatedAt:w.graph.updatedAt,explanationCount:w.graph.explanations.filter(N=>N.state!=="retired").length,concreteCount:w.graph.concrete.length,relationCount:w.graph.relations.length,pendingGroundingCount:R.length,recoveredTransactions:w.recoveredTransactions,admission:H.diagnostics(),admissionWindowStartedAt:e});return}if(c.method==="POST"&&C==="/imprint/action"){let w=await Be(c),_=typeof w.threadId=="string"?w.threadId:"",R=typeof w.transactionId=="string"?w.transactionId:"",N=String(w.action);if(!_||!R||!["yes","this_time","no"].includes(N)){$(b,400,{error:"A valid thread, imprint update, and action are required."});return}let U=await x.getThread(_),L=[...U?.messages??[]].reverse().find(ce=>ce.role==="assistant"&&ce.imprintSummary?.transactionId===R),F=L?.imprintSummary;if(!U||!L||!F){$(b,409,{error:"This imprint summary is not available in the thread."});return}if(F.resolvedAction){$(b,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${pt().slice(0,8)}`;await H.applyGroundingAction({summary:F,action:N,threadId:_,jobId:ge}),N!=="no"&&await J.recordImprintEvidence({summary:F,action:N,threadId:_,jobId:ge}).catch(ce=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ce));let K=Zt(L.result,!!L.question),de=L.turn?{...L.turn,result:Zt(L.turn.result,!!L.question)}:void 0;await x.updateAssistantMessage(_,L.jobId,{imprintSummary:{...F,resolvedAction:N},...K?{result:K}:{},...de?{turn:de}:{}});let Y={yes:"> Yes",this_time:"> This time",no:"> No"};if(await x.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:ge,replyToQuestion:Y[N]}),N==="no"){let ce="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",me=Sn({question:ce});await x.appendMessage(_,{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:me},result:me})}$(b,200,{ok:!0,action:N});return}$(b,404,{error:"Imprint endpoint not found."})}async function qe(c,b){let{screenshot:C,feedback:w,color:_,provider:R,model:N,reasoningEffort:B,serviceTier:U,sourceId:L,continuationThreadId:F,pastedImages:ge,pageScreenshots:K}=await Rr(c),de=_,Y;try{Y=JSON.parse(w)}catch{$(b,400,{error:"Invalid feedback JSON"});return}let ce=Y.annotations.flatMap(ne=>(ne.attachments??[]).map(je=>({id:je.id,annotationId:ne.id}))),me;try{me=ce.length>0?await q.promote(ce):void 0}catch(ne){$(b,409,{error:ne instanceof Error?ne.message:"Draft attachment unavailable."});return}let ee=pt().slice(0,8),xe={};if(K.length>0)for(let ne of K){let je=encodeURIComponent(ne.pathname),Ke=Ye(d,`screenshot-${ee}-${je}.webp`);await Oo(Ke,ne.data),xe[ne.pathname]=Ke}let Ae=Ye(d,`screenshot-${ee}.webp`);await Oo(Ae,C);let ie={};if(ge.length>0)for(let ne of ge){let je=Ye(d,`pasted-${ee}-${ne.annotationId}-${ne.index}.webp`);await Oo(je,ne.data),ie[ne.annotationId]||(ie[ne.annotationId]=[]),ie[ne.annotationId].push(je)}let Me=Es(Y),be,Z=!1;if(Me.length>0){let ne=await x.findContinuationThread(Me,F);ne?(be=ne.id,Z=!0,de=ne.messages.find(je=>je.annotationSnapshot?.color)?.annotationSnapshot?.color??de,await x.addElementIdentifiers(be,Me)):be=(await x.createThread(`thread-${pt()}`,Me)).id}else be=(await x.createThread(`thread-${pt()}`,[])).id;let ye=Z||(await x.findContinuationThread(Me))?.id===be,it=Y.annotations.map(ne=>ne.id),Ee=Object.keys(xe).length>0,te=await zn(J,Y,Me,ne=>console.warn(`[\u22B9 ${f}:${ee}] Contextual memory unavailable; continuing without it:`,ne instanceof Error?ne.message:String(ne))),we=(await x.getThread(be))?.messages??[],De=await H.contextualize({text:zt(Y),subjectHints:Gi(Y,Me),pendingGroundingExplanationIds:Bn(we),correctionExplanationIds:Ls(we)}).catch(ne=>{console.warn(`[\u22B9 ${f}:${ee}] Imprint context unavailable; continuing without it:`,ne instanceof Error?ne.message:String(ne))}),ze=$r({jobId:ee,threadId:be,artifactIds:_s(Y,ee)}),Ne={id:ee,status:"queued",screenshotPath:Ae,feedback:Y,createdAt:Date.now(),color:de,threadId:be,annotationIds:it,provider:cn(R),model:N||void 0,agentSettings:Bt({reasoningEffort:B,serviceTier:U}),...Object.keys(ie).length>0?{imagePaths:ie}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:L||void 0,...Ee?{screenshotPaths:xe}:{},...te?{memoryReview:te}:{},...De?{imprintContext:De}:{},lifecycle:ze},_e=new Set(Y.annotations.map(ne=>ne.pathname).filter(Boolean)),Ve;if(_e.size>1){let ne=new Map;for(let je of Y.annotations){let Ke=je.pathname||"(unknown)";ne.has(Ke)||ne.set(Ke,[]),ne.get(Ke).push(je.instruction||Us({...Y,annotations:[je]}))}Ve=[...ne.entries()].map(([je,Ke])=>`\`${je}\`
199
- ${Ke.map(Lo=>`- ${Lo}`).join(`
198
+ ${Ts}`;let U=Rp(c.color,`[\u22B9 ${I}:${c.id}]`),me=c.screenshotPaths&&Object.keys(c.screenshotPaths).length>0?`${Object.keys(c.screenshotPaths).length} pages [${Object.keys(c.screenshotPaths).join(", ")}]`:c.screenshotPath;console.log(`${U} Reviewing ${me} (provider: ${P})${c.threadId?` (thread: ${c.threadId})`:""}${z?` (resuming: ${z.slice(0,8)})`:""}`);let V=new jo(c.id),fe=new bo(c.id,c.imprintContext),le=(te,ye)=>{if(te.type==="delta"&&"text"in te){let We=fe.push(te.text),Ue=V.push(We.visibleText);Ue.visibleText&&(R.accumulateText(ye,"response",Ue.visibleText),R.broadcast({...te,text:Ue.visibleText},ye,c.sourceId));for(let Ce of Ue.orientations)R.broadcast({type:"orientation",jobId:ye,orientation:Ce},ye,c.sourceId);for(let Ce of We.usages)R.broadcast({type:"imprint_used",jobId:ye,usage:Ce},ye,c.sourceId);return}else te.type==="thinking"&&"text"in te&&R.accumulateText(ye,"thinking",te.text);R.broadcast(te,ye,c.sourceId)},{process:se,result:Z}=P==="codex"?fo(c.id,{prompt:F,projectRoot:r,screenshotPath:c.screenshotPath,resumeSessionId:z,model:c.model,sandboxMode:B?"read-only":void 0,configOverrides:Qn(c.agentSettings),onEvent:le}):P==="copilot"?Qi(c.id,{prompt:F,projectRoot:r,resumeSessionId:z,model:c.model,timeoutMs:h,copilotPath:p.copilot?.path??k,onEvent:le}):lo(c.id,{prompt:F,projectRoot:r,maxTurns:l,maxBudgetUsd:w,allowedTools:B?["Read"]:b,claudePath:g,resumeSessionId:z,model:c.model,reasoningEffort:c.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:le});R.setActiveProcess(c.id,se);let re=await Z,be=[...(re.fileEdits??[]).map(te=>te.file_path),...(re.editEvents??[]).flatMap(te=>te.filePath?[te.filePath]:[])],Te=fe.finalize(re.text),he=_r(Te.visibleText,c.id),Fe=V.finalize(Te.visibleText),xe=he.visibleText,Y=js(xe),Ie=D?zt(xe,{context:c.imprintContext,requestText:T??Wt(c.feedback),applicationOccurred:be.length>0||Y.some(te=>te.status==="resolved")}):{visibleText:xe,draft:void 0,error:void 0},gt=Ie.visibleText,Se=D?Ie.error?{state:Ie.error.includes("missing")?"missing":"invalid",reason:Ie.error}:Ie.draft?.decision==="none"?{state:"none",reason:Ie.draft.reason}:Ie.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let te of Fe.orientations)R.broadcast({type:"orientation",jobId:c.id,orientation:te},c.id,c.sourceId);for(let te of Te.usages)R.broadcast({type:"imprint_used",jobId:c.id,usage:te},c.id,c.sourceId);if(c.result=gt,re.success){console.log(`${U} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${U} Captured ${re.fileEdits.length} file edit(s): ${re.fileEdits.map(ae=>`${ae.tool} ${ae.file_path}`).join(", ")}`),re.editEvents&&re.editEvents.length>0&&console.log(`${U} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(ae=>`${ae.operation} ${ae.filePath}`).join(", ")}`),c.status="done";let te=Ps(xe),ye=Y;if(ye.length>0&&c.annotationIds&&c.annotationIds.length>0){let ae=new Set(c.annotationIds);ye.every(et=>ae.has(et.annotationId))||(ye=ye.map((et,Pt)=>({...et,annotationId:c.annotationIds[Pt%c.annotationIds.length]})))}let We=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(ae=>`${ae.tool} ${ae.file_path.split("/").pop()}`):re.toolsUsed,Ue=R.getBufferedEvents(c.id),Ce=Ip(Ue?.events??[],r,he.segments),Ae,Ze=bs(xe),K=vs(xe);if(K)if(!(c.memoryReview?.packets.some(de=>de.proposalId===K.proposalId)||c.surfacedProposalIds?.includes(K.proposalId)))Ae={status:"rejected",action:K.action,proposalId:K.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Ae=await q.commitConversationalReview(K)}catch(de){Ae={status:"rejected",action:K.action,proposalId:K.proposalId,message:de instanceof Error?de.message:String(de)}}let we=Ms(xe,be.length),pe,ze,Bt,Vn,Hn=c.imprintContext?.pendingGroundingExplanationIds??[];if(Ie.draft){let ae=Ie.draft.decision==="recognize"?[Ie.draft.explanationId]:[],de=Ie.draft.decision==="recognize"?ae:[...Ie.draft.usedExplanationIds??[],...Ie.draft.appliedExplanationIds??[]],et=Ie.draft.decision==="recognize"?[]:Ie.draft.appliedExplanationIds??[];de.length>0&&(Bt=[...new Set(de)]),et.length>0&&(Vn=[...new Set(et)])}Ie.draft?.decision==="none"&&H.recordNoop(Ie.draft.reason);let Rt=Ie.draft?.decision==="recognize"?Ie.draft:void 0;if(Rt&&!K&&!Ze){let ae=c.imprintContext?.explanations.find(de=>de.id===Rt.explanationId&&de.state==="grounded");ae?ze={explanationId:ae.id,title:Rt.summary.title,detail:Rt.summary.detail,statement:ae.statement}:Se={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let hn=Ie.draft?.decision==="mutate"||Ie.draft?.decision==="apply"?Ie.draft:void 0;if(c.threadId&&hn&&!K&&!Ze)try{pe=await H.capture(hn,{threadId:c.threadId,jobId:c.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:Hn,applicationOccurred:be.length>0||ye.some(ae=>ae.status==="resolved")}),pe?(Se={state:"mutated"},await q.recordImprintEvidence({summary:pe,threadId:c.threadId,jobId:c.id}).catch(ae=>console.warn(`${U} Canonical Imprint evidence linkage failed:`,ae))):Se={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(ae){Se={state:"invalid",reason:ae instanceof Error?ae.message:String(ae)},console.warn(`${U} Continuous imprint update failed; the thread result remains available:`,ae instanceof Error?ae.message:String(ae))}else hn&&(Se={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});Ie.error&&console.warn(`${U} Ignored invalid imprint block: ${Ie.error}`),(Se.state==="missing"||Se.state==="invalid")&&H.recordAssessmentFailure(Se.state);let gn=pe?.transactionId;if(c.threadId&&pe&&!pe.grounding){let ae=await v.getThread(c.threadId),de=new Set(pe.changes.map(Pt=>Pt.explanationId)),et=ae?yp(ae.messages,de):void 0;if(et?.imprintSummary){let Pt=et.imprintSummary;await v.updateAssistantMessage(c.threadId,et.jobId,{imprintSummary:{...Pt,detail:pe.detail,changes:pe.changes,additionalObservationCount:(Pt.additionalObservationCount??0)+1,coalescedTransactionIds:[...Pt.coalescedTransactionIds??[],pe.transactionId]}}),pe=void 0}}let ne=Rn({question:te,resolutions:ye,changedFiles:be,decisionRequired:!!Ze,imprintTransactionId:gn,groundingRequired:!!pe?.grounding}),$e=Ce?.flatMap(ae=>ae.kind==="orientation"?[ae.orientation]:[])??[],De=c.lifecycle?qn(c.lifecycle,gn?[gn]:[],Se):void 0;if(c.threadId){let ae=B?Ze?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":gt;await v.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:ae,resolutions:!B&&ye.length>0?ye:void 0,question:B?void 0:te??void 0,sessionId:re.sessionId,toolsUsed:B?void 0:We,editEvents:!B&&re.editEvents&&re.editEvents.length>0?re.editEvents:void 0,segments:!B&&Ce&&Ce.length>0?Ce:void 0,turn:{phase:"complete",orientation:$e,result:ne},result:ne,memoryReviewCard:Ze??void 0,memoryReceipt:Ae,imprintSummary:pe,imprintRecognition:ze,imprintUsedExplanationIds:Bt,imprintAppliedExplanationIds:Vn,modelDetails:we.length>0?we:void 0,model:c.model,provider:P,...De?{lifecycle:De}:{}})}if(c.threadId&&!K&&!c.surfacedProposalIds?.length&&c.kind!=="project_model"){let ae=c.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await q.captureCompletedJob({jobId:c.id,threadId:c.threadId,createdAt:c.createdAt,completedAt:Date.now(),requestSummary:T??(Wt(c.feedback)||"[request unavailable]"),responseSummary:te??gt,outcome:te?"question_asked":ye.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:P,model:c.model,sessionId:re.sessionId},subjectHints:ae,filePaths:[...(re.fileEdits??[]).map(de=>de.file_path),...(re.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>ia(de)?dp(r,de):de),resolutions:ye.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:c.memoryReview?.acceptedTruth?.decisions.map(de=>de.id),submissionIds:De?.submissionIds,outcomeId:De?.outcomeId,imprintEvidenceIds:De?.imprintEvidenceIds,imprintAssessment:De?.imprintAssessment})}catch(de){console.warn(`${U} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}Ae?.status==="committed"&&Ae.decisionId&&P!=="copilot"&&await Oe({provider:P,model:c.model,agentSettings:c.agentSettings,threadId:c.threadId,annotationIds:c.annotationIds,sourceId:c.sourceId,reason:`Project accepted decision ${Ae.decisionId}`}),te&&(console.log(`${U} \u{1F4AC} Question detected: "${te.slice(0,120)}" \u2192 broadcasting to ${ee.size} SSE clients (threadId=${c.threadId??c.id}, annotationIds=${c.annotationIds?.join(",")??"none"})`),R.broadcast({type:"question",jobId:c.id,threadId:c.threadId??c.id,question:te,annotationIds:c.annotationIds},c.id,c.sourceId)),we.length>0&&(console.log(`${U} Applied model gap(s): ${we.map(ae=>`${ae.category}/${ae.element}`).join(", ")}`),R.broadcast({type:"novel_patterns",jobId:c.id,patterns:we,threadId:c.threadId},c.id,c.sourceId)),R.broadcast({type:"done",jobId:c.id,success:!0,resolutions:ye.length>0?ye:void 0,responseText:gt,threadId:c.threadId,annotationIds:c.annotationIds,result:ne},c.id,c.sourceId),Me.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds})}else console.error(`${U} Error: ${re.error}`),c.status="error",c.error=re.error,c.threadId&&await v.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,error:re.error||"Unknown error",model:c.model,provider:P,...c.lifecycle?{lifecycle:qn(c.lifecycle)}:{}}),R.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:re.error||"Unknown error",provider:P,model:c.model,recoverable:re.recoverableError,code:re.errorCode},c.id,c.sourceId),Me.push({id:c.id,status:"error",completedAt:Date.now(),error:re.error,threadId:c.threadId,annotationIds:c.annotationIds});rt()});let St=sp(async(c,S)=>{if(bp(c,S),c.method==="OPTIONS"){S.writeHead(204),S.end();return}let O=c.url||"/",T=O.split("?")[0],C=new URL(O,`http://127.0.0.1:${I}`),P=C.pathname,B=kp(c,C);if(B&&B!==i){N(S,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:B,projectName:Uo(r)});return}if(P.startsWith("/ambient/")&&B!==i){N(S,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:B});return}if(c.headers.origin){if(!sa(c.headers.origin)){N(S,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(B!==i){N(S,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:B,projectName:Uo(r)});return}}try{if(P.startsWith("/ambient/"))await zo(c,S,P);else if(c.method==="POST"&&P==="/draft-attachments"){let D=C.searchParams.get("annotationId")?.trim()??"",z=C.searchParams.get("name")?.trim()??"",F=C.searchParams.get("kind"),U=String(c.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(F!=="svg"&&F!=="text"||F==="svg"&&U!=="image/svg+xml"||F==="text"&&U!=="text/plain"){N(S,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let me=await Tp(c,gp);if(me.length===0){N(S,400,{error:"Attachment is empty."});return}let V=await J.stage({annotationId:D,name:z,mimeType:U,kind:F,data:me});N(S,201,{attachment:{id:V.id,name:V.name,mimeType:V.mimeType,size:V.size,kind:V.kind}})}else if(c.method==="POST"&&P==="/draft-attachments/claim"){let D=await Ne(c),z=Array.isArray(D.ids)?D.ids.filter(F=>typeof F=="string").slice(0,100):[];await J.claim(z),N(S,200,{ok:!0})}else if(c.method==="DELETE"&&P.startsWith("/draft-attachments/"))await J.release([P.slice(19)]),N(S,200,{ok:!0});else if(c.method==="POST"&&P==="/send")await Je(c,S);else if(c.method==="POST"&&P==="/capture/native"){if(!u){N(S,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let D=await Ne(c),z=typeof D.pageUrl=="string"?D.pageUrl:"",F=D.clip&&typeof D.clip=="object"&&!Array.isArray(D.clip)?D.clip:null;if(!z||!F){N(S,400,{error:"pageUrl and clip are required."});return}let U=await xs(u,{pageUrl:z,clip:{x:Number(F.x),y:Number(F.y),width:Number(F.width),height:Number(F.height)},scale:typeof D.scale=="number"?D.scale:1});S.writeHead(200,{"Content-Type":"image/webp","Content-Length":U.length,"Cache-Control":"no-store"}),S.end(U)}else if(c.method==="GET"&&P==="/events")mt(c,S);else if(c.method==="GET"&&P==="/status")await ft(c,S,B);else if(c.method==="GET"&&P==="/ui-preferences")await Go(S);else if(c.method==="PATCH"&&P==="/ui-preferences")await Wo(c,S);else if(c.method==="PATCH"&&P==="/config")await Tt(c,S);else if(c.method==="POST"&&P==="/leases"){if(y!=="detached"){N(S,409,{error:"Bridge leases are only available for detached bridges."});return}try{let D=await Ne(c),z=typeof D.leaseId=="string"?D.leaseId.trim():"",F=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}W();let U=X.acquire(z,F);N(S,201,{ok:!0,lease:U,ttlMs:Zs})}catch{N(S,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(c.method==="PATCH"||c.method==="DELETE")){if(y!=="detached"){N(S,409,{error:"Bridge leases are only available for detached bridges."});return}let D="";try{D=decodeURIComponent(P.slice(8))}catch{N(S,400,{error:"Invalid lease id."});return}if(!D){N(S,400,{error:"A lease id is required."});return}if(c.method==="PATCH"){let z=X.heartbeat(D);if(!z){N(S,404,{error:"Lease not found."});return}N(S,200,{ok:!0,lease:z})}else{let z=X.release(D);N(S,z.found?200:404,{ok:z.found}),z.becameEmpty&&Q()}}else if(c.method==="POST"&&P==="/shutdown"){if(y!=="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:y});return}N(S,200,{ok:!0}),setTimeout(ie,100)}else if(c.method==="POST"&&P==="/restart"){if(y!=="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:y});return}N(S,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let D of ee)try{D.res.end()}catch{}St.close(()=>{Ys(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(c.method==="GET"&&P==="/capabilities")N(S,200,{providers:p});else if(P.startsWith("/imprint/"))await ut(c,S,P);else if(P.startsWith("/memory/"))await Pe(c,S,P);else if(c.method==="POST"&&P==="/mcp/install")await Kn(c,S);else if(c.method==="POST"&&P==="/reply")await it(c,S);else if(c.method==="POST"&&P==="/cancel")mn(c,S);else if(c.method==="POST"&&P==="/materialize")N(S,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(c.method==="GET"&&P==="/materialization-runs")N(S,410,{error:"Use /projection-runs."});else if(c.method==="GET"&&P==="/projection-runs"){let D=await ue.loadRuns();N(S,200,D)}else if(c.method==="GET"&&P==="/projection/proposals"){let D=await ue.loadModelProposals();N(S,200,D)}else if(c.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let D=P.slice(22,-15);await ht(D,c,S)}else if(c.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let D=P.slice(22,-6);await Le(D,S)}else if(c.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let D=P.slice(22,-8);await Nt(D,c,S)}else if(P.startsWith("/model/proposals/"))N(S,410,{error:"Use /projection/proposals."});else if(P==="/model/component"||P==="/model/token")N(S,410,{error:"Direct model editing was removed. Project understanding changes through collaboration and canonical projection."});else if(c.method==="POST"&&P==="/model/consolidate")N(S,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="POST"&&P==="/model/synthesize")N(S,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="GET"&&P==="/model"){let D=await ue.loadModel();N(S,200,{model:D})}else if(c.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let D=P.slice(6,P.length-7),z=parseInt(C.searchParams.get("afterSeq")??"-1",10),F=R.getBufferedEvents(D,isNaN(z)?-1:z);F?N(S,200,F):N(S,404,{error:"Unknown job"})}else if(c.method==="GET"&&T.startsWith("/files/"))await ua(T.slice(7),S);else if(c.method==="GET"&&P==="/threads/recent"){let D=Math.min(Math.max(parseInt(C.searchParams.get("limit")??"5",10)||5,1),200),z=await v.listRecent(D);N(S,200,z)}else if(c.method==="POST"&&P==="/workspace/clear"){let D=[...R.cancelAll(),..._.cancelAll()];for(let F of D)F.threadId&&await v.appendMessage(F.threadId,{role:"assistant",timestamp:Date.now(),jobId:F.id,cancelled:!0});Me.length=0;let z=await v.advanceWorkspaceGeneration();for(let F of ee)Wn(F,{type:"workspace_cleared",workspaceGeneration:z});N(S,200,{cleared:!0,workspaceGeneration:z})}else if(c.method==="GET"&&P.startsWith("/decision/")){let D=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(D))N(S,400,{error:"Invalid decision id"});else{let z=await v.getThread(D),F=[...z?.messages??[]].reverse().find(U=>U.annotationSnapshot);if(z&&F?.annotationSnapshot){let U=[...z.messages].reverse().find(me=>me.resolutions?.length);N(S,200,{decision:{id:z.id,createdAt:F.timestamp,url:F.annotationSnapshot.url,viewport:F.annotationSnapshot.viewport,color:F.annotationSnapshot.color,annotations:F.annotationSnapshot.annotations,resolutions:U?.resolutions??[]},authority:"thread_snapshot"})}else{let U=await _e.loadDecision(D);U?N(S,200,{decision:U,authority:"legacy_archive"}):N(S,404,{error:"Decision not found"})}}}else if(c.method==="GET"&&P.startsWith("/thread/")){let D=P.slice(8);await ma(D,S)}else if(c.method==="POST"&&P.startsWith("/thread/")&&P.endsWith("/archive")){let D=P.slice(8,-8);await Kr(D,S)}else if(c.method==="DELETE"&&P.startsWith("/thread/")){let D=P.slice(8);await Kr(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 zo(c,S,O){if(c.method!=="POST"){N(S,405,{error:"Ambient endpoints accept POST requests only."});return}let T=await Ne(c,Sp),C=typeof T.sessionId=="string"?T.sessionId.trim():"",P=typeof T.turnId=="string"?T.turnId.trim():"",B=typeof T.executionOwner=="string"?T.executionOwner:void 0,D=Mi(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 F=Array.isArray(T.subjectHints)?T.subjectHints.filter(U=>typeof U=="string"&&!!U.trim()).slice(0,20):void 0;N(S,200,await Be.expandContext({query:z,subjectHints:F,knowledgeView:D}));return}if(O==="/ambient/turns/assess"){let z=typeof T.threadId=="string"?T.threadId.trim():"",F=typeof T.jobId=="string"?T.jobId.trim():"",U=typeof T.assessmentText=="string"?T.assessmentText.trim():"";if(!z||!F||!U){N(S,400,{error:"threadId, jobId, and assessmentText are required."});return}let me=Array.isArray(T.semanticCandidates)?T.semanticCandidates.flatMap(fe=>{if(!fe||typeof fe!="object"||Array.isArray(fe))return[];let le=fe,se=typeof le.claim=="string"?le.claim.trim():"",Z=typeof le.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(le.proposedKind)?le.proposedKind:void 0;return se?[{claim:se,rationale:typeof le.rationale=="string"?le.rationale.trim():void 0,proposedKind:Z,sourceText:typeof le.sourceText=="string"?le.sourceText.trim():void 0}]:[]}).slice(0,8):[],V=await Be.assess({threadId:z,jobId:F,assessmentText:U,semanticCandidates:me});N(S,V.status==="committed"||V.status==="assessed"?200:V.status==="rejected"?422:404,V);return}if(!C||!P||C.length>256||P.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 Be.prepare({sessionId:C,turnId:P,prompt:z,model:typeof T.model=="string"?T.model:void 0,executionOwner:B,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 Be.recordEvent({sessionId:C,turnId:P,executionOwner:B,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 Be.complete({sessionId:C,turnId:P,executionOwner:B,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 Pe(c,S,O){try{if(c.method==="GET"&&O==="/memory/status"){N(S,200,await q.status());return}if(c.method==="GET"&&O==="/memory/diagnostics"){N(S,200,await q.diagnostics());return}if(c.method==="GET"&&O==="/memory/model-view"){N(S,200,await q.getModelView());return}if(c.method==="GET"&&O==="/memory/imprint-view"){let T=await v.load(),C=[...new Set(Object.values(T.threads).flatMap(P=>Gn(P.messages)))];N(S,200,await q.getImprintView(C,new Set(Object.keys(T.threads))));return}if(c.method==="POST"&&O==="/memory/constraints"){let T=await Ne(c),C=typeof T.reactComponent=="string"?T.reactComponent.trim():"",P=await q.getModelView(),B=C?P.entries.filter(D=>D.key===`components.${C}`||D.key.startsWith(`components.${C}.`)):[];N(S,200,{modelEntries:B});return}if(c.method==="POST"&&O==="/memory/conversation-action"){let T=await Ne(c),C=typeof T.threadId=="string"?T.threadId:"",P=typeof T.proposalId=="string"?T.proposalId:"",B=String(T.action);if(!C||!P||!["accept","edit_and_accept","reject","defer"].includes(B)){N(S,400,{error:"A valid thread, proposal, and review action are required."});return}let D=await v.getThread(C),z=D?.messages.find(he=>he.memoryReviewCard?.proposalId===P)?.memoryReviewCard,F=D?.messages.flatMap(he=>he.memoryReview?.packets??[]).find(he=>he.proposalId===P),U=D?.elementIdentifiers.some(he=>he.startsWith("codex-session:"))?(await q.findPendingProposalsForThread(C)).find(he=>he.proposalId===P):void 0,me=typeof T.kind=="string"&&["principle","preference","rule","constraint"].includes(T.kind)?T.kind:void 0,V=z?.kind??F?.proposedKind??U?.proposedKind??me;if(!D||!z&&!F&&!U){N(S,409,{error:"This decision candidate was not surfaced in the thread."});return}if((B==="accept"||B==="edit_and_accept")&&!V){N(S,400,{error:"The decision kind is required to accept this candidate."});return}let fe=await ue.findModelProposalsByThread(C),le=(await Promise.all(fe.map(async he=>({proposal:he,matches:(await Promise.all(he.decisionIds.map(Fe=>q.findPendingProposalForLegacyDecision(Fe)))).some(Fe=>Fe?.proposalId===P)})))).find(he=>he.matches)?.proposal,se={proposalId:P,action:B,kind:V,claim:B==="edit_and_accept"&&typeof T.claim=="string"?T.claim.trim():void 0,reason:B==="defer"?void 0:`The owner explicitly chose ${B.replaceAll("_"," ")} from the decision review card.`,taskContext:B==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:B==="defer"?["different_action","owner_request"]:void 0};if(se.action==="edit_and_accept"&&!se.claim){N(S,400,{error:"Edited decision wording is required."});return}let Z=await q.commitConversationalReview(se),re=`memory-${pt().slice(0,8)}`,be=B==="accept"?"> Accepted decision":B==="edit_and_accept"?"> Edited and accepted decision":B==="reject"?"> Rejected decision":"> Deferred decision";await v.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:re,replyToQuestion:be}),await v.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:re,responseText:"",memoryReceipt:Z,provider:ln(typeof T.provider=="string"?T.provider:void 0),model:typeof T.model=="string"?T.model:void 0}),Z.status==="committed"&&le&&await ue.dismissModelProposal(le.id);let Te=ln(typeof T.provider=="string"?T.provider:void 0);Z.status==="committed"&&Z.decisionId&&Te!=="copilot"&&await Oe({provider:Te,model:typeof T.model=="string"?T.model:void 0,agentSettings:qt(T),threadId:C,reason:`Project accepted decision ${Z.decisionId}`}),N(S,Z.status==="committed"?200:409,{receipt:Z});return}if(c.method==="POST"&&O==="/memory/analyze"){let T=await Ne(c),C=await q.analyzeLegacy({projectKey:typeof T.projectKey=="string"?T.projectKey:void 0}),P=Object.fromEntries([...new Set(C.issues.map(B=>B.code))].map(B=>[B,C.issues.filter(D=>D.code===B).length]));N(S,200,{...C,issues:void 0,issueCounts:P});return}if(c.method==="POST"&&O==="/memory/review"){let T=await Ne(c),C=await q.review(cr(T.query),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,200,C);return}if(c.method==="POST"&&O==="/memory/context"){let T=await Ne(c),C=await q.contextualize(cr(T.query),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,200,C);return}if(c.method==="POST"&&O==="/memory/initialize"){let T=await Ne(c),C=await q.initializeFromLegacy({confirmed:T.confirm===!0,projectKey:typeof T.projectKey=="string"?T.projectKey:void 0,writerVersion:st});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(c.method==="POST"&&O==="/memory/plan"){let T=await Ne(c),C=await q.planReview(dr(T.command),{projectKey:typeof T.projectKey=="string"?T.projectKey:void 0});N(S,C.result.ok?200:422,C);return}if(c.method==="POST"&&O==="/memory/commit"){let T=await Ne(c),C=T.transaction&&typeof T.transaction=="object"&&!Array.isArray(T.transaction)?T.transaction:{},P=await q.commitReview(dr(T.command),{transactionId:typeof C.transactionId=="string"?C.transactionId:"",committedAt:typeof C.committedAt=="string"?C.committedAt:""});N(S,200,{status:await q.status(),journal:P.report});return}if(c.method==="POST"&&O==="/memory/recover"){let T=await Ne(c),C=await q.recover(T.confirm===!0);N(S,200,{status:await q.status(),journal:C.report});return}N(S,404,{error:"Memory endpoint not found."})}catch(T){let C=T instanceof Error?T.message:String(T),P=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(C),B=/required|invalid|unsupported|expected|must be|confirmation/i.test(C);if(P||B){N(S,P?409:400,{error:C});return}throw T}}async function ut(c,S,O){if(c.method==="GET"&&O==="/imprint/status"){let[T,C]=await Promise.all([H.store.load(),v.load()]),P=[...new Set(Object.values(C.threads).flatMap(B=>Gn(B.messages)))].filter(B=>T.graph.explanations.some(D=>D.id===B&&D.state==="testing"));N(S,200,{state:"ready",head:T.graph.head,updatedAt:T.graph.updatedAt,explanationCount:T.graph.explanations.filter(B=>B.state!=="retired").length,concreteCount:T.graph.concrete.length,relationCount:T.graph.relations.length,pendingGroundingCount:P.length,recoveredTransactions:T.recoveredTransactions,admission:H.diagnostics(),admissionWindowStartedAt:e});return}if(c.method==="POST"&&O==="/imprint/action"){let T=await Ne(c),C=typeof T.threadId=="string"?T.threadId:"",P=typeof T.transactionId=="string"?T.transactionId:"",B=String(T.action);if(!C||!P||!["yes","this_time","no"].includes(B)){N(S,400,{error:"A valid thread, imprint update, and action are required."});return}let z=await v.getThread(C),F=[...z?.messages??[]].reverse().find(se=>se.role==="assistant"&&se.imprintSummary?.transactionId===P),U=F?.imprintSummary;if(!z||!F||!U){N(S,409,{error:"This imprint summary is not available in the thread."});return}if(U.resolvedAction){N(S,409,{error:"This imprint summary has already been resolved."});return}let me=`imprint-${pt().slice(0,8)}`;await H.applyGroundingAction({summary:U,action:B,threadId:C,jobId:me}),B!=="no"&&await q.recordImprintEvidence({summary:U,action:B,threadId:C,jobId:me}).catch(se=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",se));let V=tn(F.result,!!F.question),fe=F.turn?{...F.turn,result:tn(F.turn.result,!!F.question)}:void 0;await v.updateAssistantMessage(C,F.jobId,{imprintSummary:{...U,resolvedAction:B},...V?{result:V}:{},...fe?{turn:fe}:{}});let le={yes:"> Yes",this_time:"> This time",no:"> No"};if(await v.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:me,replyToQuestion:le[B]}),B==="no"){let se="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",Z=Rn({question:se});await v.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:me,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:se,turn:{phase:"complete",orientation:[],result:Z},result:Z})}N(S,200,{ok:!0,action:B});return}N(S,404,{error:"Imprint endpoint not found."})}async function Je(c,S){let{screenshot:O,feedback:T,color:C,provider:P,model:B,reasoningEffort:D,serviceTier:z,sourceId:F,continuationThreadId:U,continuationTargetBindingId:me,continuationSelectorAliases:V,pastedImages:fe,pageScreenshots:le}=await Mr(c),se=C,Z;try{Z=JSON.parse(T)}catch{N(S,400,{error:"Invalid feedback JSON"});return}let re=Z.annotations.flatMap(ne=>(ne.attachments??[]).map($e=>({id:$e.id,annotationId:ne.id}))),be;try{be=re.length>0?await J.promote(re):void 0}catch(ne){N(S,409,{error:ne instanceof Error?ne.message:"Draft attachment unavailable."});return}let Te=pt().slice(0,8),he={};if(le.length>0)for(let ne of le){let $e=encodeURIComponent(ne.pathname),De=Ye(d,`screenshot-${Te}-${$e}.webp`);await Fo(De,ne.data),he[ne.pathname]=De}let Fe=Ye(d,`screenshot-${Te}.webp`);await Fo(Fe,O);let xe={};if(fe.length>0)for(let ne of fe){let $e=Ye(d,`pasted-${Te}-${ne.annotationId}-${ne.index}.webp`);await Fo($e,ne.data),xe[ne.annotationId]||(xe[ne.annotationId]=[]),xe[ne.annotationId].push($e)}let Y=zs(Z),Ie=Gs(Z,V),gt=Jr(Z,V),Se,te=!1,ye;if(Y.length>0){let ne=await v.findOrCreateContinuationThread(Y,`thread-${pt()}`,U,Ie,gt,me);Se=ne.thread.id,ye=ne.decision,te=ye.action==="continued",console.log(`[Continuation] ${JSON.stringify({event:"continuation_resolution",...ye,...U?{preferredThreadId:U}:{},...me?{preferredTargetBindingId:me}:{},resolvedThreadId:Se,...ne.targetBindings[0]?.id?{resolvedTargetBindingId:ne.targetBindings[0].id}:{}})}`),te&&(se=ne.thread.messages.find($e=>$e.annotationSnapshot?.color)?.annotationSnapshot?.color??se)}else Se=(await v.createThread(`thread-${pt()}`,[])).id;let We=te||(await v.findContinuationThread(Y))?.id===Se,Ue=Z.annotations.map(ne=>ne.id),Ce=Object.keys(he).length>0,Ae=await Yn(q,Z,Y,ne=>console.warn(`[\u22B9 ${I}:${Te}] Contextual memory unavailable; continuing without it:`,ne instanceof Error?ne.message:String(ne))),Ze=(await v.getThread(Se))?.messages??[],K=await H.contextualize({text:Wt(Z),subjectHints:os(Z,Y),pendingGroundingExplanationIds:Gn(Ze),correctionExplanationIds:ta(Ze)}).catch(ne=>{console.warn(`[\u22B9 ${I}:${Te}] Imprint context unavailable; continuing without it:`,ne instanceof Error?ne.message:String(ne))}),we=Br({jobId:Te,threadId:Se,artifactIds:Ws(Z,Te)}),pe={id:Te,status:"queued",screenshotPath:Fe,feedback:Z,createdAt:Date.now(),color:se,threadId:Se,annotationIds:Ue,provider:ln(P),model:B||void 0,agentSettings:qt({reasoningEffort:D,serviceTier:z}),...Object.keys(xe).length>0?{imagePaths:xe}:{},...be&&Object.keys(be).length>0?{attachmentFiles:be}:{},sourceId:F||void 0,...Ce?{screenshotPaths:he}:{},...Ae?{memoryReview:Ae}:{},...K?{imprintContext:K}:{},lifecycle:we},ze=new Set(Z.annotations.map(ne=>ne.pathname).filter(Boolean)),Bt;if(ze.size>1){let ne=new Map;for(let $e of Z.annotations){let De=$e.pathname||"(unknown)";ne.has(De)||ne.set(De,[]),ne.get(De).push($e.instruction||na({...Z,annotations:[$e]}))}Bt=[...ne.entries()].map(([$e,De])=>`\`${$e}\`
199
+ ${De.map(ae=>`- ${ae}`).join(`
200
200
  `)}`).join(`
201
- `)}else Ve=Us(Y);let V=_n(Y,Object.keys(ie).length>0?ie:void 0,me),Ie=Ur(Y);await x.appendMessage(be,{role:"human",timestamp:Date.now(),jobId:ee,screenshotPath:Ae,...Ee?{screenshotPaths:xe}:{},...Object.keys(ie).length>0?{imagePaths:ie}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},annotationIds:it,annotationSnapshot:{url:Y.url,viewport:Y.viewport,annotations:Y.annotations,color:de||void 0},feedbackSummary:Ve,...Ie?{requestText:Ie}:{},feedbackContext:V||void 0,...te?{memoryReview:te}:{},...De?{imprintContext:De}:{},lifecycle:ze});let fe=P.enqueue(Ne);$(b,200,{jobId:ee,position:fe,threadId:be,color:de||void 0,continuedThread:Z,continuationEligible:ye})}async function rt(c,b){let C=c.headers["content-type"]||"",w,_,R,N,B,U,L,F,ge=[];if(C.includes("multipart/form-data")){let V=await Rr(c),Ie=V.feedback?JSON.parse(V.feedback):{};w=Ie.threadId,_=Ie.reply,R=Ie.color,N=Ie.provider,B=Ie.model,U=Bt(Ie),L=Ie.sourceId||V.sourceId,F=typeof Ie.memoryReviewProposalId=="string"?Ie.memoryReviewProposalId:void 0;for(let fe of V.pastedImages)ge.push(fe.data)}else{let V=[];for await(let ne of c)V.push(typeof ne=="string"?Buffer.from(ne):ne);let Ie=Buffer.concat(V).toString("utf-8"),fe;try{fe=JSON.parse(Ie)}catch{$(b,400,{error:"Invalid JSON"});return}w=fe.threadId,_=fe.reply,R=fe.color,N=fe.provider,B=fe.model,U=Bt(fe),L=fe.sourceId,F=fe.memoryReviewProposalId}if(!w||!_){$(b,400,{error:"Missing threadId or reply"});return}let K=await x.getThread(w);if(!K){$(b,404,{error:"Thread not found"});return}let de;if(F){let V=await se.findModelProposalsByThread(w);if(de=(await Promise.all(V.flatMap(fe=>fe.authorityStatus==="accepted"?[]:fe.decisionIds.map(async ne=>({modelProposalId:fe.id,underlying:await J.findPendingProposalForLegacyDecision(ne)}))))).filter(fe=>!!fe.underlying).find(fe=>fe.underlying.proposalId===F),!de){$(b,409,{error:"The requested memory decision is not pending in this thread."});return}}let Y="";{let V=await x.getThreadHistory(w);for(let Ie=V.length-1;Ie>=0;Ie--)if(V[Ie].screenshotPath){Y=V[Ie].screenshotPath;break}}let ce=await qo(w);if(!Y&&!ce){$(b,400,{error:"No screenshot available"});return}let me=P.hasActiveThread(w),ee=me?P.getQueuedThreadJob(w,V=>V._replyText!==void 0||V._replyPrompt!==void 0):null,xe=ee?.id??pt().slice(0,8),Ae=$r({jobId:xe,threadId:w}),ie=[],Me=`${xe}-${Date.now()}`;for(let V=0;V<ge.length;V++){let Ie=Ye(d,`reply-${Me}-${V}.webp`);await Oo(Ie,ge[V]),ie.push(Ie)}await x.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:xe,replyToQuestion:_,screenshotPath:Y,...me?{queued:!0}:{},...ie.length>0?{replyImagePaths:ie}:{},lifecycle:{...Ae,artifactIds:ie.map((V,Ie)=>`reply-image:${xe}:${Ie}`)}});let be=await x.getThreadHistory(w),Z=[...be].reverse().find(V=>V.memoryReview)?.memoryReview,ye=await H.contextualize({text:_,subjectHints:Wi(be,K.elementIdentifiers),pendingGroundingExplanationIds:Bn(be),correctionExplanationIds:Ls(be)}).catch(V=>{console.warn(`[\u22B9 ${f}:${xe}] Imprint context unavailable for reply; continuing without it:`,V instanceof Error?V.message:String(V))});ye&&await x.updateMessage(w,xe,{imprintContext:ye});let it=new Set(be.flatMap(V=>V.memoryReceipt?.status==="committed"?[V.memoryReceipt.proposalId]:[])),Ee=[...be].reverse().find(V=>V.memoryReviewCard&&!it.has(V.memoryReviewCard.proposalId))?.memoryReviewCard,te=[];for(let V of be)if(V.annotationIds)for(let Ie of V.annotationIds)te.includes(Ie)||te.push(Ie);let we=cn(N),De=de,ze=De?[De.underlying.proposalId]:Ee?[Ee.proposalId]:[],Ne=gs(Y,be,we,ie.length>0?ie:void 0);if(De?Ne+=["","## Decision review card",`Privately review proposal ${De.underlying.proposalId}: ${De.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
- `):Ee&&(Ne+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Ee)}`,"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(`
203
- `)),ee){let V=ee,fe=[...V._replyTexts??(V._replyText?[V._replyText]:[]),_],ne=[...V._replyImagePaths??[],...ie];V._replyTexts=fe,V._replyText=qs(fe),V._replyImagePaths=ne.length>0?ne:void 0,V._replyPrompt=Ne,V.annotationIds=te.length>0?te:V.annotationIds,V.agentSettings=U??V.agentSettings,V.memoryReview=Z??V.memoryReview,V.imprintContext=ye??V.imprintContext,V.surfacedProposalIds=[...new Set([...V.surfacedProposalIds??[],...ze])],V.lifecycle={...V.lifecycle??Ae,submissionIds:[...new Set([...V.lifecycle?.submissionIds??[],...Ae.submissionIds])],artifactIds:[...new Set([...V.lifecycle?.artifactIds??[],...Ae.artifactIds])]},$(b,200,{jobId:xe,position:1,threadId:w,bundled:!0});return}let _e={id:xe,status:"queued",screenshotPath:Y,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:R,threadId:w,annotationIds:te.length>0?te:void 0,provider:we,model:B||void 0,agentSettings:U,sourceId:L||void 0,...Z?{memoryReview:Z}:{},...ye?{imprintContext:ye}:{},...ze.length?{surfacedProposalIds:ze}:{},lifecycle:Ae};ce&&(_e.kind=ce),_e._replyPrompt=Ne,_e._replyTexts=[_],_e._replyText=qs([_]),ie.length>0&&(_e._replyImagePaths=ie);let Ve=me?P.enqueueNext(_e):P.enqueue(_e);$(b,200,{jobId:xe,position:Ve,threadId:w})}function mt(c,b){b.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),b.write(`event: connected
201
+ `)}else Bt=na(Z);let Vn=On(Z,Object.keys(xe).length>0?xe:void 0,be),Hn=ei(Z),Rt=Zr(Z);await v.appendMessage(Se,{role:"human",timestamp:Date.now(),jobId:Te,screenshotPath:Fe,...Ce?{screenshotPaths:he}:{},...Object.keys(xe).length>0?{imagePaths:xe}:{},...be&&Object.keys(be).length>0?{attachmentFiles:be}:{},annotationIds:Ue,annotationSnapshot:{url:Z.url,viewport:Z.viewport,annotations:Z.annotations,color:se||void 0},feedbackSummary:Bt,...Hn?{requestText:Hn}:{},...Rt.length>0?{requestItems:Rt}:{},feedbackContext:Vn||void 0,...Ae?{memoryReview:Ae}:{},...K?{imprintContext:K}:{},lifecycle:we});let hn=R.enqueue(pe),gn=await Promise.all(((await v.getThread(Se))?.targetBindings??[]).map(async ne=>({...ne,continuationEligible:await v.isTargetBindingContinuationEligible(Se,ne.id)})));N(S,200,{jobId:Te,position:hn,threadId:Se,color:se||void 0,continuedThread:te,continuationDecision:ye,continuationEligible:We,targetBindings:gn})}async function it(c,S){let O=c.headers["content-type"]||"",T,C,P,B,D,z,F,U,me=[];if(O.includes("multipart/form-data")){let K=await Mr(c),we=K.feedback?JSON.parse(K.feedback):{};T=we.threadId,C=we.reply,P=we.color,B=we.provider,D=we.model,z=qt(we),F=we.sourceId||K.sourceId,U=typeof we.memoryReviewProposalId=="string"?we.memoryReviewProposalId:void 0;for(let pe of K.pastedImages)me.push(pe.data)}else{let K=[];for await(let ze of c)K.push(typeof ze=="string"?Buffer.from(ze):ze);let we=Buffer.concat(K).toString("utf-8"),pe;try{pe=JSON.parse(we)}catch{N(S,400,{error:"Invalid JSON"});return}T=pe.threadId,C=pe.reply,P=pe.color,B=pe.provider,D=pe.model,z=qt(pe),F=pe.sourceId,U=pe.memoryReviewProposalId}if(!T||!C){N(S,400,{error:"Missing threadId or reply"});return}let V=await v.getThread(T);if(!V){N(S,404,{error:"Thread not found"});return}let fe;if(U){let K=await ue.findModelProposalsByThread(T);if(fe=(await Promise.all(K.flatMap(pe=>pe.authorityStatus==="accepted"?[]:pe.decisionIds.map(async ze=>({modelProposalId:pe.id,underlying:await q.findPendingProposalForLegacyDecision(ze)}))))).filter(pe=>!!pe.underlying).find(pe=>pe.underlying.proposalId===U),!fe){N(S,409,{error:"The requested memory decision is not pending in this thread."});return}}let le="";{let K=await v.getThreadHistory(T);for(let we=K.length-1;we>=0;we--)if(K[we].screenshotPath){le=K[we].screenshotPath;break}}let se=await Ko(T);if(!le&&!se){N(S,400,{error:"No screenshot available"});return}let Z=R.hasActiveThread(T),re=Z?R.getQueuedThreadJob(T,K=>K._replyText!==void 0||K._replyPrompt!==void 0):null,be=re?.id??pt().slice(0,8),Te=Br({jobId:be,threadId:T}),he=[],Fe=`${be}-${Date.now()}`;for(let K=0;K<me.length;K++){let we=Ye(d,`reply-${Fe}-${K}.webp`);await Fo(we,me[K]),he.push(we)}await v.appendMessage(T,{role:"human",timestamp:Date.now(),jobId:be,replyToQuestion:C,screenshotPath:le,...Z?{queued:!0}:{},...he.length>0?{replyImagePaths:he}:{},lifecycle:{...Te,artifactIds:he.map((K,we)=>`reply-image:${be}:${we}`)}});let xe=await v.getThreadHistory(T),Y=[...xe].reverse().find(K=>K.memoryReview)?.memoryReview,Ie=await H.contextualize({text:C,subjectHints:rs(xe,V.elementIdentifiers),pendingGroundingExplanationIds:Gn(xe),correctionExplanationIds:ta(xe)}).catch(K=>{console.warn(`[\u22B9 ${I}:${be}] Imprint context unavailable for reply; continuing without it:`,K instanceof Error?K.message:String(K))});Ie&&await v.updateMessage(T,be,{imprintContext:Ie});let gt=new Set(xe.flatMap(K=>K.memoryReceipt?.status==="committed"?[K.memoryReceipt.proposalId]:[])),Se=[...xe].reverse().find(K=>K.memoryReviewCard&&!gt.has(K.memoryReviewCard.proposalId))?.memoryReviewCard,te=[];for(let K of xe)if(K.annotationIds)for(let we of K.annotationIds)te.includes(we)||te.push(we);let ye=ln(B),We=fe,Ue=We?[We.underlying.proposalId]:Se?[Se.proposalId]:[],Ce=As(le,xe,ye,he.length>0?he:void 0);if(We?Ce+=["","## Decision review card",`Privately review proposal ${We.underlying.proposalId}: ${We.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
+ `):Se&&(Ce+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Se)}`,"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(`
203
+ `)),re){let K=re,pe=[...K._replyTexts??(K._replyText?[K._replyText]:[]),C],ze=[...K._replyImagePaths??[],...he];K._replyTexts=pe,K._replyText=ea(pe),K._replyImagePaths=ze.length>0?ze:void 0,K._replyPrompt=Ce,K.annotationIds=te.length>0?te:K.annotationIds,K.agentSettings=z??K.agentSettings,K.memoryReview=Y??K.memoryReview,K.imprintContext=Ie??K.imprintContext,K.surfacedProposalIds=[...new Set([...K.surfacedProposalIds??[],...Ue])],K.lifecycle={...K.lifecycle??Te,submissionIds:[...new Set([...K.lifecycle?.submissionIds??[],...Te.submissionIds])],artifactIds:[...new Set([...K.lifecycle?.artifactIds??[],...Te.artifactIds])]},N(S,200,{jobId:be,position:1,threadId:T,bundled:!0});return}let Ae={id:be,status:"queued",screenshotPath:le,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:T,annotationIds:te.length>0?te:void 0,provider:ye,model:D||void 0,agentSettings:z,sourceId:F||void 0,...Y?{memoryReview:Y}:{},...Ie?{imprintContext:Ie}:{},...Ue.length?{surfacedProposalIds:Ue}:{},lifecycle:Te};se&&(Ae.kind=se),Ae._replyPrompt=Ce,Ae._replyTexts=[C],Ae._replyText=ea([C]),he.length>0&&(Ae._replyImagePaths=he);let Ze=Z?R.enqueueNext(Ae):R.enqueue(Ae);N(S,200,{jobId:be,position:Ze,threadId:T})}function mt(c,S){S.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),S.write(`event: connected
204
204
  data: {"status":"connected"}
205
205
 
206
- `);let w=new URL(c.url||"/",`http://127.0.0.1:${f}`).searchParams.get("sourceId")||void 0,_={id:pt().slice(0,8),res:b,sourceId:w};re.add(_),c.on("close",()=>{re.delete(_)})}async function ft(c,b,C){a??=ks(c.headers),ot();let w=[...P.allActive,...A.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[_,R,N,B,U]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),J.status(),H.store.load(),x.load()]),L=[],F=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);_.status==="rejected"&&L.push({subsystem:"projection",message:F(_)}),R.status==="rejected"&&L.push({subsystem:"projection",message:F(R)}),N.status==="rejected"?L.push({subsystem:"memory",message:F(N)}):N.value.state==="degraded"&&L.push({subsystem:"memory",message:N.value.error??"Product memory is degraded."}),B.status==="rejected"&&L.push({subsystem:"imprint",message:F(B)}),U.status==="rejected"&&L.push({subsystem:"threads",message:F(U)});let ge=_.status==="fulfilled"?_.value.runs:[],K=R.status==="fulfilled"?R.value.proposals:[],de=Rs(ge,K),Y=de.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),ce=N.status==="fulfilled"?N.value:{initialized:!1,state:"degraded",error:F(N)},me=U.status==="fulfilled"?[...new Set(Object.values(U.value.threads).flatMap(Z=>Bn(Z.messages)))]:[],ee=B.status==="fulfilled"?me.filter(Z=>B.value.graph.explanations.some(ye=>ye.id===Z&&ye.state==="testing")):[],xe=B.status==="fulfilled"?{state:"ready",head:B.value.graph.head,updatedAt:B.value.graph.updatedAt,explanationCount:B.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:B.value.graph.concrete.length,relationCount:B.value.graph.relations.length,pendingGroundingCount:ee.length,recoveredTransactions:B.value.recoveredTransactions,admission:H.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:F(B),pendingGroundingCount:ee.length,admission:H.diagnostics(),admissionWindowStartedAt:e},Ae=L.length>0?"degraded":ce.state==="absent"||ce.state==="initializing"?"initializing":"healthy",ie=w.filter(Z=>x.isThreadInActiveWorkspace(Z.threadId)),Me=Pe.filter(Z=>x.isThreadInActiveWorkspace(Z.threadId)),be=new Date().toISOString();$(b,200,{ok:!0,schemaVersion:3,generatedAt:be,serverStartedAt:e,health:{state:Ae,issues:L},version:st,restartMode:I,projectId:i,workspaceGeneration:x.getActiveWorkspaceGeneration(),storeId:s.storeId,projectName:Do(r),projectRoot:r,requestProjectId:C,projectIdVerified:C===i,devOrigin:a,capture:{native:{configured:!!u,endpoint:u?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:ie[0]?{id:ie[0].id,status:ie[0].status}:null,activeJobs:ie.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:P.depth+A.depth,projectionQueueDepth:A.depth,leases:{active:Q.isActivated,count:Q.size,nextExpiryAt:Q.nextExpiryAt,shutdownPending:G},projection:{state:_.status==="fulfilled"&&R.status==="fulfilled"?"ready":"degraded",activeJob:A.active?{id:A.active.id,status:A.active.status,threadId:A.active.threadId,annotationIds:A.active.annotationIds??[],provider:A.active.provider,model:A.active.model}:null,queueDepth:A.depth,recentRuns:de.recentRuns,recentAppliedRuns:de.recentAppliedRuns,actionableProposalCounts:de.actionableProposalCounts,actionableProposals:Y},memory:ce,imprint:xe,recentJobsRetentionMs:pn,recentJobs:Me})}async function xt(c,b){let C=await new Promise(w=>{let _="";c.on("data",R=>{_+=R.toString()}),c.on("end",()=>w(_))});try{let w=JSON.parse(C);typeof w.devOrigin=="string"&&(a=w.devOrigin||null),$(b,200,{ok:!0,devOrigin:a})}catch{$(b,400,{error:"Invalid JSON"})}}async function Bo(c){let b=await he.load();$(c,200,{ok:!0,...b})}async function Jo(c,b){let C=await Be(c);if(!Ns(C.theme)){$(b,400,{error:"theme must be light, dark, or auto"});return}let w=await he.setTheme(C.theme);$(b,200,{ok:!0,exists:!0,preferences:w})}async function un(c,b){let w=new URL(c.url||"/",`http://127.0.0.1:${f}`).searchParams.get("jobId"),_=w?P.allActive.filter(F=>F.id===w):P.allActive,R=w?A.allActive.filter(F=>F.id===w):A.allActive,N=[..._.map(F=>F.threadId),...R.map(F=>F.threadId)].filter(Boolean),B=w?P.cancelJob(w):P.cancelActive(),U=w?A.cancelJob(w):A.cancelActive(),L=!!(B||U);for(let F of N)await x.appendMessage(F,{role:"assistant",timestamp:Date.now(),jobId:w||U?.id||"",cancelled:!0});$(b,200,{cancelled:L})}async function Oe(c){let b=pt().slice(0,8),C=c.threadId,w=!C;C||(C=(await x.createThread(`thread-${pt()}`,[])).id,bt.set(C,"project_model")),w&&await x.appendMessage(C,{role:"human",timestamp:Date.now(),jobId:b,feedbackSummary:c.reason}),await x.appendMessage(C,{role:"assistant",timestamp:Date.now(),jobId:b,responseText:w?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:c.model,provider:c.provider});let _={id:b,status:"queued",createdAt:Date.now(),provider:c.provider,model:c.model,agentSettings:c.agentSettings,threadId:C,annotationIds:c.annotationIds,sourceId:c.sourceId,standalone:w},R=A.enqueue(_);return{jobId:b,position:R,threadId:C}}async function Fe(c,b){let C=decodeURIComponent(c),w=await se.findModelProposal(C);if(!w){$(b,404,{error:"Model proposal not found"});return}$(b,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:w})}async function ht(c,b,C){let w=decodeURIComponent(c),_=[];for await(let K of b)_.push(typeof K=="string"?Buffer.from(K):K);let R;try{R=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{$(C,400,{error:"Invalid JSON"});return}let N=(R.changes??[]).flatMap(K=>{if(!Array.isArray(K.path)||K.path.length===0)return[];let de=K.path.filter(ce=>typeof ce=="string"||typeof ce=="number");if(de.length!==K.path.length)return[];let Y=Array.isArray(K.decisionIds)?K.decisionIds.filter(ce=>typeof ce=="string"):void 0;return[{path:de,value:K.value,remove:K.remove===!0,decisionIds:Y}]});if(N.length===0){$(C,400,{error:"No selected model changes"});return}let B=(R.changeSummaries??[]).flatMap(K=>{if(!K||typeof K!="object")return[];let de=Array.isArray(K.path)?K.path.filter(Y=>typeof Y=="string"||typeof Y=="number"):void 0;return Array.isArray(K.path)&&de?.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:de,value:K.value,currentValue:K.currentValue}]}),U=await se.findModelProposal(w);if(!U){$(C,404,{error:"Model proposal not found"});return}if(U.authorityStatus!=="accepted"){$(C,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(U.status!=="pending"){$(C,409,{error:`Model proposal is already ${U.status}.`});return}let L=U.decisionIds.map(K=>{let de=U.changes?.filter(me=>me.decisionIds.includes(K)).length??0,Y=N.filter(me=>me.decisionIds?.includes(K)).length,ce=Y===0?"unprojected":de>Y?"partially_projected":"projected";return{decisionId:K,status:ce}}),F=await J.applyModelProjection({runId:U.runId??U.id,presentationJobId:U.presentationJobId,decisionIds:U.decisionIds,changes:N.map(K=>({path:K.path,value:K.value,decisionIds:K.decisionIds})),coverage:L}),ge=await se.applySelectedModelProposal(w,N,B);if(!ge){$(C,404,{error:"Model proposal not found"});return}if(ge.threadId){let K=cn(R.provider),de=typeof R.model=="string"&&R.model?R.model:void 0;await x.appendMessage(ge.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ge.id}`,responseText:"",provider:K,model:de})}$(C,200,{proposal:ge,projection:F})}async function Ot(c,b,C){let w=decodeURIComponent(c),{provider:_,model:R}=await St(b),N=await se.dismissModelProposal(w);if(!N){$(C,404,{error:"Model proposal not found"});return}N.threadId&&await x.appendMessage(N.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${N.id}`,responseText:"",provider:_,model:R}),$(C,200,{proposal:N})}async function St(c){try{let b=[];for await(let w of c)b.push(typeof w=="string"?Buffer.from(w):w);if(b.length===0)return{};let C=JSON.parse(Buffer.concat(b).toString());return{provider:cn(typeof C.provider=="string"?C.provider:void 0),model:typeof C.model=="string"&&C.model?C.model:void 0,agentSettings:Bt(C)}}catch{return{}}}async function qo(c){let b=bt.get(c);if(b)return b;let _=(await x.getThread(c))?.messages.find(R=>R.role==="human")?.feedbackSummary??"";if(_.startsWith("Synthesize rules"))return bt.set(c,"synthesize"),"synthesize";if(_.startsWith("Materialize model")||_.startsWith("Project model"))return bt.set(c,"project_model"),"project_model"}async function qn(c,b){let C=[];for await(let U of c)C.push(typeof U=="string"?Buffer.from(U):U);let w;if(C.length>0)try{w=JSON.parse(Buffer.concat(C).toString("utf-8")).serverUrl}catch{}let _=[];p.claude?.available&&p.claude.mcp&&!p.claude.mcp.found&&_.push(await is(w)),p.codex?.available&&p.codex.mcp&&!p.codex.mcp.found&&_.push(await ss(w)),p.copilot?.available&&p.copilot.mcp&&!p.copilot.mcp.found&&_.push(await as(w,p.copilot.path??k));let[R,N,B]=await Promise.all([br(r),xr(r),Sr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=R),p.codex&&(p.codex.mcp=N),p.copilot&&(p.copilot.mcp=B),$(b,200,{results:_,capabilities:{providers:p}})}async function Ys(c,b){let C=[];for await(let R of c)C.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{$(b,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){$(b,400,{error:"Missing or invalid name"});return}let _=await J.recordDirectModelMutation({key:`components.${w.name}`,value:{description:""},claim:`${w.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await J.getCanonicalModelEntries()),$(b,200,{added:!0,alreadyExists:!1,..._})}async function Zs(c,b){let C=[];for await(let R of c)C.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{$(b,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){$(b,400,{error:"Missing or invalid name"});return}let _=await J.recordDirectModelMutation({key:`components.${w.name}`,value:null,claim:`${w.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await J.getCanonicalModelEntries()),$(b,200,{removed:!0,..._})}async function ea(c,b){let C=[];for await(let N of c)C.push(typeof N=="string"?Buffer.from(N):N);let w;try{w=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{$(b,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"||typeof w.value!="string"){$(b,400,{error:"Missing or invalid path/value"});return}let _=w.value;try{let N=JSON.parse(w.value);N&&typeof N=="object"&&(_=N)}catch{}let R=await J.recordDirectModelMutation({key:`tokens.${w.path}`,value:_,claim:`${w.path} uses ${w.value} in the product model.`});await se.applyCanonicalEntries(await J.getCanonicalModelEntries()),$(b,200,{updated:!0,...R})}async function ta(c,b){let C=[];for await(let R of c)C.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{$(b,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"){$(b,400,{error:"Missing or invalid path"});return}let _=await J.recordDirectModelMutation({key:`tokens.${w.path}`,value:null,claim:`${w.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await J.getCanonicalModelEntries()),$(b,200,{removed:!0,..._})}async function na(c,b){if(!c||c.includes("/")||c.includes("\\")||c.includes("..")){$(b,400,{error:"Invalid filename"});return}try{let C=[Ye(d,c),Ye(r,".popmelt","artifacts","thread-media",c),Ye(r,".popmelt","artifacts","eval-screenshots",c),Ye(r,".popmelt","evals","screenshots",c),Ye(r,".popmelt","screenshots",c)],w;for(let N of C)try{w=await Wl(N);break}catch{}if(!w)throw new Error("File not found");let _=c.split(".").pop()?.toLowerCase(),R=_==="png"?"image/png":_==="webp"?"image/webp":_==="jpg"||_==="jpeg"?"image/jpeg":_==="svg"?"image/svg+xml":_==="txt"?"text/plain; charset=utf-8":"application/octet-stream";b.writeHead(200,{"Content-Type":R,"Cache-Control":"public, max-age=3600"}),b.end(w)}catch{$(b,404,{error:"File not found"})}}function mn(c){return`/files/${Do(c)}`}async function oa(c,b){let C=await x.getThread(c);if(!C){$(b,404,{error:"Thread not found"});return}let w=C.messages.filter(L=>L.role==="assistant"&&L.responseText?.includes("Model suggestion ready")),_=await(w.length>0?se.findModelProposalsByThread(c):Promise.resolve([])),R=await Promise.all(_.map(async(L,F)=>{if(L.authorityStatus==="accepted")return L;let ge=(await Promise.all(L.decisionIds.map(K=>J.findPendingProposalForLegacyDecision(K)))).find(Boolean);return{...L,authorityStatus:"legacy_untrusted",presentationJobId:L.presentationJobId??w[F]?.jobId??w.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),N=[...R].sort((L,F)=>F.updatedAt-L.updatedAt)[0]??null,B=C.elementIdentifiers.some(L=>L.startsWith("codex-session:"))?await J.findPendingProposalsForThread(c):[],U=C.messages.map(({screenshotPath:L,screenshotPaths:F,imagePaths:ge,attachmentFiles:K,replyImagePaths:de,...Y})=>({...Y,...L?{screenshotUrl:mn(L)}:{},...F?{screenshotUrls:Object.fromEntries(Object.entries(F).map(([ce,me])=>[ce,mn(me)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([ce,me])=>[ce,me.map(mn)]))}:{},...K?{attachments:Object.fromEntries(Object.entries(K).map(([ce,me])=>[ce,me.map(({path:ee,...xe})=>({...xe,url:mn(ee)}))]))}:{},...de?{replyImageUrls:de.map(mn)}:{}}));$(b,200,{id:C.id,createdAt:C.createdAt,messages:U,modelProposal:N,modelProposals:R,decisionCandidates:B})}async function ra(c,b){let C=decodeURIComponent(c);if(!await x.deleteThread(C)){$(b,404,{deleted:!1,error:"Thread not found"});return}$(b,200,{deleted:!0})}let Br=9,Jr=!1;for(let c=t;c<t+Br;c++)try{await vp($t,c),f=c,Jr=!0,console.log(`[\u22B9 is watching :${f}]`);break}catch(b){if(b.code==="EADDRINUSE"){let C=await ln(c);if(Dn(C,{projectId:i,version:st,restartMode:I}))return console.log(`[\u22B9 already watching :${c}]`),{port:c,projectId:i,close:async()=>{}};continue}throw b}if(!Jr)throw new Error(`[Bridge] All ports ${t}\u2013${t+Br-1} in use`);for(let[c,b]of Object.entries(p))!b.available||!b.path||h(c,b.path).then(C=>{if(C)console.log(`[Bridge] ${c} warmed up`);else{console.warn(`[Bridge] ${c} warm-up failed \u2014 marking unavailable`),b.available=!1,b.path=null;for(let w of re)Jn(w,{type:"capabilities_changed",data:{}})}});let ia=setInterval(()=>{zs(d).catch(()=>{}),q.sweep().catch(()=>{})},op),qr=setInterval(()=>{Q.expireStale().becameEmpty&&X()},ip);return qr.unref?.(),{port:f,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(ia),clearInterval(qr),W(),Q.clear(),await q.cleanupPartials(),await P.destroyAsync(),A.destroy();for(let c of re)try{c.res.end()}catch{}return re.clear(),new Promise(c=>{$t.close(()=>c())})}}}async function zs(o){try{let e=await Vl(o),t=Date.now();for(let n of e){let r=Ye(o,n);try{let i=await Hl(r);t-i.mtimeMs>rp&&await Ql(r)}catch{}}}catch{}}import{randomUUID as bp}from"crypto";var xp=5e3,Sp=250;function Dr(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Ks(o,e=fetch){let t=`${process.pid}-${bp()}`,n=`http://127.0.0.1:${o.port}`,r=!1,i=!1,s=async()=>(await e(`${n}/leases`,{method:"POST",headers:Dr(o),body:JSON.stringify({leaseId:t,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(v){return console.warn("[popmelt] failed to register bridge lease:",v instanceof Error?v.message:String(v)),null}let a=async()=>{if(!(r||i)){i=!0;try{(await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"PATCH",headers:Dr(o)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{a()},xp);return d.unref?.(),{id:t,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"DELETE",headers:Dr(o),keepalive:!0})}catch{}}}}}function Hs(o,e=process){let t=!1,n=new Map,r=()=>{if(!t){t=!0;for(let[i,s]of n)e.removeListener(i,s);n.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let a=e.listenerCount(i),d=o.release();if(a>0)return;let l=new Promise(v=>{setTimeout(v,Sp)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};n.set(i,s),e.prependOnceListener(i,s)}return r}var Cp=1111,Qs=3e4,$p=8e3;async function Op(o){return Mp(o).catch(()=>o)}async function Xs(o,e){let n=(await jp(e,"utf8").catch(()=>"")).slice(-$p).trim();return new Error(n?`${o}
206
+ `);let T=new URL(c.url||"/",`http://127.0.0.1:${I}`).searchParams.get("sourceId")||void 0,C={id:pt().slice(0,8),res:S,sourceId:T};ee.add(C),c.on("close",()=>{ee.delete(C)})}async function ft(c,S,O){a??=Ns(c.headers),rt();let T=[...R.allActive,..._.allActive.map(Y=>({id:Y.id,status:Y.status,threadId:Y.threadId,annotationIds:Y.annotationIds??[],color:"#000000",kind:"project_model",standalone:Y.standalone}))],[C,P,B,D,z]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),q.status(),H.store.load(),v.load()]),F=[],U=Y=>Y.reason instanceof Error?Y.reason.message:String(Y.reason);C.status==="rejected"&&F.push({subsystem:"projection",message:U(C)}),P.status==="rejected"&&F.push({subsystem:"projection",message:U(P)}),B.status==="rejected"?F.push({subsystem:"memory",message:U(B)}):B.value.state==="degraded"&&F.push({subsystem:"memory",message:B.value.error??"Product memory is degraded."}),D.status==="rejected"&&F.push({subsystem:"imprint",message:U(D)}),z.status==="rejected"&&F.push({subsystem:"threads",message:U(z)});let me=C.status==="fulfilled"?C.value.runs:[],V=P.status==="fulfilled"?P.value.proposals:[],fe=Bs(me,V),le=fe.actionableProposals.map(Y=>({id:Y.id,status:Y.status,title:Y.title,summary:Y.summary,decisionIds:Y.decisionIds,threadId:Y.threadId,runId:Y.runId,presentationJobId:Y.presentationJobId,authorityStatus:Y.authorityStatus,underlyingProposalId:Y.underlyingProposalId,createdAt:Y.createdAt,updatedAt:Y.updatedAt,appliedAt:Y.appliedAt,dismissedAt:Y.dismissedAt,error:Y.error})),se=B.status==="fulfilled"?B.value:{initialized:!1,state:"degraded",error:U(B)},Z=z.status==="fulfilled"?[...new Set(Object.values(z.value.threads).flatMap(Y=>Gn(Y.messages)))]:[],re=D.status==="fulfilled"?Z.filter(Y=>D.value.graph.explanations.some(Ie=>Ie.id===Y&&Ie.state==="testing")):[],be=D.status==="fulfilled"?{state:"ready",head:D.value.graph.head,updatedAt:D.value.graph.updatedAt,explanationCount:D.value.graph.explanations.filter(Y=>Y.state!=="retired").length,concreteCount:D.value.graph.concrete.length,relationCount:D.value.graph.relations.length,pendingGroundingCount:re.length,recoveredTransactions:D.value.recoveredTransactions,admission:H.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:U(D),pendingGroundingCount:re.length,admission:H.diagnostics(),admissionWindowStartedAt:e},Te=F.length>0?"degraded":se.state==="absent"||se.state==="initializing"?"initializing":"healthy",he=T.filter(Y=>v.isThreadInActiveWorkspace(Y.threadId)),Fe=Me.filter(Y=>v.isThreadInActiveWorkspace(Y.threadId)),xe=new Date().toISOString();N(S,200,{ok:!0,schemaVersion:3,generatedAt:xe,serverStartedAt:e,health:{state:Te,issues:F},version:st,restartMode:y,projectId:i,workspaceGeneration:v.getActiveWorkspaceGeneration(),storeId:s.storeId,projectName:Uo(r),projectRoot:r,requestProjectId:O,projectIdVerified:O===i,devOrigin:a,capture:{native:{configured:!!u,endpoint:u?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:he[0]?{id:he[0].id,status:he[0].status}:null,activeJobs:he.map(Y=>({id:Y.id,status:Y.status,threadId:Y.threadId,annotationIds:Y.annotationIds,color:Y.color,kind:Y.kind,standalone:"standalone"in Y?Y.standalone:void 0})),queueDepth:R.depth+_.depth,projectionQueueDepth:_.depth,leases:{active:X.isActivated,count:X.size,nextExpiryAt:X.nextExpiryAt,shutdownPending:L},projection:{state:C.status==="fulfilled"&&P.status==="fulfilled"?"ready":"degraded",activeJob:_.active?{id:_.active.id,status:_.active.status,threadId:_.active.threadId,annotationIds:_.active.annotationIds??[],provider:_.active.provider,model:_.active.model}:null,queueDepth:_.depth,recentRuns:fe.recentRuns,recentAppliedRuns:fe.recentAppliedRuns,actionableProposalCounts:fe.actionableProposalCounts,actionableProposals:le},memory:se,imprint:be,recentJobsRetentionMs:un,recentJobs:Fe})}async function Tt(c,S){let O=await new Promise(T=>{let C="";c.on("data",P=>{C+=P.toString()}),c.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 Go(c){let S=await ge.load();N(c,200,{ok:!0,...S})}async function Wo(c,S){let O=await Ne(c);if(!Xs(O.theme)){N(S,400,{error:"theme must be light, dark, or auto"});return}let T=await ge.setTheme(O.theme);N(S,200,{ok:!0,exists:!0,preferences:T})}async function mn(c,S){let T=new URL(c.url||"/",`http://127.0.0.1:${I}`).searchParams.get("jobId"),C=T?R.allActive.filter(U=>U.id===T):R.allActive,P=T?_.allActive.filter(U=>U.id===T):_.allActive,B=[...C.map(U=>U.threadId),...P.map(U=>U.threadId)].filter(Boolean),D=T?R.cancelJob(T):R.cancelActive(),z=T?_.cancelJob(T):_.cancelActive(),F=!!(D||z);for(let U of B)await v.appendMessage(U,{role:"assistant",timestamp:Date.now(),jobId:T||z?.id||"",cancelled:!0});N(S,200,{cancelled:F})}async function Oe(c){let S=pt().slice(0,8),O=c.threadId,T=!O;O||(O=(await v.createThread(`thread-${pt()}`,[])).id,xt.set(O,"project_model")),T&&await v.appendMessage(O,{role:"human",timestamp:Date.now(),jobId:S,feedbackSummary:c.reason}),await v.appendMessage(O,{role:"assistant",timestamp:Date.now(),jobId:S,responseText:T?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:c.model,provider:c.provider});let C={id:S,status:"queued",createdAt:Date.now(),provider:c.provider,model:c.model,agentSettings:c.agentSettings,threadId:O,annotationIds:c.annotationIds,sourceId:c.sourceId,standalone:T},P=_.enqueue(C);return{jobId:S,position:P,threadId:O}}async function Le(c,S){let O=decodeURIComponent(c),T=await ue.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 ht(c,S,O){let T=decodeURIComponent(c),C=[];for await(let V of S)C.push(typeof V=="string"?Buffer.from(V):V);let P;try{P=JSON.parse(Buffer.concat(C).toString("utf-8"))}catch{N(O,400,{error:"Invalid JSON"});return}let B=(P.changes??[]).flatMap(V=>{if(!Array.isArray(V.path)||V.path.length===0)return[];let fe=V.path.filter(se=>typeof se=="string"||typeof se=="number");if(fe.length!==V.path.length)return[];let le=Array.isArray(V.decisionIds)?V.decisionIds.filter(se=>typeof se=="string"):void 0;return[{path:fe,value:V.value,remove:V.remove===!0,decisionIds:le}]});if(B.length===0){N(O,400,{error:"No selected model changes"});return}let D=(P.changeSummaries??[]).flatMap(V=>{if(!V||typeof V!="object")return[];let fe=Array.isArray(V.path)?V.path.filter(le=>typeof le=="string"||typeof le=="number"):void 0;return Array.isArray(V.path)&&fe?.length!==V.path.length?[]:[{group:typeof V.group=="string"?V.group:void 0,label:typeof V.label=="string"?V.label:void 0,detail:typeof V.detail=="string"?V.detail:void 0,path:fe,value:V.value,currentValue:V.currentValue}]}),z=await ue.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 F=z.decisionIds.map(V=>{let fe=z.changes?.filter(Z=>Z.decisionIds.includes(V)).length??0,le=B.filter(Z=>Z.decisionIds?.includes(V)).length,se=le===0?"unprojected":fe>le?"partially_projected":"projected";return{decisionId:V,status:se}}),U=await q.applyModelProjection({runId:z.runId??z.id,presentationJobId:z.presentationJobId,decisionIds:z.decisionIds,changes:B.map(V=>({path:V.path,value:V.value,decisionIds:V.decisionIds})),coverage:F}),me=await ue.applySelectedModelProposal(T,B,D);if(!me){N(O,404,{error:"Model proposal not found"});return}if(me.threadId){let V=ln(P.provider),fe=typeof P.model=="string"&&P.model?P.model:void 0;await v.appendMessage(me.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${me.id}`,responseText:"",provider:V,model:fe})}N(O,200,{proposal:me,projection:U})}async function Nt(c,S,O){let T=decodeURIComponent(c),{provider:C,model:P}=await kt(S),B=await ue.dismissModelProposal(T);if(!B){N(O,404,{error:"Model proposal not found"});return}B.threadId&&await v.appendMessage(B.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${B.id}`,responseText:"",provider:C,model:P}),N(O,200,{proposal:B})}async function kt(c){try{let S=[];for await(let T of c)S.push(typeof T=="string"?Buffer.from(T):T);if(S.length===0)return{};let O=JSON.parse(Buffer.concat(S).toString());return{provider:ln(typeof O.provider=="string"?O.provider:void 0),model:typeof O.model=="string"&&O.model?O.model:void 0,agentSettings:qt(O)}}catch{return{}}}async function Ko(c){let S=xt.get(c);if(S)return S;let C=(await v.getThread(c))?.messages.find(P=>P.role==="human")?.feedbackSummary??"";if(C.startsWith("Synthesize rules"))return xt.set(c,"synthesize"),"synthesize";if(C.startsWith("Materialize model")||C.startsWith("Project model"))return xt.set(c,"project_model"),"project_model"}async function Kn(c,S){let O=[];for await(let z of c)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=[];p.claude?.available&&p.claude.mcp&&!p.claude.mcp.found&&C.push(await ys(T)),p.codex?.available&&p.codex.mcp&&!p.codex.mcp.found&&C.push(await Is(T)),p.copilot?.available&&p.copilot.mcp&&!p.copilot.mcp.found&&C.push(await ws(T,p.copilot.path??k));let[P,B,D]=await Promise.all([kr(r),Rr(r),Pr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=P),p.codex&&(p.codex.mcp=B),p.copilot&&(p.copilot.mcp=D),N(S,200,{results:C,capabilities:{providers:p}})}async function ua(c,S){if(!c||c.includes("/")||c.includes("\\")||c.includes("..")){N(S,400,{error:"Invalid filename"});return}try{let O=[Ye(d,c),Ye(r,".popmelt","artifacts","thread-media",c),Ye(r,".popmelt","artifacts","eval-screenshots",c),Ye(r,".popmelt","evals","screenshots",c),Ye(r,".popmelt","screenshots",c)],T;for(let B of O)try{T=await tp(B);break}catch{}if(!T)throw new Error("File not found");let C=c.split(".").pop()?.toLowerCase(),P=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":P,"Cache-Control":"public, max-age=3600"}),S.end(T)}catch{N(S,404,{error:"File not found"})}}function fn(c){return`/files/${Uo(c)}`}async function ma(c,S){let O=await v.getThread(c);if(!O){N(S,404,{error:"Thread not found"});return}let T=O.messages.filter(F=>F.role==="assistant"&&F.responseText?.includes("Model suggestion ready")),C=await(T.length>0?ue.findModelProposalsByThread(c):Promise.resolve([])),P=await Promise.all(C.map(async(F,U)=>{if(F.authorityStatus==="accepted")return F;let me=(await Promise.all(F.decisionIds.map(V=>q.findPendingProposalForLegacyDecision(V)))).find(Boolean);return{...F,authorityStatus:"legacy_untrusted",presentationJobId:F.presentationJobId??T[U]?.jobId??T.at(-1)?.jobId,underlyingProposalId:me?.proposalId,underlyingClaim:me?.claim}})),B=[...P].sort((F,U)=>U.updatedAt-F.updatedAt)[0]??null,D=O.elementIdentifiers.some(F=>F.startsWith("codex-session:"))?await q.findPendingProposalsForThread(c):[],z=O.messages.map(({screenshotPath:F,screenshotPaths:U,imagePaths:me,attachmentFiles:V,replyImagePaths:fe,...le})=>({...le,...F?{screenshotUrl:fn(F)}:{},...U?{screenshotUrls:Object.fromEntries(Object.entries(U).map(([se,Z])=>[se,fn(Z)]))}:{},...me?{imageUrls:Object.fromEntries(Object.entries(me).map(([se,Z])=>[se,Z.map(fn)]))}:{},...V?{attachments:Object.fromEntries(Object.entries(V).map(([se,Z])=>[se,Z.map(({path:re,...be})=>({...be,url:fn(re)}))]))}:{},...fe?{replyImageUrls:fe.map(fn)}:{}}));N(S,200,{id:O.id,createdAt:O.createdAt,messages:z,modelProposal:B,modelProposals:P,decisionCandidates:D})}async function Kr(c,S){let O=decodeURIComponent(c);if(!await v.archiveThread(O)){N(S,404,{archived:!1,error:"Thread not found"});return}N(S,200,{archived:!0})}let Vr=9,Hr=!1;for(let c=t;c<t+Vr;c++)try{await jp(St,c),I=c,Hr=!0,console.log(`[\u22B9 is watching :${I}]`);break}catch(S){if(S.code==="EADDRINUSE"){let O=await pn(c);if(Jn(O,{projectId:i,version:st,restartMode:y}))return console.log(`[\u22B9 already watching :${c}]`),{port:c,projectId:i,close:async()=>{}};continue}throw S}if(!Hr)throw new Error(`[Bridge] All ports ${t}\u2013${t+Vr-1} in use`);for(let[c,S]of Object.entries(p))!S.available||!S.path||m(c,S.path).then(O=>{if(O)console.log(`[Bridge] ${c} warmed up`);else{console.warn(`[Bridge] ${c} warm-up failed \u2014 marking unavailable`),S.available=!1,S.path=null;for(let T of ee)Wn(T,{type:"capabilities_changed",data:{}})}});let fa=setInterval(()=>{ra(d).catch(()=>{}),J.sweep().catch(()=>{})},up),Qr=setInterval(()=>{X.expireStale().becameEmpty&&Q()},fp);return Qr.unref?.(),{port:I,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(fa),clearInterval(Qr),W(),X.clear(),await J.cleanupPartials(),await R.destroyAsync(),_.destroy();for(let c of ee)try{c.res.end()}catch{}return ee.clear(),new Promise(c=>{St.close(()=>c()),St.closeAllConnections?.()})}}}async function ra(o){try{let e=await np(o),t=Date.now();for(let n of e){let r=Ye(o,n);try{let i=await rp(r);t-i.mtimeMs>mp&&await ip(r)}catch{}}}catch{}}import{randomUUID as Mp}from"crypto";var Ep=5e3,_p=250;function Gr(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function da(o,e=fetch){let t=`${process.pid}-${Mp()}`,n=`http://127.0.0.1:${o.port}`,r=!1,i=!1,s=async()=>(await e(`${n}/leases`,{method:"POST",headers:Gr(o),body:JSON.stringify({leaseId:t,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(w){return console.warn("[popmelt] failed to register bridge lease:",w instanceof Error?w.message:String(w)),null}let a=async()=>{if(!(r||i)){i=!0;try{(await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"PATCH",headers:Gr(o)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{a()},Ep);return d.unref?.(),{id:t,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"DELETE",headers:Gr(o),keepalive:!0})}catch{}}}}}function ca(o,e=process){let t=!1,n=new Map,r=()=>{if(!t){t=!0;for(let[i,s]of n)e.removeListener(i,s);n.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let a=e.listenerCount(i),d=o.release();if(a>0)return;let l=new Promise(w=>{setTimeout(w,_p)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};n.set(i,s),e.prependOnceListener(i,s)}return r}var Fp=1111,la=3e4,Up=8e3;async function zp(o){return Jp(o).catch(()=>o)}async function pa(o,e){let n=(await Bp(e,"utf8").catch(()=>"")).slice(-Up).trim();return new Error(n?`${o}
207
207
  Bridge log (${e}):
208
- ${n}`:o)}async function bh(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let t=await Dp(o);if(o.manageLease===!1)return t;let n=await Ks({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let r=Hs(n);return{...t,close:async()=>{r(),await n.release()}}}let e=await Vs(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Dp(o){let e=o.port??Cp,t=await Op(o.projectRoot??process.cwd()),n=Nt(t),r=await Ao(t);for(let y=e;y<e+10;y++){let k=await ln(y);if(k&&k.projectId===n){if(k.version&&k.version!==st){if(k.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${y}/shutdown`,{method:"POST"})}catch{}await new Promise(g=>setTimeout(g,500));break}continue}if(!Dn(k,{projectId:n,version:st,restartMode:"detached"}))continue;let T=o.devOrigin;if(T&&k.devOrigin!==T)try{await fetch(`http://127.0.0.1:${y}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:T})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(y),process.env.POPMELT_PROJECT_ID=n,{port:y,projectId:n,storeId:r.storeId,close:async()=>{}}}}let i=Nr(Ep(_p(import.meta.url)),"bridge-entry.mjs"),s=Nr(t,".popmelt"),a=Nr(s,"bridge.log");await Ap(s,{recursive:!0}),await Pp(a,`
208
+ ${n}`:o)}async function Eh(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let t=await Gp(o);if(o.manageLease===!1)return t;let n=await da({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let r=ca(n);return{...t,close:async()=>{r(),await n.release()}}}let e=await aa(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Gp(o){let e=o.port??Fp,t=await zp(o.projectRoot??process.cwd()),n=Jt(t),r=await Do(t);for(let g=e;g<e+10;g++){let k=await pn(g);if(k&&k.projectId===n){if(k.version&&k.version!==st){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(!Jn(k,{projectId:n,version:st,restartMode:"detached"}))continue;let x=o.devOrigin;if(x&&k.devOrigin!==x)try{await fetch(`http://127.0.0.1:${g}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:x})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=n,{port:g,projectId:n,storeId:r.storeId,close:async()=>{}}}}let i=Wr(qp(Lp(import.meta.url)),"bridge-entry.mjs"),s=Wr(t,".popmelt"),a=Wr(s,"bridge.log");await Np(s,{recursive:!0}),await Dp(a,`
209
209
  [${new Date().toISOString()}] Starting detached bridge
210
- `);let d=Rp(a,"a"),l;try{l=Tp(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{kp(d)}let v=null;l.once("error",y=>{v=`spawn error: ${y.message}`}),l.once("exit",(y,k)=>{v=`child exited before becoming healthy (${k?`signal ${k}`:`code ${y??"unknown"}`})`}),l.unref();let S=Date.now()+Qs;for(;Date.now()<S;){if(await new Promise(y=>setTimeout(y,100)),v)throw await Xs(`[Bridge] Detached bridge ${v}`,a);for(let y=e;y<e+10;y++){let k=await ln(y);if(Dn(k,{projectId:n,version:st,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(y),process.env.POPMELT_PROJECT_ID=n,{port:y,projectId:n,storeId:r.storeId,close:async()=>{}}}}throw l.kill("SIGTERM"),await Xs(`[Bridge] Detached bridge failed to start within ${Qs/1e3}s (port ${e})`,a)}export{It as ImprintService,Lt as ImprintStore,Ft as formatImprintPrompt,Go as imprintExplanationRef,Ut as parseImprintDraft,fa as qualifyImprintRelation,bh as startPopmelt};
210
+ `);let d=Op(a,"a"),l;try{l=Cp(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{$p(d)}let w=null;l.once("error",g=>{w=`spawn error: ${g.message}`}),l.once("exit",(g,k)=>{w=`child exited before becoming healthy (${k?`signal ${k}`:`code ${g??"unknown"}`})`}),l.unref();let b=Date.now()+la;for(;Date.now()<b;){if(await new Promise(g=>setTimeout(g,100)),w)throw await pa(`[Bridge] Detached bridge ${w}`,a);for(let g=e;g<e+10;g++){let k=await pn(g);if(Jn(k,{projectId:n,version:st,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(g),process.env.POPMELT_PROJECT_ID=n,{port:g,projectId:n,storeId:r.storeId,close:async()=>{}}}}throw l.kill("SIGTERM"),await pa(`[Bridge] Detached bridge failed to start within ${la/1e3}s (port ${e})`,a)}export{wt as ImprintService,Ut as ImprintStore,Gt as formatImprintPrompt,Ho as imprintExplanationRef,zt as parseImprintDraft,xa as qualifyImprintRelation,Eh as startPopmelt};