@popmelt.com/core 0.10.1 → 0.10.2

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,4 +1,4 @@
1
- import{spawn as lp}from"child_process";import{closeSync as pp,openSync as up}from"fs";import{appendFile as mp,mkdir as fp,readFile as hp,realpath as gp}from"fs/promises";import{dirname as yp,join as ji}from"path";import{fileURLToPath as Ip}from"url";import{execFileSync as El,spawn as ks}from"child_process";import{randomUUID as ct}from"crypto";import{mkdir as _l,readFile as Rs,readdir as Cl,realpath as $l,stat as Ol,unlink as Dl,writeFile as Ao}from"fs/promises";import{createServer as Nl}from"http";import{tmpdir as Bl}from"os";import{basename as jo,dirname as Jl,isAbsolute as Cs,join as Be,relative as Ll,resolve as ql}from"path";import{fileURLToPath as Ul}from"url";function Oi(o,e){return`<!DOCTYPE html>
1
+ import{spawn as jp}from"child_process";import{closeSync as Ap,openSync as Ep}from"fs";import{appendFile as _p,mkdir as Cp,readFile as $p,realpath as Op}from"fs/promises";import{dirname as Dp,join as Cr}from"path";import{fileURLToPath as Np}from"url";import{execFileSync as Ql,spawn as Ds}from"child_process";import{randomUUID as lt}from"crypto";import{mkdir as Xl,readFile as Ns,readdir as Yl,realpath as Zl,stat as ep,unlink as tp,writeFile as Eo}from"fs/promises";import{createServer as np}from"http";import{tmpdir as op}from"os";import{basename as _o,dirname as rp,isAbsolute as Us,join as Le,relative as ip,resolve as sp}from"path";import{fileURLToPath as ap}from"url";function Jr(o,e){return`<!DOCTYPE html>
2
2
  <html>
3
3
  <head>
4
4
  <meta charset="utf-8">
@@ -28,34 +28,36 @@ import{spawn as lp}from"child_process";import{closeSync as pp,openSync as up}fro
28
28
  });
29
29
  </script>
30
30
  </body>
31
- </html>`}import{createHash as xa,randomUUID as Sa}from"crypto";import{isAbsolute as Ta,relative as Pa}from"path";function _t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function an(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(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:n,outcomes:t}}function Ct(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
32
- `)}async function dn(o,e,t,n){let i=Ct(e);if(!(!i&&t.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:t,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(c=>[c.decisionId,c.state])),d=new Map(r.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(c=>({...c,implementation:s.get(c.id)??"unknown",verification:d.get(c.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){n?.(r);return}}function cn(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,i)=>["",`${i+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,` - 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,i)=>["",`${i+1}. ${n.claim}`," - 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.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
33
- `)}import{randomUUID as rt}from"crypto";function Bo(o,e){return{storeId:o,explanationId:e}}function ta(o,e){let{fromId:t,toId:n,...i}=e;return{...i,from:Bo(o,t),to:Bo(o,n)}}var Di={project:0,route:1,component:2,selector:2,file:3},Ni={intention:0,principle:1,pattern:2};function $t(o,e){let t=Di[o.scope.kind]-Di[e.scope.kind];return t!==0?t:Ni[o.kind]-Ni[e.kind]}function Bi(o){return o==="expresses"||o==="excepts"}function na(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(r=>r.id===e.fromId),n=o.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let i=$t(t,n);return i===0?void 0:i>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function xt(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let i=na(o,n);if(!i)return[];let r=`${i.type}:${i.fromId}:${i.toId}`;return t.has(r)?[]:(t.add(r),[i])}),e}import{createHash as oa}from"crypto";import{mkdir as ia,open as ra,readFile as Ji,readdir as sa,rename as aa,unlink as da}from"fs/promises";import{dirname as ca,join as Ot}from"path";function De(o){return structuredClone(o)}function Li(o){return oa("sha256").update(JSON.stringify(o)).digest("hex")}async function St(o,e){await ia(ca(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)}
34
- `,"utf8"),await n.sync()}finally{await n.close()}try{await aa(t,o)}catch(i){throw await da(t).catch(()=>{}),i}}function la(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function pa(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=De(e):o.explanations.push(De(e))}function $n(o,e){let t=De(o);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(i=>i.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(De(n.explanation))}else if(n.op==="replace_explanation")pa(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(i=>i.id!==n.explanationId),t.relations=t.relations.filter(i=>i.fromId!==n.explanationId&&i.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(i=>i.id===n.concrete.id)||t.concrete.push(De(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(i=>i.id!==n.concreteId),t.relations=t.relations.filter(i=>i.fromId!==n.concreteId&&i.toId!==n.concreteId);else if(n.op==="add_evidence"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);i.evidence.some(r=>r.id===n.evidence.id)||(i.evidence.push(De(n.evidence)),i.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(i,De(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let i=n.relation,r=t.explanations.find(l=>l.id===i.fromId),s=t.explanations.find(l=>l.id===i.toId),d=t.concrete.some(l=>l.id===i.fromId),c=t.concrete.some(l=>l.id===i.toId);if(Bi(i.type)){if(!(i.type==="expresses"?!!((r||d)&&s):!!(r&&s)))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(t.relations.some(w=>w.type===i.type&&w.fromId===i.fromId&&w.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toId}`);if(i.type==="expresses"&&r&&s){if($t(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let w=new Map;for(let k of t.relations)k.type==="expresses"&&w.set(k.fromId,[...w.get(k.fromId)??[],k.toId]);let R=[i.toId],b=new Set;for(;R.length;){let k=R.pop();if(k===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);b.has(k)||(b.add(k),R.push(...w.get(k)??[]))}}}else if(!r||!s&&!c)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);t.relations.some(l=>l.id===i.id)||t.relations.push(De(i))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(i=>i.id!==n.relationId));return t}function ua(o,e){let t=[],n=De(o);for(let i of e){if(i.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===i.explanationId);r&&t.unshift({op:"add_explanation",explanation:De(r)})}else if(i.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===i.concreteId);r&&t.unshift({op:"add_concrete",concrete:De(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=n.explanations.find(d=>d.id===r);s&&t.unshift({op:"replace_explanation",explanation:De(s)})}else if(i.op==="add_relation")t.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=n.relations.find(s=>s.id===i.relationId);r&&t.unshift({op:"add_relation",relation:De(r)})}n=$n(n,[i])}return t}function qi(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Dt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Ji(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 sa(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),i=la(this.projectId,e.createdAt),r=[],s=null;for(let d=0;d<n.length;d++){let c=JSON.parse(await Ji(Ot(this.journalDir,n[d]),"utf8")),{hash:l,...w}=c;if(c.sequence!==d+1||c.previousHash!==s||l!==Li(w))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);i=$n(i,c.mutations),i.updatedAt=c.committedAt,i.head={sequence:c.sequence,hash:c.hash},r.push(c),s=c.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:xt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=xt(t.graph),i=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let d=i.get(s.id);d&&d.type===s.type&&d.fromId===s.fromId&&d.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),d&&r.push({op:"add_relation",relation:d}))}if(r.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:r}),{migrated:!0,relationMutations:r.length}}return await St(this.graphPath,n),await St(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(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=n.graph.head.sequence+1,r=ua(n.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:De(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...s,hash:Li(s)},c=$n(n.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:i,hash:d.hash};let l=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await St(Ot(this.journalDir,l),d);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await St(this.graphPath,c),await St(this.manifestPath,w),t={graph:c,transaction:d}}),await this.writeChain,t}async undo(e,t,n,i){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(s.mutations.flatMap(qi));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>qi(w).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await St(this.graphPath,e.graph),await St(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 ma=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),fa=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"]),ha=[/\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],ga=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Lo(o){return!!(o&&ga.test(o))}function ya(o){return o.scope.kind==="project"||Lo(`${o.statement} ${o.rationale}`)}function Ia(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 va(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function wa(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 it(o){return new Set(va(o).split(" ").filter(e=>e.length>2&&!fa.has(e)).flatMap(wa))}function Ui(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 ba(o){if(o)for(let e of ha){let t=e.exec(o);if(!t||t.index<=0)continue;let n=Ui(o.slice(0,t.index)),i=Ui(o.slice(t.index+t[0].length));if(n&&i)return{target:n,reference:i}}}function mt(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 Jo(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 ft(o,e,t){return{id:rt(),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 we(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Fi(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 zi(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 i=Number(n);if(!Number.isInteger(i)||i<0||i>=t.length)return{found:!1};t=t[i]}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 Bt(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(),i=t.at(-1)?.[1],r,s=[];if(i)r=i;else{let c=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!c)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(c);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;r=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let d=typeof r=="string"?JSON.parse(r):r;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("imprint assessment is invalid");if(d.decision==="none"){let f=String(d.reason);if(!ma.has(f))throw new Error("imprint no-op reason is invalid");if(f==="task_specific_detail"&&s.some(E=>{if(!E||typeof E!="object"||Array.isArray(E))return!1;let D=E;return(D.finalScope??D.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(d.usedExplanationIds)?d.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],v=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...g])].some(E=>!v.has(E)))throw new Error("imprint use must cite only surfaced explanations");let M=[...new Set([...p,...e.applicationOccurred?[]:g])],h=e.applicationOccurred?g:[],m;if(h.length){m=h;let E=new Set(e.context?.pendingGroundingExplanationIds??[]),D=h.filter(T=>{let C=e.context?.explanations.find(z=>z.id===T);return v.has(T)&&C&&(C.state==="emerging"||C.state==="testing")&&!E.has(T)});if(D.length){let T=d.grounding,C=typeof T?.explanationId=="string"&&D.includes(T.explanationId)?T.explanationId:D[0],z=we(T?.question,300);return{draft:{decision:"apply",summary:{title:we(d.summary?.title,120)||"Applied shared understanding",detail:we(d.summary?.detail,500)||we(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:h,grounding:{explanationId:C,question:z||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(f==="duplicate"){let E=we(d.duplicateOfExplanationId,100),D=d.scopeComparison;if(!E)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 T=e.context?.explanations.find(C=>C.id===E);if(!T)throw new Error("duplicate assessment must cite a surfaced explanation");if(Lo(e.requestText)&&!ya(T))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:E,scopeComparison:D,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}if(d.decision==="recognize"){let f=we(d.explanationId,100);if(!f)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(u=>u.id===f);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let g=d.summary,v={title:we(g?.title,120),detail:we(g?.detail,500)};if(!v.title||!v.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:v},visibleText:n}}if(d.decision==="apply"){let f=d.summary,p={title:we(f?.title,120),detail:we(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let v=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!v.has(E)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(g)]},visibleText:n};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(E=>{let D=v.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!u.has(E)});if(!M.length){if(g.every(D=>v.get(D)?.state==="grounded"||u.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let h=d.grounding,m=typeof h?.explanationId=="string"&&M.includes(h.explanationId)?h.explanationId:M[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:g,grounding:{explanationId:m,question:we(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(d.decision!==void 0&&d.decision!=="mutate")throw new Error("imprint decision is invalid");let c=d.summary,l=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let w={kind:l,title:we(c?.title,120),detail:we(c?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let R=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],b=[];for(let f of Array.isArray(d.mutations)?d.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let g=we(p.statement),v=we(p.rationale);if(!g||!v)continue;b.push({op:"add",clientId:we(p.clientId,100)||void 0,kind:p.kind,statement:g,rationale:v,scope:Fi(p.scope),rootReason:we(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let g={op:"revise",explanationId:p.explanationId,statement:we(p.statement)||void 0,rationale:we(p.rationale)||void 0,scope:Fi(p.scope),reopenGrounding:p.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&b.push(g)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let g=we(p.summary);g&&b.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:g})}else if(p.op==="relation"&&typeof p.fromId=="string"&&typeof p.toId=="string"&&["expresses","excepts"].includes(String(p.type))){let g=we(p.rationale);if(!g)continue;b.push({op:"relation",type:p.type,fromId:p.fromId,toId:p.toId,rationale:g})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let g=we(p.reason);g&&b.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:g})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let g=we(p.modelPath,300);g&&b.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:g,rationale:we(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&b.push({op:"retire",explanationId:p.explanationId,reason:we(p.reason)})}let k=d.grounding,S=k&&typeof k.explanationId=="string"&&we(k.question)?{explanationId:k.explanationId,question:we(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:R,mutations:b,grounding:S},visibleText:n}}catch(d){return{visibleText:n,error:d instanceof Error?d.message:String(d)}}}function Jt(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),i=new Set(o?.correctionExplanationIds??[]),r=Lo(e.requestText),s=o?.retrievalIntent,d=o?.historicalCaveats??[];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((c,l)=>[`${l+1}. [${c.state}; ${c.kind}] ${c.statement}`,` - Why: ${c.rationale}`,` - Scope: ${c.scope.kind} ${c.scope.values.join(", ")}`,` - Explanation: ${c.id}`,...n.has(c.id)?[" - Grounding: already pending; do not ask again"]:[],...i.has(c.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...c.concrete.map(w=>` - Concrete terminal: ${w.modelPath} = ${JSON.stringify(w.value)}`)].join(`
35
- `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(c=>`- ${c.fromId} --${c.type}--> ${c.toId}: ${c.rationale}`)]:[],...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."]:[],...d.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...d.map((c,l)=>[`${l+1}. [challenged; ${c.kind}] ${c.statement}`,` - Why it was previously proposed: ${c.rationale}`,` - Scope: ${c.scope.kind} ${c.scope.values.join(", ")}`,` - Historical explanation: ${c.id}`].join(`
36
- `)),"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."]:[],"","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.",...r?["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","fromId":"<specific id or clientId>","toId":"<abstract rule id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact 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(`
37
- `)}var Nt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Dt(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 contextualize(e){let t=it(e.text??""),n=it((e.subjectHints??[]).join(" ")),i=ba(e.text),r=it(i?.target??""),s=it(i?.reference??""),d=new Set(e.pendingGroundingExplanationIds??[]),c=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!d.size&&!c.size)return;let{graph:l}=await this.store.load(),w=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||c.has(h.id))).map(h=>{let m=it([h.statement,h.rationale].join(" ")),E=it(h.scope.values.join(" ")),D=mt(m,t),T=mt(E,t),C=mt(E,n),z=mt(m,n),X=D+T*.2+C*.25+z*.75+(h.state==="grounded"?.08:0)+(d.has(h.id)?1:0)+(c.has(h.id)?1:0),G=d.has(h.id)||c.has(h.id)||D>=.12||T>=.5||C>=.2||z>=.2;return{item:h,score:X,relevant:G}}).filter(h=>h.relevant&&h.score>=.18).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)),R=Math.max(1,e.maxExplanations??6),b=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=mt(it(`${m.statement} ${m.rationale}`),h),D=mt(it(m.scope.values.join(" ")),h);return{item:m,score:E+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,E)=>E.score-m.score||E.item.updatedAt.localeCompare(m.item.updatedAt)),k=[],S=h=>{k.length<R&&!k.some(m=>m.id===h.id)&&k.push(h)};if(i&&(b(r).slice(0,2).forEach(({item:h})=>S(h)),b(s).slice(0,2).forEach(({item:h})=>S(h))),w.forEach(({item:h})=>S(h)),!k.length)return;let f=new Set(k.map(h=>h.id)),p=new Set(l.relations.flatMap(h=>f.has(h.fromId)?[h.toId]:f.has(h.toId)?[h.fromId]:[])),g=new Set(l.explanations.flatMap(h=>p.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),v=l.explanations.filter(h=>g.has(h.id)&&!f.has(h.id)).sort((h,m)=>m.updatedAt.localeCompare(h.updatedAt)).slice(0,4),u=[...k,...v];for(let h of v)f.add(h.id);let M=i?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=it(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),E=mt(m,r),D=mt(m,s);return{item:h,score:E+D,targetScore:E,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:u.map(h=>{let m=new Set(l.relations.filter(E=>E.toId===h.id&&E.type==="expresses").map(E=>E.fromId));return{id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state,concrete:l.concrete.filter(E=>m.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:w.length>k.length||v.length<g.size,...i?{retrievalIntent:i}:{},...M.length?{historicalCaveats:M}:{},...d.size?{pendingGroundingExplanationIds:[...d]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:l.relations.filter(h=>f.has(h.fromId)&&f.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:[],i=t.applicationOccurred?n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...i])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),d=await this.store.load(),c=new Map(d.graph.explanations.map(x=>[x.id,x])),l=new Map,w=new Map,R=[],b=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),S=new Set(n.flatMap(x=>x.op==="revise"&&n.some(Q=>Q.op==="evidence"&&Q.stance==="challenges"&&Q.explanationId===x.explanationId)?[x.explanationId]:[])),f=new Set(n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),p=x=>c.has(x)||f.has(x),g=new Set;for(let x of n)x.op==="relation"&&x.fromId!==x.toId&&p(x.fromId)&&p(x.toId)?(g.add(x.fromId),g.add(x.toId)):x.op==="supersede"&&x.explanationId!==x.replacementId&&p(x.explanationId)&&p(x.replacementId)?(g.add(x.explanationId),g.add(x.replacementId)):x.op==="bind_concrete"&&p(x.explanationId)&&zi(t.concreteModel,x.modelPath).found&&g.add(x.explanationId);let v=d.graph.explanations.length===0;for(let x of n){if(x.op!=="add")continue;let Q=!!(x.clientId&&g.has(x.clientId)),L=!!x.rootReason?.trim()||v;if(!Q&&!L)continue;v&&(v=!1);let K=rt();x.clientId&&l.set(x.clientId,K);let H=x.clientId?r.includes(x.clientId):!1,B={id:K,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:Jo(x.scope),state:H?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,B),b.add(K),R.push({op:"add_explanation",explanation:B})}let u=x=>l.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let Q=u(x.explanationId),L=c.get(Q);if(L?.state!=="grounded")continue;let K=rt(),H={id:K,kind:L.kind,statement:x.statement??L.statement,rationale:x.rationale??L.rationale,scope:x.scope?Jo(x.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,H),w.set(Q,K),b.add(K),R.push({op:"add_explanation",explanation:H});let B=$t(L,H);B!==0&&R.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:B>0?Q:K,toId:B>0?K:Q,rationale:x.rationale??e.summary.detail,createdAt:s}})}let M=x=>{let Q=u(x);return w.get(Q)??Q};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let L=M(x.explanationId);if(!c.has(L))continue;let K=zi(t.concreteModel,x.modelPath);if(!K.found)continue;let H=d.graph.concrete.find(B=>B.modelPath===x.modelPath&&JSON.stringify(B.value)===JSON.stringify(K.value));H||(H={id:rt(),modelPath:x.modelPath,value:structuredClone(K.value),createdAt:s,updatedAt:s},R.push({op:"add_concrete",concrete:H})),R.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:H.id,toId:L,rationale:x.rationale,createdAt:s}}),b.add(L);continue}if(x.op==="relation"){let L=M(x.fromId),K=M(x.toId);if(!c.has(L)||!c.has(K)||L===K)continue;x.type==="expresses"&&$t(c.get(L),c.get(K))<0&&([L,K]=[K,L]),R.push({op:"add_relation",relation:{id:rt(),type:x.type,fromId:L,toId:K,rationale:x.rationale,createdAt:s}}),b.add(L),b.add(K);continue}if(x.op==="supersede"){let L=M(x.explanationId),K=M(x.replacementId);if(!c.has(L)||!c.has(K)||L===K)continue;R.push({op:"add_evidence",explanationId:L,evidence:ft(t,"challenges",x.reason)}),R.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:K},updatedAt:s}),b.add(L),b.add(K);continue}let Q=M(x.explanationId);if(c.has(Q))if(b.add(Q),x.op==="revise"){if(w.has(u(x.explanationId)))continue;let L=c.get(Q);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let K={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Jo(x.scope)}:{},...x.reopenGrounding||S.has(x.explanationId)?{state:"testing"}:{}};R.push({op:"revise_explanation",explanationId:Q,patch:K,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&S.has(x.explanationId))continue;R.push({op:"add_evidence",explanationId:Q,evidence:ft(t,x.stance,x.summary)}),x.stance==="challenges"&&R.push({op:"revise_explanation",explanationId:Q,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(R.push({op:"add_evidence",explanationId:Q,evidence:ft(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),R.push({op:"revise_explanation",explanationId:Q,patch:{state:"retired"},updatedAt:s}))}for(let x of r){let Q=M(x),L=c.get(Q);!L||L.state==="grounded"||L.state==="retired"||k.has(Q)&&!b.has(Q)||(b.has(Q)||(b.add(Q),R.push({op:"add_evidence",explanationId:Q,evidence:{...ft(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&R.push({op:"revise_explanation",explanationId:Q,patch:{state:"testing"},updatedAt:s}))}let h=new Set(d.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toId}`)),m=R.filter(x=>{if(x.op!=="add_relation")return!0;let Q=`${x.relation.type}:${x.relation.fromId}:${x.relation.toId}`;return h.has(Q)?!1:(h.add(Q),!0)});if(!m.length)return;let E=rt(),D=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:m}),T=new Map(D.graph.explanations.map(x=>[x.id,x])),C=[...b].flatMap(x=>{let Q=T.get(x);if(!Q)return[];let L=!d.graph.explanations.some(H=>H.id===x),K=Q.state==="challenged"||Q.state==="retired";return[{explanationId:x,action:L?"added":K?"challenged":"revised",statement:Q.statement,state:Q.state}]}),z=r.map(M).find(x=>T.get(x)?.state==="testing"&&!k.has(x)),X=e.grounding?M(e.grounding.explanationId):z,G=X?T.get(X):void 0,Y=G?.state==="testing"&&!k.has(G.id)?{explanationId:G.id,question:e.grounding?.question||Ia(G),state:"testing"}:void 0;return{transactionId:E,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:C,...Y?{grounding:Y}:{}}}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 r=(await this.store.load()).graph.explanations.find(l=>l.id===n);if(!r||r.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},d=[],c="";if(e.action==="yes"?(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),c=`Grounded: ${r.statement}`):e.action==="this_time"&&(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),c=`Observed this time: ${r.statement}`),!d.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:rt(),committedAt:t,source:s,summary:c,mutations:d}),"applied"}};var Tt=1,qo="bridge";function Wi(o){return`codex-session:${o}`}function ka(o,e){return`codex-${xa("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function Hi(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 Ra(o,e){let t=new Set,n=r=>{if(typeof r!="string"||!r.trim())return;let s=r.trim();t.add(Ta(s)?Pa(e,s):s)},i=(r,s="",d=0)=>{if(!(d>5||r===null||r===void 0)){if(typeof r=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&n(r),s==="command")for(let c of r.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(c[1]);return}if(Array.isArray(r)){r.forEach(c=>i(c,s,d+1));return}if(typeof r=="object")for(let[c,l]of Object.entries(r))i(l,c,d+1)}};for(let r of o)i(r.toolInput);return[...t]}function On(o){return o?Math.ceil(o.length/4):0}function Gi(o,e,t,n,i,r){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(`
38
- `),d=cn(n),c=Vi(i,r),l=[s,d,c].filter(Boolean).join(`
39
- `);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:On(s),memoryEstimatedTokens:On(d),imprintEstimatedTokens:On(c),totalEstimatedTokens:On(l)}}}function Vi(o,e){return o?Jt(o,{requestText:e}).split(`
40
- `).map(t=>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(`
31
+ </html>`}import{createHash as Md,randomUUID as jd}from"crypto";import{isAbsolute as Ad,relative as Ed}from"path";function $t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function cn(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}}function Ot(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
32
+ `)}async function Bn(o,e,t,n){let r=Ot(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(c=>[c.decisionId,c.state])),a=new Map(i.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:i.source,...i.actionPacket.decisions.length>0?{acceptedTruth:{decisions:i.actionPacket.decisions.map(c=>({...c,implementation:s.get(c.id)??"unknown",verification:a.get(c.id)??"unverified"})),conflicts:i.actionPacket.conflicts,truncated:i.actionPacket.completeness.status==="truncated"}}:{},packets:i.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:i.reviewSelection.completeness.status==="truncated",estimatedTokens:i.actionPacket.budget.estimatedTokens+i.reviewSelection.completeness.estimatedTokens}}catch(i){n?.(i);return}}function ln(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(`
33
+ `)}import{randomUUID as st}from"crypto";function qo(o,e){return{storeId:o,explanationId:e}}function pa(o,e){let{fromId:t,toId:n,toStoreId:r,...i}=e;return{...i,from:qo(o,t),to:qo(r??o,n)}}var Lr={project:0,route:1,component:2,selector:2,file:3},qr={intention:0,principle:1,pattern:2};function Dt(o,e){let t=Lr[o.scope.kind]-Lr[e.scope.kind];return t!==0?t:qr[o.kind]-qr[e.kind]}function Fr(o){return o==="expresses"||o==="excepts"}function ua(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=Dt(t,n);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function Tt(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let r=ua(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 ma}from"crypto";import{mkdir as fa,open as ha,readFile as Ur,readdir as ga,rename as ya,unlink as Ia}from"fs/promises";import{dirname as wa,join as Nt}from"path";function Be(o){return structuredClone(o)}function zr(o){return ma("sha256").update(JSON.stringify(o)).digest("hex")}async function Pt(o,e){await fa(wa(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await ha(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
34
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await ya(t,o)}catch(r){throw await Ia(t).catch(()=>{}),r}}function va(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function ba(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=Be(e):o.explanations.push(Be(e))}function Jn(o,e){let t=Be(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(Be(n.explanation))}else if(n.op==="replace_explanation")ba(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(Be(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(Be(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,Be(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let r=n.relation,i=t.explanations.find(b=>b.id===r.fromId),s=!!r.toStoreId,a=s?void 0:t.explanations.find(b=>b.id===r.toId),c=t.concrete.some(b=>b.id===r.fromId),l=!s&&t.concrete.some(b=>b.id===r.toId);if(Fr(r.type)){if(!(r.type==="expresses"?s?!!i:!!((i||c)&&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(Dt(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(b=>b.id===r.id)||t.relations.push(Be(r))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==n.relationId));return t}function xa(o,e){let t=[],n=Be(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:Be(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:Be(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:Be(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:Be(i)})}n=Jn(n,[r])}return t}function Vr(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 Bt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Nt(e,".popmelt","imprint"),this.manifestPath=Nt(this.imprintDir,"manifest.json"),this.graphPath=Nt(this.imprintDir,"graph.json"),this.journalDir=Nt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await Ur(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 ga(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=va(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<n.length;a++){let c=JSON.parse(await Ur(Nt(this.journalDir,n[a]),"utf8")),{hash:l,...b}=c;if(c.sequence!==a+1||c.previousHash!==s||l!==zr(b))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=Jn(r,c.mutations),r.updatedAt=c.committedAt,r.head={sequence:c.sequence,hash:c.hash},i.push(c),s=c.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:Tt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=Tt(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 Pt(this.graphPath,n),await Pt(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=xa(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:Be(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:zr(s)},c=Jn(n.graph,a.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:a.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Pt(Nt(this.journalDir,l),a);let b={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await Pt(this.graphPath,c),await Pt(this.manifestPath,b),t={graph:c,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(Vr));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(b=>Vr(b).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 Pt(this.graphPath,e.graph),await Pt(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 Sa=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Ta=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"]),Pa=[/\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],Ra=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Uo(o){return!!(o&&Ra.test(o))}function ka(o){return o.scope.kind==="project"||Uo(`${o.statement} ${o.rationale}`)}function Ma(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 ja(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Aa(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 it(o){return new Set(ja(o).split(" ").filter(e=>e.length>2&&!Ta.has(e)).flatMap(Aa))}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 Ea(o){if(o)for(let e of Pa){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 ft(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 Fo(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 ht(o,e,t){return{id:st(),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 Wr(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 Gr(o,e,t){if(o&&typeof o=="object"&&!Array.isArray(o)){let i=o,s=ve(i.explanationId,100),a=ve(i.storeId,100);return s?{explanationId:s,...a?{storeId:a}:{}}:void 0}let n=ve(e,100),r=ve(t,100);return n?{explanationId:n,...r?{storeId:r}:{}}:void 0}function Kr(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 Jt(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 c=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!c)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(c);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let b=l;i=b.imprint,s=Array.isArray(b.annotations)?b.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(!Sa.has(h))throw new Error("imprint no-op reason is invalid");if(h==="task_specific_detail"&&s.some(E=>{if(!E||typeof E!="object"||Array.isArray(E))return!1;let D=E;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(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],I=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...u,...g])].some(E=>!I.has(E)))throw new Error("imprint use must cite only surfaced explanations");let j=[...new Set([...u,...e.applicationOccurred?[]:g])],f=e.applicationOccurred?g:[],m;if(f.length){m=f;let E=new Set(e.context?.pendingGroundingExplanationIds??[]),D=f.filter(P=>{let O=e.context?.explanations.find(W=>W.id===P);return I.has(P)&&O&&(O.state==="emerging"||O.state==="testing")&&!E.has(P)});if(D.length){let P=a.grounding,O=typeof P?.explanationId=="string"&&D.includes(P.explanationId)?P.explanationId:D[0],W=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:f,grounding:{explanationId:O,question:W||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(h==="duplicate"){let E=ve(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!E)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(O=>O.id===E);if(!P)throw new Error("duplicate assessment must cite a surfaced explanation");if(Uo(e.requestText)&&!ka(P))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:h,duplicateOfExplanationId:E,scopeComparison:D,...j.length?{usedExplanationIds:j}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:h,...j.length?{usedExplanationIds:j}:{},...m?{appliedExplanationIds:m}:{}},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 g=a.summary,I={title:ve(g?.title,120),detail:ve(g?.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 g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let I=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!I.has(E)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(g)]},visibleText:n};let p=new Set(e.context?.pendingGroundingExplanationIds??[]),j=g.filter(E=>{let D=I.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!p.has(E)});if(!j.length){if(g.every(D=>I.get(D)?.state==="grounded"||p.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let f=a.grounding,m=typeof f?.explanationId=="string"&&j.includes(f.explanationId)?f.explanationId:j[0];return{draft:{decision:"apply",summary:u,appliedExplanationIds:g,grounding:{explanationId:m,question:ve(f?.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 c=a.summary,l=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let b={kind:l,title:ve(c?.title,120),detail:ve(c?.detail,500)};if(!b.title||!b.detail)throw new Error("summary title and detail are required");let S=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(h=>typeof h=="string"&&!!h.trim()):[],y=[];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 g=ve(u.statement),I=ve(u.rationale);if(!g||!I)continue;y.push({op:"add",clientId:ve(u.clientId,100)||void 0,kind:u.kind,statement:g,rationale:I,scope:Wr(u.scope),rootReason:ve(u.rootReason,300)||void 0})}else if(u.op==="revise"&&typeof u.explanationId=="string"){let g={op:"revise",explanationId:u.explanationId,statement:ve(u.statement)||void 0,rationale:ve(u.rationale)||void 0,scope:Wr(u.scope),reopenGrounding:u.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&y.push(g)}else if(u.op==="evidence"&&typeof u.explanationId=="string"&&["supports","challenges","excepts"].includes(String(u.stance))){let g=ve(u.summary);g&&y.push({op:"evidence",explanationId:u.explanationId,stance:u.stance,summary:g})}else if(u.op==="relation"&&["expresses","excepts"].includes(String(u.type))){let g=ve(u.rationale),I=Gr(u.from,u.fromId,u.fromStoreId),p=Gr(u.to,u.toId,u.toStoreId);if(!g||!I||!p)continue;y.push({op:"relation",type:u.type,from:I,to:p,rationale:g})}else if(u.op==="supersede"&&typeof u.explanationId=="string"&&typeof u.replacementId=="string"){let g=ve(u.reason);g&&y.push({op:"supersede",explanationId:u.explanationId,replacementId:u.replacementId,reason:g})}else if(u.op==="bind_concrete"&&typeof u.explanationId=="string"){let g=ve(u.modelPath,300);g&&y.push({op:"bind_concrete",explanationId:u.explanationId,modelPath:g,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:b,appliedExplanationIds:S,mutations:y,grounding:T},visibleText:n}}catch(a){return{visibleText:n,error:a instanceof Error?a.message:String(a)}}}function Lt(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),r=new Set(o?.correctionExplanationIds??[]),i=Uo(e.requestText),s=o?.retrievalIntent,a=o?.historicalCaveats??[],c=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},b=!!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(`
35
+ `)),...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||b?["","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":"${c??"<writable-primary-store>"}","explanationId":"<specific-local-id-or-clientId>"},"to":{"storeId":"<mounted-target-store>","explanationId":"<abstract-target-id>"},"rationale":"<why>"}.`]:[],...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(`
36
+ `)),"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":{"explanationId":"<specific local id or clientId>"},"to":{"explanationId":"<abstract local id or clientId>"},"rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact 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(`
37
+ `)}var gt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Bt(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=it(e.text??""),n=it((e.subjectHints??[]).join(" ")),r=Ea(e.text),i=it(r?.target??""),s=it(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),c=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!a.size&&!c.size)return;let l=await this.contextualGraph(),b=l.explanations.filter(f=>f.state!=="retired"&&(f.state!=="challenged"||c.has(f.id))).map(f=>{let m=it([f.statement,f.rationale].join(" ")),E=it(f.scope.values.join(" ")),D=ft(m,t),P=ft(E,t),O=ft(E,n),W=ft(m,n),K=D+P*.2+O*.25+W*.75+(f.state==="grounded"?.08:0)+(a.has(f.id)?1:0)+(c.has(f.id)?1:0),_=a.has(f.id)||c.has(f.id)||D>=.12||P>=.5||O>=.2||W>=.2;return{item:f,score:K,relevant:_}}).filter(f=>f.relevant&&f.score>=.18).sort((f,m)=>m.score-f.score||m.item.updatedAt.localeCompare(f.item.updatedAt)),S=Math.max(1,e.maxExplanations??6),y=f=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=ft(it(`${m.statement} ${m.rationale}`),f),D=ft(it(m.scope.values.join(" ")),f);return{item:m,score:E+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,E)=>E.score-m.score||E.item.updatedAt.localeCompare(m.item.updatedAt)),k=[],T=f=>{k.length<S&&!k.some(m=>m.id===f.id)&&k.push(f)};if(r&&(y(i).slice(0,2).forEach(({item:f})=>T(f)),y(s).slice(0,2).forEach(({item:f})=>T(f))),b.forEach(({item:f})=>T(f)),!k.length)return;let h=new Set(k.map(f=>f.id)),u=new Set(l.relations.flatMap(f=>f.toStoreId?[]:h.has(f.fromId)?[f.toId]:h.has(f.toId)?[f.fromId]:[])),g=new Set(l.explanations.flatMap(f=>u.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),I=l.explanations.filter(f=>g.has(f.id)&&!h.has(f.id)).sort((f,m)=>m.updatedAt.localeCompare(f.updatedAt)).slice(0,4),p=[...k,...I];for(let f of I)h.add(f.id);let j=r?l.explanations.filter(f=>f.state==="challenged").map(f=>{let m=it(`${f.statement} ${f.rationale} ${f.scope.values.join(" ")}`),E=ft(m,i),D=ft(m,s);return{item:f,score:E+D,targetScore:E,referenceScore:D}}).filter(f=>f.targetScore>=.12&&f.referenceScore>=.12).sort((f,m)=>m.score-f.score||m.item.updatedAt.localeCompare(f.item.updatedAt)).slice(0,3).map(({item:f})=>({id:f.id,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:f.scope,state:f.state})):[];return{explanations:p.map(f=>{let m=new Set(l.relations.filter(E=>!E.toStoreId&&E.toId===f.id&&E.type==="expresses").map(E=>E.fromId));return{id:f.id,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:f.scope,state:f.state,concrete:l.concrete.filter(E=>m.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:b.length>k.length||I.length<g.size,...r?{retrievalIntent:r}:{},...j.length?{historicalCaveats:j}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:l.relations.filter(f=>!f.toStoreId&&h.has(f.fromId)&&h.has(f.toId)).map(f=>({id:f.id,type:f.type,fromId:f.fromId,toId:f.toId,rationale:f.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(),c=new Map(a.graph.explanations.map(x=>[x.id,x])),l=new Map,b=new Map,S=[],y=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),T=new Set(n.flatMap(x=>x.op==="revise"&&n.some($=>$.op==="evidence"&&$.stance==="challenges"&&$.explanationId===x.explanationId)?[x.explanationId]:[])),h=new Set(n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),u=t.storeId?.trim(),g=x=>c.has(x)||h.has(x),I=new Map((t.context?.explanations??[]).flatMap(x=>x.storeId?[[`${x.storeId}:${x.id}`,x]]:[])),p=x=>x.storeId??u,j=x=>{let $=p(x.from),L=p(x.to);return u&&$!==u||!u&&(x.from.storeId||x.to.storeId)||!g(x.from.explanationId)?!1:!L||L===u?g(x.to.explanationId):!!I.get(`${L}:${x.to.explanationId}`)?.memoryId},f=new Set;for(let x of n)x.op==="relation"&&(p(x.from)!==p(x.to)||x.from.explanationId!==x.to.explanationId)&&j(x)?(f.add(x.from.explanationId),p(x.to)===u&&f.add(x.to.explanationId)):x.op==="supersede"&&x.explanationId!==x.replacementId&&g(x.explanationId)&&g(x.replacementId)?(f.add(x.explanationId),f.add(x.replacementId)):x.op==="bind_concrete"&&g(x.explanationId)&&Kr(t.concreteModel,x.modelPath).found&&f.add(x.explanationId);let m=a.graph.explanations.length===0;for(let x of n){if(x.op!=="add")continue;let $=!!(x.clientId&&f.has(x.clientId)),L=!!x.rootReason?.trim()||m;if(!$&&!L)continue;m&&(m=!1);let B=st();x.clientId&&l.set(x.clientId,B);let Q=x.clientId?i.includes(x.clientId):!1,he={id:B,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:Fo(x.scope),state:Q?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ht(t,"supports",e.summary.detail)]};c.set(B,he),y.add(B),S.push({op:"add_explanation",explanation:he})}let E=x=>l.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let $=E(x.explanationId),L=c.get($);if(L?.state!=="grounded")continue;let B=st(),Q={id:B,kind:L.kind,statement:x.statement??L.statement,rationale:x.rationale??L.rationale,scope:x.scope?Fo(x.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ht(t,"supports",e.summary.detail)]};c.set(B,Q),b.set($,B),y.add(B),S.push({op:"add_explanation",explanation:Q});let he=Dt(L,Q);he!==0&&S.push({op:"add_relation",relation:{id:st(),type:"expresses",fromId:he>0?$:B,toId:he>0?B:$,rationale:x.rationale??e.summary.detail,createdAt:s}})}let D=x=>{let $=E(x);return b.get($)??$};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let L=D(x.explanationId);if(!c.has(L))continue;let B=Kr(t.concreteModel,x.modelPath);if(!B.found)continue;let Q=a.graph.concrete.find(he=>he.modelPath===x.modelPath&&JSON.stringify(he.value)===JSON.stringify(B.value));Q||(Q={id:st(),modelPath:x.modelPath,value:structuredClone(B.value),createdAt:s,updatedAt:s},S.push({op:"add_concrete",concrete:Q})),S.push({op:"add_relation",relation:{id:st(),type:"expresses",fromId:Q.id,toId:L,rationale:x.rationale,createdAt:s}}),y.add(L);continue}if(x.op==="relation"){if(!j(x))continue;let L=p(x.from),B=p(x.to);if(u&&L!==u)continue;let Q=D(x.from.explanationId),he=B===u?D(x.to.explanationId):x.to.explanationId,_e=c.get(Q),se=B===u?c.get(he):I.get(`${B}:${he}`);if(!_e||!se||B===u&&Q===he)continue;if(x.type==="expresses"&&Dt(_e,se)<0){if(B!==u)continue;[Q,he]=[he,Q]}S.push({op:"add_relation",relation:{id:st(),type:x.type,fromId:Q,...B&&B!==u?{toStoreId:B}:{},toId:he,rationale:x.rationale,createdAt:s}}),y.add(Q),B===u&&y.add(he);continue}if(x.op==="supersede"){let L=D(x.explanationId),B=D(x.replacementId);if(!c.has(L)||!c.has(B)||L===B)continue;S.push({op:"add_evidence",explanationId:L,evidence:ht(t,"challenges",x.reason)}),S.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:B},updatedAt:s}),y.add(L),y.add(B);continue}let $=D(x.explanationId);if(c.has($))if(y.add($),x.op==="revise"){if(b.has(E(x.explanationId)))continue;let L=c.get($);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let B={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Fo(x.scope)}:{},...x.reopenGrounding||T.has(x.explanationId)?{state:"testing"}:{}};S.push({op:"revise_explanation",explanationId:$,patch:B,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&T.has(x.explanationId))continue;S.push({op:"add_evidence",explanationId:$,evidence:ht(t,x.stance,x.summary)}),x.stance==="challenges"&&S.push({op:"revise_explanation",explanationId:$,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(S.push({op:"add_evidence",explanationId:$,evidence:ht(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),S.push({op:"revise_explanation",explanationId:$,patch:{state:"retired"},updatedAt:s}))}for(let x of i){let $=D(x),L=c.get($);!L||L.state==="grounded"||L.state==="retired"||k.has($)&&!y.has($)||(y.has($)||(y.add($),S.push({op:"add_evidence",explanationId:$,evidence:{...ht(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&S.push({op:"revise_explanation",explanationId:$,patch:{state:"testing"},updatedAt:s}))}let P=new Set(a.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toStoreId??""}:${x.toId}`)),O=S.filter(x=>{if(x.op!=="add_relation")return!0;let $=`${x.relation.type}:${x.relation.fromId}:${x.relation.toStoreId??""}:${x.relation.toId}`;return P.has($)?!1:(P.add($),!0)});if(!O.length)return;let W=st(),K=await this.store.commit({transactionId:W,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:O}),_=new Map(K.graph.explanations.map(x=>[x.id,x])),H=[...y].flatMap(x=>{let $=_.get(x);if(!$)return[];let L=!a.graph.explanations.some(Q=>Q.id===x),B=$.state==="challenged"||$.state==="retired";return[{explanationId:x,action:L?"added":B?"challenged":"revised",statement:$.statement,state:$.state}]}),G=i.map(D).find(x=>_.get(x)?.state==="testing"&&!k.has(x)),fe=e.grounding?D(e.grounding.explanationId):G,X=fe?_.get(fe):void 0,oe=X?.state==="testing"&&!k.has(X.id)?{explanationId:X.id,question:e.grounding?.question||Ma(X),state:"testing"}:void 0;return{transactionId:W,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:H,...oe?{grounding:oe}:{}}}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=[],c="";if(e.action==="yes"?(a.push({op:"add_evidence",explanationId:n,evidence:{...ht(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}),c=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:n,evidence:{...ht(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}),c=`Observed this time: ${i.statement}`),!a.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:st(),committedAt:t,source:s,summary:c,mutations:a}),"applied"}};import{mkdir as ci,readFile as hn,writeFile as li}from"fs/promises";import{join as zt}from"path";var _a=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 Ln(o){return new Set(zo(o).split(" ").filter(e=>e.length>2&&!_a.has(e)))}function Qr(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 Ca(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 $a(o,e){let t=new Map,n=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(zo).filter(Boolean),i=Ln([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 c of Ca(s)){let l=zo(c.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:c.by,score:k})}let S=["/","#","[","]","="].some(y=>c.value.includes(y))?0:Math.round(Qr(Ln(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 Oa(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 Da(o){return Math.ceil(JSON.stringify(o).length/4)}function Vo(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 g=[...o.events].reverse().find(I=>I.entity.entityType==="proposal"&&I.entity.entityId===u.id&&I.toState==="deferred"&&I.transitionContext?.kind==="proposal_deferral")?.transitionContext;return g?g.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||g.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||g.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||g.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||g.resurfaceWhen.includes("after_date")&&!!(g.revisitAfter&&Date.parse(n)>=Date.parse(g.revisitAfter)):!1}),s=o.records.filter(u=>u.recordType==="implementation_attempt"),a=$a(t,e),c=[...a.values()].sort((u,g)=>g.score-u.score),l=Ln([e.action,e.text].filter(Boolean).join(" ")),b=i.flatMap(u=>{let g=u.subjects.map(f=>a.get(f.subjectId)).filter(f=>!!f),I=Math.max(0,...g.map(f=>f.score)),p=Math.round(Qr(Ln(u.claim),l)*35),j=I+p;return j>=50?[{proposal:u,proposalMatches:g,score:j}]:[]}).sort((u,g)=>g.score-u.score||u.proposal.id.localeCompare(g.proposal.id)),S=Math.max(1,e.maxPackets??3),y=Math.max(200,e.maxEstimatedTokens??1200),k=[],T=0;for(let u of b){if(k.length>=S)break;let g=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(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:u.proposalMatches.map(({score:j,...f})=>f)},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:Oa(u.proposal,s),evidence:{sourceCount:u.proposal.sourceRefs.length,sourceRefs:g},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:u.proposal.id},...g]},p={...I,estimatedTokens:Da(I)};if(T+p.estimatedTokens>y)break;k.push(p),T+=p.estimatedTokens}let h=Math.max(0,b.length-k.length);return{packets:k,subjectMatches:c.map(({score:u,...g})=>g),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:b.length,omittedPacketCount:h,maxEstimatedTokens:y,estimatedTokens:T},uncertainty:a.size===0?"subject_unresolved":b.length===0?"no_relevant_pending_proposal":void 0}}var Na=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 qn(o){return new Set(Ho(o).split(" ").filter(e=>e.length>2&&!Na.has(e)))}function Xr(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 Ba(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Ho).filter(Boolean),r=qn([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,c=[{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 c){let b=Ho(l.value);for(let k of n){let T=b===k?95:b.includes(k)||k.includes(b)?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(Xr(qn(b),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 Ja(o){return Math.ceil(JSON.stringify(o).length/4)}function qt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function La(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 qa(o,e,t){let n=e.filter(a=>a.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((a,c)=>c.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 Yr(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,c=o.records.filter(m=>m.recordType==="implementation_attempt"),l=o.records.filter(m=>m.recordType==="verification_attempt"),b=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=Ba(r,e),T=new Map(k.map(m=>[m.subjectId,m.score])),h=qn([e.action,e.text].filter(Boolean).join(" ")),u=a.flatMap(m=>{let E=Math.max(0,...m.subjects.map(O=>T.get(O.subjectId)??0)),D=Math.round(Xr(qn(m.claim),h)*35),P=E+D;return P>=50?[{decision:m,score:P}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of u.slice(0,n))g.set(m.decision.id,m.decision);for(let m of o.relationships){if(!qt(m,"excepts")&&!qt(m,"contradicts"))continue;let E=s.find(P=>P.id===m.from.entityId),D=s.find(P=>P.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<n&&g.set(E.id,E),g.size<n&&g.set(D.id,D))}let I=[...g.values()],p=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&g.has(m.from.entityId)&&g.has(m.to.entityId),j=(m,E=!1)=>{let D=new Set(m.map($=>$.id)),P=b.filter($=>$.target.entityType==="decision"&&D.has($.target.entityId)),O=new Set(o.relationships.filter($=>qt($,"excepts")&&D.has($.from.entityId)&&D.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),K=o.relationships.filter($=>qt($,"contradicts")&&D.has($.from.entityId)&&D.has($.to.entityId)).map($=>({id:$.id,decisionIds:[$.from.entityId,$.to.entityId],unresolvedQuestion:$.reason,expansionRefs:[{kind:"record",id:$.id}]})),_=new Set(K.flatMap($=>$.decisionIds)),H=S.filter($=>$.sourceRefs.some(L=>L.kind==="record"&&D.has(L.id))||o.relationships.some(L=>L.relationshipType==="supports"&&L.from.entityType==="evidence"&&L.from.entityId===$.id&&L.to.entityType==="decision"&&D.has(L.to.entityId))),G=Math.max(0,u.length-m.length),fe=o.relationships.some($=>qt($,"contradicts")&&p($)&&(!D.has($.from.entityId)||!D.has($.to.entityId))),X=E||G>0||fe,oe=[];k.length===0&&(e.subjectHints?.length??0)>0?oe.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):m.length===0&&oe.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&oe.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap($=>$.expansionRefs)}),H.some($=>$.availability!=="available")&&oe.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:H.map($=>({kind:"record",id:$.id}))}),X&&oe.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:$,...L})=>L),modelEntries:y.filter($=>$.decisionIds.some(L=>D.has(L))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),decisions:m.map($=>({id:$.id,kind:$.kind,claim:$.claim,subjectIds:$.subjects.map(L=>L.subjectId),authority:$.authority,effectiveState:_.has($.id)?"conflicted":O.has($.id)?"excepted":"active",freshness:P.filter(L=>L.target.entityId===$.id).map(L=>L.signalType),expansionRef:{kind:"record",id:$.id}})),conflicts:K,uncertainties:oe,implementation:m.map($=>La($.id,c)),verification:m.map($=>qa($.id,l,P)),evidence:H.map($=>({evidenceId:$.id,summary:$.summary,availability:$.availability,sourceRefs:$.sourceRefs})),completeness:{status:X?"truncated":"complete",omittedDecisionCount:G,omittedEvidenceCount:0,conflictsComplete:!fe}};return x.budget.estimatedTokens=Ja(x),x},f=j(I);for(;f.budget.estimatedTokens>t&&I.length>0;){let m=I.pop(),E=o.relationships.filter(D=>qt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);I=I.filter(D=>!E.includes(D.id)),f=j(I,!0)}return f}var Fa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Ft(o){return Fa.test(o)}function Ua(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function te(o,e,t,n){o.push({path:e,code:t,message:n,severity:"error"})}function Wo(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Ee(o,e,t){Ft(t)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Ke(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Rt(o,e,t,n=!1){n&&t.level==="contributor"&&te(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&te(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var za={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"])},Va=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Ha(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),Ke(o,`${t}.createdAt`,e.createdAt),Rt(o,`${t}.authority`,e.authority);let n=za[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(r)&&te(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(Va.has(i)&&(Rt(o,`${t}.authority`,e.authority,!0),e.reason?.trim()||te(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)&&te(o,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(o,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Ke(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Wa(o,e,t,n){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),Ke(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&te(o,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(o,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(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)&&te(o,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Rt(o,`${t}.authority`,e.authority,!0),e.claim.trim()||te(o,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Wo(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())&&te(o,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Ke(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&te(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&te(o,`${t}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Ke(o,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),Ke(o,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Ke(o,`${t}.appliedAt`,e.appliedAt),Rt(o,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&te(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())&&te(o,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&te(o,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Wo(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Wo(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ga(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()&&te(o,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&te(o,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),Ke(o,`${t}.createdAt`,e.createdAt),e.reason.trim()||te(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&&te(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?te(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Rt(o,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(o,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(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))&&te(o,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(o,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function kt(o){let e=[];Ee(e,"manifest.projectId",o.manifest.projectId),Ke(e,"manifest.createdAt",o.manifest.createdAt),Ke(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(h,u)=>{let g=t.get(h);g?te(e,u,"duplicate_id",`ID is already used at ${g}.`):t.set(h,u)};o.records.forEach((h,u)=>{let g=`records[${u}]`;n(h.id,g),Wa(e,h,g,o.manifest.projectId)}),o.events.forEach((h,u)=>{let g=`events[${u}]`;n(h.id,g),Ha(e,h,g),h.projectId!==o.manifest.projectId&&te(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((h,u)=>{let g=`relationships[${u}]`;n(h.id,g),Ga(e,h,g),h.projectId!==o.manifest.projectId&&te(e,`${g}.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 g=`tombstones[${u}]`;n(h.id,g),Ee(e,`${g}.id`,h.id),Ee(e,`${g}.objectId`,h.objectId),Ee(e,`${g}.deletedById`,h.deletedById),Ke(e,`${g}.deletedAt`,h.deletedAt),Rt(e,`${g}.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 g=`${h.entityType}:${h.entityId}`;!r.has(g)&&!i.has(g)&&te(e,u,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};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)),c=(h,u)=>{a.has(h)||te(e,u,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(h,u,g)=>{!r.has(`${h}:${u}`)&&!i.has(`${h}:${u}`)&&te(e,g,"dangling_entity_reference",`No ${h} record or tombstone exists.`)};o.records.forEach((h,u)=>{let g=`records[${u}]`;switch(h.recordType){case"authority_grant":l("participant",h.granteeId,`${g}.granteeId`),l("participant",h.grantedById,`${g}.grantedById`),h.subjectIds.forEach((I,p)=>l("subject",I,`${g}.subjectIds[${p}]`));break;case"observation":h.captureContext.subjectIds.forEach((I,p)=>l("subject",I,`${g}.captureContext.subjectIds[${p}]`)),h.captureContext.artifactIds.forEach((I,p)=>c(I,`${g}.captureContext.artifactIds[${p}]`));break;case"proposal":case"decision":h.subjects.forEach((I,p)=>l("subject",I.subjectId,`${g}.subjects[${p}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((I,p)=>c(I,`${g}.messageArtifactIds[${p}]`)),h.resultRefs.forEach((I,p)=>s(I,`${g}.resultRefs[${p}]`));break;case"iteration":h.threadIds.forEach((I,p)=>l("thread",I,`${g}.threadIds[${p}]`)),h.artifactIds.forEach((I,p)=>c(I,`${g}.artifactIds[${p}]`));break;case"evidence":h.artifactIds.forEach((I,p)=>c(I,`${g}.artifactIds[${p}]`));break;case"advisory_explanation":h.subjectIds.forEach((I,p)=>l("subject",I,`${g}.subjectIds[${p}]`)),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${g}.evidenceIds[${p}]`)),h.supersededById&&l("advisory_explanation",h.supersededById,`${g}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((I,p)=>l("iteration",I,`${g}.iterationIds[${p}]`)),h.coverageClaims.forEach((I,p)=>l("decision",I.decisionId,`${g}.coverageClaims[${p}].decisionId`)),h.artifactIds.forEach((I,p)=>c(I,`${g}.artifactIds[${p}]`));break;case"eval_spec":h.replacesSpecId&&l("eval_spec",h.replacesSpecId,`${g}.replacesSpecId`),h.decisionIds.forEach((I,p)=>l("decision",I,`${g}.decisionIds[${p}]`)),h.subjectIds.forEach((I,p)=>l("subject",I,`${g}.subjectIds[${p}]`)),(h.dependencies??[]).forEach((I,p)=>{I.kind==="subject"&&I.subjectId&&l("subject",I.subjectId,`${g}.dependencies[${p}].subjectId`)}),(h.scenarios??[]).forEach((I,p)=>{I.subjectIds?.forEach((j,f)=>l("subject",j,`${g}.scenarios[${p}].subjectIds[${f}]`))}),h.targets.forEach((I,p)=>l(I.entityType,I.entityId,`${g}.targets[${p}]`));break;case"verification_attempt":h.evalSpecId&&l("eval_spec",h.evalSpecId,`${g}.evalSpecId`),h.targets.forEach((I,p)=>l(I.entityType,I.entityId,`${g}.targets[${p}]`)),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${g}.evidenceIds[${p}]`));break;case"model_entry":h.subjectIds.forEach((I,p)=>l("subject",I,`${g}.subjectIds[${p}]`)),h.decisionIds.forEach((I,p)=>l("decision",I,`${g}.decisionIds[${p}]`));break;case"model_projection":Rt(e,`${g}.authority`,h.authority,!0),l("participant",h.appliedById,`${g}.appliedById`),h.decisionIds.forEach((I,p)=>l("decision",I,`${g}.decisionIds[${p}]`)),h.entryIds.forEach((I,p)=>l("model_entry",I,`${g}.entryIds[${p}]`)),h.coverage.forEach((I,p)=>l("decision",I.decisionId,`${g}.coverage[${p}].decisionId`));break;case"freshness_signal":s(h.target,`${g}.target`),h.evidenceIds.forEach((I,p)=>l("evidence",I,`${g}.evidenceIds[${p}]`));break;default:break}});let b=new Map(o.events.map(h=>[h.id,h])),S=new Map(o.records.map(h=>[`${h.recordType}:${h.id}`,h])),y=new Map;o.events.forEach((h,u)=>{let g=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,I=y.get(g)??new Set;I.add(h.toState),y.set(g,I),I.size>1&&te(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]]:[])),T=(h,u,g,I,p)=>{if(h.level!=="delegate"||!h.grantId)return;let j=k.get(h.grantId);if(!j){te(e,p,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==u||j.level!=="delegate")&&te(e,p,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let f=Date.parse(g);(f<Date.parse(j.startsAt)||j.endsAt&&f>Date.parse(j.endsAt)||j.revokedAt&&f>=Date.parse(j.revokedAt))&&te(e,p,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&I.length&&!I.every(m=>j.subjectIds.includes(m))&&te(e,p,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let h of o.records)h.recordType==="decision"&&T(h.authority,h.acceptedById,h.createdAt,h.subjects.map(u=>u.subjectId),`records:${h.id}.authority`);o.events.forEach((h,u)=>{let g=S.get(`${h.entity.entityType}:${h.entity.entityId}`),I=g&&"subjects"in g?g.subjects.map(p=>p.subjectId):[];T(h.authority,h.participantId,h.createdAt,I,`events[${u}].authority`)}),o.relationships.forEach((h,u)=>{if(!h.authority)return;let g=[h.from,h.to].flatMap(I=>{let p=S.get(`${I.entityType}:${I.entityId}`);return p&&"subjects"in p?p.subjects.map(j=>j.subjectId):[]});T(h.authority,h.participantId,h.createdAt,g,`relationships[${u}].authority`)});for(let h of o.records){if(h.recordType!=="decision")continue;let u=b.get(h.acceptanceEventId);(!u||u.entity.entityType!=="proposal"||u.entity.entityId!==h.proposalId||u.toState!=="accepted")&&te(e,`records:${h.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),u&&u.participantId!==h.acceptedById&&te(e,`records:${h.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),S.has(`proposal:${h.proposalId}`)||te(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)||te(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())||te(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(g=>g.recordType==="decision"&&g.proposalId===h.id)||te(e,`records:${h.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ua(e)}function pn(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 Zr(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 Ka(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 Fn(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."}),Ft(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Ka(e))Ft(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={...pn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Zr(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={...pn(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={...pn(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Zr(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,c],events:[s,a],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...pn(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={...pn(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 Qa}from"crypto";import{readFile as Xa,readdir as Ya,realpath as Za}from"fs/promises";import{join as un,relative as ed}from"path";var td=["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 Ut(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function ei(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,t,n){let i=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Qa("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 Go(o,e){try{return JSON.parse(await Xa(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function nd(o){let e=Ut(o);if(!e)return 0;let t=0,n=r=>{let i=Ut(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 od(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function mn(o){let e=[],t=await Za(o.projectRoot).catch(()=>o.projectRoot),n=un(t,".popmelt"),r=await Go(un(n,"threads.json"),e),i=await Go(un(n,"model.json"),e),s=Ut(r),a=Ut(s?.threads)??{},c=Object.entries(a).map(([L,B])=>({key:L,value:Ut(B)})).filter(L=>!!L.value),l=un(n,"decisions"),b=await Ya(l).catch(()=>[]),S=[];for(let L of b.filter(B=>B.endsWith(".json")).sort()){let B=Ut(await Go(un(l,L),e));B&&S.push({file:L,value:B})}let y=c.flatMap(({value:L})=>[L.createdAt,L.updatedAt]).filter(L=>typeof L=="number"&&Number.isFinite(L)),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 h=le(T,"project",T,k),u=le(T,"participant","legacy-owner",k),g=le(T,"participant","legacy-agent",k),I=le(T,"subject","project",k),p=ze(Math.max(k,...y)),j=[],f=[],m=new Map,E=new Map,D=new Map(S.map(L=>[L.value.id??L.file.replace(/^d-|\.json$/g,""),L.value])),P=new Map,O=(L,B,Q,he,_e)=>{let se=m.get(Q);if(se)return se;let Oe=le(T,"artifact",L,he);return f.push({id:Oe,kind:B,mediaType:_e,location:Q,availability:"available"}),m.set(Q,Oe),Oe};for(let{file:L,value:B}of S){let Q=B.id??L.replace(/^d-|\.json$/g,""),he=B.createdAt??k,_e=[O(`${Q}:envelope`,"other",`.popmelt/decisions/${L}`,he,"application/json")];B.screenshotPath&&_e.push(O(`${Q}:screenshot`,"screenshot",`.popmelt/${B.screenshotPath.replace(/^\.popmelt\//,"")}`,he,B.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[se,Oe]of(B.pastedImagePaths??[]).entries())_e.push(O(`${Q}:image:${se}`,"image",Oe,he));P.set(Q,_e)}let W=(L,B,Q)=>({id:L,schemaVersion:1,projectId:h,createdAt:p,participantId:B,sourceRefs:Q}),K=(L,B)=>{j.push(B);let Q=E.get(L)??[];Q.push(B.id),E.set(L,Q)},_=[{...W(u,u,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...W(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(..._),j.push({...W(I,u,[]),recordType:"subject",subjectType:"project",label:ed(process.cwd(),t)||t,aliases:[],locators:[{id:le(T,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:ze(k),sourceRefs:[]}]});let H=new Map,G=(L,B)=>{let Q=H.get(L);if(Q)return Q;let he=le(T,"subject",L,B),_e={...W(he,u,[{kind:"external",id:L}]),createdAt:ze(B),recordType:"subject",subjectType:"element",label:L,aliases:[],locators:[{id:le(T,"locator",L,B),kind:"dom_selector",value:L,status:"current",validFrom:ze(B),sourceRefs:[{kind:"external",id:L}]}]};return j.push(_e),H.set(L,he),he};for(let{key:L,value:B}of c){let Q=B.id??L,he=B.createdAt??k,_e=le(T,"thread",Q,he),se={kind:"thread",id:Q},Oe=[],It=[],sn=Array.isArray(B.messages)?B.messages:[],Me,ot,wt=0;sn.forEach((xe,pt)=>{let De=xe.timestamp??he,rt=le(T,"artifact",`${Q}:message:${pt}`,De);if(Oe.push(rt),f.push({id:rt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${Q}/messages/${pt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${Q}/messages/${pt}`,rt),xe.screenshotPath&&O(`${Q}:message:${pt}:screenshot`,"screenshot",xe.screenshotPath,De),xe.role==="human"){Me=xe;let qe=xe.feedbackSummary??xe.replyToQuestion;if(qe?.trim()){let Fe=le(T,"observation",`${Q}:${pt}`,De),Ye=B.elementIdentifiers??[],_t={...W(Fe,u,[se,{kind:"message",id:rt}]),createdAt:ze(De),recordType:"observation",state:"open",statement:qe,captureContext:{subjectIds:Ye.map(xt=>G(xt,he)),artifactIds:[rt]},resolvedByIds:[]};K(Q,_t),ot=Fe,It.push({entityType:"observation",entityId:Fe})}return}if(xe.role!=="assistant")return;let ut=xe.jobId??`${Q}:${pt}`,mt=le(T,"iteration",ut,De),bt=D.get(ut),Oo=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",Do={...W(mt,g,[se,{kind:"message",id:rt},...(P.get(ut)??[]).map(qe=>({kind:"artifact",id:qe}))]),createdAt:ze(De),recordType:"iteration",threadIds:[_e],startedAt:ze(Me?.timestamp,De),completedAt:ze(De),requestSummary:ei(Me?.feedbackSummary,Me?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:Oo,execution:{provider:xe.provider??bt?.provider,model:xe.model??bt?.model,sessionId:xe.sessionId??bt?.sessionId},artifactIds:[rt,...P.get(ut)??[]]};K(Q,Do),It.push({entityType:"iteration",entityId:mt});let an=xe.resolutions??bt?.resolutions??[];for(let[qe,Fe]of an.entries()){if(Fe.status!=="resolved"||!Fe.summary?.trim())continue;let Ye=B.elementIdentifiers??[],_t=(Ye.length?Ye:[t]).map(Dn=>({subjectId:Dn===t?I:G(Dn,he),role:"governed"})),xt=le(T,"proposal",`${ut}:${Fe.annotationId??"resolution"}:${qe}`,De),No={...W(xt,g,[se,{kind:"iteration",id:mt}]),createdAt:ze(De),recordType:"proposal",state:"pending",claim:Fe.summary,subjects:_t,subjectSemantics:_t.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:ei(Me?.feedbackSummary,Me?.replyToQuestion,Fe.summary),iterationId:mt,inferredById:g}};K(Q,No),It.push({entityType:"proposal",entityId:xt}),e.push({severity:"warning",code:"acceptance_unresolved",source:Q,message:`Proposal ${xt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(an.some(qe=>qe.status==="resolved")||bt?.gitDiff){let qe=le(T,"implementation",ut,De),Fe={...W(qe,g,[se,{kind:"iteration",id:mt}]),createdAt:ze(De),recordType:"implementation_attempt",state:"completed",iterationIds:[mt],coverageClaims:[],summary:an.map(Ye=>Ye.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(Q,Fe),It.push({entityType:"implementation_attempt",entityId:qe}),wt+=1}ot&&(ot=void 0)});let vt=sn.at(-1),On={...W(_e,u,[se]),createdAt:ze(he),recordType:"thread",state:vt?.question?"open":"resolved",messageArtifactIds:Oe,outcome:vt?.question?"question_unresolved":wt?"implementation_only":"no_outcome",resultRefs:It};j.push(On),E.set(Q,[_e,...E.get(Q)??[]])}let fe=nd(i);fe&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${fe} model values were not promoted because their accepted decision provenance is unresolved.`});let X={manifest:{formatVersion:1,projectId:h,createdAt:ze(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:f,tombstones:[]},oe=kt(X),$=(o.proofCaseIds??td).map(L=>({legacyId:L,threadFound:c.some(({key:B,value:Q})=>(Q.id??B)===L),decisionEnvelopeFound:D.has(L),recordIds:E.get(L)??[]}));return{bundle:X,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((L,B)=>L+(B.value.messages?.length??0),0),decisionEnvelopes:S.length,modelEntries:fe,artifactsReferenced:f.length},imported:od(j),unresolvedAcceptance:e.filter(L=>L.code==="acceptance_unresolved").length,deferredModelEntries:fe,proofCases:$,issues:e,schemaIssues:oe.issues}}}import{createHash as rd}from"crypto";import{mkdir as ti,open as Ko,readFile as Qo,readdir as id,rename as sd,unlink as Xo}from"fs/promises";import{join as at}from"path";var ad={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Un(o){return rd("sha256").update(JSON.stringify(o)).digest("hex")}function ni(o){return Un(o)}function oi(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 dd(o,e,t){return oi(structuredClone(o),e,t)}async function Mt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Ko(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
38
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await sd(t,o)}catch(r){throw await Xo(t).catch(()=>{}),r}}async function fn(o){return JSON.parse(await Qo(o,"utf8"))}var zn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=at(e,".popmelt","memory"),this.journalDir=at(this.memoryDir,"journal"),this.manifestPath=at(this.memoryDir,"manifest.json"),this.checkpointPath=at(this.memoryDir,"checkpoint.json"),this.lockPath=at(this.memoryDir,"writer.lock")}async readHead(){let e=await fn(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=kt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await ti(this.journalDir,{recursive:!0});try{throw await Qo(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 Qo(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=Un(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 Mt(this.checkpointPath,r),await Mt(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 Mt(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=Un(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 Mt(at(this.memoryDir,n),r),e.manifest.checkpoint={file:n,sequence:r.sequence,hash:t},await Mt(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(!Ft(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:ni(i)},a=dd(n.bundle,e,t.committedAt),c=kt(a);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await Mt(at(this.journalDir,l),s),n.manifest.head={sequence:r,hash:s.hash},n.manifest.updatedAt=t.committedAt,await Mt(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({...ad,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await fn(this.manifestPath),t=await fn(at(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!==Un(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await id(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),c=t.sequence,l=t.journalHash??null,b=new Set;for(let y of s){let k=await fn(at(this.journalDir,y)),{hash:T,...h}=k;if(T!==ni(h))throw new Error(`Journal hash mismatch: ${y}`);if(k.sequence!==c+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(b.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);oi(a,k.mutation,k.committedAt),c=k.sequence,l=k.hash,b.add(k.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let S=kt(a);if(!S.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(S.issues)}`);return{bundle:a,manifest:e,transactionIds:b,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:c,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await ti(this.memoryDir,{recursive:!0});let t;try{t=await Ko(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let r=await fn(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 Xo(this.lockPath),t=await Ko(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Xo(this.lockPath).catch(()=>{})}}};import{randomBytes as cd}from"crypto";function Se(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=cd(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 ld=()=>({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(),c=ld(),l=c.records,b=o.records.find(p=>p.recordType==="thread"&&p.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));b||(b={id:le(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(b));let S=[];for(let p of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(f=>f.recordType==="subject"&&f.locators.some(m=>m.value===p&&m.status==="current"));j||(j={id:le(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:le(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(f=>f.recordType==="subject"&&f.locators.some(m=>m.kind==="source_file"&&m.value===p&&m.status==="current"));j||(j={id:le(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:le(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=le(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=le(r,"live-iteration",i,e.completedAt),h={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:[b.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=[],g=e.resolutions.filter(p=>p.status==="resolved"&&p.summary.trim()),I=S.length>0?S:o.records.filter(p=>p.recordType==="subject"&&p.subjectType==="project").slice(0,1);if(y.length>0&&I.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[p,j]of y.entries()){let f=le(r,"live-proposal",`${i}:${p}`,e.completedAt),m=I.map(D=>({subjectId:D.id,role:"governed"})),E={id:f,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(E),u.push(f)}if(g.length>0){let p=new Set(e.governingDecisionIds??[]),j=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&p.has(m.id)),f={id:le(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: ${g.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:T}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};l.push(f)}return{mutation:c,iterationId:T,proposalIds:u,observationId:k}}import{createHash as pd}from"crypto";import{mkdir as ud,open as md,readFile as fd,rename as hd,unlink as gd}from"fs/promises";import{join as ii}from"path";function si(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ai(o){return pd("sha256").update(JSON.stringify(o)).digest("hex")}async function yd(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await md(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
39
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await hd(t,o)}catch(r){throw await gd(t).catch(()=>{}),r}}function Id(o,e,t=new Date().toISOString()){let n={},r={},i={},s=(c,l,b)=>{let S=c[l]??=[];S.includes(b)||S.push(b)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let b of[l.label,...l.aliases,...l.locators.filter(S=>S.status==="current").map(S=>S.value)]){let S=si(b);S&&s(n,S,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)s(r,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)s(i,l.subjectId,c.id);let a={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:ai(a)}}function di(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[si(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 Vn=class{constructor(e){this.indexDir=ii(e,".popmelt","memory","indexes"),this.indexPath=ii(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await fd(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===ai(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let n=Id(e,t);return await ud(this.indexDir,{recursive:!0}),await yd(this.indexPath,n),n}};var yn="popmelt:imprint",pi="popmelt:imprint-evidence",Vt="popmelt:imprint-relation";function gn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===yn)?.id}function Yo(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 Hn(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 Zo(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var Gt=class{constructor(e){this.projectRoot=e;this.store=new zn(e),this.indexStore=new Vn(e),this.manifestPath=zt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await hn(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 mn({...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 mn({...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=zt(this.projectRoot,".popmelt","memory","migrations"),t=zt(e,"imprint-advisories-v2.json");try{let p=JSON.parse(await hn(t,"utf8"));return{migrated:!1,explanations:p.explanations??0,evidence:p.evidence??0}}catch{}let n;try{n=Tt(JSON.parse(await hn(zt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await ci(e,{recursive:!0}),await li(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,c=r.bundle.records.find(p=>p.recordType==="subject"&&p.subjectType==="project");if(!a||!c)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,b=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===Vt?[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(f=>gn(f)===p.id);y.set(p.id,j?.id??le(l,"imprint-explanation",p.id,Date.parse(p.createdAt)))}let T=[],h=[],u=[],g=0;for(let p of n.explanations){let j=y.get(p.id),f=k.find(P=>P.id===j),m=[],E=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 E){let O=le(l,"imprint-evidence-record",P.id,Date.parse(P.createdAt));m.push(O),!b.has(O)&&(T.push({id:O,schemaVersion:1,projectId:l,createdAt:P.createdAt,participantId:a.id,sourceRefs:Yo([{kind:"external",id:P.id,uri:pi},{kind:"external",id:p.id,uri:yn},{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:le(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:pi}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:O},reason:"This advisory explanation was derived from collaboration evidence."}),g+=1)}let D={id:j,schemaVersion:1,projectId:l,createdAt:f?.createdAt??p.createdAt,participantId:f?.participantId??a.id,sourceRefs:Yo([...f?.sourceRefs??[],{kind:"external",id:p.id,uri:yn}]),recordType:"advisory_explanation",kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),subjectIds:[c.id],evidenceIds:[...new Set([...f?.evidenceIds??[],...m])],concreteBindings:Hn(n,p.id),supersededById:p.supersededBy?y.get(p.supersededBy):void 0,updatedAt:p.updatedAt};f?h.push(D):T.push(D)}for(let p of n.relations){let j=Zo(p.type);if(!j||p.toStoreId)continue;let f=y.get(p.fromId),m=y.get(p.toId);!f||!m||S.has(p.id)||u.push({id:le(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:Vt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:f},to:{entityType:"advisory_explanation",entityId:m},reason:p.rationale||"The Imprint graph connected these explanations."})}let I=new Date().toISOString();if(T.length||h.length||u.length)try{let p=await this.store.commit({records:T,recordReplacements:h,events:[],relationships:u,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(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 ci(e,{recursive:!0}),await li(t,JSON.stringify({version:2,migratedAt:I,explanations:n.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:g}}async review(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,selection:Vo(n.bundle,r)}}async contextualize(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:Yr(n.bundle,r),reviewSelection:Vo(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:gn(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:Fn(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 mn({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=Fn(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},c=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=Fn(t.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(y=>y.message).join(" ")};let b=await this.store.commitReviewPlan(l.plan,{transactionId:Se(i),committedAt:s});await this.refreshIndex(b);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:b.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=le(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=Tt(JSON.parse(await hn(zt(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 c=e.occurredAt??new Date().toISOString(),l=Date.parse(c),b=n.bundle.manifest.projectId,S=[],y=[],k=[],T=n.bundle.records.filter(I=>I.recordType==="advisory_explanation"),h=new Map(T.flatMap(I=>{let p=gn(I);return p?[[p,I.id]]:[]}));for(let I of e.summary.changes)if(!h.has(I.explanationId)){let p=t?.explanations.find(j=>j.id===I.explanationId);h.set(I.explanationId,le(b,"imprint-explanation",I.explanationId,Date.parse(p?.createdAt??c)))}for(let I of e.summary.changes){let p={kind:"external",id:I.explanationId,uri:yn},j=h.get(I.explanationId),f=T.find(P=>P.id===j),m=t?.explanations.find(P=>P.id===I.explanationId),E={id:le(b,"imprint-live-evidence",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,createdAt:c,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(E);let D={id:j,schemaVersion:1,projectId:b,createdAt:f?.createdAt??m?.createdAt??c,participantId:f?.participantId??s.id,sourceRefs:Yo([...f?.sourceRefs??[],p,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??f?.kind??"pattern",state:m?.state??I.state,statement:m?.statement??I.statement,rationale:m?.rationale??f?.rationale??e.summary.detail,scope:structuredClone(m?.scope??f?.scope??{kind:"project",values:[]}),subjectIds:f?.subjectIds??[a.id],evidenceIds:[...new Set([...f?.evidenceIds??[],E.id])],concreteBindings:m?Hn(t,I.explanationId):f?.concreteBindings??[],supersededById:m?.supersededBy?h.get(m.supersededBy):f?.supersededById,updatedAt:m?.updatedAt??c};f?y.push(D):S.push(D),k.push({id:le(b,"imprint-live-evidence-link",`${e.summary.transactionId}:${I.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:b,createdAt:c,participantId:s.id,sourceRefs:[p],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.id},to:{entityType:"evidence",entityId:E.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let u=new Set(n.bundle.relationships.flatMap(I=>I.sourceRefs.flatMap(p=>p.kind==="external"&&p.uri===Vt?[p.id]:[])));for(let I of t?.relations??[]){let p=Zo(I.type);if(!p)continue;let j=h.get(I.fromId),f=I.toStoreId?e.qualifiedExplanationMemoryIds?.[`${I.toStoreId}:${I.toId}`]:h.get(I.toId);!j||!f||u.has(I.id)||k.push({id:le(b,"imprint-relation",I.id,Date.parse(I.createdAt)),schemaVersion:1,projectId:b,createdAt:I.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:I.id,uri:Vt}],recordType:"relationship",relationshipType:p,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:f,...I.toStoreId?{storeId:I.toStoreId}:{}},reason:I.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let I=await this.store.commit({records:S,recordReplacements:y,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});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=Tt(JSON.parse(await hn(zt(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,c=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(c.flatMap(m=>{let E=gn(m);return E?[[E,m]]:[]})),b=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(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 E=l.get(m.id);if(!E){S.push({id:b.get(m.id),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:yn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Hn(e,m.id),supersededById:m.supersededBy?b.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(E),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:Hn(e,m.id),supersededById:m.supersededBy?b.get(m.supersededBy):void 0,updatedAt:m.updatedAt},P=O=>JSON.stringify({kind:O.kind,state:O.state,statement:O.statement,rationale:O.rationale,scope:O.scope,concreteBindings:O.concreteBindings,supersededById:O.supersededById,updatedAt:O.updatedAt});P(E)!==P(D)&&y.push(D)}for(let[m,E]of l)k.has(m)||E.state==="retired"||y.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let T=new Set(t.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),h=new Map(t.bundle.relationships.flatMap(m=>{if(T.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Vt)?.id;return E?[[E,m]]:[]})),u=[],g=new Set;for(let m of e.relations){let E=Zo(m.type);if(!E||m.toStoreId)continue;let D=b.get(m.fromId),P=b.get(m.toId);if(!D||!P)continue;let O=h.get(m.id);O&&O.relationshipType===E&&O.from.entityType==="advisory_explanation"&&O.from.entityId===D&&O.to.entityType==="advisory_explanation"&&O.to.entityId===P||(O&&g.add(m.id),u.push({id:le(a,"imprint-relation",`${m.id}:${E}:${D}:${P}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Vt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:P},reason:m.rationale||"The Imprint graph connected these explanations."}))}let I=new Set(e.relations.map(m=>m.id)),p=n?[...h].filter(([m])=>!I.has(m)||g.has(m)).map(([,m])=>({id:le(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,f=le(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:f,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 g=gn(u);return g?[[g,u.id]]:[]})),c=new Set(e.map(u=>a.get(u)??u)),l=new Map(r.bundle.records.flatMap(u=>u.recordType==="participant"?[[u.id,u.kind]]:[])),b=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 g=u.evidenceIds.flatMap(f=>{let m=b.get(f);if(!m)return[];let E=m.sourceRefs.find(W=>W.kind==="thread")?.id,D=m.sourceRefs.find(W=>W.kind==="message")?.id,P=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",O=l.get(m.participantId)??"unknown";return[{id:m.id,kind:P,summary:m.summary,createdAt:m.createdAt,participantKind:O,threadId:E,jobId:D}]}).sort((f,m)=>m.createdAt.localeCompare(f.createdAt)),I=r.bundle.relationships.flatMap(f=>{if(S.has(f.id))return[];if(!y.has(f.relationshipType))return[];let m=f.from.entityType==="advisory_explanation"&&f.from.entityId===u.id&&f.to.entityType==="advisory_explanation",E=f.to.entityType==="advisory_explanation"&&f.to.entityId===u.id&&f.from.entityType==="advisory_explanation";if(!m&&!E)return[];let D=m?f.to.entityId:f.from.entityId,P=s.get(D);return P?[{id:f.id,type:f.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:P.id,statement:P.statement,rationale:f.reason}]:[]}),p=[...(u.supersededById?[u.supersededById]:[]).flatMap(f=>{let m=s.get(f);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(f=>f.supersededById===u.id?[{id:`supersedes:${f.id}:${u.id}`,type:"supersedes",direction:"outgoing",explanationId:f.id,statement:f.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...u.sourceRefs.flatMap(f=>f.kind==="thread"?[f.id]:[]),...g.flatMap(f=>f.threadId?[f.threadId]:[])])].filter(f=>!t||t.has(f));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:g.length,recentEvidence:g.slice(0,4),concrete:u.concreteBindings.map(f=>({...structuredClone(f)})),relations:[...I,...p],sourceThreadIds:j,needsGrounding:u.state==="testing"&&c.has(u.id)}}).sort((u,g)=>Number(g.needsGrounding)-Number(u.needsGrounding)||k[u.state]-k[g.state]||g.updatedAt.localeCompare(u.updatedAt)),h={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:h,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(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))a.decisionIds.some(c=>t.has(c))&&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 c=i.filter(l=>l.targets.some(b=>b.entityType==="decision"&&b.entityId===a.id)).sort((l,b)=>b.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:c?c.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),c=Se(i),l=Se(i),b=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"}]},h=[{subjectId:r.id,role:"governed"}],u={...T,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:h,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},g={...T,id:c,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={...T,id:l,recordType:"decision",proposalId:a,acceptanceEventId:c,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:h,noChange:!1,effectiveAt:s},p={...T,id:b,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:[b],coverage:[{decisionId:l,status:"projected"}]},f={...T,id:Se(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},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}.`})),E=k.map(P=>({...T,id:Se(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:I.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,I,p,j],events:[g,...m],relationships:[f,...E],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:b}}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(),c=Se(s),l=e.changes.map(T=>{let h=T.decisionIds?.filter(I=>e.decisionIds.includes(I)),u=h?.length?h:e.decisionIds,g=[...new Set(r.filter(I=>u.includes(I.id)).flatMap(I=>I.subjects.map(p=>p.subjectId)))];return{id:Se(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:T.path.map(String).join("."),subjectIds:g,decisionIds:u,value:T.value}}),b=new Set(l.flatMap(T=>T.decisionIds)),S={id:c,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(h=>h.decisionId===T)??{decisionId:T,status:b.has(T)?"projected":"unprojected"})},y=l.flatMap(T=>T.decisionIds.map(h=>({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:h},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:c,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 mn({...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=di(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 Wt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function ke(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Ht(o,e,t){let n=ke(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function er(o){let e=Wt(o),t=Wt(e.authority),n=t.level,r=t.mode,i=Ht(n,"authority.level",["owner","delegate","contributor"]),s=Ht(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:ke(e.proposalId,"proposalId"),participantId:ke(e.participantId,"participantId"),occurredAt:ke(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:ke(e.eventId,"eventId"),decisionId:ke(e.decisionId,"decisionId"),kind:Ht(e.kind,"kind",["principle","preference","rule","constraint"]),reason:ke(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:ke(e.eventId,"eventId"),reason:ke(e.reason,"reason")};case"defer":{let c=Wt(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...a,action:"defer",eventId:ke(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>ke(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>Ht(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.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:ke(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:ke(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:ke(e.acceptanceEventId,"acceptanceEventId"),decisionId:ke(e.decisionId,"decisionId"),relationshipId:ke(e.relationshipId,"relationshipId"),claim:ke(e.claim,"claim"),kind:Ht(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Wt(c);return{subjectId:ke(l.subjectId,"subjectId"),role:Ht(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:ke(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function tr(o){let e=Wt(o),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>ke(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:Wt(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 wd=1400,vd=6,bd=2,nr=6;function ui(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 hi(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!ui(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(ui):[],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 mi(o){return[o.primary,...o.mounted]}function In(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 fi(o){return Math.ceil(JSON.stringify(o).length/4)}function xd(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 Sd(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})=>xd(y,S,S.storeId!==t)),i=In(r.map(S=>S.acceptedTruth?.decisions??[])).slice(0,vd),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}`))),c=In(r.map(S=>S.packets)).slice(0,bd),l=i.length<r.reduce((S,y)=>S+(y.acceptedTruth?.decisions.length??0),0)||c.length<r.reduce((S,y)=>S+y.packets.length,0),b={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:l||r.some(S=>S.acceptedTruth?.truncated)}}:{},packets:c,truncated:l||e.length>0||r.some(S=>S.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;fi(b)>wd;){if(b.packets.length)b.packets.pop();else if(b.acceptedTruth?.decisions.length)b.acceptedTruth.decisions.pop();else break;b.truncated=!0,b.acceptedTruth&&(b.acceptedTruth.truncated=!0)}if(b.estimatedTokens=fi(b),!(!b.packets.length&&!b.acceptedTruth?.decisions.length))return b}function gi(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 Td(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 Pd(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,c=t.get(Te(s,i.from.memoryId)),l=t.get(Te(a,i.to.memoryId));return!c||!l?[]:[{id:i.id,type:i.type,fromId:c,toId:l,rationale:i.rationale,storeId:n.storeId,readOnly:n.storeId!==e,from:{storeId:s,explanationId:c},to:{storeId:a,explanationId:l}}]}))}function Rd(o){let e=new Set;return o.filter(t=>{let n=Td(t);return e.has(n)?!1:(e.add(n),!0)})}function kd(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})=>gi(j,p,p.storeId!==t)),c=In(a.map(p=>p.explanations)),l=Rd([...a.flatMap(p=>p.relations??[]),...r]),b=new Map([...c,...i].map(p=>[Te(p.storeId??"",p.id),p])),S=[],y=new Set,k=p=>{if(!p||S.length>=nr)return;let j=Te(p.storeId??"",p.id);y.has(j)||(y.add(j),S.push(p))};for(let p of c.slice(0,nr)){let j=Te(p.storeId??"",p.id),f=l.flatMap(m=>m.from&&Te(m.from.storeId,m.from.explanationId)===j?[b.get(Te(m.to.storeId,m.to.explanationId))]:m.to&&Te(m.to.storeId,m.to.explanationId)===j?[b.get(Te(m.from.storeId,m.from.explanationId))]:[]).find(Boolean);f&&(k(p),k(f))}c.forEach(k),i.forEach(k);let T=S,h=l.filter(p=>{let j=p.from,f=p.to;return!!(j&&f&&y.has(Te(j.storeId,j.explanationId))&&y.has(Te(f.storeId,f.explanationId)))}),u=new Set([...c.map(p=>Te(p.storeId??"",p.id)),...i.map(p=>Te(p.storeId??"",p.id))]).size,g=[...new Set(a.flatMap(p=>p.pendingGroundingExplanationIds??[]))],I=[...new Set(a.flatMap(p=>p.correctionExplanationIds??[]))];return{explanations:T,relations:h,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:In(a.map(p=>p.historicalCaveats??[])).slice(0,3),...g.length?{pendingGroundingExplanationIds:g}:{},...I.length?{correctionExplanationIds:I}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var Wn=class{constructor(e,t,n=r=>({memory:new Gt(r.projectRoot),imprint:new gt(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=mi(this.normalized(e)),s=await Promise.allSettled(i.map(async l=>{let b,S=await Bn(this.reader(l).memory,t,n,y=>{b=y});if(b)throw b;return{store:l,context:S}})),a=s.flatMap(l=>l.status==="fulfilled"&&l.value.context?[l.value]:[]),c=s.flatMap((l,b)=>l.status==="rejected"?[i[b].storeId]:[]);return this.record(i.length,c.length,r),Sd(a,c,this.primary.storeId,i.length>1)}async imprintContext(e,t){let n=performance.now(),r=mi(this.normalized(e)),i=r.length>1,s=r.map(async _=>({store:_,context:await this.reader(_).imprint.contextualize(_.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async _=>({store:_,topology:await(this.reader(_).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[c,l]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),b=c.flatMap(_=>_.status==="fulfilled"&&_.value.context?[_.value]:[]),S=c.flatMap((_,H)=>_.status==="rejected"?[r[H].storeId]:[]),y=l.flatMap(_=>_.status==="fulfilled"?[_.value]:[]),k=l.flatMap((_,H)=>_.status==="rejected"?[r[H].storeId]:[]),T=new Map(y.flatMap(({store:_,topology:H})=>H.explanations.map(G=>[Te(_.storeId,G.explanationId),G.memoryId]))),h=b.map(({store:_,context:H})=>({store:_,context:{...H,explanations:H.explanations.map(G=>({...G,memoryId:T.get(Te(_.storeId,G.id))}))}})),u=Pd(y,this.primary.storeId),g=h.map(({store:_,context:H})=>gi(H,_,_.storeId!==this.primary.storeId)),I=In(g.map(_=>_.explanations)).slice(0,nr),p=new Set(I.map(_=>Te(_.storeId??"",_.id))),j=new Set(g.flatMap(_=>_.explanations.map(H=>Te(H.storeId??"",H.id)))),f=new Map,m=(_,H)=>{if(j.has(Te(_,H)))return;let G=f.get(_)??new Set;G.add(H),f.set(_,G)};for(let _ of u){if(!_.from||!_.to)continue;let H=Te(_.from.storeId,_.from.explanationId),G=Te(_.to.storeId,_.to.explanationId);p.has(H)&&m(_.to.storeId,_.to.explanationId),p.has(G)&&m(_.from.storeId,_.from.explanationId)}let E=new Map(r.map(_=>[_.storeId,_])),D=[...f].map(async([_,H])=>{let G=E.get(_),fe=G?this.reader(G).imprint.explanationsByIds:void 0;if(!G||!fe)return{storeId:_,explanations:[]};let X=await fe.call(this.reader(G).imprint,[...H]);return{storeId:_,explanations:X.map(oe=>({...oe,memoryId:T.get(Te(_,oe.id)),storeId:_,storeRoot:G.projectRoot,readOnly:_!==this.primary.storeId}))}}),P=await Promise.allSettled(D),O=P.flatMap(_=>_.status==="fulfilled"?_.value.explanations:[]),W=P.flatMap((_,H)=>_.status==="rejected"?[[...f.keys()][H]]:[]),K=[...new Set([...k,...W])];return this.record(r.length,new Set([...S,...K]).size,n),kd(h,S,this.primary.storeId,i,u,O,K)}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)}};var jt=1,or="bridge";function yi(o){return`codex-session:${o}`}function _d(o,e){return`codex-${Md("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function Ii(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 Cd(o,e){let t=new Set,n=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(Ad(s)?Ed(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 c of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(c[1]);return}if(Array.isArray(i)){i.forEach(c=>r(c,s,a+1));return}if(typeof i=="object")for(let[c,l]of Object.entries(i))r(l,c,a+1)}};for(let i of o)r(i.toolInput);return[...t]}function Gn(o){return o?Math.ceil(o.length/4):0}function wi(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(`
40
+ `),a=ln(n),c=vi(r,i),l=[s,a,c].filter(Boolean).join(`
41
+ `);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:Gn(s),memoryEstimatedTokens:Gn(a),imprintEstimatedTokens:Gn(c),totalEstimatedTokens:Gn(l)}}}function vi(o,e){return o?Lt(o,{requestText:e}).split(`
42
+ `).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(`
41
43
  `):["","## 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(`
42
- `)}function Aa(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 ja(o,e){let t=e.flatMap((n,i)=>{let r=o[i];return r?[{packetId:`ambient:${n}`,proposalId:n,claim:r.claim.trim(),proposedKind:r.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 Dn=class{constructor(e){this.options=e;this.turns=new Map}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([Wi(e)])}async prepare(e){if(e.executionOwner===qo)return{status:"managed_by_bridge",protocolVersion:Tt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let b=Gi(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Tt,threadId:n.threadId,jobId:n.jobId,...b}}let i=await this.findThread(e.sessionId);i||(i=await this.options.threadStore.createThread(`thread-${Sa()}`,[Wi(e.sessionId)]));let r=ka(e.sessionId,e.turnId),s=i.messages.find(b=>b.jobId===r&&b.role==="human"),d=Hi(e.prompt),c=s?.memoryReview??await dn(this.options.memoryService,d,[]),l=s?.imprintContext??await this.options.imprintService.contextualize({text:e.prompt,pendingGroundingExplanationIds:i.messages.flatMap(b=>b.role==="assistant"&&b.imprintSummary?.grounding&&!b.imprintSummary.resolvedAction?[b.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(i.id,{role:"human",timestamp:Date.now(),jobId:r,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...c?{memoryReview:c}:{},...l?{imprintContext:l}:{}});let w={sessionId:e.sessionId,turnId:e.turnId,threadId:i.id,jobId:r,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:l,events:[]};this.turns.set(t,w);let R=Gi(e.sessionId,i.id,r,c,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Tt,threadId:i.id,jobId:r,...R}}async recordEvent(e){if(e.executionOwner===qo)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(n=>n.threadId===e.threadId&&n.jobId===e.jobId);return t?(t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)},{status:"recorded"}):{status:"turn_not_found"}}async complete(e){if(e.executionOwner===qo)return{status:"managed_by_bridge",protocolVersion:Tt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Tt};let i=(await this.options.threadStore.getThread(t.threadId))?.messages.find(p=>p.role==="assistant"&&p.jobId===t.jobId);if(i)return e.lastAssistantMessage&&e.lastAssistantMessage!==i.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Tt,threadId:t.threadId,jobId:t.jobId};let r=Ra(t.events,this.options.projectRoot),s=r.length>0,d,c={state:"not_applicable"},l,w;if(t.assessment?.assessmentText){let p=Bt(t.assessment.assessmentText,{context:t.imprintContext,requestText:t.prompt,applicationOccurred:s});p.error?c={state:p.error.includes("missing")?"missing":"invalid",reason:p.error}:p.draft?.decision==="none"?(this.options.imprintService.recordNoop(p.draft.reason),c={state:"none",reason:p.draft.reason}):p.draft?.decision==="recognize"?c={state:"none",reason:"recognized existing grounded understanding"}:(p.draft?.decision==="mutate"||p.draft?.decision==="apply")&&(d=await this.options.imprintService.capture(p.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:t.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:s}),c=d?{state:"mutated"}:{state:"invalid",reason:"imprint mutation failed admission or produced no durable change"},d&&await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId}).catch(()=>{})),l=Aa(p.draft),w=p.draft&&p.draft.decision!=="recognize"?p.draft.appliedExplanationIds:void 0}let R=s?"completed":"no_change",b=an({changedFiles:r}),k={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(p=>p.toolName),turn:{phase:"complete",orientation:[],result:b},result:b,provider:"codex",model:e.model,imprintSummary:d,imprintUsedExplanationIds:l,imprintAppliedExplanationIds:w};await this.options.threadStore.appendMessage(t.threadId,k);let S=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:R,execution:{provider:"codex",model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:r,resolutions:s?[{status:"resolved",summary:`Changed ${r.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(p=>p.id),imprintAssessment:c}),f=ja(t.assessment?.semanticCandidates??[],S.proposalIds);return f&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:f}),{status:"completed",protocolVersion:Tt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Hi(e.query),n=await dn(this.options.memoryService,t,e.subjectHints??[]),i=await this.options.imprintService.contextualize({text:e.query,subjectHints:e.subjectHints});return{memoryContext:n,imprintContext:i,formattedContext:[cn(n),Vi(i,e.query)].filter(Boolean).join(`
43
- `)}}};import{mkdir as Ca,readFile as Ki,realpath as $a,writeFile as Oa}from"fs/promises";import{join as Nn}from"path";function Lt(o){return Ea(o).slice(0,12)}var Ma=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Ea(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):_a(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(t/Math.pow(2,b*8)&255);let n=1779033703,i=3144134277,r=1013904242,s=2773480762,d=1359893119,c=2600822924,l=528734635,w=1541459225,R=new Array(64);for(let b=0;b<e.length;b+=64){for(let h=0;h<16;h++){let m=b+h*4;R[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=Ze(R[h-15],7)^Ze(R[h-15],18)^R[h-15]>>>3,E=Ze(R[h-2],17)^Ze(R[h-2],19)^R[h-2]>>>10;R[h]=R[h-16]+m+R[h-7]+E>>>0}let k=n,S=i,f=r,p=s,g=d,v=c,u=l,M=w;for(let h=0;h<64;h++){let m=Ze(g,6)^Ze(g,11)^Ze(g,25),E=g&v^~g&u,D=M+m+E+Ma[h]+R[h]>>>0,T=Ze(k,2)^Ze(k,13)^Ze(k,22),C=k&S^k&f^S&f,z=T+C>>>0;M=u,u=v,v=g,g=p+D>>>0,p=f,f=S,S=k,k=D+z>>>0}n=n+k>>>0,i=i+S>>>0,r=r+f>>>0,s=s+p>>>0,d=d+g>>>0,c=c+v>>>0,l=l+u>>>0,w=w+M>>>0}return[n,i,r,s,d,c,l,w].map(b=>b.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function _a(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}async function Fo(o){return $a(o).catch(()=>o)}function Qi(o){return Nn(o,".popmelt","store.json")}function Da(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 Uo(o){let e=await Fo(o);try{let t=JSON.parse(await Ki(Qi(e),"utf8"));return Da(t)?t:null}catch{return null}}async function Na(o){let e=await Fo(o),t=await Uo(e);if(t)return t;let n;for(let i of[Nn(e,".popmelt","memory","manifest.json"),Nn(e,".popmelt","imprint","manifest.json")])try{let r=JSON.parse(await Ki(i,"utf8"));if(typeof r.projectId=="string"&&r.projectId.trim()){n=r.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Lt(e)}`,createdAt:new Date().toISOString()}}async function Bn(o){let e=await Fo(o),t=await Uo(e);if(t)return t;let n=await Na(e),i=Nn(e,".popmelt");await Ca(i,{recursive:!0});try{return await Oa(Qi(e),`${JSON.stringify(n,null,2)}
44
- `,{encoding:"utf8",flag:"wx"}),n}catch(r){let s=await Uo(e);if(s)return s;throw r}}var Ba=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ja=new Set(["default","flex","fast","priority"]);function qt(o){let e=typeof o.reasoningEffort=="string"&&Ba.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&Ja.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Jn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as La}from"child_process";import{createInterface as qa}from"readline";function ln(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
45
-
46
- ${t}`:t;return o.push(n),n}var Ua=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"]),Xi=1e5;function Fa(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ua.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>Xi?n.slice(0,Xi)+`
47
- \u2026[truncated]`:n}function Ln(o,e){let{prompt:t,projectRoot:n,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:w,timeoutMs:R=3e5,onEvent:b}=e,k=[];c?k.push("--resume",c,"-p",t):k.push("-p",t),k.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),l&&k.push("--model",l),w&&k.push("--effort",w);for(let p of s)k.push("--allowedTools",p);let S=La(d,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),f=new Promise(p=>{let g,v=[],u=[],M=[],h=!1,m="",E,D,T=!1,C=setTimeout(()=>{T=!0,S.kill("SIGTERM"),setTimeout(()=>{try{S.kill("SIGKILL")}catch{}},5e3)},R),z=qa({input:S.stdout}),X=new Set;z.on("line",Y=>{if(Y.trim())try{let x=JSON.parse(Y);x.session_id&&!g&&(g=x.session_id);let Q=x.type??(x.event?.type?`event.${x.event.type}`:"unknown");if(X.add(Q),x.type==="result"&&x.result&&v.length===0){let L=typeof x.result=="string"?x.result:"";if(L){let K=ln(v,L);K&&b?.({type:"delta",jobId:o,text:K},o)}}if(x.type==="assistant"&&Array.isArray(x.message?.content)){typeof x.error=="string"&&(E=x.error);for(let L of x.message.content){if(L.type==="text"&&L.text){let K=ln(v,L.text);K&&b?.({type:"delta",jobId:o,text:K},o)}if(L.type==="tool_use"&&L.name){let K=L.input?.file_path||L.input?.path||void 0,H=Fa(L);if(b?.({type:"tool_use",jobId:o,tool:L.name,...K?{file:K}:{},...H?{content:H}:{}},o),L.name==="Edit"&&L.input?.file_path){let B={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};u.push(B),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:B.file_path,oldString:typeof B.old_string=="string"?B.old_string:void 0,newString:typeof B.new_string=="string"?B.new_string:void 0,replaceAll:typeof B.replace_all=="boolean"?B.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(u.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:L.input.file_path,content:typeof L.input.content=="string"?L.input.content:void 0}))}L.type==="thinking"&&L.thinking&&b?.({type:"thinking",jobId:o,text:L.thinking},o)}}x.type==="result"&&x.is_error===!0&&(h=!0,typeof x.error=="string"&&(E=x.error),typeof x.result=="string"&&(D=x.result)),x.type==="user"&&x.tool_use_result?.file?.filePath&&b?.({type:"tool_use",jobId:o,tool:"Read",file:x.tool_use_result.file.filePath},o)}catch{}});let G=[];S.stderr?.on("data",Y=>{G.push(Y.toString())}),S.on("close",Y=>{if(clearTimeout(C),z.close(),v.length===0&&X.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...X].join(", ")}`),T)h=!0,m=`Timed out after ${Math.round(R/6e4)} minutes`;else if(Y!==0&&Y!==null){h=!0;let Q=G.join("").trim(),L=v.join("").trim(),K=v.length===0&&X.size>0?` (no text captured, event types: ${[...X].join(", ")})`:"";m=Q||D||L||`Claude process exited with code ${Y}${K}`}h&&!m&&D&&(m=D);let x=za(m,E);p({sessionId:g,text:v.join(""),success:!h,error:h?x.message:void 0,errorCode:h?x.code:void 0,recoverableError:h?x.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:M.length>0?M:void 0})}),S.on("error",Y=>{clearTimeout(C),h=!0,m=Y.message,p({sessionId:g,text:v.join(""),success:!1,error:m,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:M.length>0?M:void 0})})});return{process:S,result:f}}function za(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 Ha,spawnSync as rr}from"child_process";import{readFileSync as Ga,statSync as Va}from"fs";import{basename as Ka,extname as Qa,isAbsolute as Xa,relative as sr,resolve as Ya}from"path";import{createInterface as Za}from"readline";function Un(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:void 0}function qn(o,e){for(let t of o)if(t)for(let n of e){let i=t[n];if(typeof i=="string"&&i.trim())return i.trim()}}function Yi(o){let e=Un(o);if(e)return e;if(typeof o=="string")try{return Un(JSON.parse(o))}catch{return}}function zo(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Wa(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 Zi(o){let e=Un(o)??{},t=Un(e.invocation),n=Yi(e.arguments)??Yi(t?.arguments),i=qn([e,t],["server","server_name"]),r=qn([e,t],["tool","tool_name","name"]),s=qn([n,e,t],["title","display_name","description"]),d=qn([n],["code","script"]),c=Wa(i,r,s,d)?"Browser":i?zo(i):r?zo(r):"MCP",l=r&&zo(r),w=s??l,R=w&&w!==c?`${c}: ${w}`:c;return{tool:c,...w?{content:w}:{},telemetryLabel:R}}function er(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var tr=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"]),Wo=2e5,ed=1e5,ar=2e5;function dr(o){let e=Ka(o).toLowerCase(),t=Qa(o).toLowerCase();return tr.has(t)||tr.has(e)}function pn(o,e){let t=Xa(e)?e:Ya(o,e),n=sr(o,t);return n===""||n.startsWith("..")?null:t}function Fn(o,e){if(!dr(e))return;let t=pn(o,e);if(t)try{let n=Va(t);return n.isFile()?n.size>Wo?{exists:!0,truncated:!0}:{exists:!0,content:Ga(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function td(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function nd(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 nr(o){return td(o,["patch","diff","unifiedDiff","unified_diff"])}function Ho(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function or(o,e){let t=rr("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ar+65536});return t.status!==0?null:t.stdout??""}function od(o){let e=new Set;for(let t of o.split(`
48
- `)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let i=n.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function ir(o){let e=or(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=or(o,["diff","--no-ext-diff","HEAD","--"])??"",n=Ho(t,ar);return{status:e,changedFiles:od(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function id(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function rd(o,e){if(!dr(e))return;let t=pn(o,e);if(!t)return;let n=sr(o,t);if(n===""||n.startsWith(".."))return;let i=rr("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Wo+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=Ho(r,Wo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function sd(o,e,t){return e.map(n=>{let i=t.has(n)?t.get(n):rd(o,n),r=Fn(o,n);return{filePath:n,...i?{before:i}:{},...r?{after:r}:{}}})}function zn(o,e){let{prompt:t,projectRoot:n,screenshotPath:i,resumeSessionId:r,model:s,onEvent:d,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,w=[];if(r){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(r),w.push(t),i&&w.push("--image",i)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(t),i&&w.push("--image",i)}let R=Ha("codex",w,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:o}}),b=new Promise(k=>{let S,f=[],p=[],g=[],v=new Map,u=new Map,M=!1,h="",m=Za({input:R.stdout}),E=new Set;m.on("line",T=>{if(T.trim())try{let C=JSON.parse(T),z=C.type??"unknown";if(E.add(z),z==="thread.started"&&C.thread_id&&!S&&(S=C.thread_id),(z==="item.agentMessage.delta"||z==="item/agentMessage/delta")&&C.delta?.text&&(f.push(C.delta.text),d?.({type:"delta",jobId:o,text:C.delta.text},o)),(z==="item.reasoning.delta"||z==="item/reasoning/delta")&&C.delta?.text&&d?.({type:"thinking",jobId:o,text:C.delta.text},o),(z==="item.started"||z==="item/started")&&C.item){let X=C.item.type;if(X==="command_execution"){let G=C.item.command,Y=G?er(G):void 0,x=ir(n),Q=new Map;for(let K of x?.changedFiles??[])Q.set(K,Fn(n,K));typeof C.item.id=="string"&&u.set(C.item.id,{...G?{rawCommand:G}:{},...Y?{command:Y}:{},...x?{beforeWorktree:x}:{},beforeSnapshots:Q});let L=Y?`Bash: ${Y.split(`
49
- `)[0].slice(0,80)}`:"Bash";p.push(L),d?.({type:"tool_use",jobId:o,tool:"Bash",...Y?{content:Y}:{}},o)}else if(X==="file_change"){let G=C.item.filename||C.item.path;G&&!v.has(G)&&v.set(G,Fn(n,G)),p.push(G?`Edit ${G.split("/").pop()}`:"Edit");let Y=G?pn(n,G)??G:void 0;d?.({type:"tool_use",jobId:o,tool:"Edit",...Y?{file:Y}:{}},o)}else if(X==="file_read"){let G=C.item.filename||C.item.path;p.push(G?`Read ${G.split("/").pop()}`:"Read");let Y=G?pn(n,G)??G:void 0;d?.({type:"tool_use",jobId:o,tool:"Read",...Y?{file:Y}:{}},o)}else if(X==="web_search")p.push("WebSearch"),d?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(X==="mcp_tool_call"){let G=Zi(C.item);p.push(G.telemetryLabel),d?.({type:"tool_use",jobId:o,tool:G.tool,...G.content?{content:G.content}:{}},o)}}if((z==="item.completed"||z==="item/completed")&&C.item){if(C.item.type==="agent_message"){let X=C.item.text;if(typeof X=="string"&&X){let G=ln(f,X);G&&d?.({type:"delta",jobId:o,text:G},o)}}else if(C.item.type==="reasoning"){let X=C.item.text;typeof X=="string"&&X&&d?.({type:"thinking",jobId:o,text:X},o)}else if(C.item.type==="file_change"&&Array.isArray(C.item.changes))for(let X of C.item.changes){let G=X.path||X.filename,Y=X.kind==="add"?"Write":"Edit";if(G){p.push(`${Y} ${G.split("/").pop()}`);let x=pn(n,G)??G;d?.({type:"tool_use",jobId:o,tool:Y,file:x},o);let Q=X,L=typeof Q.kind=="string"?Q.kind:void 0,K=nd(L),H=v.get(G),B=Fn(n,G);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:K,filePath:G,...H?{before:H}:{},...B?{after:B}:{},...nr(Q)?{patch:nr(Q)}:{},...L?{rawKind:L}:{}}),v.set(G,B)}}else if(C.item.type==="command_execution"){let X=typeof C.item.id=="string"?C.item.id:void 0,G=X?u.get(X):void 0,Y=typeof C.item.command=="string"?C.item.command:G?.rawCommand,x=Y?er(Y):G?.command,Q=ir(n);if(id(G?.beforeWorktree,Q)){let L=[...new Set([...G?.beforeWorktree?.changedFiles??[],...Q?.changedFiles??[]])],K=typeof C.item.aggregated_output=="string"?Ho(C.item.aggregated_output,ed):void 0,H=typeof C.item.exit_code=="number"?C.item.exit_code:C.item.exit_code===null?null:void 0,B=typeof C.item.status=="string"?C.item.status:void 0;g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Y?{rawCommand:Y}:{},...x?{command:x}:{},...H!==void 0?{exitCode:H}:{},...B?{status:B}:{},...K?{output:K.text}:{},...K?.truncated?{outputTruncated:!0}:{},...G?.beforeWorktree?{beforeWorktree:G.beforeWorktree}:{},...Q?{afterWorktree:Q}:{},...L.length>0?{touchedFiles:sd(n,L,G?.beforeSnapshots??new Map)}:{}})}X&&u.delete(X)}}z==="turn.failed"&&(M=!0,h=C.error?.message||C.message||"Turn failed")}catch{}});let D=[];R.stderr?.on("data",T=>{D.push(T.toString())}),R.on("close",T=>{m.close(),f.length===0&&E.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...E].join(", ")}`),T!==0&&T!==null&&(M=!0,h=D.join("")||`Codex process exited with code ${T}`),k({sessionId:S,text:f.join(""),success:!M,error:M?h:void 0,editEvents:g.length>0?g:void 0,toolsUsed:p.length>0?p:void 0})}),R.on("error",T=>{M=!0,h=T.message,k({sessionId:S,text:f.join(""),success:!1,error:h,editEvents:g.length>0?g:void 0,toolsUsed:p.length>0?p:void 0})})});return{process:R,result:b}}import{spawn as ad}from"child_process";import{createInterface as dd}from"readline";function cr(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 lr(o,e){let{prompt:t,projectRoot:n,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:d,copilotPath:c="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"];i&&l.push(`--resume=${i}`),r&&l.push("--model",r),l.push("-p",t);let w=ad(c,l,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(b=>{let k,S=[],f=[],p=!1,g="",v=!1,u=setTimeout(()=>{v=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),M=dd({input:w.stdout}),h=new Set,m=[];M.on("line",D=>{if(D.trim())try{let T=JSON.parse(D),C=mn(T);h.add(C),m.length<5&&ld(C)&&m.push(D.slice(0,800));let z=un(T,["sessionId","session_id","id"],["session","conversation","thread"]);z&&!k&&(k=z);let X=cd(T,S.length===0);X&&(S.push(X),d?.({type:"delta",jobId:o,text:X},o));let G=pd(T);G&&d?.({type:"thinking",jobId:o,text:G},o);let Y=ud(T);Y&&(f.push(Y.label),d?.({type:"tool_use",jobId:o,tool:Y.tool,...Y.file?{file:Y.file}:{},...Y.content?{content:Y.content}:{}},o));let x=md(T);x&&(p=!0,g=x)}catch{}});let E=[];w.stderr?.on("data",D=>{E.push(D.toString())}),w.on("close",D=>{clearTimeout(u),M.close(),S.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(`
50
- `)}`)),v?(p=!0,g=`Timed out after ${Math.round(s/6e4)} minutes`):D!==0&&D!==null&&(p=!0,g=E.join("").trim()||g||`Copilot process exited with code ${D}`);let T=p?cr(g,r):null;b({sessionId:k,text:S.join(""),success:!p,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})}),w.on("error",D=>{clearTimeout(u);let T=cr(D.message,r);b({sessionId:k,text:S.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})})});return{process:w,result:R}}function mn(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 cd(o,e=!1){let t=mn(o).toLowerCase(),n=o.update,i=n?.content;if(n?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return Fe(o.delta)??Fe(o.content)??Fe(o.message);if(t==="assistant.message"&&e)return Fe(o.message)??Fe(o.content)??Fe(o);if(t==="result"&&e)return Fe(o.result)??Fe(o.output)??Fe(o.message)??Fe(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&Go(o))return o.text;if(typeof o.message=="string"&&Go(o))return o.message;if(typeof o.delta=="string"&&Go(o))return o.delta}function Fe(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(Fe).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=Fe(e[t]);if(n)return n}}function ld(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function pd(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 ud(o){let e=un(o,["tool","toolName","tool_name","name"]),t=un(o,["command","cmd"]),n=un(o,["file","path","filename","filePath"]),i=mn(o);if(t||i.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
51
- `)[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&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function md(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"&&mn(o).toLowerCase().includes("error"))return o.message}function un(o,e,t=[]){for(let n of e){let i=o[n];if(typeof i=="string")return i}for(let[n,i]of Object.entries(o)){if(!i||typeof i!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=un(i,e);if(r)return r}}function Go(o){let e=mn(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as fd,readFile as hd}from"fs/promises";import{join as Vo}from"path";var Wn=class{constructor(e){let t=Vo(e,".popmelt");this.decisionsDir=Vo(t,"decisions")}async listDecisionIds(){try{return(await fd(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 hd(Vo(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 gd,randomUUID as yd}from"crypto";import{mkdir as Ko,readFile as pr,readdir as ur,rename as Hn,stat as mr,unlink as Gn,writeFile as Vn}from"fs/promises";import{extname as Id,join as Ve}from"path";var vd=10080*60*1e3,wd=600*1e3,bd=3600*1e3;function xd(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function Sd(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var Kn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let t=yd(),n=xd(e.mimeType),i=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:Sd(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await Ko(this.draftsDir,{recursive:!0});let d=Ve(this.draftsDir,i),c=Ve(this.draftsDir,`${t}.json`),l=`${d}.part`,w=`${c}.part`;return await Vn(l,e.data),await Hn(l,d),await Vn(w,JSON.stringify(s,null,2)),await Hn(w,c),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 i=await this.readManifest(n.id);if(!i)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(i.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ve(this.draftsDir,i.contentFile),s=await pr(r),d=gd("sha256").update(s).digest("hex"),c=Ve(this.mediaDir,`${d}${Id(i.contentFile)||".bin"}`);await Ko(this.mediaDir,{recursive:!0});try{await mr(c)}catch{let l=`${c}.part`;await Vn(l,s),await Hn(l,c)}(t[n.annotationId]??=[]).push({id:i.id,name:i.name,mimeType:i.mimeType,size:i.size,kind:i.kind,path:c}),i.releasedAt=Date.now(),i.lastSeenAt=Date.now(),await this.writeManifest(i)}return t}async sweep(e=Date.now()){let t;try{t=await ur(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let i=Ve(this.draftsDir,n);if(n.endsWith(".part")){let d=await mr(i).catch(()=>null);d&&e-d.mtimeMs>bd&&await Gn(i).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>wd:e-r.lastSeenAt>vd)||await Promise.all([Gn(i).catch(()=>{}),Gn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await ur(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Gn(Ve(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await pr(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Ko(this.draftsDir,{recursive:!0});let t=Ve(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Vn(n,JSON.stringify(e,null,2)),await Hn(n,t)}};import{randomUUID as fr}from"crypto";import{mkdir as Qo,readFile as Xo,writeFile as Qn}from"fs/promises";import{dirname as Yo,join as Ut}from"path";var Ke="[ProjectionWorker]",Td={version:1,runs:[]},Pd={version:1,updatedAt:0,proposals:[]},kd=12;function Rd(o){return Array.isArray(o)?o.map((e,t)=>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 hr(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(`${Ke} 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(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function Ad(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function jd(o,e,t){let n=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let S of r){if(!S||typeof S!="object")continue;let f=S.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&n.has(p)&&i.add(p)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},d=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},c=Array.isArray(t?.rules)?t.rules:[],l=r.filter(S=>{if(!S||typeof S!="object")return!1;let f=S.id,p=typeof f=="string"?c.find(g=>g&&typeof g=="object"&&g.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(S)}).length,w=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},R=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},b=Object.keys(s).filter(S=>JSON.stringify(s[S])!==JSON.stringify(w[S])).length,k=Object.keys(d).filter(S=>JSON.stringify(d[S])!==JSON.stringify(R[S])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:k,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(S=>!i.has(S))}}function Md(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ed(o,e,t){let n=o[e];if(n&&typeof n=="object")return n;let i=typeof t=="number"?[]:{};return o[String(e)]=i,i}function Xn(o,e,t){let n=o;for(let r=0;r<e.length-1;r++)n=Ed(n,e[r],e[r+1]);let i=e[e.length-1];n[String(i)]=Md(t)}function gr(o,e){let t=o;for(let i=0;i<e.length-1;i++){let r=t[String(e[i])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function _d(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 Cd(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 yr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=_d(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?Cd(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var Yn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Ut(e,".popmelt");this.runsPath=Ut(n,"projection-runs.json"),this.legacyRunsPath=Ut(n,"materialization-runs.json"),this.proposalsPath=Ut(n,"projection-queue.json"),this.legacyProposalsPath=Ut(n,"model-proposals.json"),this.modelPath=Ut(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Xo(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Rd(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let i=n.key.split(".");n.value===null?gr(t,i):Xn(t,i,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(kd),t=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!t.has(i.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(),i=n.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(S=>S.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),d=Nd(i,s),c=Ad(i,n.totalCandidateDecisionCount,d);t=fr().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:r,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let w=!0,R,b,k;try{let S=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(S,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:f},await this.persistRun(l);let g=await p;if(!g.success)w=!1,R=g.error,console.error(`${Ke} ${f} spawn error:`,R);else{let v=Dd(g.text,r);if(v){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of v)Xn(u,m.path,m.value);Array.isArray(u.rules)&&(u.rules=hr(u.rules));let M=jd(u,r,s);if(v){let m=[...new Set(v.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=r.filter(E=>!m.includes(E))}b=M;let h=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:b,changes:v});k=h.id,console.log(`${Ke} Created model proposal ${h.id} for ${r.length} decision(s)`)}else w=!1,R="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${R}`)}}catch(S){w=!1,R=S instanceof Error?S.message:String(S),console.error(`${Ke} Error:`,R)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:w,error:R}),{processedIds:r,success:w,error:R,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=hr(e.rules)),await Qn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} 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 Qo(Yo(this.runsPath),{recursive:!0}),await Qn(this.runsPath,JSON.stringify(t,null,2)),t):{...Td,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Pd,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(n);for(let s of i.changes??[])Xn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>i.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>n.createdAt-i.createdAt||n.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,t,n,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let c of t)!Array.isArray(c.path)||c.path.length===0||(c.remove?gr(s,c.path):Xn(s,c.path,c.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,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:fr().slice(0,8),status:"pending",title:$d(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"}.`:Od(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(i=>i.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),i=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(i={...r,...t,updatedAt:Date.now()},i)),i?(n.updatedAt=Date.now(),await this.persistModelProposals(n),i):null}async persistModelProposals(e){try{await Qo(Yo(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...i})=>i)};await Qn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(i=>i.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await Qo(Yo(this.runsPath),{recursive:!0}),await Qn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Xo(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Xo(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,i){let r=n.provider??this.options.provider??"codex",s=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return r==="codex"?{provider:"codex",...zn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Jn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...Ln(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function $d(o){let t=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.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 Od(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,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Dd(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 i=new Set(e),r=n.flatMap((s,d)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let c=s;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let w=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&i.has(R)):[];return w.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:w,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function Nd(o,e){let t=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
52
- Kind: ${r.kind}
53
- Claim: ${r.claim}
54
- ${r.rationale?`Rationale: ${r.rationale}`:""}
55
- Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
56
- Authority: ${r.authority.level}/${r.authority.mode}`).join(`
57
-
58
- `),n=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
44
+ `)}function $d(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 Od(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 Kn=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 Wn(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([yi(e)])}async prepare(e){if(e.executionOwner===or)return{status:"managed_by_bridge",protocolVersion:jt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let y=wi(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:jt,threadId:n.threadId,jobId:n.jobId,...y}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${jd()}`,[yi(e.sessionId)]));let i=_d(e.sessionId,e.turnId),s=r.messages.find(y=>y.jobId===i&&y.role==="human"),a=Ii(e.prompt),c=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,...c?{memoryReview:c}:{},...l?{imprintContext:l}:{}});let b={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:l,events:[]};this.turns.set(t,b);let S=wi(e.sessionId,r.id,i,c,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:jt,threadId:r.id,jobId:i,...S}}async recordEvent(e){if(e.executionOwner===or)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(n=>n.threadId===e.threadId&&n.jobId===e.jobId);return t?(t.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)},{status:"recorded"}):{status:"turn_not_found"}}async complete(e){if(e.executionOwner===or)return{status:"managed_by_bridge",protocolVersion:jt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:jt};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:jt,threadId:t.threadId,jobId:t.jobId};let i=Cd(t.events,this.options.projectRoot),s=i.length>0,a,c={state:"not_applicable"},l,b;if(t.assessment?.assessmentText){let u=Jt(t.assessment.assessmentText,{context:t.imprintContext,requestText:t.prompt,applicationOccurred:s});u.error?c={state:u.error.includes("missing")?"missing":"invalid",reason:u.error}:u.draft?.decision==="none"?(this.options.imprintService.recordNoop(u.draft.reason),c={state:"none",reason:u.draft.reason}):u.draft?.decision==="recognize"?c={state:"none",reason:"recognized existing grounded understanding"}:(u.draft?.decision==="mutate"||u.draft?.decision==="apply")&&(a=await this.options.imprintService.capture(u.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:t.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:s,storeId:this.options.storeId,context:t.imprintContext}),c=a?{state:"mutated"}:{state:"invalid",reason:"imprint mutation failed admission or produced no durable change"},a&&await this.options.memoryService.recordImprintEvidence({summary:a,threadId:t.threadId,jobId:t.jobId,qualifiedExplanationMemoryIds:Object.fromEntries((t.imprintContext?.explanations??[]).flatMap(g=>g.storeId&&g.memoryId?[[`${g.storeId}:${g.id}`,g.memoryId]]:[]))}).catch(()=>{})),l=$d(u.draft),b=u.draft&&u.draft.decision!=="recognize"?u.draft.appliedExplanationIds:void 0}let S=s?"completed":"no_change",y=cn({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:b};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:c}),h=Od(t.assessment?.semanticCandidates??[],T.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:jt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Ii(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:[ln(n),vi(r,e.query)].filter(Boolean).join(`
45
+ `)}}};import{mkdir as Jd,readFile as bi,realpath as Ld,writeFile as qd}from"fs/promises";import{join as Qn}from"path";function Kt(o){return Nd(o).slice(0,12)}var Dd=[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 Nd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Bd(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,c=2600822924,l=528734635,b=1541459225,S=new Array(64);for(let y=0;y<e.length;y+=64){for(let f=0;f<16;f++){let m=y+f*4;S[f]=(e[m]<<24|e[m+1]<<16|e[m+2]<<8|e[m+3])>>>0}for(let f=16;f<64;f++){let m=et(S[f-15],7)^et(S[f-15],18)^S[f-15]>>>3,E=et(S[f-2],17)^et(S[f-2],19)^S[f-2]>>>10;S[f]=S[f-16]+m+S[f-7]+E>>>0}let k=n,T=r,h=i,u=s,g=a,I=c,p=l,j=b;for(let f=0;f<64;f++){let m=et(g,6)^et(g,11)^et(g,25),E=g&I^~g&p,D=j+m+E+Dd[f]+S[f]>>>0,P=et(k,2)^et(k,13)^et(k,22),O=k&T^k&h^T&h,W=P+O>>>0;j=p,p=I,I=g,g=u+D>>>0,u=h,h=T,T=k,k=D+W>>>0}n=n+k>>>0,r=r+T>>>0,i=i+h>>>0,s=s+u>>>0,a=a+g>>>0,c=c+I>>>0,l=l+p>>>0,b=b+j>>>0}return[n,r,i,s,a,c,l,b].map(y=>y.toString(16).padStart(8,"0")).join("")}function et(o,e){return o>>>e|o<<32-e}function Bd(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}async function ir(o){return Ld(o).catch(()=>o)}function xi(o){return Qn(o,".popmelt","store.json")}function Fd(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 rr(o){let e=await ir(o);try{let t=JSON.parse(await bi(xi(e),"utf8"));return Fd(t)?t:null}catch{return null}}async function Ud(o){let e=await ir(o),t=await rr(e);if(t)return t;let n;for(let r of[Qn(e,".popmelt","memory","manifest.json"),Qn(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await bi(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){n=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Kt(e)}`,createdAt:new Date().toISOString()}}async function Xn(o){let e=await ir(o),t=await rr(e);if(t)return t;let n=await Ud(e),r=Qn(e,".popmelt");await Jd(r,{recursive:!0});try{return await qd(xi(e),`${JSON.stringify(n,null,2)}
46
+ `,{encoding:"utf8",flag:"wx"}),n}catch(i){let s=await rr(e);if(s)return s;throw i}}var zd=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Vd=new Set(["default","flex","fast","priority"]);function Qt(o){let e=typeof o.reasoningEffort=="string"&&zd.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&Vd.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Yn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as Hd}from"child_process";import{createInterface as Wd}from"readline";function wn(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
47
+
48
+ ${t}`:t;return o.push(n),n}var Gd=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"]),Si=1e5;function Kd(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Gd.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>Si?n.slice(0,Si)+`
49
+ \u2026[truncated]`:n}function Zn(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:c,model:l,reasoningEffort:b,timeoutMs:S=3e5,onEvent:y}=e,k=[];c?k.push("--resume",c,"-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),b&&k.push("--effort",b);for(let u of s)k.push("--allowedTools",u);let T=Hd(a,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(u=>{let g,I=[],p=[],j=[],f=!1,m="",E,D,P=!1,O=setTimeout(()=>{P=!0,T.kill("SIGTERM"),setTimeout(()=>{try{T.kill("SIGKILL")}catch{}},5e3)},S),W=Wd({input:T.stdout}),K=new Set;W.on("line",H=>{if(H.trim())try{let G=JSON.parse(H);G.session_id&&!g&&(g=G.session_id);let fe=G.type??(G.event?.type?`event.${G.event.type}`:"unknown");if(K.add(fe),G.type==="result"&&G.result&&I.length===0){let X=typeof G.result=="string"?G.result:"";if(X){let oe=wn(I,X);oe&&y?.({type:"delta",jobId:o,text:oe},o)}}if(G.type==="assistant"&&Array.isArray(G.message?.content)){typeof G.error=="string"&&(E=G.error);for(let X of G.message.content){if(X.type==="text"&&X.text){let oe=wn(I,X.text);oe&&y?.({type:"delta",jobId:o,text:oe},o)}if(X.type==="tool_use"&&X.name){let oe=X.input?.file_path||X.input?.path||void 0,x=Kd(X);if(y?.({type:"tool_use",jobId:o,tool:X.name,...oe?{file:oe}:{},...x?{content:x}:{}},o),X.name==="Edit"&&X.input?.file_path){let $={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($),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:$.file_path,oldString:typeof $.old_string=="string"?$.old_string:void 0,newString:typeof $.new_string=="string"?$.new_string:void 0,replaceAll:typeof $.replace_all=="boolean"?$.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)}}G.type==="result"&&G.is_error===!0&&(f=!0,typeof G.error=="string"&&(E=G.error),typeof G.result=="string"&&(D=G.result)),G.type==="user"&&G.tool_use_result?.file?.filePath&&y?.({type:"tool_use",jobId:o,tool:"Read",file:G.tool_use_result.file.filePath},o)}catch{}});let _=[];T.stderr?.on("data",H=>{_.push(H.toString())}),T.on("close",H=>{if(clearTimeout(O),W.close(),I.length===0&&K.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...K].join(", ")}`),P)f=!0,m=`Timed out after ${Math.round(S/6e4)} minutes`;else if(H!==0&&H!==null){f=!0;let fe=_.join("").trim(),X=I.join("").trim(),oe=I.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";m=fe||D||X||`Claude process exited with code ${H}${oe}`}f&&!m&&D&&(m=D);let G=Qd(m,E);u({sessionId:g,text:I.join(""),success:!f,error:f?G.message:void 0,errorCode:f?G.code:void 0,recoverableError:f?G.recoverable:void 0,fileEdits:p.length>0?p:void 0,editEvents:j.length>0?j:void 0})}),T.on("error",H=>{clearTimeout(O),f=!0,m=H.message,u({sessionId:g,text:I.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:h}}function Qd(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 Yd,spawnSync as Ei}from"child_process";import{readFileSync as Zd,statSync as ec}from"fs";import{basename as tc,extname as nc,isAbsolute as oc,relative as _i,resolve as rc}from"path";import{createInterface as ic}from"readline";function to(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:void 0}function eo(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 Ti(o){let e=to(o);if(e)return e;if(typeof o=="string")try{return to(JSON.parse(o))}catch{return}}function sr(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Xd(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=to(o)??{},t=to(e.invocation),n=Ti(e.arguments)??Ti(t?.arguments),r=eo([e,t],["server","server_name"]),i=eo([e,t],["tool","tool_name","name"]),s=eo([n,e,t],["title","display_name","description"]),a=eo([n],["code","script"]),c=Xd(r,i,s,a)?"Browser":r?sr(r):i?sr(i):"MCP",l=i&&sr(i),b=s??l,S=b&&b!==c?`${c}: ${b}`:c;return{tool:c,...b?{content:b}:{},telemetryLabel:S}}function Ri(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var ki=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"]),ar=2e5,sc=1e5,Ci=2e5;function $i(o){let e=tc(o).toLowerCase(),t=nc(o).toLowerCase();return ki.has(t)||ki.has(e)}function vn(o,e){let t=oc(e)?e:rc(o,e),n=_i(o,t);return n===""||n.startsWith("..")?null:t}function no(o,e){if(!$i(e))return;let t=vn(o,e);if(t)try{let n=ec(t);return n.isFile()?n.size>ar?{exists:!0,truncated:!0}:{exists:!0,content:Zd(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ac(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function dc(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 ac(o,["patch","diff","unifiedDiff","unified_diff"])}function dr(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function ji(o,e){let t=Ei("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Ci+65536});return t.status!==0?null:t.stdout??""}function cc(o){let e=new Set;for(let t of o.split(`
50
+ `)){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 Ai(o){let e=ji(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=ji(o,["diff","--no-ext-diff","HEAD","--"])??"",n=dr(t,Ci);return{status:e,changedFiles:cc(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function lc(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function pc(o,e){if(!$i(e))return;let t=vn(o,e);if(!t)return;let n=_i(o,t);if(n===""||n.startsWith(".."))return;let r=Ei("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ar+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=dr(i,ar);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function uc(o,e,t){return e.map(n=>{let r=t.has(n)?t.get(n):pc(o,n),i=no(o,n);return{filePath:n,...r?{before:r}:{},...i?{after:i}:{}}})}function oo(o,e){let{prompt:t,projectRoot:n,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let k of l)b.push("-c",k);s&&b.push("-m",s),b.push(i),b.push(t),r&&b.push("--image",r)}else{b.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let k of l)b.push("-c",k);s&&b.push("-m",s),b.push(t),r&&b.push("--image",r)}let S=Yd("codex",b,{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,h=[],u=[],g=[],I=new Map,p=new Map,j=!1,f="",m=ic({input:S.stdout}),E=new Set;m.on("line",P=>{if(P.trim())try{let O=JSON.parse(P),W=O.type??"unknown";if(E.add(W),W==="thread.started"&&O.thread_id&&!T&&(T=O.thread_id),(W==="item.agentMessage.delta"||W==="item/agentMessage/delta")&&O.delta?.text&&(h.push(O.delta.text),a?.({type:"delta",jobId:o,text:O.delta.text},o)),(W==="item.reasoning.delta"||W==="item/reasoning/delta")&&O.delta?.text&&a?.({type:"thinking",jobId:o,text:O.delta.text},o),(W==="item.started"||W==="item/started")&&O.item){let K=O.item.type;if(K==="command_execution"){let _=O.item.command,H=_?Ri(_):void 0,G=Ai(n),fe=new Map;for(let oe of G?.changedFiles??[])fe.set(oe,no(n,oe));typeof O.item.id=="string"&&p.set(O.item.id,{..._?{rawCommand:_}:{},...H?{command:H}:{},...G?{beforeWorktree:G}:{},beforeSnapshots:fe});let X=H?`Bash: ${H.split(`
51
+ `)[0].slice(0,80)}`:"Bash";u.push(X),a?.({type:"tool_use",jobId:o,tool:"Bash",...H?{content:H}:{}},o)}else if(K==="file_change"){let _=O.item.filename||O.item.path;_&&!I.has(_)&&I.set(_,no(n,_)),u.push(_?`Edit ${_.split("/").pop()}`:"Edit");let H=_?vn(n,_)??_:void 0;a?.({type:"tool_use",jobId:o,tool:"Edit",...H?{file:H}:{}},o)}else if(K==="file_read"){let _=O.item.filename||O.item.path;u.push(_?`Read ${_.split("/").pop()}`:"Read");let H=_?vn(n,_)??_:void 0;a?.({type:"tool_use",jobId:o,tool:"Read",...H?{file:H}:{}},o)}else if(K==="web_search")u.push("WebSearch"),a?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(K==="mcp_tool_call"){let _=Pi(O.item);u.push(_.telemetryLabel),a?.({type:"tool_use",jobId:o,tool:_.tool,..._.content?{content:_.content}:{}},o)}}if((W==="item.completed"||W==="item/completed")&&O.item){if(O.item.type==="agent_message"){let K=O.item.text;if(typeof K=="string"&&K){let _=wn(h,K);_&&a?.({type:"delta",jobId:o,text:_},o)}}else if(O.item.type==="reasoning"){let K=O.item.text;typeof K=="string"&&K&&a?.({type:"thinking",jobId:o,text:K},o)}else if(O.item.type==="file_change"&&Array.isArray(O.item.changes))for(let K of O.item.changes){let _=K.path||K.filename,H=K.kind==="add"?"Write":"Edit";if(_){u.push(`${H} ${_.split("/").pop()}`);let G=vn(n,_)??_;a?.({type:"tool_use",jobId:o,tool:H,file:G},o);let fe=K,X=typeof fe.kind=="string"?fe.kind:void 0,oe=dc(X),x=I.get(_),$=no(n,_);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:oe,filePath:_,...x?{before:x}:{},...$?{after:$}:{},...Mi(fe)?{patch:Mi(fe)}:{},...X?{rawKind:X}:{}}),I.set(_,$)}}else if(O.item.type==="command_execution"){let K=typeof O.item.id=="string"?O.item.id:void 0,_=K?p.get(K):void 0,H=typeof O.item.command=="string"?O.item.command:_?.rawCommand,G=H?Ri(H):_?.command,fe=Ai(n);if(lc(_?.beforeWorktree,fe)){let X=[...new Set([..._?.beforeWorktree?.changedFiles??[],...fe?.changedFiles??[]])],oe=typeof O.item.aggregated_output=="string"?dr(O.item.aggregated_output,sc):void 0,x=typeof O.item.exit_code=="number"?O.item.exit_code:O.item.exit_code===null?null:void 0,$=typeof O.item.status=="string"?O.item.status:void 0;g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...H?{rawCommand:H}:{},...G?{command:G}:{},...x!==void 0?{exitCode:x}:{},...$?{status:$}:{},...oe?{output:oe.text}:{},...oe?.truncated?{outputTruncated:!0}:{},..._?.beforeWorktree?{beforeWorktree:_.beforeWorktree}:{},...fe?{afterWorktree:fe}:{},...X.length>0?{touchedFiles:uc(n,X,_?.beforeSnapshots??new Map)}:{}})}K&&p.delete(K)}}W==="turn.failed"&&(j=!0,f=O.error?.message||O.message||"Turn failed")}catch{}});let D=[];S.stderr?.on("data",P=>{D.push(P.toString())}),S.on("close",P=>{m.close(),h.length===0&&E.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...E].join(", ")}`),P!==0&&P!==null&&(j=!0,f=D.join("")||`Codex process exited with code ${P}`),k({sessionId:T,text:h.join(""),success:!j,error:j?f:void 0,editEvents:g.length>0?g:void 0,toolsUsed:u.length>0?u:void 0})}),S.on("error",P=>{j=!0,f=P.message,k({sessionId:T,text:h.join(""),success:!1,error:f,editEvents:g.length>0?g:void 0,toolsUsed:u.length>0?u:void 0})})});return{process:S,result:y}}import{spawn as mc}from"child_process";import{createInterface as fc}from"readline";function Oi(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 Di(o,e){let{prompt:t,projectRoot:n,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:c="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 b=mc(c,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=[],h=[],u=!1,g="",I=!1,p=setTimeout(()=>{I=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},s),j=fc({input:b.stdout}),f=new Set,m=[];j.on("line",D=>{if(D.trim())try{let P=JSON.parse(D),O=xn(P);f.add(O),m.length<5&&gc(O)&&m.push(D.slice(0,800));let W=bn(P,["sessionId","session_id","id"],["session","conversation","thread"]);W&&!k&&(k=W);let K=hc(P,T.length===0);K&&(T.push(K),a?.({type:"delta",jobId:o,text:K},o));let _=yc(P);_&&a?.({type:"thinking",jobId:o,text:_},o);let H=Ic(P);H&&(h.push(H.label),a?.({type:"tool_use",jobId:o,tool:H.tool,...H.file?{file:H.file}:{},...H.content?{content:H.content}:{}},o));let G=wc(P);G&&(u=!0,g=G)}catch{}});let E=[];b.stderr?.on("data",D=>{E.push(D.toString())}),b.on("close",D=>{clearTimeout(p),j.close(),T.length===0&&f.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...f].join(", ")}`),m.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${m.join(`
52
+ `)}`)),I?(u=!0,g=`Timed out after ${Math.round(s/6e4)} minutes`):D!==0&&D!==null&&(u=!0,g=E.join("").trim()||g||`Copilot process exited with code ${D}`);let P=u?Oi(g,i):null;y({sessionId:k,text:T.join(""),success:!u,error:P?.message,errorCode:P?.code,recoverableError:P?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),b.on("error",D=>{clearTimeout(p);let P=Oi(D.message,i);y({sessionId:k,text:T.join(""),success:!1,error:P.message,errorCode:P.code,recoverableError:P.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:b,result:S}}function xn(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 hc(o,e=!1){let t=xn(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"&&cr(o))return o.text;if(typeof o.message=="string"&&cr(o))return o.message;if(typeof o.delta=="string"&&cr(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 gc(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function yc(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 Ic(o){let e=bn(o,["tool","toolName","tool_name","name"]),t=bn(o,["command","cmd"]),n=bn(o,["file","path","filename","filePath"]),r=xn(o);if(t||r.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
53
+ `)[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 wc(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"&&xn(o).toLowerCase().includes("error"))return o.message}function bn(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=bn(r,e);if(i)return i}}function cr(o){let e=xn(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as vc,readFile as bc}from"fs/promises";import{join as lr}from"path";var ro=class{constructor(e){let t=lr(e,".popmelt");this.decisionsDir=lr(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 bc(lr(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 xc,randomUUID as Sc}from"crypto";import{mkdir as pr,readFile as Ni,readdir as Bi,rename as io,stat as Ji,unlink as so,writeFile as ao}from"fs/promises";import{extname as Tc,join as Qe}from"path";var Pc=10080*60*1e3,Rc=600*1e3,kc=3600*1e3;function Mc(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function jc(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var co=class{constructor(e){this.draftsDir=Qe(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Qe(e,".popmelt","artifacts","thread-media")}async stage(e){let t=Sc(),n=Mc(e.mimeType),r=`${t}${n}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:jc(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await pr(this.draftsDir,{recursive:!0});let a=Qe(this.draftsDir,r),c=Qe(this.draftsDir,`${t}.json`),l=`${a}.part`,b=`${c}.part`;return await ao(l,e.data),await io(l,a),await ao(b,JSON.stringify(s,null,2)),await io(b,c),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 Ni(i),a=xc("sha256").update(s).digest("hex"),c=Qe(this.mediaDir,`${a}${Tc(r.contentFile)||".bin"}`);await pr(this.mediaDir,{recursive:!0});try{await Ji(c)}catch{let l=`${c}.part`;await ao(l,s),await io(l,c)}(t[n.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:c}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return t}async sweep(e=Date.now()){let t;try{t=await Bi(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let r=Qe(this.draftsDir,n);if(n.endsWith(".part")){let a=await Ji(r).catch(()=>null);a&&e-a.mtimeMs>kc&&await so(r).catch(()=>{});return}if(!n.endsWith(".json"))return;let i=await this.readManifest(n.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>Rc:e-i.lastSeenAt>Pc)||await Promise.all([so(r).catch(()=>{}),so(Qe(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Bi(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>so(Qe(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Ni(Qe(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await pr(this.draftsDir,{recursive:!0});let t=Qe(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await ao(n,JSON.stringify(e,null,2)),await io(n,t)}};import{randomUUID as Li}from"crypto";import{mkdir as ur,readFile as mr,writeFile as lo}from"fs/promises";import{dirname as fr,join as Xt}from"path";var Xe="[ProjectionWorker]",Ac={version:1,runs:[]},Ec={version:1,updatedAt:0,proposals:[]},_c=12;function Cc(o){return Array.isArray(o)?o.map((e,t)=>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 qi(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 $c(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Oc(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 h=T.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:{},c=Array.isArray(t?.rules)?t.rules:[],l=i.filter(T=>{if(!T||typeof T!="object")return!1;let h=T.id,u=typeof h=="string"?c.find(g=>g&&typeof g=="object"&&g.id===h):void 0;return JSON.stringify(u)!==JSON.stringify(T)}).length,b=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(b[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 Dc(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Nc(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 po(o,e,t){let n=o;for(let i=0;i<e.length-1;i++)n=Nc(n,e[i],e[i+1]);let r=e[e.length-1];n[String(r)]=Dc(t)}function Fi(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 Bc(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 Jc(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 Ui(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=Bc(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?Jc(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var uo=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Xt(e,".popmelt");this.runsPath=Xt(n,"projection-runs.json"),this.legacyRunsPath=Xt(n,"materialization-runs.json"),this.proposalsPath=Xt(n,"projection-queue.json"),this.legacyProposalsPath=Xt(n,"model-proposals.json"),this.modelPath=Xt(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await mr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Cc(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?Fi(t,r):po(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(_c),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=Uc(r,s),c=$c(r,n.totalCandidateDecisionCount,a);t=Li().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:c};await this.persistRun(l);let b=!0,S,y,k;try{let T=`projection-${Date.now()}`,{provider:h,result:u}=this.spawnModelAgent(T,a,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:h},await this.persistRun(l);let g=await u;if(!g.success)b=!1,S=g.error,console.error(`${Xe} ${h} spawn error:`,S);else{let I=Fc(g.text,i);if(I){let p=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of I)po(p,m.path,m.value);Array.isArray(p.rules)&&(p.rules=qi(p.rules));let j=Oc(p,i,s);if(I){let m=[...new Set(I.flatMap(E=>E.decisionIds))];j.coveredDecisionIds=m,j.uncoveredDecisionIds=i.filter(E=>!m.includes(E))}y=j;let f=await this.createModelProposal({decisionIds:i,proposedModel:p,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:y,changes:I});k=f.id,console.log(`${Xe} Created model proposal ${f.id} for ${i.length} decision(s)`)}else b=!1,S="No valid bounded <model-changes> block found in response",console.error(`${Xe} ${S}`)}}catch(T){b=!1,S=T instanceof Error?T.message:String(T),console.error(`${Xe} Error:`,S)}return await this.persistRun({...l,status:b?"proposed":"failed",completedAt:Date.now(),error:S,outputStats:y,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:b,error:S}),{processedIds:i,success:b,error:S,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=qi(e.rules)),await lo(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 ur(fr(this.runsPath),{recursive:!0}),await lo(this.runsPath,JSON.stringify(t,null,2)),t):{...Ac,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??{...Ec,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??[])po(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 c of t)!Array.isArray(c.path)||c.path.length===0||(c.remove?Fi(s,c.path):po(s,c.path,c.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:Li().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"}.`:qc(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 ur(fr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...r})=>r)};await lo(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 ur(fr(this.runsPath),{recursive:!0}),await lo(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 mr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await mr(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,c)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...oo(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Yn(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",...Zn(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 qc(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 Fc(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 c=s;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(S=>typeof S=="string"||typeof S=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let b=Array.isArray(c.decisionIds)?c.decisionIds.filter(S=>typeof S=="string"&&r.has(S)):[];return b.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${a+1}`,path:c.path,value:c.value,decisionIds:b,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return i.length===n.length?i:null}catch{return null}}function Uc(o,e){let t=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
54
+ Kind: ${i.kind}
55
+ Claim: ${i.claim}
56
+ ${i.rationale?`Rationale: ${i.rationale}`:""}
57
+ Subjects: ${i.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
58
+ Authority: ${i.authority.level}/${i.authority.mode}`).join(`
59
+
60
+ `),n=o.map(i=>i.id);return`You are extracting a local design model from accumulated design decisions.
59
61
 
60
62
  ## Instructions
61
63
  1. Review the current model (if any) and the new decisions below.
@@ -127,15 +129,15 @@ Example:
127
129
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
128
130
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
129
131
  - bindings: Tailwind class names (without responsive prefixes) that use this token
130
- Include property and bindings when the decision context has class-level evidence.`}var Zn=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 i of this.listeners)i(e,t,n)}cancelJob(e){let t=this.queue.findIndex(i=>i.id===e);if(t>=0){let[i]=this.queue.splice(t,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):null}let 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}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 Bd}from"child_process";import{readFile as wr}from"fs/promises";import{homedir as ei}from"os";import{join as et}from"path";var ti=/popmelt/i;function Pt(){return{found:!1,name:null,scope:null,disabled:!1}}function Ft(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function fn(o){for(let e of Object.keys(o))if(ti.test(e))return e;return null}async function eo(o){try{let e=await wr(o,"utf-8");return JSON.parse(e)}catch{return null}}async function ni(o){let e=ei(),t=await eo(et(e,".claude.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=fn(i.mcpServers);if(r)return Ft(r,"user")}if(i.projects&&typeof i.projects=="object"){let s=i.projects[o];if(s&&typeof s=="object"){let d=s;if(d.mcpServers&&typeof d.mcpServers=="object"){let c=fn(d.mcpServers);if(c){let l=Array.isArray(d.disabledMcpjsonServers)&&d.disabledMcpjsonServers.some(w=>ti.test(w));return Ft(c,"project",l)}}}}}let n=await eo(et(o,".mcp.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=fn(i.mcpServers);if(s){let d=await Ir(o,s);return Ft(s,"mcp.json",d)}}let r=fn(i);if(r&&r!=="mcpServers"){let s=await Ir(o,r);return Ft(r,"mcp.json",s)}}return Pt()}async function Ir(o,e){let t=et(o,".claude","settings.local.json"),n=await eo(t);if(n&&typeof n=="object"){let i=n;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var Jd=/^\[mcp_servers\.([^\]]+)\]/;function Ld(o){let e=o.split(`
131
- `),t=[],n=null;for(let i of e){let r=i.match(Jd);r?(n&&t.push({name:n.name,body:n.bodyLines.join(`
132
- `)}),n={name:r[1],bodyLines:[]}):i.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
133
- `)}),n=null):n&&n.bodyLines.push(i)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
134
- `)}),t}function qd(o){return/enabled\s*=\s*false/i.test(o)}async function oi(o){let e=process.env.CODEX_HOME||et(ei(),".codex"),t=await vr(et(e,"config.toml"),"user");if(t.found)return t;let n=await vr(et(o,".codex","config.toml"),"project");return n.found?n:Pt()}async function ii(o,e="copilot"){let t=await Ud(e);if(t.found)return t;let n=process.env.COPILOT_HOME||et(ei(),".copilot"),i=await Zo(et(n,"mcp-config.json"),"user");if(i.found)return i;let r=await Zo(et(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Zo(et(o,".github","mcp.json"),"mcp.json");return s.found?s:Pt()}async function Ud(o){try{let e=await new Promise((t,n)=>{Bd(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return br(JSON.parse(e),"user")}catch{return Pt()}}async function Zo(o,e){let t=await eo(o);return br(t,e)}function br(o,e){if(!o||typeof o!="object")return Pt();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,i=fn(n);return i?Ft(i,e):Pt()}async function vr(o,e){try{let t=await wr(o,"utf-8"),n=Ld(t);for(let i of n)if(ti.test(i.name)){let r=qd(i.body);return Ft(i.name,e,r)}}catch{}return Pt()}import{execFile as xr}from"child_process";import{mkdir as Fd,readFile as Sr,writeFile as Tr}from"fs/promises";import{homedir as Pr}from"os";import{dirname as zd,join as ri}from"path";var si="https://mcp.popmelt.com/mcp";async function kr(o=si){let e=ri(Pr(),".claude.json"),t;try{let i=await Sr(e,"utf-8");t=JSON.parse(i)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let i of Object.keys(n))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:o},await Tr(e,JSON.stringify(t,null,2)+`
135
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Rr(o=si){let e=process.env.CODEX_HOME||ri(Pr(),".codex"),t=ri(e,"config.toml"),n;try{n=await Sr(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Fd(zd(t),{recursive:!0});let i=`
132
+ Include property and bindings when the decision context has class-level evidence.`}var mo=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}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 zc}from"child_process";import{readFile as Hi}from"fs/promises";import{homedir as gr}from"os";import{join as tt}from"path";var yr=/popmelt/i;function At(){return{found:!1,name:null,scope:null,disabled:!1}}function Yt(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function Sn(o){for(let e of Object.keys(o))if(yr.test(e))return e;return null}async function fo(o){try{let e=await Hi(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Ir(o){let e=gr(),t=await fo(tt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=Sn(r.mcpServers);if(i)return Yt(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 c=Sn(a.mcpServers);if(c){let l=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(b=>yr.test(b));return Yt(c,"project",l)}}}}}let n=await fo(tt(o,".mcp.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=Sn(r.mcpServers);if(s){let a=await zi(o,s);return Yt(s,"mcp.json",a)}}let i=Sn(r);if(i&&i!=="mcpServers"){let s=await zi(o,i);return Yt(i,"mcp.json",s)}}return At()}async function zi(o,e){let t=tt(o,".claude","settings.local.json"),n=await fo(t);if(n&&typeof n=="object"){let r=n;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var Vc=/^\[mcp_servers\.([^\]]+)\]/;function Hc(o){let e=o.split(`
133
+ `),t=[],n=null;for(let r of e){let i=r.match(Vc);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
134
+ `)}),n={name:i[1],bodyLines:[]}):r.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
135
+ `)}),n=null):n&&n.bodyLines.push(r)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
136
+ `)}),t}function Wc(o){return/enabled\s*=\s*false/i.test(o)}async function wr(o){let e=process.env.CODEX_HOME||tt(gr(),".codex"),t=await Vi(tt(e,"config.toml"),"user");if(t.found)return t;let n=await Vi(tt(o,".codex","config.toml"),"project");return n.found?n:At()}async function vr(o,e="copilot"){let t=await Gc(e);if(t.found)return t;let n=process.env.COPILOT_HOME||tt(gr(),".copilot"),r=await hr(tt(n,"mcp-config.json"),"user");if(r.found)return r;let i=await hr(tt(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await hr(tt(o,".github","mcp.json"),"mcp.json");return s.found?s:At()}async function Gc(o){try{let e=await new Promise((t,n)=>{zc(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return Wi(JSON.parse(e),"user")}catch{return At()}}async function hr(o,e){let t=await fo(o);return Wi(t,e)}function Wi(o,e){if(!o||typeof o!="object")return At();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=Sn(n);return r?Yt(r,e):At()}async function Vi(o,e){try{let t=await Hi(o,"utf-8"),n=Hc(t);for(let r of n)if(yr.test(r.name)){let i=Wc(r.body);return Yt(r.name,e,i)}}catch{}return At()}import{execFile as Gi}from"child_process";import{mkdir as Kc,readFile as Ki,writeFile as Qi}from"fs/promises";import{homedir as Xi}from"os";import{dirname as Qc,join as br}from"path";var xr="https://mcp.popmelt.com/mcp";async function Yi(o=xr){let e=br(Xi(),".claude.json"),t;try{let r=await Ki(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 Qi(e,JSON.stringify(t,null,2)+`
137
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Zi(o=xr){let e=process.env.CODEX_HOME||br(Xi(),".codex"),t=br(e,"config.toml"),n;try{n=await Ki(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Kc(Qc(t),{recursive:!0});let r=`
136
138
  [mcp_servers.popmelt]
137
139
  url = "${o}"
138
- `;return await Tr(t,n+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ar(o=si,e="copilot"){let t=await Wd(e);if(Hd(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,i)=>{xr(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);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 Wd(o){try{let e=await new Promise((t,n)=>{xr(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return JSON.parse(e)}catch{return null}}function Hd(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))}var to=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 i=this.leases.get(e),r={id:e,ownerPid:t,createdAt:i?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}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,i]of this.leases)i.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()}};var Gd=String.raw`
140
+ `;return await Qi(t,n+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function es(o=xr,e="copilot"){let t=await Xc(e);if(Yc(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,r)=>{Gi(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 Xc(o){try{let e=await new Promise((t,n)=>{Gi(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 Yc(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))}var ho=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()}};var Zc=String.raw`
139
141
  (() => {
140
142
  const hidden = [];
141
143
  const visit = (root) => {
@@ -156,7 +158,7 @@ url = "${o}"
156
158
  visit(document);
157
159
  window.__popmeltNativeCaptureHidden = hidden;
158
160
  })()
159
- `,Vd=String.raw`
161
+ `,el=String.raw`
160
162
  (() => {
161
163
  for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
162
164
  if (value) element.style.setProperty('visibility', value, priority);
@@ -164,22 +166,20 @@ url = "${o}"
164
166
  }
165
167
  delete window.__popmeltNativeCaptureHidden;
166
168
  })()
167
- `;function no(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Kd(o,e){let t=no(e);if(!t)return null;let n=new URL(t),i=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&no(s.url)),r=i.find(s=>no(s.url)===t);return r||(i.find(s=>{let d=new URL(no(s.url));return d.origin===n.origin&&d.pathname===n.pathname})??null)}function Qd(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 Xd(o){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",o).href,i=await fetch(n,{signal:e.signal});if(!i.ok)throw new Error(`CDP discovery returned ${i.status}`);let r=await i.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Yd(o){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let i=new e(o,{handshakeTimeout:1e3}),r=()=>{i.off("error",s),t(i)},s=d=>{i.off("open",r),n(d)};i.once("open",r),i.once("error",s)})}function Zd(o){let e=1,t=new Map;return o.on("message",n=>{let i;try{i=JSON.parse(String(n))}catch{return}if(!i.id)return;let r=t.get(i.id);r&&(t.delete(i.id),clearTimeout(r.timeout),i.error?r.reject(new Error(i.error.message||`CDP error ${i.error.code??""}`.trim())):r.resolve(i.result??{}))}),o.on("close",()=>{for(let[n,i]of t)clearTimeout(i.timeout),i.reject(new Error("CDP connection closed")),t.delete(n)}),(n,i={})=>new Promise((r,s)=>{let d=e++,c=setTimeout(()=>{t.delete(d),s(new Error(`CDP ${n} timed out`))},4e3);t.set(d,{resolve:r,reject:s,timeout:c}),o.send(JSON.stringify({id:d,method:n,params:i}),l=>{l&&(clearTimeout(c),t.delete(d),s(l))})})}async function jr(o,e){let t=Qd(e.clip),n=await Xd(o),i=Kd(n,e.pageUrl);if(!i?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Yd(i.webSocketDebuggerUrl),s=Zd(r),d=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Gd,returnByValue:!0}),d=!0;let c=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 c.data=="string"?c.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{d&&await s("Runtime.evaluate",{expression:Vd,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as Fr,readFile as In,writeFile as zr}from"fs/promises";import{join as Gt}from"path";var ec=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ai(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function oo(o){return new Set(ai(o).split(" ").filter(e=>e.length>2&&!ec.has(e)))}function Mr(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 tc(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 nc(o,e){let t=new Map,n=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(ai).filter(Boolean),r=oo([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 d;for(let c of tc(s)){let l=ai(c.value);for(let b of i){let k=l===b?95:l.includes(b)||b.includes(l)?75:0;k>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:c.by,score:k})}let R=["/","#","[","]","="].some(b=>c.value.includes(b))?0:Math.round(Mr(oo(l),r)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&t.set(s.id,d)}return t}function oc(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)),i=e.filter(s=>s.iterationIds.some(d=>t.has(d))||s.sourceRefs.some(d=>d.kind==="thread"&&n.has(d.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function ic(o){return Math.ceil(JSON.stringify(o).length/4)}function di(o,e){let t=o.records.filter(p=>p.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(p=>{if(p.recordType!=="proposal"||i&&!i.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let g=[...o.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===p.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return g?g.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||g.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||g.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||g.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||g.resurfaceWhen.includes("after_date")&&!!(g.revisitAfter&&Date.parse(n)>=Date.parse(g.revisitAfter)):!1}),s=o.records.filter(p=>p.recordType==="implementation_attempt"),d=nc(t,e),c=[...d.values()].sort((p,g)=>g.score-p.score),l=oo([e.action,e.text].filter(Boolean).join(" ")),w=r.flatMap(p=>{let g=p.subjects.map(h=>d.get(h.subjectId)).filter(h=>!!h),v=Math.max(0,...g.map(h=>h.score)),u=Math.round(Mr(oo(p.claim),l)*35),M=v+u;return M>=50?[{proposal:p,proposalMatches:g,score:M}]:[]}).sort((p,g)=>g.score-p.score||p.proposal.id.localeCompare(g.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),k=[],S=0;for(let p of w){if(k.length>=R)break;let g=p.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:o.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(M=>M.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:M,...h})=>h)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(M=>M.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:oc(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:g},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...g]},u={...v,estimatedTokens:ic(v)};if(S+u.estimatedTokens>b)break;k.push(u),S+=u.estimatedTokens}let f=Math.max(0,w.length-k.length);return{packets:k,subjectMatches:c.map(({score:p,...g})=>g),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:f,maxEstimatedTokens:b,estimatedTokens:S},uncertainty:d.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var rc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ci(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function io(o){return new Set(ci(o).split(" ").filter(e=>e.length>2&&!rc.has(e)))}function Er(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 sc(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(ci).filter(Boolean),i=io([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{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 c){let w=ci(l.value);for(let k of n){let S=w===k?95:w.includes(k)||k.includes(w)?75:0;S>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:l.by,score:S})}let b=["/","#","[","]","="].some(k=>l.value.includes(k))?0:Math.round(Er(io(w),i)*55);b>=30&&b>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}d&&r.push(d)}return r.sort((s,d)=>d.score-s.score||s.subjectId.localeCompare(d.subjectId))}function ac(o){return Math.ceil(JSON.stringify(o).length/4)}function zt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function dc(o,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!t.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),i=n.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function cc(o,e,t){let n=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===o)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),i=t.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===o),r=n[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:n.map(d=>d.id)}}function _r(o,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),i=o.records.filter(m=>m.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"),d=r?s.filter(m=>r.has(m.id)):s,c=o.records.filter(m=>m.recordType==="implementation_attempt"),l=o.records.filter(m=>m.recordType==="verification_attempt"),w=o.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),R=o.records.filter(m=>m.recordType==="evidence"),b=o.records.filter(m=>m.recordType==="model_entry"),k=sc(i,e),S=new Map(k.map(m=>[m.subjectId,m.score])),f=io([e.action,e.text].filter(Boolean).join(" ")),p=d.flatMap(m=>{let E=Math.max(0,...m.subjects.map(C=>S.get(C.subjectId)??0)),D=Math.round(Er(io(m.claim),f)*35),T=E+D;return T>=50?[{decision:m,score:T}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of p.slice(0,n))g.set(m.decision.id,m.decision);for(let m of o.relationships){if(!zt(m,"excepts")&&!zt(m,"contradicts"))continue;let E=s.find(T=>T.id===m.from.entityId),D=s.find(T=>T.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<n&&g.set(E.id,E),g.size<n&&g.set(D.id,D))}let v=[...g.values()],u=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&g.has(m.from.entityId)&&g.has(m.to.entityId),M=(m,E=!1)=>{let D=new Set(m.map(B=>B.id)),T=w.filter(B=>B.target.entityType==="decision"&&D.has(B.target.entityId)),C=new Set(o.relationships.filter(B=>zt(B,"excepts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),X=o.relationships.filter(B=>zt(B,"contradicts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).map(B=>({id:B.id,decisionIds:[B.from.entityId,B.to.entityId],unresolvedQuestion:B.reason,expansionRefs:[{kind:"record",id:B.id}]})),G=new Set(X.flatMap(B=>B.decisionIds)),Y=R.filter(B=>B.sourceRefs.some(V=>V.kind==="record"&&D.has(V.id))||o.relationships.some(V=>V.relationshipType==="supports"&&V.from.entityType==="evidence"&&V.from.entityId===B.id&&V.to.entityType==="decision"&&D.has(V.to.entityId))),x=Math.max(0,p.length-m.length),Q=o.relationships.some(B=>zt(B,"contradicts")&&u(B)&&(!D.has(B.from.entityId)||!D.has(B.to.entityId))),L=E||x>0||Q,K=[];k.length===0&&(e.subjectHints?.length??0)>0?K.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):m.length===0&&K.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),X.length&&K.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:X.flatMap(B=>B.expansionRefs)}),Y.some(B=>B.availability!=="available")&&K.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Y.map(B=>({kind:"record",id:B.id}))}),L&&K.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let H={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:B,...V})=>V),modelEntries:b.filter(B=>B.decisionIds.some(V=>D.has(V))).map(B=>({id:B.id,key:B.key,value:B.value,decisionIds:B.decisionIds})),decisions:m.map(B=>({id:B.id,kind:B.kind,claim:B.claim,subjectIds:B.subjects.map(V=>V.subjectId),authority:B.authority,effectiveState:G.has(B.id)?"conflicted":C.has(B.id)?"excepted":"active",freshness:T.filter(V=>V.target.entityId===B.id).map(V=>V.signalType),expansionRef:{kind:"record",id:B.id}})),conflicts:X,uncertainties:K,implementation:m.map(B=>dc(B.id,c)),verification:m.map(B=>cc(B.id,l,T)),evidence:Y.map(B=>({evidenceId:B.id,summary:B.summary,availability:B.availability,sourceRefs:B.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:x,omittedEvidenceCount:0,conflictsComplete:!Q}};return H.budget.estimatedTokens=ac(H),H},h=M(v);for(;h.budget.estimatedTokens>t&&v.length>0;){let m=v.pop(),E=o.relationships.filter(D=>zt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);v=v.filter(D=>!E.includes(D.id)),h=M(v,!0)}return h}var lc=/^[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 lc.test(o)}function pc(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 li(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Me(o,e,t){Wt(t)||oe(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&oe(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function kt(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 uc={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"])},mc=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function fc(o,e,t){Me(o,`${t}.id`,e.id),Me(o,`${t}.projectId`,e.projectId),Me(o,`${t}.participantId`,e.participantId),Me(o,`${t}.entity.entityId`,e.entity.entityId),Qe(o,`${t}.createdAt`,e.createdAt),kt(o,`${t}.authority`,e.authority);let n=uc[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(i)&&oe(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(mc.has(r)&&(kt(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&&Qe(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function hc(o,e,t,n){Me(o,`${t}.id`,e.id),Me(o,`${t}.projectId`,e.projectId),Me(o,`${t}.participantId`,e.participantId),Qe(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"&&(kt(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"&&li(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."),Qe(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&oe(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&oe(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&oe(o,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(o,`${t}.concreteBindings[${r}].createdAt`,i.createdAt),Qe(o,`${t}.concreteBindings[${r}].updatedAt`,i.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"&&(Qe(o,`${t}.appliedAt`,e.appliedAt),kt(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(i=>!i.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&&li(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&li(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function gc(o,e,t){if(Me(o,`${t}.id`,e.id),Me(o,`${t}.projectId`,e.projectId),Me(o,`${t}.participantId`,e.participantId),Me(o,`${t}.from.entityId`,e.from.entityId),Me(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."),Qe(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 i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&oe(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?oe(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&kt(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 Rt(o){let e=[];Me(e,"manifest.projectId",o.manifest.projectId),Qe(e,"manifest.createdAt",o.manifest.createdAt),Qe(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(f,p)=>{let g=t.get(f);g?oe(e,p,"duplicate_id",`ID is already used at ${g}.`):t.set(f,p)};o.records.forEach((f,p)=>{let g=`records[${p}]`;n(f.id,g),hc(e,f,g,o.manifest.projectId)}),o.events.forEach((f,p)=>{let g=`events[${p}]`;n(f.id,g),fc(e,f,g),f.projectId!==o.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((f,p)=>{let g=`relationships[${p}]`;n(f.id,g),gc(e,f,g),f.projectId!==o.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((f,p)=>{n(f.id,`artifacts[${p}]`),Me(e,`artifacts[${p}].id`,f.id)}),o.tombstones.forEach((f,p)=>{let g=`tombstones[${p}]`;n(f.id,g),Me(e,`${g}.id`,f.id),Me(e,`${g}.objectId`,f.objectId),Me(e,`${g}.deletedById`,f.deletedById),Qe(e,`${g}.deletedAt`,f.deletedAt),kt(e,`${g}.authority`,f.authority,!0)});let i=new Set(o.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(o.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{if(f.storeId)return;let g=`${f.entityType}:${f.entityId}`;!i.has(g)&&!r.has(g)&&oe(e,p,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};o.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),o.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let d=new Set(o.artifacts.map(f=>f.id)),c=(f,p)=>{d.has(f)||oe(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,g)=>{!i.has(`${f}:${p}`)&&!r.has(`${f}:${p}`)&&oe(e,g,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};o.records.forEach((f,p)=>{let g=`records[${p}]`;switch(f.recordType){case"authority_grant":l("participant",f.granteeId,`${g}.granteeId`),l("participant",f.grantedById,`${g}.grantedById`),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`));break;case"observation":f.captureContext.subjectIds.forEach((v,u)=>l("subject",v,`${g}.captureContext.subjectIds[${u}]`)),f.captureContext.artifactIds.forEach((v,u)=>c(v,`${g}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":f.subjects.forEach((v,u)=>l("subject",v.subjectId,`${g}.subjects[${u}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((v,u)=>c(v,`${g}.messageArtifactIds[${u}]`)),f.resultRefs.forEach((v,u)=>s(v,`${g}.resultRefs[${u}]`));break;case"iteration":f.threadIds.forEach((v,u)=>l("thread",v,`${g}.threadIds[${u}]`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"evidence":f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"advisory_explanation":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${g}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((v,u)=>l("iteration",v,`${g}.iterationIds[${u}]`)),f.coverageClaims.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverageClaims[${u}].decisionId`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${g}.replacesSpecId`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),(f.dependencies??[]).forEach((v,u)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${g}.dependencies[${u}].subjectId`)}),(f.scenarios??[]).forEach((v,u)=>{v.subjectIds?.forEach((M,h)=>l("subject",M,`${g}.scenarios[${u}].subjectIds[${h}]`))}),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${g}.evalSpecId`),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;case"model_entry":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`));break;case"model_projection":kt(e,`${g}.authority`,f.authority,!0),l("participant",f.appliedById,`${g}.appliedById`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.entryIds.forEach((v,u)=>l("model_entry",v,`${g}.entryIds[${u}]`)),f.coverage.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverage[${u}].decisionId`));break;case"freshness_signal":s(f.target,`${g}.target`),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;default:break}});let w=new Map(o.events.map(f=>[f.id,f])),R=new Map(o.records.map(f=>[`${f.recordType}:${f.id}`,f])),b=new Map;o.events.forEach((f,p)=>{let g=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,v=b.get(g)??new Set;v.add(f.toState),b.set(g,v),v.size>1&&oe(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(o.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),S=(f,p,g,v,u)=>{if(f.level!=="delegate"||!f.grantId)return;let M=k.get(f.grantId);if(!M){oe(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&oe(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(g);(h<Date.parse(M.startsAt)||M.endsAt&&h>Date.parse(M.endsAt)||M.revokedAt&&h>=Date.parse(M.revokedAt))&&oe(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&v.length&&!v.every(m=>M.subjectIds.includes(m))&&oe(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of o.records)f.recordType==="decision"&&S(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);o.events.forEach((f,p)=>{let g=R.get(`${f.entity.entityType}:${f.entity.entityId}`),v=g&&"subjects"in g?g.subjects.map(u=>u.subjectId):[];S(f.authority,f.participantId,f.createdAt,v,`events[${p}].authority`)}),o.relationships.forEach((f,p)=>{if(!f.authority)return;let g=[f.from,f.to].flatMap(v=>{let u=R.get(`${v.entityType}:${v.entityId}`);return u&&"subjects"in u?u.subjects.map(M=>M.subjectId):[]});S(f.authority,f.participantId,f.createdAt,g,`relationships[${p}].authority`)});for(let f of o.records){if(f.recordType!=="decision")continue;let p=w.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&oe(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&oe(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${f.proposalId}`)||oe(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(o.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===f.id)||oe(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(o.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===f.id&&v.toState==="revoked"&&!!v.reason?.trim())||oe(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of o.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;o.records.some(g=>g.recordType==="decision"&&g.proposalId===f.id)||oe(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return pc(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 Cr(o,e,t,n,i){return{id:i,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 yc(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 ro(o,e){let t=[],n=o.records.find(r=>r.recordType==="proposal"&&r.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 r of yc(e))Wt(r)||t.push({code:"invalid_generated_id",message:`${r} 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 r={...hn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Cr(o,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],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 r={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."},d={...hn(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Cr(o,r,e,d.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:r.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:[r,c],events:[s,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...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:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let i={...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:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}import{createHash as Ic}from"crypto";import{readFile as vc,readdir as wc,realpath as bc}from"fs/promises";import{join as gn,relative as xc}from"path";var Sc=["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 ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function $r(...o){return o.find(e=>!!e?.trim())?.trim()}function le(o,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ic("sha256").update(`${o}\0${e}\0${t}`).digest("hex"),d=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${d}${s.slice(4,7)}-${s.slice(7,19)}`}async function pi(o,e){try{return JSON.parse(await vc(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function Tc(o){let e=Ht(o);if(!e)return 0;let t=0,n=i=>{let r=Ht(i);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let i of Object.values(e))n(i);return t}function Pc(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 bc(o.projectRoot).catch(()=>o.projectRoot),n=gn(t,".popmelt"),i=await pi(gn(n,"threads.json"),e),r=await pi(gn(n,"model.json"),e),s=Ht(i),d=Ht(s?.threads)??{},c=Object.entries(d).map(([V,W])=>({key:V,value:Ht(W)})).filter(V=>!!V.value),l=gn(n,"decisions"),w=await wc(l).catch(()=>[]),R=[];for(let V of w.filter(W=>W.endsWith(".json")).sort()){let W=Ht(await pi(gn(l,V),e));W&&R.push({file:V,value:W})}let b=c.flatMap(({value:V})=>[V.createdAt,V.updatedAt]).filter(V=>typeof V=="number"&&Number.isFinite(V)),k=b.length?Math.min(...b):0,S=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 f=le(S,"project",S,k),p=le(S,"participant","legacy-owner",k),g=le(S,"participant","legacy-agent",k),v=le(S,"subject","project",k),u=ze(Math.max(k,...b)),M=[],h=[],m=new Map,E=new Map,D=new Map(R.map(V=>[V.value.id??V.file.replace(/^d-|\.json$/g,""),V.value])),T=new Map,C=(V,W,ee,ke,Je)=>{let ue=m.get(ee);if(ue)return ue;let Ce=le(S,"artifact",V,ke);return h.push({id:Ce,kind:W,mediaType:Je,location:ee,availability:"available"}),m.set(ee,Ce),Ce};for(let{file:V,value:W}of R){let ee=W.id??V.replace(/^d-|\.json$/g,""),ke=W.createdAt??k,Je=[C(`${ee}:envelope`,"other",`.popmelt/decisions/${V}`,ke,"application/json")];W.screenshotPath&&Je.push(C(`${ee}:screenshot`,"screenshot",`.popmelt/${W.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,W.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,Ce]of(W.pastedImagePaths??[]).entries())Je.push(C(`${ee}:image:${ue}`,"image",Ce,ke));T.set(ee,Je)}let z=(V,W,ee)=>({id:V,schemaVersion:1,projectId:f,createdAt:u,participantId:W,sourceRefs:ee}),X=(V,W)=>{M.push(W);let ee=E.get(V)??[];ee.push(W.id),E.set(V,ee)},G=[{...z(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...z(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];M.push(...G),M.push({...z(v,p,[]),recordType:"subject",subjectType:"project",label:xc(process.cwd(),t)||t,aliases:[],locators:[{id:le(S,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:ze(k),sourceRefs:[]}]});let Y=new Map,x=(V,W)=>{let ee=Y.get(V);if(ee)return ee;let ke=le(S,"subject",V,W),Je={...z(ke,p,[{kind:"external",id:V}]),createdAt:ze(W),recordType:"subject",subjectType:"element",label:V,aliases:[],locators:[{id:le(S,"locator",V,W),kind:"dom_selector",value:V,status:"current",validFrom:ze(W),sourceRefs:[{kind:"external",id:V}]}]};return M.push(Je),Y.set(V,ke),ke};for(let{key:V,value:W}of c){let ee=W.id??V,ke=W.createdAt??k,Je=le(S,"thread",ee,ke),ue={kind:"thread",id:ee},Ce=[],gt=[],on=Array.isArray(W.messages)?W.messages:[],Re,nt,yt=0;on.forEach((be,lt)=>{let $e=be.timestamp??ke,ot=le(S,"artifact",`${ee}:message:${lt}`,$e);if(Ce.push(ot),h.push({id:ot,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,ot),be.screenshotPath&&C(`${ee}:message:${lt}:screenshot`,"screenshot",be.screenshotPath,$e),be.role==="human"){Re=be;let Le=be.feedbackSummary??be.replyToQuestion;if(Le?.trim()){let qe=le(S,"observation",`${ee}:${lt}`,$e),Xe=W.elementIdentifiers??[],Mt={...z(qe,p,[ue,{kind:"message",id:ot}]),createdAt:ze($e),recordType:"observation",state:"open",statement:Le,captureContext:{subjectIds:Xe.map(wt=>x(wt,ke)),artifactIds:[ot]},resolvedByIds:[]};X(ee,Mt),nt=qe,gt.push({entityType:"observation",entityId:qe})}return}if(be.role!=="assistant")return;let pt=be.jobId??`${ee}:${lt}`,ut=le(S,"iteration",pt,$e),vt=D.get(pt),_o=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",Co={...z(ut,g,[ue,{kind:"message",id:ot},...(T.get(pt)??[]).map(Le=>({kind:"artifact",id:Le}))]),createdAt:ze($e),recordType:"iteration",threadIds:[Je],startedAt:ze(Re?.timestamp,$e),completedAt:ze($e),requestSummary:$r(Re?.feedbackSummary,Re?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:_o,execution:{provider:be.provider??vt?.provider,model:be.model??vt?.model,sessionId:be.sessionId??vt?.sessionId},artifactIds:[ot,...T.get(pt)??[]]};X(ee,Co),gt.push({entityType:"iteration",entityId:ut});let rn=be.resolutions??vt?.resolutions??[];for(let[Le,qe]of rn.entries()){if(qe.status!=="resolved"||!qe.summary?.trim())continue;let Xe=W.elementIdentifiers??[],Mt=(Xe.length?Xe:[t]).map(_n=>({subjectId:_n===t?v:x(_n,ke),role:"governed"})),wt=le(S,"proposal",`${pt}:${qe.annotationId??"resolution"}:${Le}`,$e),$o={...z(wt,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"proposal",state:"pending",claim:qe.summary,subjects:Mt,subjectSemantics:Mt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$r(Re?.feedbackSummary,Re?.replyToQuestion,qe.summary),iterationId:ut,inferredById:g}};X(ee,$o),gt.push({entityType:"proposal",entityId:wt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ee,message:`Proposal ${wt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(rn.some(Le=>Le.status==="resolved")||vt?.gitDiff){let Le=le(S,"implementation",pt,$e),qe={...z(Le,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"implementation_attempt",state:"completed",iterationIds:[ut],coverageClaims:[],summary:rn.map(Xe=>Xe.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};X(ee,qe),gt.push({entityType:"implementation_attempt",entityId:Le}),yt+=1}nt&&(nt=void 0)});let It=on.at(-1),En={...z(Je,p,[ue]),createdAt:ze(ke),recordType:"thread",state:It?.question?"open":"resolved",messageArtifactIds:Ce,outcome:It?.question?"question_unresolved":yt?"implementation_only":"no_outcome",resultRefs:gt};M.push(En),E.set(ee,[Je,...E.get(ee)??[]])}let Q=Tc(r);Q&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${Q} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:f,createdAt:ze(k),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:h,tombstones:[]},K=Rt(L),B=(o.proofCaseIds??Sc).map(V=>({legacyId:V,threadFound:c.some(({key:W,value:ee})=>(ee.id??W)===V),decisionEnvelopeFound:D.has(V),recordIds:E.get(V)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((V,W)=>V+(W.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:Q,artifactsReferenced:h.length},imported:Pc(M),unresolvedAcceptance:e.filter(V=>V.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:B,issues:e,schemaIssues:K.issues}}}import{createHash as kc}from"crypto";import{mkdir as Or,open as ui,readFile as mi,readdir as Rc,rename as Ac,unlink as fi}from"fs/promises";import{join as st}from"path";var jc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function ao(o){return kc("sha256").update(JSON.stringify(o)).digest("hex")}function Dr(o){return ao(o)}function Nr(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 i=o.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(i<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=o.records[i];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);o.records[i]=structuredClone(n)}for(let n of e.projectionUpdates){let i=o.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(i.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${i.state}`);i.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 Mc(o,e,t){return Nr(structuredClone(o),e,t)}async function At(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await ui(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
168
- `,"utf8"),await n.sync()}finally{await n.close()}try{await Ac(t,o)}catch(i){throw await fi(t).catch(()=>{}),i}}async function so(o){return JSON.parse(await mi(o,"utf8"))}var co=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=st(e,".popmelt","memory"),this.journalDir=st(this.memoryDir,"journal"),this.manifestPath=st(this.memoryDir,"manifest.json"),this.checkpointPath=st(this.memoryDir,"checkpoint.json"),this.lockPath=st(this.memoryDir,"writer.lock")}async initialize(e){let t=Rt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Or(this.journalDir,{recursive:!0});try{throw await mi(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 mi(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=ao(e),i={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await At(this.checkpointPath,i),await At(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await At(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=ao(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await At(st(this.memoryDir,n),i),e.manifest.checkpoint={file:n,sequence:i.sequence,hash:t},await At(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.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 i=n.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Dr(r)},d=Mc(n.bundle,e,t.committedAt),c=Rt(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(i).padStart(12,"0")}-${t.transactionId}.json`;return await At(st(this.journalDir,l),s),n.manifest.head={sequence:i,hash:s.hash},n.manifest.updatedAt=t.committedAt,await At(this.manifestPath,n.manifest),{bundle:d,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...jc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await so(this.manifestPath),t=await so(st(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!==ao(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await Rc(this.journalDir),i=n.filter(b=>b.endsWith(".tmp")),s=n.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>t.sequence),d=structuredClone(t.bundle),c=t.sequence,l=t.journalHash??null,w=new Set;for(let b of s){let k=await so(st(this.journalDir,b)),{hash:S,...f}=k;if(S!==Dr(f))throw new Error(`Journal hash mismatch: ${b}`);if(k.sequence!==c+1)throw new Error(`Journal sequence gap at ${b}`);if(k.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(w.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);Nr(d,k.mutation,k.committedAt),c=k.sequence,l=k.hash,w.add(k.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=Rt(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:w,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:c,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Or(this.memoryDir,{recursive:!0});let t;try{t=await ui(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let i=await so(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await fi(this.lockPath),t=await ui(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await fi(this.lockPath).catch(()=>{})}}};import{randomBytes as Ec}from"crypto";function xe(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=Ec(10).toString("hex"),i=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${i}${n.slice(4,7)}-${n.slice(7,19)}`}var _c=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Br(o,e){let t=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),n=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=_c(),l=c.records,w=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));w||(w={id:le(i,"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(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let R=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let M=o.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===u&&m.status==="current"));M||(M={id:le(i,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(i,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),R.push(M)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=o.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===u&&m.status==="current"));M||(M={id:le(i,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(i,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),R.push(M)}let b=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),k;if(b.length>0){k=le(i,"live-observation",r,e.createdAt);let u={id:k,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:R.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let S=le(i,"live-iteration",r,e.completedAt),f={id:S,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(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[w.id],startedAt:s,completedAt:d,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(f);let p=[],g=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),v=R.length>0?R:o.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(b.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,M]of b.entries()){let h=le(i,"live-proposal",`${r}:${u}`,e.completedAt),m=v.map(D=>({subjectId:D.id,role:"governed"})),E={id:h,schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:S},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:M.claim.trim(),rationale:M.rationale?.trim()||void 0,proposedKind:M.proposedKind,subjects:m,subjectSemantics:m.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:M.sourceText?.trim()||e.requestSummary,iterationId:S,inferredById:n.id}};l.push(E),p.push(h)}if(g.length>0){let u=new Set(e.governingDecisionIds??[]),M=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&u.has(m.id)),h={id:le(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:S}],recordType:"implementation_attempt",state:"completed",iterationIds:[S],coverageClaims:M.map(m=>({decisionId:m.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${g.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:S}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};l.push(h)}return{mutation:c,iterationId:S,proposalIds:p,observationId:k}}import{createHash as Cc}from"crypto";import{mkdir as $c,open as Oc,readFile as Dc,rename as Nc,unlink as Bc}from"fs/promises";import{join as Jr}from"path";function Lr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qr(o){return Cc("sha256").update(JSON.stringify(o)).digest("hex")}async function Jc(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Oc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
169
- `,"utf8"),await n.sync()}finally{await n.close()}try{await Nc(t,o)}catch(i){throw await Bc(t).catch(()=>{}),i}}function Lc(o,e,t=new Date().toISOString()){let n={},i={},r={},s=(c,l,w)=>{let R=c[l]??=[];R.includes(w)||R.push(w)};for(let c of o.records)if(c.recordType==="subject"){let l=c;for(let w of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=Lr(w);R&&s(n,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)s(i,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)s(r,l.subjectId,c.id);let d={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...d,checksum:qr(d)}}function Ur(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[Lr(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 lo=class{constructor(e){this.indexDir=Jr(e,".popmelt","memory","indexes"),this.indexPath=Jr(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let i=JSON.parse(await Dc(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===t.sequence&&i.journalHead.hash===t.hash&&r===qr(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let n=Lc(e,t);return await $c(this.indexDir,{recursive:!0}),await Jc(this.indexPath,n),n}};var vn="popmelt:imprint",Wr="popmelt:imprint-evidence",Vt="popmelt:imprint-relation";function po(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===vn)?.id}function hi(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 uo(o,e){if(!o)return[];let t=new Set(o.relations.flatMap(n=>n.type==="expresses"&&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 gi(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var mo=class{constructor(e){this.projectRoot=e;this.store=new co(e),this.indexStore=new lo(e),this.manifestPath=Gt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await In(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let n=await yn({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(n.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(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=Gt(this.projectRoot,".popmelt","memory","migrations"),t=Gt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await In(t,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let n;try{n=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await Fr(e,{recursive:!0}),await zr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),d=i.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,c=i.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!d||!c)return{migrated:!1,explanations:0,evidence:0};let l=i.bundle.manifest.projectId,w=new Set(i.bundle.records.map(u=>u.id)),R=new Set(i.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Vt?[M.id]:[]))),b=new Map,k=i.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of n.explanations){let M=k.find(h=>po(h)===u.id);b.set(u.id,M?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let S=[],f=[],p=[],g=0;for(let u of n.explanations){let M=b.get(u.id),h=k.find(T=>T.id===M),m=[],E=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let T of E){let C=le(l,"imprint-evidence-record",T.id,Date.parse(T.createdAt));m.push(C),!w.has(C)&&(S.push({id:C,schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:d.id,sourceRefs:hi([{kind:"external",id:T.id,uri:Wr},{kind:"external",id:u.id,uri:vn},{kind:"thread",id:T.threadId},{kind:"message",id:T.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(T.kind)?"user_feedback":"judgment",summary:T.summary,availability:"available",artifactIds:[]}),p.push({id:le(l,"imprint-evidence-link",`${u.id}:${T.id}`,Date.parse(T.createdAt)),schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:T.id,uri:Wr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"evidence",entityId:C},reason:"This advisory explanation was derived from collaboration evidence."}),g+=1)}let D={id:M,schemaVersion:1,projectId:l,createdAt:h?.createdAt??u.createdAt,participantId:h?.participantId??d.id,sourceRefs:hi([...h?.sourceRefs??[],{kind:"external",id:u.id,uri:vn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[c.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:uo(n,u.id),supersededById:u.supersededBy?b.get(u.supersededBy):void 0,updatedAt:u.updatedAt};h?f.push(D):S.push(D)}for(let u of n.relations){let M=gi(u.type);if(!M)continue;let h=b.get(u.fromId),m=b.get(u.toId);!h||!m||R.has(u.id)||p.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:u.id,uri:Vt}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:h},to:{entityType:"advisory_explanation",entityId:m},reason:u.rationale||"The Imprint graph connected these explanations."})}let v=new Date().toISOString();if(S.length||f.length||p.length)try{let u=await this.store.commit({records:S,recordReplacements:f,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:v});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Fr(e,{recursive:!0}),await zr(t,JSON.stringify({version:2,migratedAt:v,explanations:n.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:g}}async review(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,selection:di(n.bundle,i)}}async contextualize(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:_r(n.bundle,i),reviewSelection:di(n.bundle,i)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:ro(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(),i=ro(n.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),i=t.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!n||n.state!=="pending"||!i)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 r=Date.now(),s=new Date(r).toISOString(),d={proposalId:n.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},c=e.action==="accept"?{...d,action:"accept",eventId:xe(r),decisionId:xe(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:xe(r),replacementProposalId:xe(r),acceptanceEventId:xe(r),decisionId:xe(r),relationshipId:xe(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:xe(r),reason:e.reason}:{...d,action:"defer",eventId:xe(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=ro(t.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:xe(r),committedAt:s});await this.refreshIndex(w);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence: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=Br(t.bundle,e),i=le(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),i=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active"),r=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="ai"&&v.status==="active"),s=e.action?i:r??i,d=n.bundle.records.find(v=>v.recordType==="subject"&&v.subjectType==="project");if(!s||!d)return;let c=e.occurredAt??new Date().toISOString(),l=Date.parse(c),w=n.bundle.manifest.projectId,R=[],b=[],k=[],S=n.bundle.records.filter(v=>v.recordType==="advisory_explanation"),f=new Map(S.flatMap(v=>{let u=po(v);return u?[[u,v.id]]:[]}));for(let v of e.summary.changes)if(!f.has(v.explanationId)){let u=t?.explanations.find(M=>M.id===v.explanationId);f.set(v.explanationId,le(w,"imprint-explanation",v.explanationId,Date.parse(u?.createdAt??c)))}for(let v of e.summary.changes){let u={kind:"external",id:v.explanationId,uri:vn},M=f.get(v.explanationId),h=S.find(T=>T.id===M),m=t?.explanations.find(T=>T.id===v.explanationId),E={id:le(w,"imprint-live-evidence",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};R.push(E);let D={id:M,schemaVersion:1,projectId:w,createdAt:h?.createdAt??m?.createdAt??c,participantId:h?.participantId??s.id,sourceRefs:hi([...h?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??h?.kind??"pattern",state:m?.state??v.state,statement:m?.statement??v.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],E.id])],concreteBindings:m?uo(t,v.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?f.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??c};h?b.push(D):R.push(D),k.push({id:le(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.id},to:{entityType:"evidence",entityId:E.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(n.bundle.relationships.flatMap(v=>v.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Vt?[u.id]:[])));for(let v of t?.relations??[]){let u=gi(v.type);if(!u)continue;let M=f.get(v.fromId),h=f.get(v.toId);!M||!h||p.has(v.id)||k.push({id:le(w,"imprint-relation",v.id,Date.parse(v.createdAt)),schemaVersion:1,projectId:w,createdAt:v.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:v.id,uri:Vt}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:h},reason:v.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let v=await this.store.commit({records:R,recordReplacements:b,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});await this.refreshIndex(v)}catch(v){if(!(v instanceof Error)||!v.message.includes("Transaction already exists"))throw v}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=xt(JSON.parse(await In(Gt(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"),r=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??n;if(!r)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 d=t.bundle.manifest.projectId,c=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(c.flatMap(m=>{let E=po(m);return E?[[E,m]]:[]})),w=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(d,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),R=[],b=[],k=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=l.get(m.id);if(!E){R.push({id:w.get(m.id),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:vn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:uo(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(E),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:uo(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt},T=C=>JSON.stringify({kind:C.kind,state:C.state,statement:C.statement,rationale:C.rationale,scope:C.scope,concreteBindings:C.concreteBindings,supersededById:C.supersededById,updatedAt:C.updatedAt});T(E)!==T(D)&&b.push(D)}for(let[m,E]of l)k.has(m)||E.state==="retired"||b.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let S=new Set(t.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),f=new Map(t.bundle.relationships.flatMap(m=>{if(S.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Vt)?.id;return E?[[E,m]]:[]})),p=[],g=new Set;for(let m of e.relations){let E=gi(m.type);if(!E)continue;let D=w.get(m.fromId),T=w.get(m.toId);if(!D||!T)continue;let C=f.get(m.id);C&&C.relationshipType===E&&C.from.entityType==="advisory_explanation"&&C.from.entityId===D&&C.to.entityType==="advisory_explanation"&&C.to.entityId===T||(C&&g.add(m.id),p.push({id:le(d,"imprint-relation",`${m.id}:${E}:${D}:${T}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:Vt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:T},reason:m.rationale||"The Imprint graph connected these explanations."}))}let v=new Set(e.relations.map(m=>m.id)),u=n?[...f].filter(([m])=>!v.has(m)||g.has(m)).map(([,m])=>({id:le(d,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:d,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!R.length&&!b.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let M=e.updatedAt,h=le(d,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:R,recordReplacements:b,events:[],relationships:p,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:h,committedAt:M});return await this.refreshIndex(m),{status:"synced",relationships:p.length+u.length,explanations:R.length+b.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 i of t.bundle.records)n[i.recordType]=(n[i.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:t.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),i=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=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)&&!i.has(s.id)&&!r.has(s.id)).sort((s,d)=>d.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(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),n=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>t.has(r))&&n.set(i.key,i);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 i=await this.store.load(),r=i.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(r.map(p=>[p.id,p])),d=new Map(r.flatMap(p=>{let g=po(p);return g?[[g,p.id]]:[]})),c=new Set(e.map(p=>d.get(p)??p)),l=new Map(i.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),w=new Map(i.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),R=new Set(i.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),b=new Set(["expresses","operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},S=r.map(p=>{let g=p.evidenceIds.flatMap(h=>{let m=w.get(h);if(!m)return[];let E=m.sourceRefs.find(z=>z.kind==="thread")?.id,D=m.sourceRefs.find(z=>z.kind==="message")?.id,T=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",C=l.get(m.participantId)??"unknown";return[{id:m.id,kind:T,summary:m.summary,createdAt:m.createdAt,participantKind:C,threadId:E,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),v=i.bundle.relationships.flatMap(h=>{if(R.has(h.id))return[];if(!b.has(h.relationshipType))return[];let m=h.from.entityType==="advisory_explanation"&&h.from.entityId===p.id&&h.to.entityType==="advisory_explanation",E=h.to.entityType==="advisory_explanation"&&h.to.entityId===p.id&&h.from.entityType==="advisory_explanation";if(!m&&!E)return[];let D=m?h.to.entityId:h.from.entityId,T=s.get(D);return T?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:T.id,statement:T.statement,rationale:h.reason}]:[]}),u=[...(p.supersededById?[p.supersededById]:[]).flatMap(h=>{let m=s.get(h);return m?[{id:`supersedes:${p.id}:${m.id}`,type:"supersedes",direction:"incoming",explanationId:m.id,statement:m.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(h=>h.supersededById===p.id?[{id:`supersedes:${h.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:h.id,statement:h.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],M=[...new Set([...p.sourceRefs.flatMap(h=>h.kind==="thread"?[h.id]:[]),...g.flatMap(h=>h.threadId?[h.threadId]:[])])].filter(h=>!t||t.has(h));return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:g.length,recentEvidence:g.slice(0,4),concrete:p.concreteBindings.map(h=>({...structuredClone(h)})),relations:[...v,...u],sourceThreadIds:M,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,g)=>Number(g.needsGrounding)-Number(p.needsGrounding)||k[p.state]-k[g.state]||g.updatedAt.localeCompare(p.updatedAt)),f={total:S.filter(p=>p.state!=="retired").length,emerging:S.filter(p=>p.state==="emerging").length,testing:S.filter(p=>p.state==="testing").length,grounded:S.filter(p=>p.state==="grounded").length,challenged:S.filter(p=>p.state==="challenged").length,retired:S.filter(p=>p.state==="retired").length,needsGrounding:S.filter(p=>p.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:f,explanations:S}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),n=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>t.has(c))&&n.set(d.key,d);let i=[...n.values()],r=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=r.filter(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===d.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:i.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:i.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.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(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),i=t.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!n||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),d=xe(r),c=xe(r),l=xe(r),w=xe(r),R=xe(r),b=new Set(t.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),k=t.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),S={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:i.id,role:"governed"}],p={...S,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},g={...S,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...S,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},u={...S,id:w,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[l],value:e.value},M={...S,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},h={...S,id:xe(r),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."},m=k.map(T=>({...S,id:xe(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=k.map(T=>({...S,id:xe(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[p,v,u,M],events:[g,...m],relationships:[h,...E],artifacts:[],tombstones:[],projectionUpdates:k.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:xe(r),committedAt:s});return await this.refreshIndex(D),{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(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.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(i=>i.recordType==="subject"?[[i.id,i.label]]:[]));return t.records.filter(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.kind==="thread"&&r.id===e)).sort((i,r)=>i.createdAt.localeCompare(r.createdAt)).map(i=>({proposalId:i.id,claim:i.claim,rationale:i.rationale,proposedKind:i.proposedKind,subjectLabels:i.subjects.flatMap(r=>{let s=n.get(r.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(S=>S.recordType==="model_projection"&&S.state==="applied"&&S.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let i=t.bundle.records.filter(S=>S.recordType==="decision"&&e.decisionIds.includes(S.id)&&S.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),d=new Date(s).toISOString(),c=xe(s),l=e.changes.map(S=>{let f=S.decisionIds?.filter(v=>e.decisionIds.includes(v)),p=f?.length?f:e.decisionIds,g=[...new Set(i.filter(v=>p.includes(v.id)).flatMap(v=>v.subjects.map(u=>u.subjectId)))];return{id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:p.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:S.path.map(String).join("."),subjectIds:g,decisionIds:p,value:S.value}}),w=new Set(l.flatMap(S=>S.decisionIds)),R={id:c,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:e.decisionIds.map(S=>({kind:"record",id:S})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(S=>S.id),coverage:e.decisionIds.map(S=>e.coverage?.find(f=>f.decisionId===S)??{decisionId:S,status:w.has(S)?"projected":"unprojected"})},b=l.flatMap(S=>S.decisionIds.map(f=>({id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:S.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:xe(s),committedAt:d});return await this.refreshIndex(k),{projectionId:c,entryIds:l.map(S=>S.id),headSequence:k.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await yn({...e,projectRoot:this.projectRoot})).bundle}}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}),i=Ur(n,t.subjectHints??[]);return i?{...t,subjectIds:[...new Set([...t.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.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 Qt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Pe(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Kt(o,e,t){let n=Pe(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function yi(o){let e=Qt(o),t=Qt(e.authority),n=t.level,i=t.mode,r=Kt(n,"authority.level",["owner","delegate","contributor"]),s=Kt(i,"authority.mode",["local_trusted","hosted"]),d={proposalId:Pe(e.proposalId,"proposalId"),participantId:Pe(e.participantId,"participantId"),occurredAt:Pe(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Pe(e.eventId,"eventId"),decisionId:Pe(e.decisionId,"decisionId"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Pe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Pe(e.eventId,"eventId"),reason:Pe(e.reason,"reason")};case"defer":{let c=Qt(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Pe(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Pe(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>Kt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Pe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Pe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Pe(e.acceptanceEventId,"acceptanceEventId"),decisionId:Pe(e.decisionId,"decisionId"),relationshipId:Pe(e.relationshipId,"relationshipId"),claim:Pe(e.claim,"claim"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Qt(c);return{subjectId:Pe(l.subjectId,"subjectId"),role:Kt(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:Pe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Ii(o){let e=Qt(o),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(d=>Pe(d,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Qt(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:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Hr(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,i=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!i||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(d=>typeof d=="string"&&r.has(d)):void 0;return{proposalId:t.proposalId,action:n,kind:i,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 Gr(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 vi(o){let t=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],i=await qc(o),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),d,c,l,w,R,b,k,S,f,p,g,v,u,M,h=[],m=[],E=0,D=[];for(;E<i.length;){let T=i.indexOf(r,E);if(T===-1)break;let C=T+r.length;if(i.slice(T,T+s.length).equals(s))break;let z=C;i[z]===13&&i[z+1]===10&&(z+=2);let X=i.indexOf(`\r
169
+ `;function go(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function tl(o,e){let t=go(e);if(!t)return null;let n=new URL(t),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&go(s.url)),i=r.find(s=>go(s.url)===t);return i||(r.find(s=>{let a=new URL(go(s.url));return a.origin===n.origin&&a.pathname===n.pathname})??null)}function nl(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 ol(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 rl(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 il(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++,c=setTimeout(()=>{t.delete(a),s(new Error(`CDP ${n} timed out`))},4e3);t.set(a,{resolve:i,reject:s,timeout:c}),o.send(JSON.stringify({id:a,method:n,params:r}),l=>{l&&(clearTimeout(c),t.delete(a),s(l))})})}async function ts(o,e){let t=nl(e.clip),n=await ol(o),r=tl(n,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await rl(r.webSocketDebuggerUrl),s=il(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Zc,returnByValue:!0}),a=!0;let c=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 c.data=="string"?c.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{a&&await s("Runtime.evaluate",{expression:el,returnByValue:!0}).catch(()=>{}),i.close()}}function ns(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 os(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 Sr(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 sl(o),i=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),a,c,l,b,S,y,k,T,h,u,g,I,p,j,f=[],m=[],E=0,D=[];for(;E<r.length;){let P=r.indexOf(i,E);if(P===-1)break;let O=P+i.length;if(r.slice(P,P+s.length).equals(s))break;let W=O;r[W]===13&&r[W+1]===10&&(W+=2);let K=r.indexOf(`\r
170
170
  \r
171
- `,z);if(X===-1)break;let G=i.slice(z,X).toString("utf-8"),Y=X+4,x=i.indexOf(r,Y),Q=x!==-1?x-2:i.length;D.push({headers:G,body:i.slice(Y,Q)}),E=x!==-1?x:i.length}for(let T of D){let C=T.headers.match(/name="([^"]+)"/);if(!C)continue;let z=C[1];if(z==="screenshot")d=T.body;else if(z==="feedback")c=T.body.toString("utf-8");else if(z==="color")l=T.body.toString("utf-8");else if(z==="provider")w=T.body.toString("utf-8");else if(z==="model")R=T.body.toString("utf-8");else if(z==="reasoningEffort")b=T.body.toString("utf-8");else if(z==="serviceTier")k=T.body.toString("utf-8");else if(z==="goal")S=T.body.toString("utf-8");else if(z==="pageUrl")f=T.body.toString("utf-8");else if(z==="viewport")p=T.body.toString("utf-8");else if(z==="planId")g=T.body.toString("utf-8");else if(z==="manifest")v=T.body.toString("utf-8");else if(z==="tasks")u=T.body.toString("utf-8");else if(z==="sourceId")M=T.body.toString("utf-8");else if(z.startsWith("screenshot-")){let X=z.slice(11);try{let G=decodeURIComponent(X);m.push({pathname:G,data:T.body})}catch{}}else if(z.startsWith("image-")){let X=z.split("-"),G=parseInt(X[X.length-1],10),Y=X.slice(1,-1).join("-");Y&&!isNaN(G)&&h.push({annotationId:Y,index:G,data:T.body})}}if(!d)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:d,feedback:c,color:l,provider:w,model:R,reasoningEffort:b,serviceTier:k,goal:S,pageUrl:f,viewport:p,planId:g,manifest:v,tasks:u,sourceId:M,pastedImages:h,pageScreenshots:m}}function qc(o){return new Promise((e,t)=>{let n=[];o.on("data",i=>n.push(i)),o.on("end",()=>e(Buffer.concat(n))),o.on("error",t)})}import{randomUUID as Uc}from"crypto";var wn="<orientation>",at="</orientation>";function Xt(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,i=!1,r=!1;for(let s=t;s<o.length;s++){let d=o[s];if(i){r?r=!1:d==="\\"?r=!0:d==='"'&&(i=!1);continue}if(d==='"')i=!0;else if(d==="{")n++;else if(d==="}"){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 Vr(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function Kr(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(wn,t);if(n<0){Vr(e,o.slice(t));break}Vr(e,o.slice(t,n));let i=n+wn.length,r=Xt(o,i);if(r.status!=="complete"){let d=o.indexOf(at,i);if(d>=0){t=d+at.length;continue}t=i;continue}e.push({kind:"orientation",json:o.slice(r.start,r.end)}),t=r.end;let s=t;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(at,s)&&(t=s+at.length)}return e}var Fc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),zc=new Set(["strengthened","weakened","mixed","unknown"]);function bn(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 Wc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function Qr(o,e,t,n=Date.now()){let i=Wc(o);if(!i)return null;let r=typeof i.transition=="string"&&Fc.has(i.transition)?i.transition:null,s=bn(i.focus);if(!r||!s)return null;let d=typeof i.evidencePosture=="string"&&zc.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:Uc(),jobId:e,sequence:t,timestamp:n,transition:r,snapshot:{focus:s,seeking:bn(i.seeking),workingHypothesis:bn(i.workingHypothesis),evidencePosture:d,update:bn(i.update),nextObservation:bn(i.nextObservation)},contextPolicy:"exclude"}}function wi(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function bi(o,e,t=0){let n=[],i=[],r=new Set,s=t;for(let c of Kr(o)){if(c.kind==="text"){c.text&&i.push(c);continue}try{let l=Qr(JSON.parse(c.json),e,s);if(!l)continue;let w=wi(l);if(r.has(w))continue;r.add(w),n.push(l),i.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:i.map(c=>c.kind==="text"?c.text:`
171
+ `,W);if(K===-1)break;let _=r.slice(W,K).toString("utf-8"),H=K+4,G=r.indexOf(i,H),fe=G!==-1?G-2:r.length;D.push({headers:_,body:r.slice(H,fe)}),E=G!==-1?G:r.length}for(let P of D){let O=P.headers.match(/name="([^"]+)"/);if(!O)continue;let W=O[1];if(W==="screenshot")a=P.body;else if(W==="feedback")c=P.body.toString("utf-8");else if(W==="color")l=P.body.toString("utf-8");else if(W==="provider")b=P.body.toString("utf-8");else if(W==="model")S=P.body.toString("utf-8");else if(W==="reasoningEffort")y=P.body.toString("utf-8");else if(W==="serviceTier")k=P.body.toString("utf-8");else if(W==="goal")T=P.body.toString("utf-8");else if(W==="pageUrl")h=P.body.toString("utf-8");else if(W==="viewport")u=P.body.toString("utf-8");else if(W==="planId")g=P.body.toString("utf-8");else if(W==="manifest")I=P.body.toString("utf-8");else if(W==="tasks")p=P.body.toString("utf-8");else if(W==="sourceId")j=P.body.toString("utf-8");else if(W.startsWith("screenshot-")){let K=W.slice(11);try{let _=decodeURIComponent(K);m.push({pathname:_,data:P.body})}catch{}}else if(W.startsWith("image-")){let K=W.split("-"),_=parseInt(K[K.length-1],10),H=K.slice(1,-1).join("-");H&&!isNaN(_)&&f.push({annotationId:H,index:_,data:P.body})}}if(!a)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:a,feedback:c,color:l,provider:b,model:S,reasoningEffort:y,serviceTier:k,goal:T,pageUrl:h,viewport:u,planId:g,manifest:I,tasks:p,sourceId:j,pastedImages:f,pageScreenshots:m}}function sl(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)})}import{randomUUID as al}from"crypto";var Tn="<orientation>",dt="</orientation>";function Zt(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 rs(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function is(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(Tn,t);if(n<0){rs(e,o.slice(t));break}rs(e,o.slice(t,n));let r=n+Tn.length,i=Zt(o,r);if(i.status!=="complete"){let a=o.indexOf(dt,r);if(a>=0){t=a+dt.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(dt,s)&&(t=s+dt.length)}return e}var dl=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),cl=new Set(["strengthened","weakened","mixed","unknown"]);function Pn(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 ll(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function ss(o,e,t,n=Date.now()){let r=ll(o);if(!r)return null;let i=typeof r.transition=="string"&&dl.has(r.transition)?r.transition:null,s=Pn(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&cl.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:al(),jobId:e,sequence:t,timestamp:n,transition:i,snapshot:{focus:s,seeking:Pn(r.seeking),workingHypothesis:Pn(r.workingHypothesis),evidencePosture:a,update:Pn(r.update),nextObservation:Pn(r.nextObservation)},contextPolicy:"exclude"}}function Tr(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Pr(o,e,t=0){let n=[],r=[],i=new Set,s=t;for(let c of is(o)){if(c.kind==="text"){c.text&&r.push(c);continue}try{let l=ss(JSON.parse(c.json),e,s);if(!l)continue;let b=Tr(l);if(i.has(b))continue;i.add(b),n.push(l),r.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:r.map(c=>c.kind==="text"?c.text:`
172
172
 
173
173
  `).join("").replace(/\n{3,}/g,`
174
174
 
175
- `).trim(),orientations:n,segments:i}}function Hc(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 fo=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 c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(at.startsWith(l)&&l.length<at.length||(l.startsWith(at)&&(this.buffer=this.buffer.slice(c+at.length)),this.optionalClosePending=!1,!this.buffer))break}let i=this.buffer.indexOf(wn);if(i<0){let c=Hc(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,i);let r=i+wn.length,s=Xt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(i);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let d=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let c=Qr(JSON.parse(d),this.jobId,this.sequence);if(!c)continue;let l=wi(c);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=bi(e,this.jobId,this.sequence),n=t.orientations.filter(i=>{let r=wi(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},Xr=`## Public orientation updates
175
+ `).trim(),orientations:n,segments:r}}function pl(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 yo=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 c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(dt.startsWith(l)&&l.length<dt.length||(l.startsWith(dt)&&(this.buffer=this.buffer.slice(c+dt.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(Tn);if(r<0){let c=pl(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,r);let i=r+Tn.length,s=Zt(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 c=ss(JSON.parse(a),this.jobId,this.sequence);if(!c)continue;let l=Tr(c);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=Pr(e,this.jobId,this.sequence),n=t.orientations.filter(r=>{let i=Tr(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}}},as=`## Public orientation updates
176
176
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
177
177
  <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>
178
178
 
179
179
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
180
180
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
181
181
 
182
- 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 Yr=`## Project collaboration history
182
+ 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 ds=`## Project collaboration history
183
183
  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.
184
184
 
185
185
  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.
@@ -188,53 +188,53 @@ Search raw \`.popmelt\` records only when the supplied Imprint context is insuff
188
188
 
189
189
  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.
190
190
 
191
- 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 xn(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(l=>{let w=[l.selector];return l.reactComponent&&w.push(`(${l.reactComponent})`),w.join(" ")}).join(", "),s=i.instruction||"No text";n.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let d=e?.[i.id];if(d&&d.length>0)for(let l of d)n.push(` Attached image: use the Read tool to view ${l}`);let c=t?.[i.id];if(c?.length)for(let l of c)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 i of o.styleModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"";for(let s of i.changes)n.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let i of o.textModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=JSON.stringify(i.original),d=JSON.stringify(i.modified),c=i.textNodePath.length>0?` textNodePath=${i.textNodePath.join(".")}`:"";n.push(`- ${i.selector} ${r}${c}: ${s} \u2192 ${d}`)}}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 i of o.domModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=i.sourceElement?.reactComponent?` from ${i.sourceSelector} (${i.sourceElement.reactComponent})`:i.sourceSelector?` from ${i.sourceSelector}`:"",d=i.referenceSelector?` ${i.placement} ${i.referenceSelector}`:` at index ${i.targetIndex}`;n.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${d}`)}}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 i of o.spacingTokenChanges){n.push(`
192
- ### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let r of i.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[i.selector];i.reactComponent&&r.push(`(${i.reactComponent})`),i.context&&r.push(`in ${i.context}`),i.textContent&&r.push(`"${i.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
193
- `)}function Zr(o,e,t){let n=[],r=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(""),!r&&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 d of t.threadHistory)if(d.role==="human")s++,d.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${d.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),d.feedbackSummary&&n.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&n.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${d.question}"`);else{if(n.push(`### Round ${s} (assistant)`),d.responseText&&n.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let c of d.resolutions){let l=c.finalScope??c.inferredScope,w=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${c.annotationId}: ${c.status}${w} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&n.push(` Files: ${c.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&n.push(`Tools used: ${d.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 R of s)if(typeof R=="object"&&R!==null&&"text"in R){let b=R,k=b.scope||"general";w.has(k)||w.set(k,[]),w.get(k).push(b.text)}for(let[R,b]of w){n.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let k of b)n.push(`- ${k}`)}}else for(let w of s)typeof w=="string"&&n.push(`- ${w}`);let d=t.designModel.tokens;d&&typeof d=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```"));let c=t.designModel.components;c&&typeof c=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(c,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.")),r){let s=t?.screenshotPaths??{},d=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;d.has(l)||d.set(l,[]),d.get(l).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of d){n.push(""),n.push(`## Page: ${c}`);let w=s[c];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 R={...e,annotations:l,styleModifications:e.styleModifications},b=xn(R,t?.imagePaths,t?.attachmentFiles);b&&(n.push(""),n.push(b))}}else{let s=xn(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(`
194
- `)}function es(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ts(o,e,t,n){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),t!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let d of e)d.role==="human"?(s++,d.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${d.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),d.feedbackSummary&&i.push(`Annotations: ${d.feedbackSummary}`))):d.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${d.question}"`)):(i.push(`### Round ${s} (assistant)`),d.responseText&&i.push(`Response: ${d.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of n)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),i.push("<resolution>"),i.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),i.push("</resolution>"),i.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."),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
195
- `)}function Gc(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 Vc(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&&!Gc(e[t]))return!1;return!0}function ns(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(Vc)}catch{return[]}}function Kc(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 i=n;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}function os(o,e){return e>0?Kc(o):[]}import{execFile as Qc}from"child_process";import{readdir as Xc,readFile as Yc,stat as Zc}from"fs/promises";import{homedir as Sn}from"os";import{join as tt}from"path";var go=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:is()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:is()}],Tn=[{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"}],Pn={id:"",label:"Default",source:"cli"},el=/^\s*-\s+"([^"]+)"/;function tl(o){let e=[],t=!1;for(let n of o.split(`
196
- `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let i=n.match(el);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:xi(r),source:"cli"})}return yo([Pn,...e])}function nl(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,i)=>{let r=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(n=>{let i=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!i)return[];let r=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():xi(i),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,d=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;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:i,label:r,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...d&&d.length>0?{speedTiers:d}:{}}]})}function is(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function ol(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return yo(e.map(t=>({id:t,label:xi(t),source:"cli"})))}function xi(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 r=n[1]==="sonnet"?"Sonn":al(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${r}${s}${n[4]?" Fast":""}`}let i=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return t}async function rs(o="copilot"){let e=await ho(o,["help","config"]),t=tl(e);return t.length>1?t:[Pn]}async function ss(o="codex"){let e=await ho(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||tt(Sn(),".codex");return ds(tt(n,"models_cache.json"))}),t=nl(e);return t.length>0?yo([...t,...Tn]):Tn}async function as(o="claude"){let e=tt(Sn(),".claude"),t=[tt(Sn(),".claude","stats-cache.json"),tt(Sn(),".claude","settings.json"),tt(Sn(),".claude.json"),tt(e,"cache","changelog.md")],[n,i,r]=await Promise.all([ho(o,["--help"]).catch(()=>""),ho(o,["--version"]).catch(()=>""),il(e).catch(()=>[])]),s=sl([...t,...r]),d=await Promise.all(s.map(l=>ds(l).catch(()=>""))),c=ol([n,i,...d].join(`
197
- `));return yo([...go,...c])}function ho(o,e,t=5e3){return new Promise((n,i)=>{Qc(o,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){i(r);return}n(s)})})}async function ds(o){return Yc(o,"utf-8")}async function il(o){let e=[tt(o,"projects"),tt(o,"telemetry")],t=[];for(let n of e)await cs(n,t,4);return t.sort((n,i)=>i.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function cs(o,e,t){if(t<0)return;let n;try{n=await Xc(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async i=>{let r=tt(o,i.name);if(i.isDirectory()){await cs(r,e,t-1);return}if(!(!i.isFile()||!rl(i.name)))try{let s=await Zc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function rl(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function yo(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 sl(o){return[...new Set(o)]}function al(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Io=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 r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,i=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),i}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 i=this.bufferEvent(t,e);for(let r of this.listeners)r(i,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let i={...t,seq:n.nextSeq++};return n.events.push(i),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),i}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(d=>d.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,t,n){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[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}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(i=>{let r=!1,s=()=>{r||(r=!0,i())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){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)})}}};import{randomUUID as dl}from"crypto";var Yt="<imprint-use>",vo="</imprint-use>";function cl(o){let e=Math.min(o.length,Yt.length-1);for(let t=e;t>0;t--)if(Yt.startsWith(o.slice(-t)))return t;return 0}function ls(o,e,t,n,i=Date.now()){if(!o||typeof o!="object"||Array.isArray(o))return null;let r=o,s=Array.isArray(r.explanationIds)?r.explanationIds.filter(c=>typeof c=="string"&&!!c.trim()):[],d=[...new Set(s)].flatMap(c=>{let l=e?.explanations.find(w=>w.id===c);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return d.length===0?null:{id:dl(),jobId:t,sequence:n,timestamp:i,explanations:d}}var wo=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 c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(vo.startsWith(l)&&l.length<vo.length||(l.startsWith(vo)&&(this.buffer=this.buffer.slice(c+vo.length)),this.optionalClosePending=!1,!this.buffer))break}let i=this.buffer.indexOf(Yt);if(i<0){let c=cl(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,i);let r=i+Yt.length,s=Xt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(i);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let d=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let c=ls(JSON.parse(d),this.context,this.jobId,this.sequence);if(!c)continue;let l=this.takeNewExplanations(c);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",i=0;for(;i<e.length;){let r=e.indexOf(Yt,i);if(r<0){n+=e.slice(i);break}n+=e.slice(i,r);let s=r+Yt.length,d=Xt(e,s);if(d.status!=="complete"){i=s;continue}try{let w=ls(JSON.parse(e.slice(d.start,d.end)),this.context,this.jobId,this.sequence);if(w){let R=this.takeNewExplanations(w);R&&t.push(R)}}catch{}let l=e.slice(d.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;i=d.end+l}return{visibleText:n.trim(),usages:t}}};function kn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function bo(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Si(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 ps(o){let e=Si(bo(o.origin));if(e)return e;let t=Si(bo(o.referer));if(t)return t;let n=bo(o["x-forwarded-host"]);if(!n)return null;let i=bo(o["x-forwarded-proto"])==="https"?"https":"http";return Si(`${i}://${n}`)}function us(o,e,t=5){let n=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),i=[...o].sort(n).slice(0,t),r=o.filter(c=>c.status==="applied"||c.status==="failed").sort(n).slice(0,t),s=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=s.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:d,actionableProposals:s}}import{createHash as To}from"crypto";import{mkdir as An,readFile as jt,unlink as hl,writeFile as Zt}from"fs/promises";import{dirname as Po,extname as gl,join as Ne}from"path";var ll={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 pl(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 ms(o,e){let t=e??pl(o);return{kind:t,...ll[t]}}import{createHash as ul,randomUUID as ml}from"crypto";var fs=o=>`${o}-${ml()}`;function Ti(o,...e){return`${o}-${ul("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Pi(o){return{schemaVersion:1,submissionIds:[fs("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function Rn(o,e=[],t){return{...o,outcomeId:o.outcomeId??fs("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function fl(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function xo(o,e){return e?[`${o||"/"}:${e}`]:[]}function hs(o){let e=fl(o.url);return[...new Set([...o.annotations.flatMap(t=>xo(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>xo(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>xo(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>xo(t.pathname??e,t.durableSelector??t.selector))])]}function gs(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 So(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Ti("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?[Ti("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Ti("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function ki(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=So(o.id,t)||e;return e}function ys(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(i=>i.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 yl={version:1,threads:{}},Is=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],jn={version:2,updatedAt:0,files:{}};function Il(o){return JSON.stringify(o,null,2)}function vl(o){return Object.fromEntries(Is.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function wl(o){let e={...o};for(let t of Is)delete e[t];return e}function en(o){let e=o;if(o.error){let t=ms(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=_t(e.result,!1),n=_t(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 ko=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Ne(e,".popmelt");this.legacyFilePath=Ne(t,"threads.json"),this.threadsDir=Ne(t,"threads"),this.indexPath=Ne(this.threadsDir,"index.json"),this.artifactsDir=Ne(t,"artifacts","thread-messages"),this.mediaDir=Ne(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await jt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[i,r]of Object.entries(e.files)){let s=await this.readThread(Ne(this.threadsDir,r));s&&(t[i]=s)}this.cache={version:1,threads:t};let n=!1;for(let i of Object.values(t))n=ki(i)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await jt(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(en)}]))},this.index={...jn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))ki(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...yl,threads:{}},this.index={...jn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let i of Object.values(t.threads))if(i.elementIdentifiers.some(s=>n.has(s)))return i;return null}async createThread(e,t){let n=await this.load(),i={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,t){let i=(await this.load()).threads[e];i&&(So(e,t),i.messages.push(en(t)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,t){let i=(await this.load()).threads[e];if(!i)return;So(e,t);let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,en(t)):i.messages.push(en(t)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(d=>d.jobId===t);if(s.length===0)return!1;for(let d of s)if(Object.assign(d,n),d.error){let c=en(d);Object.assign(d,c),delete d.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of t)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((i,r)=>r.updatedAt-i.updatedAt),n.slice(0,e).map(i=>{let s=i.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",d=i.messages.filter(p=>p.role==="assistant"),c=p=>{if(p.role!=="assistant")return;if(p.question)return p.question;let g=p.imprintSummary?.grounding;if(g?.question&&!p.imprintSummary?.resolvedAction)return g.question},l=i.messages.findLastIndex(p=>!!c(p)),w=i.messages.findLastIndex(p=>p.role==="human"),R=l>w?c(i.messages[l]):void 0,b=i.messages.at(-1)?.role,k=Array.from(new Set(i.messages.slice(0,Math.max(0,w)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),S=d.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=d.some(p=>!!p.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:S,hasError:f,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:k,elementIdentifiers:i.elementIdentifiers,lifecycle:ys(i)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let i=n.messages.at(-1);if(!i||i.role!=="human"||/^(imprint|memory)-/.test(i.jobId))continue;let r=Rn(i.lifecycle);i.queued&&await this.updateMessage(n.id,i.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:i.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),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 jt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let d=await jt(Ne(Po(this.legacyFilePath),i.path),"utf8");To("sha256").update(d).digest("hex")===i.sha256&&(s=JSON.parse(d))}catch{}return en({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=vl(e),n=wl(e);if(Object.keys(t).length===0)return n;let i=Il(t),r=To("sha256").update(i).digest("hex"),s=Ne("artifacts","thread-messages",`${r}.json`);await An(this.artifactsDir,{recursive:!0});try{await jt(Ne(Po(this.legacyFilePath),s),"utf8")}catch{await Zt(Ne(Po(this.legacyFilePath),s),i)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(Po(n)===this.mediaDir)return n;try{let i=await jt(n),r=To("sha256").update(i).digest("hex"),s=Ne(this.mediaDir,`${r}${gl(n)||".bin"}`);await An(this.mediaDir,{recursive:!0});try{await jt(s)}catch{await Zt(s,i)}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,i])=>[n,await t(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,i])=>[n,await Promise.all(i.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,i])=>[n,await Promise.all(i.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await An(this.threadsDir,{recursive:!0});let t=this.index??{...jn,files:{}},n=t.files[e.id]??`${To("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Zt(Ne(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Zt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await An(this.threadsDir,{recursive:!0}),this.index=this.index??{...jn,files:{}},await Zt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...jn,files:{}},n=t.files[e];n&&await hl(Ne(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await An(this.threadsDir,{recursive:!0}),await Zt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as bl,open as xl,readFile as Sl,rename as Tl,unlink as Pl}from"fs/promises";import{dirname as kl,join as Rl}from"path";var vs={schemaVersion:1,theme:"auto",updatedAt:null};function ws(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Al(o,e){await bl(kl(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await xl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
198
- `,"utf8"),await n.sync()}finally{await n.close()}await Tl(t,o)}catch(n){throw await Pl(t).catch(()=>{}),n}}var Ro=class{constructor(e){this.path=Rl(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Sl(this.path,"utf8")),t=ws(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...vs}}}catch{return{exists:!1,preferences:{...vs}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Al(this.path,t),t}};function bs(o){return ws(o)!==null}function ht(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 tn(o){return o?[ht(o.selector,400),ht(o.context,200),ht(o.reactComponent,120),ht(o.textContent)].filter(e=>!!e):[]}function Ri(o){return[...new Set(o.filter(e=>!!e))]}function xs(o,e){return Ri([...e,...o.annotations.flatMap(t=>[ht(t.pathname,200),ht(t.linkedSelector,400),...t.elements.flatMap(tn)]),...o.styleModifications.flatMap(t=>tn(t.element)),...(o.textModifications??[]).flatMap(t=>tn(t.element)),...(o.domModifications??[]).flatMap(t=>[...tn(t.element),...tn(t.sourceElement)])])}function Ss(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Ri(t?[...e,...t.annotations.flatMap(n=>[ht(n.pathname,200),ht(n.linkedSelector,400),...n.elements.flatMap(tn)])]:e)}function jl(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function Ts(o){let e=o.annotations.flatMap(i=>{let r=jl(i);return r?[{instruction:r,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
199
-
200
- `);let n=new Map;for(let i of e){let r=i.pathname||"(unknown)",s=n.get(r)??[];s.push(i.instruction),n.set(r,s)}return[...n.entries()].map(([i,r])=>`\`${i}\`
201
- ${r.map(s=>`- ${s}`).join(`
191
+ 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 Rn(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 b=[l.selector];return l.reactComponent&&b.push(`(${l.reactComponent})`),b.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 c=t?.[r.id];if(c?.length)for(let l of c)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)n.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of o.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),c=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";n.push(`- ${r.selector} ${i}${c}: ${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(`
192
+ ### ${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(`
193
+ `)}function cs(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 c of a.resolutions){let l=c.finalScope??c.inferredScope,b=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${c.annotationId}: ${c.status}${b} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&n.push(` Files: ${c.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 b=new Map;for(let S of s)if(typeof S=="object"&&S!==null&&"text"in S){let y=S,k=y.scope||"general";b.has(k)||b.set(k,[]),b.get(k).push(y.text)}for(let[S,y]of b){n.push(`**${S.charAt(0).toUpperCase()+S.slice(1)}**`);for(let k of y)n.push(`- ${k}`)}}else for(let b of s)typeof b=="string"&&n.push(`- ${b}`);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 c=t.designModel.components;c&&typeof c=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(c,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 c of e.annotations){let l=c.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of a){n.push(""),n.push(`## Page: ${c}`);let b=s[c];b&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${b}`):!b&&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=Rn(S,t?.imagePaths,t?.attachmentFiles);y&&(n.push(""),n.push(y))}}else{let s=Rn(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(`
194
+ `)}function ls(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ps(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(`
195
+ `)}function ul(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 ml(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&&!ul(e[t]))return!1;return!0}function us(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(ml)}catch{return[]}}function fl(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?fl(o):[]}import{execFile as hl}from"child_process";import{readdir as gl,readFile as yl,stat as Il}from"fs/promises";import{homedir as kn}from"os";import{join as nt}from"path";var wo=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:fs()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:fs()}],Mn=[{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"}],jn={id:"",label:"Default",source:"cli"},wl=/^\s*-\s+"([^"]+)"/;function vl(o){let e=[],t=!1;for(let n of o.split(`
196
+ `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let r=n.match(wl);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Rr(i),source:"cli"})}return vo([jn,...e])}function bl(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():Rr(r),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;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(c=>{if(!c||typeof c!="object")return[];let l=c;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 fs(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function xl(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return vo(e.map(t=>({id:t,label:Rr(t),source:"cli"})))}function Rr(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":Rl(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 hs(o="copilot"){let e=await Io(o,["help","config"]),t=vl(e);return t.length>1?t:[jn]}async function gs(o="codex"){let e=await Io(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||nt(kn(),".codex");return Is(nt(n,"models_cache.json"))}),t=bl(e);return t.length>0?vo([...t,...Mn]):Mn}async function ys(o="claude"){let e=nt(kn(),".claude"),t=[nt(kn(),".claude","stats-cache.json"),nt(kn(),".claude","settings.json"),nt(kn(),".claude.json"),nt(e,"cache","changelog.md")],[n,r,i]=await Promise.all([Io(o,["--help"]).catch(()=>""),Io(o,["--version"]).catch(()=>""),Sl(e).catch(()=>[])]),s=Pl([...t,...i]),a=await Promise.all(s.map(l=>Is(l).catch(()=>""))),c=xl([n,r,...a].join(`
197
+ `));return vo([...wo,...c])}function Io(o,e,t=5e3){return new Promise((n,r)=>{hl(o,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}n(s)})})}async function Is(o){return yl(o,"utf-8")}async function Sl(o){let e=[nt(o,"projects"),nt(o,"telemetry")],t=[];for(let n of e)await ws(n,t,4);return t.sort((n,r)=>r.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function ws(o,e,t){if(t<0)return;let n;try{n=await gl(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async r=>{let i=nt(o,r.name);if(r.isDirectory()){await ws(i,e,t-1);return}if(!(!r.isFile()||!Tl(r.name)))try{let s=await Il(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function Tl(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function vo(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 Pl(o){return[...new Set(o)]}function Rl(o){return o.charAt(0).toUpperCase()+o.slice(1)}var bo=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}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)})}}};import{randomUUID as kl}from"crypto";var en="<imprint-use>",xo="</imprint-use>";function Ml(o){let e=Math.min(o.length,en.length-1);for(let t=e;t>0;t--)if(en.startsWith(o.slice(-t)))return t;return 0}function vs(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(c=>typeof c=="string"&&!!c.trim()):[],a=[...new Set(s)].flatMap(c=>{let l=e?.explanations.find(b=>b.id===c);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return a.length===0?null:{id:kl(),jobId:t,sequence:n,timestamp:r,explanations:a}}var So=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 c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(xo.startsWith(l)&&l.length<xo.length||(l.startsWith(xo)&&(this.buffer=this.buffer.slice(c+xo.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(en);if(r<0){let c=Ml(this.buffer);t+=c>0?this.buffer.slice(0,-c):this.buffer,this.buffer=c>0?this.buffer.slice(-c):"";break}t+=this.buffer.slice(0,r);let i=r+en.length,s=Zt(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 c=vs(JSON.parse(a),this.context,this.jobId,this.sequence);if(!c)continue;let l=this.takeNewExplanations(c);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(en,r);if(i<0){n+=e.slice(r);break}n+=e.slice(r,i);let s=i+en.length,a=Zt(e,s);if(a.status!=="complete"){r=s;continue}try{let b=vs(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(b){let S=this.takeNewExplanations(b);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 An(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function To(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function kr(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 bs(o){let e=kr(To(o.origin));if(e)return e;let t=kr(To(o.referer));if(t)return t;let n=To(o["x-forwarded-host"]);if(!n)return null;let r=To(o["x-forwarded-proto"])==="https"?"https":"http";return kr(`${r}://${n}`)}function xs(o,e,t=5){let n=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),r=[...o].sort(n).slice(0,t),i=o.filter(c=>c.status==="applied"||c.status==="failed").sort(n).slice(0,t),s=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),a=s.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{createHash as ko}from"crypto";import{mkdir as _n,readFile as Et,unlink as $l,writeFile as tn}from"fs/promises";import{dirname as Mo,extname as Ol,join as Je}from"path";var jl={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 Al(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 Ss(o,e){let t=e??Al(o);return{kind:t,...jl[t]}}import{createHash as El,randomUUID as _l}from"crypto";var Ts=o=>`${o}-${_l()}`;function Mr(o,...e){return`${o}-${El("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function jr(o){return{schemaVersion:1,submissionIds:[Ts("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function En(o,e=[],t){return{...o,outcomeId:o.outcomeId??Ts("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function Cl(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function Po(o,e){return e?[`${o||"/"}:${e}`]:[]}function Ps(o){let e=Cl(o.url);return[...new Set([...o.annotations.flatMap(t=>Po(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>Po(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>Po(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>Po(t.pathname??e,t.durableSelector??t.selector))])]}function Rs(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 Ro(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Mr("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?[Mr("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Mr("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Ar(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=Ro(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 Dl={version:1,threads:{}},Ms=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Cn={version:2,updatedAt:0,files:{}};function Nl(o){return JSON.stringify(o,null,2)}function Bl(o){return Object.fromEntries(Ms.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Jl(o){let e={...o};for(let t of Ms)delete e[t];return e}function nn(o){let e=o;if(o.error){let t=Ss(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=$t(e.result,!1),n=$t(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 jo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Je(e,".popmelt");this.legacyFilePath=Je(t,"threads.json"),this.threadsDir=Je(t,"threads"),this.indexPath=Je(this.threadsDir,"index.json"),this.artifactsDir=Je(t,"artifacts","thread-messages"),this.mediaDir=Je(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Et(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(Je(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let n=!1;for(let r of Object.values(t))n=Ar(r)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Et(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(nn)}]))},this.index={...Cn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Ar(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...Dl,threads:{}},this.index={...Cn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let r of Object.values(t.threads))if(r.elementIdentifiers.some(s=>n.has(s)))return r;return null}async createThread(e,t){let n=await this.load(),r={id:e,lifecycleVersion:1,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&&(Ro(e,t),r.messages.push(nn(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;Ro(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,nn(t)):r.messages.push(nn(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 c=nn(a);Object.assign(a,c),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 listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((r,i)=>i.updatedAt-r.updatedAt),n.slice(0,e).map(r=>{let s=r.messages.find(u=>u.role==="human")?.feedbackSummary||"[thread]",a=r.messages.filter(u=>u.role==="assistant"),c=u=>{if(u.role!=="assistant")return;if(u.question)return u.question;let g=u.imprintSummary?.grounding;if(g?.question&&!u.imprintSummary?.resolvedAction)return g.question},l=r.messages.findLastIndex(u=>!!c(u)),b=r.messages.findLastIndex(u=>u.role==="human"),S=l>b?c(r.messages[l]):void 0,y=r.messages.at(-1)?.role,k=Array.from(new Set(r.messages.slice(0,Math.max(0,b)).filter(u=>u.role==="assistant"&&!!u.jobId).map(u=>u.jobId))),T=a.some(u=>!!u.responseText||!!u.question||!!u.result||!!u.memoryReviewCard||!!u.memoryReceipt),h=a.some(u=>!!u.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:T,hasError:h,lastMessageRole:y,pendingQuestion:S,acknowledgedJobIds:k,elementIdentifiers:r.elementIdentifiers,lifecycle:ks(r)}})}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=En(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 Et(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let a=await Et(Je(Mo(this.legacyFilePath),r.path),"utf8");ko("sha256").update(a).digest("hex")===r.sha256&&(s=JSON.parse(a))}catch{}return nn({...i,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=Bl(e),n=Jl(e);if(Object.keys(t).length===0)return n;let r=Nl(t),i=ko("sha256").update(r).digest("hex"),s=Je("artifacts","thread-messages",`${i}.json`);await _n(this.artifactsDir,{recursive:!0});try{await Et(Je(Mo(this.legacyFilePath),s),"utf8")}catch{await tn(Je(Mo(this.legacyFilePath),s),r)}return{...n,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async n=>{if(Mo(n)===this.mediaDir)return n;try{let r=await Et(n),i=ko("sha256").update(r).digest("hex"),s=Je(this.mediaDir,`${i}${Ol(n)||".bin"}`);await _n(this.mediaDir,{recursive:!0});try{await Et(s)}catch{await tn(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 _n(this.threadsDir,{recursive:!0});let t=this.index??{...Cn,files:{}},n=t.files[e.id]??`${ko("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 tn(Je(this.threadsDir,n),JSON.stringify(i,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await tn(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await _n(this.threadsDir,{recursive:!0}),this.index=this.index??{...Cn,files:{}},await tn(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...Cn,files:{}},n=t.files[e];n&&await $l(Je(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await _n(this.threadsDir,{recursive:!0}),await tn(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as Ll,open as ql,readFile as Fl,rename as Ul,unlink as zl}from"fs/promises";import{dirname as Vl,join as Hl}from"path";var js={schemaVersion:1,theme:"auto",updatedAt:null};function As(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Wl(o,e){await Ll(Vl(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await ql(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
198
+ `,"utf8"),await n.sync()}finally{await n.close()}await Ul(t,o)}catch(n){throw await zl(t).catch(()=>{}),n}}var Ao=class{constructor(e){this.path=Hl(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Fl(this.path,"utf8")),t=As(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...js}}}catch{return{exists:!1,preferences:{...js}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Wl(this.path,t),t}};function Es(o){return As(o)!==null}function yt(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 on(o){return o?[yt(o.selector,400),yt(o.context,200),yt(o.reactComponent,120),yt(o.textContent)].filter(e=>!!e):[]}function Er(o){return[...new Set(o.filter(e=>!!e))]}function _s(o,e){return Er([...e,...o.annotations.flatMap(t=>[yt(t.pathname,200),yt(t.linkedSelector,400),...t.elements.flatMap(on)]),...o.styleModifications.flatMap(t=>on(t.element)),...(o.textModifications??[]).flatMap(t=>on(t.element)),...(o.domModifications??[]).flatMap(t=>[...on(t.element),...on(t.sourceElement)])])}function Cs(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Er(t?[...e,...t.annotations.flatMap(n=>[yt(n.pathname,200),yt(n.linkedSelector,400),...n.elements.flatMap(on)])]:e)}function Gl(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function $s(o){let e=o.annotations.flatMap(r=>{let i=Gl(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(`
199
+
200
+ `);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}\`
201
+ ${i.map(s=>`- ${s}`).join(`
202
202
  `)}`).join(`
203
- `)}var Ps={name:"@popmelt.com/core",version:"0.10.1",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},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",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 dt=Ps.version;var Fl=1111,zl=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Wl=1800*1e3,Hl=3600*1e3,As=45e3,Gl=5e3,Vl=1e4,Kl=2*1024*1024;function js(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(`
204
- `)}function Mn(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Ms(o){let e=o.findLastIndex(i=>i.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(i=>i.role==="assistant"&&i.imprintSummary?.resolvedAction==="no"&&!!i.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function Ql(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 $s(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 Xl(o,e,t){let n=[...t];for(let i of o)if(i.type==="tool_use"){let r=i.tool||"",s=i.file??void 0,d=i.content??void 0,c=s?s.split("/").pop()??s:void 0,l;switch(r){case"Read":l=c?`Reading ${c}`:"Reading file";break;case"Edit":l=c?`Editing ${c}`:"Editing file";break;case"Write":l=c?`Writing ${c}`:"Writing file";break;case"Bash":l=d?d.split(`
205
- `)[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=r?`Using ${r}`:"tool";break}let w=s??d??void 0,R=s?Cs(s)?s:ql(e,s):void 0,b=n[n.length-1];b&&b.kind==="tool_group"&&b.tool===r?b.items.push({label:l,detail:w,...R?{filePath:R}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:l,detail:w,...R?{filePath:R}:{}}]})}return n}function Yl(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(`
206
- `)}function Zl(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Es(o){let e=o.styleModifications.flatMap(s=>{let d=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(c=>`${d}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),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"}`),i=o.annotations.map(s=>{let d=s.instruction?.trim();if(d)return d;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let c=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${c}`}),r=[...e,...n,...t,...i].map(s=>Zl(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function ep(o,e){let t=o.headers.origin;$s(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 tp=16384,np=131072;async function _e(o,e=tp){let t=[],n=0;for await(let r of o){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let i=JSON.parse(Buffer.concat(t).toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object");return i}async function op(o,e){let t=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>e)throw new Error("Request body too large");t.push(r)}return Buffer.concat(t)}function ip(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,i,r]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function Mo(o,e){try{o.res.write(`event: ${e.type}
203
+ `)}var Os={name:"@popmelt.com/core",version:"0.10.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 .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},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",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 ct=Os.version;var dp=1111,cp=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],lp=1800*1e3,pp=3600*1e3,Bs=45e3,up=5e3,mp=1e4,fp=2*1024*1024;function Js(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(`
204
+ `)}function $n(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 hp(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 zs(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 gp(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,c=s?s.split("/").pop()??s:void 0,l;switch(i){case"Read":l=c?`Reading ${c}`:"Reading file";break;case"Edit":l=c?`Editing ${c}`:"Editing file";break;case"Write":l=c?`Writing ${c}`:"Writing file";break;case"Bash":l=a?a.split(`
205
+ `)[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 b=s??a??void 0,S=s?Us(s)?s:sp(e,s):void 0,y=n[n.length-1];y&&y.kind==="tool_group"&&y.tool===i?y.items.push({label:l,detail:b,...S?{filePath:S}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:l,detail:b,...S?{filePath:S}:{}}]})}return n}function yp(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(`
206
+ `)}function Ip(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function qs(o){let e=o.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(c=>`${a}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),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 c=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${c}`}),i=[...e,...n,...t,...r].map(s=>Ip(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function wp(o,e){let t=o.headers.origin;zs(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 C(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}var vp=16384,bp=131072;async function $e(o,e=vp){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 xp(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 Sp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function Tp(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 Co(o,e){try{o.res.write(`event: ${e.type}
207
207
  data: ${JSON.stringify(e)}
208
208
 
209
- `)}catch{}}function nn(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Eo(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}}function sp(o,e){return new Promise((t,n)=>{let i=s=>{o.removeListener("listening",r),n(s)},r=()=>{o.removeListener("error",i),t()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function Os(o={}){let e=new Date().toISOString(),t=o.port??Fl,n=o.projectRoot??process.cwd(),i=await $l(n).catch(()=>n),r=Lt(i),s=await Bn(i),d=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Be(Bl(),"popmelt-bridge"),l=o.maxTurns??40,w=o.maxBudgetUsd??1,R=[...o.allowedTools??zl],b=o.claudePath??"claude",k=o.copilotPath??"copilot",S=o.provider??"codex",f=o.timeoutMs,p=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=o.restartMode??"embedded",v=t,u={},M={claude:b,codex:"codex",copilot:k};for(let[a,I]of Object.entries(M))try{let j=I.includes("/")?I:El("which",[I],{encoding:"utf-8"}).trim();u[a]={available:!0,path:j}}catch{u[a]={available:!1,path:null}}function h(a,I){return new Promise(j=>{let y=ks(I,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,P=$=>{A||(A=!0,j($))},O=setTimeout(()=>{y.kill("SIGTERM"),P(!0)},5e3);y.on("error",()=>{clearTimeout(O),P(!1)}),y.on("close",$=>{clearTimeout(O),P($===0)})})}await Promise.all([(async()=>{u.claude&&(u.claude.models=u.claude.available&&u.claude.path?await as(u.claude.path).catch(()=>go):go)})(),(async()=>{u.codex&&(u.codex.models=u.codex.available&&u.codex.path?await ss(u.codex.path).catch(()=>Tn):Tn)})(),(async()=>{u.copilot&&(u.copilot.models=u.copilot.available&&u.copilot.path?await rs(u.copilot.path).catch(()=>[Pn]):[Pn])})()]);let[m,E,D]=await Promise.all([ni(i),oi(i),ii(i,u.copilot?.path??k)]);u.claude&&(u.claude.mcp=m),u.codex&&(u.codex.mcp=E),u.copilot&&(u.copilot.mcp=D),m.found&&m.name&&R.push(`mcp__${m.name}__*`),await _l(c,{recursive:!0}),_s(c).catch(()=>{});let T=new Io(1),C=new Zn,z=new to(As),X=null,G=0,Y=!1,x=()=>{G+=1,Y=!1,X&&clearTimeout(X),X=null},Q=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},L=()=>{if(g!=="detached"||z.size>0||Y)return;Y=!0;let a=++G,I=Date.now()+Vl,j=()=>{if(a!==G)return;if(z.size>0){x();return}if(!(T.isRunning||T.depth>0||C.isRunning||C.depth>0)||Date.now()>=I){Y=!1,X=setTimeout(Q,50),X.unref?.();return}X=setTimeout(j,250),X.unref?.()};j()},K=new Set,H=new ko(i),B=await H.recoverInterruptedTurns();B>0&&console.warn(`[Popmelt] Recovered ${B} interrupted thread turn(s) from durable history.`);let V=new Kn(i);V.sweep();let W=new mo(i),ee=new Nt(i,r);try{let a=await ee.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let ke=new Ro(i),Je=new Wn(i),ue=new Yn(i,{claudePath:b,provider:S,timeoutMs:f,loadProjectableDecisions:a=>W.getProjectableDecisions(a),onEvent:a=>{for(let I of K)Mo(I,a)}}),Ce=new Dn({projectRoot:i,threadStore:H,memoryService:W,imprintService:ee,loadConcreteModel:()=>ue.loadModel()});W.beginAutomaticInitialization({writerVersion:dt}).then(async a=>{a.state==="ready"?(await W.migrateImprintSnapshot(),await W.syncImprintGraph(),await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),S!=="copilot"&&(await ue.getUnprojectedPatternDecisions()).length>0&&await Xe({provider:S,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${v}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let gt=20,on=300*1e3,Re=[];function nt(){let a=Date.now()-on;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>gt);)Re.shift()}let yt=new Map,It=null,En;T.addListener((a,I,j)=>{for(let y of K)(!j||!y.sourceId||y.sourceId===j)&&Mo(y,a)}),C.addListener((a,I,j)=>{for(let y of K)(!j||!y.sourceId||y.sourceId===j)&&Mo(y,a)}),C.setProcessor(async a=>{let I=a.provider??S;try{let j=await ue.run({provider:I,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let y=await ue.loadRuns(),A=j.runId?y.runs.find(O=>O.id===j.runId):void 0;if(j.success&&j.proposalId){let O=await ue.findModelProposal(j.proposalId),$=await ue.loadModel(),q=O?yr(O,$):null;if(O&&q){let N=O.decisionIds.map(J=>({decisionId:J,status:"projected"}));await W.applyModelProjection({runId:O.runId??O.id,presentationJobId:O.presentationJobId,decisionIds:O.decisionIds,changes:q.map(J=>({path:J.path,value:J.value,decisionIds:J.decisionIds})),coverage:N}),await ue.applySelectedModelProposal(O.id,q.map(J=>({path:J.path,value:J.value})),q.map(J=>({group:J.path[0]==="rules"||J.path[0]==="components"||J.path[0]==="tokens"?J.path[0]:"model",label:J.label??J.id,detail:J.rationale,path:J.path,value:J.value})),"automatic")}}let P=Yl(j,A);if(a.threadId&&(await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:I})),j.success)a.status="done",a.result=P,C.broadcast({type:"done",jobId:a.id,success:!0,responseText:P,threadId:a.threadId},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt();else{if(a.status="error",a.error=j.error??"Projection failed",a.threadId){let O=`Model projection failed.
209
+ `)}catch{}}function rn(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function $o(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}}function Pp(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??dp,n=o.projectRoot??process.cwd(),r=await Zl(n).catch(()=>n),i=Kt(r),s=await Xn(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Le(op(),"popmelt-bridge"),l=o.maxTurns??40,b=o.maxBudgetUsd??1,S=[...o.allowedTools??cp],y=o.claudePath??"claude",k=o.copilotPath??"copilot",T=o.provider??"codex",h=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=o.restartMode??"embedded",I=t,p={},j={claude:y,codex:"codex",copilot:k};for(let[d,v]of Object.entries(j))try{let A=v.includes("/")?v:Ql("which",[v],{encoding:"utf-8"}).trim();p[d]={available:!0,path:A}}catch{p[d]={available:!1,path:null}}function f(d,v){return new Promise(A=>{let w=Ds(v,["--version"],{stdio:["ignore","ignore","ignore"]}),M=!1,R=J=>{M||(M=!0,A(J))},N=setTimeout(()=>{w.kill("SIGTERM"),R(!0)},5e3);w.on("error",()=>{clearTimeout(N),R(!1)}),w.on("close",J=>{clearTimeout(N),R(J===0)})})}await Promise.all([(async()=>{p.claude&&(p.claude.models=p.claude.available&&p.claude.path?await ys(p.claude.path).catch(()=>wo):wo)})(),(async()=>{p.codex&&(p.codex.models=p.codex.available&&p.codex.path?await gs(p.codex.path).catch(()=>Mn):Mn)})(),(async()=>{p.copilot&&(p.copilot.models=p.copilot.available&&p.copilot.path?await hs(p.copilot.path).catch(()=>[jn]):[jn])})()]);let[m,E,D]=await Promise.all([Ir(r),wr(r),vr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=m),p.codex&&(p.codex.mcp=E),p.copilot&&(p.copilot.mcp=D),m.found&&m.name&&S.push(`mcp__${m.name}__*`),await Xl(c,{recursive:!0}),Fs(c).catch(()=>{});let P=new bo(1),O=new mo,W=new ho(Bs),K=null,_=0,H=!1,G=()=>{_+=1,H=!1,K&&clearTimeout(K),K=null},fe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(g!=="detached"||W.size>0||H)return;H=!0;let d=++_,v=Date.now()+mp,A=()=>{if(d!==_)return;if(W.size>0){G();return}if(!(P.isRunning||P.depth>0||O.isRunning||O.depth>0)||Date.now()>=v){H=!1,K=setTimeout(fe,50),K.unref?.();return}K=setTimeout(A,250),K.unref?.()};A()},oe=new Set,x=new jo(r),$=await x.recoverInterruptedTurns();$>0&&console.warn(`[Popmelt] Recovered ${$} interrupted thread turn(s) from durable history.`);let L=new co(r);L.sweep();let B=new Gt(r),Q=new gt(r,i);try{let d=await Q.store.migrateTopology();d.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${d.relationMutations} relation mutation(s)).`)}catch(d){console.warn(`[Popmelt] Imprint topology migration deferred: ${d instanceof Error?d.message:String(d)}`)}let he=new Ao(r),_e=new ro(r),se=new uo(r,{claudePath:y,provider:T,timeoutMs:h,loadProjectableDecisions:d=>B.getProjectableDecisions(d),onEvent:d=>{for(let v of oe)Co(v,d)}}),Oe=new Kn({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:x,memoryService:B,imprintService:Q,loadConcreteModel:()=>se.loadModel()});B.beginAutomaticInitialization({writerVersion:ct}).then(async d=>{d.state==="ready"?(await B.migrateImprintSnapshot(),await B.syncImprintGraph(),await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),T!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await Ye({provider:T,reason:"Project accepted decisions that were waiting when the bridge restarted"})):d.state==="degraded"&&console.warn(`[\u22B9 ${I}] Product memory is degraded; legacy preview remains available: ${d.error}`)});let It=20,sn=300*1e3,Me=[];function ot(){let d=Date.now()-sn;for(;Me.length>0&&(Me[0].completedAt<d||Me.length>It);)Me.shift()}let wt=new Map,vt=null,On;P.addListener((d,v,A)=>{for(let w of oe)(!A||!w.sourceId||w.sourceId===A)&&Co(w,d)}),O.addListener((d,v,A)=>{for(let w of oe)(!A||!w.sourceId||w.sourceId===A)&&Co(w,d)}),O.setProcessor(async d=>{let v=d.provider??T;try{let A=await se.run({provider:v,model:d.model,threadId:d.threadId,presentationJobId:d.id,agentSettings:d.agentSettings});if(d.status==="cancelled")return;let w=await se.loadRuns(),M=A.runId?w.runs.find(N=>N.id===A.runId):void 0;if(A.success&&A.proposalId){let N=await se.findModelProposal(A.proposalId),J=await se.loadModel(),U=N?Ui(N,J):null;if(N&&U){let F=N.decisionIds.map(q=>({decisionId:q,status:"projected"}));await B.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(q=>({path:q.path,value:q.value,decisionIds:q.decisionIds})),coverage:F}),await se.applySelectedModelProposal(N.id,U.map(q=>({path:q.path,value:q.value})),U.map(q=>({group:q.path[0]==="rules"||q.path[0]==="components"||q.path[0]==="tokens"?q.path[0]:"model",label:q.label??q.id,detail:q.rationale,path:q.path,value:q.value})),"automatic")}}let R=yp(A,M);if(d.threadId&&(await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:R,model:d.model,provider:v})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:R,model:d.model,provider:v})),A.success)d.status="done",d.result=R,O.broadcast({type:"done",jobId:d.id,success:!0,responseText:R,threadId:d.threadId},d.id,d.sourceId),Me.push({id:d.id,status:"done",completedAt:Date.now(),threadId:d.threadId,annotationIds:d.annotationIds,color:"#000000",kind:"project_model"}),ot();else{if(d.status="error",d.error=A.error??"Projection failed",d.threadId){let N=`Model projection failed.
210
210
 
211
- ${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}catch(j){if(a.status==="cancelled")return;if(a.status="error",a.error=j instanceof Error?j.message:String(j),a.threadId){let y=`Model projection failed.
211
+ ${d.error}`;await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:N,error:d.error,model:d.model,provider:v})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:N,error:d.error,model:d.model,provider:v})}O.broadcast({type:"error",jobId:d.id,threadId:d.threadId,message:d.error,provider:v,model:d.model},d.id,d.sourceId),Me.push({id:d.id,status:"error",completedAt:Date.now(),error:d.error,threadId:d.threadId,annotationIds:d.annotationIds,color:"#000000",kind:"project_model"}),ot()}}catch(A){if(d.status==="cancelled")return;if(d.status="error",d.error=A instanceof Error?A.message:String(A),d.threadId){let w=`Model projection failed.
212
212
 
213
- ${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}),T.setProcessor(async a=>{let I=a,j=I._replyPrompt,y=I._replyText,A=I._replyImagePaths,P=a.provider??S,O=!!(a.surfacedProposalIds?.length&&j),$=!O&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&y!==void 0&&await H.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let ne=await H.getThread(a.threadId);if(ne){for(let Ie=ne.messages.length-1;Ie>=0;Ie--)if(ne.messages[Ie].sessionId){q=ne.messages[Ie].sessionId;break}}}O&&(q=void 0);let N;if(q&&j){if(N=y??j,A&&A.length>0){N+=`
213
+ ${d.error}`;await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:w,error:d.error,model:d.model,provider:v})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:w,error:d.error,model:d.model,provider:v})}O.broadcast({type:"error",jobId:d.id,threadId:d.threadId,message:d.error,provider:v,model:d.model},d.id,d.sourceId),Me.push({id:d.id,status:"error",completedAt:Date.now(),error:d.error,threadId:d.threadId,annotationIds:d.annotationIds,color:"#000000",kind:"project_model"}),ot()}}),P.setProcessor(async d=>{let v=d,A=v._replyPrompt,w=v._replyText,M=v._replyImagePaths,R=d.provider??T,N=!!(d.surfacedProposalIds?.length&&A),J=!N&&!["synthesize","project_model"].includes(d.kind??"");d.threadId&&w!==void 0&&await x.updateMessage(d.threadId,d.id,{queued:!1});let U;if(d.threadId){let ee=await x.getThread(d.threadId);if(ee){for(let we=ee.messages.length-1;we>=0;we--)if(ee.messages[we].sessionId){U=ee.messages[we].sessionId;break}}}N&&(U=void 0);let F;if(U&&A){if(F=w??A,M&&M.length>0){F+=`
214
214
 
215
- The developer attached reference images with their reply:`;for(let ne of A)N+=`
216
- Attached image: use the Read tool to view the image at: ${ne}`}a.kind==="synthesize"?N+=`
215
+ The developer attached reference images with their reply:`;for(let ee of M)F+=`
216
+ Attached image: use the Read tool to view the image at: ${ee}`}d.kind==="synthesize"?F+=`
217
217
 
218
- Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:N+="\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(q)N=xn(a.feedback,a.imagePaths,a.attachmentFiles)+`
218
+ 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(U)F=Rn(d.feedback,d.imagePaths,d.attachmentFiles)+`
219
219
 
220
220
  Follow the developer's instructions. If they ask for changes, apply them to the source files.
221
221
 
222
- After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(P!=="codex"?`
222
+ After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(R!=="codex"?`
223
223
 
224
- IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let ne=!j&&a.threadId?await H.getThreadHistory(a.threadId):void 0,Ie=j?null:await ue.loadModel();N=j??Zr(a.screenshotPath,a.feedback,{threadHistory:ne&&ne.length>0?ne:void 0,provider:P,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:Ie??void 0,screenshotPaths:a.screenshotPaths})}N+=cn(a.memoryReview),$&&(N+=Jt(a.imprintContext,{requestText:y??Ct(a.feedback)})),a.threadId&&!O&&(N+=`
224
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${d.screenshotPath}`:"");else{let ee=!A&&d.threadId?await x.getThreadHistory(d.threadId):void 0,we=A?null:await se.loadModel();F=A??cs(d.screenshotPath,d.feedback,{threadHistory:ee&&ee.length>0?ee:void 0,provider:R,imagePaths:d.imagePaths,attachmentFiles:d.attachmentFiles,designModel:we??void 0,screenshotPaths:d.screenshotPaths})}F+=ln(d.memoryReview),J&&(F+=Lt(d.imprintContext,{requestText:w??Ot(d.feedback)})),d.threadId&&!N&&(F+=`
225
225
 
226
- ${Yr}`),N+=`
226
+ ${ds}`),F+=`
227
227
 
228
- ${Xr}`;let J=rp(a.color,`[\u22B9 ${v}:${a.id}]`),he=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${J} Reviewing ${he} (provider: ${P})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let U=new fo(a.id),se=new wo(a.id,a.imprintContext),me=(ne,Ie)=>{if(ne.type==="delta"&&"text"in ne){let Oe=se.push(ne.text),Ue=U.push(Oe.visibleText);Ue.visibleText&&(T.accumulateText(Ie,"response",Ue.visibleText),T.broadcast({...ne,text:Ue.visibleText},Ie,a.sourceId));for(let Ee of Ue.orientations)T.broadcast({type:"orientation",jobId:Ie,orientation:Ee},Ie,a.sourceId);for(let Ee of Oe.usages)T.broadcast({type:"imprint_used",jobId:Ie,usage:Ee},Ie,a.sourceId);return}else ne.type==="thinking"&&"text"in ne&&T.accumulateText(Ie,"thinking",ne.text);T.broadcast(ne,Ie,a.sourceId)},{process:te,result:ge}=P==="codex"?zn(a.id,{prompt:N,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:O?"read-only":void 0,configOverrides:Jn(a.agentSettings),onEvent:me}):P==="copilot"?lr(a.id,{prompt:N,projectRoot:i,resumeSessionId:q,model:a.model,timeoutMs:f,copilotPath:u.copilot?.path??k,onEvent:me}):Ln(a.id,{prompt:N,projectRoot:i,maxTurns:l,maxBudgetUsd:w,allowedTools:O?["Read"]:R,claudePath:b,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:me});T.setActiveProcess(a.id,te);let ie=await ge,ve=[...(ie.fileEdits??[]).map(ne=>ne.file_path),...(ie.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],Te=se.finalize(ie.text),pe=bi(Te.visibleText,a.id),Z=U.finalize(Te.visibleText),Se=pe.visibleText,We=ns(Se),ye=$?Bt(Se,{context:a.imprintContext,requestText:y??Ct(a.feedback),applicationOccurred:ve.length>0||We.some(ne=>ne.status==="resolved")}):{visibleText:Se,draft:void 0,error:void 0},He=ye.visibleText,Ae=$?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 ne of Z.orientations)T.broadcast({type:"orientation",jobId:a.id,orientation:ne},a.id,a.sourceId);for(let ne of Te.usages)T.broadcast({type:"imprint_used",jobId:a.id,usage:ne},a.id,a.sourceId);if(a.result=He,ie.success){console.log(`${J} Iteration complete`),ie.fileEdits&&ie.fileEdits.length>0&&console.log(`${J} Captured ${ie.fileEdits.length} file edit(s): ${ie.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),ie.editEvents&&ie.editEvents.length>0&&console.log(`${J} Captured ${ie.editEvents.length} edit event(s): ${ie.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),a.status="done";let ne=es(Se),Ie=We;if(Ie.length>0&&a.annotationIds&&a.annotationIds.length>0){let de=new Set(a.annotationIds);Ie.every(Ye=>de.has(Ye.annotationId))||(Ie=Ie.map((Ye,bt)=>({...Ye,annotationId:a.annotationIds[bt%a.annotationIds.length]})))}let Oe=ie.fileEdits&&ie.fileEdits.length>0?ie.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):ie.toolsUsed,Ue=T.getBufferedEvents(a.id),Ee=Xl(Ue?.events??[],i,pe.segments),je,re=Gr(Se),F=Hr(Se);if(F)if(!(a.memoryReview?.packets.some(ce=>ce.proposalId===F.proposalId)||a.surfacedProposalIds?.includes(F.proposalId)))je={status:"rejected",action:F.action,proposalId:F.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{je=await W.commitConversationalReview(F)}catch(ce){je={status:"rejected",action:F.action,proposalId:F.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=os(Se,ve.length),fe,Ge,Ci,$i,Zs=a.imprintContext?.pendingGroundingExplanationIds??[];if(ye.draft){let de=ye.draft.decision==="recognize"?[ye.draft.explanationId]:[],ce=ye.draft.decision==="recognize"?de:[...ye.draft.usedExplanationIds??[],...ye.draft.appliedExplanationIds??[]],Ye=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];ce.length>0&&(Ci=[...new Set(ce)]),Ye.length>0&&($i=[...new Set(Ye)])}ye.draft?.decision==="none"&&ee.recordNoop(ye.draft.reason);let Cn=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Cn&&!F&&!re){let de=a.imprintContext?.explanations.find(ce=>ce.id===Cn.explanationId&&ce.state==="grounded");de?Ge={explanationId:de.id,title:Cn.summary.title,detail:Cn.summary.detail,statement:de.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Oo=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(a.threadId&&Oo&&!F&&!re)try{fe=await ee.capture(Oo,{threadId:a.threadId,jobId:a.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:Zs,applicationOccurred:ve.length>0||Ie.some(de=>de.status==="resolved")}),fe?(Ae={state:"mutated"},await W.recordImprintEvidence({summary:fe,threadId:a.threadId,jobId:a.id}).catch(de=>console.warn(`${J} Canonical Imprint evidence linkage failed:`,de))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(de){Ae={state:"invalid",reason:de instanceof Error?de.message:String(de)},console.warn(`${J} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else Oo&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ye.error&&console.warn(`${J} Ignored invalid imprint block: ${ye.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&ee.recordAssessmentFailure(Ae.state);let Do=fe?.transactionId;if(a.threadId&&fe&&!fe.grounding){let de=await H.getThread(a.threadId),ce=new Set(fe.changes.map(bt=>bt.explanationId)),Ye=de?Ql(de.messages,ce):void 0;if(Ye?.imprintSummary){let bt=Ye.imprintSummary;await H.updateAssistantMessage(a.threadId,Ye.jobId,{imprintSummary:{...bt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(bt.additionalObservationCount??0)+1,coalescedTransactionIds:[...bt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let No=an({question:ne,resolutions:Ie,changedFiles:ve,decisionRequired:!!re,imprintTransactionId:Do,groundingRequired:!!fe?.grounding}),ea=Ee?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Et=a.lifecycle?Rn(a.lifecycle,Do?[Do]:[],Ae):void 0;if(a.threadId){let de=O?re?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":He;await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:de,resolutions:!O&&Ie.length>0?Ie:void 0,question:O?void 0:ne??void 0,sessionId:ie.sessionId,toolsUsed:O?void 0:Oe,editEvents:!O&&ie.editEvents&&ie.editEvents.length>0?ie.editEvents:void 0,segments:!O&&Ee&&Ee.length>0?Ee:void 0,turn:{phase:"complete",orientation:ea,result:No},result:No,memoryReviewCard:re??void 0,memoryReceipt:je,imprintSummary:fe,imprintRecognition:Ge,imprintUsedExplanationIds:Ci,imprintAppliedExplanationIds:$i,modelDetails:ae.length>0?ae:void 0,model:a.model,provider:P,...Et?{lifecycle:Et}:{}})}if(a.threadId&&!F&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let de=a.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await W.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:y??(Ct(a.feedback)||"[request unavailable]"),responseSummary:ne??He,outcome:ne?"question_asked":Ie.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:P,model:a.model,sessionId:ie.sessionId},subjectHints:de,filePaths:[...(ie.fileEdits??[]).map(ce=>ce.file_path),...(ie.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>Cs(ce)?Ll(i,ce):ce),resolutions:Ie.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Et?.submissionIds,outcomeId:Et?.outcomeId,imprintEvidenceIds:Et?.imprintEvidenceIds,imprintAssessment:Et?.imprintAssessment})}catch(ce){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}je?.status==="committed"&&je.decisionId&&P!=="copilot"&&await Xe({provider:P,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${je.decisionId}`}),ne&&(console.log(`${J} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${K.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),T.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:ne,annotationIds:a.annotationIds},a.id,a.sourceId)),ae.length>0&&(console.log(`${J} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),T.broadcast({type:"novel_patterns",jobId:a.id,patterns:ae,threadId:a.threadId},a.id,a.sourceId)),T.broadcast({type:"done",jobId:a.id,success:!0,resolutions:Ie.length>0?Ie:void 0,responseText:He,threadId:a.threadId,annotationIds:a.annotationIds,result:No},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${J} Error: ${ie.error}`),a.status="error",a.error=ie.error,a.threadId&&await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:ie.error||"Unknown error",model:a.model,provider:P,...a.lifecycle?{lifecycle:Rn(a.lifecycle)}:{}}),T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:ie.error||"Unknown error",provider:P,model:a.model,recoverable:ie.recoverableError,code:ie.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:ie.error,threadId:a.threadId,annotationIds:a.annotationIds});nt()});let be=Nl(async(a,I)=>{if(ep(a,I),a.method==="OPTIONS"){I.writeHead(204),I.end();return}let j=a.url||"/",y=j.split("?")[0],A=new URL(j,`http://127.0.0.1:${v}`),P=A.pathname,O=ip(a,A);if(O&&O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:jo(i)});return}if(P.startsWith("/ambient/")&&O!==r){_(I,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:r,requestProjectId:O});return}if(a.headers.origin){if(!$s(a.headers.origin)){_(I,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:jo(i)});return}}try{if(P.startsWith("/ambient/"))await lt(a,I,P);else if(a.method==="POST"&&P==="/draft-attachments"){let $=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",N=A.searchParams.get("kind"),J=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(I,400,{error:"A valid annotationId is required."});return}if(N!=="svg"&&N!=="text"||N==="svg"&&J!=="image/svg+xml"||N==="text"&&J!=="text/plain"){_(I,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let he=await op(a,Kl);if(he.length===0){_(I,400,{error:"Attachment is empty."});return}let U=await V.stage({annotationId:$,name:q,mimeType:J,kind:N,data:he});_(I,201,{attachment:{id:U.id,name:U.name,mimeType:U.mimeType,size:U.size,kind:U.kind}})}else if(a.method==="POST"&&P==="/draft-attachments/claim"){let $=await _e(a),q=Array.isArray($.ids)?$.ids.filter(N=>typeof N=="string").slice(0,100):[];await V.claim(q),_(I,200,{ok:!0})}else if(a.method==="DELETE"&&P.startsWith("/draft-attachments/"))await V.release([P.slice(19)]),_(I,200,{ok:!0});else if(a.method==="POST"&&P==="/send")await pt(a,I);else if(a.method==="POST"&&P==="/capture/native"){if(!p){_(I,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await _e(a),q=typeof $.pageUrl=="string"?$.pageUrl:"",N=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!q||!N){_(I,400,{error:"pageUrl and clip are required."});return}let J=await jr(p,{pageUrl:q,clip:{x:Number(N.x),y:Number(N.y),width:Number(N.width),height:Number(N.height)},scale:typeof $.scale=="number"?$.scale:1});I.writeHead(200,{"Content-Type":"image/webp","Content-Length":J.length,"Cache-Control":"no-store"}),I.end(J)}else if(a.method==="GET"&&P==="/events")vt(a,I);else if(a.method==="GET"&&P==="/status")await _o(a,I,O);else if(a.method==="GET"&&P==="/ui-preferences")await rn(I);else if(a.method==="PATCH"&&P==="/ui-preferences")await Le(a,I);else if(a.method==="PATCH"&&P==="/config")await Co(a,I);else if(a.method==="POST"&&P==="/leases"){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await _e(a),q=typeof $.leaseId=="string"?$.leaseId.trim():"",N=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!q||q.length>128){_(I,400,{error:"A valid leaseId is required."});return}x();let J=z.acquire(q,N);_(I,201,{ok:!0,lease:J,ttlMs:As})}catch{_(I,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(P.slice(8))}catch{_(I,400,{error:"Invalid lease id."});return}if(!$){_(I,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=z.heartbeat($);if(!q){_(I,404,{error:"Lease not found."});return}_(I,200,{ok:!0,lease:q})}else{let q=z.release($);_(I,q.found?200:404,{ok:q.found}),q.becameEmpty&&L()}}else if(a.method==="POST"&&P==="/shutdown"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0}),setTimeout(Q,100)}else if(a.method==="POST"&&P==="/restart"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of K)try{$.res.end()}catch{}be.close(()=>{ks(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&P==="/capabilities")_(I,200,{providers:u});else if(P.startsWith("/imprint/"))await ot(a,I,P);else if(P.startsWith("/memory/"))await $e(a,I,P);else if(a.method==="POST"&&P==="/mcp/install")await qs(a,I);else if(a.method==="POST"&&P==="/reply")await ut(a,I);else if(a.method==="POST"&&P==="/cancel")qe(a,I);else if(a.method==="POST"&&P==="/materialize")_(I,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&P==="/materialization-runs")_(I,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&P==="/projection-runs"){let $=await ue.loadRuns();_(I,200,$)}else if(a.method==="GET"&&P==="/projection/proposals"){let $=await ue.loadModelProposals();_(I,200,$)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let $=P.slice(22,-15);await wt($,a,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let $=P.slice(22,-6);await Mt($,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let $=P.slice(22,-8);await $o($,a,I)}else if(P.startsWith("/model/proposals/"))_(I,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&P==="/model/component")await Us(a,I);else if(a.method==="DELETE"&&P==="/model/component")await Fs(a,I);else if(a.method==="PATCH"&&P==="/model/token")await zs(a,I);else if(a.method==="DELETE"&&P==="/model/token")await Ws(a,I);else if(a.method==="POST"&&P==="/model/consolidate")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&P==="/model/synthesize")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&P==="/model"){let $=await ue.loadModel();_(I,200,{model:$})}else if(a.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let $=P.slice(6,P.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),N=T.getBufferedEvents($,isNaN(q)?-1:q);N?_(I,200,N):_(I,404,{error:"Unknown job"})}else if(a.method==="GET"&&y.startsWith("/files/"))await Ks(y.slice(7),I);else if(a.method==="GET"&&P==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await H.listRecent($);_(I,200,q)}else if(a.method==="GET"&&P.startsWith("/decision/")){let $=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(I,400,{error:"Invalid decision id"});else{let q=await H.getThread($),N=[...q?.messages??[]].reverse().find(J=>J.annotationSnapshot);if(q&&N?.annotationSnapshot){let J=[...q.messages].reverse().find(he=>he.resolutions?.length);_(I,200,{decision:{id:q.id,createdAt:N.timestamp,url:N.annotationSnapshot.url,viewport:N.annotationSnapshot.viewport,color:N.annotationSnapshot.color,annotations:N.annotationSnapshot.annotations,resolutions:J?.resolutions??[]},authority:"thread_snapshot"})}else{let J=await Je.loadDecision($);J?_(I,200,{decision:J,authority:"legacy_archive"}):_(I,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&P.startsWith("/thread/")){let $=P.slice(8);await Qs($,I)}else if(a.method==="DELETE"&&P.startsWith("/thread/")){let $=P.slice(8);await Xs($,I)}else a.method==="GET"&&(P==="/canvas"||P==="/canvas/")?Hs(a,I):a.method==="GET"&&P==="/canvas/manifest"?await Gs(I):a.method==="GET"&&P==="/canvas/app.mjs"?await Vs(I):_(I,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(I,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function lt(a,I,j){if(a.method!=="POST"){_(I,405,{error:"Ambient endpoints accept POST requests only."});return}let y=await _e(a,np),A=typeof y.sessionId=="string"?y.sessionId.trim():"",P=typeof y.turnId=="string"?y.turnId.trim():"",O=typeof y.executionOwner=="string"?y.executionOwner:void 0;if(j==="/ambient/context"){let $=typeof y.query=="string"?y.query.trim():"";if(!$){_(I,400,{error:"query is required."});return}let q=Array.isArray(y.subjectHints)?y.subjectHints.filter(N=>typeof N=="string"&&!!N.trim()).slice(0,20):void 0;_(I,200,await Ce.expandContext({query:$,subjectHints:q}));return}if(j==="/ambient/turns/assess"){let $=typeof y.threadId=="string"?y.threadId.trim():"",q=typeof y.jobId=="string"?y.jobId.trim():"",N=typeof y.assessmentText=="string"?y.assessmentText.trim():"";if(!$||!q||!N){_(I,400,{error:"threadId, jobId, and assessmentText are required."});return}let J=Array.isArray(y.semanticCandidates)?y.semanticCandidates.flatMap(U=>{if(!U||typeof U!="object"||Array.isArray(U))return[];let se=U,me=typeof se.claim=="string"?se.claim.trim():"",te=typeof se.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(se.proposedKind)?se.proposedKind:void 0;return me?[{claim:me,rationale:typeof se.rationale=="string"?se.rationale.trim():void 0,proposedKind:te,sourceText:typeof se.sourceText=="string"?se.sourceText.trim():void 0}]:[]}).slice(0,8):[],he=await Ce.assess({threadId:$,jobId:q,assessmentText:N,semanticCandidates:J});_(I,he.status==="recorded"?200:404,he);return}if(!A||!P||A.length>256||P.length>256){_(I,400,{error:"Valid sessionId and turnId values are required."});return}if(j==="/ambient/turns/prepare"){let $=typeof y.prompt=="string"?y.prompt.trim():"";if(!$){_(I,400,{error:"prompt is required."});return}_(I,200,await Ce.prepare({sessionId:A,turnId:P,prompt:$,model:typeof y.model=="string"?y.model:void 0,executionOwner:O}));return}if(j==="/ambient/turns/event"){let $=typeof y.toolName=="string"?y.toolName.trim():"";if(!$){_(I,400,{error:"toolName is required."});return}_(I,200,await Ce.recordEvent({sessionId:A,turnId:P,executionOwner:O,toolName:$,toolUseId:typeof y.toolUseId=="string"?y.toolUseId:void 0,toolInput:y.toolInput,toolResponse:y.toolResponse}));return}if(j==="/ambient/turns/complete"){_(I,200,await Ce.complete({sessionId:A,turnId:P,executionOwner:O,lastAssistantMessage:typeof y.lastAssistantMessage=="string"?y.lastAssistantMessage:void 0,model:typeof y.model=="string"?y.model:void 0}));return}_(I,404,{error:"Ambient endpoint not found."})}async function $e(a,I,j){try{if(a.method==="GET"&&j==="/memory/status"){_(I,200,await W.status());return}if(a.method==="GET"&&j==="/memory/diagnostics"){_(I,200,await W.diagnostics());return}if(a.method==="GET"&&j==="/memory/model-view"){_(I,200,await W.getModelView());return}if(a.method==="GET"&&j==="/memory/imprint-view"){let y=await H.load(),A=[...new Set(Object.values(y.threads).flatMap(P=>Mn(P.messages)))];_(I,200,await W.getImprintView(A,new Set(Object.keys(y.threads))));return}if(a.method==="POST"&&j==="/memory/constraints"){let y=await _e(a),A=typeof y.reactComponent=="string"?y.reactComponent.trim():"",P=await W.getModelView(),O=A?P.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(I,200,{modelEntries:O});return}if(a.method==="POST"&&j==="/memory/conversation-action"){let y=await _e(a),A=typeof y.threadId=="string"?y.threadId:"",P=typeof y.proposalId=="string"?y.proposalId:"",O=String(y.action);if(!A||!P||!["accept","edit_and_accept","reject","defer"].includes(O)){_(I,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await H.getThread(A),q=$?.messages.find(pe=>pe.memoryReviewCard?.proposalId===P)?.memoryReviewCard,N=$?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===P),J=$?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await W.findPendingProposalsForThread(A)).find(pe=>pe.proposalId===P):void 0,he=typeof y.kind=="string"&&["principle","preference","rule","constraint"].includes(y.kind)?y.kind:void 0,U=q?.kind??N?.proposedKind??J?.proposedKind??he;if(!$||!q&&!N&&!J){_(I,409,{error:"This decision candidate was not surfaced in the thread."});return}if((O==="accept"||O==="edit_and_accept")&&!U){_(I,400,{error:"The decision kind is required to accept this candidate."});return}let se=await ue.findModelProposalsByThread(A),me=(await Promise.all(se.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Z=>W.findPendingProposalForLegacyDecision(Z)))).some(Z=>Z?.proposalId===P)})))).find(pe=>pe.matches)?.proposal,te={proposalId:P,action:O,kind:U,claim:O==="edit_and_accept"&&typeof y.claim=="string"?y.claim.trim():void 0,reason:O==="defer"?void 0:`The owner explicitly chose ${O.replaceAll("_"," ")} from the decision review card.`,taskContext:O==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:O==="defer"?["different_action","owner_request"]:void 0};if(te.action==="edit_and_accept"&&!te.claim){_(I,400,{error:"Edited decision wording is required."});return}let ge=await W.commitConversationalReview(te),ie=`memory-${ct().slice(0,8)}`,ve=O==="accept"?"> Accepted decision":O==="edit_and_accept"?"> Edited and accepted decision":O==="reject"?"> Rejected decision":"> Deferred decision";await H.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:ie,replyToQuestion:ve}),await H.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:ie,responseText:"",memoryReceipt:ge,provider:nn(typeof y.provider=="string"?y.provider:void 0),model:typeof y.model=="string"?y.model:void 0}),ge.status==="committed"&&me&&await ue.dismissModelProposal(me.id);let Te=nn(typeof y.provider=="string"?y.provider:void 0);ge.status==="committed"&&ge.decisionId&&Te!=="copilot"&&await Xe({provider:Te,model:typeof y.model=="string"?y.model:void 0,agentSettings:qt(y),threadId:A,reason:`Project accepted decision ${ge.decisionId}`}),_(I,ge.status==="committed"?200:409,{receipt:ge});return}if(a.method==="POST"&&j==="/memory/analyze"){let y=await _e(a),A=await W.analyzeLegacy({projectKey:typeof y.projectKey=="string"?y.projectKey:void 0}),P=Object.fromEntries([...new Set(A.issues.map(O=>O.code))].map(O=>[O,A.issues.filter($=>$.code===O).length]));_(I,200,{...A,issues:void 0,issueCounts:P});return}if(a.method==="POST"&&j==="/memory/review"){let y=await _e(a),A=await W.review(Ii(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,A);return}if(a.method==="POST"&&j==="/memory/context"){let y=await _e(a),A=await W.contextualize(Ii(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,A);return}if(a.method==="POST"&&j==="/memory/initialize"){let y=await _e(a),A=await W.initializeFromLegacy({confirmed:y.confirm===!0,projectKey:typeof y.projectKey=="string"?y.projectKey:void 0,writerVersion:dt});_(I,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&j==="/memory/plan"){let y=await _e(a),A=await W.planReview(yi(y.command),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,A.result.ok?200:422,A);return}if(a.method==="POST"&&j==="/memory/commit"){let y=await _e(a),A=y.transaction&&typeof y.transaction=="object"&&!Array.isArray(y.transaction)?y.transaction:{},P=await W.commitReview(yi(y.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(I,200,{status:await W.status(),journal:P.report});return}if(a.method==="POST"&&j==="/memory/recover"){let y=await _e(a),A=await W.recover(y.confirm===!0);_(I,200,{status:await W.status(),journal:A.report});return}_(I,404,{error:"Memory endpoint not found."})}catch(y){let A=y instanceof Error?y.message:String(y),P=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),O=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(P||O){_(I,P?409:400,{error:A});return}throw y}}async function ot(a,I,j){if(a.method==="GET"&&j==="/imprint/status"){let[y,A]=await Promise.all([ee.store.load(),H.load()]),P=[...new Set(Object.values(A.threads).flatMap(O=>Mn(O.messages)))].filter(O=>y.graph.explanations.some($=>$.id===O&&$.state==="testing"));_(I,200,{state:"ready",head:y.graph.head,updatedAt:y.graph.updatedAt,explanationCount:y.graph.explanations.filter(O=>O.state!=="retired").length,concreteCount:y.graph.concrete.length,relationCount:y.graph.relations.length,pendingGroundingCount:P.length,recoveredTransactions:y.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&j==="/imprint/action"){let y=await _e(a),A=typeof y.threadId=="string"?y.threadId:"",P=typeof y.transactionId=="string"?y.transactionId:"",O=String(y.action);if(!A||!P||!["yes","this_time","no"].includes(O)){_(I,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await H.getThread(A),N=[...q?.messages??[]].reverse().find(te=>te.role==="assistant"&&te.imprintSummary?.transactionId===P),J=N?.imprintSummary;if(!q||!N||!J){_(I,409,{error:"This imprint summary is not available in the thread."});return}if(J.resolvedAction){_(I,409,{error:"This imprint summary has already been resolved."});return}let he=`imprint-${ct().slice(0,8)}`;await ee.applyGroundingAction({summary:J,action:O,threadId:A,jobId:he}),O!=="no"&&await W.recordImprintEvidence({summary:J,action:O,threadId:A,jobId:he}).catch(te=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",te));let U=_t(N.result,!!N.question),se=N.turn?{...N.turn,result:_t(N.turn.result,!!N.question)}:void 0;await H.updateAssistantMessage(A,N.jobId,{imprintSummary:{...J,resolvedAction:O},...U?{result:U}:{},...se?{turn:se}:{}});let me={yes:"> Yes",this_time:"> This time",no:"> No"};if(await H.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:he,replyToQuestion:me[O]}),O==="no"){let te="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",ge=an({question:te});await H.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:he,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:te,turn:{phase:"complete",orientation:[],result:ge},result:ge})}_(I,200,{ok:!0,action:O});return}_(I,404,{error:"Imprint endpoint not found."})}async function pt(a,I){let{screenshot:j,feedback:y,color:A,provider:P,model:O,reasoningEffort:$,serviceTier:q,sourceId:N,pastedImages:J,pageScreenshots:he}=await vi(a),U;try{U=JSON.parse(y)}catch{_(I,400,{error:"Invalid feedback JSON"});return}let se=U.annotations.flatMap(re=>(re.attachments??[]).map(F=>({id:F.id,annotationId:re.id}))),me;try{me=se.length>0?await V.promote(se):void 0}catch(re){_(I,409,{error:re instanceof Error?re.message:"Draft attachment unavailable."});return}let te=ct().slice(0,8),ge={};if(he.length>0)for(let re of he){let F=encodeURIComponent(re.pathname),ae=Be(c,`screenshot-${te}-${F}.webp`);await Ao(ae,re.data),ge[re.pathname]=ae}let ie=Be(c,`screenshot-${te}.webp`);await Ao(ie,j);let ve={};if(J.length>0)for(let re of J){let F=Be(c,`pasted-${te}-${re.annotationId}-${re.index}.webp`);await Ao(F,re.data),ve[re.annotationId]||(ve[re.annotationId]=[]),ve[re.annotationId].push(F)}let Te=hs(U),pe;if(Te.length>0){let re=await H.findContinuationThread(Te);re?(pe=re.id,await H.addElementIdentifiers(pe,Te)):pe=(await H.createThread(`thread-${ct()}`,Te)).id}else pe=(await H.createThread(`thread-${ct()}`,[])).id;let Z=U.annotations.map(re=>re.id),Se=Object.keys(ge).length>0,We=await dn(W,U,Te,re=>console.warn(`[\u22B9 ${v}:${te}] Contextual memory unavailable; continuing without it:`,re instanceof Error?re.message:String(re))),ye=(await H.getThread(pe))?.messages??[],He=await ee.contextualize({text:Ct(U),subjectHints:xs(U,Te),pendingGroundingExplanationIds:Mn(ye),correctionExplanationIds:Ms(ye)}).catch(re=>{console.warn(`[\u22B9 ${v}:${te}] Imprint context unavailable; continuing without it:`,re instanceof Error?re.message:String(re))}),Ae=Pi({jobId:te,threadId:pe,artifactIds:gs(U,te)}),ne={id:te,status:"queued",screenshotPath:ie,feedback:U,createdAt:Date.now(),color:A,threadId:pe,annotationIds:Z,provider:nn(P),model:O||void 0,agentSettings:qt({reasoningEffort:$,serviceTier:q}),...Object.keys(ve).length>0?{imagePaths:ve}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:N||void 0,...Se?{screenshotPaths:ge}:{},...We?{memoryReview:We}:{},...He?{imprintContext:He}:{},lifecycle:Ae},Ie=new Set(U.annotations.map(re=>re.pathname).filter(Boolean)),Oe;if(Ie.size>1){let re=new Map;for(let F of U.annotations){let ae=F.pathname||"(unknown)";re.has(ae)||re.set(ae,[]),re.get(ae).push(F.instruction||Es({...U,annotations:[F]}))}Oe=[...re.entries()].map(([F,ae])=>`\`${F}\`
229
- ${ae.map(fe=>`- ${fe}`).join(`
228
+ ${as}`;let q=Tp(d.color,`[\u22B9 ${I}:${d.id}]`),ge=d.screenshotPaths&&Object.keys(d.screenshotPaths).length>0?`${Object.keys(d.screenshotPaths).length} pages [${Object.keys(d.screenshotPaths).join(", ")}]`:d.screenshotPath;console.log(`${q} Reviewing ${ge} (provider: ${R})${d.threadId?` (thread: ${d.threadId})`:""}${U?` (resuming: ${U.slice(0,8)})`:""}`);let V=new yo(d.id),me=new So(d.id,d.imprintContext),re=(ee,we)=>{if(ee.type==="delta"&&"text"in ee){let Ne=me.push(ee.text),Ue=V.push(Ne.visibleText);Ue.visibleText&&(P.accumulateText(we,"response",Ue.visibleText),P.broadcast({...ee,text:Ue.visibleText},we,d.sourceId));for(let Ce of Ue.orientations)P.broadcast({type:"orientation",jobId:we,orientation:Ce},we,d.sourceId);for(let Ce of Ne.usages)P.broadcast({type:"imprint_used",jobId:we,usage:Ce},we,d.sourceId);return}else ee.type==="thinking"&&"text"in ee&&P.accumulateText(we,"thinking",ee.text);P.broadcast(ee,we,d.sourceId)},{process:Z,result:ye}=R==="codex"?oo(d.id,{prompt:F,projectRoot:r,screenshotPath:d.screenshotPath,resumeSessionId:U,model:d.model,sandboxMode:N?"read-only":void 0,configOverrides:Yn(d.agentSettings),onEvent:re}):R==="copilot"?Di(d.id,{prompt:F,projectRoot:r,resumeSessionId:U,model:d.model,timeoutMs:h,copilotPath:p.copilot?.path??k,onEvent:re}):Zn(d.id,{prompt:F,projectRoot:r,maxTurns:l,maxBudgetUsd:b,allowedTools:N?["Read"]:S,claudePath:y,resumeSessionId:U,model:d.model,reasoningEffort:d.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:re});P.setActiveProcess(d.id,Z);let ne=await ye,be=[...(ne.fileEdits??[]).map(ee=>ee.file_path),...(ne.editEvents??[]).flatMap(ee=>ee.filePath?[ee.filePath]:[])],Re=me.finalize(ne.text),pe=Pr(Re.visibleText,d.id),Y=V.finalize(Re.visibleText),Pe=pe.visibleText,He=us(Pe),Ie=J?Jt(Pe,{context:d.imprintContext,requestText:w??Ot(d.feedback),applicationOccurred:be.length>0||He.some(ee=>ee.status==="resolved")}):{visibleText:Pe,draft:void 0,error:void 0},We=Ie.visibleText,je=J?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 ee of Y.orientations)P.broadcast({type:"orientation",jobId:d.id,orientation:ee},d.id,d.sourceId);for(let ee of Re.usages)P.broadcast({type:"imprint_used",jobId:d.id,usage:ee},d.id,d.sourceId);if(d.result=We,ne.success){console.log(`${q} Iteration complete`),ne.fileEdits&&ne.fileEdits.length>0&&console.log(`${q} Captured ${ne.fileEdits.length} file edit(s): ${ne.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),ne.editEvents&&ne.editEvents.length>0&&console.log(`${q} Captured ${ne.editEvents.length} edit event(s): ${ne.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),d.status="done";let ee=ls(Pe),we=He;if(we.length>0&&d.annotationIds&&d.annotationIds.length>0){let de=new Set(d.annotationIds);we.every(Ze=>de.has(Ze.annotationId))||(we=we.map((Ze,St)=>({...Ze,annotationId:d.annotationIds[St%d.annotationIds.length]})))}let Ne=ne.fileEdits&&ne.fileEdits.length>0?ne.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):ne.toolsUsed,Ue=P.getBufferedEvents(d.id),Ce=gp(Ue?.events??[],r,pe.segments),Ae,ie=os(Pe),z=ns(Pe);if(z)if(!(d.memoryReview?.packets.some(ce=>ce.proposalId===z.proposalId)||d.surfacedProposalIds?.includes(z.proposalId)))Ae={status:"rejected",action:z.action,proposalId:z.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Ae=await B.commitConversationalReview(z)}catch(ce){Ae={status:"rejected",action:z.action,proposalId:z.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=ms(Pe,be.length),ue,Ge,Nr,Br,ca=d.imprintContext?.pendingGroundingExplanationIds??[];if(Ie.draft){let de=Ie.draft.decision==="recognize"?[Ie.draft.explanationId]:[],ce=Ie.draft.decision==="recognize"?de:[...Ie.draft.usedExplanationIds??[],...Ie.draft.appliedExplanationIds??[]],Ze=Ie.draft.decision==="recognize"?[]:Ie.draft.appliedExplanationIds??[];ce.length>0&&(Nr=[...new Set(ce)]),Ze.length>0&&(Br=[...new Set(Ze)])}Ie.draft?.decision==="none"&&Q.recordNoop(Ie.draft.reason);let Nn=Ie.draft?.decision==="recognize"?Ie.draft:void 0;if(Nn&&!z&&!ie){let de=d.imprintContext?.explanations.find(ce=>ce.id===Nn.explanationId&&ce.state==="grounded");de?Ge={explanationId:de.id,title:Nn.summary.title,detail:Nn.summary.detail,statement:de.statement}:je={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Bo=Ie.draft?.decision==="mutate"||Ie.draft?.decision==="apply"?Ie.draft:void 0;if(d.threadId&&Bo&&!z&&!ie)try{ue=await Q.capture(Bo,{threadId:d.threadId,jobId:d.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:ca,applicationOccurred:be.length>0||we.some(de=>de.status==="resolved")}),ue?(je={state:"mutated"},await B.recordImprintEvidence({summary:ue,threadId:d.threadId,jobId:d.id}).catch(de=>console.warn(`${q} Canonical Imprint evidence linkage failed:`,de))):je={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(de){je={state:"invalid",reason:de instanceof Error?de.message:String(de)},console.warn(`${q} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else Bo&&(je={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});Ie.error&&console.warn(`${q} Ignored invalid imprint block: ${Ie.error}`),(je.state==="missing"||je.state==="invalid")&&Q.recordAssessmentFailure(je.state);let Jo=ue?.transactionId;if(d.threadId&&ue&&!ue.grounding){let de=await x.getThread(d.threadId),ce=new Set(ue.changes.map(St=>St.explanationId)),Ze=de?hp(de.messages,ce):void 0;if(Ze?.imprintSummary){let St=Ze.imprintSummary;await x.updateAssistantMessage(d.threadId,Ze.jobId,{imprintSummary:{...St,detail:ue.detail,changes:ue.changes,additionalObservationCount:(St.additionalObservationCount??0)+1,coalescedTransactionIds:[...St.coalescedTransactionIds??[],ue.transactionId]}}),ue=void 0}}let Lo=cn({question:ee,resolutions:we,changedFiles:be,decisionRequired:!!ie,imprintTransactionId:Jo,groundingRequired:!!ue?.grounding}),la=Ce?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Ct=d.lifecycle?En(d.lifecycle,Jo?[Jo]:[],je):void 0;if(d.threadId){let de=N?ie?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":We;await x.appendMessageBeforeQueuedReplies(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:de,resolutions:!N&&we.length>0?we:void 0,question:N?void 0:ee??void 0,sessionId:ne.sessionId,toolsUsed:N?void 0:Ne,editEvents:!N&&ne.editEvents&&ne.editEvents.length>0?ne.editEvents:void 0,segments:!N&&Ce&&Ce.length>0?Ce:void 0,turn:{phase:"complete",orientation:la,result:Lo},result:Lo,memoryReviewCard:ie??void 0,memoryReceipt:Ae,imprintSummary:ue,imprintRecognition:Ge,imprintUsedExplanationIds:Nr,imprintAppliedExplanationIds:Br,modelDetails:ae.length>0?ae:void 0,model:d.model,provider:R,...Ct?{lifecycle:Ct}:{}})}if(d.threadId&&!z&&!d.surfacedProposalIds?.length&&d.kind!=="project_model"){let de=d.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await B.captureCompletedJob({jobId:d.id,threadId:d.threadId,createdAt:d.createdAt,completedAt:Date.now(),requestSummary:w??(Ot(d.feedback)||"[request unavailable]"),responseSummary:ee??We,outcome:ee?"question_asked":we.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:R,model:d.model,sessionId:ne.sessionId},subjectHints:de,filePaths:[...(ne.fileEdits??[]).map(ce=>ce.file_path),...(ne.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>Us(ce)?ip(r,ce):ce),resolutions:we.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:d.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Ct?.submissionIds,outcomeId:Ct?.outcomeId,imprintEvidenceIds:Ct?.imprintEvidenceIds,imprintAssessment:Ct?.imprintAssessment})}catch(ce){console.warn(`${q} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}Ae?.status==="committed"&&Ae.decisionId&&R!=="copilot"&&await Ye({provider:R,model:d.model,agentSettings:d.agentSettings,threadId:d.threadId,annotationIds:d.annotationIds,sourceId:d.sourceId,reason:`Project accepted decision ${Ae.decisionId}`}),ee&&(console.log(`${q} \u{1F4AC} Question detected: "${ee.slice(0,120)}" \u2192 broadcasting to ${oe.size} SSE clients (threadId=${d.threadId??d.id}, annotationIds=${d.annotationIds?.join(",")??"none"})`),P.broadcast({type:"question",jobId:d.id,threadId:d.threadId??d.id,question:ee,annotationIds:d.annotationIds},d.id,d.sourceId)),ae.length>0&&(console.log(`${q} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),P.broadcast({type:"novel_patterns",jobId:d.id,patterns:ae,threadId:d.threadId},d.id,d.sourceId)),P.broadcast({type:"done",jobId:d.id,success:!0,resolutions:we.length>0?we:void 0,responseText:We,threadId:d.threadId,annotationIds:d.annotationIds,result:Lo},d.id,d.sourceId),Me.push({id:d.id,status:"done",completedAt:Date.now(),threadId:d.threadId,annotationIds:d.annotationIds})}else console.error(`${q} Error: ${ne.error}`),d.status="error",d.error=ne.error,d.threadId&&await x.appendMessageBeforeQueuedReplies(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,error:ne.error||"Unknown error",model:d.model,provider:R,...d.lifecycle?{lifecycle:En(d.lifecycle)}:{}}),P.broadcast({type:"error",jobId:d.id,threadId:d.threadId,message:ne.error||"Unknown error",provider:R,model:d.model,recoverable:ne.recoverableError,code:ne.errorCode},d.id,d.sourceId),Me.push({id:d.id,status:"error",completedAt:Date.now(),error:ne.error,threadId:d.threadId,annotationIds:d.annotationIds});ot()});let xe=np(async(d,v)=>{if(wp(d,v),d.method==="OPTIONS"){v.writeHead(204),v.end();return}let A=d.url||"/",w=A.split("?")[0],M=new URL(A,`http://127.0.0.1:${I}`),R=M.pathname,N=Sp(d,M);if(N&&N!==i){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:_o(r)});return}if(R.startsWith("/ambient/")&&N!==i){C(v,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:N});return}if(d.headers.origin){if(!zs(d.headers.origin)){C(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(N!==i){C(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:_o(r)});return}}try{if(R.startsWith("/ambient/"))await pt(d,v,R);else if(d.method==="POST"&&R==="/draft-attachments"){let J=M.searchParams.get("annotationId")?.trim()??"",U=M.searchParams.get("name")?.trim()??"",F=M.searchParams.get("kind"),q=String(d.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!J||J.length>128||!/^[a-z0-9_-]+$/i.test(J)){C(v,400,{error:"A valid annotationId is required."});return}if(F!=="svg"&&F!=="text"||F==="svg"&&q!=="image/svg+xml"||F==="text"&&q!=="text/plain"){C(v,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await xp(d,fp);if(ge.length===0){C(v,400,{error:"Attachment is empty."});return}let V=await L.stage({annotationId:J,name:U,mimeType:q,kind:F,data:ge});C(v,201,{attachment:{id:V.id,name:V.name,mimeType:V.mimeType,size:V.size,kind:V.kind}})}else if(d.method==="POST"&&R==="/draft-attachments/claim"){let J=await $e(d),U=Array.isArray(J.ids)?J.ids.filter(F=>typeof F=="string").slice(0,100):[];await L.claim(U),C(v,200,{ok:!0})}else if(d.method==="DELETE"&&R.startsWith("/draft-attachments/"))await L.release([R.slice(19)]),C(v,200,{ok:!0});else if(d.method==="POST"&&R==="/send")await ut(d,v);else if(d.method==="POST"&&R==="/capture/native"){if(!u){C(v,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let J=await $e(d),U=typeof J.pageUrl=="string"?J.pageUrl:"",F=J.clip&&typeof J.clip=="object"&&!Array.isArray(J.clip)?J.clip:null;if(!U||!F){C(v,400,{error:"pageUrl and clip are required."});return}let q=await ts(u,{pageUrl:U,clip:{x:Number(F.x),y:Number(F.y),width:Number(F.width),height:Number(F.height)},scale:typeof J.scale=="number"?J.scale:1});v.writeHead(200,{"Content-Type":"image/webp","Content-Length":q.length,"Cache-Control":"no-store"}),v.end(q)}else if(d.method==="GET"&&R==="/events")bt(d,v);else if(d.method==="GET"&&R==="/status")await Oo(d,v,N);else if(d.method==="GET"&&R==="/ui-preferences")await an(v);else if(d.method==="PATCH"&&R==="/ui-preferences")await qe(d,v);else if(d.method==="PATCH"&&R==="/config")await Do(d,v);else if(d.method==="POST"&&R==="/leases"){if(g!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await $e(d),U=typeof J.leaseId=="string"?J.leaseId.trim():"",F=typeof J.ownerPid=="number"&&Number.isInteger(J.ownerPid)&&J.ownerPid>0?J.ownerPid:void 0;if(!U||U.length>128){C(v,400,{error:"A valid leaseId is required."});return}G();let q=W.acquire(U,F);C(v,201,{ok:!0,lease:q,ttlMs:Bs})}catch{C(v,400,{error:"Invalid lease request."})}}else if(R.startsWith("/leases/")&&(d.method==="PATCH"||d.method==="DELETE")){if(g!=="detached"){C(v,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(R.slice(8))}catch{C(v,400,{error:"Invalid lease id."});return}if(!J){C(v,400,{error:"A lease id is required."});return}if(d.method==="PATCH"){let U=W.heartbeat(J);if(!U){C(v,404,{error:"Lease not found."});return}C(v,200,{ok:!0,lease:U})}else{let U=W.release(J);C(v,U.found?200:404,{ok:U.found}),U.becameEmpty&&X()}}else if(d.method==="POST"&&R==="/shutdown"){if(g!=="detached"){C(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}C(v,200,{ok:!0}),setTimeout(fe,100)}else if(d.method==="POST"&&R==="/restart"){if(g!=="detached"){C(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}C(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of oe)try{J.res.end()}catch{}xe.close(()=>{Ds(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(d.method==="GET"&&R==="/capabilities")C(v,200,{providers:p});else if(R.startsWith("/imprint/"))await rt(d,v,R);else if(R.startsWith("/memory/"))await De(d,v,R);else if(d.method==="POST"&&R==="/mcp/install")await Xs(d,v);else if(d.method==="POST"&&R==="/reply")await mt(d,v);else if(d.method==="POST"&&R==="/cancel")Fe(d,v);else if(d.method==="POST"&&R==="/materialize")C(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(d.method==="GET"&&R==="/materialization-runs")C(v,410,{error:"Use /projection-runs."});else if(d.method==="GET"&&R==="/projection-runs"){let J=await se.loadRuns();C(v,200,J)}else if(d.method==="GET"&&R==="/projection/proposals"){let J=await se.loadModelProposals();C(v,200,J)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply-selected")){let J=R.slice(22,-15);await xt(J,d,v)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply")){let J=R.slice(22,-6);await _t(J,v)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/dismiss")){let J=R.slice(22,-8);await No(J,d,v)}else if(R.startsWith("/model/proposals/"))C(v,410,{error:"Use /projection/proposals."});else if(d.method==="POST"&&R==="/model/component")await Ys(d,v);else if(d.method==="DELETE"&&R==="/model/component")await Zs(d,v);else if(d.method==="PATCH"&&R==="/model/token")await ea(d,v);else if(d.method==="DELETE"&&R==="/model/token")await ta(d,v);else if(d.method==="POST"&&R==="/model/consolidate")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(d.method==="POST"&&R==="/model/synthesize")C(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(d.method==="GET"&&R==="/model"){let J=await se.loadModel();C(v,200,{model:J})}else if(d.method==="GET"&&R.startsWith("/jobs/")&&R.endsWith("/events")){let J=R.slice(6,R.length-7),U=parseInt(M.searchParams.get("afterSeq")??"-1",10),F=P.getBufferedEvents(J,isNaN(U)?-1:U);F?C(v,200,F):C(v,404,{error:"Unknown job"})}else if(d.method==="GET"&&w.startsWith("/files/"))await ia(w.slice(7),v);else if(d.method==="GET"&&R==="/threads/recent"){let J=Math.min(Math.max(parseInt(M.searchParams.get("limit")??"5",10)||5,1),20),U=await x.listRecent(J);C(v,200,U)}else if(d.method==="GET"&&R.startsWith("/decision/")){let J=R.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))C(v,400,{error:"Invalid decision id"});else{let U=await x.getThread(J),F=[...U?.messages??[]].reverse().find(q=>q.annotationSnapshot);if(U&&F?.annotationSnapshot){let q=[...U.messages].reverse().find(ge=>ge.resolutions?.length);C(v,200,{decision:{id:U.id,createdAt:F.timestamp,url:F.annotationSnapshot.url,viewport:F.annotationSnapshot.viewport,color:F.annotationSnapshot.color,annotations:F.annotationSnapshot.annotations,resolutions:q?.resolutions??[]},authority:"thread_snapshot"})}else{let q=await _e.loadDecision(J);q?C(v,200,{decision:q,authority:"legacy_archive"}):C(v,404,{error:"Decision not found"})}}}else if(d.method==="GET"&&R.startsWith("/thread/")){let J=R.slice(8);await sa(J,v)}else if(d.method==="DELETE"&&R.startsWith("/thread/")){let J=R.slice(8);await aa(J,v)}else d.method==="GET"&&(R==="/canvas"||R==="/canvas/")?na(d,v):d.method==="GET"&&R==="/canvas/manifest"?await oa(v):d.method==="GET"&&R==="/canvas/app.mjs"?await ra(v):C(v,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),C(v,500,{error:J instanceof Error?J.message:"Internal error"})}});async function pt(d,v,A){if(d.method!=="POST"){C(v,405,{error:"Ambient endpoints accept POST requests only."});return}let w=await $e(d,bp),M=typeof w.sessionId=="string"?w.sessionId.trim():"",R=typeof w.turnId=="string"?w.turnId.trim():"",N=typeof w.executionOwner=="string"?w.executionOwner:void 0,J=hi(w.knowledgeView);if(A==="/ambient/context"){let U=typeof w.query=="string"?w.query.trim():"";if(!U){C(v,400,{error:"query is required."});return}let F=Array.isArray(w.subjectHints)?w.subjectHints.filter(q=>typeof q=="string"&&!!q.trim()).slice(0,20):void 0;C(v,200,await Oe.expandContext({query:U,subjectHints:F,knowledgeView:J}));return}if(A==="/ambient/turns/assess"){let U=typeof w.threadId=="string"?w.threadId.trim():"",F=typeof w.jobId=="string"?w.jobId.trim():"",q=typeof w.assessmentText=="string"?w.assessmentText.trim():"";if(!U||!F||!q){C(v,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(w.semanticCandidates)?w.semanticCandidates.flatMap(me=>{if(!me||typeof me!="object"||Array.isArray(me))return[];let re=me,Z=typeof re.claim=="string"?re.claim.trim():"",ye=typeof re.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(re.proposedKind)?re.proposedKind:void 0;return Z?[{claim:Z,rationale:typeof re.rationale=="string"?re.rationale.trim():void 0,proposedKind:ye,sourceText:typeof re.sourceText=="string"?re.sourceText.trim():void 0}]:[]}).slice(0,8):[],V=await Oe.assess({threadId:U,jobId:F,assessmentText:q,semanticCandidates:ge});C(v,V.status==="recorded"?200:404,V);return}if(!M||!R||M.length>256||R.length>256){C(v,400,{error:"Valid sessionId and turnId values are required."});return}if(A==="/ambient/turns/prepare"){let U=typeof w.prompt=="string"?w.prompt.trim():"";if(!U){C(v,400,{error:"prompt is required."});return}C(v,200,await Oe.prepare({sessionId:M,turnId:R,prompt:U,model:typeof w.model=="string"?w.model:void 0,executionOwner:N,knowledgeView:J}));return}if(A==="/ambient/turns/event"){let U=typeof w.toolName=="string"?w.toolName.trim():"";if(!U){C(v,400,{error:"toolName is required."});return}C(v,200,await Oe.recordEvent({sessionId:M,turnId:R,executionOwner:N,toolName:U,toolUseId:typeof w.toolUseId=="string"?w.toolUseId:void 0,toolInput:w.toolInput,toolResponse:w.toolResponse}));return}if(A==="/ambient/turns/complete"){C(v,200,await Oe.complete({sessionId:M,turnId:R,executionOwner:N,lastAssistantMessage:typeof w.lastAssistantMessage=="string"?w.lastAssistantMessage:void 0,model:typeof w.model=="string"?w.model:void 0}));return}C(v,404,{error:"Ambient endpoint not found."})}async function De(d,v,A){try{if(d.method==="GET"&&A==="/memory/status"){C(v,200,await B.status());return}if(d.method==="GET"&&A==="/memory/diagnostics"){C(v,200,await B.diagnostics());return}if(d.method==="GET"&&A==="/memory/model-view"){C(v,200,await B.getModelView());return}if(d.method==="GET"&&A==="/memory/imprint-view"){let w=await x.load(),M=[...new Set(Object.values(w.threads).flatMap(R=>$n(R.messages)))];C(v,200,await B.getImprintView(M,new Set(Object.keys(w.threads))));return}if(d.method==="POST"&&A==="/memory/constraints"){let w=await $e(d),M=typeof w.reactComponent=="string"?w.reactComponent.trim():"",R=await B.getModelView(),N=M?R.entries.filter(J=>J.key===`components.${M}`||J.key.startsWith(`components.${M}.`)):[];C(v,200,{modelEntries:N});return}if(d.method==="POST"&&A==="/memory/conversation-action"){let w=await $e(d),M=typeof w.threadId=="string"?w.threadId:"",R=typeof w.proposalId=="string"?w.proposalId:"",N=String(w.action);if(!M||!R||!["accept","edit_and_accept","reject","defer"].includes(N)){C(v,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await x.getThread(M),U=J?.messages.find(pe=>pe.memoryReviewCard?.proposalId===R)?.memoryReviewCard,F=J?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===R),q=J?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await B.findPendingProposalsForThread(M)).find(pe=>pe.proposalId===R):void 0,ge=typeof w.kind=="string"&&["principle","preference","rule","constraint"].includes(w.kind)?w.kind:void 0,V=U?.kind??F?.proposedKind??q?.proposedKind??ge;if(!J||!U&&!F&&!q){C(v,409,{error:"This decision candidate was not surfaced in the thread."});return}if((N==="accept"||N==="edit_and_accept")&&!V){C(v,400,{error:"The decision kind is required to accept this candidate."});return}let me=await se.findModelProposalsByThread(M),re=(await Promise.all(me.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Y=>B.findPendingProposalForLegacyDecision(Y)))).some(Y=>Y?.proposalId===R)})))).find(pe=>pe.matches)?.proposal,Z={proposalId:R,action:N,kind:V,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(Z.action==="edit_and_accept"&&!Z.claim){C(v,400,{error:"Edited decision wording is required."});return}let ye=await B.commitConversationalReview(Z),ne=`memory-${lt().slice(0,8)}`,be=N==="accept"?"> Accepted decision":N==="edit_and_accept"?"> Edited and accepted decision":N==="reject"?"> Rejected decision":"> Deferred decision";await x.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:ne,replyToQuestion:be}),await x.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:ne,responseText:"",memoryReceipt:ye,provider:rn(typeof w.provider=="string"?w.provider:void 0),model:typeof w.model=="string"?w.model:void 0}),ye.status==="committed"&&re&&await se.dismissModelProposal(re.id);let Re=rn(typeof w.provider=="string"?w.provider:void 0);ye.status==="committed"&&ye.decisionId&&Re!=="copilot"&&await Ye({provider:Re,model:typeof w.model=="string"?w.model:void 0,agentSettings:Qt(w),threadId:M,reason:`Project accepted decision ${ye.decisionId}`}),C(v,ye.status==="committed"?200:409,{receipt:ye});return}if(d.method==="POST"&&A==="/memory/analyze"){let w=await $e(d),M=await B.analyzeLegacy({projectKey:typeof w.projectKey=="string"?w.projectKey:void 0}),R=Object.fromEntries([...new Set(M.issues.map(N=>N.code))].map(N=>[N,M.issues.filter(J=>J.code===N).length]));C(v,200,{...M,issues:void 0,issueCounts:R});return}if(d.method==="POST"&&A==="/memory/review"){let w=await $e(d),M=await B.review(tr(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,200,M);return}if(d.method==="POST"&&A==="/memory/context"){let w=await $e(d),M=await B.contextualize(tr(w.query),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,200,M);return}if(d.method==="POST"&&A==="/memory/initialize"){let w=await $e(d),M=await B.initializeFromLegacy({confirmed:w.confirm===!0,projectKey:typeof w.projectKey=="string"?w.projectKey:void 0,writerVersion:ct});C(v,201,{status:M.status,report:{source:M.report.source,imported:M.report.imported,unresolvedAcceptance:M.report.unresolvedAcceptance,deferredModelEntries:M.report.deferredModelEntries,proofCases:M.report.proofCases,schemaIssues:M.report.schemaIssues}});return}if(d.method==="POST"&&A==="/memory/plan"){let w=await $e(d),M=await B.planReview(er(w.command),{projectKey:typeof w.projectKey=="string"?w.projectKey:void 0});C(v,M.result.ok?200:422,M);return}if(d.method==="POST"&&A==="/memory/commit"){let w=await $e(d),M=w.transaction&&typeof w.transaction=="object"&&!Array.isArray(w.transaction)?w.transaction:{},R=await B.commitReview(er(w.command),{transactionId:typeof M.transactionId=="string"?M.transactionId:"",committedAt:typeof M.committedAt=="string"?M.committedAt:""});C(v,200,{status:await B.status(),journal:R.report});return}if(d.method==="POST"&&A==="/memory/recover"){let w=await $e(d),M=await B.recover(w.confirm===!0);C(v,200,{status:await B.status(),journal:M.report});return}C(v,404,{error:"Memory endpoint not found."})}catch(w){let M=w instanceof Error?w.message:String(w),R=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(M),N=/required|invalid|unsupported|expected|must be|confirmation/i.test(M);if(R||N){C(v,R?409:400,{error:M});return}throw w}}async function rt(d,v,A){if(d.method==="GET"&&A==="/imprint/status"){let[w,M]=await Promise.all([Q.store.load(),x.load()]),R=[...new Set(Object.values(M.threads).flatMap(N=>$n(N.messages)))].filter(N=>w.graph.explanations.some(J=>J.id===N&&J.state==="testing"));C(v,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:Q.diagnostics(),admissionWindowStartedAt:e});return}if(d.method==="POST"&&A==="/imprint/action"){let w=await $e(d),M=typeof w.threadId=="string"?w.threadId:"",R=typeof w.transactionId=="string"?w.transactionId:"",N=String(w.action);if(!M||!R||!["yes","this_time","no"].includes(N)){C(v,400,{error:"A valid thread, imprint update, and action are required."});return}let U=await x.getThread(M),F=[...U?.messages??[]].reverse().find(Z=>Z.role==="assistant"&&Z.imprintSummary?.transactionId===R),q=F?.imprintSummary;if(!U||!F||!q){C(v,409,{error:"This imprint summary is not available in the thread."});return}if(q.resolvedAction){C(v,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${lt().slice(0,8)}`;await Q.applyGroundingAction({summary:q,action:N,threadId:M,jobId:ge}),N!=="no"&&await B.recordImprintEvidence({summary:q,action:N,threadId:M,jobId:ge}).catch(Z=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",Z));let V=$t(F.result,!!F.question),me=F.turn?{...F.turn,result:$t(F.turn.result,!!F.question)}:void 0;await x.updateAssistantMessage(M,F.jobId,{imprintSummary:{...q,resolvedAction:N},...V?{result:V}:{},...me?{turn:me}:{}});let re={yes:"> Yes",this_time:"> This time",no:"> No"};if(await x.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:ge,replyToQuestion:re[N]}),N==="no"){let Z="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",ye=cn({question:Z});await x.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:ge,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:Z,turn:{phase:"complete",orientation:[],result:ye},result:ye})}C(v,200,{ok:!0,action:N});return}C(v,404,{error:"Imprint endpoint not found."})}async function ut(d,v){let{screenshot:A,feedback:w,color:M,provider:R,model:N,reasoningEffort:J,serviceTier:U,sourceId:F,pastedImages:q,pageScreenshots:ge}=await Sr(d),V;try{V=JSON.parse(w)}catch{C(v,400,{error:"Invalid feedback JSON"});return}let me=V.annotations.flatMap(ie=>(ie.attachments??[]).map(z=>({id:z.id,annotationId:ie.id}))),re;try{re=me.length>0?await L.promote(me):void 0}catch(ie){C(v,409,{error:ie instanceof Error?ie.message:"Draft attachment unavailable."});return}let Z=lt().slice(0,8),ye={};if(ge.length>0)for(let ie of ge){let z=encodeURIComponent(ie.pathname),ae=Le(c,`screenshot-${Z}-${z}.webp`);await Eo(ae,ie.data),ye[ie.pathname]=ae}let ne=Le(c,`screenshot-${Z}.webp`);await Eo(ne,A);let be={};if(q.length>0)for(let ie of q){let z=Le(c,`pasted-${Z}-${ie.annotationId}-${ie.index}.webp`);await Eo(z,ie.data),be[ie.annotationId]||(be[ie.annotationId]=[]),be[ie.annotationId].push(z)}let Re=Ps(V),pe;if(Re.length>0){let ie=await x.findContinuationThread(Re);ie?(pe=ie.id,await x.addElementIdentifiers(pe,Re)):pe=(await x.createThread(`thread-${lt()}`,Re)).id}else pe=(await x.createThread(`thread-${lt()}`,[])).id;let Y=V.annotations.map(ie=>ie.id),Pe=Object.keys(ye).length>0,He=await Bn(B,V,Re,ie=>console.warn(`[\u22B9 ${I}:${Z}] Contextual memory unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))),Ie=(await x.getThread(pe))?.messages??[],We=await Q.contextualize({text:Ot(V),subjectHints:_s(V,Re),pendingGroundingExplanationIds:$n(Ie),correctionExplanationIds:Ls(Ie)}).catch(ie=>{console.warn(`[\u22B9 ${I}:${Z}] Imprint context unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))}),je=jr({jobId:Z,threadId:pe,artifactIds:Rs(V,Z)}),ee={id:Z,status:"queued",screenshotPath:ne,feedback:V,createdAt:Date.now(),color:M,threadId:pe,annotationIds:Y,provider:rn(R),model:N||void 0,agentSettings:Qt({reasoningEffort:J,serviceTier:U}),...Object.keys(be).length>0?{imagePaths:be}:{},...re&&Object.keys(re).length>0?{attachmentFiles:re}:{},sourceId:F||void 0,...Pe?{screenshotPaths:ye}:{},...He?{memoryReview:He}:{},...We?{imprintContext:We}:{},lifecycle:je},we=new Set(V.annotations.map(ie=>ie.pathname).filter(Boolean)),Ne;if(we.size>1){let ie=new Map;for(let z of V.annotations){let ae=z.pathname||"(unknown)";ie.has(ae)||ie.set(ae,[]),ie.get(ae).push(z.instruction||qs({...V,annotations:[z]}))}Ne=[...ie.entries()].map(([z,ae])=>`\`${z}\`
229
+ ${ae.map(ue=>`- ${ue}`).join(`
230
230
  `)}`).join(`
231
- `)}else Oe=Es(U);let Ue=xn(U,Object.keys(ve).length>0?ve:void 0,me),Ee=Ts(U);await H.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:te,screenshotPath:ie,...Se?{screenshotPaths:ge}:{},...Object.keys(ve).length>0?{imagePaths:ve}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},annotationIds:Z,annotationSnapshot:{url:U.url,viewport:U.viewport,annotations:U.annotations,color:A||void 0},feedbackSummary:Oe,...Ee?{requestText:Ee}:{},feedbackContext:Ue||void 0,...We?{memoryReview:We}:{},...He?{imprintContext:He}:{},lifecycle:Ae});let je=T.enqueue(ne);_(I,200,{jobId:te,position:je,threadId:pe})}async function ut(a,I){let j=a.headers["content-type"]||"",y,A,P,O,$,q,N,J,he=[];if(j.includes("multipart/form-data")){let F=await vi(a),ae=F.feedback?JSON.parse(F.feedback):{};y=ae.threadId,A=ae.reply,P=ae.color,O=ae.provider,$=ae.model,q=qt(ae),N=ae.sourceId||F.sourceId,J=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let fe of F.pastedImages)he.push(fe.data)}else{let F=[];for await(let Ge of a)F.push(typeof Ge=="string"?Buffer.from(Ge):Ge);let ae=Buffer.concat(F).toString("utf-8"),fe;try{fe=JSON.parse(ae)}catch{_(I,400,{error:"Invalid JSON"});return}y=fe.threadId,A=fe.reply,P=fe.color,O=fe.provider,$=fe.model,q=qt(fe),N=fe.sourceId,J=fe.memoryReviewProposalId}if(!y||!A){_(I,400,{error:"Missing threadId or reply"});return}let U=await H.getThread(y);if(!U){_(I,404,{error:"Thread not found"});return}let se;if(J){let F=await ue.findModelProposalsByThread(y);if(se=(await Promise.all(F.flatMap(fe=>fe.authorityStatus==="accepted"?[]:fe.decisionIds.map(async Ge=>({modelProposalId:fe.id,underlying:await W.findPendingProposalForLegacyDecision(Ge)}))))).filter(fe=>!!fe.underlying).find(fe=>fe.underlying.proposalId===J),!se){_(I,409,{error:"The requested memory decision is not pending in this thread."});return}}let me="";{let F=await H.getThreadHistory(y);for(let ae=F.length-1;ae>=0;ae--)if(F[ae].screenshotPath){me=F[ae].screenshotPath;break}}let te=await Ls(y);if(!me&&!te){_(I,400,{error:"No screenshot available"});return}let ge=T.hasActiveThread(y),ie=ge?T.getQueuedThreadJob(y,F=>F._replyText!==void 0||F._replyPrompt!==void 0):null,ve=ie?.id??ct().slice(0,8),Te=Pi({jobId:ve,threadId:y}),pe=[],Z=`${ve}-${Date.now()}`;for(let F=0;F<he.length;F++){let ae=Be(c,`reply-${Z}-${F}.webp`);await Ao(ae,he[F]),pe.push(ae)}await H.appendMessage(y,{role:"human",timestamp:Date.now(),jobId:ve,replyToQuestion:A,screenshotPath:me,...ge?{queued:!0}:{},...pe.length>0?{replyImagePaths:pe}:{},lifecycle:{...Te,artifactIds:pe.map((F,ae)=>`reply-image:${ve}:${ae}`)}});let Se=await H.getThreadHistory(y),We=[...Se].reverse().find(F=>F.memoryReview)?.memoryReview,ye=await ee.contextualize({text:A,subjectHints:Ss(Se,U.elementIdentifiers),pendingGroundingExplanationIds:Mn(Se),correctionExplanationIds:Ms(Se)}).catch(F=>{console.warn(`[\u22B9 ${v}:${ve}] Imprint context unavailable for reply; continuing without it:`,F instanceof Error?F.message:String(F))});ye&&await H.updateMessage(y,ve,{imprintContext:ye});let He=new Set(Se.flatMap(F=>F.memoryReceipt?.status==="committed"?[F.memoryReceipt.proposalId]:[])),Ae=[...Se].reverse().find(F=>F.memoryReviewCard&&!He.has(F.memoryReviewCard.proposalId))?.memoryReviewCard,ne=[];for(let F of Se)if(F.annotationIds)for(let ae of F.annotationIds)ne.includes(ae)||ne.push(ae);let Ie=nn(O),Oe=se,Ue=Oe?[Oe.underlying.proposalId]:Ae?[Ae.proposalId]:[],Ee=ts(me,Se,Ie,pe.length>0?pe:void 0);if(Oe?Ee+=["","## Decision review card",`Privately review proposal ${Oe.underlying.proposalId}: ${Oe.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(`
232
- `):Ae&&(Ee+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Ae)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
233
- `)),ie){let F=ie,fe=[...F._replyTexts??(F._replyText?[F._replyText]:[]),A],Ge=[...F._replyImagePaths??[],...pe];F._replyTexts=fe,F._replyText=js(fe),F._replyImagePaths=Ge.length>0?Ge:void 0,F._replyPrompt=Ee,F.annotationIds=ne.length>0?ne:F.annotationIds,F.agentSettings=q??F.agentSettings,F.memoryReview=We??F.memoryReview,F.imprintContext=ye??F.imprintContext,F.surfacedProposalIds=[...new Set([...F.surfacedProposalIds??[],...Ue])],F.lifecycle={...F.lifecycle??Te,submissionIds:[...new Set([...F.lifecycle?.submissionIds??[],...Te.submissionIds])],artifactIds:[...new Set([...F.lifecycle?.artifactIds??[],...Te.artifactIds])]},_(I,200,{jobId:ve,position:1,threadId:y,bundled:!0});return}let je={id:ve,status:"queued",screenshotPath:me,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:y,annotationIds:ne.length>0?ne:void 0,provider:Ie,model:$||void 0,agentSettings:q,sourceId:N||void 0,...We?{memoryReview:We}:{},...ye?{imprintContext:ye}:{},...Ue.length?{surfacedProposalIds:Ue}:{},lifecycle:Te};te&&(je.kind=te),je._replyPrompt=Ee,je._replyTexts=[A],je._replyText=js([A]),pe.length>0&&(je._replyImagePaths=pe);let re=ge?T.enqueueNext(je):T.enqueue(je);_(I,200,{jobId:ve,position:re,threadId:y})}function vt(a,I){I.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),I.write(`event: connected
231
+ `)}else Ne=qs(V);let Ue=Rn(V,Object.keys(be).length>0?be:void 0,re),Ce=$s(V);await x.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:Z,screenshotPath:ne,...Pe?{screenshotPaths:ye}:{},...Object.keys(be).length>0?{imagePaths:be}:{},...re&&Object.keys(re).length>0?{attachmentFiles:re}:{},annotationIds:Y,annotationSnapshot:{url:V.url,viewport:V.viewport,annotations:V.annotations,color:M||void 0},feedbackSummary:Ne,...Ce?{requestText:Ce}:{},feedbackContext:Ue||void 0,...He?{memoryReview:He}:{},...We?{imprintContext:We}:{},lifecycle:je});let Ae=P.enqueue(ee);C(v,200,{jobId:Z,position:Ae,threadId:pe})}async function mt(d,v){let A=d.headers["content-type"]||"",w,M,R,N,J,U,F,q,ge=[];if(A.includes("multipart/form-data")){let z=await Sr(d),ae=z.feedback?JSON.parse(z.feedback):{};w=ae.threadId,M=ae.reply,R=ae.color,N=ae.provider,J=ae.model,U=Qt(ae),F=ae.sourceId||z.sourceId,q=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let ue of z.pastedImages)ge.push(ue.data)}else{let z=[];for await(let Ge of d)z.push(typeof Ge=="string"?Buffer.from(Ge):Ge);let ae=Buffer.concat(z).toString("utf-8"),ue;try{ue=JSON.parse(ae)}catch{C(v,400,{error:"Invalid JSON"});return}w=ue.threadId,M=ue.reply,R=ue.color,N=ue.provider,J=ue.model,U=Qt(ue),F=ue.sourceId,q=ue.memoryReviewProposalId}if(!w||!M){C(v,400,{error:"Missing threadId or reply"});return}let V=await x.getThread(w);if(!V){C(v,404,{error:"Thread not found"});return}let me;if(q){let z=await se.findModelProposalsByThread(w);if(me=(await Promise.all(z.flatMap(ue=>ue.authorityStatus==="accepted"?[]:ue.decisionIds.map(async Ge=>({modelProposalId:ue.id,underlying:await B.findPendingProposalForLegacyDecision(Ge)}))))).filter(ue=>!!ue.underlying).find(ue=>ue.underlying.proposalId===q),!me){C(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let re="";{let z=await x.getThreadHistory(w);for(let ae=z.length-1;ae>=0;ae--)if(z[ae].screenshotPath){re=z[ae].screenshotPath;break}}let Z=await Qs(w);if(!re&&!Z){C(v,400,{error:"No screenshot available"});return}let ye=P.hasActiveThread(w),ne=ye?P.getQueuedThreadJob(w,z=>z._replyText!==void 0||z._replyPrompt!==void 0):null,be=ne?.id??lt().slice(0,8),Re=jr({jobId:be,threadId:w}),pe=[],Y=`${be}-${Date.now()}`;for(let z=0;z<ge.length;z++){let ae=Le(c,`reply-${Y}-${z}.webp`);await Eo(ae,ge[z]),pe.push(ae)}await x.appendMessage(w,{role:"human",timestamp:Date.now(),jobId:be,replyToQuestion:M,screenshotPath:re,...ye?{queued:!0}:{},...pe.length>0?{replyImagePaths:pe}:{},lifecycle:{...Re,artifactIds:pe.map((z,ae)=>`reply-image:${be}:${ae}`)}});let Pe=await x.getThreadHistory(w),He=[...Pe].reverse().find(z=>z.memoryReview)?.memoryReview,Ie=await Q.contextualize({text:M,subjectHints:Cs(Pe,V.elementIdentifiers),pendingGroundingExplanationIds:$n(Pe),correctionExplanationIds:Ls(Pe)}).catch(z=>{console.warn(`[\u22B9 ${I}:${be}] Imprint context unavailable for reply; continuing without it:`,z instanceof Error?z.message:String(z))});Ie&&await x.updateMessage(w,be,{imprintContext:Ie});let We=new Set(Pe.flatMap(z=>z.memoryReceipt?.status==="committed"?[z.memoryReceipt.proposalId]:[])),je=[...Pe].reverse().find(z=>z.memoryReviewCard&&!We.has(z.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let z of Pe)if(z.annotationIds)for(let ae of z.annotationIds)ee.includes(ae)||ee.push(ae);let we=rn(N),Ne=me,Ue=Ne?[Ne.underlying.proposalId]:je?[je.proposalId]:[],Ce=ps(re,Pe,we,pe.length>0?pe:void 0);if(Ne?Ce+=["","## Decision review card",`Privately review proposal ${Ne.underlying.proposalId}: ${Ne.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(`
232
+ `):je&&(Ce+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(je)}`,"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(`
233
+ `)),ne){let z=ne,ue=[...z._replyTexts??(z._replyText?[z._replyText]:[]),M],Ge=[...z._replyImagePaths??[],...pe];z._replyTexts=ue,z._replyText=Js(ue),z._replyImagePaths=Ge.length>0?Ge:void 0,z._replyPrompt=Ce,z.annotationIds=ee.length>0?ee:z.annotationIds,z.agentSettings=U??z.agentSettings,z.memoryReview=He??z.memoryReview,z.imprintContext=Ie??z.imprintContext,z.surfacedProposalIds=[...new Set([...z.surfacedProposalIds??[],...Ue])],z.lifecycle={...z.lifecycle??Re,submissionIds:[...new Set([...z.lifecycle?.submissionIds??[],...Re.submissionIds])],artifactIds:[...new Set([...z.lifecycle?.artifactIds??[],...Re.artifactIds])]},C(v,200,{jobId:be,position:1,threadId:w,bundled:!0});return}let Ae={id:be,status:"queued",screenshotPath:re,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:ee.length>0?ee:void 0,provider:we,model:J||void 0,agentSettings:U,sourceId:F||void 0,...He?{memoryReview:He}:{},...Ie?{imprintContext:Ie}:{},...Ue.length?{surfacedProposalIds:Ue}:{},lifecycle:Re};Z&&(Ae.kind=Z),Ae._replyPrompt=Ce,Ae._replyTexts=[M],Ae._replyText=Js([M]),pe.length>0&&(Ae._replyImagePaths=pe);let ie=ye?P.enqueueNext(Ae):P.enqueue(Ae);C(v,200,{jobId:be,position:ie,threadId:w})}function bt(d,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
234
234
  data: {"status":"connected"}
235
235
 
236
- `);let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("sourceId")||void 0,A={id:ct().slice(0,8),res:I,sourceId:y};K.add(A),a.on("close",()=>{K.delete(A)})}async function _o(a,I,j){d??=ps(a.headers),nt();let y=[...T.allActive,...C.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,P,O,$,q]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),W.status(),ee.store.load(),H.load()]),N=[],J=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&N.push({subsystem:"projection",message:J(A)}),P.status==="rejected"&&N.push({subsystem:"projection",message:J(P)}),O.status==="rejected"?N.push({subsystem:"memory",message:J(O)}):O.value.state==="degraded"&&N.push({subsystem:"memory",message:O.value.error??"Product memory is degraded."}),$.status==="rejected"&&N.push({subsystem:"imprint",message:J($)}),q.status==="rejected"&&N.push({subsystem:"threads",message:J(q)});let he=A.status==="fulfilled"?A.value.runs:[],U=P.status==="fulfilled"?P.value.proposals:[],se=us(he,U),me=se.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})),te=O.status==="fulfilled"?O.value:{initialized:!1,state:"degraded",error:J(O)},ge=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>Mn(Z.messages)))]:[],ie=$.status==="fulfilled"?ge.filter(Z=>$.value.graph.explanations.some(Se=>Se.id===Z&&Se.state==="testing")):[],ve=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:ie.length,recoveredTransactions:$.value.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J($),pendingGroundingCount:ie.length,admission:ee.diagnostics(),admissionWindowStartedAt:e},Te=N.length>0?"degraded":te.state==="absent"||te.state==="initializing"?"initializing":"healthy",pe=new Date().toISOString();_(I,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Te,issues:N},version:dt,restartMode:g,projectId:r,storeId:s.storeId,projectName:jo(i),projectRoot:i,requestProjectId:j,projectIdVerified:j===r,devOrigin:d,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:y[0]?{id:y[0].id,status:y[0].status}:null,activeJobs:y.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:T.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:z.isActivated,count:z.size,nextExpiryAt:z.nextExpiryAt,shutdownPending:Y},projection:{state:A.status==="fulfilled"&&P.status==="fulfilled"?"ready":"degraded",activeJob:C.active?{id:C.active.id,status:C.active.status,threadId:C.active.threadId,annotationIds:C.active.annotationIds??[],provider:C.active.provider,model:C.active.model}:null,queueDepth:C.depth,recentRuns:se.recentRuns,recentAppliedRuns:se.recentAppliedRuns,actionableProposalCounts:se.actionableProposalCounts,actionableProposals:me},memory:te,imprint:ve,recentJobsRetentionMs:on,recentJobs:Re})}async function Co(a,I){let j=await new Promise(y=>{let A="";a.on("data",P=>{A+=P.toString()}),a.on("end",()=>y(A))});try{let y=JSON.parse(j);typeof y.devOrigin=="string"&&(d=y.devOrigin||null),_(I,200,{ok:!0,devOrigin:d})}catch{_(I,400,{error:"Invalid JSON"})}}async function rn(a){let I=await ke.load();_(a,200,{ok:!0,...I})}async function Le(a,I){let j=await _e(a);if(!bs(j.theme)){_(I,400,{error:"theme must be light, dark, or auto"});return}let y=await ke.setTheme(j.theme);_(I,200,{ok:!0,exists:!0,preferences:y})}async function qe(a,I){let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("jobId"),A=y?T.allActive.filter(J=>J.id===y):T.allActive,P=y?C.allActive.filter(J=>J.id===y):C.allActive,O=[...A.map(J=>J.threadId),...P.map(J=>J.threadId)].filter(Boolean),$=y?T.cancelJob(y):T.cancelActive(),q=y?C.cancelJob(y):C.cancelActive(),N=!!($||q);for(let J of O)await H.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:y||q?.id||"",cancelled:!0});_(I,200,{cancelled:N})}async function Xe(a){let I=ct().slice(0,8),j=a.threadId,y=!j;j||(j=(await H.createThread(`thread-${ct()}`,[])).id,yt.set(j,"project_model")),y&&await H.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:a.reason}),await H.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:I,responseText:y?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:I,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:j,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:y},P=C.enqueue(A);return{jobId:I,position:P,threadId:j}}async function Mt(a,I){let j=decodeURIComponent(a),y=await ue.findModelProposal(j);if(!y){_(I,404,{error:"Model proposal not found"});return}_(I,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:y})}async function wt(a,I,j){let y=decodeURIComponent(a),A=[];for await(let U of I)A.push(typeof U=="string"?Buffer.from(U):U);let P;try{P=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(j,400,{error:"Invalid JSON"});return}let O=(P.changes??[]).flatMap(U=>{if(!Array.isArray(U.path)||U.path.length===0)return[];let se=U.path.filter(te=>typeof te=="string"||typeof te=="number");if(se.length!==U.path.length)return[];let me=Array.isArray(U.decisionIds)?U.decisionIds.filter(te=>typeof te=="string"):void 0;return[{path:se,value:U.value,remove:U.remove===!0,decisionIds:me}]});if(O.length===0){_(j,400,{error:"No selected model changes"});return}let $=(P.changeSummaries??[]).flatMap(U=>{if(!U||typeof U!="object")return[];let se=Array.isArray(U.path)?U.path.filter(me=>typeof me=="string"||typeof me=="number"):void 0;return Array.isArray(U.path)&&se?.length!==U.path.length?[]:[{group:typeof U.group=="string"?U.group:void 0,label:typeof U.label=="string"?U.label:void 0,detail:typeof U.detail=="string"?U.detail:void 0,path:se,value:U.value,currentValue:U.currentValue}]}),q=await ue.findModelProposal(y);if(!q){_(j,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(j,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(j,409,{error:`Model proposal is already ${q.status}.`});return}let N=q.decisionIds.map(U=>{let se=q.changes?.filter(ge=>ge.decisionIds.includes(U)).length??0,me=O.filter(ge=>ge.decisionIds?.includes(U)).length,te=me===0?"unprojected":se>me?"partially_projected":"projected";return{decisionId:U,status:te}}),J=await W.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:O.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:N}),he=await ue.applySelectedModelProposal(y,O,$);if(!he){_(j,404,{error:"Model proposal not found"});return}if(he.threadId){let U=nn(P.provider),se=typeof P.model=="string"&&P.model?P.model:void 0;await H.appendMessage(he.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${he.id}`,responseText:"",provider:U,model:se})}_(j,200,{proposal:he,projection:J})}async function $o(a,I,j){let y=decodeURIComponent(a),{provider:A,model:P}=await _n(I),O=await ue.dismissModelProposal(y);if(!O){_(j,404,{error:"Model proposal not found"});return}O.threadId&&await H.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${O.id}`,responseText:"",provider:A,model:P}),_(j,200,{proposal:O})}async function _n(a){try{let I=[];for await(let y of a)I.push(typeof y=="string"?Buffer.from(y):y);if(I.length===0)return{};let j=JSON.parse(Buffer.concat(I).toString());return{provider:nn(typeof j.provider=="string"?j.provider:void 0),model:typeof j.model=="string"&&j.model?j.model:void 0,agentSettings:qt(j)}}catch{return{}}}async function Ls(a){let I=yt.get(a);if(I)return I;let A=(await H.getThread(a))?.messages.find(P=>P.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return yt.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return yt.set(a,"project_model"),"project_model"}async function qs(a,I){let j=[];for await(let q of a)j.push(typeof q=="string"?Buffer.from(q):q);let y;if(j.length>0)try{y=JSON.parse(Buffer.concat(j).toString("utf-8")).serverUrl}catch{}let A=[];u.claude?.available&&u.claude.mcp&&!u.claude.mcp.found&&A.push(await kr(y)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&A.push(await Rr(y)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&A.push(await Ar(y,u.copilot.path??k));let[P,O,$]=await Promise.all([ni(i),oi(i),ii(i,u.copilot?.path??k)]);u.claude&&(u.claude.mcp=P),u.codex&&(u.codex.mcp=O),u.copilot&&(u.copilot.mcp=$),_(I,200,{results:A,capabilities:{providers:u}})}async function Us(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let A=await W.recordDirectModelMutation({key:`components.${y.name}`,value:{description:""},claim:`${y.name} is an explicitly governed component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{added:!0,alreadyExists:!1,...A})}async function Fs(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let A=await W.recordDirectModelMutation({key:`components.${y.name}`,value:null,claim:`${y.name} is not governed as a component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...A})}async function zs(a,I){let j=[];for await(let O of a)j.push(typeof O=="string"?Buffer.from(O):O);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"||typeof y.value!="string"){_(I,400,{error:"Missing or invalid path/value"});return}let A=y.value;try{let O=JSON.parse(y.value);O&&typeof O=="object"&&(A=O)}catch{}let P=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:A,claim:`${y.path} uses ${y.value} in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{updated:!0,...P})}async function Ws(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"){_(I,400,{error:"Missing or invalid path"});return}let A=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:null,claim:`${y.path} is intentionally absent from the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...A})}function Hs(a,I){let j=d??"http://localhost:3000";if(!d){let A=a.headers.referer||a.headers.origin;if(A)try{let P=new URL(typeof A=="string"?A:A[0]||"");(P.hostname==="localhost"||P.hostname==="127.0.0.1")&&(j=P.origin)}catch{}}let y=Oi(v,j);I.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),I.end(y)}async function Gs(a){let I=Date.now();if(It&&I<It.expires){_(a,200,It.data);return}try{let{scanForComponents:j}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:y}=await import("./render-generator-HWFLZYC3.mjs"),A=await j(i);It={data:A,expires:I+5e3},y(A,i,En).then(P=>{En=P}).catch(P=>console.warn("[Bridge] Render generation failed:",P)),_(a,200,A)}catch(j){console.error("[Bridge] Scanner error:",j),_(a,500,{error:"Failed to scan components"})}}async function Vs(a){let I=[Be(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Be(i,"packages","popmelt","dist","canvas.mjs")];try{let j=Ul(import.meta.url);I.unshift(Be(Jl(j),"canvas.mjs"))}catch{}for(let j of I)try{let y=await Rs(j,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(y);return}catch{}console.error("[Bridge] Canvas bundle not found in:",I),_(a,404,{error:"Canvas bundle not found"})}async function Ks(a,I){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(I,400,{error:"Invalid filename"});return}try{let j=[Be(c,a),Be(i,".popmelt","artifacts","thread-media",a),Be(i,".popmelt","artifacts","eval-screenshots",a),Be(i,".popmelt","evals","screenshots",a),Be(i,".popmelt","screenshots",a)],y;for(let O of j)try{y=await Rs(O);break}catch{}if(!y)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),P=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";I.writeHead(200,{"Content-Type":P,"Cache-Control":"public, max-age=3600"}),I.end(y)}catch{_(I,404,{error:"File not found"})}}function sn(a){return`/files/${jo(a)}`}async function Qs(a,I){let j=await H.getThread(a);if(!j){_(I,404,{error:"Thread not found"});return}let y=j.messages.filter(N=>N.role==="assistant"&&N.responseText?.includes("Model suggestion ready")),A=await(y.length>0?ue.findModelProposalsByThread(a):Promise.resolve([])),P=await Promise.all(A.map(async(N,J)=>{if(N.authorityStatus==="accepted")return N;let he=(await Promise.all(N.decisionIds.map(U=>W.findPendingProposalForLegacyDecision(U)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??y[J]?.jobId??y.at(-1)?.jobId,underlyingProposalId:he?.proposalId,underlyingClaim:he?.claim}})),O=[...P].sort((N,J)=>J.updatedAt-N.updatedAt)[0]??null,$=j.elementIdentifiers.some(N=>N.startsWith("codex-session:"))?await W.findPendingProposalsForThread(a):[],q=j.messages.map(({screenshotPath:N,screenshotPaths:J,imagePaths:he,attachmentFiles:U,replyImagePaths:se,...me})=>({...me,...N?{screenshotUrl:sn(N)}:{},...J?{screenshotUrls:Object.fromEntries(Object.entries(J).map(([te,ge])=>[te,sn(ge)]))}:{},...he?{imageUrls:Object.fromEntries(Object.entries(he).map(([te,ge])=>[te,ge.map(sn)]))}:{},...U?{attachments:Object.fromEntries(Object.entries(U).map(([te,ge])=>[te,ge.map(({path:ie,...ve})=>({...ve,url:sn(ie)}))]))}:{},...se?{replyImageUrls:se.map(sn)}:{}}));_(I,200,{id:j.id,createdAt:j.createdAt,messages:q,modelProposal:O,modelProposals:P,decisionCandidates:$})}async function Xs(a,I){let j=decodeURIComponent(a);if(!await H.deleteThread(j)){_(I,404,{deleted:!1,error:"Thread not found"});return}_(I,200,{deleted:!0})}let Mi=9,Ei=!1;for(let a=t;a<t+Mi;a++)try{await sp(be,a),v=a,Ei=!0,console.log(`[\u22B9 is watching :${v}]`);break}catch(I){if(I.code==="EADDRINUSE"){let j=await Eo(a);if(kn(j,{projectId:r,version:dt,restartMode:g}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw I}if(!Ei)throw new Error(`[Bridge] All ports ${t}\u2013${t+Mi-1} in use`);for(let[a,I]of Object.entries(u))!I.available||!I.path||h(a,I.path).then(j=>{if(j)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),I.available=!1,I.path=null;for(let y of K)Mo(y,{type:"capabilities_changed",data:{}})}});let Ys=setInterval(()=>{_s(c).catch(()=>{}),V.sweep().catch(()=>{})},Wl),_i=setInterval(()=>{z.expireStale().becameEmpty&&L()},Gl);return _i.unref?.(),{port:v,projectId:r,storeId:s.storeId,close:async()=>{clearInterval(Ys),clearInterval(_i),x(),z.clear(),await V.cleanupPartials(),await T.destroyAsync(),C.destroy();for(let a of K)try{a.res.end()}catch{}return K.clear(),new Promise(a=>{be.close(()=>a())})}}}async function _s(o){try{let e=await Cl(o),t=Date.now();for(let n of e){let i=Be(o,n);try{let r=await Ol(i);t-r.mtimeMs>Hl&&await Dl(i)}catch{}}}catch{}}import{randomUUID as ap}from"crypto";var dp=5e3,cp=250;function Ai(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Ds(o,e=fetch){let t=`${process.pid}-${ap()}`,n=`http://127.0.0.1:${o.port}`,i=!1,r=!1,s=async()=>(await e(`${n}/leases`,{method:"POST",headers:Ai(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 d=async()=>{if(!(i||r)){r=!0;try{(await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"PATCH",headers:Ai(o)})).status===404&&!i&&await s()}catch{}finally{r=!1}}},c=setInterval(()=>{d()},dp);return c.unref?.(),{id:t,release:async()=>{if(!i){i=!0,clearInterval(c);try{await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"DELETE",headers:Ai(o),keepalive:!0})}catch{}}}}}function Ns(o,e=process){let t=!1,n=new Map,i=()=>{if(!t){t=!0;for(let[r,s]of n)e.removeListener(r,s);n.clear()}};for(let r of["SIGINT","SIGTERM"]){let s=()=>{let d=e.listenerCount(r),c=o.release();if(d>0)return;let l=new Promise(w=>{setTimeout(w,cp)});Promise.race([c,l]).finally(()=>{i(),e.kill(e.pid,r)})};n.set(r,s),e.prependOnceListener(r,s)}return i}var vp=1111,Bs=3e4,wp=8e3;async function bp(o){return gp(o).catch(()=>o)}async function Js(o,e){let n=(await hp(e,"utf8").catch(()=>"")).slice(-wp).trim();return new Error(n?`${o}
236
+ `);let w=new URL(d.url||"/",`http://127.0.0.1:${I}`).searchParams.get("sourceId")||void 0,M={id:lt().slice(0,8),res:v,sourceId:w};oe.add(M),d.on("close",()=>{oe.delete(M)})}async function Oo(d,v,A){a??=bs(d.headers),ot();let w=[...P.allActive,...O.allActive.map(Y=>({id:Y.id,status:Y.status,threadId:Y.threadId,annotationIds:Y.annotationIds??[],color:"#000000",kind:"project_model",standalone:Y.standalone}))],[M,R,N,J,U]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),B.status(),Q.store.load(),x.load()]),F=[],q=Y=>Y.reason instanceof Error?Y.reason.message:String(Y.reason);M.status==="rejected"&&F.push({subsystem:"projection",message:q(M)}),R.status==="rejected"&&F.push({subsystem:"projection",message:q(R)}),N.status==="rejected"?F.push({subsystem:"memory",message:q(N)}):N.value.state==="degraded"&&F.push({subsystem:"memory",message:N.value.error??"Product memory is degraded."}),J.status==="rejected"&&F.push({subsystem:"imprint",message:q(J)}),U.status==="rejected"&&F.push({subsystem:"threads",message:q(U)});let ge=M.status==="fulfilled"?M.value.runs:[],V=R.status==="fulfilled"?R.value.proposals:[],me=xs(ge,V),re=me.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})),Z=N.status==="fulfilled"?N.value:{initialized:!1,state:"degraded",error:q(N)},ye=U.status==="fulfilled"?[...new Set(Object.values(U.value.threads).flatMap(Y=>$n(Y.messages)))]:[],ne=J.status==="fulfilled"?ye.filter(Y=>J.value.graph.explanations.some(Pe=>Pe.id===Y&&Pe.state==="testing")):[],be=J.status==="fulfilled"?{state:"ready",head:J.value.graph.head,updatedAt:J.value.graph.updatedAt,explanationCount:J.value.graph.explanations.filter(Y=>Y.state!=="retired").length,concreteCount:J.value.graph.concrete.length,relationCount:J.value.graph.relations.length,pendingGroundingCount:ne.length,recoveredTransactions:J.value.recoveredTransactions,admission:Q.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:q(J),pendingGroundingCount:ne.length,admission:Q.diagnostics(),admissionWindowStartedAt:e},Re=F.length>0?"degraded":Z.state==="absent"||Z.state==="initializing"?"initializing":"healthy",pe=new Date().toISOString();C(v,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Re,issues:F},version:ct,restartMode:g,projectId:i,storeId:s.storeId,projectName:_o(r),projectRoot:r,requestProjectId:A,projectIdVerified:A===i,devOrigin:a,capture:{native:{configured:!!u,endpoint:u?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:w[0]?{id:w[0].id,status:w[0].status}:null,activeJobs:w.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:P.depth+O.depth,projectionQueueDepth:O.depth,leases:{active:W.isActivated,count:W.size,nextExpiryAt:W.nextExpiryAt,shutdownPending:H},projection:{state:M.status==="fulfilled"&&R.status==="fulfilled"?"ready":"degraded",activeJob:O.active?{id:O.active.id,status:O.active.status,threadId:O.active.threadId,annotationIds:O.active.annotationIds??[],provider:O.active.provider,model:O.active.model}:null,queueDepth:O.depth,recentRuns:me.recentRuns,recentAppliedRuns:me.recentAppliedRuns,actionableProposalCounts:me.actionableProposalCounts,actionableProposals:re},memory:Z,imprint:be,recentJobsRetentionMs:sn,recentJobs:Me})}async function Do(d,v){let A=await new Promise(w=>{let M="";d.on("data",R=>{M+=R.toString()}),d.on("end",()=>w(M))});try{let w=JSON.parse(A);typeof w.devOrigin=="string"&&(a=w.devOrigin||null),C(v,200,{ok:!0,devOrigin:a})}catch{C(v,400,{error:"Invalid JSON"})}}async function an(d){let v=await he.load();C(d,200,{ok:!0,...v})}async function qe(d,v){let A=await $e(d);if(!Es(A.theme)){C(v,400,{error:"theme must be light, dark, or auto"});return}let w=await he.setTheme(A.theme);C(v,200,{ok:!0,exists:!0,preferences:w})}async function Fe(d,v){let w=new URL(d.url||"/",`http://127.0.0.1:${I}`).searchParams.get("jobId"),M=w?P.allActive.filter(q=>q.id===w):P.allActive,R=w?O.allActive.filter(q=>q.id===w):O.allActive,N=[...M.map(q=>q.threadId),...R.map(q=>q.threadId)].filter(Boolean),J=w?P.cancelJob(w):P.cancelActive(),U=w?O.cancelJob(w):O.cancelActive(),F=!!(J||U);for(let q of N)await x.appendMessage(q,{role:"assistant",timestamp:Date.now(),jobId:w||U?.id||"",cancelled:!0});C(v,200,{cancelled:F})}async function Ye(d){let v=lt().slice(0,8),A=d.threadId,w=!A;A||(A=(await x.createThread(`thread-${lt()}`,[])).id,wt.set(A,"project_model")),w&&await x.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:d.reason}),await x.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:w?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:d.model,provider:d.provider});let M={id:v,status:"queued",createdAt:Date.now(),provider:d.provider,model:d.model,agentSettings:d.agentSettings,threadId:A,annotationIds:d.annotationIds,sourceId:d.sourceId,standalone:w},R=O.enqueue(M);return{jobId:v,position:R,threadId:A}}async function _t(d,v){let A=decodeURIComponent(d),w=await se.findModelProposal(A);if(!w){C(v,404,{error:"Model proposal not found"});return}C(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:w})}async function xt(d,v,A){let w=decodeURIComponent(d),M=[];for await(let V of v)M.push(typeof V=="string"?Buffer.from(V):V);let R;try{R=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{C(A,400,{error:"Invalid JSON"});return}let N=(R.changes??[]).flatMap(V=>{if(!Array.isArray(V.path)||V.path.length===0)return[];let me=V.path.filter(Z=>typeof Z=="string"||typeof Z=="number");if(me.length!==V.path.length)return[];let re=Array.isArray(V.decisionIds)?V.decisionIds.filter(Z=>typeof Z=="string"):void 0;return[{path:me,value:V.value,remove:V.remove===!0,decisionIds:re}]});if(N.length===0){C(A,400,{error:"No selected model changes"});return}let J=(R.changeSummaries??[]).flatMap(V=>{if(!V||typeof V!="object")return[];let me=Array.isArray(V.path)?V.path.filter(re=>typeof re=="string"||typeof re=="number"):void 0;return Array.isArray(V.path)&&me?.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:me,value:V.value,currentValue:V.currentValue}]}),U=await se.findModelProposal(w);if(!U){C(A,404,{error:"Model proposal not found"});return}if(U.authorityStatus!=="accepted"){C(A,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(U.status!=="pending"){C(A,409,{error:`Model proposal is already ${U.status}.`});return}let F=U.decisionIds.map(V=>{let me=U.changes?.filter(ye=>ye.decisionIds.includes(V)).length??0,re=N.filter(ye=>ye.decisionIds?.includes(V)).length,Z=re===0?"unprojected":me>re?"partially_projected":"projected";return{decisionId:V,status:Z}}),q=await B.applyModelProjection({runId:U.runId??U.id,presentationJobId:U.presentationJobId,decisionIds:U.decisionIds,changes:N.map(V=>({path:V.path,value:V.value,decisionIds:V.decisionIds})),coverage:F}),ge=await se.applySelectedModelProposal(w,N,J);if(!ge){C(A,404,{error:"Model proposal not found"});return}if(ge.threadId){let V=rn(R.provider),me=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:V,model:me})}C(A,200,{proposal:ge,projection:q})}async function No(d,v,A){let w=decodeURIComponent(d),{provider:M,model:R}=await Dn(v),N=await se.dismissModelProposal(w);if(!N){C(A,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:M,model:R}),C(A,200,{proposal:N})}async function Dn(d){try{let v=[];for await(let w of d)v.push(typeof w=="string"?Buffer.from(w):w);if(v.length===0)return{};let A=JSON.parse(Buffer.concat(v).toString());return{provider:rn(typeof A.provider=="string"?A.provider:void 0),model:typeof A.model=="string"&&A.model?A.model:void 0,agentSettings:Qt(A)}}catch{return{}}}async function Qs(d){let v=wt.get(d);if(v)return v;let M=(await x.getThread(d))?.messages.find(R=>R.role==="human")?.feedbackSummary??"";if(M.startsWith("Synthesize rules"))return wt.set(d,"synthesize"),"synthesize";if(M.startsWith("Materialize model")||M.startsWith("Project model"))return wt.set(d,"project_model"),"project_model"}async function Xs(d,v){let A=[];for await(let U of d)A.push(typeof U=="string"?Buffer.from(U):U);let w;if(A.length>0)try{w=JSON.parse(Buffer.concat(A).toString("utf-8")).serverUrl}catch{}let M=[];p.claude?.available&&p.claude.mcp&&!p.claude.mcp.found&&M.push(await Yi(w)),p.codex?.available&&p.codex.mcp&&!p.codex.mcp.found&&M.push(await Zi(w)),p.copilot?.available&&p.copilot.mcp&&!p.copilot.mcp.found&&M.push(await es(w,p.copilot.path??k));let[R,N,J]=await Promise.all([Ir(r),wr(r),vr(r,p.copilot?.path??k)]);p.claude&&(p.claude.mcp=R),p.codex&&(p.codex.mcp=N),p.copilot&&(p.copilot.mcp=J),C(v,200,{results:M,capabilities:{providers:p}})}async function Ys(d,v){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let M=await B.recordDirectModelMutation({key:`components.${w.name}`,value:{description:""},claim:`${w.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{added:!0,alreadyExists:!1,...M})}async function Zs(d,v){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.name||typeof w.name!="string"){C(v,400,{error:"Missing or invalid name"});return}let M=await B.recordDirectModelMutation({key:`components.${w.name}`,value:null,claim:`${w.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{removed:!0,...M})}async function ea(d,v){let A=[];for await(let N of d)A.push(typeof N=="string"?Buffer.from(N):N);let w;try{w=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"||typeof w.value!="string"){C(v,400,{error:"Missing or invalid path/value"});return}let M=w.value;try{let N=JSON.parse(w.value);N&&typeof N=="object"&&(M=N)}catch{}let R=await B.recordDirectModelMutation({key:`tokens.${w.path}`,value:M,claim:`${w.path} uses ${w.value} in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{updated:!0,...R})}async function ta(d,v){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let w;try{w=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(v,400,{error:"Invalid JSON"});return}if(!w.path||typeof w.path!="string"){C(v,400,{error:"Missing or invalid path"});return}let M=await B.recordDirectModelMutation({key:`tokens.${w.path}`,value:null,claim:`${w.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(v,200,{removed:!0,...M})}function na(d,v){let A=a??"http://localhost:3000";if(!a){let M=d.headers.referer||d.headers.origin;if(M)try{let R=new URL(typeof M=="string"?M:M[0]||"");(R.hostname==="localhost"||R.hostname==="127.0.0.1")&&(A=R.origin)}catch{}}let w=Jr(I,A);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(w)}async function oa(d){let v=Date.now();if(vt&&v<vt.expires){C(d,200,vt.data);return}try{let{scanForComponents:A}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:w}=await import("./render-generator-HWFLZYC3.mjs"),M=await A(r);vt={data:M,expires:v+5e3},w(M,r,On).then(R=>{On=R}).catch(R=>console.warn("[Bridge] Render generation failed:",R)),C(d,200,M)}catch(A){console.error("[Bridge] Scanner error:",A),C(d,500,{error:"Failed to scan components"})}}async function ra(d){let v=[Le(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Le(r,"packages","popmelt","dist","canvas.mjs")];try{let A=ap(import.meta.url);v.unshift(Le(rp(A),"canvas.mjs"))}catch{}for(let A of v)try{let w=await Ns(A,"utf-8");d.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),d.end(w);return}catch{}console.error("[Bridge] Canvas bundle not found in:",v),C(d,404,{error:"Canvas bundle not found"})}async function ia(d,v){if(!d||d.includes("/")||d.includes("\\")||d.includes("..")){C(v,400,{error:"Invalid filename"});return}try{let A=[Le(c,d),Le(r,".popmelt","artifacts","thread-media",d),Le(r,".popmelt","artifacts","eval-screenshots",d),Le(r,".popmelt","evals","screenshots",d),Le(r,".popmelt","screenshots",d)],w;for(let N of A)try{w=await Ns(N);break}catch{}if(!w)throw new Error("File not found");let M=d.split(".").pop()?.toLowerCase(),R=M==="png"?"image/png":M==="webp"?"image/webp":M==="jpg"||M==="jpeg"?"image/jpeg":M==="svg"?"image/svg+xml":M==="txt"?"text/plain; charset=utf-8":"application/octet-stream";v.writeHead(200,{"Content-Type":R,"Cache-Control":"public, max-age=3600"}),v.end(w)}catch{C(v,404,{error:"File not found"})}}function dn(d){return`/files/${_o(d)}`}async function sa(d,v){let A=await x.getThread(d);if(!A){C(v,404,{error:"Thread not found"});return}let w=A.messages.filter(F=>F.role==="assistant"&&F.responseText?.includes("Model suggestion ready")),M=await(w.length>0?se.findModelProposalsByThread(d):Promise.resolve([])),R=await Promise.all(M.map(async(F,q)=>{if(F.authorityStatus==="accepted")return F;let ge=(await Promise.all(F.decisionIds.map(V=>B.findPendingProposalForLegacyDecision(V)))).find(Boolean);return{...F,authorityStatus:"legacy_untrusted",presentationJobId:F.presentationJobId??w[q]?.jobId??w.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),N=[...R].sort((F,q)=>q.updatedAt-F.updatedAt)[0]??null,J=A.elementIdentifiers.some(F=>F.startsWith("codex-session:"))?await B.findPendingProposalsForThread(d):[],U=A.messages.map(({screenshotPath:F,screenshotPaths:q,imagePaths:ge,attachmentFiles:V,replyImagePaths:me,...re})=>({...re,...F?{screenshotUrl:dn(F)}:{},...q?{screenshotUrls:Object.fromEntries(Object.entries(q).map(([Z,ye])=>[Z,dn(ye)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([Z,ye])=>[Z,ye.map(dn)]))}:{},...V?{attachments:Object.fromEntries(Object.entries(V).map(([Z,ye])=>[Z,ye.map(({path:ne,...be})=>({...be,url:dn(ne)}))]))}:{},...me?{replyImageUrls:me.map(dn)}:{}}));C(v,200,{id:A.id,createdAt:A.createdAt,messages:U,modelProposal:N,modelProposals:R,decisionCandidates:J})}async function aa(d,v){let A=decodeURIComponent(d);if(!await x.deleteThread(A)){C(v,404,{deleted:!1,error:"Thread not found"});return}C(v,200,{deleted:!0})}let $r=9,Or=!1;for(let d=t;d<t+$r;d++)try{await Pp(xe,d),I=d,Or=!0,console.log(`[\u22B9 is watching :${I}]`);break}catch(v){if(v.code==="EADDRINUSE"){let A=await $o(d);if(An(A,{projectId:i,version:ct,restartMode:g}))return console.log(`[\u22B9 already watching :${d}]`),{port:d,projectId:i,close:async()=>{}};continue}throw v}if(!Or)throw new Error(`[Bridge] All ports ${t}\u2013${t+$r-1} in use`);for(let[d,v]of Object.entries(p))!v.available||!v.path||f(d,v.path).then(A=>{if(A)console.log(`[Bridge] ${d} warmed up`);else{console.warn(`[Bridge] ${d} warm-up failed \u2014 marking unavailable`),v.available=!1,v.path=null;for(let w of oe)Co(w,{type:"capabilities_changed",data:{}})}});let da=setInterval(()=>{Fs(c).catch(()=>{}),L.sweep().catch(()=>{})},lp),Dr=setInterval(()=>{W.expireStale().becameEmpty&&X()},up);return Dr.unref?.(),{port:I,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(da),clearInterval(Dr),G(),W.clear(),await L.cleanupPartials(),await P.destroyAsync(),O.destroy();for(let d of oe)try{d.res.end()}catch{}return oe.clear(),new Promise(d=>{xe.close(()=>d())})}}}async function Fs(o){try{let e=await Yl(o),t=Date.now();for(let n of e){let r=Le(o,n);try{let i=await ep(r);t-i.mtimeMs>pp&&await tp(r)}catch{}}}catch{}}import{randomUUID as Rp}from"crypto";var kp=5e3,Mp=250;function _r(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Hs(o,e=fetch){let t=`${process.pid}-${Rp()}`,n=`http://127.0.0.1:${o.port}`,r=!1,i=!1,s=async()=>(await e(`${n}/leases`,{method:"POST",headers:_r(o),body:JSON.stringify({leaseId:t,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(b){return console.warn("[popmelt] failed to register bridge lease:",b instanceof Error?b.message:String(b)),null}let a=async()=>{if(!(r||i)){i=!0;try{(await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"PATCH",headers:_r(o)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},c=setInterval(()=>{a()},kp);return c.unref?.(),{id:t,release:async()=>{if(!r){r=!0,clearInterval(c);try{await e(`${n}/leases/${encodeURIComponent(t)}`,{method:"DELETE",headers:_r(o),keepalive:!0})}catch{}}}}}function Ws(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),c=o.release();if(a>0)return;let l=new Promise(b=>{setTimeout(b,Mp)});Promise.race([c,l]).finally(()=>{r(),e.kill(e.pid,i)})};n.set(i,s),e.prependOnceListener(i,s)}return r}var Bp=1111,Gs=3e4,Jp=8e3;async function Lp(o){return Op(o).catch(()=>o)}async function Ks(o,e){let n=(await $p(e,"utf8").catch(()=>"")).slice(-Jp).trim();return new Error(n?`${o}
237
237
  Bridge log (${e}):
238
- ${n}`:o)}async function ih(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 xp(o);if(o.manageLease===!1)return t;let n=await Ds({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let i=Ns(n);return{...t,close:async()=>{i(),await n.release()}}}let e=await Os(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function xp(o){let e=o.port??vp,t=await bp(o.projectRoot??process.cwd()),n=Lt(t),i=await Bn(t);for(let b=e;b<e+10;b++){let k=await Eo(b);if(k&&k.projectId===n){if(k.version&&k.version!==dt){if(k.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${b}/shutdown`,{method:"POST"})}catch{}await new Promise(f=>setTimeout(f,500));break}continue}if(!kn(k,{projectId:n,version:dt,restartMode:"detached"}))continue;let S=o.devOrigin;if(S&&k.devOrigin!==S)try{await fetch(`http://127.0.0.1:${b}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:S})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,storeId:i.storeId,close:async()=>{}}}}let r=ji(yp(Ip(import.meta.url)),"bridge-entry.mjs"),s=ji(t,".popmelt"),d=ji(s,"bridge.log");await fp(s,{recursive:!0}),await mp(d,`
238
+ ${n}`:o)}async function jh(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 qp(o);if(o.manageLease===!1)return t;let n=await Hs({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let r=Ws(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 qp(o){let e=o.port??Bp,t=await Lp(o.projectRoot??process.cwd()),n=Kt(t),r=await Xn(t);for(let y=e;y<e+10;y++){let k=await $o(y);if(k&&k.projectId===n){if(k.version&&k.version!==ct){if(k.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${y}/shutdown`,{method:"POST"})}catch{}await new Promise(h=>setTimeout(h,500));break}continue}if(!An(k,{projectId:n,version:ct,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=Cr(Dp(Np(import.meta.url)),"bridge-entry.mjs"),s=Cr(t,".popmelt"),a=Cr(s,"bridge.log");await Cp(s,{recursive:!0}),await _p(a,`
239
239
  [${new Date().toISOString()}] Starting detached bridge
240
- `);let c=up(d,"a"),l;try{l=lp(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{pp(c)}let w=null;l.once("error",b=>{w=`spawn error: ${b.message}`}),l.once("exit",(b,k)=>{w=`child exited before becoming healthy (${k?`signal ${k}`:`code ${b??"unknown"}`})`}),l.unref();let R=Date.now()+Bs;for(;Date.now()<R;){if(await new Promise(b=>setTimeout(b,100)),w)throw await Js(`[Bridge] Detached bridge ${w}`,d);for(let b=e;b<e+10;b++){let k=await Eo(b);if(kn(k,{projectId:n,version:dt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,storeId:i.storeId,close:async()=>{}}}}throw l.kill("SIGTERM"),await Js(`[Bridge] Detached bridge failed to start within ${Bs/1e3}s (port ${e})`,d)}export{Nt as ImprintService,Dt as ImprintStore,Jt as formatImprintPrompt,Bo as imprintExplanationRef,Bt as parseImprintDraft,ta as qualifyImprintRelation,ih as startPopmelt};
240
+ `);let c=Ep(a,"a"),l;try{l=jp(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{Ap(c)}let b=null;l.once("error",y=>{b=`spawn error: ${y.message}`}),l.once("exit",(y,k)=>{b=`child exited before becoming healthy (${k?`signal ${k}`:`code ${y??"unknown"}`})`}),l.unref();let S=Date.now()+Gs;for(;Date.now()<S;){if(await new Promise(y=>setTimeout(y,100)),b)throw await Ks(`[Bridge] Detached bridge ${b}`,a);for(let y=e;y<e+10;y++){let k=await $o(y);if(An(k,{projectId:n,version:ct,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 Ks(`[Bridge] Detached bridge failed to start within ${Gs/1e3}s (port ${e})`,a)}export{gt as ImprintService,Bt as ImprintStore,Lt as formatImprintPrompt,qo as imprintExplanationRef,Jt as parseImprintDraft,pa as qualifyImprintRelation,jh as startPopmelt};