@popmelt.com/core 0.10.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,56 +1,26 @@
1
- import{mkdir as Sp,unlink as Tp,writeFile as kp}from"fs/promises";import{join as Fs}from"path";import{execFileSync as Wl,spawn as _s}from"child_process";import{randomUUID as ct}from"crypto";import{mkdir as Kl,readFile as Cs,readdir as Gl,realpath as Hl,stat as Ql,unlink as Xl,writeFile as Mo}from"fs/promises";import{createServer as Yl}from"http";import{tmpdir as Zl}from"os";import{basename as jo,dirname as ep,isAbsolute as Js,join as qe,relative as tp,resolve as np}from"path";import{fileURLToPath as op}from"url";function Cr(o,e){return`<!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <title>Popmelt Canvas</title>
6
- <link rel="preconnect" href="https://fonts.googleapis.com">
7
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
8
- <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
9
- <style>*{margin:0;padding:0;box-sizing:border-box}html,body,#root{height:100%;overflow:hidden}</style>
10
- </head>
11
- <body>
12
- <div id="root"></div>
13
- <script type="importmap">
14
- {"imports":{
15
- "react":"https://esm.sh/react@19?dev",
16
- "react-dom/client":"https://esm.sh/react-dom@19/client?dev",
17
- "react/jsx-runtime":"https://esm.sh/react@19/jsx-runtime?dev"
18
- }}
19
- </script>
20
- <script type="module">
21
- const isProxied = location.pathname === '/popmelt' || location.pathname.startsWith('/popmelt/');
22
- const bridgeOrigin = isProxied ? location.origin + '/popmelt' : location.origin;
23
- const canvasModule = isProxied ? bridgeOrigin + '/app.mjs' : location.origin + '/canvas/app.mjs';
24
- const { mountCanvas } = await import(canvasModule);
25
- mountCanvas(document.getElementById('root'), {
26
- devOrigin: isProxied ? location.origin : ${JSON.stringify(e)},
27
- bridgeOrigin,
28
- });
29
- </script>
30
- </body>
31
- </html>`}import{createHash as Td,randomUUID as kd}from"crypto";import{isAbsolute as Rd,relative as Pd}from"path";function Ct(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function on(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 $t(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
32
- `)}async function On(o,e,t,n){let r=$t(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(p=>p.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 rn(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";var $r={project:0,route:1,component:2,selector:2,file:3},Or={intention:0,principle:1,pattern:2};function Ot(o,e){let t=$r[o.scope.kind]-$r[e.scope.kind];return t!==0?t:Or[o.kind]-Or[e.kind]}function Dr(o){return o==="expresses"||o==="excepts"}function da(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=Ot(t,n);return r===0?void 0:r>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 r=da(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 ca}from"crypto";import{mkdir as la,open as pa,readFile as Nr,readdir as ua,rename as ma,unlink as fa}from"fs/promises";import{dirname as ha,join as Dt}from"path";function Be(o){return structuredClone(o)}function Br(o){return ca("sha256").update(JSON.stringify(o)).digest("hex")}async function St(o,e){await la(ha(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await pa(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
34
- `,"utf8"),await n.sync()}finally{await n.close()}try{await ma(t,o)}catch(r){throw await fa(t).catch(()=>{}),r}}function ga(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function ya(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 No(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")ya(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),p=!s&&t.concrete.some(b=>b.id===r.toId);if(Dr(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(Ot(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 v=[r.toId],P=new Set;for(;v.length;){let T=v.pop();if(T===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);P.has(T)||(P.add(T),v.push(...S.get(T)??[]))}}}else if(!i||!a&&!p)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 Ia(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=No(n,[r])}return t}function Jr(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 Dn=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Dt(e,".popmelt","imprint"),this.manifestPath=Dt(this.imprintDir,"manifest.json"),this.graphPath=Dt(this.imprintDir,"graph.json"),this.journalDir=Dt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await Nr(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 ua(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=ga(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<n.length;a++){let c=JSON.parse(await Nr(Dt(this.journalDir,n[a]),"utf8")),{hash:p,...b}=c;if(c.sequence!==a+1||c.previousHash!==s||p!==Br(b))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=No(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: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),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 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(S=>S.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=n.graph.head.sequence+1,i=Ia(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:Br(s)},c=No(n.graph,a.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:a.hash};let p=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await St(Dt(this.journalDir,p),a);let b={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,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(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(Jr));if(i.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(b=>Jr(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 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 wa=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),va=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"]),ba=[/\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],xa=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Jo(o){return!!(o&&xa.test(o))}function Sa(o){return o.scope.kind==="project"||Jo(`${o.statement} ${o.rationale}`)}function Ta(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 ka(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ra(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(ka(o).split(" ").filter(e=>e.length>2&&!va.has(e)).flatMap(Ra))}function qr(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 Pa(o){if(o)for(let e of ba){let t=e.exec(o);if(!t||t.index<=0)continue;let n=qr(o.slice(0,t.index)),r=qr(o.slice(t.index+t[0].length));if(n&&r)return{target:n,reference:r}}}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 Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ft(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 Lr(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Fr(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 Ur(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 sn(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 p=JSON.parse(c);if(!p||typeof p!="object"||Array.isArray(p)||!Object.prototype.hasOwnProperty.call(p,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let b=p;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(!wa.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()):[],y=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...u,...g])].some(E=>!y.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(k=>{let O=e.context?.explanations.find(K=>K.id===k);return y.has(k)&&O&&(O.state==="emerging"||O.state==="testing")&&!E.has(k)});if(D.length){let k=a.grounding,O=typeof k?.explanationId=="string"&&D.includes(k.explanationId)?k.explanationId:D[0],K=ve(k?.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:K||"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 k=e.context?.explanations.find(O=>O.id===E);if(!k)throw new Error("duplicate assessment must cite a surfaced explanation");if(Jo(e.requestText)&&!Sa(k))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(l=>l.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,y={title:ve(g?.title,120),detail:ve(g?.detail,500)};if(!y.title||!y.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:h,summary:y},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 y=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!y.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 l=new Set(e.context?.pendingGroundingExplanationIds??[]),j=g.filter(E=>{let D=y.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!l.has(E)});if(!j.length){if(g.every(D=>y.get(D)?.state==="grounded"||l.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,p=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(p)))throw new Error("summary.kind is invalid");let b={kind:p,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()):[],v=[];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),y=ve(u.rationale);if(!g||!y)continue;v.push({op:"add",clientId:ve(u.clientId,100)||void 0,kind:u.kind,statement:g,rationale:y,scope:Lr(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:Lr(u.scope),reopenGrounding:u.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&v.push(g)}else if(u.op==="evidence"&&typeof u.explanationId=="string"&&["supports","challenges","excepts"].includes(String(u.stance))){let g=ve(u.summary);g&&v.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),y=Fr(u.from,u.fromId,u.fromStoreId),l=Fr(u.to,u.toId,u.toStoreId);if(!g||!y||!l)continue;v.push({op:"relation",type:u.type,from:y,to:l,rationale:g})}else if(u.op==="supersede"&&typeof u.explanationId=="string"&&typeof u.replacementId=="string"){let g=ve(u.reason);g&&v.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&&v.push({op:"bind_concrete",explanationId:u.explanationId,modelPath:g,rationale:ve(u.rationale)})}else u.op==="retire"&&typeof u.explanationId=="string"&&v.push({op:"retire",explanationId:u.explanationId,reason:ve(u.reason)})}let P=a.grounding,T=P&&typeof P.explanationId=="string"&&ve(P.question)?{explanationId:P.explanationId,question:ve(P.question,300)}:void 0;return{draft:{decision:"mutate",summary:b,appliedExplanationIds:S,mutations:v,grounding:T},visibleText:n}}catch(a){return{visibleText:n,error:a instanceof Error?a.message:String(a)}}}function an(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),r=new Set(o?.correctionExplanationIds??[]),i=Jo(e.requestText),s=o?.retrievalIntent,a=o?.historicalCaveats??[],c=t.find(v=>v.storeId&&!v.readOnly)?.storeId,p=(v,P)=>{let T=v[P];return T?`[${T.storeId}] ${T.explanationId}`:P==="from"?v.fromId:v.toId},b=!!o?.relations?.some(v=>v.from&&v.to&&v.from.storeId!==v.to.storeId),S=t.some(v=>v.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((v,P)=>[`${P+1}. [${v.state}; ${v.kind}] ${v.statement}`,` - Why: ${v.rationale}`,` - Scope: ${v.scope.kind} ${v.scope.values.join(", ")}`,` - Explanation: ${v.id}`,...v.storeId?[` - Store: ${v.storeId}${v.readOnly?" (read-only)":" (writable primary)"}`]:[],...n.has(v.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(v.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...v.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(v=>`- ${v.storeId?`[owned by ${v.storeId}${v.readOnly?"; read-only":""}] `:""}${p(v,"from")} --${v.type}--> ${p(v,"to")}: ${v.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((v,P)=>[`${P+1}. [challenged; ${v.kind}] ${v.statement}`,` - Why it was previously proposed: ${v.rationale}`,` - Scope: ${v.scope.kind} ${v.scope.values.join(", ")}`,` - Historical explanation: ${v.id}`,...v.storeId?[` - Store: ${v.storeId}${v.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(v=>v.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 Tt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Dn(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=Pa(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 p=await this.contextualGraph(),b=p.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=mt(m,t),k=mt(E,t),O=mt(E,n),K=mt(m,n),H=D+k*.2+O*.25+K*.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||k>=.5||O>=.2||K>=.2;return{item:f,score:H,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),v=f=>p.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=mt(it(`${m.statement} ${m.rationale}`),f),D=mt(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)),P=[],T=f=>{P.length<S&&!P.some(m=>m.id===f.id)&&P.push(f)};if(r&&(v(i).slice(0,2).forEach(({item:f})=>T(f)),v(s).slice(0,2).forEach(({item:f})=>T(f))),b.forEach(({item:f})=>T(f)),!P.length)return;let h=new Set(P.map(f=>f.id)),u=new Set(p.relations.flatMap(f=>f.toStoreId?[]:h.has(f.fromId)?[f.toId]:h.has(f.toId)?[f.fromId]:[])),g=new Set(p.explanations.flatMap(f=>u.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),y=p.explanations.filter(f=>g.has(f.id)&&!h.has(f.id)).sort((f,m)=>m.updatedAt.localeCompare(f.updatedAt)).slice(0,4),l=[...P,...y];for(let f of y)h.add(f.id);let j=r?p.explanations.filter(f=>f.state==="challenged").map(f=>{let m=it(`${f.statement} ${f.rationale} ${f.scope.values.join(" ")}`),E=mt(m,i),D=mt(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:l.map(f=>{let m=new Set(p.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:p.concrete.filter(E=>m.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:b.length>P.length||y.length<g.size,...r?{retrievalIntent:r}:{},...j.length?{historicalCaveats:j}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:p.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])),p=new Map,b=new Map,S=[],v=new Set,P=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),y=new Map((t.context?.explanations??[]).flatMap(x=>x.storeId?[[`${x.storeId}:${x.id}`,x]]:[])),l=x=>x.storeId??u,j=x=>{let $=l(x.from),q=l(x.to);return u&&$!==u||!u&&(x.from.storeId||x.to.storeId)||!g(x.from.explanationId)?!1:!q||q===u?g(x.to.explanationId):!!y.get(`${q}:${x.to.explanationId}`)?.memoryId},f=new Set;for(let x of n)x.op==="relation"&&(l(x.from)!==l(x.to)||x.from.explanationId!==x.to.explanationId)&&j(x)?(f.add(x.from.explanationId),l(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)&&Ur(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)),q=!!x.rootReason?.trim()||m;if(!$&&!q)continue;m&&(m=!1);let B=st();x.clientId&&p.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:Bo(x.scope),state:Q?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(B,he),v.add(B),S.push({op:"add_explanation",explanation:he})}let E=x=>p.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let $=E(x.explanationId),q=c.get($);if(q?.state!=="grounded")continue;let B=st(),Q={id:B,kind:q.kind,statement:x.statement??q.statement,rationale:x.rationale??q.rationale,scope:x.scope?Bo(x.scope):q.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(B,Q),b.set($,B),v.add(B),S.push({op:"add_explanation",explanation:Q});let he=Ot(q,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 q=D(x.explanationId);if(!c.has(q))continue;let B=Ur(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:q,rationale:x.rationale,createdAt:s}}),v.add(q);continue}if(x.op==="relation"){if(!j(x))continue;let q=l(x.from),B=l(x.to);if(u&&q!==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):y.get(`${B}:${he}`);if(!_e||!se||B===u&&Q===he)continue;if(x.type==="expresses"&&Ot(_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}}),v.add(Q),B===u&&v.add(he);continue}if(x.op==="supersede"){let q=D(x.explanationId),B=D(x.replacementId);if(!c.has(q)||!c.has(B)||q===B)continue;S.push({op:"add_evidence",explanationId:q,evidence:ft(t,"challenges",x.reason)}),S.push({op:"revise_explanation",explanationId:q,patch:{state:"challenged",supersededBy:B},updatedAt:s}),v.add(q),v.add(B);continue}let $=D(x.explanationId);if(c.has($))if(v.add($),x.op==="revise"){if(b.has(E(x.explanationId)))continue;let q=c.get($);if(!q||q.state!=="emerging"&&q.state!=="testing")continue;let B={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Bo(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:ft(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:ft(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),q=c.get($);!q||q.state==="grounded"||q.state==="retired"||P.has($)&&!v.has($)||(v.has($)||(v.add($),S.push({op:"add_evidence",explanationId:$,evidence:{...ft(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),q.state==="emerging"&&S.push({op:"revise_explanation",explanationId:$,patch:{state:"testing"},updatedAt:s}))}let k=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 k.has($)?!1:(k.add($),!0)});if(!O.length)return;let K=st(),H=await this.store.commit({transactionId:K,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:O}),_=new Map(H.graph.explanations.map(x=>[x.id,x])),W=[...v].flatMap(x=>{let $=_.get(x);if(!$)return[];let q=!a.graph.explanations.some(Q=>Q.id===x),B=$.state==="challenged"||$.state==="retired";return[{explanationId:x,action:q?"added":B?"challenged":"revised",statement:$.statement,state:$.state}]}),G=i.map(D).find(x=>_.get(x)?.state==="testing"&&!P.has(x)),fe=e.grounding?D(e.grounding.explanationId):G,X=fe?_.get(fe):void 0,oe=X?.state==="testing"&&!P.has(X.id)?{explanationId:X.id,question:e.grounding?.question||Ta(X),state:"testing"}:void 0;return{transactionId:K,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:W,...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(p=>p.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:{...ft(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:{...ft(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 oi,readFile as un,writeFile as ri}from"fs/promises";import{join as qt}from"path";var Ma=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function qo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Nn(o){return new Set(qo(o).split(" ").filter(e=>e.length>2&&!Ma.has(e)))}function zr(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function ja(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 Aa(o,e){let t=new Map,n=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(qo).filter(Boolean),i=Nn([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 ja(s)){let p=qo(c.value);for(let v of r){let P=p===v?95:p.includes(v)||v.includes(p)?75:0;P>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:c.by,score:P})}let S=["/","#","[","]","="].some(v=>c.value.includes(v))?0:Math.round(zr(Nn(p),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 Ea(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 _a(o){return Math.ceil(JSON.stringify(o).length/4)}function Lo(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(y=>y.entity.entityType==="proposal"&&y.entity.entityId===u.id&&y.toState==="deferred"&&y.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=Aa(t,e),c=[...a.values()].sort((u,g)=>g.score-u.score),p=Nn([e.action,e.text].filter(Boolean).join(" ")),b=i.flatMap(u=>{let g=u.subjects.map(f=>a.get(f.subjectId)).filter(f=>!!f),y=Math.max(0,...g.map(f=>f.score)),l=Math.round(zr(Nn(u.claim),p)*35),j=y+l;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),v=Math.max(200,e.maxEstimatedTokens??1200),P=[],T=0;for(let u of b){if(P.length>=S)break;let g=u.proposal.sourceRefs.slice(0,4),y={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:Ea(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]},l={...y,estimatedTokens:_a(y)};if(T+l.estimatedTokens>v)break;P.push(l),T+=l.estimatedTokens}let h=Math.max(0,b.length-P.length);return{packets:P,subjectMatches:c.map(({score:u,...g})=>g),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:b.length,omittedPacketCount:h,maxEstimatedTokens:v,estimatedTokens:T},uncertainty:a.size===0?"subject_unresolved":b.length===0?"no_relevant_pending_proposal":void 0}}var Ca=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Fo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Bn(o){return new Set(Fo(o).split(" ").filter(e=>e.length>2&&!Ca.has(e)))}function Vr(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 $a(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Fo).filter(Boolean),r=Bn([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(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of c){let b=Fo(p.value);for(let P of n){let T=b===P?95:b.includes(P)||P.includes(b)?75:0;T>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=90?"exact":"strong",matchedBy:p.by,score:T})}let v=["/","#","[","]","="].some(P=>p.value.includes(P))?0:Math.round(Vr(Bn(b),r)*55);v>=30&&v>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:v>=45?"strong":"weak",matchedBy:"semantic",score:v})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function Oa(o){return Math.ceil(JSON.stringify(o).length/4)}function Nt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Da(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 Na(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 Wr(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"),p=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"),v=o.records.filter(m=>m.recordType==="model_entry"),P=$a(r,e),T=new Map(P.map(m=>[m.subjectId,m.score])),h=Bn([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(Vr(Bn(m.claim),h)*35),k=E+D;return k>=50?[{decision:m,score:k}]:[]}).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(!Nt(m,"excepts")&&!Nt(m,"contradicts"))continue;let E=s.find(k=>k.id===m.from.entityId),D=s.find(k=>k.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 y=[...g.values()],l=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)),k=b.filter($=>$.target.entityType==="decision"&&D.has($.target.entityId)),O=new Set(o.relationships.filter($=>Nt($,"excepts")&&D.has($.from.entityId)&&D.has($.to.entityId)).flatMap($=>[$.from.entityId,$.to.entityId])),H=o.relationships.filter($=>Nt($,"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(H.flatMap($=>$.decisionIds)),W=S.filter($=>$.sourceRefs.some(q=>q.kind==="record"&&D.has(q.id))||o.relationships.some(q=>q.relationshipType==="supports"&&q.from.entityType==="evidence"&&q.from.entityId===$.id&&q.to.entityType==="decision"&&D.has(q.to.entityId))),G=Math.max(0,u.length-m.length),fe=o.relationships.some($=>Nt($,"contradicts")&&l($)&&(!D.has($.from.entityId)||!D.has($.to.entityId))),X=E||G>0||fe,oe=[];P.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:[]}),H.length&&oe.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap($=>$.expansionRefs)}),W.some($=>$.availability!=="available")&&oe.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:W.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:P.map(({score:$,...q})=>q),modelEntries:v.filter($=>$.decisionIds.some(q=>D.has(q))).map($=>({id:$.id,key:$.key,value:$.value,decisionIds:$.decisionIds})),decisions:m.map($=>({id:$.id,kind:$.kind,claim:$.claim,subjectIds:$.subjects.map(q=>q.subjectId),authority:$.authority,effectiveState:_.has($.id)?"conflicted":O.has($.id)?"excepted":"active",freshness:k.filter(q=>q.target.entityId===$.id).map(q=>q.signalType),expansionRef:{kind:"record",id:$.id}})),conflicts:H,uncertainties:oe,implementation:m.map($=>Da($.id,c)),verification:m.map($=>Na($.id,p,k)),evidence:W.map($=>({evidenceId:$.id,summary:$.summary,availability:$.availability,sourceRefs:$.sourceRefs})),completeness:{status:X?"truncated":"complete",omittedDecisionCount:G,omittedEvidenceCount:0,conflictsComplete:!fe}};return x.budget.estimatedTokens=Oa(x),x},f=j(y);for(;f.budget.estimatedTokens>t&&y.length>0;){let m=y.pop(),E=o.relationships.filter(D=>Nt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);y=y.filter(D=>!E.includes(D.id)),f=j(y,!0)}return f}var Ba=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Bt(o){return Ba.test(o)}function Ja(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 Uo(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Ee(o,e,t){Bt(t)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function He(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function kt(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 qa={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"])},La=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Fa(o,e,t){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),Ee(o,`${t}.entity.entityId`,e.entity.entityId),He(o,`${t}.createdAt`,e.createdAt),kt(o,`${t}.authority`,e.authority);let n=qa[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(La.has(i)&&(kt(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&&He(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ua(o,e,t,n){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),He(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&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"&&(kt(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"&&Uo(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."),He(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."),He(o,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),He(o,`${t}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(He(o,`${t}.appliedAt`,e.appliedAt),kt(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&&Uo(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Uo(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function za(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."),He(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&&kt(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 Rt(o){let e=[];Ee(e,"manifest.projectId",o.manifest.projectId),He(e,"manifest.createdAt",o.manifest.createdAt),He(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(h,u)=>{let 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),Ua(e,h,g,o.manifest.projectId)}),o.events.forEach((h,u)=>{let g=`events[${u}]`;n(h.id,g),Fa(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),za(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),He(e,`${g}.deletedAt`,h.deletedAt),kt(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.")},p=(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":p("participant",h.granteeId,`${g}.granteeId`),p("participant",h.grantedById,`${g}.grantedById`),h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`));break;case"observation":h.captureContext.subjectIds.forEach((y,l)=>p("subject",y,`${g}.captureContext.subjectIds[${l}]`)),h.captureContext.artifactIds.forEach((y,l)=>c(y,`${g}.captureContext.artifactIds[${l}]`));break;case"proposal":case"decision":h.subjects.forEach((y,l)=>p("subject",y.subjectId,`${g}.subjects[${l}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((y,l)=>c(y,`${g}.messageArtifactIds[${l}]`)),h.resultRefs.forEach((y,l)=>s(y,`${g}.resultRefs[${l}]`));break;case"iteration":h.threadIds.forEach((y,l)=>p("thread",y,`${g}.threadIds[${l}]`)),h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"evidence":h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"advisory_explanation":h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`)),h.supersededById&&p("advisory_explanation",h.supersededById,`${g}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((y,l)=>p("iteration",y,`${g}.iterationIds[${l}]`)),h.coverageClaims.forEach((y,l)=>p("decision",y.decisionId,`${g}.coverageClaims[${l}].decisionId`)),h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"eval_spec":h.replacesSpecId&&p("eval_spec",h.replacesSpecId,`${g}.replacesSpecId`),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`)),h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),(h.dependencies??[]).forEach((y,l)=>{y.kind==="subject"&&y.subjectId&&p("subject",y.subjectId,`${g}.dependencies[${l}].subjectId`)}),(h.scenarios??[]).forEach((y,l)=>{y.subjectIds?.forEach((j,f)=>p("subject",j,`${g}.scenarios[${l}].subjectIds[${f}]`))}),h.targets.forEach((y,l)=>p(y.entityType,y.entityId,`${g}.targets[${l}]`));break;case"verification_attempt":h.evalSpecId&&p("eval_spec",h.evalSpecId,`${g}.evalSpecId`),h.targets.forEach((y,l)=>p(y.entityType,y.entityId,`${g}.targets[${l}]`)),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`));break;case"model_entry":h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`));break;case"model_projection":kt(e,`${g}.authority`,h.authority,!0),p("participant",h.appliedById,`${g}.appliedById`),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`)),h.entryIds.forEach((y,l)=>p("model_entry",y,`${g}.entryIds[${l}]`)),h.coverage.forEach((y,l)=>p("decision",y.decisionId,`${g}.coverage[${l}].decisionId`));break;case"freshness_signal":s(h.target,`${g}.target`),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`));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])),v=new Map;o.events.forEach((h,u)=>{let g=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,y=v.get(g)??new Set;y.add(h.toState),v.set(g,y),y.size>1&&te(e,`events[${u}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let P=new Map(o.records.flatMap(h=>h.recordType==="authority_grant"?[[h.id,h]]:[])),T=(h,u,g,y,l)=>{if(h.level!=="delegate"||!h.grantId)return;let j=P.get(h.grantId);if(!j){te(e,l,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==u||j.level!=="delegate")&&te(e,l,"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,l,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&y.length&&!y.every(m=>j.subjectIds.includes(m))&&te(e,l,"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}`),y=g&&"subjects"in g?g.subjects.map(l=>l.subjectId):[];T(h.authority,h.participantId,h.createdAt,y,`events[${u}].authority`)}),o.relationships.forEach((h,u)=>{if(!h.authority)return;let g=[h.from,h.to].flatMap(y=>{let l=S.get(`${y.entityType}:${y.entityId}`);return l&&"subjects"in l?l.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(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.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(y=>y.entity.entityType==="decision"&&y.entity.entityId===h.id&&y.toState==="revoked"&&!!y.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 Ja(e)}function dn(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 Kr(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 Va(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 Jn(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."}),Bt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Va(e))Bt(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={...dn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Kr(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={...dn(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={...dn(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Kr(o,i,e,a.id,e.decisionId),p={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:[p]},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={...dn(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={...dn(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 Wa}from"crypto";import{readFile as Ka,readdir as Ga,realpath as Ha}from"fs/promises";import{join as cn,relative as Qa}from"path";var Xa=["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 Jt(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 Gr(...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=Wa("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 zo(o,e){try{return JSON.parse(await Ka(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function Ya(o){let e=Jt(o);if(!e)return 0;let t=0,n=r=>{let i=Jt(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 Za(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function ln(o){let e=[],t=await Ha(o.projectRoot).catch(()=>o.projectRoot),n=cn(t,".popmelt"),r=await zo(cn(n,"threads.json"),e),i=await zo(cn(n,"model.json"),e),s=Jt(r),a=Jt(s?.threads)??{},c=Object.entries(a).map(([q,B])=>({key:q,value:Jt(B)})).filter(q=>!!q.value),p=cn(n,"decisions"),b=await Ga(p).catch(()=>[]),S=[];for(let q of b.filter(B=>B.endsWith(".json")).sort()){let B=Jt(await zo(cn(p,q),e));B&&S.push({file:q,value:B})}let v=c.flatMap(({value:q})=>[q.createdAt,q.updatedAt]).filter(q=>typeof q=="number"&&Number.isFinite(q)),P=v.length?Math.min(...v):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,P),u=le(T,"participant","legacy-owner",P),g=le(T,"participant","legacy-agent",P),y=le(T,"subject","project",P),l=ze(Math.max(P,...v)),j=[],f=[],m=new Map,E=new Map,D=new Map(S.map(q=>[q.value.id??q.file.replace(/^d-|\.json$/g,""),q.value])),k=new Map,O=(q,B,Q,he,_e)=>{let se=m.get(Q);if(se)return se;let Oe=le(T,"artifact",q,he);return f.push({id:Oe,kind:B,mediaType:_e,location:Q,availability:"available"}),m.set(Q,Oe),Oe};for(let{file:q,value:B}of S){let Q=B.id??q.replace(/^d-|\.json$/g,""),he=B.createdAt??P,_e=[O(`${Q}:envelope`,"other",`.popmelt/decisions/${q}`,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));k.set(Q,_e)}let K=(q,B,Q)=>({id:q,schemaVersion:1,projectId:h,createdAt:l,participantId:B,sourceRefs:Q}),H=(q,B)=>{j.push(B);let Q=E.get(q)??[];Q.push(B.id),E.set(q,Q)},_=[{...K(u,u,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...K(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(..._),j.push({...K(y,u,[]),recordType:"subject",subjectType:"project",label:Qa(process.cwd(),t)||t,aliases:[],locators:[{id:le(T,"locator",t,P),kind:"project_root",value:t,status:"current",validFrom:ze(P),sourceRefs:[]}]});let W=new Map,G=(q,B)=>{let Q=W.get(q);if(Q)return Q;let he=le(T,"subject",q,B),_e={...K(he,u,[{kind:"external",id:q}]),createdAt:ze(B),recordType:"subject",subjectType:"element",label:q,aliases:[],locators:[{id:le(T,"locator",q,B),kind:"dom_selector",value:q,status:"current",validFrom:ze(B),sourceRefs:[{kind:"external",id:q}]}]};return j.push(_e),W.set(q,he),he};for(let{key:q,value:B}of c){let Q=B.id??q,he=B.createdAt??P,_e=le(T,"thread",Q,he),se={kind:"thread",id:Q},Oe=[],gt=[],en=Array.isArray(B.messages)?B.messages:[],Me,ot,yt=0;en.forEach((xe,lt)=>{let De=xe.timestamp??he,rt=le(T,"artifact",`${Q}:message:${lt}`,De);if(Oe.push(rt),f.push({id:rt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${Q}/messages/${lt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${Q}/messages/${lt}`,rt),xe.screenshotPath&&O(`${Q}:message:${lt}:screenshot`,"screenshot",xe.screenshotPath,De),xe.role==="human"){Me=xe;let Le=xe.feedbackSummary??xe.replyToQuestion;if(Le?.trim()){let Fe=le(T,"observation",`${Q}:${lt}`,De),Ye=B.elementIdentifiers??[],Et={...K(Fe,u,[se,{kind:"message",id:rt}]),createdAt:ze(De),recordType:"observation",state:"open",statement:Le,captureContext:{subjectIds:Ye.map(vt=>G(vt,he)),artifactIds:[rt]},resolvedByIds:[]};H(Q,Et),ot=Fe,gt.push({entityType:"observation",entityId:Fe})}return}if(xe.role!=="assistant")return;let pt=xe.jobId??`${Q}:${lt}`,ut=le(T,"iteration",pt,De),wt=D.get(pt),Eo=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",_o={...K(ut,g,[se,{kind:"message",id:rt},...(k.get(pt)??[]).map(Le=>({kind:"artifact",id:Le}))]),createdAt:ze(De),recordType:"iteration",threadIds:[_e],startedAt:ze(Me?.timestamp,De),completedAt:ze(De),requestSummary:Gr(Me?.feedbackSummary,Me?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:Eo,execution:{provider:xe.provider??wt?.provider,model:xe.model??wt?.model,sessionId:xe.sessionId??wt?.sessionId},artifactIds:[rt,...k.get(pt)??[]]};H(Q,_o),gt.push({entityType:"iteration",entityId:ut});let tn=xe.resolutions??wt?.resolutions??[];for(let[Le,Fe]of tn.entries()){if(Fe.status!=="resolved"||!Fe.summary?.trim())continue;let Ye=B.elementIdentifiers??[],Et=(Ye.length?Ye:[t]).map(Cn=>({subjectId:Cn===t?y:G(Cn,he),role:"governed"})),vt=le(T,"proposal",`${pt}:${Fe.annotationId??"resolution"}:${Le}`,De),Co={...K(vt,g,[se,{kind:"iteration",id:ut}]),createdAt:ze(De),recordType:"proposal",state:"pending",claim:Fe.summary,subjects:Et,subjectSemantics:Et.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Gr(Me?.feedbackSummary,Me?.replyToQuestion,Fe.summary),iterationId:ut,inferredById:g}};H(Q,Co),gt.push({entityType:"proposal",entityId:vt}),e.push({severity:"warning",code:"acceptance_unresolved",source:Q,message:`Proposal ${vt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(tn.some(Le=>Le.status==="resolved")||wt?.gitDiff){let Le=le(T,"implementation",pt,De),Fe={...K(Le,g,[se,{kind:"iteration",id:ut}]),createdAt:ze(De),recordType:"implementation_attempt",state:"completed",iterationIds:[ut],coverageClaims:[],summary:tn.map(Ye=>Ye.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};H(Q,Fe),gt.push({entityType:"implementation_attempt",entityId:Le}),yt+=1}ot&&(ot=void 0)});let It=en.at(-1),_n={...K(_e,u,[se]),createdAt:ze(he),recordType:"thread",state:It?.question?"open":"resolved",messageArtifactIds:Oe,outcome:It?.question?"question_unresolved":yt?"implementation_only":"no_outcome",resultRefs:gt};j.push(_n),E.set(Q,[_e,...E.get(Q)??[]])}let fe=Ya(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(P),updatedAt:l,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=Rt(X),$=(o.proofCaseIds??Xa).map(q=>({legacyId:q,threadFound:c.some(({key:B,value:Q})=>(Q.id??B)===q),decisionEnvelopeFound:D.has(q),recordIds:E.get(q)??[]}));return{bundle:X,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((q,B)=>q+(B.value.messages?.length??0),0),decisionEnvelopes:S.length,modelEntries:fe,artifactsReferenced:f.length},imported:Za(j),unresolvedAcceptance:e.filter(q=>q.code==="acceptance_unresolved").length,deferredModelEntries:fe,proofCases:$,issues:e,schemaIssues:oe.issues}}}import{createHash as ed}from"crypto";import{mkdir as Hr,open as Vo,readFile as Wo,readdir as td,rename as nd,unlink as Ko}from"fs/promises";import{join as at}from"path";var od={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function qn(o){return ed("sha256").update(JSON.stringify(o)).digest("hex")}function Qr(o){return qn(o)}function Xr(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 rd(o,e,t){return Xr(structuredClone(o),e,t)}async function Pt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Vo(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
38
- `,"utf8"),await n.sync()}finally{await n.close()}try{await nd(t,o)}catch(r){throw await Ko(t).catch(()=>{}),r}}async function pn(o){return JSON.parse(await Wo(o,"utf8"))}var Ln=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 pn(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=Rt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Hr(this.journalDir,{recursive:!0});try{throw await Wo(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 Wo(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=qn(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 Pt(this.checkpointPath,r),await Pt(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 Pt(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=qn(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 Pt(at(this.memoryDir,n),r),e.manifest.checkpoint={file:n,sequence:r.sequence,hash:t},await Pt(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(!Bt(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:Qr(i)},a=rd(n.bundle,e,t.committedAt),c=Rt(a);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let p=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await Pt(at(this.journalDir,p),s),n.manifest.head={sequence:r,hash:s.hash},n.manifest.updatedAt=t.committedAt,await Pt(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({...od,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await pn(this.manifestPath),t=await pn(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!==qn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await td(this.journalDir),r=n.filter(v=>v.endsWith(".tmp")),s=n.filter(v=>/^\d{12}-[0-9a-f-]+\.json$/i.test(v)).sort().filter(v=>Number(v.slice(0,12))>t.sequence),a=structuredClone(t.bundle),c=t.sequence,p=t.journalHash??null,b=new Set;for(let v of s){let P=await pn(at(this.journalDir,v)),{hash:T,...h}=P;if(T!==Qr(h))throw new Error(`Journal hash mismatch: ${v}`);if(P.sequence!==c+1)throw new Error(`Journal sequence gap at ${v}`);if(P.previousHash!==p)throw new Error(`Journal chain mismatch at ${v}`);if(P.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${v}`);if(b.has(P.transactionId))throw new Error(`Duplicate transaction ID: ${P.transactionId}`);Xr(a,P.mutation,P.committedAt),c=P.sequence,p=P.hash,b.add(P.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==p)throw new Error("Journal manifest head hash mismatch.");let S=Rt(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:p}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Hr(this.memoryDir,{recursive:!0});let t;try{t=await Vo(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let r=await pn(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 Ko(this.lockPath),t=await Vo(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Ko(this.lockPath).catch(()=>{})}}};import{randomBytes as id}from"crypto";function Se(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=id(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 sd=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Yr(o,e){let t=o.records.find(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),n=o.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.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=sd(),p=c.records,b=o.records.find(l=>l.recordType==="thread"&&l.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(l=>l.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(b));let S=[];for(let l of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(f=>f.recordType==="subject"&&f.locators.some(m=>m.value===l&&m.status==="current"));j||(j={id:le(r,"live-subject",l,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"element",label:l,aliases:[],locators:[{id:le(r,"live-locator",l,e.createdAt),kind:"dom_selector",value:l,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:l}]}]},p.push(j)),S.push(j)}for(let l 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===l&&m.status==="current"));j||(j={id:le(r,"live-file-subject",l,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"file",label:l,aliases:[],locators:[{id:le(r,"live-file-locator",l,e.createdAt),kind:"source_file",value:l,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:l}]}]},p.push(j)),S.push(j)}let v=(e.semanticCandidates??[]).filter(l=>l.claim.trim()),P;if(v.length>0){P=le(r,"live-observation",i,e.createdAt);let l={id:P,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:v.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:S.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};p.push(l)}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(l=>({kind:"external",id:l,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(l=>({kind:"external",id:l,uri:"popmelt:imprint-evidence"})),...P?[{kind:"record",id:P}]:[]],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}:{}};p.push(h);let u=[],g=e.resolutions.filter(l=>l.status==="resolved"&&l.summary.trim()),y=S.length>0?S:o.records.filter(l=>l.recordType==="subject"&&l.subjectType==="project").slice(0,1);if(v.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[l,j]of v.entries()){let f=le(r,"live-proposal",`${i}:${l}`,e.completedAt),m=y.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}};p.push(E),u.push(f)}if(g.length>0){let l=new Set(e.governingDecisionIds??[]),j=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&l.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:[]};p.push(f)}return{mutation:c,iterationId:T,proposalIds:u,observationId:P}}import{createHash as ad}from"crypto";import{mkdir as dd,open as cd,readFile as ld,rename as pd,unlink as ud}from"fs/promises";import{join as Zr}from"path";function ei(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ti(o){return ad("sha256").update(JSON.stringify(o)).digest("hex")}async function md(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await cd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
39
- `,"utf8"),await n.sync()}finally{await n.close()}try{await pd(t,o)}catch(r){throw await ud(t).catch(()=>{}),r}}function fd(o,e,t=new Date().toISOString()){let n={},r={},i={},s=(c,p,b)=>{let S=c[p]??=[];S.includes(b)||S.push(b)};for(let c of o.records)if(c.recordType==="subject"){let p=c;for(let b of[p.label,...p.aliases,...p.locators.filter(S=>S.status==="current").map(S=>S.value)]){let S=ei(b);S&&s(n,S,p.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let p of c.subjects)s(r,p.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let p of c.subjects)s(i,p.subjectId,c.id);let a={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:ti(a)}}function ni(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[ei(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 Fn=class{constructor(e){this.indexDir=Zr(e,".popmelt","memory","indexes"),this.indexPath=Zr(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await ld(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===t.sequence&&r.journalHead.hash===t.hash&&i===ti(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let n=fd(e,t);return await dd(this.indexDir,{recursive:!0}),await md(this.indexPath,n),n}};var fn="popmelt:imprint",ii="popmelt:imprint-evidence",Lt="popmelt:imprint-relation";function mn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===fn)?.id}function Go(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 Un(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 Ho(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var zt=class{constructor(e){this.projectRoot=e;this.store=new Ln(e),this.indexStore=new Fn(e),this.manifestPath=qt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await un(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 ln({...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 ln({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=qt(this.projectRoot,".popmelt","memory","migrations"),t=qt(e,"imprint-advisories-v2.json");try{let l=JSON.parse(await un(t,"utf8"));return{migrated:!1,explanations:l.explanations??0,evidence:l.evidence??0}}catch{}let n;try{n=xt(JSON.parse(await un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await oi(e,{recursive:!0}),await ri(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(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),a=r.bundle.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.status==="active")??i,c=r.bundle.records.find(l=>l.recordType==="subject"&&l.subjectType==="project");if(!a||!c)return{migrated:!1,explanations:0,evidence:0};let p=r.bundle.manifest.projectId,b=new Set(r.bundle.records.map(l=>l.id)),S=new Set(r.bundle.relationships.flatMap(l=>l.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Lt?[j.id]:[]))),v=new Map,P=r.bundle.records.filter(l=>l.recordType==="advisory_explanation");for(let l of n.explanations){let j=P.find(f=>mn(f)===l.id);v.set(l.id,j?.id??le(p,"imprint-explanation",l.id,Date.parse(l.createdAt)))}let T=[],h=[],u=[],g=0;for(let l of n.explanations){let j=v.get(l.id),f=P.find(k=>k.id===j),m=[],E=l.evidence.length?l.evidence:[{id:`fallback:${l.id}`,kind:"observation",stance:"supports",summary:l.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:l.createdAt}];for(let k of E){let O=le(p,"imprint-evidence-record",k.id,Date.parse(k.createdAt));m.push(O),!b.has(O)&&(T.push({id:O,schemaVersion:1,projectId:p,createdAt:k.createdAt,participantId:a.id,sourceRefs:Go([{kind:"external",id:k.id,uri:ii},{kind:"external",id:l.id,uri:fn},{kind:"thread",id:k.threadId},{kind:"message",id:k.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(k.kind)?"user_feedback":"judgment",summary:k.summary,availability:"available",artifactIds:[]}),u.push({id:le(p,"imprint-evidence-link",`${l.id}:${k.id}`,Date.parse(k.createdAt)),schemaVersion:1,projectId:p,createdAt:k.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:k.id,uri:ii}],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:p,createdAt:f?.createdAt??l.createdAt,participantId:f?.participantId??a.id,sourceRefs:Go([...f?.sourceRefs??[],{kind:"external",id:l.id,uri:fn}]),recordType:"advisory_explanation",kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),subjectIds:[c.id],evidenceIds:[...new Set([...f?.evidenceIds??[],...m])],concreteBindings:Un(n,l.id),supersededById:l.supersededBy?v.get(l.supersededBy):void 0,updatedAt:l.updatedAt};f?h.push(D):T.push(D)}for(let l of n.relations){let j=Ho(l.type);if(!j||l.toStoreId)continue;let f=v.get(l.fromId),m=v.get(l.toId);!f||!m||S.has(l.id)||u.push({id:le(p,"imprint-relation",l.id,Date.parse(l.createdAt)),schemaVersion:1,projectId:p,createdAt:l.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:l.id,uri:Lt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:f},to:{entityType:"advisory_explanation",entityId:m},reason:l.rationale||"The Imprint graph connected these explanations."})}let y=new Date().toISOString();if(T.length||h.length||u.length)try{let l=await this.store.commit({records:T,recordReplacements:h,events:[],relationships:u,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(p,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:y});await this.refreshIndex(l)}catch(l){if(!(l instanceof Error)||!l.message.includes("Transaction already exists"))throw l}return await oi(e,{recursive:!0}),await ri(t,JSON.stringify({version:2,migratedAt:y,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:Lo(n.bundle,r)}}async contextualize(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:Wr(n.bundle,r),reviewSelection:Lo(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:mn(t)??t.id}]:[]),relations:e.bundle.relationships.flatMap(t=>t.relationshipType!=="expresses"&&t.relationshipType!=="excepts"||t.from.entityType!=="advisory_explanation"||t.to.entityType!=="advisory_explanation"?[]:[{id:t.id,type:t.relationshipType,from:{memoryId:t.from.entityId,...t.from.storeId?{storeId:t.from.storeId}:{}},to:{memoryId:t.to.entityId,...t.to.storeId?{storeId:t.to.storeId}:{}},rationale:t.reason}])}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:Jn(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 ln({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=Jn(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(v=>v.recordType==="proposal"&&v.id===e.proposalId),r=t.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.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(v=>v.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=Jn(t.bundle,c);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(v=>v.message).join(" ")};let b=await this.store.commitReviewPlan(p.plan,{transactionId:Se(i),committedAt:s});await this.refreshIndex(b);let S=p.plan.resultRefs.find(v=>v.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=Yr(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=xt(JSON.parse(await un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),r=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active"),i=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="ai"&&y.status==="active"),s=e.action?r:i??r,a=n.bundle.records.find(y=>y.recordType==="subject"&&y.subjectType==="project");if(!s||!a)return;let c=e.occurredAt??new Date().toISOString(),p=Date.parse(c),b=n.bundle.manifest.projectId,S=[],v=[],P=[],T=n.bundle.records.filter(y=>y.recordType==="advisory_explanation"),h=new Map(T.flatMap(y=>{let l=mn(y);return l?[[l,y.id]]:[]}));for(let y of e.summary.changes)if(!h.has(y.explanationId)){let l=t?.explanations.find(j=>j.id===y.explanationId);h.set(y.explanationId,le(b,"imprint-explanation",y.explanationId,Date.parse(l?.createdAt??c)))}for(let y of e.summary.changes){let l={kind:"external",id:y.explanationId,uri:fn},j=h.get(y.explanationId),f=T.find(k=>k.id===j),m=t?.explanations.find(k=>k.id===y.explanationId),E={id:le(b,"imprint-live-evidence",`${e.summary.transactionId}:${y.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:b,createdAt:c,participantId:s.id,sourceRefs:[l,{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:Go([...f?.sourceRefs??[],l,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??f?.kind??"pattern",state:m?.state??y.state,statement:m?.statement??y.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?Un(t,y.explanationId):f?.concreteBindings??[],supersededById:m?.supersededBy?h.get(m.supersededBy):f?.supersededById,updatedAt:m?.updatedAt??c};f?v.push(D):S.push(D),P.push({id:le(b,"imprint-live-evidence-link",`${e.summary.transactionId}:${y.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:b,createdAt:c,participantId:s.id,sourceRefs:[l],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(y=>y.sourceRefs.flatMap(l=>l.kind==="external"&&l.uri===Lt?[l.id]:[])));for(let y of t?.relations??[]){let l=Ho(y.type);if(!l)continue;let j=h.get(y.fromId),f=y.toStoreId?e.qualifiedExplanationMemoryIds?.[`${y.toStoreId}:${y.toId}`]:h.get(y.toId);!j||!f||u.has(y.id)||P.push({id:le(b,"imprint-relation",y.id,Date.parse(y.createdAt)),schemaVersion:1,projectId:b,createdAt:y.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:y.id,uri:Lt}],recordType:"relationship",relationshipType:l,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:f,...y.toStoreId?{storeId:y.toStoreId}:{}},reason:y.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let y=await this.store.commit({records:S,recordReplacements:v,events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});await this.refreshIndex(y)}catch(y){if(!(y instanceof Error)||!y.message.includes("Transaction already exists"))throw y}}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 un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(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"),p=new Map(c.flatMap(m=>{let E=mn(m);return E?[[E,m]]:[]})),b=new Map([...[...p].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!p.has(m.id)).map(m=>[m.id,le(a,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),S=[],v=[],P=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=p.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:fn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Un(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:Un(e,m.id),supersededById:m.supersededBy?b.get(m.supersededBy):void 0,updatedAt:m.updatedAt},k=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});k(E)!==k(D)&&v.push(D)}for(let[m,E]of p)P.has(m)||E.state==="retired"||v.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===Lt)?.id;return E?[[E,m]]:[]})),u=[],g=new Set;for(let m of e.relations){let E=Ho(m.type);if(!E||m.toStoreId)continue;let D=b.get(m.fromId),k=b.get(m.toId);if(!D||!k)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===k||(O&&g.add(m.id),u.push({id:le(a,"imprint-relation",`${m.id}:${E}:${D}:${k}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Lt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:k},reason:m.rationale||"The Imprint graph connected these explanations."}))}let y=new Set(e.relations.map(m=>m.id)),l=n?[...h].filter(([m])=>!y.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&&!v.length&&!u.length&&!l.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:v,events:[],relationships:u,artifacts:[],tombstones:l,projectionUpdates:[]},{transactionId:f,committedAt:j});return await this.refreshIndex(m),{status:"synced",relationships:u.length+l.length,explanations:S.length+v.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=mn(u);return g?[[g,u.id]]:[]})),c=new Set(e.map(u=>a.get(u)??u)),p=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]:[])),v=new Set(["expresses","operationalizes","excepts"]),P={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(K=>K.kind==="thread")?.id,D=m.sourceRefs.find(K=>K.kind==="message")?.id,k=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",O=p.get(m.participantId)??"unknown";return[{id:m.id,kind:k,summary:m.summary,createdAt:m.createdAt,participantKind:O,threadId:E,jobId:D}]}).sort((f,m)=>m.createdAt.localeCompare(f.createdAt)),y=r.bundle.relationships.flatMap(f=>{if(S.has(f.id))return[];if(!v.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,k=s.get(D);return k?[{id:f.id,type:f.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:k.id,statement:k.statement,rationale:f.reason}]:[]}),l=[...(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:[...y,...l],sourceThreadIds:j,needsGrounding:u.state==="testing"&&c.has(u.id)}}).sort((u,g)=>Number(g.needsGrounding)-Number(u.needsGrounding)||P[u.state]-P[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,p)=>c.createdAt.localeCompare(p.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(p=>p.targets.some(b=>b.entityType==="decision"&&b.entityId===a.id)).sort((p,b)=>b.createdAt.localeCompare(p.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(p=>p.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(k=>k.recordType==="participant"&&k.kind==="human"&&k.status==="active"),r=t.bundle.records.find(k=>k.recordType==="subject"&&k.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),p=Se(i),b=Se(i),S=Se(i),v=new Set(t.bundle.records.flatMap(k=>k.recordType==="model_entry"&&k.key===e.key?k.decisionIds:[])),P=t.bundle.records.filter(k=>k.recordType==="decision"&&k.state==="active"&&v.has(k.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."},y={...T,id:p,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},l={...T,id:b,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[p],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:[p],entryIds:[b],coverage:[{decisionId:p,status:"projected"}]},f={...T,id:Se(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},m=P.map(k=>({...T,id:Se(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:k.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=P.map(k=>({...T,id:Se(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:k.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[u,y,l,j],events:[g,...m],relationships:[f,...E],artifacts:[],tombstones:[],projectionUpdates:P.map(k=>({entityType:"decision",entityId:k.id,fromState:"active",state:"superseded"}))},{transactionId:Se(i),committedAt:s});return await this.refreshIndex(D),{decisionId:p,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),p=e.changes.map(T=>{let h=T.decisionIds?.filter(y=>e.decisionIds.includes(y)),u=h?.length?h:e.decisionIds,g=[...new Set(r.filter(y=>u.includes(y.id)).flatMap(y=>y.subjects.map(l=>l.subjectId)))];return{id:Se(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:u.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:T.path.map(String).join("."),subjectIds:g,decisionIds:u,value:T.value}}),b=new Set(p.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:p.map(T=>T.id),coverage:e.decisionIds.map(T=>e.coverage?.find(h=>h.decisionId===T)??{decisionId:T,status:b.has(T)?"projected":"unprojected"})},v=p.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."}))),P=await this.store.commit({records:[...p,S],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Se(s),committedAt:a});return await this.refreshIndex(P),{projectionId:c,entryIds:p.map(T=>T.id),headSequence:P.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await ln({...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=ni(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 Ut(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 Ft(o,e,t){let n=Pe(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function Qo(o){let e=Ut(o),t=Ut(e.authority),n=t.level,r=t.mode,i=Ft(n,"authority.level",["owner","delegate","contributor"]),s=Ft(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Pe(e.proposalId,"proposalId"),participantId:Pe(e.participantId,"participantId"),occurredAt:Pe(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:Pe(e.eventId,"eventId"),decisionId:Pe(e.decisionId,"decisionId"),kind:Ft(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Pe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Pe(e.eventId,"eventId"),reason:Pe(e.reason,"reason")};case"defer":{let c=Ut(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: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(p=>Pe(p,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(p=>Ft(p,"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: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:Ft(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let p=Ut(c);return{subjectId:Pe(p.subjectId,"subjectId"),role:Ft(p.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Pe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Xo(o){let e=Ut(o),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Pe(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:Ut(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 hd=1400,gd=6,yd=2,Yo=6;function si(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 ci(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!si(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(si):[],n=new Set([e.primary.storeId]);return{primary:e.primary,mounted:t.filter(r=>n.has(r.storeId)?!1:(n.add(r.storeId),!0))}}function ai(o){return[o.primary,...o.mounted]}function hn(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 di(o){return Math.ceil(JSON.stringify(o).length/4)}function Id(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 wd(o,e,t,n){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let r=o.map(({store:S,context:v})=>Id(v,S,S.storeId!==t)),i=hn(r.map(S=>S.acceptedTruth?.decisions??[])).slice(0,gd),s=new Set(i.map(S=>`${S.storeId}:${S.id}`)),a=r.flatMap(S=>S.acceptedTruth?.conflicts??[]).filter(S=>S.decisionIds.every(v=>s.has(`${S.storeId}:${v}`))),c=hn(r.map(S=>S.packets)).slice(0,yd),p=i.length<r.reduce((S,v)=>S+(v.acceptedTruth?.decisions.length??0),0)||c.length<r.reduce((S,v)=>S+v.packets.length,0),b={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:p||r.some(S=>S.acceptedTruth?.truncated)}}:{},packets:c,truncated:p||e.length>0||r.some(S=>S.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;di(b)>hd;){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=di(b),!(!b.packets.length&&!b.acceptedTruth?.decisions.length))return b}function li(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 vd(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 bd(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)),p=t.get(Te(a,i.to.memoryId));return!c||!p?[]:[{id:i.id,type:i.type,fromId:c,toId:p,rationale:i.rationale,storeId:n.storeId,readOnly:n.storeId!==e,from:{storeId:s,explanationId:c},to:{storeId:a,explanationId:p}}]}))}function xd(o){let e=new Set;return o.filter(t=>{let n=vd(t);return e.has(n)?!1:(e.add(n),!0)})}function Sd(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:l,context:j})=>li(j,l,l.storeId!==t)),c=hn(a.map(l=>l.explanations)),p=xd([...a.flatMap(l=>l.relations??[]),...r]),b=new Map([...c,...i].map(l=>[Te(l.storeId??"",l.id),l])),S=[],v=new Set,P=l=>{if(!l||S.length>=Yo)return;let j=Te(l.storeId??"",l.id);v.has(j)||(v.add(j),S.push(l))};for(let l of c.slice(0,Yo)){let j=Te(l.storeId??"",l.id),f=p.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&&(P(l),P(f))}c.forEach(P),i.forEach(P);let T=S,h=p.filter(l=>{let j=l.from,f=l.to;return!!(j&&f&&v.has(Te(j.storeId,j.explanationId))&&v.has(Te(f.storeId,f.explanationId)))}),u=new Set([...c.map(l=>Te(l.storeId??"",l.id)),...i.map(l=>Te(l.storeId??"",l.id))]).size,g=[...new Set(a.flatMap(l=>l.pendingGroundingExplanationIds??[]))],y=[...new Set(a.flatMap(l=>l.correctionExplanationIds??[]))];return{explanations:T,relations:h,truncated:T.length<u||e.length>0||a.some(l=>l.truncated),...a.find(l=>l.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(l=>l.retrievalIntent).retrievalIntent}:{},historicalCaveats:hn(a.map(l=>l.historicalCaveats??[])).slice(0,3),...g.length?{pendingGroundingExplanationIds:g}:{},...y.length?{correctionExplanationIds:y}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var zn=class{constructor(e,t,n=r=>({memory:new zt(r.projectRoot),imprint:new Tt(r.projectRoot,r.projectId)})){this.primary=e;this.createReader=n;this.readers=new Map;this.state={reads:0,storeReads:0,failedStoreReads:0,lastDurationMs:0};this.readers.set(e.storeId,t)}diagnostics(){return{...this.state}}normalized(e){return!e||e.primary.storeId!==this.primary.storeId||e.primary.projectId!==this.primary.projectId?{primary:this.primary,mounted:[]}:{primary:this.primary,mounted:e.mounted}}reader(e){let t=this.readers.get(e.storeId);if(t)return t;let n=this.createReader(e);return this.readers.set(e.storeId,n),n}async memoryContext(e,t,n){let r=performance.now(),i=ai(this.normalized(e)),s=await Promise.allSettled(i.map(async p=>{let b,S=await On(this.reader(p).memory,t,n,v=>{b=v});if(b)throw b;return{store:p,context:S}})),a=s.flatMap(p=>p.status==="fulfilled"&&p.value.context?[p.value]:[]),c=s.flatMap((p,b)=>p.status==="rejected"?[i[b].storeId]:[]);return this.record(i.length,c.length,r),wd(a,c,this.primary.storeId,i.length>1)}async imprintContext(e,t){let n=performance.now(),r=ai(this.normalized(e)),i=r.length>1,s=r.map(async _=>({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,p]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),b=c.flatMap(_=>_.status==="fulfilled"&&_.value.context?[_.value]:[]),S=c.flatMap((_,W)=>_.status==="rejected"?[r[W].storeId]:[]),v=p.flatMap(_=>_.status==="fulfilled"?[_.value]:[]),P=p.flatMap((_,W)=>_.status==="rejected"?[r[W].storeId]:[]),T=new Map(v.flatMap(({store:_,topology:W})=>W.explanations.map(G=>[Te(_.storeId,G.explanationId),G.memoryId]))),h=b.map(({store:_,context:W})=>({store:_,context:{...W,explanations:W.explanations.map(G=>({...G,memoryId:T.get(Te(_.storeId,G.id))}))}})),u=bd(v,this.primary.storeId),g=h.map(({store:_,context:W})=>li(W,_,_.storeId!==this.primary.storeId)),y=hn(g.map(_=>_.explanations)).slice(0,Yo),l=new Set(y.map(_=>Te(_.storeId??"",_.id))),j=new Set(g.flatMap(_=>_.explanations.map(W=>Te(W.storeId??"",W.id)))),f=new Map,m=(_,W)=>{if(j.has(Te(_,W)))return;let G=f.get(_)??new Set;G.add(W),f.set(_,G)};for(let _ of u){if(!_.from||!_.to)continue;let W=Te(_.from.storeId,_.from.explanationId),G=Te(_.to.storeId,_.to.explanationId);l.has(W)&&m(_.to.storeId,_.to.explanationId),l.has(G)&&m(_.from.storeId,_.from.explanationId)}let E=new Map(r.map(_=>[_.storeId,_])),D=[...f].map(async([_,W])=>{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,[...W]);return{storeId:_,explanations:X.map(oe=>({...oe,memoryId:T.get(Te(_,oe.id)),storeId:_,storeRoot:G.projectRoot,readOnly:_!==this.primary.storeId}))}}),k=await Promise.allSettled(D),O=k.flatMap(_=>_.status==="fulfilled"?_.value.explanations:[]),K=k.flatMap((_,W)=>_.status==="rejected"?[[...f.keys()][W]]:[]),H=[...new Set([...P,...K])];return this.record(r.length,new Set([...S,...H]).size,n),Sd(h,S,this.primary.storeId,i,u,O,H)}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 Mt=1,Zo="bridge";function pi(o){return`codex-session:${o}`}function Md(o,e){return`codex-${Td("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function ui(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 jd(o,e){let t=new Set,n=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(Rd(s)?Pd(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,p]of Object.entries(i))r(p,c,a+1)}};for(let i of o)r(i.toolInput);return[...t]}function Vn(o){return o?Math.ceil(o.length/4):0}function mi(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=rn(n),c=fi(r,i),p=[s,a,c].filter(Boolean).join(`
41
- `);return{additionalContext:p,contextBudget:{protocolEstimatedTokens:Vn(s),memoryEstimatedTokens:Vn(a),imprintEstimatedTokens:Vn(c),totalEstimatedTokens:Vn(p)}}}function fi(o,e){return o?an(o,{requestText:e}).split(`
1
+ import{mkdir as hp,unlink as gp,writeFile as yp}from"fs/promises";import{join as qs}from"path";import{execFileSync as Jl,spawn as Es}from"child_process";import{randomUUID as dt}from"crypto";import{mkdir as ql,readFile as Ll,readdir as Fl,realpath as Ul,stat as zl,unlink as Vl,writeFile as Po}from"fs/promises";import{createServer as Wl}from"http";import{tmpdir as Kl}from"os";import{basename as Mo,isAbsolute as Ns,join as Xe,relative as Gl,resolve as Hl}from"path";import{createHash as yd,randomUUID as Id}from"crypto";import{isAbsolute as wd,relative as vd}from"path";function Ct(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function on(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 $t(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
2
+ `)}async function $n(o,e,t,n){let r=$t(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(p=>p.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 rn(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(`
3
+ `)}import{randomUUID as it}from"crypto";var Cr={project:0,route:1,component:2,selector:2,file:3},$r={intention:0,principle:1,pattern:2};function Ot(o,e){let t=Cr[o.scope.kind]-Cr[e.scope.kind];return t!==0?t:$r[o.kind]-$r[e.kind]}function Or(o){return o==="expresses"||o==="excepts"}function ta(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=Ot(t,n);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function bt(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let r=ta(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 na}from"crypto";import{mkdir as oa,open as ra,readFile as Dr,readdir as ia,rename as sa,unlink as aa}from"fs/promises";import{dirname as da,join as Dt}from"path";function Je(o){return structuredClone(o)}function Nr(o){return na("sha256").update(JSON.stringify(o)).digest("hex")}async function xt(o,e){await oa(da(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)}
4
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await sa(t,o)}catch(r){throw await aa(t).catch(()=>{}),r}}function ca(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function la(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=Je(e):o.explanations.push(Je(e))}function No(o,e){let t=Je(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(Je(n.explanation))}else if(n.op==="replace_explanation")la(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(Je(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(Je(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,Je(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),p=!s&&t.concrete.some(b=>b.id===r.toId);if(Or(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(Ot(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 w=[r.toId],P=new Set;for(;w.length;){let T=w.pop();if(T===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);P.has(T)||(P.add(T),w.push(...S.get(T)??[]))}}}else if(!i||!a&&!p)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);t.relations.some(b=>b.id===r.id)||t.relations.push(Je(r))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(r=>r.id!==n.relationId));return t}function pa(o,e){let t=[],n=Je(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:Je(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:Je(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:Je(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:Je(i)})}n=No(n,[r])}return t}function Br(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 On=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Dt(e,".popmelt","imprint"),this.manifestPath=Dt(this.imprintDir,"manifest.json"),this.graphPath=Dt(this.imprintDir,"graph.json"),this.journalDir=Dt(this.imprintDir,"journal")}async readHead(){return(await this.readManifest()).head}async readManifest(){try{let e=JSON.parse(await Dr(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 ia(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=ca(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<n.length;a++){let c=JSON.parse(await Dr(Dt(this.journalDir,n[a]),"utf8")),{hash:p,...b}=c;if(c.sequence!==a+1||c.previousHash!==s||p!==Nr(b))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);r=No(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:bt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=bt(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 xt(this.graphPath,n),await xt(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=pa(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:Je(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:Nr(s)},c=No(n.graph,a.mutations);c.updatedAt=e.committedAt,c.head={sequence:r,hash:a.hash};let p=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await xt(Dt(this.journalDir,p),a);let b={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await xt(this.graphPath,c),await xt(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(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(Br));if(i.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(b=>Br(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 xt(this.graphPath,e.graph),await xt(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 ua=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),ma=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"]),fa=[/\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],ha=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Jo(o){return!!(o&&ha.test(o))}function ga(o){return o.scope.kind==="project"||Jo(`${o.statement} ${o.rationale}`)}function ya(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 Ia(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 rt(o){return new Set(Ia(o).split(" ").filter(e=>e.length>2&&!ma.has(e)).flatMap(wa))}function Jr(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 va(o){if(o)for(let e of fa){let t=e.exec(o);if(!t||t.index<=0)continue;let n=Jr(o.slice(0,t.index)),r=Jr(o.slice(t.index+t[0].length));if(n&&r)return{target:n,reference:r}}}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 Bo(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ft(o,e,t){return{id:it(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ve(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function qr(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Lr(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 Fr(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 sn(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 p=JSON.parse(c);if(!p||typeof p!="object"||Array.isArray(p)||!Object.prototype.hasOwnProperty.call(p,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let b=p;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(!ua.has(h))throw new Error("imprint no-op reason is invalid");if(h==="task_specific_detail"&&s.some(j=>{if(!j||typeof j!="object"||Array.isArray(j))return!1;let D=j;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(j=>typeof j=="string"&&!!j.trim()):[],g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(j=>typeof j=="string"&&!!j.trim()):[],y=new Set(e.context?.explanations.map(j=>j.id)??[]);if([...new Set([...u,...g])].some(j=>!y.has(j)))throw new Error("imprint use must cite only surfaced explanations");let M=[...new Set([...u,...e.applicationOccurred?[]:g])],f=e.applicationOccurred?g:[],m;if(f.length){m=f;let j=new Set(e.context?.pendingGroundingExplanationIds??[]),D=f.filter(k=>{let O=e.context?.explanations.find(K=>K.id===k);return y.has(k)&&O&&(O.state==="emerging"||O.state==="testing")&&!j.has(k)});if(D.length){let k=a.grounding,O=typeof k?.explanationId=="string"&&D.includes(k.explanationId)?k.explanationId:D[0],K=ve(k?.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:K||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(h==="duplicate"){let j=ve(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!j)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 k=e.context?.explanations.find(O=>O.id===j);if(!k)throw new Error("duplicate assessment must cite a surfaced explanation");if(Jo(e.requestText)&&!ga(k))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:h,duplicateOfExplanationId:j,scopeComparison:D,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:h,...M.length?{usedExplanationIds:M}:{},...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(l=>l.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,y={title:ve(g?.title,120),detail:ve(g?.detail,500)};if(!y.title||!y.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:h,summary:y},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(j=>typeof j=="string"&&!!j.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let y=new Map(e.context?.explanations.map(j=>[j.id,j])??[]);if(g.some(j=>!y.has(j)))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 l=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(j=>{let D=y.get(j);return D&&(D.state==="emerging"||D.state==="testing")&&!l.has(j)});if(!M.length){if(g.every(D=>y.get(D)?.state==="grounded"||l.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"&&M.includes(f.explanationId)?f.explanationId:M[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,p=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(p)))throw new Error("summary.kind is invalid");let b={kind:p,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()):[],w=[];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),y=ve(u.rationale);if(!g||!y)continue;w.push({op:"add",clientId:ve(u.clientId,100)||void 0,kind:u.kind,statement:g,rationale:y,scope:qr(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:qr(u.scope),reopenGrounding:u.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&w.push(g)}else if(u.op==="evidence"&&typeof u.explanationId=="string"&&["supports","challenges","excepts"].includes(String(u.stance))){let g=ve(u.summary);g&&w.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),y=Lr(u.from,u.fromId,u.fromStoreId),l=Lr(u.to,u.toId,u.toStoreId);if(!g||!y||!l)continue;w.push({op:"relation",type:u.type,from:y,to:l,rationale:g})}else if(u.op==="supersede"&&typeof u.explanationId=="string"&&typeof u.replacementId=="string"){let g=ve(u.reason);g&&w.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&&w.push({op:"bind_concrete",explanationId:u.explanationId,modelPath:g,rationale:ve(u.rationale)})}else u.op==="retire"&&typeof u.explanationId=="string"&&w.push({op:"retire",explanationId:u.explanationId,reason:ve(u.reason)})}let P=a.grounding,T=P&&typeof P.explanationId=="string"&&ve(P.question)?{explanationId:P.explanationId,question:ve(P.question,300)}:void 0;return{draft:{decision:"mutate",summary:b,appliedExplanationIds:S,mutations:w,grounding:T},visibleText:n}}catch(a){return{visibleText:n,error:a instanceof Error?a.message:String(a)}}}function an(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),r=new Set(o?.correctionExplanationIds??[]),i=Jo(e.requestText),s=o?.retrievalIntent,a=o?.historicalCaveats??[],c=t.find(w=>w.storeId&&!w.readOnly)?.storeId,p=(w,P)=>{let T=w[P];return T?`[${T.storeId}] ${T.explanationId}`:P==="from"?w.fromId:w.toId},b=!!o?.relations?.some(w=>w.from&&w.to&&w.from.storeId!==w.to.storeId),S=t.some(w=>w.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((w,P)=>[`${P+1}. [${w.state}; ${w.kind}] ${w.statement}`,` - Why: ${w.rationale}`,` - Scope: ${w.scope.kind} ${w.scope.values.join(", ")}`,` - Explanation: ${w.id}`,...w.storeId?[` - Store: ${w.storeId}${w.readOnly?" (read-only)":" (writable primary)"}`]:[],...n.has(w.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(w.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...w.concrete.map(T=>` - Concrete terminal: ${T.modelPath} = ${JSON.stringify(T.value)}`)].join(`
5
+ `)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(w=>`- ${w.storeId?`[owned by ${w.storeId}${w.readOnly?"; read-only":""}] `:""}${p(w,"from")} --${w.type}--> ${p(w,"to")}: ${w.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((w,P)=>[`${P+1}. [challenged; ${w.kind}] ${w.statement}`,` - Why it was previously proposed: ${w.rationale}`,` - Scope: ${w.scope.kind} ${w.scope.values.join(", ")}`,` - Historical explanation: ${w.id}`,...w.storeId?[` - Store: ${w.storeId}${w.readOnly?" (read-only)":" (writable primary)"}`]:[]].join(`
6
+ `)),"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(w=>w.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(`
7
+ `)}var St=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new On(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=rt(e.text??""),n=rt((e.subjectHints??[]).join(" ")),r=va(e.text),i=rt(r?.target??""),s=rt(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),c=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!a.size&&!c.size)return;let p=await this.contextualGraph(),b=p.explanations.filter(f=>f.state!=="retired"&&(f.state!=="challenged"||c.has(f.id))).map(f=>{let m=rt([f.statement,f.rationale].join(" ")),j=rt(f.scope.values.join(" ")),D=mt(m,t),k=mt(j,t),O=mt(j,n),K=mt(m,n),H=D+k*.2+O*.25+K*.75+(f.state==="grounded"?.08:0)+(a.has(f.id)?1:0)+(c.has(f.id)?1:0),E=a.has(f.id)||c.has(f.id)||D>=.12||k>=.5||O>=.2||K>=.2;return{item:f,score:H,relevant:E}}).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),w=f=>p.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let j=mt(rt(`${m.statement} ${m.rationale}`),f),D=mt(rt(m.scope.values.join(" ")),f);return{item:m,score:j+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,j)=>j.score-m.score||j.item.updatedAt.localeCompare(m.item.updatedAt)),P=[],T=f=>{P.length<S&&!P.some(m=>m.id===f.id)&&P.push(f)};if(r&&(w(i).slice(0,2).forEach(({item:f})=>T(f)),w(s).slice(0,2).forEach(({item:f})=>T(f))),b.forEach(({item:f})=>T(f)),!P.length)return;let h=new Set(P.map(f=>f.id)),u=new Set(p.relations.flatMap(f=>f.toStoreId?[]:h.has(f.fromId)?[f.toId]:h.has(f.toId)?[f.fromId]:[])),g=new Set(p.explanations.flatMap(f=>u.has(f.id)&&f.state!=="retired"&&f.state!=="challenged"?[f.id]:[])),y=p.explanations.filter(f=>g.has(f.id)&&!h.has(f.id)).sort((f,m)=>m.updatedAt.localeCompare(f.updatedAt)).slice(0,4),l=[...P,...y];for(let f of y)h.add(f.id);let M=r?p.explanations.filter(f=>f.state==="challenged").map(f=>{let m=rt(`${f.statement} ${f.rationale} ${f.scope.values.join(" ")}`),j=mt(m,i),D=mt(m,s);return{item:f,score:j+D,targetScore:j,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:l.map(f=>{let m=new Set(p.relations.filter(j=>!j.toStoreId&&j.toId===f.id&&j.type==="expresses").map(j=>j.fromId));return{id:f.id,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:f.scope,state:f.state,concrete:p.concrete.filter(j=>m.has(j.id)).map(j=>({id:j.id,modelPath:j.modelPath,value:j.value}))}}),truncated:b.length>P.length||y.length<g.size,...r?{retrievalIntent:r}:{},...M.length?{historicalCaveats:M}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:p.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])),p=new Map,b=new Map,S=[],w=new Set,P=new Set(t.pendingGroundingExplanationIds??[]),T=new Set(n.flatMap(x=>x.op==="revise"&&n.some(C=>C.op==="evidence"&&C.stance==="challenges"&&C.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),y=new Map((t.context?.explanations??[]).flatMap(x=>x.storeId?[[`${x.storeId}:${x.id}`,x]]:[])),l=x=>x.storeId??u,M=x=>{let C=l(x.from),q=l(x.to);return u&&C!==u||!u&&(x.from.storeId||x.to.storeId)||!g(x.from.explanationId)?!1:!q||q===u?g(x.to.explanationId):!!y.get(`${q}:${x.to.explanationId}`)?.memoryId},f=new Set;for(let x of n)x.op==="relation"&&(l(x.from)!==l(x.to)||x.from.explanationId!==x.to.explanationId)&&M(x)?(f.add(x.from.explanationId),l(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)&&Fr(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 C=!!(x.clientId&&f.has(x.clientId)),q=!!x.rootReason?.trim()||m;if(!C&&!q)continue;m&&(m=!1);let B=it();x.clientId&&p.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:Bo(x.scope),state:Q?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(B,he),w.add(B),S.push({op:"add_explanation",explanation:he})}let j=x=>p.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let C=j(x.explanationId),q=c.get(C);if(q?.state!=="grounded")continue;let B=it(),Q={id:B,kind:q.kind,statement:x.statement??q.statement,rationale:x.rationale??q.rationale,scope:x.scope?Bo(x.scope):q.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(B,Q),b.set(C,B),w.add(B),S.push({op:"add_explanation",explanation:Q});let he=Ot(q,Q);he!==0&&S.push({op:"add_relation",relation:{id:it(),type:"expresses",fromId:he>0?C:B,toId:he>0?B:C,rationale:x.rationale??e.summary.detail,createdAt:s}})}let D=x=>{let C=j(x);return b.get(C)??C};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let q=D(x.explanationId);if(!c.has(q))continue;let B=Fr(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:it(),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:it(),type:"expresses",fromId:Q.id,toId:q,rationale:x.rationale,createdAt:s}}),w.add(q);continue}if(x.op==="relation"){if(!M(x))continue;let q=l(x.from),B=l(x.to);if(u&&q!==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):y.get(`${B}:${he}`);if(!_e||!se||B===u&&Q===he)continue;if(x.type==="expresses"&&Ot(_e,se)<0){if(B!==u)continue;[Q,he]=[he,Q]}S.push({op:"add_relation",relation:{id:it(),type:x.type,fromId:Q,...B&&B!==u?{toStoreId:B}:{},toId:he,rationale:x.rationale,createdAt:s}}),w.add(Q),B===u&&w.add(he);continue}if(x.op==="supersede"){let q=D(x.explanationId),B=D(x.replacementId);if(!c.has(q)||!c.has(B)||q===B)continue;S.push({op:"add_evidence",explanationId:q,evidence:ft(t,"challenges",x.reason)}),S.push({op:"revise_explanation",explanationId:q,patch:{state:"challenged",supersededBy:B},updatedAt:s}),w.add(q),w.add(B);continue}let C=D(x.explanationId);if(c.has(C))if(w.add(C),x.op==="revise"){if(b.has(j(x.explanationId)))continue;let q=c.get(C);if(!q||q.state!=="emerging"&&q.state!=="testing")continue;let B={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Bo(x.scope)}:{},...x.reopenGrounding||T.has(x.explanationId)?{state:"testing"}:{}};S.push({op:"revise_explanation",explanationId:C,patch:B,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&T.has(x.explanationId))continue;S.push({op:"add_evidence",explanationId:C,evidence:ft(t,x.stance,x.summary)}),x.stance==="challenges"&&S.push({op:"revise_explanation",explanationId:C,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(S.push({op:"add_evidence",explanationId:C,evidence:ft(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),S.push({op:"revise_explanation",explanationId:C,patch:{state:"retired"},updatedAt:s}))}for(let x of i){let C=D(x),q=c.get(C);!q||q.state==="grounded"||q.state==="retired"||P.has(C)&&!w.has(C)||(w.has(C)||(w.add(C),S.push({op:"add_evidence",explanationId:C,evidence:{...ft(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),q.state==="emerging"&&S.push({op:"revise_explanation",explanationId:C,patch:{state:"testing"},updatedAt:s}))}let k=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 C=`${x.relation.type}:${x.relation.fromId}:${x.relation.toStoreId??""}:${x.relation.toId}`;return k.has(C)?!1:(k.add(C),!0)});if(!O.length)return;let K=it(),H=await this.store.commit({transactionId:K,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:O}),E=new Map(H.graph.explanations.map(x=>[x.id,x])),W=[...w].flatMap(x=>{let C=E.get(x);if(!C)return[];let q=!a.graph.explanations.some(Q=>Q.id===x),B=C.state==="challenged"||C.state==="retired";return[{explanationId:x,action:q?"added":B?"challenged":"revised",statement:C.statement,state:C.state}]}),G=i.map(D).find(x=>E.get(x)?.state==="testing"&&!P.has(x)),fe=e.grounding?D(e.grounding.explanationId):G,X=fe?E.get(fe):void 0,oe=X?.state==="testing"&&!P.has(X.id)?{explanationId:X.id,question:e.grounding?.question||ya(X),state:"testing"}:void 0;return{transactionId:K,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:W,...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(p=>p.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:{...ft(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:{...ft(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:it(),committedAt:t,source:s,summary:c,mutations:a}),"applied"}};import{mkdir as ni,readFile as un,writeFile as oi}from"fs/promises";import{join as qt}from"path";var ba=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function qo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dn(o){return new Set(qo(o).split(" ").filter(e=>e.length>2&&!ba.has(e)))}function Ur(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 xa(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 Sa(o,e){let t=new Map,n=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(qo).filter(Boolean),i=Dn([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 xa(s)){let p=qo(c.value);for(let w of r){let P=p===w?95:p.includes(w)||w.includes(p)?75:0;P>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:c.by,score:P})}let S=["/","#","[","]","="].some(w=>c.value.includes(w))?0:Math.round(Ur(Dn(p),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 Ta(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 ka(o){return Math.ceil(JSON.stringify(o).length/4)}function Lo(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(y=>y.entity.entityType==="proposal"&&y.entity.entityId===u.id&&y.toState==="deferred"&&y.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=Sa(t,e),c=[...a.values()].sort((u,g)=>g.score-u.score),p=Dn([e.action,e.text].filter(Boolean).join(" ")),b=i.flatMap(u=>{let g=u.subjects.map(f=>a.get(f.subjectId)).filter(f=>!!f),y=Math.max(0,...g.map(f=>f.score)),l=Math.round(Ur(Dn(u.claim),p)*35),M=y+l;return M>=50?[{proposal:u,proposalMatches:g,score:M}]:[]}).sort((u,g)=>g.score-u.score||u.proposal.id.localeCompare(g.proposal.id)),S=Math.max(1,e.maxPackets??3),w=Math.max(200,e.maxEstimatedTokens??1200),P=[],T=0;for(let u of b){if(P.length>=S)break;let g=u.proposal.sourceRefs.slice(0,4),y={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(M=>M.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:u.proposalMatches.map(({score:M,...f})=>f)},proposal:{id:u.proposal.id,claim:u.proposal.claim,state:u.proposal.state,proposedKind:u.proposal.proposedKind,subjectIds:u.proposal.subjects.map(M=>M.subjectId),origin:u.proposal.origin.mode},authority:"unaccepted",presentation:u.score>=100&&["constraint","rule"].includes(u.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ta(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]},l={...y,estimatedTokens:ka(y)};if(T+l.estimatedTokens>w)break;P.push(l),T+=l.estimatedTokens}let h=Math.max(0,b.length-P.length);return{packets:P,subjectMatches:c.map(({score:u,...g})=>g),completeness:{status:h>0?"truncated":"complete",consideredProposalCount:b.length,omittedPacketCount:h,maxEstimatedTokens:w,estimatedTokens:T},uncertainty:a.size===0?"subject_unresolved":b.length===0?"no_relevant_pending_proposal":void 0}}var Ra=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Fo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Nn(o){return new Set(Fo(o).split(" ").filter(e=>e.length>2&&!Ra.has(e)))}function zr(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Pa(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Fo).filter(Boolean),r=Nn([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(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of c){let b=Fo(p.value);for(let P of n){let T=b===P?95:b.includes(P)||P.includes(b)?75:0;T>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=90?"exact":"strong",matchedBy:p.by,score:T})}let w=["/","#","[","]","="].some(P=>p.value.includes(P))?0:Math.round(zr(Nn(b),r)*55);w>=30&&w>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:w>=45?"strong":"weak",matchedBy:"semantic",score:w})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function Ma(o){return Math.ceil(JSON.stringify(o).length/4)}function Nt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ja(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 Aa(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 Vr(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"),p=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"),w=o.records.filter(m=>m.recordType==="model_entry"),P=Pa(r,e),T=new Map(P.map(m=>[m.subjectId,m.score])),h=Nn([e.action,e.text].filter(Boolean).join(" ")),u=a.flatMap(m=>{let j=Math.max(0,...m.subjects.map(O=>T.get(O.subjectId)??0)),D=Math.round(zr(Nn(m.claim),h)*35),k=j+D;return k>=50?[{decision:m,score:k}]:[]}).sort((m,j)=>j.score-m.score||m.decision.id.localeCompare(j.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(!Nt(m,"excepts")&&!Nt(m,"contradicts"))continue;let j=s.find(k=>k.id===m.from.entityId),D=s.find(k=>k.id===m.to.entityId);!j||!D||!g.has(j.id)&&!g.has(D.id)||(g.size<n&&g.set(j.id,j),g.size<n&&g.set(D.id,D))}let y=[...g.values()],l=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&g.has(m.from.entityId)&&g.has(m.to.entityId),M=(m,j=!1)=>{let D=new Set(m.map(C=>C.id)),k=b.filter(C=>C.target.entityType==="decision"&&D.has(C.target.entityId)),O=new Set(o.relationships.filter(C=>Nt(C,"excepts")&&D.has(C.from.entityId)&&D.has(C.to.entityId)).flatMap(C=>[C.from.entityId,C.to.entityId])),H=o.relationships.filter(C=>Nt(C,"contradicts")&&D.has(C.from.entityId)&&D.has(C.to.entityId)).map(C=>({id:C.id,decisionIds:[C.from.entityId,C.to.entityId],unresolvedQuestion:C.reason,expansionRefs:[{kind:"record",id:C.id}]})),E=new Set(H.flatMap(C=>C.decisionIds)),W=S.filter(C=>C.sourceRefs.some(q=>q.kind==="record"&&D.has(q.id))||o.relationships.some(q=>q.relationshipType==="supports"&&q.from.entityType==="evidence"&&q.from.entityId===C.id&&q.to.entityType==="decision"&&D.has(q.to.entityId))),G=Math.max(0,u.length-m.length),fe=o.relationships.some(C=>Nt(C,"contradicts")&&l(C)&&(!D.has(C.from.entityId)||!D.has(C.to.entityId))),X=j||G>0||fe,oe=[];P.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:[]}),H.length&&oe.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:H.flatMap(C=>C.expansionRefs)}),W.some(C=>C.availability!=="available")&&oe.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:W.map(C=>({kind:"record",id:C.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:P.map(({score:C,...q})=>q),modelEntries:w.filter(C=>C.decisionIds.some(q=>D.has(q))).map(C=>({id:C.id,key:C.key,value:C.value,decisionIds:C.decisionIds})),decisions:m.map(C=>({id:C.id,kind:C.kind,claim:C.claim,subjectIds:C.subjects.map(q=>q.subjectId),authority:C.authority,effectiveState:E.has(C.id)?"conflicted":O.has(C.id)?"excepted":"active",freshness:k.filter(q=>q.target.entityId===C.id).map(q=>q.signalType),expansionRef:{kind:"record",id:C.id}})),conflicts:H,uncertainties:oe,implementation:m.map(C=>ja(C.id,c)),verification:m.map(C=>Aa(C.id,p,k)),evidence:W.map(C=>({evidenceId:C.id,summary:C.summary,availability:C.availability,sourceRefs:C.sourceRefs})),completeness:{status:X?"truncated":"complete",omittedDecisionCount:G,omittedEvidenceCount:0,conflictsComplete:!fe}};return x.budget.estimatedTokens=Ma(x),x},f=M(y);for(;f.budget.estimatedTokens>t&&y.length>0;){let m=y.pop(),j=o.relationships.filter(D=>Nt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);y=y.filter(D=>!j.includes(D.id)),f=M(y,!0)}return f}var Ea=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Bt(o){return Ea.test(o)}function _a(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 Uo(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Ee(o,e,t){Bt(t)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Ge(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Tt(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 Ca={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"])},$a=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function Oa(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),Ge(o,`${t}.createdAt`,e.createdAt),Tt(o,`${t}.authority`,e.authority);let n=Ca[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($a.has(i)&&(Tt(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&&Ge(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Da(o,e,t,n){Ee(o,`${t}.id`,e.id),Ee(o,`${t}.projectId`,e.projectId),Ee(o,`${t}.participantId`,e.participantId),Ge(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"&&(Tt(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"&&Uo(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."),Ge(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."),Ge(o,`${t}.concreteBindings[${i}].createdAt`,r.createdAt),Ge(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"&&(Ge(o,`${t}.appliedAt`,e.appliedAt),Tt(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&&Uo(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Uo(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Na(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."),Ge(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&&Tt(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),Ge(e,"manifest.createdAt",o.manifest.createdAt),Ge(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),Da(e,h,g,o.manifest.projectId)}),o.events.forEach((h,u)=>{let g=`events[${u}]`;n(h.id,g),Oa(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),Na(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),Ge(e,`${g}.deletedAt`,h.deletedAt),Tt(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.")},p=(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":p("participant",h.granteeId,`${g}.granteeId`),p("participant",h.grantedById,`${g}.grantedById`),h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`));break;case"observation":h.captureContext.subjectIds.forEach((y,l)=>p("subject",y,`${g}.captureContext.subjectIds[${l}]`)),h.captureContext.artifactIds.forEach((y,l)=>c(y,`${g}.captureContext.artifactIds[${l}]`));break;case"proposal":case"decision":h.subjects.forEach((y,l)=>p("subject",y.subjectId,`${g}.subjects[${l}].subjectId`));break;case"thread":h.messageArtifactIds.forEach((y,l)=>c(y,`${g}.messageArtifactIds[${l}]`)),h.resultRefs.forEach((y,l)=>s(y,`${g}.resultRefs[${l}]`));break;case"iteration":h.threadIds.forEach((y,l)=>p("thread",y,`${g}.threadIds[${l}]`)),h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"evidence":h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"advisory_explanation":h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`)),h.supersededById&&p("advisory_explanation",h.supersededById,`${g}.supersededById`);break;case"implementation_attempt":h.iterationIds.forEach((y,l)=>p("iteration",y,`${g}.iterationIds[${l}]`)),h.coverageClaims.forEach((y,l)=>p("decision",y.decisionId,`${g}.coverageClaims[${l}].decisionId`)),h.artifactIds.forEach((y,l)=>c(y,`${g}.artifactIds[${l}]`));break;case"eval_spec":h.replacesSpecId&&p("eval_spec",h.replacesSpecId,`${g}.replacesSpecId`),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`)),h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),(h.dependencies??[]).forEach((y,l)=>{y.kind==="subject"&&y.subjectId&&p("subject",y.subjectId,`${g}.dependencies[${l}].subjectId`)}),(h.scenarios??[]).forEach((y,l)=>{y.subjectIds?.forEach((M,f)=>p("subject",M,`${g}.scenarios[${l}].subjectIds[${f}]`))}),h.targets.forEach((y,l)=>p(y.entityType,y.entityId,`${g}.targets[${l}]`));break;case"verification_attempt":h.evalSpecId&&p("eval_spec",h.evalSpecId,`${g}.evalSpecId`),h.targets.forEach((y,l)=>p(y.entityType,y.entityId,`${g}.targets[${l}]`)),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`));break;case"model_entry":h.subjectIds.forEach((y,l)=>p("subject",y,`${g}.subjectIds[${l}]`)),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`));break;case"model_projection":Tt(e,`${g}.authority`,h.authority,!0),p("participant",h.appliedById,`${g}.appliedById`),h.decisionIds.forEach((y,l)=>p("decision",y,`${g}.decisionIds[${l}]`)),h.entryIds.forEach((y,l)=>p("model_entry",y,`${g}.entryIds[${l}]`)),h.coverage.forEach((y,l)=>p("decision",y.decisionId,`${g}.coverage[${l}].decisionId`));break;case"freshness_signal":s(h.target,`${g}.target`),h.evidenceIds.forEach((y,l)=>p("evidence",y,`${g}.evidenceIds[${l}]`));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])),w=new Map;o.events.forEach((h,u)=>{let g=`${h.entity.entityType}:${h.entity.entityId}:${h.fromState??"null"}`,y=w.get(g)??new Set;y.add(h.toState),w.set(g,y),y.size>1&&te(e,`events[${u}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let P=new Map(o.records.flatMap(h=>h.recordType==="authority_grant"?[[h.id,h]]:[])),T=(h,u,g,y,l)=>{if(h.level!=="delegate"||!h.grantId)return;let M=P.get(h.grantId);if(!M){te(e,l,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==u||M.level!=="delegate")&&te(e,l,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let f=Date.parse(g);(f<Date.parse(M.startsAt)||M.endsAt&&f>Date.parse(M.endsAt)||M.revokedAt&&f>=Date.parse(M.revokedAt))&&te(e,l,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&y.length&&!y.every(m=>M.subjectIds.includes(m))&&te(e,l,"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}`),y=g&&"subjects"in g?g.subjects.map(l=>l.subjectId):[];T(h.authority,h.participantId,h.createdAt,y,`events[${u}].authority`)}),o.relationships.forEach((h,u)=>{if(!h.authority)return;let g=[h.from,h.to].flatMap(y=>{let l=S.get(`${y.entityType}:${y.entityId}`);return l&&"subjects"in l?l.subjects.map(M=>M.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(y=>y.relationshipType==="supersedes"&&y.to.entityType==="decision"&&y.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(y=>y.entity.entityType==="decision"&&y.entity.entityId===h.id&&y.toState==="revoked"&&!!y.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 _a(e)}function dn(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 Wr(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 Ba(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Bn(o,e){let 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."}),Bt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Ba(e))Bt(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={...dn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Wr(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={...dn(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={...dn(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Wr(o,i,e,a.id,e.decisionId),p={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:[p]},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={...dn(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={...dn(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 Ja}from"crypto";import{readFile as qa,readdir as La,realpath as Fa}from"fs/promises";import{join as cn,relative as Ua}from"path";var za=["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 Jt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ue(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Kr(...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=Ja("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 zo(o,e){try{return JSON.parse(await qa(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function Va(o){let e=Jt(o);if(!e)return 0;let t=0,n=r=>{let i=Jt(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 Wa(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function ln(o){let e=[],t=await Fa(o.projectRoot).catch(()=>o.projectRoot),n=cn(t,".popmelt"),r=await zo(cn(n,"threads.json"),e),i=await zo(cn(n,"model.json"),e),s=Jt(r),a=Jt(s?.threads)??{},c=Object.entries(a).map(([q,B])=>({key:q,value:Jt(B)})).filter(q=>!!q.value),p=cn(n,"decisions"),b=await La(p).catch(()=>[]),S=[];for(let q of b.filter(B=>B.endsWith(".json")).sort()){let B=Jt(await zo(cn(p,q),e));B&&S.push({file:q,value:B})}let w=c.flatMap(({value:q})=>[q.createdAt,q.updatedAt]).filter(q=>typeof q=="number"&&Number.isFinite(q)),P=w.length?Math.min(...w):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,P),u=le(T,"participant","legacy-owner",P),g=le(T,"participant","legacy-agent",P),y=le(T,"subject","project",P),l=Ue(Math.max(P,...w)),M=[],f=[],m=new Map,j=new Map,D=new Map(S.map(q=>[q.value.id??q.file.replace(/^d-|\.json$/g,""),q.value])),k=new Map,O=(q,B,Q,he,_e)=>{let se=m.get(Q);if(se)return se;let De=le(T,"artifact",q,he);return f.push({id:De,kind:B,mediaType:_e,location:Q,availability:"available"}),m.set(Q,De),De};for(let{file:q,value:B}of S){let Q=B.id??q.replace(/^d-|\.json$/g,""),he=B.createdAt??P,_e=[O(`${Q}:envelope`,"other",`.popmelt/decisions/${q}`,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,De]of(B.pastedImagePaths??[]).entries())_e.push(O(`${Q}:image:${se}`,"image",De,he));k.set(Q,_e)}let K=(q,B,Q)=>({id:q,schemaVersion:1,projectId:h,createdAt:l,participantId:B,sourceRefs:Q}),H=(q,B)=>{M.push(B);let Q=j.get(q)??[];Q.push(B.id),j.set(q,Q)},E=[{...K(u,u,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...K(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];M.push(...E),M.push({...K(y,u,[]),recordType:"subject",subjectType:"project",label:Ua(process.cwd(),t)||t,aliases:[],locators:[{id:le(T,"locator",t,P),kind:"project_root",value:t,status:"current",validFrom:Ue(P),sourceRefs:[]}]});let W=new Map,G=(q,B)=>{let Q=W.get(q);if(Q)return Q;let he=le(T,"subject",q,B),_e={...K(he,u,[{kind:"external",id:q}]),createdAt:Ue(B),recordType:"subject",subjectType:"element",label:q,aliases:[],locators:[{id:le(T,"locator",q,B),kind:"dom_selector",value:q,status:"current",validFrom:Ue(B),sourceRefs:[{kind:"external",id:q}]}]};return M.push(_e),W.set(q,he),he};for(let{key:q,value:B}of c){let Q=B.id??q,he=B.createdAt??P,_e=le(T,"thread",Q,he),se={kind:"thread",id:Q},De=[],gt=[],en=Array.isArray(B.messages)?B.messages:[],Me,nt,yt=0;en.forEach((Te,ct)=>{let Ne=Te.timestamp??he,ot=le(T,"artifact",`${Q}:message:${ct}`,Ne);if(De.push(ot),f.push({id:ot,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${Q}/messages/${ct}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${Q}/messages/${ct}`,ot),Te.screenshotPath&&O(`${Q}:message:${ct}:screenshot`,"screenshot",Te.screenshotPath,Ne),Te.role==="human"){Me=Te;let $e=Te.feedbackSummary??Te.replyToQuestion;if($e?.trim()){let Le=le(T,"observation",`${Q}:${ct}`,Ne),ut=B.elementIdentifiers??[],Et={...K(Le,u,[se,{kind:"message",id:ot}]),createdAt:Ue(Ne),recordType:"observation",state:"open",statement:$e,captureContext:{subjectIds:ut.map(wt=>G(wt,he)),artifactIds:[ot]},resolvedByIds:[]};H(Q,Et),nt=Le,gt.push({entityType:"observation",entityId:Le})}return}if(Te.role!=="assistant")return;let lt=Te.jobId??`${Q}:${ct}`,pt=le(T,"iteration",lt,Ne),It=D.get(lt),Eo=Te.cancelled?"cancelled":Te.error?"failed":Te.question?"question_asked":(Te.resolutions?.length??0)>0?"completed":"no_change",_o={...K(pt,g,[se,{kind:"message",id:ot},...(k.get(lt)??[]).map($e=>({kind:"artifact",id:$e}))]),createdAt:Ue(Ne),recordType:"iteration",threadIds:[_e],startedAt:Ue(Me?.timestamp,Ne),completedAt:Ue(Ne),requestSummary:Kr(Me?.feedbackSummary,Me?.replyToQuestion)??"[legacy request unavailable]",responseSummary:Te.question??Te.error??Te.responseText?.slice(0,1e3),outcome:Eo,execution:{provider:Te.provider??It?.provider,model:Te.model??It?.model,sessionId:Te.sessionId??It?.sessionId},artifactIds:[ot,...k.get(lt)??[]]};H(Q,_o),gt.push({entityType:"iteration",entityId:pt});let tn=Te.resolutions??It?.resolutions??[];for(let[$e,Le]of tn.entries()){if(Le.status!=="resolved"||!Le.summary?.trim())continue;let ut=B.elementIdentifiers??[],Et=(ut.length?ut:[t]).map(_n=>({subjectId:_n===t?y:G(_n,he),role:"governed"})),wt=le(T,"proposal",`${lt}:${Le.annotationId??"resolution"}:${$e}`,Ne),Co={...K(wt,g,[se,{kind:"iteration",id:pt}]),createdAt:Ue(Ne),recordType:"proposal",state:"pending",claim:Le.summary,subjects:Et,subjectSemantics:Et.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Kr(Me?.feedbackSummary,Me?.replyToQuestion,Le.summary),iterationId:pt,inferredById:g}};H(Q,Co),gt.push({entityType:"proposal",entityId:wt}),e.push({severity:"warning",code:"acceptance_unresolved",source:Q,message:`Proposal ${wt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(tn.some($e=>$e.status==="resolved")||It?.gitDiff){let $e=le(T,"implementation",lt,Ne),Le={...K($e,g,[se,{kind:"iteration",id:pt}]),createdAt:Ue(Ne),recordType:"implementation_attempt",state:"completed",iterationIds:[pt],coverageClaims:[],summary:tn.map(ut=>ut.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};H(Q,Le),gt.push({entityType:"implementation_attempt",entityId:$e}),yt+=1}nt&&(nt=void 0)});let At=en.at(-1),Ao={...K(_e,u,[se]),createdAt:Ue(he),recordType:"thread",state:At?.question?"open":"resolved",messageArtifactIds:De,outcome:At?.question?"question_unresolved":yt?"implementation_only":"no_outcome",resultRefs:gt};M.push(Ao),j.set(Q,[_e,...j.get(Q)??[]])}let fe=Va(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:Ue(P),updatedAt:l,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:f,tombstones:[]},oe=kt(X),C=(o.proofCaseIds??za).map(q=>({legacyId:q,threadFound:c.some(({key:B,value:Q})=>(Q.id??B)===q),decisionEnvelopeFound:D.has(q),recordIds:j.get(q)??[]}));return{bundle:X,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((q,B)=>q+(B.value.messages?.length??0),0),decisionEnvelopes:S.length,modelEntries:fe,artifactsReferenced:f.length},imported:Wa(M),unresolvedAcceptance:e.filter(q=>q.code==="acceptance_unresolved").length,deferredModelEntries:fe,proofCases:C,issues:e,schemaIssues:oe.issues}}}import{createHash as Ka}from"crypto";import{mkdir as Gr,open as Vo,readFile as Wo,readdir as Ga,rename as Ha,unlink as Ko}from"fs/promises";import{join as st}from"path";var Qa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Jn(o){return Ka("sha256").update(JSON.stringify(o)).digest("hex")}function Hr(o){return Jn(o)}function Qr(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 Xa(o,e,t){return Qr(structuredClone(o),e,t)}async function Rt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Vo(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
8
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await Ha(t,o)}catch(r){throw await Ko(t).catch(()=>{}),r}}async function pn(o){return JSON.parse(await Wo(o,"utf8"))}var qn=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 readHead(){let e=await pn(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 Gr(this.journalDir,{recursive:!0});try{throw await Wo(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 Wo(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=Jn(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 Rt(this.checkpointPath,r),await Rt(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 Rt(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=Jn(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 Rt(st(this.memoryDir,n),r),e.manifest.checkpoint={file:n,sequence:r.sequence,hash:t},await Rt(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(!Bt(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:Hr(i)},a=Xa(n.bundle,e,t.committedAt),c=kt(a);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let p=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await Rt(st(this.journalDir,p),s),n.manifest.head={sequence:r,hash:s.hash},n.manifest.updatedAt=t.committedAt,await Rt(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({...Qa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await pn(this.manifestPath),t=await pn(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!==Jn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await Ga(this.journalDir),r=n.filter(w=>w.endsWith(".tmp")),s=n.filter(w=>/^\d{12}-[0-9a-f-]+\.json$/i.test(w)).sort().filter(w=>Number(w.slice(0,12))>t.sequence),a=structuredClone(t.bundle),c=t.sequence,p=t.journalHash??null,b=new Set;for(let w of s){let P=await pn(st(this.journalDir,w)),{hash:T,...h}=P;if(T!==Hr(h))throw new Error(`Journal hash mismatch: ${w}`);if(P.sequence!==c+1)throw new Error(`Journal sequence gap at ${w}`);if(P.previousHash!==p)throw new Error(`Journal chain mismatch at ${w}`);if(P.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${w}`);if(b.has(P.transactionId))throw new Error(`Duplicate transaction ID: ${P.transactionId}`);Qr(a,P.mutation,P.committedAt),c=P.sequence,p=P.hash,b.add(P.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==p)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:p}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Gr(this.memoryDir,{recursive:!0});let t;try{t=await Vo(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let r=await pn(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 Ko(this.lockPath),t=await Vo(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Ko(this.lockPath).catch(()=>{})}}};import{randomBytes as Ya}from"crypto";function xe(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=Ya(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 Za=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Xr(o,e){let t=o.records.find(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),n=o.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.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=Za(),p=c.records,b=o.records.find(l=>l.recordType==="thread"&&l.sourceRefs.some(M=>M.kind==="thread"&&M.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(l=>l.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(b));let S=[];for(let l of[...new Set(e.subjectHints.filter(Boolean))]){let M=o.records.find(f=>f.recordType==="subject"&&f.locators.some(m=>m.value===l&&m.status==="current"));M||(M={id:le(r,"live-subject",l,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"element",label:l,aliases:[],locators:[{id:le(r,"live-locator",l,e.createdAt),kind:"dom_selector",value:l,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:l}]}]},p.push(M)),S.push(M)}for(let l of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=o.records.find(f=>f.recordType==="subject"&&f.locators.some(m=>m.kind==="source_file"&&m.value===l&&m.status==="current"));M||(M={id:le(r,"live-file-subject",l,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"file",label:l,aliases:[],locators:[{id:le(r,"live-file-locator",l,e.createdAt),kind:"source_file",value:l,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:l}]}]},p.push(M)),S.push(M)}let w=(e.semanticCandidates??[]).filter(l=>l.claim.trim()),P;if(w.length>0){P=le(r,"live-observation",i,e.createdAt);let l={id:P,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:w.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:S.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};p.push(l)}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(l=>({kind:"external",id:l,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(l=>({kind:"external",id:l,uri:"popmelt:imprint-evidence"})),...P?[{kind:"record",id:P}]:[]],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}:{}};p.push(h);let u=[],g=e.resolutions.filter(l=>l.status==="resolved"&&l.summary.trim()),y=S.length>0?S:o.records.filter(l=>l.recordType==="subject"&&l.subjectType==="project").slice(0,1);if(w.length>0&&y.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[l,M]of w.entries()){let f=le(r,"live-proposal",`${i}:${l}`,e.completedAt),m=y.map(D=>({subjectId:D.id,role:"governed"})),j={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: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:T,inferredById:n.id}};p.push(j),u.push(f)}if(g.length>0){let l=new Set(e.governingDecisionIds??[]),M=o.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&l.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:M.map(m=>({decisionId:m.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${g.map(j=>j.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:T}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};p.push(f)}return{mutation:c,iterationId:T,proposalIds:u,observationId:P}}import{createHash as ed}from"crypto";import{mkdir as td,open as nd,readFile as od,rename as rd,unlink as id}from"fs/promises";import{join as Yr}from"path";function Zr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ei(o){return ed("sha256").update(JSON.stringify(o)).digest("hex")}async function sd(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await nd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
9
+ `,"utf8"),await n.sync()}finally{await n.close()}try{await rd(t,o)}catch(r){throw await id(t).catch(()=>{}),r}}function ad(o,e,t=new Date().toISOString()){let n={},r={},i={},s=(c,p,b)=>{let S=c[p]??=[];S.includes(b)||S.push(b)};for(let c of o.records)if(c.recordType==="subject"){let p=c;for(let b of[p.label,...p.aliases,...p.locators.filter(S=>S.status==="current").map(S=>S.value)]){let S=Zr(b);S&&s(n,S,p.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let p of c.subjects)s(r,p.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let p of c.subjects)s(i,p.subjectId,c.id);let a={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:ei(a)}}function ti(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[Zr(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 Ln=class{constructor(e){this.indexDir=Yr(e,".popmelt","memory","indexes"),this.indexPath=Yr(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await od(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===t.sequence&&r.journalHead.hash===t.hash&&i===ei(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let n=ad(e,t);return await td(this.indexDir,{recursive:!0}),await sd(this.indexPath,n),n}};var fn="popmelt:imprint",ri="popmelt:imprint-evidence",Lt="popmelt:imprint-relation";function mn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===fn)?.id}function Go(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 Fn(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 Ho(o){if(o==="expresses")return"expresses";if(o==="excepts")return"excepts"}var zt=class{constructor(e){this.projectRoot=e;this.store=new qn(e),this.indexStore=new Ln(e),this.manifestPath=qt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await un(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 ln({...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 ln({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=qt(this.projectRoot,".popmelt","memory","migrations"),t=qt(e,"imprint-advisories-v2.json");try{let l=JSON.parse(await un(t,"utf8"));return{migrated:!1,explanations:l.explanations??0,evidence:l.evidence??0}}catch{}let n;try{n=bt(JSON.parse(await un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await ni(e,{recursive:!0}),await oi(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),a=r.bundle.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.status==="active")??i,c=r.bundle.records.find(l=>l.recordType==="subject"&&l.subjectType==="project");if(!a||!c)return{migrated:!1,explanations:0,evidence:0};let p=r.bundle.manifest.projectId,b=new Set(r.bundle.records.map(l=>l.id)),S=new Set(r.bundle.relationships.flatMap(l=>l.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Lt?[M.id]:[]))),w=new Map,P=r.bundle.records.filter(l=>l.recordType==="advisory_explanation");for(let l of n.explanations){let M=P.find(f=>mn(f)===l.id);w.set(l.id,M?.id??le(p,"imprint-explanation",l.id,Date.parse(l.createdAt)))}let T=[],h=[],u=[],g=0;for(let l of n.explanations){let M=w.get(l.id),f=P.find(k=>k.id===M),m=[],j=l.evidence.length?l.evidence:[{id:`fallback:${l.id}`,kind:"observation",stance:"supports",summary:l.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:l.createdAt}];for(let k of j){let O=le(p,"imprint-evidence-record",k.id,Date.parse(k.createdAt));m.push(O),!b.has(O)&&(T.push({id:O,schemaVersion:1,projectId:p,createdAt:k.createdAt,participantId:a.id,sourceRefs:Go([{kind:"external",id:k.id,uri:ri},{kind:"external",id:l.id,uri:fn},{kind:"thread",id:k.threadId},{kind:"message",id:k.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(k.kind)?"user_feedback":"judgment",summary:k.summary,availability:"available",artifactIds:[]}),u.push({id:le(p,"imprint-evidence-link",`${l.id}:${k.id}`,Date.parse(k.createdAt)),schemaVersion:1,projectId:p,createdAt:k.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:k.id,uri:ri}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"evidence",entityId:O},reason:"This advisory explanation was derived from collaboration evidence."}),g+=1)}let D={id:M,schemaVersion:1,projectId:p,createdAt:f?.createdAt??l.createdAt,participantId:f?.participantId??a.id,sourceRefs:Go([...f?.sourceRefs??[],{kind:"external",id:l.id,uri:fn}]),recordType:"advisory_explanation",kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),subjectIds:[c.id],evidenceIds:[...new Set([...f?.evidenceIds??[],...m])],concreteBindings:Fn(n,l.id),supersededById:l.supersededBy?w.get(l.supersededBy):void 0,updatedAt:l.updatedAt};f?h.push(D):T.push(D)}for(let l of n.relations){let M=Ho(l.type);if(!M||l.toStoreId)continue;let f=w.get(l.fromId),m=w.get(l.toId);!f||!m||S.has(l.id)||u.push({id:le(p,"imprint-relation",l.id,Date.parse(l.createdAt)),schemaVersion:1,projectId:p,createdAt:l.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:l.id,uri:Lt}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:f},to:{entityType:"advisory_explanation",entityId:m},reason:l.rationale||"The Imprint graph connected these explanations."})}let y=new Date().toISOString();if(T.length||h.length||u.length)try{let l=await this.store.commit({records:T,recordReplacements:h,events:[],relationships:u,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(p,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:y});await this.refreshIndex(l)}catch(l){if(!(l instanceof Error)||!l.message.includes("Transaction already exists"))throw l}return await ni(e,{recursive:!0}),await oi(t,JSON.stringify({version:2,migratedAt:y,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:Lo(n.bundle,r)}}async contextualize(e,t={}){let n=await this.loadSource(t),r=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:Vr(n.bundle,r),reviewSelection:Lo(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:mn(t)??t.id}]:[]),relations:e.bundle.relationships.flatMap(t=>t.relationshipType!=="expresses"&&t.relationshipType!=="excepts"||t.from.entityType!=="advisory_explanation"||t.to.entityType!=="advisory_explanation"?[]:[{id:t.id,type:t.relationshipType,from:{memoryId:t.from.entityId,...t.from.storeId?{storeId:t.from.storeId}:{}},to:{memoryId:t.to.entityId,...t.to.storeId?{storeId:t.to.storeId}:{}},rationale:t.reason}])}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:Bn(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 ln({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=Bn(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(w=>w.recordType==="proposal"&&w.id===e.proposalId),r=t.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.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:xe(i),decisionId:xe(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:xe(i),replacementProposalId:xe(i),acceptanceEventId:xe(i),decisionId:xe(i),relationshipId:xe(i),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:xe(i),reason:e.reason}:{...a,action:"defer",eventId:xe(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(w=>w.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=Bn(t.bundle,c);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(w=>w.message).join(" ")};let b=await this.store.commitReviewPlan(p.plan,{transactionId:xe(i),committedAt:s});await this.refreshIndex(b);let S=p.plan.resultRefs.find(w=>w.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=Xr(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=bt(JSON.parse(await un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),r=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active"),i=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="ai"&&y.status==="active"),s=e.action?r:i??r,a=n.bundle.records.find(y=>y.recordType==="subject"&&y.subjectType==="project");if(!s||!a)return;let c=e.occurredAt??new Date().toISOString(),p=Date.parse(c),b=n.bundle.manifest.projectId,S=[],w=[],P=[],T=n.bundle.records.filter(y=>y.recordType==="advisory_explanation"),h=new Map(T.flatMap(y=>{let l=mn(y);return l?[[l,y.id]]:[]}));for(let y of e.summary.changes)if(!h.has(y.explanationId)){let l=t?.explanations.find(M=>M.id===y.explanationId);h.set(y.explanationId,le(b,"imprint-explanation",y.explanationId,Date.parse(l?.createdAt??c)))}for(let y of e.summary.changes){let l={kind:"external",id:y.explanationId,uri:fn},M=h.get(y.explanationId),f=T.find(k=>k.id===M),m=t?.explanations.find(k=>k.id===y.explanationId),j={id:le(b,"imprint-live-evidence",`${e.summary.transactionId}:${y.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:b,createdAt:c,participantId:s.id,sourceRefs:[l,{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(j);let D={id:M,schemaVersion:1,projectId:b,createdAt:f?.createdAt??m?.createdAt??c,participantId:f?.participantId??s.id,sourceRefs:Go([...f?.sourceRefs??[],l,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??f?.kind??"pattern",state:m?.state??y.state,statement:m?.statement??y.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??[],j.id])],concreteBindings:m?Fn(t,y.explanationId):f?.concreteBindings??[],supersededById:m?.supersededBy?h.get(m.supersededBy):f?.supersededById,updatedAt:m?.updatedAt??c};f?w.push(D):S.push(D),P.push({id:le(b,"imprint-live-evidence-link",`${e.summary.transactionId}:${y.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:b,createdAt:c,participantId:s.id,sourceRefs:[l],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.id},to:{entityType:"evidence",entityId:j.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let u=new Set(n.bundle.relationships.flatMap(y=>y.sourceRefs.flatMap(l=>l.kind==="external"&&l.uri===Lt?[l.id]:[])));for(let y of t?.relations??[]){let l=Ho(y.type);if(!l)continue;let M=h.get(y.fromId),f=y.toStoreId?e.qualifiedExplanationMemoryIds?.[`${y.toStoreId}:${y.toId}`]:h.get(y.toId);!M||!f||u.has(y.id)||P.push({id:le(b,"imprint-relation",y.id,Date.parse(y.createdAt)),schemaVersion:1,projectId:b,createdAt:y.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:y.id,uri:Lt}],recordType:"relationship",relationshipType:l,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:f,...y.toStoreId?{storeId:y.toStoreId}:{}},reason:y.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let y=await this.store.commit({records:S,recordReplacements:w,events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});await this.refreshIndex(y)}catch(y){if(!(y instanceof Error)||!y.message.includes("Transaction already exists"))throw y}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=bt(JSON.parse(await un(qt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(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"),p=new Map(c.flatMap(m=>{let j=mn(m);return j?[[j,m]]:[]})),b=new Map([...[...p].map(([m,j])=>[m,j.id]),...e.explanations.filter(m=>!p.has(m.id)).map(m=>[m.id,le(a,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),S=[],w=[],P=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let j=p.get(m.id);if(!j){S.push({id:b.get(m.id),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:fn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Fn(e,m.id),supersededById:m.supersededBy?b.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(j),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:Fn(e,m.id),supersededById:m.supersededBy?b.get(m.supersededBy):void 0,updatedAt:m.updatedAt},k=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});k(j)!==k(D)&&w.push(D)}for(let[m,j]of p)P.has(m)||j.state==="retired"||w.push({...structuredClone(j),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 j=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Lt)?.id;return j?[[j,m]]:[]})),u=[],g=new Set;for(let m of e.relations){let j=Ho(m.type);if(!j||m.toStoreId)continue;let D=b.get(m.fromId),k=b.get(m.toId);if(!D||!k)continue;let O=h.get(m.id);O&&O.relationshipType===j&&O.from.entityType==="advisory_explanation"&&O.from.entityId===D&&O.to.entityType==="advisory_explanation"&&O.to.entityId===k||(O&&g.add(m.id),u.push({id:le(a,"imprint-relation",`${m.id}:${j}:${D}:${k}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Lt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:k},reason:m.rationale||"The Imprint graph connected these explanations."}))}let y=new Set(e.relations.map(m=>m.id)),l=n?[...h].filter(([m])=>!y.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&&!w.length&&!u.length&&!l.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let M=e.updatedAt,f=le(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:S,recordReplacements:w,events:[],relationships:u,artifacts:[],tombstones:l,projectionUpdates:[]},{transactionId:f,committedAt:M});return await this.refreshIndex(m),{status:"synced",relationships:u.length+l.length,explanations:S.length+w.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=mn(u);return g?[[g,u.id]]:[]})),c=new Set(e.map(u=>a.get(u)??u)),p=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]:[])),w=new Set(["expresses","operationalizes","excepts"]),P={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 j=m.sourceRefs.find(K=>K.kind==="thread")?.id,D=m.sourceRefs.find(K=>K.kind==="message")?.id,k=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",O=p.get(m.participantId)??"unknown";return[{id:m.id,kind:k,summary:m.summary,createdAt:m.createdAt,participantKind:O,threadId:j,jobId:D}]}).sort((f,m)=>m.createdAt.localeCompare(f.createdAt)),y=r.bundle.relationships.flatMap(f=>{if(S.has(f.id))return[];if(!w.has(f.relationshipType))return[];let m=f.from.entityType==="advisory_explanation"&&f.from.entityId===u.id&&f.to.entityType==="advisory_explanation",j=f.to.entityType==="advisory_explanation"&&f.to.entityId===u.id&&f.from.entityType==="advisory_explanation";if(!m&&!j)return[];let D=m?f.to.entityId:f.from.entityId,k=s.get(D);return k?[{id:f.id,type:f.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:k.id,statement:k.statement,rationale:f.reason}]:[]}),l=[...(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."}]:[])],M=[...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:[...y,...l],sourceThreadIds:M,needsGrounding:u.state==="testing"&&c.has(u.id)}}).sort((u,g)=>Number(g.needsGrounding)-Number(u.needsGrounding)||P[u.state]-P[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,p)=>c.createdAt.localeCompare(p.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(p=>p.targets.some(b=>b.entityType==="decision"&&b.entityId===a.id)).sort((p,b)=>b.createdAt.localeCompare(p.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(p=>p.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(k=>k.recordType==="participant"&&k.kind==="human"&&k.status==="active"),r=t.bundle.records.find(k=>k.recordType==="subject"&&k.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=xe(i),c=xe(i),p=xe(i),b=xe(i),S=xe(i),w=new Set(t.bundle.records.flatMap(k=>k.recordType==="model_entry"&&k.key===e.key?k.decisionIds:[])),P=t.bundle.records.filter(k=>k.recordType==="decision"&&k.state==="active"&&w.has(k.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."},y={...T,id:p,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},l={...T,id:b,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[p],value:e.value},M={...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:[p],entryIds:[b],coverage:[{decisionId:p,status:"projected"}]},f={...T,id:xe(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:b},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},m=P.map(k=>({...T,id:xe(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:k.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),j=P.map(k=>({...T,id:xe(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:y.id},to:{entityType:"decision",entityId:k.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[u,y,l,M],events:[g,...m],relationships:[f,...j],artifacts:[],tombstones:[],projectionUpdates:P.map(k=>({entityType:"decision",entityId:k.id,fromState:"active",state:"superseded"}))},{transactionId:xe(i),committedAt:s});return await this.refreshIndex(D),{decisionId:p,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=xe(s),p=e.changes.map(T=>{let h=T.decisionIds?.filter(y=>e.decisionIds.includes(y)),u=h?.length?h:e.decisionIds,g=[...new Set(r.filter(y=>u.includes(y.id)).flatMap(y=>y.subjects.map(l=>l.subjectId)))];return{id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:u.map(y=>({kind:"record",id:y})),recordType:"model_entry",key:T.path.map(String).join("."),subjectIds:g,decisionIds:u,value:T.value}}),b=new Set(p.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:p.map(T=>T.id),coverage:e.decisionIds.map(T=>e.coverage?.find(h=>h.decisionId===T)??{decisionId:T,status:b.has(T)?"projected":"unprojected"})},w=p.flatMap(T=>T.decisionIds.map(h=>({id:xe(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."}))),P=await this.store.commit({records:[...p,S],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:xe(s),committedAt:a});return await this.refreshIndex(P),{projectionId:c,entryIds:p.map(T=>T.id),headSequence:P.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await ln({...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=ti(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 Ut(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 Ft(o,e,t){let n=Pe(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function Qo(o){let e=Ut(o),t=Ut(e.authority),n=t.level,r=t.mode,i=Ft(n,"authority.level",["owner","delegate","contributor"]),s=Ft(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Pe(e.proposalId,"proposalId"),participantId:Pe(e.participantId,"participantId"),occurredAt:Pe(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:Pe(e.eventId,"eventId"),decisionId:Pe(e.decisionId,"decisionId"),kind:Ft(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Pe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Pe(e.eventId,"eventId"),reason:Pe(e.reason,"reason")};case"defer":{let c=Ut(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: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(p=>Pe(p,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(p=>Ft(p,"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: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:Ft(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let p=Ut(c);return{subjectId:Pe(p.subjectId,"subjectId"),role:Ft(p.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Pe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Xo(o){let e=Ut(o),t=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Pe(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:Ut(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 dd=1400,cd=6,ld=2,Yo=6;function ii(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 di(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!ii(e.primary))return;let t=Array.isArray(e.mounted)?e.mounted.filter(ii):[],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 si(o){return[o.primary,...o.mounted]}function hn(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 ai(o){return Math.ceil(JSON.stringify(o).length/4)}function pd(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 ud(o,e,t,n){if(!o.length)return;if(!n&&e.length===0)return o[0].context;let r=o.map(({store:S,context:w})=>pd(w,S,S.storeId!==t)),i=hn(r.map(S=>S.acceptedTruth?.decisions??[])).slice(0,cd),s=new Set(i.map(S=>`${S.storeId}:${S.id}`)),a=r.flatMap(S=>S.acceptedTruth?.conflicts??[]).filter(S=>S.decisionIds.every(w=>s.has(`${S.storeId}:${w}`))),c=hn(r.map(S=>S.packets)).slice(0,ld),p=i.length<r.reduce((S,w)=>S+(w.acceptedTruth?.decisions.length??0),0)||c.length<r.reduce((S,w)=>S+w.packets.length,0),b={source:"composed",...i.length?{acceptedTruth:{decisions:i,conflicts:a,truncated:p||r.some(S=>S.acceptedTruth?.truncated)}}:{},packets:c,truncated:p||e.length>0||r.some(S=>S.truncated),estimatedTokens:0,...e.length?{unavailableStoreIds:e}:{}};for(;ai(b)>dd;){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=ai(b),!(!b.packets.length&&!b.acceptedTruth?.decisions.length))return b}function ci(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 Se(o,e){return`${o}:${e}`}function md(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}:${Se(e.storeId,e.explanationId)}:${Se(t.storeId,t.explanationId)}`}function fd(o,e){let t=new Map;for(let{store:n,topology:r}of o)for(let i of r.explanations)t.set(Se(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(Se(s,i.from.memoryId)),p=t.get(Se(a,i.to.memoryId));return!c||!p?[]:[{id:i.id,type:i.type,fromId:c,toId:p,rationale:i.rationale,storeId:n.storeId,readOnly:n.storeId!==e,from:{storeId:s,explanationId:c},to:{storeId:a,explanationId:p}}]}))}function hd(o){let e=new Set;return o.filter(t=>{let n=md(t);return e.has(n)?!1:(e.add(n),!0)})}function gd(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:l,context:M})=>ci(M,l,l.storeId!==t)),c=hn(a.map(l=>l.explanations)),p=hd([...a.flatMap(l=>l.relations??[]),...r]),b=new Map([...c,...i].map(l=>[Se(l.storeId??"",l.id),l])),S=[],w=new Set,P=l=>{if(!l||S.length>=Yo)return;let M=Se(l.storeId??"",l.id);w.has(M)||(w.add(M),S.push(l))};for(let l of c.slice(0,Yo)){let M=Se(l.storeId??"",l.id),f=p.flatMap(m=>m.from&&Se(m.from.storeId,m.from.explanationId)===M?[b.get(Se(m.to.storeId,m.to.explanationId))]:m.to&&Se(m.to.storeId,m.to.explanationId)===M?[b.get(Se(m.from.storeId,m.from.explanationId))]:[]).find(Boolean);f&&(P(l),P(f))}c.forEach(P),i.forEach(P);let T=S,h=p.filter(l=>{let M=l.from,f=l.to;return!!(M&&f&&w.has(Se(M.storeId,M.explanationId))&&w.has(Se(f.storeId,f.explanationId)))}),u=new Set([...c.map(l=>Se(l.storeId??"",l.id)),...i.map(l=>Se(l.storeId??"",l.id))]).size,g=[...new Set(a.flatMap(l=>l.pendingGroundingExplanationIds??[]))],y=[...new Set(a.flatMap(l=>l.correctionExplanationIds??[]))];return{explanations:T,relations:h,truncated:T.length<u||e.length>0||a.some(l=>l.truncated),...a.find(l=>l.retrievalIntent)?.retrievalIntent?{retrievalIntent:a.find(l=>l.retrievalIntent).retrievalIntent}:{},historicalCaveats:hn(a.map(l=>l.historicalCaveats??[])).slice(0,3),...g.length?{pendingGroundingExplanationIds:g}:{},...y.length?{correctionExplanationIds:y}:{},...e.length?{unavailableStoreIds:e}:{},...s.length?{unavailableTopologyStoreIds:s}:{}}}var Un=class{constructor(e,t,n=r=>({memory:new zt(r.projectRoot),imprint:new St(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=si(this.normalized(e)),s=await Promise.allSettled(i.map(async p=>{let b,S=await $n(this.reader(p).memory,t,n,w=>{b=w});if(b)throw b;return{store:p,context:S}})),a=s.flatMap(p=>p.status==="fulfilled"&&p.value.context?[p.value]:[]),c=s.flatMap((p,b)=>p.status==="rejected"?[i[b].storeId]:[]);return this.record(i.length,c.length,r),ud(a,c,this.primary.storeId,i.length>1)}async imprintContext(e,t){let n=performance.now(),r=si(this.normalized(e)),i=r.length>1,s=r.map(async E=>({store:E,context:await this.reader(E).imprint.contextualize(E.storeId===this.primary.storeId?t:{...t,pendingGroundingExplanationIds:void 0,correctionExplanationIds:void 0})})),a=i?r.map(async E=>({store:E,topology:await(this.reader(E).memory.imprintTopology?.()??Promise.resolve({explanations:[],relations:[]}))})):[],[c,p]=await Promise.all([Promise.allSettled(s),Promise.allSettled(a)]),b=c.flatMap(E=>E.status==="fulfilled"&&E.value.context?[E.value]:[]),S=c.flatMap((E,W)=>E.status==="rejected"?[r[W].storeId]:[]),w=p.flatMap(E=>E.status==="fulfilled"?[E.value]:[]),P=p.flatMap((E,W)=>E.status==="rejected"?[r[W].storeId]:[]),T=new Map(w.flatMap(({store:E,topology:W})=>W.explanations.map(G=>[Se(E.storeId,G.explanationId),G.memoryId]))),h=b.map(({store:E,context:W})=>({store:E,context:{...W,explanations:W.explanations.map(G=>({...G,memoryId:T.get(Se(E.storeId,G.id))}))}})),u=fd(w,this.primary.storeId),g=h.map(({store:E,context:W})=>ci(W,E,E.storeId!==this.primary.storeId)),y=hn(g.map(E=>E.explanations)).slice(0,Yo),l=new Set(y.map(E=>Se(E.storeId??"",E.id))),M=new Set(g.flatMap(E=>E.explanations.map(W=>Se(W.storeId??"",W.id)))),f=new Map,m=(E,W)=>{if(M.has(Se(E,W)))return;let G=f.get(E)??new Set;G.add(W),f.set(E,G)};for(let E of u){if(!E.from||!E.to)continue;let W=Se(E.from.storeId,E.from.explanationId),G=Se(E.to.storeId,E.to.explanationId);l.has(W)&&m(E.to.storeId,E.to.explanationId),l.has(G)&&m(E.from.storeId,E.from.explanationId)}let j=new Map(r.map(E=>[E.storeId,E])),D=[...f].map(async([E,W])=>{let G=j.get(E),fe=G?this.reader(G).imprint.explanationsByIds:void 0;if(!G||!fe)return{storeId:E,explanations:[]};let X=await fe.call(this.reader(G).imprint,[...W]);return{storeId:E,explanations:X.map(oe=>({...oe,memoryId:T.get(Se(E,oe.id)),storeId:E,storeRoot:G.projectRoot,readOnly:E!==this.primary.storeId}))}}),k=await Promise.allSettled(D),O=k.flatMap(E=>E.status==="fulfilled"?E.value.explanations:[]),K=k.flatMap((E,W)=>E.status==="rejected"?[[...f.keys()][W]]:[]),H=[...new Set([...P,...K])];return this.record(r.length,new Set([...S,...H]).size,n),gd(h,S,this.primary.storeId,i,u,O,H)}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 Pt=1,Zo="bridge";function li(o){return`codex-session:${o}`}function bd(o,e){return`codex-${yd("sha256").update(`${o}:${e}`).digest("hex").slice(0,16)}`}function pi(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 xd(o,e){let t=new Set,n=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();t.add(wd(s)?vd(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,p]of Object.entries(i))r(p,c,a+1)}};for(let i of o)r(i.toolInput);return[...t]}function zn(o){return o?Math.ceil(o.length/4):0}function ui(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(`
10
+ `),a=rn(n),c=mi(r,i),p=[s,a,c].filter(Boolean).join(`
11
+ `);return{additionalContext:p,contextBudget:{protocolEstimatedTokens:zn(s),memoryEstimatedTokens:zn(a),imprintEstimatedTokens:zn(c),totalEstimatedTokens:zn(p)}}}function mi(o,e){return o?an(o,{requestText:e}).split(`
42
12
  `).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(`
43
13
  `):["","## 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(`
44
- `)}function Ad(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 Ed(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 Wn=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 zn(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([pi(e)])}async prepare(e){if(e.executionOwner===Zo)return{status:"managed_by_bridge",protocolVersion:Mt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let v=mi(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Mt,threadId:n.threadId,jobId:n.jobId,...v}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${kd()}`,[pi(e.sessionId)]));let i=Md(e.sessionId,e.turnId),s=r.messages.find(v=>v.jobId===i&&v.role==="human"),a=ui(e.prompt),c=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),p=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(v=>v.role==="assistant"&&v.imprintSummary?.grounding&&!v.imprintSummary.resolvedAction?[v.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}:{},...p?{imprintContext:p}:{}});let b={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:p,events:[]};this.turns.set(t,b);let S=mi(e.sessionId,r.id,i,c,p,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Mt,threadId:r.id,jobId:i,...S}}async recordEvent(e){if(e.executionOwner===Zo)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===Zo)return{status:"managed_by_bridge",protocolVersion:Mt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Mt};let r=(await this.options.threadStore.getThread(t.threadId))?.messages.find(u=>u.role==="assistant"&&u.jobId===t.jobId);if(r)return e.lastAssistantMessage&&e.lastAssistantMessage!==r.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Mt,threadId:t.threadId,jobId:t.jobId};let i=jd(t.events,this.options.projectRoot),s=i.length>0,a,c={state:"not_applicable"},p,b;if(t.assessment?.assessmentText){let u=sn(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(()=>{})),p=Ad(u.draft),b=u.draft&&u.draft.decision!=="recognize"?u.draft.appliedExplanationIds:void 0}let S=s?"completed":"no_change",v=on({changedFiles:i}),P={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:v},result:v,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:p,imprintAppliedExplanationIds:b};await this.options.threadStore.appendMessage(t.threadId,P);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=Ed(t.assessment?.semanticCandidates??[],T.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:Mt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=ui(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:[rn(n),fi(r,e.query)].filter(Boolean).join(`
45
- `)}}};import{mkdir as Od,readFile as hi,realpath as Dd,writeFile as Nd}from"fs/promises";import{join as Gn}from"path";function Kn(o){return Cd(o).slice(0,12)}var _d=[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 Cd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):$d(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let v=7;v>=0;v--)e.push(t/Math.pow(2,v*8)&255);let n=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,c=2600822924,p=528734635,b=1541459225,S=new Array(64);for(let v=0;v<e.length;v+=64){for(let f=0;f<16;f++){let m=v+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 P=n,T=r,h=i,u=s,g=a,y=c,l=p,j=b;for(let f=0;f<64;f++){let m=et(g,6)^et(g,11)^et(g,25),E=g&y^~g&l,D=j+m+E+_d[f]+S[f]>>>0,k=et(P,2)^et(P,13)^et(P,22),O=P&T^P&h^T&h,K=k+O>>>0;j=l,l=y,y=g,g=u+D>>>0,u=h,h=T,T=P,P=D+K>>>0}n=n+P>>>0,r=r+T>>>0,i=i+h>>>0,s=s+u>>>0,a=a+g>>>0,c=c+y>>>0,p=p+l>>>0,b=b+j>>>0}return[n,r,i,s,a,c,p,b].map(v=>v.toString(16).padStart(8,"0")).join("")}function et(o,e){return o>>>e|o<<32-e}function $d(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 tr(o){return Dd(o).catch(()=>o)}function gi(o){return Gn(o,".popmelt","store.json")}function Bd(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function er(o){let e=await tr(o);try{let t=JSON.parse(await hi(gi(e),"utf8"));return Bd(t)?t:null}catch{return null}}async function Jd(o){let e=await tr(o),t=await er(e);if(t)return t;let n;for(let r of[Gn(e,".popmelt","memory","manifest.json"),Gn(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await hi(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){n=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Kn(e)}`,createdAt:new Date().toISOString()}}async function yi(o){let e=await tr(o),t=await er(e);if(t)return t;let n=await Jd(e),r=Gn(e,".popmelt");await Od(r,{recursive:!0});try{return await Nd(gi(e),`${JSON.stringify(n,null,2)}
46
- `,{encoding:"utf8",flag:"wx"}),n}catch(i){let s=await er(e);if(s)return s;throw i}}var qd=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ld=new Set(["default","flex","fast","priority"]);function Vt(o){let e=typeof o.reasoningEffort=="string"&&qd.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&Ld.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Hn(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 Fd}from"child_process";import{createInterface as Ud}from"readline";function gn(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
47
-
48
- ${t}`:t;return o.push(n),n}var zd=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"]),Ii=1e5;function Vd(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!zd.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>Ii?n.slice(0,Ii)+`
49
- \u2026[truncated]`:n}function Qn(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:p,reasoningEffort:b,timeoutMs:S=3e5,onEvent:v}=e,P=[];c?P.push("--resume",c,"-p",t):P.push("-p",t),P.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),p&&P.push("--model",p),b&&P.push("--effort",b);for(let u of s)P.push("--allowedTools",u);let T=Fd(a,P,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(u=>{let g,y=[],l=[],j=[],f=!1,m="",E,D,k=!1,O=setTimeout(()=>{k=!0,T.kill("SIGTERM"),setTimeout(()=>{try{T.kill("SIGKILL")}catch{}},5e3)},S),K=Ud({input:T.stdout}),H=new Set;K.on("line",W=>{if(W.trim())try{let G=JSON.parse(W);G.session_id&&!g&&(g=G.session_id);let fe=G.type??(G.event?.type?`event.${G.event.type}`:"unknown");if(H.add(fe),G.type==="result"&&G.result&&y.length===0){let X=typeof G.result=="string"?G.result:"";if(X){let oe=gn(y,X);oe&&v?.({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=gn(y,X.text);oe&&v?.({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=Vd(X);if(v?.({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};l.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&&(l.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&&v?.({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&&v?.({type:"tool_use",jobId:o,tool:"Read",file:G.tool_use_result.file.filePath},o)}catch{}});let _=[];T.stderr?.on("data",W=>{_.push(W.toString())}),T.on("close",W=>{if(clearTimeout(O),K.close(),y.length===0&&H.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...H].join(", ")}`),k)f=!0,m=`Timed out after ${Math.round(S/6e4)} minutes`;else if(W!==0&&W!==null){f=!0;let fe=_.join("").trim(),X=y.join("").trim(),oe=y.length===0&&H.size>0?` (no text captured, event types: ${[...H].join(", ")})`:"";m=fe||D||X||`Claude process exited with code ${W}${oe}`}f&&!m&&D&&(m=D);let G=Wd(m,E);u({sessionId:g,text:y.join(""),success:!f,error:f?G.message:void 0,errorCode:f?G.code:void 0,recoverableError:f?G.recoverable:void 0,fileEdits:l.length>0?l:void 0,editEvents:j.length>0?j:void 0})}),T.on("error",W=>{clearTimeout(O),f=!0,m=W.message,u({sessionId:g,text:y.join(""),success:!1,error:m,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:l.length>0?l:void 0,editEvents:j.length>0?j:void 0})})});return{process:T,result:h}}function Wd(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 Gd,spawnSync as Ri}from"child_process";import{readFileSync as Hd,statSync as Qd}from"fs";import{basename as Xd,extname as Yd,isAbsolute as Zd,relative as Pi,resolve as ec}from"path";import{createInterface as tc}from"readline";function Yn(o){return o&&typeof o=="object"&&!Array.isArray(o)?o:void 0}function Xn(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 wi(o){let e=Yn(o);if(e)return e;if(typeof o=="string")try{return Yn(JSON.parse(o))}catch{return}}function nr(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Kd(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 vi(o){let e=Yn(o)??{},t=Yn(e.invocation),n=wi(e.arguments)??wi(t?.arguments),r=Xn([e,t],["server","server_name"]),i=Xn([e,t],["tool","tool_name","name"]),s=Xn([n,e,t],["title","display_name","description"]),a=Xn([n],["code","script"]),c=Kd(r,i,s,a)?"Browser":r?nr(r):i?nr(i):"MCP",p=i&&nr(i),b=s??p,S=b&&b!==c?`${c}: ${b}`:c;return{tool:c,...b?{content:b}:{},telemetryLabel:S}}function bi(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var xi=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),or=2e5,nc=1e5,Mi=2e5;function ji(o){let e=Xd(o).toLowerCase(),t=Yd(o).toLowerCase();return xi.has(t)||xi.has(e)}function yn(o,e){let t=Zd(e)?e:ec(o,e),n=Pi(o,t);return n===""||n.startsWith("..")?null:t}function Zn(o,e){if(!ji(e))return;let t=yn(o,e);if(t)try{let n=Qd(t);return n.isFile()?n.size>or?{exists:!0,truncated:!0}:{exists:!0,content:Hd(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function oc(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function rc(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 Si(o){return oc(o,["patch","diff","unifiedDiff","unified_diff"])}function rr(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Ti(o,e){let t=Ri("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Mi+65536});return t.status!==0?null:t.stdout??""}function ic(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 ki(o){let e=Ti(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Ti(o,["diff","--no-ext-diff","HEAD","--"])??"",n=rr(t,Mi);return{status:e,changedFiles:ic(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function sc(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function ac(o,e){if(!ji(e))return;let t=yn(o,e);if(!t)return;let n=Pi(o,t);if(n===""||n.startsWith(".."))return;let r=Ri("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:or+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=rr(i,or);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function dc(o,e,t){return e.map(n=>{let r=t.has(n)?t.get(n):ac(o,n),i=Zn(o,n);return{filePath:n,...r?{before:r}:{},...i?{after:i}:{}}})}function eo(o,e){let{prompt:t,projectRoot:n,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:c="workspace-write",configOverrides:p=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let P of p)b.push("-c",P);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 P of p)b.push("-c",P);s&&b.push("-m",s),b.push(t),r&&b.push("--image",r)}let S=Gd("codex",b,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:o}}),v=new Promise(P=>{let T,h=[],u=[],g=[],y=new Map,l=new Map,j=!1,f="",m=tc({input:S.stdout}),E=new Set;m.on("line",k=>{if(k.trim())try{let O=JSON.parse(k),K=O.type??"unknown";if(E.add(K),K==="thread.started"&&O.thread_id&&!T&&(T=O.thread_id),(K==="item.agentMessage.delta"||K==="item/agentMessage/delta")&&O.delta?.text&&(h.push(O.delta.text),a?.({type:"delta",jobId:o,text:O.delta.text},o)),(K==="item.reasoning.delta"||K==="item/reasoning/delta")&&O.delta?.text&&a?.({type:"thinking",jobId:o,text:O.delta.text},o),(K==="item.started"||K==="item/started")&&O.item){let H=O.item.type;if(H==="command_execution"){let _=O.item.command,W=_?bi(_):void 0,G=ki(n),fe=new Map;for(let oe of G?.changedFiles??[])fe.set(oe,Zn(n,oe));typeof O.item.id=="string"&&l.set(O.item.id,{..._?{rawCommand:_}:{},...W?{command:W}:{},...G?{beforeWorktree:G}:{},beforeSnapshots:fe});let X=W?`Bash: ${W.split(`
51
- `)[0].slice(0,80)}`:"Bash";u.push(X),a?.({type:"tool_use",jobId:o,tool:"Bash",...W?{content:W}:{}},o)}else if(H==="file_change"){let _=O.item.filename||O.item.path;_&&!y.has(_)&&y.set(_,Zn(n,_)),u.push(_?`Edit ${_.split("/").pop()}`:"Edit");let W=_?yn(n,_)??_:void 0;a?.({type:"tool_use",jobId:o,tool:"Edit",...W?{file:W}:{}},o)}else if(H==="file_read"){let _=O.item.filename||O.item.path;u.push(_?`Read ${_.split("/").pop()}`:"Read");let W=_?yn(n,_)??_:void 0;a?.({type:"tool_use",jobId:o,tool:"Read",...W?{file:W}:{}},o)}else if(H==="web_search")u.push("WebSearch"),a?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(H==="mcp_tool_call"){let _=vi(O.item);u.push(_.telemetryLabel),a?.({type:"tool_use",jobId:o,tool:_.tool,..._.content?{content:_.content}:{}},o)}}if((K==="item.completed"||K==="item/completed")&&O.item){if(O.item.type==="agent_message"){let H=O.item.text;if(typeof H=="string"&&H){let _=gn(h,H);_&&a?.({type:"delta",jobId:o,text:_},o)}}else if(O.item.type==="reasoning"){let H=O.item.text;typeof H=="string"&&H&&a?.({type:"thinking",jobId:o,text:H},o)}else if(O.item.type==="file_change"&&Array.isArray(O.item.changes))for(let H of O.item.changes){let _=H.path||H.filename,W=H.kind==="add"?"Write":"Edit";if(_){u.push(`${W} ${_.split("/").pop()}`);let G=yn(n,_)??_;a?.({type:"tool_use",jobId:o,tool:W,file:G},o);let fe=H,X=typeof fe.kind=="string"?fe.kind:void 0,oe=rc(X),x=y.get(_),$=Zn(n,_);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:oe,filePath:_,...x?{before:x}:{},...$?{after:$}:{},...Si(fe)?{patch:Si(fe)}:{},...X?{rawKind:X}:{}}),y.set(_,$)}}else if(O.item.type==="command_execution"){let H=typeof O.item.id=="string"?O.item.id:void 0,_=H?l.get(H):void 0,W=typeof O.item.command=="string"?O.item.command:_?.rawCommand,G=W?bi(W):_?.command,fe=ki(n);if(sc(_?.beforeWorktree,fe)){let X=[...new Set([..._?.beforeWorktree?.changedFiles??[],...fe?.changedFiles??[]])],oe=typeof O.item.aggregated_output=="string"?rr(O.item.aggregated_output,nc):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",...W?{rawCommand:W}:{},...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:dc(n,X,_?.beforeSnapshots??new Map)}:{}})}H&&l.delete(H)}}K==="turn.failed"&&(j=!0,f=O.error?.message||O.message||"Turn failed")}catch{}});let D=[];S.stderr?.on("data",k=>{D.push(k.toString())}),S.on("close",k=>{m.close(),h.length===0&&E.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...E].join(", ")}`),k!==0&&k!==null&&(j=!0,f=D.join("")||`Codex process exited with code ${k}`),P({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",k=>{j=!0,f=k.message,P({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:v}}import{spawn as cc}from"child_process";import{createInterface as lc}from"readline";function Ai(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 Ei(o,e){let{prompt:t,projectRoot:n,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:c="copilot"}=e,p=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&p.push(`--resume=${r}`),i&&p.push("--model",i),p.push("-p",t);let b=cc(c,p,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),S=new Promise(v=>{let P,T=[],h=[],u=!1,g="",y=!1,l=setTimeout(()=>{y=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},s),j=lc({input:b.stdout}),f=new Set,m=[];j.on("line",D=>{if(D.trim())try{let k=JSON.parse(D),O=wn(k);f.add(O),m.length<5&&uc(O)&&m.push(D.slice(0,800));let K=In(k,["sessionId","session_id","id"],["session","conversation","thread"]);K&&!P&&(P=K);let H=pc(k,T.length===0);H&&(T.push(H),a?.({type:"delta",jobId:o,text:H},o));let _=mc(k);_&&a?.({type:"thinking",jobId:o,text:_},o);let W=fc(k);W&&(h.push(W.label),a?.({type:"tool_use",jobId:o,tool:W.tool,...W.file?{file:W.file}:{},...W.content?{content:W.content}:{}},o));let G=hc(k);G&&(u=!0,g=G)}catch{}});let E=[];b.stderr?.on("data",D=>{E.push(D.toString())}),b.on("close",D=>{clearTimeout(l),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
- `)}`)),y?(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 k=u?Ai(g,i):null;v({sessionId:P,text:T.join(""),success:!u,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),b.on("error",D=>{clearTimeout(l);let k=Ai(D.message,i);v({sessionId:P,text:T.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:b,result:S}}function wn(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 pc(o,e=!1){let t=wn(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"&&ir(o))return o.text;if(typeof o.message=="string"&&ir(o))return o.message;if(typeof o.delta=="string"&&ir(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 uc(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function mc(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 fc(o){let e=In(o,["tool","toolName","tool_name","name"]),t=In(o,["command","cmd"]),n=In(o,["file","path","filename","filePath"]),r=wn(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 hc(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"&&wn(o).toLowerCase().includes("error"))return o.message}function In(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=In(r,e);if(i)return i}}function ir(o){let e=wn(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as gc,readFile as yc}from"fs/promises";import{join as sr}from"path";var to=class{constructor(e){let t=sr(e,".popmelt");this.decisionsDir=sr(t,"decisions")}async listDecisionIds(){try{return(await gc(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 yc(sr(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 Ic,randomUUID as wc}from"crypto";import{mkdir as ar,readFile as _i,readdir as Ci,rename as no,stat as $i,unlink as oo,writeFile as ro}from"fs/promises";import{extname as vc,join as Qe}from"path";var bc=10080*60*1e3,xc=600*1e3,Sc=3600*1e3;function Tc(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function kc(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var io=class{constructor(e){this.draftsDir=Qe(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Qe(e,".popmelt","artifacts","thread-media")}async stage(e){let t=wc(),n=Tc(e.mimeType),r=`${t}${n}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:kc(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await ar(this.draftsDir,{recursive:!0});let a=Qe(this.draftsDir,r),c=Qe(this.draftsDir,`${t}.json`),p=`${a}.part`,b=`${c}.part`;return await ro(p,e.data),await no(p,a),await ro(b,JSON.stringify(s,null,2)),await no(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 _i(i),a=Ic("sha256").update(s).digest("hex"),c=Qe(this.mediaDir,`${a}${vc(r.contentFile)||".bin"}`);await ar(this.mediaDir,{recursive:!0});try{await $i(c)}catch{let p=`${c}.part`;await ro(p,s),await no(p,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 Ci(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let r=Qe(this.draftsDir,n);if(n.endsWith(".part")){let a=await $i(r).catch(()=>null);a&&e-a.mtimeMs>Sc&&await oo(r).catch(()=>{});return}if(!n.endsWith(".json"))return;let i=await this.readManifest(n.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>xc:e-i.lastSeenAt>bc)||await Promise.all([oo(r).catch(()=>{}),oo(Qe(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Ci(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>oo(Qe(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await _i(Qe(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await ar(this.draftsDir,{recursive:!0});let t=Qe(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await ro(n,JSON.stringify(e,null,2)),await no(n,t)}};import{randomUUID as Oi}from"crypto";import{mkdir as dr,readFile as cr,writeFile as so}from"fs/promises";import{dirname as lr,join as Wt}from"path";var Xe="[ProjectionWorker]",Rc={version:1,runs:[]},Pc={version:1,updatedAt:0,proposals:[]},Mc=12;function jc(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 Di(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 Ac(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Ec(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:[],p=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:{},v=Object.keys(s).filter(T=>JSON.stringify(s[T])!==JSON.stringify(b[T])).length,P=Object.keys(a).filter(T=>JSON.stringify(a[T])!==JSON.stringify(S[T])).length;return{ruleCount:p,tokenSectionCount:v,componentCount:P,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(T=>!r.has(T))}}function _c(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Cc(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 ao(o,e,t){let n=o;for(let i=0;i<e.length-1;i++)n=Cc(n,e[i],e[i+1]);let r=e[e.length-1];n[String(r)]=_c(t)}function Ni(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 $c(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 Oc(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 Bi(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=$c(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?Oc(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var co=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Wt(e,".popmelt");this.runsPath=Wt(n,"projection-runs.json"),this.legacyRunsPath=Wt(n,"materialization-runs.json"),this.proposalsPath=Wt(n,"projection-queue.json"),this.legacyProposalsPath=Wt(n,"model-proposals.json"),this.modelPath=Wt(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await cr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=jc(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?Ni(t,r):ao(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(Mc),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=Jc(r,s),c=Ac(r,n.totalCandidateDecisionCount,a);t=Oi().slice(0,8);let p={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(p);let b=!0,S,v,P;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"]});p={...p,provider:h},await this.persistRun(p);let g=await u;if(!g.success)b=!1,S=g.error,console.error(`${Xe} ${h} spawn error:`,S);else{let y=Bc(g.text,i);if(y){let l=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of y)ao(l,m.path,m.value);Array.isArray(l.rules)&&(l.rules=Di(l.rules));let j=Ec(l,i,s);if(y){let m=[...new Set(y.flatMap(E=>E.decisionIds))];j.coveredDecisionIds=m,j.uncoveredDecisionIds=i.filter(E=>!m.includes(E))}v=j;let f=await this.createModelProposal({decisionIds:i,proposedModel:l,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:v,changes:y});P=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({...p,status:b?"proposed":"failed",completedAt:Date.now(),error:S,outputStats:v,proposalId:P}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:b,error:S}),{processedIds:i,success:b,error:S,runId:t,proposalId:P}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Di(e.rules)),await so(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Xe} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await dr(lr(this.runsPath),{recursive:!0}),await so(this.runsPath,JSON.stringify(t,null,2)),t):{...Rc,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??{...Pc,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??[])ao(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?Ni(s,c.path):ao(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:Oi().slice(0,8),status:"pending",title:Dc(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"}.`:Nc(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 dr(lr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...r})=>r)};await so(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(r=>r.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await dr(lr(this.runsPath),{recursive:!0}),await so(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Xe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await cr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await cr(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",...eo(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Hn(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",...Qn(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 Dc(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 Nc(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 Bc(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 p=c.path[0];if(p!=="tokens"&&p!=="components"&&p!=="rules")return[];if(p==="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 Jc(o,e){let t=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
14
+ `)}function Sd(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 Td(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 Vn=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 Un(t,{memory:e.memoryService,imprint:e.imprintService})}knowledgeDiagnostics(){return this.knowledgeViewReader.diagnostics()}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([li(e)])}async prepare(e){if(e.executionOwner===Zo)return{status:"managed_by_bridge",protocolVersion:Pt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let w=ui(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Pt,threadId:n.threadId,jobId:n.jobId,...w}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${Id()}`,[li(e.sessionId)]));let i=bd(e.sessionId,e.turnId),s=r.messages.find(w=>w.jobId===i&&w.role==="human"),a=pi(e.prompt),c=s?.memoryReview??await this.knowledgeViewReader.memoryContext(e.knowledgeView,a,[]),p=s?.imprintContext??await this.knowledgeViewReader.imprintContext(e.knowledgeView,{text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(w=>w.role==="assistant"&&w.imprintSummary?.grounding&&!w.imprintSummary.resolvedAction?[w.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}:{},...p?{imprintContext:p}:{}});let b={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:p,events:[]};this.turns.set(t,b);let S=ui(e.sessionId,r.id,i,c,p,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Pt,threadId:r.id,jobId:i,...S}}async recordEvent(e){if(e.executionOwner===Zo)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===Zo)return{status:"managed_by_bridge",protocolVersion:Pt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Pt};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:Pt,threadId:t.threadId,jobId:t.jobId};let i=xd(t.events,this.options.projectRoot),s=i.length>0,a,c={state:"not_applicable"},p,b;if(t.assessment?.assessmentText){let u=sn(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(()=>{})),p=Sd(u.draft),b=u.draft&&u.draft.decision!=="recognize"?u.draft.appliedExplanationIds:void 0}let S=s?"completed":"no_change",w=on({changedFiles:i}),P={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:w},result:w,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:p,imprintAppliedExplanationIds:b};await this.options.threadStore.appendMessage(t.threadId,P);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=Td(t.assessment?.semanticCandidates??[],T.proposalIds);return h&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:h}),{status:"completed",protocolVersion:Pt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=pi(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:[rn(n),mi(r,e.query)].filter(Boolean).join(`
15
+ `)}}};import{mkdir as Md,readFile as fi,realpath as jd,writeFile as Ad}from"fs/promises";import{join as Kn}from"path";function Wn(o){return Rd(o).slice(0,12)}var kd=[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 Rd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Pd(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let w=7;w>=0;w--)e.push(t/Math.pow(2,w*8)&255);let n=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,c=2600822924,p=528734635,b=1541459225,S=new Array(64);for(let w=0;w<e.length;w+=64){for(let f=0;f<16;f++){let m=w+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=Ze(S[f-15],7)^Ze(S[f-15],18)^S[f-15]>>>3,j=Ze(S[f-2],17)^Ze(S[f-2],19)^S[f-2]>>>10;S[f]=S[f-16]+m+S[f-7]+j>>>0}let P=n,T=r,h=i,u=s,g=a,y=c,l=p,M=b;for(let f=0;f<64;f++){let m=Ze(g,6)^Ze(g,11)^Ze(g,25),j=g&y^~g&l,D=M+m+j+kd[f]+S[f]>>>0,k=Ze(P,2)^Ze(P,13)^Ze(P,22),O=P&T^P&h^T&h,K=k+O>>>0;M=l,l=y,y=g,g=u+D>>>0,u=h,h=T,T=P,P=D+K>>>0}n=n+P>>>0,r=r+T>>>0,i=i+h>>>0,s=s+u>>>0,a=a+g>>>0,c=c+y>>>0,p=p+l>>>0,b=b+M>>>0}return[n,r,i,s,a,c,p,b].map(w=>w.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function Pd(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 tr(o){return jd(o).catch(()=>o)}function hi(o){return Kn(o,".popmelt","store.json")}function Ed(o){if(!o||typeof o!="object"||Array.isArray(o))return!1;let e=o;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function er(o){let e=await tr(o);try{let t=JSON.parse(await fi(hi(e),"utf8"));return Ed(t)?t:null}catch{return null}}async function _d(o){let e=await tr(o),t=await er(e);if(t)return t;let n;for(let r of[Kn(e,".popmelt","memory","manifest.json"),Kn(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await fi(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){n=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Wn(e)}`,createdAt:new Date().toISOString()}}async function gi(o){let e=await tr(o),t=await er(e);if(t)return t;let n=await _d(e),r=Kn(e,".popmelt");await Md(r,{recursive:!0});try{return await Ad(hi(e),`${JSON.stringify(n,null,2)}
16
+ `,{encoding:"utf8",flag:"wx"}),n}catch(i){let s=await er(e);if(s)return s;throw i}}var Cd=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),$d=new Set(["default","flex","fast","priority"]);function Vt(o){let e=typeof o.reasoningEffort=="string"&&Cd.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&$d.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Gn(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 Od}from"child_process";import{createInterface as Dd}from"readline";function gn(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
17
+
18
+ ${t}`:t;return o.push(n),n}var Nd=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"]),yi=1e5;function Bd(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Nd.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>yi?n.slice(0,yi)+`
19
+ \u2026[truncated]`:n}function Hn(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:p,reasoningEffort:b,timeoutMs:S=3e5,onEvent:w}=e,P=[];c?P.push("--resume",c,"-p",t):P.push("-p",t),P.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),p&&P.push("--model",p),b&&P.push("--effort",b);for(let u of s)P.push("--allowedTools",u);let T=Od(a,P,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),h=new Promise(u=>{let g,y=[],l=[],M=[],f=!1,m="",j,D,k=!1,O=setTimeout(()=>{k=!0,T.kill("SIGTERM"),setTimeout(()=>{try{T.kill("SIGKILL")}catch{}},5e3)},S),K=Dd({input:T.stdout}),H=new Set;K.on("line",W=>{if(W.trim())try{let G=JSON.parse(W);G.session_id&&!g&&(g=G.session_id);let fe=G.type??(G.event?.type?`event.${G.event.type}`:"unknown");if(H.add(fe),G.type==="result"&&G.result&&y.length===0){let X=typeof G.result=="string"?G.result:"";if(X){let oe=gn(y,X);oe&&w?.({type:"delta",jobId:o,text:oe},o)}}if(G.type==="assistant"&&Array.isArray(G.message?.content)){typeof G.error=="string"&&(j=G.error);for(let X of G.message.content){if(X.type==="text"&&X.text){let oe=gn(y,X.text);oe&&w?.({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=Bd(X);if(w?.({type:"tool_use",jobId:o,tool:X.name,...oe?{file:oe}:{},...x?{content:x}:{}},o),X.name==="Edit"&&X.input?.file_path){let C={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};l.push(C),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:C.file_path,oldString:typeof C.old_string=="string"?C.old_string:void 0,newString:typeof C.new_string=="string"?C.new_string:void 0,replaceAll:typeof C.replace_all=="boolean"?C.replace_all:void 0})}else X.name==="Write"&&X.input?.file_path&&(l.push({tool:"Write",file_path:X.input.file_path,content:X.input.content}),M.push({sequence:M.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&&w?.({type:"thinking",jobId:o,text:X.thinking},o)}}G.type==="result"&&G.is_error===!0&&(f=!0,typeof G.error=="string"&&(j=G.error),typeof G.result=="string"&&(D=G.result)),G.type==="user"&&G.tool_use_result?.file?.filePath&&w?.({type:"tool_use",jobId:o,tool:"Read",file:G.tool_use_result.file.filePath},o)}catch{}});let E=[];T.stderr?.on("data",W=>{E.push(W.toString())}),T.on("close",W=>{if(clearTimeout(O),K.close(),y.length===0&&H.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...H].join(", ")}`),k)f=!0,m=`Timed out after ${Math.round(S/6e4)} minutes`;else if(W!==0&&W!==null){f=!0;let fe=E.join("").trim(),X=y.join("").trim(),oe=y.length===0&&H.size>0?` (no text captured, event types: ${[...H].join(", ")})`:"";m=fe||D||X||`Claude process exited with code ${W}${oe}`}f&&!m&&D&&(m=D);let G=Jd(m,j);u({sessionId:g,text:y.join(""),success:!f,error:f?G.message:void 0,errorCode:f?G.code:void 0,recoverableError:f?G.recoverable:void 0,fileEdits:l.length>0?l:void 0,editEvents:M.length>0?M:void 0})}),T.on("error",W=>{clearTimeout(O),f=!0,m=W.message,u({sessionId:g,text:y.join(""),success:!1,error:m,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:l.length>0?l:void 0,editEvents:M.length>0?M:void 0})})});return{process:T,result:h}}function Jd(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 Ld,spawnSync as ki}from"child_process";import{readFileSync as Fd,statSync as Ud}from"fs";import{basename as zd,extname as Vd,isAbsolute as Wd,relative as Ri,resolve as Kd}from"path";import{createInterface as Gd}from"readline";function Xn(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 r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Ii(o){let e=Xn(o);if(e)return e;if(typeof o=="string")try{return Xn(JSON.parse(o))}catch{return}}function nr(o){return o.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function qd(o,e,t,n){return o!=="node_repl"||e!=="js"?!1:n&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(n)?!0:!!(t&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(t))}function wi(o){let e=Xn(o)??{},t=Xn(e.invocation),n=Ii(e.arguments)??Ii(t?.arguments),r=Qn([e,t],["server","server_name"]),i=Qn([e,t],["tool","tool_name","name"]),s=Qn([n,e,t],["title","display_name","description"]),a=Qn([n],["code","script"]),c=qd(r,i,s,a)?"Browser":r?nr(r):i?nr(i):"MCP",p=i&&nr(i),b=s??p,S=b&&b!==c?`${c}: ${b}`:c;return{tool:c,...b?{content:b}:{},telemetryLabel:S}}function vi(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var bi=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"]),or=2e5,Hd=1e5,Pi=2e5;function Mi(o){let e=zd(o).toLowerCase(),t=Vd(o).toLowerCase();return bi.has(t)||bi.has(e)}function yn(o,e){let t=Wd(e)?e:Kd(o,e),n=Ri(o,t);return n===""||n.startsWith("..")?null:t}function Yn(o,e){if(!Mi(e))return;let t=yn(o,e);if(t)try{let n=Ud(t);return n.isFile()?n.size>or?{exists:!0,truncated:!0}:{exists:!0,content:Fd(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Qd(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function Xd(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 xi(o){return Qd(o,["patch","diff","unifiedDiff","unified_diff"])}function rr(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function Si(o,e){let t=ki("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Pi+65536});return t.status!==0?null:t.stdout??""}function Yd(o){let e=new Set;for(let t of o.split(`
20
+ `)){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 Ti(o){let e=Si(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=Si(o,["diff","--no-ext-diff","HEAD","--"])??"",n=rr(t,Pi);return{status:e,changedFiles:Yd(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function Zd(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function ec(o,e){if(!Mi(e))return;let t=yn(o,e);if(!t)return;let n=Ri(o,t);if(n===""||n.startsWith(".."))return;let r=ki("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:or+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=rr(i,or);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function tc(o,e,t){return e.map(n=>{let r=t.has(n)?t.get(n):ec(o,n),i=Yn(o,n);return{filePath:n,...r?{before:r}:{},...i?{after:i}:{}}})}function Zn(o,e){let{prompt:t,projectRoot:n,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:c="workspace-write",configOverrides:p=[]}=e,b=[];if(i){b.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let P of p)b.push("-c",P);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 P of p)b.push("-c",P);s&&b.push("-m",s),b.push(t),r&&b.push("--image",r)}let S=Ld("codex",b,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:o}}),w=new Promise(P=>{let T,h=[],u=[],g=[],y=new Map,l=new Map,M=!1,f="",m=Gd({input:S.stdout}),j=new Set;m.on("line",k=>{if(k.trim())try{let O=JSON.parse(k),K=O.type??"unknown";if(j.add(K),K==="thread.started"&&O.thread_id&&!T&&(T=O.thread_id),(K==="item.agentMessage.delta"||K==="item/agentMessage/delta")&&O.delta?.text&&(h.push(O.delta.text),a?.({type:"delta",jobId:o,text:O.delta.text},o)),(K==="item.reasoning.delta"||K==="item/reasoning/delta")&&O.delta?.text&&a?.({type:"thinking",jobId:o,text:O.delta.text},o),(K==="item.started"||K==="item/started")&&O.item){let H=O.item.type;if(H==="command_execution"){let E=O.item.command,W=E?vi(E):void 0,G=Ti(n),fe=new Map;for(let oe of G?.changedFiles??[])fe.set(oe,Yn(n,oe));typeof O.item.id=="string"&&l.set(O.item.id,{...E?{rawCommand:E}:{},...W?{command:W}:{},...G?{beforeWorktree:G}:{},beforeSnapshots:fe});let X=W?`Bash: ${W.split(`
21
+ `)[0].slice(0,80)}`:"Bash";u.push(X),a?.({type:"tool_use",jobId:o,tool:"Bash",...W?{content:W}:{}},o)}else if(H==="file_change"){let E=O.item.filename||O.item.path;E&&!y.has(E)&&y.set(E,Yn(n,E)),u.push(E?`Edit ${E.split("/").pop()}`:"Edit");let W=E?yn(n,E)??E:void 0;a?.({type:"tool_use",jobId:o,tool:"Edit",...W?{file:W}:{}},o)}else if(H==="file_read"){let E=O.item.filename||O.item.path;u.push(E?`Read ${E.split("/").pop()}`:"Read");let W=E?yn(n,E)??E:void 0;a?.({type:"tool_use",jobId:o,tool:"Read",...W?{file:W}:{}},o)}else if(H==="web_search")u.push("WebSearch"),a?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(H==="mcp_tool_call"){let E=wi(O.item);u.push(E.telemetryLabel),a?.({type:"tool_use",jobId:o,tool:E.tool,...E.content?{content:E.content}:{}},o)}}if((K==="item.completed"||K==="item/completed")&&O.item){if(O.item.type==="agent_message"){let H=O.item.text;if(typeof H=="string"&&H){let E=gn(h,H);E&&a?.({type:"delta",jobId:o,text:E},o)}}else if(O.item.type==="reasoning"){let H=O.item.text;typeof H=="string"&&H&&a?.({type:"thinking",jobId:o,text:H},o)}else if(O.item.type==="file_change"&&Array.isArray(O.item.changes))for(let H of O.item.changes){let E=H.path||H.filename,W=H.kind==="add"?"Write":"Edit";if(E){u.push(`${W} ${E.split("/").pop()}`);let G=yn(n,E)??E;a?.({type:"tool_use",jobId:o,tool:W,file:G},o);let fe=H,X=typeof fe.kind=="string"?fe.kind:void 0,oe=Xd(X),x=y.get(E),C=Yn(n,E);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:oe,filePath:E,...x?{before:x}:{},...C?{after:C}:{},...xi(fe)?{patch:xi(fe)}:{},...X?{rawKind:X}:{}}),y.set(E,C)}}else if(O.item.type==="command_execution"){let H=typeof O.item.id=="string"?O.item.id:void 0,E=H?l.get(H):void 0,W=typeof O.item.command=="string"?O.item.command:E?.rawCommand,G=W?vi(W):E?.command,fe=Ti(n);if(Zd(E?.beforeWorktree,fe)){let X=[...new Set([...E?.beforeWorktree?.changedFiles??[],...fe?.changedFiles??[]])],oe=typeof O.item.aggregated_output=="string"?rr(O.item.aggregated_output,Hd):void 0,x=typeof O.item.exit_code=="number"?O.item.exit_code:O.item.exit_code===null?null:void 0,C=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",...W?{rawCommand:W}:{},...G?{command:G}:{},...x!==void 0?{exitCode:x}:{},...C?{status:C}:{},...oe?{output:oe.text}:{},...oe?.truncated?{outputTruncated:!0}:{},...E?.beforeWorktree?{beforeWorktree:E.beforeWorktree}:{},...fe?{afterWorktree:fe}:{},...X.length>0?{touchedFiles:tc(n,X,E?.beforeSnapshots??new Map)}:{}})}H&&l.delete(H)}}K==="turn.failed"&&(M=!0,f=O.error?.message||O.message||"Turn failed")}catch{}});let D=[];S.stderr?.on("data",k=>{D.push(k.toString())}),S.on("close",k=>{m.close(),h.length===0&&j.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...j].join(", ")}`),k!==0&&k!==null&&(M=!0,f=D.join("")||`Codex process exited with code ${k}`),P({sessionId:T,text:h.join(""),success:!M,error:M?f:void 0,editEvents:g.length>0?g:void 0,toolsUsed:u.length>0?u:void 0})}),S.on("error",k=>{M=!0,f=k.message,P({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:w}}import{spawn as nc}from"child_process";import{createInterface as oc}from"readline";function ji(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 Ai(o,e){let{prompt:t,projectRoot:n,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:c="copilot"}=e,p=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&p.push(`--resume=${r}`),i&&p.push("--model",i),p.push("-p",t);let b=nc(c,p,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),S=new Promise(w=>{let P,T=[],h=[],u=!1,g="",y=!1,l=setTimeout(()=>{y=!0,b.kill("SIGTERM"),setTimeout(()=>{try{b.kill("SIGKILL")}catch{}},5e3)},s),M=oc({input:b.stdout}),f=new Set,m=[];M.on("line",D=>{if(D.trim())try{let k=JSON.parse(D),O=wn(k);f.add(O),m.length<5&&ic(O)&&m.push(D.slice(0,800));let K=In(k,["sessionId","session_id","id"],["session","conversation","thread"]);K&&!P&&(P=K);let H=rc(k,T.length===0);H&&(T.push(H),a?.({type:"delta",jobId:o,text:H},o));let E=sc(k);E&&a?.({type:"thinking",jobId:o,text:E},o);let W=ac(k);W&&(h.push(W.label),a?.({type:"tool_use",jobId:o,tool:W.tool,...W.file?{file:W.file}:{},...W.content?{content:W.content}:{}},o));let G=dc(k);G&&(u=!0,g=G)}catch{}});let j=[];b.stderr?.on("data",D=>{j.push(D.toString())}),b.on("close",D=>{clearTimeout(l),M.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(`
22
+ `)}`)),y?(u=!0,g=`Timed out after ${Math.round(s/6e4)} minutes`):D!==0&&D!==null&&(u=!0,g=j.join("").trim()||g||`Copilot process exited with code ${D}`);let k=u?ji(g,i):null;w({sessionId:P,text:T.join(""),success:!u,error:k?.message,errorCode:k?.code,recoverableError:k?.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})}),b.on("error",D=>{clearTimeout(l);let k=ji(D.message,i);w({sessionId:P,text:T.join(""),success:!1,error:k.message,errorCode:k.code,recoverableError:k.recoverable,provider:"copilot",toolsUsed:h.length>0?h:void 0})})});return{process:b,result:S}}function wn(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 rc(o,e=!1){let t=wn(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 ze(o.delta)??ze(o.content)??ze(o.message);if(t==="assistant.message"&&e)return ze(o.message)??ze(o.content)??ze(o);if(t==="result"&&e)return ze(o.result)??ze(o.output)??ze(o.message)??ze(o);let i=o.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof o.text=="string"&&ir(o))return o.text;if(typeof o.message=="string"&&ir(o))return o.message;if(typeof o.delta=="string"&&ir(o))return o.delta}function ze(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(ze).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=ze(e[t]);if(n)return n}}function ic(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function sc(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 ac(o){let e=In(o,["tool","toolName","tool_name","name"]),t=In(o,["command","cmd"]),n=In(o,["file","path","filename","filePath"]),r=wn(o);if(t||r.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
23
+ `)[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 dc(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"&&wn(o).toLowerCase().includes("error"))return o.message}function In(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=In(r,e);if(i)return i}}function ir(o){let e=wn(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as cc,readFile as lc}from"fs/promises";import{join as sr}from"path";var eo=class{constructor(e){let t=sr(e,".popmelt");this.decisionsDir=sr(t,"decisions")}async listDecisionIds(){try{return(await cc(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 lc(sr(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 pc,randomUUID as uc}from"crypto";import{mkdir as ar,readFile as Ei,readdir as _i,rename as to,stat as Ci,unlink as no,writeFile as oo}from"fs/promises";import{extname as mc,join as He}from"path";var fc=10080*60*1e3,hc=600*1e3,gc=3600*1e3;function yc(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function Ic(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var ro=class{constructor(e){this.draftsDir=He(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=He(e,".popmelt","artifacts","thread-media")}async stage(e){let t=uc(),n=yc(e.mimeType),r=`${t}${n}`,i=Date.now(),s={id:t,annotationId:e.annotationId,name:Ic(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await ar(this.draftsDir,{recursive:!0});let a=He(this.draftsDir,r),c=He(this.draftsDir,`${t}.json`),p=`${a}.part`,b=`${c}.part`;return await oo(p,e.data),await to(p,a),await oo(b,JSON.stringify(s,null,2)),await to(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=He(this.draftsDir,r.contentFile),s=await Ei(i),a=pc("sha256").update(s).digest("hex"),c=He(this.mediaDir,`${a}${mc(r.contentFile)||".bin"}`);await ar(this.mediaDir,{recursive:!0});try{await Ci(c)}catch{let p=`${c}.part`;await oo(p,s),await to(p,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 _i(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let r=He(this.draftsDir,n);if(n.endsWith(".part")){let a=await Ci(r).catch(()=>null);a&&e-a.mtimeMs>gc&&await no(r).catch(()=>{});return}if(!n.endsWith(".json"))return;let i=await this.readManifest(n.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>hc:e-i.lastSeenAt>fc)||await Promise.all([no(r).catch(()=>{}),no(He(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await _i(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>no(He(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Ei(He(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await ar(this.draftsDir,{recursive:!0});let t=He(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await oo(n,JSON.stringify(e,null,2)),await to(n,t)}};import{randomUUID as $i}from"crypto";import{mkdir as dr,readFile as cr,writeFile as io}from"fs/promises";import{dirname as lr,join as Wt}from"path";var Qe="[ProjectionWorker]",wc={version:1,runs:[]},vc={version:1,updatedAt:0,proposals:[]},bc=12;function xc(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 Oi(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(`${Qe} 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(`${Qe} Rule count ${e.length} exceeds cap of 30`),e}function Sc(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Tc(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:[],p=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:{},w=Object.keys(s).filter(T=>JSON.stringify(s[T])!==JSON.stringify(b[T])).length,P=Object.keys(a).filter(T=>JSON.stringify(a[T])!==JSON.stringify(S[T])).length;return{ruleCount:p,tokenSectionCount:w,componentCount:P,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(T=>!r.has(T))}}function kc(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Rc(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 so(o,e,t){let n=o;for(let i=0;i<e.length-1;i++)n=Rc(n,e[i],e[i+1]);let r=e[e.length-1];n[String(r)]=kc(t)}function Di(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 Pc(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 Mc(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 Ni(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=Pc(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?Mc(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var ao=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Wt(e,".popmelt");this.runsPath=Wt(n,"projection-runs.json"),this.legacyRunsPath=Wt(n,"materialization-runs.json"),this.proposalsPath=Wt(n,"projection-queue.json"),this.legacyProposalsPath=Wt(n,"model-proposals.json"),this.modelPath=Wt(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await cr(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=xc(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let r=n.key.split(".");n.value===null?Di(t,r):so(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(bc),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(`${Qe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=_c(r,s),c=Sc(r,n.totalCandidateDecisionCount,a);t=$i().slice(0,8);let p={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(p);let b=!0,S,w,P;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"]});p={...p,provider:h},await this.persistRun(p);let g=await u;if(!g.success)b=!1,S=g.error,console.error(`${Qe} ${h} spawn error:`,S);else{let y=Ec(g.text,i);if(y){let l=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of y)so(l,m.path,m.value);Array.isArray(l.rules)&&(l.rules=Oi(l.rules));let M=Tc(l,i,s);if(y){let m=[...new Set(y.flatMap(j=>j.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=i.filter(j=>!m.includes(j))}w=M;let f=await this.createModelProposal({decisionIds:i,proposedModel:l,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:h,model:e.model??this.options.model,outputStats:w,changes:y});P=f.id,console.log(`${Qe} 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(`${Qe} ${S}`)}}catch(T){b=!1,S=T instanceof Error?T.message:String(T),console.error(`${Qe} Error:`,S)}return await this.persistRun({...p,status:b?"proposed":"failed",completedAt:Date.now(),error:S,outputStats:w,proposalId:P}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:b,error:S}),{processedIds:i,success:b,error:S,runId:t,proposalId:P}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Oi(e.rules)),await io(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Qe} 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 dr(lr(this.runsPath),{recursive:!0}),await io(this.runsPath,JSON.stringify(t,null,2)),t):{...wc,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??{...vc,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??[])so(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?Di(s,c.path):so(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:$i().slice(0,8),status:"pending",title:jc(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"}.`:Ac(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 dr(lr(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...r})=>r)};await io(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} 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 dr(lr(this.runsPath),{recursive:!0}),await io(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await cr(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await cr(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",...Zn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Gn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...Hn(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 jc(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 Ac(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 Ec(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 p=c.path[0];if(p!=="tokens"&&p!=="components"&&p!=="rules")return[];if(p==="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 _c(o,e){let t=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
54
24
  Kind: ${i.kind}
55
25
  Claim: ${i.claim}
56
26
  ${i.rationale?`Rationale: ${i.rationale}`:""}
@@ -129,15 +99,15 @@ Example:
129
99
  { "value": "8px", "property": "gap", "bindings": ["gap-2"] }
130
100
  - property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
131
101
  - bindings: Tailwind class names (without responsive prefixes) that use this token
132
- Include property and bindings when the decision context has class-level evidence.`}var lo=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 qc}from"child_process";import{readFile as Li}from"fs/promises";import{homedir as ur}from"os";import{join as tt}from"path";var mr=/popmelt/i;function jt(){return{found:!1,name:null,scope:null,disabled:!1}}function Kt(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function vn(o){for(let e of Object.keys(o))if(mr.test(e))return e;return null}async function po(o){try{let e=await Li(o,"utf-8");return JSON.parse(e)}catch{return null}}async function fr(o){let e=ur(),t=await po(tt(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=vn(r.mcpServers);if(i)return Kt(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=vn(a.mcpServers);if(c){let p=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(b=>mr.test(b));return Kt(c,"project",p)}}}}}let n=await po(tt(o,".mcp.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=vn(r.mcpServers);if(s){let a=await Ji(o,s);return Kt(s,"mcp.json",a)}}let i=vn(r);if(i&&i!=="mcpServers"){let s=await Ji(o,i);return Kt(i,"mcp.json",s)}}return jt()}async function Ji(o,e){let t=tt(o,".claude","settings.local.json"),n=await po(t);if(n&&typeof n=="object"){let r=n;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var Lc=/^\[mcp_servers\.([^\]]+)\]/;function Fc(o){let e=o.split(`
133
- `),t=[],n=null;for(let r of e){let i=r.match(Lc);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
102
+ Include property and bindings when the decision context has class-level evidence.`}var co=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,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 Cc}from"child_process";import{readFile as qi}from"fs/promises";import{homedir as ur}from"os";import{join as et}from"path";var mr=/popmelt/i;function Mt(){return{found:!1,name:null,scope:null,disabled:!1}}function Kt(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function vn(o){for(let e of Object.keys(o))if(mr.test(e))return e;return null}async function lo(o){try{let e=await qi(o,"utf-8");return JSON.parse(e)}catch{return null}}async function fr(o){let e=ur(),t=await lo(et(e,".claude.json"));if(t&&typeof t=="object"){let r=t;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=vn(r.mcpServers);if(i)return Kt(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=vn(a.mcpServers);if(c){let p=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(b=>mr.test(b));return Kt(c,"project",p)}}}}}let n=await lo(et(o,".mcp.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=vn(r.mcpServers);if(s){let a=await Bi(o,s);return Kt(s,"mcp.json",a)}}let i=vn(r);if(i&&i!=="mcpServers"){let s=await Bi(o,i);return Kt(i,"mcp.json",s)}}return Mt()}async function Bi(o,e){let t=et(o,".claude","settings.local.json"),n=await lo(t);if(n&&typeof n=="object"){let r=n;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var $c=/^\[mcp_servers\.([^\]]+)\]/;function Oc(o){let e=o.split(`
103
+ `),t=[],n=null;for(let r of e){let i=r.match($c);i?(n&&t.push({name:n.name,body:n.bodyLines.join(`
134
104
  `)}),n={name:i[1],bodyLines:[]}):r.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
135
105
  `)}),n=null):n&&n.bodyLines.push(r)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
136
- `)}),t}function Uc(o){return/enabled\s*=\s*false/i.test(o)}async function hr(o){let e=process.env.CODEX_HOME||tt(ur(),".codex"),t=await qi(tt(e,"config.toml"),"user");if(t.found)return t;let n=await qi(tt(o,".codex","config.toml"),"project");return n.found?n:jt()}async function gr(o,e="copilot"){let t=await zc(e);if(t.found)return t;let n=process.env.COPILOT_HOME||tt(ur(),".copilot"),r=await pr(tt(n,"mcp-config.json"),"user");if(r.found)return r;let i=await pr(tt(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await pr(tt(o,".github","mcp.json"),"mcp.json");return s.found?s:jt()}async function zc(o){try{let e=await new Promise((t,n)=>{qc(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return Fi(JSON.parse(e),"user")}catch{return jt()}}async function pr(o,e){let t=await po(o);return Fi(t,e)}function Fi(o,e){if(!o||typeof o!="object")return jt();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=vn(n);return r?Kt(r,e):jt()}async function qi(o,e){try{let t=await Li(o,"utf-8"),n=Fc(t);for(let r of n)if(mr.test(r.name)){let i=Uc(r.body);return Kt(r.name,e,i)}}catch{}return jt()}import{execFile as Ui}from"child_process";import{mkdir as Vc,readFile as zi,writeFile as Vi}from"fs/promises";import{homedir as Wi}from"os";import{dirname as Wc,join as yr}from"path";var Ir="https://mcp.popmelt.com/mcp";async function Ki(o=Ir){let e=yr(Wi(),".claude.json"),t;try{let r=await zi(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 Vi(e,JSON.stringify(t,null,2)+`
137
- `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Gi(o=Ir){let e=process.env.CODEX_HOME||yr(Wi(),".codex"),t=yr(e,"config.toml"),n;try{n=await zi(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Vc(Wc(t),{recursive:!0});let r=`
106
+ `)}),t}function Dc(o){return/enabled\s*=\s*false/i.test(o)}async function hr(o){let e=process.env.CODEX_HOME||et(ur(),".codex"),t=await Ji(et(e,"config.toml"),"user");if(t.found)return t;let n=await Ji(et(o,".codex","config.toml"),"project");return n.found?n:Mt()}async function gr(o,e="copilot"){let t=await Nc(e);if(t.found)return t;let n=process.env.COPILOT_HOME||et(ur(),".copilot"),r=await pr(et(n,"mcp-config.json"),"user");if(r.found)return r;let i=await pr(et(o,".mcp.json"),"mcp.json");if(i.found)return i;let s=await pr(et(o,".github","mcp.json"),"mcp.json");return s.found?s:Mt()}async function Nc(o){try{let e=await new Promise((t,n)=>{Cc(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return Li(JSON.parse(e),"user")}catch{return Mt()}}async function pr(o,e){let t=await lo(o);return Li(t,e)}function Li(o,e){if(!o||typeof o!="object")return Mt();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,r=vn(n);return r?Kt(r,e):Mt()}async function Ji(o,e){try{let t=await qi(o,"utf-8"),n=Oc(t);for(let r of n)if(mr.test(r.name)){let i=Dc(r.body);return Kt(r.name,e,i)}}catch{}return Mt()}import{execFile as Fi}from"child_process";import{mkdir as Bc,readFile as Ui,writeFile as zi}from"fs/promises";import{homedir as Vi}from"os";import{dirname as Jc,join as yr}from"path";var Ir="https://mcp.popmelt.com/mcp";async function Wi(o=Ir){let e=yr(Vi(),".claude.json"),t;try{let r=await Ui(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 zi(e,JSON.stringify(t,null,2)+`
107
+ `,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Ki(o=Ir){let e=process.env.CODEX_HOME||yr(Vi(),".codex"),t=yr(e,"config.toml"),n;try{n=await Ui(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Bc(Jc(t),{recursive:!0});let r=`
138
108
  [mcp_servers.popmelt]
139
109
  url = "${o}"
140
- `;return await Vi(t,n+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Hi(o=Ir,e="copilot"){let t=await Kc(e);if(Gc(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,r)=>{Ui(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 Kc(o){try{let e=await new Promise((t,n)=>{Ui(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){n(r);return}t(i)})});return JSON.parse(e)}catch{return null}}function Gc(o){if(!o||typeof o!="object")return!1;let e=o,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}var uo=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 Hc=String.raw`
110
+ `;return await zi(t,n+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Gi(o=Ir,e="copilot"){let t=await qc(e);if(Lc(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,r)=>{Fi(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 qc(o){try{let e=await new Promise((t,n)=>{Fi(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 Lc(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 po=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 Fc=String.raw`
141
111
  (() => {
142
112
  const hidden = [];
143
113
  const visit = (root) => {
@@ -158,7 +128,7 @@ url = "${o}"
158
128
  visit(document);
159
129
  window.__popmeltNativeCaptureHidden = hidden;
160
130
  })()
161
- `,Qc=String.raw`
131
+ `,Uc=String.raw`
162
132
  (() => {
163
133
  for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
164
134
  if (value) element.style.setProperty('visibility', value, priority);
@@ -166,20 +136,20 @@ url = "${o}"
166
136
  }
167
137
  delete window.__popmeltNativeCaptureHidden;
168
138
  })()
169
- `;function mo(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Xc(o,e){let t=mo(e);if(!t)return null;let n=new URL(t),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&mo(s.url)),i=r.find(s=>mo(s.url)===t);return i||(r.find(s=>{let a=new URL(mo(s.url));return a.origin===n.origin&&a.pathname===n.pathname})??null)}function Yc(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 Zc(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 el(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 tl(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}),p=>{p&&(clearTimeout(c),t.delete(a),s(p))})})}async function Qi(o,e){let t=Yc(e.clip),n=await Zc(o),r=Xc(n,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await el(r.webSocketDebuggerUrl),s=tl(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Hc,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))}}),p=typeof c.data=="string"?c.data:"";if(!p)throw new Error("CDP returned an empty screenshot");return Buffer.from(p,"base64")}finally{a&&await s("Runtime.evaluate",{expression:Qc,returnByValue:!0}).catch(()=>{}),i.close()}}function Xi(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 Yi(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 wr(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 nl(o),i=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),a,c,p,b,S,v,P,T,h,u,g,y,l,j,f=[],m=[],E=0,D=[];for(;E<r.length;){let k=r.indexOf(i,E);if(k===-1)break;let O=k+i.length;if(r.slice(k,k+s.length).equals(s))break;let K=O;r[K]===13&&r[K+1]===10&&(K+=2);let H=r.indexOf(`\r
139
+ `;function uo(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function zc(o,e){let t=uo(e);if(!t)return null;let n=new URL(t),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&uo(s.url)),i=r.find(s=>uo(s.url)===t);return i||(r.find(s=>{let a=new URL(uo(s.url));return a.origin===n.origin&&a.pathname===n.pathname})??null)}function Vc(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 Wc(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 Kc(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 Gc(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}),p=>{p&&(clearTimeout(c),t.delete(a),s(p))})})}async function Hi(o,e){let t=Vc(e.clip),n=await Wc(o),r=zc(n,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Kc(r.webSocketDebuggerUrl),s=Gc(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Fc,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))}}),p=typeof c.data=="string"?c.data:"";if(!p)throw new Error("CDP returned an empty screenshot");return Buffer.from(p,"base64")}finally{a&&await s("Runtime.evaluate",{expression:Uc,returnByValue:!0}).catch(()=>{}),i.close()}}function Qi(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 Xi(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 wr(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 Hc(o),i=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),a,c,p,b,S,w,P,T,h,u,g,y,l,M,f=[],m=[],j=0,D=[];for(;j<r.length;){let k=r.indexOf(i,j);if(k===-1)break;let O=k+i.length;if(r.slice(k,k+s.length).equals(s))break;let K=O;r[K]===13&&r[K+1]===10&&(K+=2);let H=r.indexOf(`\r
170
140
  \r
171
- `,K);if(H===-1)break;let _=r.slice(K,H).toString("utf-8"),W=H+4,G=r.indexOf(i,W),fe=G!==-1?G-2:r.length;D.push({headers:_,body:r.slice(W,fe)}),E=G!==-1?G:r.length}for(let k of D){let O=k.headers.match(/name="([^"]+)"/);if(!O)continue;let K=O[1];if(K==="screenshot")a=k.body;else if(K==="feedback")c=k.body.toString("utf-8");else if(K==="color")p=k.body.toString("utf-8");else if(K==="provider")b=k.body.toString("utf-8");else if(K==="model")S=k.body.toString("utf-8");else if(K==="reasoningEffort")v=k.body.toString("utf-8");else if(K==="serviceTier")P=k.body.toString("utf-8");else if(K==="goal")T=k.body.toString("utf-8");else if(K==="pageUrl")h=k.body.toString("utf-8");else if(K==="viewport")u=k.body.toString("utf-8");else if(K==="planId")g=k.body.toString("utf-8");else if(K==="manifest")y=k.body.toString("utf-8");else if(K==="tasks")l=k.body.toString("utf-8");else if(K==="sourceId")j=k.body.toString("utf-8");else if(K.startsWith("screenshot-")){let H=K.slice(11);try{let _=decodeURIComponent(H);m.push({pathname:_,data:k.body})}catch{}}else if(K.startsWith("image-")){let H=K.split("-"),_=parseInt(H[H.length-1],10),W=H.slice(1,-1).join("-");W&&!isNaN(_)&&f.push({annotationId:W,index:_,data:k.body})}}if(!a)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:a,feedback:c,color:p,provider:b,model:S,reasoningEffort:v,serviceTier:P,goal:T,pageUrl:h,viewport:u,planId:g,manifest:y,tasks:l,sourceId:j,pastedImages:f,pageScreenshots:m}}function nl(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 ol}from"crypto";var bn="<orientation>",dt="</orientation>";function Gt(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 Zi(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function es(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(bn,t);if(n<0){Zi(e,o.slice(t));break}Zi(e,o.slice(t,n));let r=n+bn.length,i=Gt(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 rl=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),il=new Set(["strengthened","weakened","mixed","unknown"]);function xn(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 sl(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function ts(o,e,t,n=Date.now()){let r=sl(o);if(!r)return null;let i=typeof r.transition=="string"&&rl.has(r.transition)?r.transition:null,s=xn(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&il.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:ol(),jobId:e,sequence:t,timestamp:n,transition:i,snapshot:{focus:s,seeking:xn(r.seeking),workingHypothesis:xn(r.workingHypothesis),evidencePosture:a,update:xn(r.update),nextObservation:xn(r.nextObservation)},contextPolicy:"exclude"}}function vr(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function br(o,e,t=0){let n=[],r=[],i=new Set,s=t;for(let c of es(o)){if(c.kind==="text"){c.text&&r.push(c);continue}try{let p=ts(JSON.parse(c.json),e,s);if(!p)continue;let b=vr(p);if(i.has(b))continue;i.add(b),n.push(p),r.push({kind:"orientation",orientation:p}),s++}catch{}}return{visibleText:r.map(c=>c.kind==="text"?c.text:`
141
+ `,K);if(H===-1)break;let E=r.slice(K,H).toString("utf-8"),W=H+4,G=r.indexOf(i,W),fe=G!==-1?G-2:r.length;D.push({headers:E,body:r.slice(W,fe)}),j=G!==-1?G:r.length}for(let k of D){let O=k.headers.match(/name="([^"]+)"/);if(!O)continue;let K=O[1];if(K==="screenshot")a=k.body;else if(K==="feedback")c=k.body.toString("utf-8");else if(K==="color")p=k.body.toString("utf-8");else if(K==="provider")b=k.body.toString("utf-8");else if(K==="model")S=k.body.toString("utf-8");else if(K==="reasoningEffort")w=k.body.toString("utf-8");else if(K==="serviceTier")P=k.body.toString("utf-8");else if(K==="goal")T=k.body.toString("utf-8");else if(K==="pageUrl")h=k.body.toString("utf-8");else if(K==="viewport")u=k.body.toString("utf-8");else if(K==="planId")g=k.body.toString("utf-8");else if(K==="manifest")y=k.body.toString("utf-8");else if(K==="tasks")l=k.body.toString("utf-8");else if(K==="sourceId")M=k.body.toString("utf-8");else if(K.startsWith("screenshot-")){let H=K.slice(11);try{let E=decodeURIComponent(H);m.push({pathname:E,data:k.body})}catch{}}else if(K.startsWith("image-")){let H=K.split("-"),E=parseInt(H[H.length-1],10),W=H.slice(1,-1).join("-");W&&!isNaN(E)&&f.push({annotationId:W,index:E,data:k.body})}}if(!a)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:a,feedback:c,color:p,provider:b,model:S,reasoningEffort:w,serviceTier:P,goal:T,pageUrl:h,viewport:u,planId:g,manifest:y,tasks:l,sourceId:M,pastedImages:f,pageScreenshots:m}}function Hc(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 Qc}from"crypto";var bn="<orientation>",at="</orientation>";function Gt(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 Yi(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function Zi(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(bn,t);if(n<0){Yi(e,o.slice(t));break}Yi(e,o.slice(t,n));let r=n+bn.length,i=Gt(o,r);if(i.status!=="complete"){let a=o.indexOf(at,r);if(a>=0){t=a+at.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(at,s)&&(t=s+at.length)}return e}var Xc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Yc=new Set(["strengthened","weakened","mixed","unknown"]);function xn(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 Zc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function es(o,e,t,n=Date.now()){let r=Zc(o);if(!r)return null;let i=typeof r.transition=="string"&&Xc.has(r.transition)?r.transition:null,s=xn(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&Yc.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Qc(),jobId:e,sequence:t,timestamp:n,transition:i,snapshot:{focus:s,seeking:xn(r.seeking),workingHypothesis:xn(r.workingHypothesis),evidencePosture:a,update:xn(r.update),nextObservation:xn(r.nextObservation)},contextPolicy:"exclude"}}function vr(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function br(o,e,t=0){let n=[],r=[],i=new Set,s=t;for(let c of Zi(o)){if(c.kind==="text"){c.text&&r.push(c);continue}try{let p=es(JSON.parse(c.json),e,s);if(!p)continue;let b=vr(p);if(i.has(b))continue;i.add(b),n.push(p),r.push({kind:"orientation",orientation:p}),s++}catch{}}return{visibleText:r.map(c=>c.kind==="text"?c.text:`
172
142
 
173
143
  `).join("").replace(/\n{3,}/g,`
174
144
 
175
- `).trim(),orientations:n,segments:r}}function al(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 p=this.buffer.slice(c);if(dt.startsWith(p)&&p.length<dt.length||(p.startsWith(dt)&&(this.buffer=this.buffer.slice(c+dt.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(bn);if(r<0){let c=al(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+bn.length,s=Gt(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=ts(JSON.parse(a),this.jobId,this.sequence);if(!c)continue;let p=vr(c);if(this.signatures.has(p))continue;this.signatures.add(p),n.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=br(e,this.jobId,this.sequence),n=t.orientations.filter(r=>{let i=vr(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}}},ns=`## Public orientation updates
145
+ `).trim(),orientations:n,segments:r}}function el(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 mo=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 p=this.buffer.slice(c);if(at.startsWith(p)&&p.length<at.length||(p.startsWith(at)&&(this.buffer=this.buffer.slice(c+at.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(bn);if(r<0){let c=el(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+bn.length,s=Gt(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=es(JSON.parse(a),this.jobId,this.sequence);if(!c)continue;let p=vr(c);if(this.signatures.has(p))continue;this.signatures.add(p),n.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=br(e,this.jobId,this.sequence),n=t.orientations.filter(r=>{let i=vr(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},ts=`## Public orientation updates
176
146
  During meaningful transitions in the work, emit a brief public coordination update using this exact form:
177
147
  <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
148
 
179
149
  Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
180
150
  Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
181
151
 
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 os=`## Project collaboration history
152
+ These are public collaboration signals, not private reasoning. Keep each field concrete and short. Report only meaningful changes, generally after consequential tool evidence or a major plan change. Do not emit heartbeats, hidden reasoning, chain-of-thought, confidence scores, or a narration of every tool call. Do not repeat an unchanged orientation. Orientation blocks are UI metadata and should not be referenced in the conversational answer.`;var ns=`## Project collaboration history
183
153
  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
154
 
185
155
  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.
@@ -190,29 +160,29 @@ Use Popmelt history to explain why a decision was made or how shared understandi
190
160
 
191
161
  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 Sn(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let r of o.annotations){let i=r.elements.map(p=>{let b=[p.selector];return p.reactComponent&&b.push(`(${p.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 p of a)n.push(` Attached image: use the Read tool to view ${p}`);let c=t?.[r.id];if(c?.length)for(let p of c)n.push(` Attached context (${p.name}, ${p.mimeType}): use the Read tool to inspect ${p.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
162
  ### ${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 rs(o,e,t){let n=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!i&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let a of t.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${a.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),a.feedbackSummary&&n.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&n.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${a.question}"`);else{if(n.push(`### Round ${s} (assistant)`),a.responseText&&n.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let c of a.resolutions){let p=c.finalScope??c.inferredScope,b=p?` [${p.breadth} ${p.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 v=S,P=v.scope||"general";b.has(P)||b.set(P,[]),b.get(P).push(v.text)}for(let[S,v]of b){n.push(`**${S.charAt(0).toUpperCase()+S.slice(1)}**`);for(let P of v)n.push(`- ${P}`)}}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 p=c.pathname||new URL(e.url).pathname;a.has(p)||a.set(p,[]),a.get(p).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,p]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:p,styleModifications:e.styleModifications},v=Sn(S,t?.imagePaths,t?.attachmentFiles);v&&(n.push(""),n.push(v))}}else{let s=Sn(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 is(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ss(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 dl(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 cl(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&&!dl(e[t]))return!1;return!0}function as(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(cl)}catch{return[]}}function ll(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 ds(o,e){return e>0?ll(o):[]}import{execFile as pl}from"child_process";import{readdir as ul,readFile as ml,stat as fl}from"fs/promises";import{homedir as Tn}from"os";import{join as nt}from"path";var go=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:cs()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:cs()}],kn=[{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"}],Rn={id:"",label:"Default",source:"cli"},hl=/^\s*-\s+"([^"]+)"/;function gl(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(hl);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:xr(i),source:"cli"})}return yo([Rn,...e])}function yl(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():xr(r),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let p=c;return typeof p.effort!="string"?[]:[{effort:p.effort,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0,a=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let p=c;return typeof p.id!="string"?[]:[{id:p.id,label:typeof p.name=="string"?p.name:p.id,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function cs(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Il(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return yo(e.map(t=>({id:t,label:xr(t),source:"cli"})))}function xr(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":xl(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 ls(o="copilot"){let e=await ho(o,["help","config"]),t=gl(e);return t.length>1?t:[Rn]}async function ps(o="codex"){let e=await ho(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||nt(Tn(),".codex");return ms(nt(n,"models_cache.json"))}),t=yl(e);return t.length>0?yo([...t,...kn]):kn}async function us(o="claude"){let e=nt(Tn(),".claude"),t=[nt(Tn(),".claude","stats-cache.json"),nt(Tn(),".claude","settings.json"),nt(Tn(),".claude.json"),nt(e,"cache","changelog.md")],[n,r,i]=await Promise.all([ho(o,["--help"]).catch(()=>""),ho(o,["--version"]).catch(()=>""),wl(e).catch(()=>[])]),s=bl([...t,...i]),a=await Promise.all(s.map(p=>ms(p).catch(()=>""))),c=Il([n,r,...a].join(`
197
- `));return yo([...go,...c])}function ho(o,e,t=5e3){return new Promise((n,r)=>{pl(o,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}n(s)})})}async function ms(o){return ml(o,"utf-8")}async function wl(o){let e=[nt(o,"projects"),nt(o,"telemetry")],t=[];for(let n of e)await fs(n,t,4);return t.sort((n,r)=>r.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function fs(o,e,t){if(t<0)return;let n;try{n=await ul(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async r=>{let i=nt(o,r.name);if(r.isDirectory()){await fs(i,e,t-1);return}if(!(!r.isFile()||!vl(r.name)))try{let s=await fl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function vl(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 bl(o){return[...new Set(o)]}function xl(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 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 Sl}from"crypto";var Ht="<imprint-use>",wo="</imprint-use>";function Tl(o){let e=Math.min(o.length,Ht.length-1);for(let t=e;t>0;t--)if(Ht.startsWith(o.slice(-t)))return t;return 0}function hs(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 p=e?.explanations.find(b=>b.id===c);return p?[{id:p.id,kind:p.kind,statement:p.statement,state:p.state,scope:p.scope}]:[]});return a.length===0?null:{id:Sl(),jobId:t,sequence:n,timestamp:r,explanations:a}}var vo=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 p=this.buffer.slice(c);if(wo.startsWith(p)&&p.length<wo.length||(p.startsWith(wo)&&(this.buffer=this.buffer.slice(c+wo.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(Ht);if(r<0){let c=Tl(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+Ht.length,s=Gt(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=hs(JSON.parse(a),this.context,this.jobId,this.sequence);if(!c)continue;let p=this.takeNewExplanations(c);p&&n.push(p)}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(Ht,r);if(i<0){n+=e.slice(r);break}n+=e.slice(r,i);let s=i+Ht.length,a=Gt(e,s);if(a.status!=="complete"){r=s;continue}try{let b=hs(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 p=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+p}return{visibleText:n.trim(),usages:t}}};function gs(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 Sr(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 ys(o){let e=Sr(bo(o.origin));if(e)return e;let t=Sr(bo(o.referer));if(t)return t;let n=bo(o["x-forwarded-host"]);if(!n)return null;let r=bo(o["x-forwarded-proto"])==="https"?"https":"http";return Sr(`${r}://${n}`)}function Is(o,e,t=5){let n=(c,p)=>(p.completedAt??p.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,p)=>p.updatedAt-c.updatedAt).slice(0,10),a=s.reduce((c,p)=>(c[p.status]=(c[p.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{createHash as To}from"crypto";import{mkdir as Mn,readFile as At,unlink as Al,writeFile as Qt}from"fs/promises";import{dirname as ko,extname as El,join as Je}from"path";var kl={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function Rl(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function ws(o,e){let t=e??Rl(o);return{kind:t,...kl[t]}}import{createHash as Pl,randomUUID as Ml}from"crypto";var vs=o=>`${o}-${Ml()}`;function Tr(o,...e){return`${o}-${Pl("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function kr(o){return{schemaVersion:1,submissionIds:[vs("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function Pn(o,e=[],t){return{...o,outcomeId:o.outcomeId??vs("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function jl(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function xo(o,e){return e?[`${o||"/"}:${e}`]:[]}function bs(o){let e=jl(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 xs(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=Tr("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?[Tr("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Tr("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Rr(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=So(o.id,t)||e;return e}function Ss(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:o.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var _l={version:1,threads:{}},Ts=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],jn={version:2,updatedAt:0,files:{}};function Cl(o){return JSON.stringify(o,null,2)}function $l(o){return Object.fromEntries(Ts.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Ol(o){let e={...o};for(let t of Ts)delete e[t];return e}function Xt(o){let e=o;if(o.error){let t=ws(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=Ct(e.result,!1),n=Ct(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 Ro=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 At(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=Rr(r)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await At(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(Xt)}]))},this.index={...jn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Rr(t);return await this.persistAll(),this.cache}}catch{}return this.cache={..._l,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 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&&(So(e,t),r.messages.push(Xt(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;So(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Xt(t)):r.messages.push(Xt(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=Xt(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},p=r.messages.findLastIndex(u=>!!c(u)),b=r.messages.findLastIndex(u=>u.role==="human"),S=p>b?c(r.messages[p]):void 0,v=r.messages.at(-1)?.role,P=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:v,pendingQuestion:S,acknowledgedJobIds:P,elementIdentifiers:r.elementIdentifiers,lifecycle:Ss(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=Pn(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 At(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 At(Je(ko(this.legacyFilePath),r.path),"utf8");To("sha256").update(a).digest("hex")===r.sha256&&(s=JSON.parse(a))}catch{}return Xt({...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=$l(e),n=Ol(e);if(Object.keys(t).length===0)return n;let r=Cl(t),i=To("sha256").update(r).digest("hex"),s=Je("artifacts","thread-messages",`${i}.json`);await Mn(this.artifactsDir,{recursive:!0});try{await At(Je(ko(this.legacyFilePath),s),"utf8")}catch{await Qt(Je(ko(this.legacyFilePath),s),r)}return{...n,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async n=>{if(ko(n)===this.mediaDir)return n;try{let r=await At(n),i=To("sha256").update(r).digest("hex"),s=Je(this.mediaDir,`${i}${El(n)||".bin"}`);await Mn(this.mediaDir,{recursive:!0});try{await At(s)}catch{await Qt(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 Mn(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`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Qt(Je(this.threadsDir,n),JSON.stringify(i,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Qt(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 Mn(this.threadsDir,{recursive:!0}),this.index=this.index??{...jn,files:{}},await Qt(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 Al(Je(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await Mn(this.threadsDir,{recursive:!0}),await Qt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as Dl,open as Nl,readFile as Bl,rename as Jl,unlink as ql}from"fs/promises";import{dirname as Ll,join as Fl}from"path";var ks={schemaVersion:1,theme:"auto",updatedAt:null};function Rs(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Ul(o,e){await Dl(Ll(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await Nl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
198
- `,"utf8"),await n.sync()}finally{await n.close()}await Jl(t,o)}catch(n){throw await ql(t).catch(()=>{}),n}}var Po=class{constructor(e){this.path=Fl(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Bl(this.path,"utf8")),t=Rs(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...ks}}}catch{return{exists:!1,preferences:{...ks}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Ul(this.path,t),t}};function Ps(o){return Rs(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 Yt(o){return o?[ht(o.selector,400),ht(o.context,200),ht(o.reactComponent,120),ht(o.textContent)].filter(e=>!!e):[]}function Pr(o){return[...new Set(o.filter(e=>!!e))]}function Ms(o,e){return Pr([...e,...o.annotations.flatMap(t=>[ht(t.pathname,200),ht(t.linkedSelector,400),...t.elements.flatMap(Yt)]),...o.styleModifications.flatMap(t=>Yt(t.element)),...(o.textModifications??[]).flatMap(t=>Yt(t.element)),...(o.domModifications??[]).flatMap(t=>[...Yt(t.element),...Yt(t.sourceElement)])])}function js(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Pr(t?[...e,...t.annotations.flatMap(n=>[ht(n.pathname,200),ht(n.linkedSelector,400),...n.elements.flatMap(Yt)])]:e)}function zl(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function As(o){let e=o.annotations.flatMap(r=>{let i=zl(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(`
163
+ `)}function os(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 p=c.finalScope??c.inferredScope,b=p?` [${p.breadth} ${p.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 w=S,P=w.scope||"general";b.has(P)||b.set(P,[]),b.get(P).push(w.text)}for(let[S,w]of b){n.push(`**${S.charAt(0).toUpperCase()+S.slice(1)}**`);for(let P of w)n.push(`- ${P}`)}}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 p=c.pathname||new URL(e.url).pathname;a.has(p)||a.set(p,[]),a.get(p).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,p]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:p,styleModifications:e.styleModifications},w=Sn(S,t?.imagePaths,t?.attachmentFiles);w&&(n.push(""),n.push(w))}}else{let s=Sn(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(`
164
+ `)}function rs(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function is(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(`
165
+ `)}function tl(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 nl(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&&!tl(e[t]))return!1;return!0}function ss(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(nl)}catch{return[]}}function ol(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 as(o,e){return e>0?ol(o):[]}import{execFile as rl}from"child_process";import{readdir as il,readFile as sl,stat as al}from"fs/promises";import{homedir as Tn}from"os";import{join as tt}from"path";var ho=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:ds()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:ds()}],kn=[{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"}],Rn={id:"",label:"Default",source:"cli"},dl=/^\s*-\s+"([^"]+)"/;function cl(o){let e=[],t=!1;for(let n of o.split(`
166
+ `)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let r=n.match(dl);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:xr(i),source:"cli"})}return go([Rn,...e])}function ll(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():xr(r),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let p=c;return typeof p.effort!="string"?[]:[{effort:p.effort,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0,a=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let p=c;return typeof p.id!="string"?[]:[{id:p.id,label:typeof p.name=="string"?p.name:p.id,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function ds(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function pl(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return go(e.map(t=>({id:t,label:xr(t),source:"cli"})))}function xr(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":hl(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 cs(o="copilot"){let e=await fo(o,["help","config"]),t=cl(e);return t.length>1?t:[Rn]}async function ls(o="codex"){let e=await fo(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||tt(Tn(),".codex");return us(tt(n,"models_cache.json"))}),t=ll(e);return t.length>0?go([...t,...kn]):kn}async function ps(o="claude"){let e=tt(Tn(),".claude"),t=[tt(Tn(),".claude","stats-cache.json"),tt(Tn(),".claude","settings.json"),tt(Tn(),".claude.json"),tt(e,"cache","changelog.md")],[n,r,i]=await Promise.all([fo(o,["--help"]).catch(()=>""),fo(o,["--version"]).catch(()=>""),ul(e).catch(()=>[])]),s=fl([...t,...i]),a=await Promise.all(s.map(p=>us(p).catch(()=>""))),c=pl([n,r,...a].join(`
167
+ `));return go([...ho,...c])}function fo(o,e,t=5e3){return new Promise((n,r)=>{rl(o,e,{encoding:"utf-8",timeout:t},(i,s)=>{if(i){r(i);return}n(s)})})}async function us(o){return sl(o,"utf-8")}async function ul(o){let e=[tt(o,"projects"),tt(o,"telemetry")],t=[];for(let n of e)await ms(n,t,4);return t.sort((n,r)=>r.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function ms(o,e,t){if(t<0)return;let n;try{n=await il(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async r=>{let i=tt(o,r.name);if(r.isDirectory()){await ms(i,e,t-1);return}if(!(!r.isFile()||!ml(r.name)))try{let s=await al(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function ml(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function go(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 fl(o){return[...new Set(o)]}function hl(o){return o.charAt(0).toUpperCase()+o.slice(1)}var yo=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 gl}from"crypto";var Ht="<imprint-use>",Io="</imprint-use>";function yl(o){let e=Math.min(o.length,Ht.length-1);for(let t=e;t>0;t--)if(Ht.startsWith(o.slice(-t)))return t;return 0}function fs(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 p=e?.explanations.find(b=>b.id===c);return p?[{id:p.id,kind:p.kind,statement:p.statement,state:p.state,scope:p.scope}]:[]});return a.length===0?null:{id:gl(),jobId:t,sequence:n,timestamp:r,explanations:a}}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 p=this.buffer.slice(c);if(Io.startsWith(p)&&p.length<Io.length||(p.startsWith(Io)&&(this.buffer=this.buffer.slice(c+Io.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(Ht);if(r<0){let c=yl(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+Ht.length,s=Gt(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=fs(JSON.parse(a),this.context,this.jobId,this.sequence);if(!c)continue;let p=this.takeNewExplanations(c);p&&n.push(p)}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(Ht,r);if(i<0){n+=e.slice(r);break}n+=e.slice(r,i);let s=i+Ht.length,a=Gt(e,s);if(a.status!=="complete"){r=s;continue}try{let b=fs(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 p=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+p}return{visibleText:n.trim(),usages:t}}};function hs(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function vo(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Sr(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 gs(o){let e=Sr(vo(o.origin));if(e)return e;let t=Sr(vo(o.referer));if(t)return t;let n=vo(o["x-forwarded-host"]);if(!n)return null;let r=vo(o["x-forwarded-proto"])==="https"?"https":"http";return Sr(`${r}://${n}`)}function ys(o,e,t=5){let n=(c,p)=>(p.completedAt??p.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,p)=>p.updatedAt-c.updatedAt).slice(0,10),a=s.reduce((c,p)=>(c[p.status]=(c[p.status]??0)+1,c),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{createHash as So}from"crypto";import{mkdir as Mn,readFile as jt,unlink as Sl,writeFile as Qt}from"fs/promises";import{dirname as To,extname as Tl,join as qe}from"path";var Il={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 wl(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 Is(o,e){let t=e??wl(o);return{kind:t,...Il[t]}}import{createHash as vl,randomUUID as bl}from"crypto";var ws=o=>`${o}-${bl()}`;function Tr(o,...e){return`${o}-${vl("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function kr(o){return{schemaVersion:1,submissionIds:[ws("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function Pn(o,e=[],t){return{...o,outcomeId:o.outcomeId??ws("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function xl(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function bo(o,e){return e?[`${o||"/"}:${e}`]:[]}function vs(o){let e=xl(o.url);return[...new Set([...o.annotations.flatMap(t=>bo(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>bo(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>bo(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>bo(t.pathname??e,t.durableSelector??t.selector))])]}function bs(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 xo(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=Tr("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?[Tr("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Tr("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Rr(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=xo(o.id,t)||e;return e}function xs(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 kl={version:1,threads:{}},Ss=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],jn={version:2,updatedAt:0,files:{}};function Rl(o){return JSON.stringify(o,null,2)}function Pl(o){return Object.fromEntries(Ss.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Ml(o){let e={...o};for(let t of Ss)delete e[t];return e}function Xt(o){let e=o;if(o.error){let t=Is(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=Ct(e.result,!1),n=Ct(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=qe(e,".popmelt");this.legacyFilePath=qe(t,"threads.json"),this.threadsDir=qe(t,"threads"),this.indexPath=qe(this.threadsDir,"index.json"),this.artifactsDir=qe(t,"artifacts","thread-messages"),this.mediaDir=qe(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[r,i]of Object.entries(e.files)){let s=await this.readThread(qe(this.threadsDir,i));s&&(t[r]=s)}this.cache={version:1,threads:t};let n=!1;for(let r of Object.values(t))n=Rr(r)||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(Xt)}]))},this.index={...jn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Rr(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...kl,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 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&&(xo(e,t),r.messages.push(Xt(t)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,t){let r=(await this.load()).threads[e];if(!r)return;xo(e,t);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Xt(t)):r.messages.push(Xt(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=Xt(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},p=r.messages.findLastIndex(u=>!!c(u)),b=r.messages.findLastIndex(u=>u.role==="human"),S=p>b?c(r.messages[p]):void 0,w=r.messages.at(-1)?.role,P=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:w,pendingQuestion:S,acknowledgedJobIds:P,elementIdentifiers:r.elementIdentifiers,lifecycle:xs(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=Pn(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 jt(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 jt(qe(To(this.legacyFilePath),r.path),"utf8");So("sha256").update(a).digest("hex")===r.sha256&&(s=JSON.parse(a))}catch{}return Xt({...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=Pl(e),n=Ml(e);if(Object.keys(t).length===0)return n;let r=Rl(t),i=So("sha256").update(r).digest("hex"),s=qe("artifacts","thread-messages",`${i}.json`);await Mn(this.artifactsDir,{recursive:!0});try{await jt(qe(To(this.legacyFilePath),s),"utf8")}catch{await Qt(qe(To(this.legacyFilePath),s),r)}return{...n,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let t=async n=>{if(To(n)===this.mediaDir)return n;try{let r=await jt(n),i=So("sha256").update(r).digest("hex"),s=qe(this.mediaDir,`${i}${Tl(n)||".bin"}`);await Mn(this.mediaDir,{recursive:!0});try{await jt(s)}catch{await Qt(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 Mn(this.threadsDir,{recursive:!0});let t=this.index??{...jn,files:{}},n=t.files[e.id]??`${So("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 Qt(qe(this.threadsDir,n),JSON.stringify(i,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Qt(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 Mn(this.threadsDir,{recursive:!0}),this.index=this.index??{...jn,files:{}},await Qt(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 Sl(qe(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await Mn(this.threadsDir,{recursive:!0}),await Qt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as jl,open as Al,readFile as El,rename as _l,unlink as Cl}from"fs/promises";import{dirname as $l,join as Ol}from"path";var Ts={schemaVersion:1,theme:"auto",updatedAt:null};function ks(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Dl(o,e){await jl($l(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await Al(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
168
+ `,"utf8"),await n.sync()}finally{await n.close()}await _l(t,o)}catch(n){throw await Cl(t).catch(()=>{}),n}}var Ro=class{constructor(e){this.path=Ol(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await El(this.path,"utf8")),t=ks(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Ts}}}catch{return{exists:!1,preferences:{...Ts}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Dl(this.path,t),t}};function Rs(o){return ks(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 Yt(o){return o?[ht(o.selector,400),ht(o.context,200),ht(o.reactComponent,120),ht(o.textContent)].filter(e=>!!e):[]}function Pr(o){return[...new Set(o.filter(e=>!!e))]}function Ps(o,e){return Pr([...e,...o.annotations.flatMap(t=>[ht(t.pathname,200),ht(t.linkedSelector,400),...t.elements.flatMap(Yt)]),...o.styleModifications.flatMap(t=>Yt(t.element)),...(o.textModifications??[]).flatMap(t=>Yt(t.element)),...(o.domModifications??[]).flatMap(t=>[...Yt(t.element),...Yt(t.sourceElement)])])}function Ms(o,e){let t=[...o].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Pr(t?[...e,...t.annotations.flatMap(n=>[ht(n.pathname,200),ht(n.linkedSelector,400),...n.elements.flatMap(Yt)])]:e)}function Nl(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function js(o){let e=o.annotations.flatMap(r=>{let i=Nl(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
169
 
200
170
  `);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
171
  ${i.map(s=>`- ${s}`).join(`
202
172
  `)}`).join(`
203
- `)}var Es={name:"@popmelt.com/core",version:"0.10.3",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 An=Es.version;var rp=1111,ip=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],sp=1800*1e3,ap=3600*1e3,$s=45e3,dp=5e3,cp=1e4,lp=2*1024*1024;function Os(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 En(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Ds(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 pp(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 qs(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 up(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,p;switch(i){case"Read":p=c?`Reading ${c}`:"Reading file";break;case"Edit":p=c?`Editing ${c}`:"Editing file";break;case"Write":p=c?`Writing ${c}`:"Writing file";break;case"Bash":p=a?a.split(`
205
- `)[0].trim().slice(0,60):"Running command";break;case"Glob":p="Searching files";break;case"Grep":p="Searching code";break;case"WebFetch":p="Fetching page";break;case"WebSearch":p="Searching web";break;default:p=i?`Using ${i}`:"tool";break}let b=s??a??void 0,S=s?Js(s)?s:np(e,s):void 0,v=n[n.length-1];v&&v.kind==="tool_group"&&v.tool===i?v.items.push({label:p,detail:b,...S?{filePath:S}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:p,detail:b,...S?{filePath:S}:{}}]})}return n}function mp(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 fp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Ns(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=>fp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function hp(o,e){let t=o.headers.origin;qs(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 gp=16384,yp=131072;async function $e(o,e=gp){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 Ip(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 wp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function vp(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 Ao(o,e){try{o.res.write(`event: ${e.type}
173
+ `)}var As={name:"@popmelt.com/core",version:"0.11.0",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"},"./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 An=As.version;var Ql=1111,Xl=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Yl=1800*1e3,Zl=3600*1e3,_s=45e3,ep=5e3,tp=1e4,np=2*1024*1024;function Cs(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
174
+ `)}function En(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function $s(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 op(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 Bs(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 rp(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,p;switch(i){case"Read":p=c?`Reading ${c}`:"Reading file";break;case"Edit":p=c?`Editing ${c}`:"Editing file";break;case"Write":p=c?`Writing ${c}`:"Writing file";break;case"Bash":p=a?a.split(`
175
+ `)[0].trim().slice(0,60):"Running command";break;case"Glob":p="Searching files";break;case"Grep":p="Searching code";break;case"WebFetch":p="Fetching page";break;case"WebSearch":p="Searching web";break;default:p=i?`Using ${i}`:"tool";break}let b=s??a??void 0,S=s?Ns(s)?s:Hl(e,s):void 0,w=n[n.length-1];w&&w.kind==="tool_group"&&w.tool===i?w.items.push({label:p,detail:b,...S?{filePath:S}:{}}):n.push({kind:"tool_group",tool:i,items:[{label:p,detail:b,...S?{filePath:S}:{}}]})}return n}function ip(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
176
+ `)}function sp(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Os(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=>sp(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function ap(o,e){let t=o.headers.origin;Bs(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 dp=16384,cp=131072;async function Oe(o,e=dp){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 lp(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 pp(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function up(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 jo(o,e){try{o.res.write(`event: ${e.type}
207
177
  data: ${JSON.stringify(e)}
208
178
 
209
- `)}catch{}}function Zt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function bp(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 xp(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 Ls(o={}){let e=new Date().toISOString(),t=o.port??rp,n=o.projectRoot??process.cwd(),r=await Hl(n).catch(()=>n),i=Kn(r),s=await yi(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??qe(Zl(),"popmelt-bridge"),p=o.maxTurns??40,b=o.maxBudgetUsd??1,S=[...o.allowedTools??ip],v=o.claudePath??"claude",P=o.copilotPath??"copilot",T=o.provider??"codex",h=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=o.restartMode??"embedded",y=t,l={},j={claude:v,codex:"codex",copilot:P};for(let[d,w]of Object.entries(j))try{let A=w.includes("/")?w:Wl("which",[w],{encoding:"utf-8"}).trim();l[d]={available:!0,path:A}}catch{l[d]={available:!1,path:null}}function f(d,w){return new Promise(A=>{let I=_s(w,["--version"],{stdio:["ignore","ignore","ignore"]}),M=!1,R=J=>{M||(M=!0,A(J))},N=setTimeout(()=>{I.kill("SIGTERM"),R(!0)},5e3);I.on("error",()=>{clearTimeout(N),R(!1)}),I.on("close",J=>{clearTimeout(N),R(J===0)})})}await Promise.all([(async()=>{l.claude&&(l.claude.models=l.claude.available&&l.claude.path?await us(l.claude.path).catch(()=>go):go)})(),(async()=>{l.codex&&(l.codex.models=l.codex.available&&l.codex.path?await ps(l.codex.path).catch(()=>kn):kn)})(),(async()=>{l.copilot&&(l.copilot.models=l.copilot.available&&l.copilot.path?await ls(l.copilot.path).catch(()=>[Rn]):[Rn])})()]);let[m,E,D]=await Promise.all([fr(r),hr(r),gr(r,l.copilot?.path??P)]);l.claude&&(l.claude.mcp=m),l.codex&&(l.codex.mcp=E),l.copilot&&(l.copilot.mcp=D),m.found&&m.name&&S.push(`mcp__${m.name}__*`),await Kl(c,{recursive:!0}),Bs(c).catch(()=>{});let k=new Io(1),O=new lo,K=new uo($s),H=null,_=0,W=!1,G=()=>{_+=1,W=!1,H&&clearTimeout(H),H=null},fe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(g!=="detached"||K.size>0||W)return;W=!0;let d=++_,w=Date.now()+cp,A=()=>{if(d!==_)return;if(K.size>0){G();return}if(!(k.isRunning||k.depth>0||O.isRunning||O.depth>0)||Date.now()>=w){W=!1,H=setTimeout(fe,50),H.unref?.();return}H=setTimeout(A,250),H.unref?.()};A()},oe=new Set,x=new Ro(r),$=await x.recoverInterruptedTurns();$>0&&console.warn(`[Popmelt] Recovered ${$} interrupted thread turn(s) from durable history.`);let q=new io(r);q.sweep();let B=new zt(r),Q=new Tt(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 Po(r),_e=new to(r),se=new co(r,{claudePath:v,provider:T,timeoutMs:h,loadProjectableDecisions:d=>B.getProjectableDecisions(d),onEvent:d=>{for(let w of oe)Ao(w,d)}}),Oe=new Wn({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:x,memoryService:B,imprintService:Q,loadConcreteModel:()=>se.loadModel()});B.beginAutomaticInitialization({writerVersion:An}).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 ${y}] Product memory is degraded; legacy preview remains available: ${d.error}`)});let gt=20,en=300*1e3,Me=[];function ot(){let d=Date.now()-en;for(;Me.length>0&&(Me[0].completedAt<d||Me.length>gt);)Me.shift()}let yt=new Map,It=null,_n;k.addListener((d,w,A)=>{for(let I of oe)(!A||!I.sourceId||I.sourceId===A)&&Ao(I,d)}),O.addListener((d,w,A)=>{for(let I of oe)(!A||!I.sourceId||I.sourceId===A)&&Ao(I,d)}),O.setProcessor(async d=>{let w=d.provider??T;try{let A=await se.run({provider:w,model:d.model,threadId:d.threadId,presentationJobId:d.id,agentSettings:d.agentSettings});if(d.status==="cancelled")return;let I=await se.loadRuns(),M=A.runId?I.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?Bi(N,J):null;if(N&&U){let F=N.decisionIds.map(L=>({decisionId:L,status:"projected"}));await B.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(L=>({path:L.path,value:L.value,decisionIds:L.decisionIds})),coverage:F}),await se.applySelectedModelProposal(N.id,U.map(L=>({path:L.path,value:L.value})),U.map(L=>({group:L.path[0]==="rules"||L.path[0]==="components"||L.path[0]==="tokens"?L.path[0]:"model",label:L.label??L.id,detail:L.rationale,path:L.path,value:L.value})),"automatic")}}let R=mp(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:w})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:R,model:d.model,provider:w})),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.
179
+ `)}catch{}}function Zt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function mp(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 fp(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 Js(o={}){let e=new Date().toISOString(),t=o.port??Ql,n=o.projectRoot??process.cwd(),r=await Ul(n).catch(()=>n),i=Wn(r),s=await gi(r),a=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Xe(Kl(),"popmelt-bridge"),p=o.maxTurns??40,b=o.maxBudgetUsd??1,S=[...o.allowedTools??Xl],w=o.claudePath??"claude",P=o.copilotPath??"copilot",T=o.provider??"codex",h=o.timeoutMs,u=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=o.restartMode??"embedded",y=t,l={},M={claude:w,codex:"codex",copilot:P};for(let[d,v]of Object.entries(M))try{let _=v.includes("/")?v:Jl("which",[v],{encoding:"utf-8"}).trim();l[d]={available:!0,path:_}}catch{l[d]={available:!1,path:null}}function f(d,v){return new Promise(_=>{let I=Es(v,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,R=J=>{A||(A=!0,_(J))},N=setTimeout(()=>{I.kill("SIGTERM"),R(!0)},5e3);I.on("error",()=>{clearTimeout(N),R(!1)}),I.on("close",J=>{clearTimeout(N),R(J===0)})})}await Promise.all([(async()=>{l.claude&&(l.claude.models=l.claude.available&&l.claude.path?await ps(l.claude.path).catch(()=>ho):ho)})(),(async()=>{l.codex&&(l.codex.models=l.codex.available&&l.codex.path?await ls(l.codex.path).catch(()=>kn):kn)})(),(async()=>{l.copilot&&(l.copilot.models=l.copilot.available&&l.copilot.path?await cs(l.copilot.path).catch(()=>[Rn]):[Rn])})()]);let[m,j,D]=await Promise.all([fr(r),hr(r),gr(r,l.copilot?.path??P)]);l.claude&&(l.claude.mcp=m),l.codex&&(l.codex.mcp=j),l.copilot&&(l.copilot.mcp=D),m.found&&m.name&&S.push(`mcp__${m.name}__*`),await ql(c,{recursive:!0}),Ds(c).catch(()=>{});let k=new yo(1),O=new co,K=new po(_s),H=null,E=0,W=!1,G=()=>{E+=1,W=!1,H&&clearTimeout(H),H=null},fe=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},X=()=>{if(g!=="detached"||K.size>0||W)return;W=!0;let d=++E,v=Date.now()+tp,_=()=>{if(d!==E)return;if(K.size>0){G();return}if(!(k.isRunning||k.depth>0||O.isRunning||O.depth>0)||Date.now()>=v){W=!1,H=setTimeout(fe,50),H.unref?.();return}H=setTimeout(_,250),H.unref?.()};_()},oe=new Set,x=new ko(r),C=await x.recoverInterruptedTurns();C>0&&console.warn(`[Popmelt] Recovered ${C} interrupted thread turn(s) from durable history.`);let q=new ro(r);q.sweep();let B=new zt(r),Q=new St(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 Ro(r),_e=new eo(r),se=new ao(r,{claudePath:w,provider:T,timeoutMs:h,loadProjectableDecisions:d=>B.getProjectableDecisions(d),onEvent:d=>{for(let v of oe)jo(v,d)}}),De=new Vn({projectRoot:r,storeId:s.storeId,projectId:i,threadStore:x,memoryService:B,imprintService:Q,loadConcreteModel:()=>se.loadModel()});B.beginAutomaticInitialization({writerVersion:An}).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 $e({provider:T,reason:"Project accepted decisions that were waiting when the bridge restarted"})):d.state==="degraded"&&console.warn(`[\u22B9 ${y}] Product memory is degraded; legacy preview remains available: ${d.error}`)});let gt=20,en=300*1e3,Me=[];function nt(){let d=Date.now()-en;for(;Me.length>0&&(Me[0].completedAt<d||Me.length>gt);)Me.shift()}let yt=new Map;k.addListener((d,v,_)=>{for(let I of oe)(!_||!I.sourceId||I.sourceId===_)&&jo(I,d)}),O.addListener((d,v,_)=>{for(let I of oe)(!_||!I.sourceId||I.sourceId===_)&&jo(I,d)}),O.setProcessor(async d=>{let v=d.provider??T;try{let _=await se.run({provider:v,model:d.model,threadId:d.threadId,presentationJobId:d.id,agentSettings:d.agentSettings});if(d.status==="cancelled")return;let I=await se.loadRuns(),A=_.runId?I.runs.find(N=>N.id===_.runId):void 0;if(_.success&&_.proposalId){let N=await se.findModelProposal(_.proposalId),J=await se.loadModel(),U=N?Ni(N,J):null;if(N&&U){let F=N.decisionIds.map(L=>({decisionId:L,status:"projected"}));await B.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:U.map(L=>({path:L.path,value:L.value,decisionIds:L.decisionIds})),coverage:F}),await se.applySelectedModelProposal(N.id,U.map(L=>({path:L.path,value:L.value})),U.map(L=>({group:L.path[0]==="rules"||L.path[0]==="components"||L.path[0]==="tokens"?L.path[0]:"model",label:L.label??L.id,detail:L.rationale,path:L.path,value:L.value})),"automatic")}}let R=ip(_,A);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})),_.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"}),nt();else{if(d.status="error",d.error=_.error??"Projection failed",d.threadId){let N=`Model projection failed.
210
180
 
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:w})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:N,error:d.error,model:d.model,provider:w})}O.broadcast({type:"error",jobId:d.id,threadId:d.threadId,message:d.error,provider:w,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 I=`Model projection failed.
181
+ ${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"}),nt()}}catch(_){if(d.status==="cancelled")return;if(d.status="error",d.error=_ instanceof Error?_.message:String(_),d.threadId){let I=`Model projection failed.
212
182
 
213
- ${d.error}`;await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:I,error:d.error,model:d.model,provider:w})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:I,error:d.error,model:d.model,provider:w})}O.broadcast({type:"error",jobId:d.id,threadId:d.threadId,message:d.error,provider:w,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()}}),k.setProcessor(async d=>{let w=d,A=w._replyPrompt,I=w._replyText,M=w._replyImagePaths,R=d.provider??T,N=!!(d.surfacedProposalIds?.length&&A),J=!N&&!["synthesize","project_model"].includes(d.kind??"");d.threadId&&I!==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=I??A,M&&M.length>0){F+=`
183
+ ${d.error}`;await x.updateMessage(d.threadId,d.id,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:I,error:d.error,model:d.model,provider:v})||await x.appendMessage(d.threadId,{role:"assistant",timestamp:Date.now(),jobId:d.id,responseText:I,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"}),nt()}}),k.setProcessor(async d=>{let v=d,_=v._replyPrompt,I=v._replyText,A=v._replyImagePaths,R=d.provider??T,N=!!(d.surfacedProposalIds?.length&&_),J=!N&&!["synthesize","project_model"].includes(d.kind??"");d.threadId&&I!==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&&_){if(F=I??_,A&&A.length>0){F+=`
214
184
 
215
- The developer attached reference images with their reply:`;for(let ee of M)F+=`
185
+ The developer attached reference images with their reply:`;for(let ee of A)F+=`
216
186
  Attached image: use the Read tool to view the image at: ${ee}`}d.kind==="synthesize"?F+=`
217
187
 
218
188
  Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:F+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(U)F=Sn(d.feedback,d.imagePaths,d.attachmentFiles)+`
@@ -221,17 +191,17 @@ Follow the developer's instructions. If they ask for changes, apply them to the
221
191
 
222
192
  After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(R!=="codex"?`
223
193
 
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??rs(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+=rn(d.memoryReview),J&&(F+=an(d.imprintContext,{requestText:I??$t(d.feedback)})),d.threadId&&!N&&(F+=`
194
+ IMPORTANT: First, use the Read tool to view the updated screenshot at: ${d.screenshotPath}`:"");else{let ee=!_&&d.threadId?await x.getThreadHistory(d.threadId):void 0,we=_?null:await se.loadModel();F=_??os(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+=rn(d.memoryReview),J&&(F+=an(d.imprintContext,{requestText:I??$t(d.feedback)})),d.threadId&&!N&&(F+=`
225
195
 
226
- ${os}`),F+=`
196
+ ${ns}`),F+=`
227
197
 
228
- ${ns}`;let L=vp(d.color,`[\u22B9 ${y}:${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(`${L} Reviewing ${ge} (provider: ${R})${d.threadId?` (thread: ${d.threadId})`:""}${U?` (resuming: ${U.slice(0,8)})`:""}`);let V=new fo(d.id),me=new vo(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&&(k.accumulateText(we,"response",Ue.visibleText),k.broadcast({...ee,text:Ue.visibleText},we,d.sourceId));for(let Ce of Ue.orientations)k.broadcast({type:"orientation",jobId:we,orientation:Ce},we,d.sourceId);for(let Ce of Ne.usages)k.broadcast({type:"imprint_used",jobId:we,usage:Ce},we,d.sourceId);return}else ee.type==="thinking"&&"text"in ee&&k.accumulateText(we,"thinking",ee.text);k.broadcast(ee,we,d.sourceId)},{process:Z,result:ye}=R==="codex"?eo(d.id,{prompt:F,projectRoot:r,screenshotPath:d.screenshotPath,resumeSessionId:U,model:d.model,sandboxMode:N?"read-only":void 0,configOverrides:Hn(d.agentSettings),onEvent:re}):R==="copilot"?Ei(d.id,{prompt:F,projectRoot:r,resumeSessionId:U,model:d.model,timeoutMs:h,copilotPath:l.copilot?.path??P,onEvent:re}):Qn(d.id,{prompt:F,projectRoot:r,maxTurns:p,maxBudgetUsd:b,allowedTools:N?["Read"]:S,claudePath:v,resumeSessionId:U,model:d.model,reasoningEffort:d.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:re});k.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=br(Re.visibleText,d.id),Y=V.finalize(Re.visibleText),ke=pe.visibleText,We=as(ke),Ie=J?sn(ke,{context:d.imprintContext,requestText:I??$t(d.feedback),applicationOccurred:be.length>0||We.some(ee=>ee.status==="resolved")}):{visibleText:ke,draft:void 0,error:void 0},Ke=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)k.broadcast({type:"orientation",jobId:d.id,orientation:ee},d.id,d.sourceId);for(let ee of Re.usages)k.broadcast({type:"imprint_used",jobId:d.id,usage:ee},d.id,d.sourceId);if(d.result=Ke,ne.success){console.log(`${L} Iteration complete`),ne.fileEdits&&ne.fileEdits.length>0&&console.log(`${L} 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(`${L} Captured ${ne.editEvents.length} edit event(s): ${ne.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),d.status="done";let ee=is(ke),we=We;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,bt)=>({...Ze,annotationId:d.annotationIds[bt%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=k.getBufferedEvents(d.id),Ce=up(Ue?.events??[],r,pe.segments),Ae,ie=Yi(ke),z=Xi(ke);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=ds(ke,be.length),ue,Ge,Er,_r,sa=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&&(Er=[...new Set(ce)]),Ze.length>0&&(_r=[...new Set(Ze)])}Ie.draft?.decision==="none"&&Q.recordNoop(Ie.draft.reason);let $n=Ie.draft?.decision==="recognize"?Ie.draft:void 0;if($n&&!z&&!ie){let de=d.imprintContext?.explanations.find(ce=>ce.id===$n.explanationId&&ce.state==="grounded");de?Ge={explanationId:de.id,title:$n.summary.title,detail:$n.summary.detail,statement:de.statement}:je={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let $o=Ie.draft?.decision==="mutate"||Ie.draft?.decision==="apply"?Ie.draft:void 0;if(d.threadId&&$o&&!z&&!ie)try{ue=await Q.capture($o,{threadId:d.threadId,jobId:d.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:sa,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(`${L} 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(`${L} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else $o&&(je={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});Ie.error&&console.warn(`${L} Ignored invalid imprint block: ${Ie.error}`),(je.state==="missing"||je.state==="invalid")&&Q.recordAssessmentFailure(je.state);let Oo=ue?.transactionId;if(d.threadId&&ue&&!ue.grounding){let de=await x.getThread(d.threadId),ce=new Set(ue.changes.map(bt=>bt.explanationId)),Ze=de?pp(de.messages,ce):void 0;if(Ze?.imprintSummary){let bt=Ze.imprintSummary;await x.updateAssistantMessage(d.threadId,Ze.jobId,{imprintSummary:{...bt,detail:ue.detail,changes:ue.changes,additionalObservationCount:(bt.additionalObservationCount??0)+1,coalescedTransactionIds:[...bt.coalescedTransactionIds??[],ue.transactionId]}}),ue=void 0}}let Do=on({question:ee,resolutions:we,changedFiles:be,decisionRequired:!!ie,imprintTransactionId:Oo,groundingRequired:!!ue?.grounding}),aa=Ce?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],_t=d.lifecycle?Pn(d.lifecycle,Oo?[Oo]:[],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.":Ke;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:aa,result:Do},result:Do,memoryReviewCard:ie??void 0,memoryReceipt:Ae,imprintSummary:ue,imprintRecognition:Ge,imprintUsedExplanationIds:Er,imprintAppliedExplanationIds:_r,modelDetails:ae.length>0?ae:void 0,model:d.model,provider:R,..._t?{lifecycle:_t}:{}})}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:I??($t(d.feedback)||"[request unavailable]"),responseSummary:ee??Ke,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=>Js(ce)?tp(r,ce):ce),resolutions:we.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:d.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:_t?.submissionIds,outcomeId:_t?.outcomeId,imprintEvidenceIds:_t?.imprintEvidenceIds,imprintAssessment:_t?.imprintAssessment})}catch(ce){console.warn(`${L} 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(`${L} \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"})`),k.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(`${L} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:d.id,patterns:ae,threadId:d.threadId},d.id,d.sourceId)),k.broadcast({type:"done",jobId:d.id,success:!0,resolutions:we.length>0?we:void 0,responseText:Ke,threadId:d.threadId,annotationIds:d.annotationIds,result:Do},d.id,d.sourceId),Me.push({id:d.id,status:"done",completedAt:Date.now(),threadId:d.threadId,annotationIds:d.annotationIds})}else console.error(`${L} 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:Pn(d.lifecycle)}:{}}),k.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=Yl(async(d,w)=>{if(hp(d,w),d.method==="OPTIONS"){w.writeHead(204),w.end();return}let A=d.url||"/",I=A.split("?")[0],M=new URL(A,`http://127.0.0.1:${y}`),R=M.pathname,N=wp(d,M);if(N&&N!==i){C(w,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:jo(r)});return}if(R.startsWith("/ambient/")&&N!==i){C(w,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:N});return}if(d.headers.origin){if(!qs(d.headers.origin)){C(w,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(N!==i){C(w,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:jo(r)});return}}try{if(R.startsWith("/ambient/"))await lt(d,w,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"),L=String(d.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!J||J.length>128||!/^[a-z0-9_-]+$/i.test(J)){C(w,400,{error:"A valid annotationId is required."});return}if(F!=="svg"&&F!=="text"||F==="svg"&&L!=="image/svg+xml"||F==="text"&&L!=="text/plain"){C(w,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await Ip(d,lp);if(ge.length===0){C(w,400,{error:"Attachment is empty."});return}let V=await q.stage({annotationId:J,name:U,mimeType:L,kind:F,data:ge});C(w,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 q.claim(U),C(w,200,{ok:!0})}else if(d.method==="DELETE"&&R.startsWith("/draft-attachments/"))await q.release([R.slice(19)]),C(w,200,{ok:!0});else if(d.method==="POST"&&R==="/send")await pt(d,w);else if(d.method==="POST"&&R==="/capture/native"){if(!u){C(w,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(w,400,{error:"pageUrl and clip are required."});return}let L=await Qi(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});w.writeHead(200,{"Content-Type":"image/webp","Content-Length":L.length,"Cache-Control":"no-store"}),w.end(L)}else if(d.method==="GET"&&R==="/events")wt(d,w);else if(d.method==="GET"&&R==="/status")await Eo(d,w,N);else if(d.method==="GET"&&R==="/ui-preferences")await tn(w);else if(d.method==="PATCH"&&R==="/ui-preferences")await Le(d,w);else if(d.method==="PATCH"&&R==="/config")await _o(d,w);else if(d.method==="POST"&&R==="/leases"){if(g!=="detached"){C(w,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(w,400,{error:"A valid leaseId is required."});return}G();let L=K.acquire(U,F);C(w,201,{ok:!0,lease:L,ttlMs:$s})}catch{C(w,400,{error:"Invalid lease request."})}}else if(R.startsWith("/leases/")&&(d.method==="PATCH"||d.method==="DELETE")){if(g!=="detached"){C(w,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(R.slice(8))}catch{C(w,400,{error:"Invalid lease id."});return}if(!J){C(w,400,{error:"A lease id is required."});return}if(d.method==="PATCH"){let U=K.heartbeat(J);if(!U){C(w,404,{error:"Lease not found."});return}C(w,200,{ok:!0,lease:U})}else{let U=K.release(J);C(w,U.found?200:404,{ok:U.found}),U.becameEmpty&&X()}}else if(d.method==="POST"&&R==="/shutdown"){if(g!=="detached"){C(w,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(w,200,{ok:!0}),setTimeout(fe,100)}else if(d.method==="POST"&&R==="/restart"){if(g!=="detached"){C(w,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(w,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of oe)try{J.res.end()}catch{}xe.close(()=>{_s(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(w,200,{providers:l});else if(R.startsWith("/imprint/"))await rt(d,w,R);else if(R.startsWith("/memory/"))await De(d,w,R);else if(d.method==="POST"&&R==="/mcp/install")await Gs(d,w);else if(d.method==="POST"&&R==="/reply")await ut(d,w);else if(d.method==="POST"&&R==="/cancel")Fe(d,w);else if(d.method==="POST"&&R==="/materialize")C(w,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(d.method==="GET"&&R==="/materialization-runs")C(w,410,{error:"Use /projection-runs."});else if(d.method==="GET"&&R==="/projection-runs"){let J=await se.loadRuns();C(w,200,J)}else if(d.method==="GET"&&R==="/projection/proposals"){let J=await se.loadModelProposals();C(w,200,J)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply-selected")){let J=R.slice(22,-15);await vt(J,d,w)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply")){let J=R.slice(22,-6);await Et(J,w)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/dismiss")){let J=R.slice(22,-8);await Co(J,d,w)}else if(R.startsWith("/model/proposals/"))C(w,410,{error:"Use /projection/proposals."});else if(d.method==="POST"&&R==="/model/component")await Hs(d,w);else if(d.method==="DELETE"&&R==="/model/component")await Qs(d,w);else if(d.method==="PATCH"&&R==="/model/token")await Xs(d,w);else if(d.method==="DELETE"&&R==="/model/token")await Ys(d,w);else if(d.method==="POST"&&R==="/model/consolidate")C(w,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(d.method==="POST"&&R==="/model/synthesize")C(w,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(w,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=k.getBufferedEvents(J,isNaN(U)?-1:U);F?C(w,200,F):C(w,404,{error:"Unknown job"})}else if(d.method==="GET"&&I.startsWith("/files/"))await na(I.slice(7),w);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(w,200,U)}else if(d.method==="GET"&&R.startsWith("/decision/")){let J=R.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))C(w,400,{error:"Invalid decision id"});else{let U=await x.getThread(J),F=[...U?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(U&&F?.annotationSnapshot){let L=[...U.messages].reverse().find(ge=>ge.resolutions?.length);C(w,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:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await _e.loadDecision(J);L?C(w,200,{decision:L,authority:"legacy_archive"}):C(w,404,{error:"Decision not found"})}}}else if(d.method==="GET"&&R.startsWith("/thread/")){let J=R.slice(8);await oa(J,w)}else if(d.method==="DELETE"&&R.startsWith("/thread/")){let J=R.slice(8);await ra(J,w)}else d.method==="GET"&&(R==="/canvas"||R==="/canvas/")?Zs(d,w):d.method==="GET"&&R==="/canvas/manifest"?await ea(w):d.method==="GET"&&R==="/canvas/app.mjs"?await ta(w):C(w,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),C(w,500,{error:J instanceof Error?J.message:"Internal error"})}});async function lt(d,w,A){if(d.method!=="POST"){C(w,405,{error:"Ambient endpoints accept POST requests only."});return}let I=await $e(d,yp),M=typeof I.sessionId=="string"?I.sessionId.trim():"",R=typeof I.turnId=="string"?I.turnId.trim():"",N=typeof I.executionOwner=="string"?I.executionOwner:void 0,J=ci(I.knowledgeView);if(A==="/ambient/context"){let U=typeof I.query=="string"?I.query.trim():"";if(!U){C(w,400,{error:"query is required."});return}let F=Array.isArray(I.subjectHints)?I.subjectHints.filter(L=>typeof L=="string"&&!!L.trim()).slice(0,20):void 0;C(w,200,await Oe.expandContext({query:U,subjectHints:F,knowledgeView:J}));return}if(A==="/ambient/turns/assess"){let U=typeof I.threadId=="string"?I.threadId.trim():"",F=typeof I.jobId=="string"?I.jobId.trim():"",L=typeof I.assessmentText=="string"?I.assessmentText.trim():"";if(!U||!F||!L){C(w,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(I.semanticCandidates)?I.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:L,semanticCandidates:ge});C(w,V.status==="recorded"?200:404,V);return}if(!M||!R||M.length>256||R.length>256){C(w,400,{error:"Valid sessionId and turnId values are required."});return}if(A==="/ambient/turns/prepare"){let U=typeof I.prompt=="string"?I.prompt.trim():"";if(!U){C(w,400,{error:"prompt is required."});return}C(w,200,await Oe.prepare({sessionId:M,turnId:R,prompt:U,model:typeof I.model=="string"?I.model:void 0,executionOwner:N,knowledgeView:J}));return}if(A==="/ambient/turns/event"){let U=typeof I.toolName=="string"?I.toolName.trim():"";if(!U){C(w,400,{error:"toolName is required."});return}C(w,200,await Oe.recordEvent({sessionId:M,turnId:R,executionOwner:N,toolName:U,toolUseId:typeof I.toolUseId=="string"?I.toolUseId:void 0,toolInput:I.toolInput,toolResponse:I.toolResponse}));return}if(A==="/ambient/turns/complete"){C(w,200,await Oe.complete({sessionId:M,turnId:R,executionOwner:N,lastAssistantMessage:typeof I.lastAssistantMessage=="string"?I.lastAssistantMessage:void 0,model:typeof I.model=="string"?I.model:void 0}));return}C(w,404,{error:"Ambient endpoint not found."})}async function De(d,w,A){try{if(d.method==="GET"&&A==="/memory/status"){C(w,200,await B.status());return}if(d.method==="GET"&&A==="/memory/diagnostics"){C(w,200,await B.diagnostics());return}if(d.method==="GET"&&A==="/memory/model-view"){C(w,200,await B.getModelView());return}if(d.method==="GET"&&A==="/memory/imprint-view"){let I=await x.load(),M=[...new Set(Object.values(I.threads).flatMap(R=>En(R.messages)))];C(w,200,await B.getImprintView(M,new Set(Object.keys(I.threads))));return}if(d.method==="POST"&&A==="/memory/constraints"){let I=await $e(d),M=typeof I.reactComponent=="string"?I.reactComponent.trim():"",R=await B.getModelView(),N=M?R.entries.filter(J=>J.key===`components.${M}`||J.key.startsWith(`components.${M}.`)):[];C(w,200,{modelEntries:N});return}if(d.method==="POST"&&A==="/memory/conversation-action"){let I=await $e(d),M=typeof I.threadId=="string"?I.threadId:"",R=typeof I.proposalId=="string"?I.proposalId:"",N=String(I.action);if(!M||!R||!["accept","edit_and_accept","reject","defer"].includes(N)){C(w,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),L=J?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await B.findPendingProposalsForThread(M)).find(pe=>pe.proposalId===R):void 0,ge=typeof I.kind=="string"&&["principle","preference","rule","constraint"].includes(I.kind)?I.kind:void 0,V=U?.kind??F?.proposedKind??L?.proposedKind??ge;if(!J||!U&&!F&&!L){C(w,409,{error:"This decision candidate was not surfaced in the thread."});return}if((N==="accept"||N==="edit_and_accept")&&!V){C(w,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 I.claim=="string"?I.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(w,400,{error:"Edited decision wording is required."});return}let ye=await B.commitConversationalReview(Z),ne=`memory-${ct().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:Zt(typeof I.provider=="string"?I.provider:void 0),model:typeof I.model=="string"?I.model:void 0}),ye.status==="committed"&&re&&await se.dismissModelProposal(re.id);let Re=Zt(typeof I.provider=="string"?I.provider:void 0);ye.status==="committed"&&ye.decisionId&&Re!=="copilot"&&await Ye({provider:Re,model:typeof I.model=="string"?I.model:void 0,agentSettings:Vt(I),threadId:M,reason:`Project accepted decision ${ye.decisionId}`}),C(w,ye.status==="committed"?200:409,{receipt:ye});return}if(d.method==="POST"&&A==="/memory/analyze"){let I=await $e(d),M=await B.analyzeLegacy({projectKey:typeof I.projectKey=="string"?I.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(w,200,{...M,issues:void 0,issueCounts:R});return}if(d.method==="POST"&&A==="/memory/review"){let I=await $e(d),M=await B.review(Xo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(w,200,M);return}if(d.method==="POST"&&A==="/memory/context"){let I=await $e(d),M=await B.contextualize(Xo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(w,200,M);return}if(d.method==="POST"&&A==="/memory/initialize"){let I=await $e(d),M=await B.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:An});C(w,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 I=await $e(d),M=await B.planReview(Qo(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});C(w,M.result.ok?200:422,M);return}if(d.method==="POST"&&A==="/memory/commit"){let I=await $e(d),M=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},R=await B.commitReview(Qo(I.command),{transactionId:typeof M.transactionId=="string"?M.transactionId:"",committedAt:typeof M.committedAt=="string"?M.committedAt:""});C(w,200,{status:await B.status(),journal:R.report});return}if(d.method==="POST"&&A==="/memory/recover"){let I=await $e(d),M=await B.recover(I.confirm===!0);C(w,200,{status:await B.status(),journal:M.report});return}C(w,404,{error:"Memory endpoint not found."})}catch(I){let M=I instanceof Error?I.message:String(I),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(w,R?409:400,{error:M});return}throw I}}async function rt(d,w,A){if(d.method==="GET"&&A==="/imprint/status"){let[I,M]=await Promise.all([Q.store.load(),x.load()]),R=[...new Set(Object.values(M.threads).flatMap(N=>En(N.messages)))].filter(N=>I.graph.explanations.some(J=>J.id===N&&J.state==="testing"));C(w,200,{state:"ready",head:I.graph.head,updatedAt:I.graph.updatedAt,explanationCount:I.graph.explanations.filter(N=>N.state!=="retired").length,concreteCount:I.graph.concrete.length,relationCount:I.graph.relations.length,pendingGroundingCount:R.length,recoveredTransactions:I.recoveredTransactions,admission:Q.diagnostics(),admissionWindowStartedAt:e});return}if(d.method==="POST"&&A==="/imprint/action"){let I=await $e(d),M=typeof I.threadId=="string"?I.threadId:"",R=typeof I.transactionId=="string"?I.transactionId:"",N=String(I.action);if(!M||!R||!["yes","this_time","no"].includes(N)){C(w,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),L=F?.imprintSummary;if(!U||!F||!L){C(w,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){C(w,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${ct().slice(0,8)}`;await Q.applyGroundingAction({summary:L,action:N,threadId:M,jobId:ge}),N!=="no"&&await B.recordImprintEvidence({summary:L,action:N,threadId:M,jobId:ge}).catch(Z=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",Z));let V=Ct(F.result,!!F.question),me=F.turn?{...F.turn,result:Ct(F.turn.result,!!F.question)}:void 0;await x.updateAssistantMessage(M,F.jobId,{imprintSummary:{...L,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=on({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(w,200,{ok:!0,action:N});return}C(w,404,{error:"Imprint endpoint not found."})}async function pt(d,w){let{screenshot:A,feedback:I,color:M,provider:R,model:N,reasoningEffort:J,serviceTier:U,sourceId:F,pastedImages:L,pageScreenshots:ge}=await wr(d),V;try{V=JSON.parse(I)}catch{C(w,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 q.promote(me):void 0}catch(ie){C(w,409,{error:ie instanceof Error?ie.message:"Draft attachment unavailable."});return}let Z=ct().slice(0,8),ye={};if(ge.length>0)for(let ie of ge){let z=encodeURIComponent(ie.pathname),ae=qe(c,`screenshot-${Z}-${z}.webp`);await Mo(ae,ie.data),ye[ie.pathname]=ae}let ne=qe(c,`screenshot-${Z}.webp`);await Mo(ne,A);let be={};if(L.length>0)for(let ie of L){let z=qe(c,`pasted-${Z}-${ie.annotationId}-${ie.index}.webp`);await Mo(z,ie.data),be[ie.annotationId]||(be[ie.annotationId]=[]),be[ie.annotationId].push(z)}let Re=bs(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-${ct()}`,Re)).id}else pe=(await x.createThread(`thread-${ct()}`,[])).id;let Y=V.annotations.map(ie=>ie.id),ke=Object.keys(ye).length>0,We=await On(B,V,Re,ie=>console.warn(`[\u22B9 ${y}:${Z}] Contextual memory unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))),Ie=(await x.getThread(pe))?.messages??[],Ke=await Q.contextualize({text:$t(V),subjectHints:Ms(V,Re),pendingGroundingExplanationIds:En(Ie),correctionExplanationIds:Ds(Ie)}).catch(ie=>{console.warn(`[\u22B9 ${y}:${Z}] Imprint context unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))}),je=kr({jobId:Z,threadId:pe,artifactIds:xs(V,Z)}),ee={id:Z,status:"queued",screenshotPath:ne,feedback:V,createdAt:Date.now(),color:M,threadId:pe,annotationIds:Y,provider:Zt(R),model:N||void 0,agentSettings:Vt({reasoningEffort:J,serviceTier:U}),...Object.keys(be).length>0?{imagePaths:be}:{},...re&&Object.keys(re).length>0?{attachmentFiles:re}:{},sourceId:F||void 0,...ke?{screenshotPaths:ye}:{},...We?{memoryReview:We}:{},...Ke?{imprintContext:Ke}:{},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||Ns({...V,annotations:[z]}))}Ne=[...ie.entries()].map(([z,ae])=>`\`${z}\`
198
+ ${ts}`;let L=up(d.color,`[\u22B9 ${y}:${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(`${L} Reviewing ${ge} (provider: ${R})${d.threadId?` (thread: ${d.threadId})`:""}${U?` (resuming: ${U.slice(0,8)})`:""}`);let V=new mo(d.id),me=new wo(d.id,d.imprintContext),re=(ee,we)=>{if(ee.type==="delta"&&"text"in ee){let Be=me.push(ee.text),Fe=V.push(Be.visibleText);Fe.visibleText&&(k.accumulateText(we,"response",Fe.visibleText),k.broadcast({...ee,text:Fe.visibleText},we,d.sourceId));for(let Ce of Fe.orientations)k.broadcast({type:"orientation",jobId:we,orientation:Ce},we,d.sourceId);for(let Ce of Be.usages)k.broadcast({type:"imprint_used",jobId:we,usage:Ce},we,d.sourceId);return}else ee.type==="thinking"&&"text"in ee&&k.accumulateText(we,"thinking",ee.text);k.broadcast(ee,we,d.sourceId)},{process:Z,result:ye}=R==="codex"?Zn(d.id,{prompt:F,projectRoot:r,screenshotPath:d.screenshotPath,resumeSessionId:U,model:d.model,sandboxMode:N?"read-only":void 0,configOverrides:Gn(d.agentSettings),onEvent:re}):R==="copilot"?Ai(d.id,{prompt:F,projectRoot:r,resumeSessionId:U,model:d.model,timeoutMs:h,copilotPath:l.copilot?.path??P,onEvent:re}):Hn(d.id,{prompt:F,projectRoot:r,maxTurns:p,maxBudgetUsd:b,allowedTools:N?["Read"]:S,claudePath:w,resumeSessionId:U,model:d.model,reasoningEffort:d.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:re});k.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=br(Re.visibleText,d.id),Y=V.finalize(Re.visibleText),ke=pe.visibleText,Ve=ss(ke),Ie=J?sn(ke,{context:d.imprintContext,requestText:I??$t(d.feedback),applicationOccurred:be.length>0||Ve.some(ee=>ee.status==="resolved")}):{visibleText:ke,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)k.broadcast({type:"orientation",jobId:d.id,orientation:ee},d.id,d.sourceId);for(let ee of Re.usages)k.broadcast({type:"imprint_used",jobId:d.id,usage:ee},d.id,d.sourceId);if(d.result=We,ne.success){console.log(`${L} Iteration complete`),ne.fileEdits&&ne.fileEdits.length>0&&console.log(`${L} 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(`${L} Captured ${ne.editEvents.length} edit event(s): ${ne.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),d.status="done";let ee=rs(ke),we=Ve;if(we.length>0&&d.annotationIds&&d.annotationIds.length>0){let de=new Set(d.annotationIds);we.every(Ye=>de.has(Ye.annotationId))||(we=we.map((Ye,vt)=>({...Ye,annotationId:d.annotationIds[vt%d.annotationIds.length]})))}let Be=ne.fileEdits&&ne.fileEdits.length>0?ne.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):ne.toolsUsed,Fe=k.getBufferedEvents(d.id),Ce=rp(Fe?.events??[],r,pe.segments),Ae,ie=Xi(ke),z=Qi(ke);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=as(ke,be.length),ue,Ke,Er,_r,Zs=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??[]],Ye=Ie.draft.decision==="recognize"?[]:Ie.draft.appliedExplanationIds??[];ce.length>0&&(Er=[...new Set(ce)]),Ye.length>0&&(_r=[...new Set(Ye)])}Ie.draft?.decision==="none"&&Q.recordNoop(Ie.draft.reason);let Cn=Ie.draft?.decision==="recognize"?Ie.draft:void 0;if(Cn&&!z&&!ie){let de=d.imprintContext?.explanations.find(ce=>ce.id===Cn.explanationId&&ce.state==="grounded");de?Ke={explanationId:de.id,title:Cn.summary.title,detail:Cn.summary.detail,statement:de.statement}:je={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let $o=Ie.draft?.decision==="mutate"||Ie.draft?.decision==="apply"?Ie.draft:void 0;if(d.threadId&&$o&&!z&&!ie)try{ue=await Q.capture($o,{threadId:d.threadId,jobId:d.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:Zs,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(`${L} 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(`${L} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else $o&&(je={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});Ie.error&&console.warn(`${L} Ignored invalid imprint block: ${Ie.error}`),(je.state==="missing"||je.state==="invalid")&&Q.recordAssessmentFailure(je.state);let Oo=ue?.transactionId;if(d.threadId&&ue&&!ue.grounding){let de=await x.getThread(d.threadId),ce=new Set(ue.changes.map(vt=>vt.explanationId)),Ye=de?op(de.messages,ce):void 0;if(Ye?.imprintSummary){let vt=Ye.imprintSummary;await x.updateAssistantMessage(d.threadId,Ye.jobId,{imprintSummary:{...vt,detail:ue.detail,changes:ue.changes,additionalObservationCount:(vt.additionalObservationCount??0)+1,coalescedTransactionIds:[...vt.coalescedTransactionIds??[],ue.transactionId]}}),ue=void 0}}let Do=on({question:ee,resolutions:we,changedFiles:be,decisionRequired:!!ie,imprintTransactionId:Oo,groundingRequired:!!ue?.grounding}),ea=Ce?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],_t=d.lifecycle?Pn(d.lifecycle,Oo?[Oo]:[],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:Be,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:ea,result:Do},result:Do,memoryReviewCard:ie??void 0,memoryReceipt:Ae,imprintSummary:ue,imprintRecognition:Ke,imprintUsedExplanationIds:Er,imprintAppliedExplanationIds:_r,modelDetails:ae.length>0?ae:void 0,model:d.model,provider:R,..._t?{lifecycle:_t}:{}})}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:I??($t(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=>Ns(ce)?Gl(r,ce):ce),resolutions:we.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:d.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:_t?.submissionIds,outcomeId:_t?.outcomeId,imprintEvidenceIds:_t?.imprintEvidenceIds,imprintAssessment:_t?.imprintAssessment})}catch(ce){console.warn(`${L} 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 $e({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(`${L} \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"})`),k.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(`${L} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:d.id,patterns:ae,threadId:d.threadId},d.id,d.sourceId)),k.broadcast({type:"done",jobId:d.id,success:!0,resolutions:we.length>0?we:void 0,responseText:We,threadId:d.threadId,annotationIds:d.annotationIds,result:Do},d.id,d.sourceId),Me.push({id:d.id,status:"done",completedAt:Date.now(),threadId:d.threadId,annotationIds:d.annotationIds})}else console.error(`${L} 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:Pn(d.lifecycle)}:{}}),k.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});nt()});let At=Wl(async(d,v)=>{if(ap(d,v),d.method==="OPTIONS"){v.writeHead(204),v.end();return}let _=d.url||"/",I=_.split("?")[0],A=new URL(_,`http://127.0.0.1:${y}`),R=A.pathname,N=pp(d,A);if(N&&N!==i){$(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:Mo(r)});return}if(R.startsWith("/ambient/")&&N!==i){$(v,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:N});return}if(d.headers.origin){if(!Bs(d.headers.origin)){$(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(N!==i){$(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:N,projectName:Mo(r)});return}}try{if(R.startsWith("/ambient/"))await Ao(d,v,R);else if(d.method==="POST"&&R==="/draft-attachments"){let J=A.searchParams.get("annotationId")?.trim()??"",U=A.searchParams.get("name")?.trim()??"",F=A.searchParams.get("kind"),L=String(d.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!J||J.length>128||!/^[a-z0-9_-]+$/i.test(J)){$(v,400,{error:"A valid annotationId is required."});return}if(F!=="svg"&&F!=="text"||F==="svg"&&L!=="image/svg+xml"||F==="text"&&L!=="text/plain"){$(v,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ge=await lp(d,np);if(ge.length===0){$(v,400,{error:"Attachment is empty."});return}let V=await q.stage({annotationId:J,name:U,mimeType:L,kind:F,data:ge});$(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 Oe(d),U=Array.isArray(J.ids)?J.ids.filter(F=>typeof F=="string").slice(0,100):[];await q.claim(U),$(v,200,{ok:!0})}else if(d.method==="DELETE"&&R.startsWith("/draft-attachments/"))await q.release([R.slice(19)]),$(v,200,{ok:!0});else if(d.method==="POST"&&R==="/send")await Ne(d,v);else if(d.method==="POST"&&R==="/capture/native"){if(!u){$(v,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let J=await Oe(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){$(v,400,{error:"pageUrl and clip are required."});return}let L=await Hi(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":L.length,"Cache-Control":"no-store"}),v.end(L)}else if(d.method==="GET"&&R==="/events")lt(d,v);else if(d.method==="GET"&&R==="/status")await pt(d,v,N);else if(d.method==="GET"&&R==="/ui-preferences")await Eo(v);else if(d.method==="PATCH"&&R==="/ui-preferences")await _o(d,v);else if(d.method==="PATCH"&&R==="/config")await It(d,v);else if(d.method==="POST"&&R==="/leases"){if(g!=="detached"){$(v,409,{error:"Bridge leases are only available for detached bridges."});return}try{let J=await Oe(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){$(v,400,{error:"A valid leaseId is required."});return}G();let L=K.acquire(U,F);$(v,201,{ok:!0,lease:L,ttlMs:_s})}catch{$(v,400,{error:"Invalid lease request."})}}else if(R.startsWith("/leases/")&&(d.method==="PATCH"||d.method==="DELETE")){if(g!=="detached"){$(v,409,{error:"Bridge leases are only available for detached bridges."});return}let J="";try{J=decodeURIComponent(R.slice(8))}catch{$(v,400,{error:"Invalid lease id."});return}if(!J){$(v,400,{error:"A lease id is required."});return}if(d.method==="PATCH"){let U=K.heartbeat(J);if(!U){$(v,404,{error:"Lease not found."});return}$(v,200,{ok:!0,lease:U})}else{let U=K.release(J);$(v,U.found?200:404,{ok:U.found}),U.becameEmpty&&X()}}else if(d.method==="POST"&&R==="/shutdown"){if(g!=="detached"){$(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}$(v,200,{ok:!0}),setTimeout(fe,100)}else if(d.method==="POST"&&R==="/restart"){if(g!=="detached"){$(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}$(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let J of oe)try{J.res.end()}catch{}At.close(()=>{Es(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")$(v,200,{providers:l});else if(R.startsWith("/imprint/"))await ct(d,v,R);else if(R.startsWith("/memory/"))await Te(d,v,R);else if(d.method==="POST"&&R==="/mcp/install")await _n(d,v);else if(d.method==="POST"&&R==="/reply")await ot(d,v);else if(d.method==="POST"&&R==="/cancel")tn(d,v);else if(d.method==="POST"&&R==="/materialize")$(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(d.method==="GET"&&R==="/materialization-runs")$(v,410,{error:"Use /projection-runs."});else if(d.method==="GET"&&R==="/projection-runs"){let J=await se.loadRuns();$(v,200,J)}else if(d.method==="GET"&&R==="/projection/proposals"){let J=await se.loadModelProposals();$(v,200,J)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply-selected")){let J=R.slice(22,-15);await ut(J,d,v)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/apply")){let J=R.slice(22,-6);await Le(J,v)}else if(d.method==="POST"&&R.startsWith("/projection/proposals/")&&R.endsWith("/dismiss")){let J=R.slice(22,-8);await Et(J,d,v)}else if(R.startsWith("/model/proposals/"))$(v,410,{error:"Use /projection/proposals."});else if(d.method==="POST"&&R==="/model/component")await Vs(d,v);else if(d.method==="DELETE"&&R==="/model/component")await Ws(d,v);else if(d.method==="PATCH"&&R==="/model/token")await Ks(d,v);else if(d.method==="DELETE"&&R==="/model/token")await Gs(d,v);else if(d.method==="POST"&&R==="/model/consolidate")$(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(d.method==="POST"&&R==="/model/synthesize")$(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();$(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(A.searchParams.get("afterSeq")??"-1",10),F=k.getBufferedEvents(J,isNaN(U)?-1:U);F?$(v,200,F):$(v,404,{error:"Unknown job"})}else if(d.method==="GET"&&I.startsWith("/files/"))await Hs(I.slice(7),v);else if(d.method==="GET"&&R==="/threads/recent"){let J=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),U=await x.listRecent(J);$(v,200,U)}else if(d.method==="GET"&&R.startsWith("/decision/")){let J=R.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(J))$(v,400,{error:"Invalid decision id"});else{let U=await x.getThread(J),F=[...U?.messages??[]].reverse().find(L=>L.annotationSnapshot);if(U&&F?.annotationSnapshot){let L=[...U.messages].reverse().find(ge=>ge.resolutions?.length);$(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:L?.resolutions??[]},authority:"thread_snapshot"})}else{let L=await _e.loadDecision(J);L?$(v,200,{decision:L,authority:"legacy_archive"}):$(v,404,{error:"Decision not found"})}}}else if(d.method==="GET"&&R.startsWith("/thread/")){let J=R.slice(8);await Qs(J,v)}else if(d.method==="DELETE"&&R.startsWith("/thread/")){let J=R.slice(8);await Xs(J,v)}else $(v,404,{error:"Not found"})}catch(J){console.error("[Bridge] Request error:",J),$(v,500,{error:J instanceof Error?J.message:"Internal error"})}});async function Ao(d,v,_){if(d.method!=="POST"){$(v,405,{error:"Ambient endpoints accept POST requests only."});return}let I=await Oe(d,cp),A=typeof I.sessionId=="string"?I.sessionId.trim():"",R=typeof I.turnId=="string"?I.turnId.trim():"",N=typeof I.executionOwner=="string"?I.executionOwner:void 0,J=di(I.knowledgeView);if(_==="/ambient/context"){let U=typeof I.query=="string"?I.query.trim():"";if(!U){$(v,400,{error:"query is required."});return}let F=Array.isArray(I.subjectHints)?I.subjectHints.filter(L=>typeof L=="string"&&!!L.trim()).slice(0,20):void 0;$(v,200,await De.expandContext({query:U,subjectHints:F,knowledgeView:J}));return}if(_==="/ambient/turns/assess"){let U=typeof I.threadId=="string"?I.threadId.trim():"",F=typeof I.jobId=="string"?I.jobId.trim():"",L=typeof I.assessmentText=="string"?I.assessmentText.trim():"";if(!U||!F||!L){$(v,400,{error:"threadId, jobId, and assessmentText are required."});return}let ge=Array.isArray(I.semanticCandidates)?I.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 De.assess({threadId:U,jobId:F,assessmentText:L,semanticCandidates:ge});$(v,V.status==="recorded"?200:404,V);return}if(!A||!R||A.length>256||R.length>256){$(v,400,{error:"Valid sessionId and turnId values are required."});return}if(_==="/ambient/turns/prepare"){let U=typeof I.prompt=="string"?I.prompt.trim():"";if(!U){$(v,400,{error:"prompt is required."});return}$(v,200,await De.prepare({sessionId:A,turnId:R,prompt:U,model:typeof I.model=="string"?I.model:void 0,executionOwner:N,knowledgeView:J}));return}if(_==="/ambient/turns/event"){let U=typeof I.toolName=="string"?I.toolName.trim():"";if(!U){$(v,400,{error:"toolName is required."});return}$(v,200,await De.recordEvent({sessionId:A,turnId:R,executionOwner:N,toolName:U,toolUseId:typeof I.toolUseId=="string"?I.toolUseId:void 0,toolInput:I.toolInput,toolResponse:I.toolResponse}));return}if(_==="/ambient/turns/complete"){$(v,200,await De.complete({sessionId:A,turnId:R,executionOwner:N,lastAssistantMessage:typeof I.lastAssistantMessage=="string"?I.lastAssistantMessage:void 0,model:typeof I.model=="string"?I.model:void 0}));return}$(v,404,{error:"Ambient endpoint not found."})}async function Te(d,v,_){try{if(d.method==="GET"&&_==="/memory/status"){$(v,200,await B.status());return}if(d.method==="GET"&&_==="/memory/diagnostics"){$(v,200,await B.diagnostics());return}if(d.method==="GET"&&_==="/memory/model-view"){$(v,200,await B.getModelView());return}if(d.method==="GET"&&_==="/memory/imprint-view"){let I=await x.load(),A=[...new Set(Object.values(I.threads).flatMap(R=>En(R.messages)))];$(v,200,await B.getImprintView(A,new Set(Object.keys(I.threads))));return}if(d.method==="POST"&&_==="/memory/constraints"){let I=await Oe(d),A=typeof I.reactComponent=="string"?I.reactComponent.trim():"",R=await B.getModelView(),N=A?R.entries.filter(J=>J.key===`components.${A}`||J.key.startsWith(`components.${A}.`)):[];$(v,200,{modelEntries:N});return}if(d.method==="POST"&&_==="/memory/conversation-action"){let I=await Oe(d),A=typeof I.threadId=="string"?I.threadId:"",R=typeof I.proposalId=="string"?I.proposalId:"",N=String(I.action);if(!A||!R||!["accept","edit_and_accept","reject","defer"].includes(N)){$(v,400,{error:"A valid thread, proposal, and review action are required."});return}let J=await x.getThread(A),U=J?.messages.find(pe=>pe.memoryReviewCard?.proposalId===R)?.memoryReviewCard,F=J?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===R),L=J?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await B.findPendingProposalsForThread(A)).find(pe=>pe.proposalId===R):void 0,ge=typeof I.kind=="string"&&["principle","preference","rule","constraint"].includes(I.kind)?I.kind:void 0,V=U?.kind??F?.proposedKind??L?.proposedKind??ge;if(!J||!U&&!F&&!L){$(v,409,{error:"This decision candidate was not surfaced in the thread."});return}if((N==="accept"||N==="edit_and_accept")&&!V){$(v,400,{error:"The decision kind is required to accept this candidate."});return}let me=await se.findModelProposalsByThread(A),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 I.claim=="string"?I.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){$(v,400,{error:"Edited decision wording is required."});return}let ye=await B.commitConversationalReview(Z),ne=`memory-${dt().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(A,{role:"human",timestamp:Date.now(),jobId:ne,replyToQuestion:be}),await x.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:ne,responseText:"",memoryReceipt:ye,provider:Zt(typeof I.provider=="string"?I.provider:void 0),model:typeof I.model=="string"?I.model:void 0}),ye.status==="committed"&&re&&await se.dismissModelProposal(re.id);let Re=Zt(typeof I.provider=="string"?I.provider:void 0);ye.status==="committed"&&ye.decisionId&&Re!=="copilot"&&await $e({provider:Re,model:typeof I.model=="string"?I.model:void 0,agentSettings:Vt(I),threadId:A,reason:`Project accepted decision ${ye.decisionId}`}),$(v,ye.status==="committed"?200:409,{receipt:ye});return}if(d.method==="POST"&&_==="/memory/analyze"){let I=await Oe(d),A=await B.analyzeLegacy({projectKey:typeof I.projectKey=="string"?I.projectKey:void 0}),R=Object.fromEntries([...new Set(A.issues.map(N=>N.code))].map(N=>[N,A.issues.filter(J=>J.code===N).length]));$(v,200,{...A,issues:void 0,issueCounts:R});return}if(d.method==="POST"&&_==="/memory/review"){let I=await Oe(d),A=await B.review(Xo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});$(v,200,A);return}if(d.method==="POST"&&_==="/memory/context"){let I=await Oe(d),A=await B.contextualize(Xo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});$(v,200,A);return}if(d.method==="POST"&&_==="/memory/initialize"){let I=await Oe(d),A=await B.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:An});$(v,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(d.method==="POST"&&_==="/memory/plan"){let I=await Oe(d),A=await B.planReview(Qo(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});$(v,A.result.ok?200:422,A);return}if(d.method==="POST"&&_==="/memory/commit"){let I=await Oe(d),A=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},R=await B.commitReview(Qo(I.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});$(v,200,{status:await B.status(),journal:R.report});return}if(d.method==="POST"&&_==="/memory/recover"){let I=await Oe(d),A=await B.recover(I.confirm===!0);$(v,200,{status:await B.status(),journal:A.report});return}$(v,404,{error:"Memory endpoint not found."})}catch(I){let A=I instanceof Error?I.message:String(I),R=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),N=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(R||N){$(v,R?409:400,{error:A});return}throw I}}async function ct(d,v,_){if(d.method==="GET"&&_==="/imprint/status"){let[I,A]=await Promise.all([Q.store.load(),x.load()]),R=[...new Set(Object.values(A.threads).flatMap(N=>En(N.messages)))].filter(N=>I.graph.explanations.some(J=>J.id===N&&J.state==="testing"));$(v,200,{state:"ready",head:I.graph.head,updatedAt:I.graph.updatedAt,explanationCount:I.graph.explanations.filter(N=>N.state!=="retired").length,concreteCount:I.graph.concrete.length,relationCount:I.graph.relations.length,pendingGroundingCount:R.length,recoveredTransactions:I.recoveredTransactions,admission:Q.diagnostics(),admissionWindowStartedAt:e});return}if(d.method==="POST"&&_==="/imprint/action"){let I=await Oe(d),A=typeof I.threadId=="string"?I.threadId:"",R=typeof I.transactionId=="string"?I.transactionId:"",N=String(I.action);if(!A||!R||!["yes","this_time","no"].includes(N)){$(v,400,{error:"A valid thread, imprint update, and action are required."});return}let U=await x.getThread(A),F=[...U?.messages??[]].reverse().find(Z=>Z.role==="assistant"&&Z.imprintSummary?.transactionId===R),L=F?.imprintSummary;if(!U||!F||!L){$(v,409,{error:"This imprint summary is not available in the thread."});return}if(L.resolvedAction){$(v,409,{error:"This imprint summary has already been resolved."});return}let ge=`imprint-${dt().slice(0,8)}`;await Q.applyGroundingAction({summary:L,action:N,threadId:A,jobId:ge}),N!=="no"&&await B.recordImprintEvidence({summary:L,action:N,threadId:A,jobId:ge}).catch(Z=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",Z));let V=Ct(F.result,!!F.question),me=F.turn?{...F.turn,result:Ct(F.turn.result,!!F.question)}:void 0;await x.updateAssistantMessage(A,F.jobId,{imprintSummary:{...L,resolvedAction:N},...V?{result:V}:{},...me?{turn:me}:{}});let re={yes:"> Yes",this_time:"> This time",no:"> No"};if(await x.appendMessage(A,{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=on({question:Z});await x.appendMessage(A,{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})}$(v,200,{ok:!0,action:N});return}$(v,404,{error:"Imprint endpoint not found."})}async function Ne(d,v){let{screenshot:_,feedback:I,color:A,provider:R,model:N,reasoningEffort:J,serviceTier:U,sourceId:F,pastedImages:L,pageScreenshots:ge}=await wr(d),V;try{V=JSON.parse(I)}catch{$(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 q.promote(me):void 0}catch(ie){$(v,409,{error:ie instanceof Error?ie.message:"Draft attachment unavailable."});return}let Z=dt().slice(0,8),ye={};if(ge.length>0)for(let ie of ge){let z=encodeURIComponent(ie.pathname),ae=Xe(c,`screenshot-${Z}-${z}.webp`);await Po(ae,ie.data),ye[ie.pathname]=ae}let ne=Xe(c,`screenshot-${Z}.webp`);await Po(ne,_);let be={};if(L.length>0)for(let ie of L){let z=Xe(c,`pasted-${Z}-${ie.annotationId}-${ie.index}.webp`);await Po(z,ie.data),be[ie.annotationId]||(be[ie.annotationId]=[]),be[ie.annotationId].push(z)}let Re=vs(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-${dt()}`,Re)).id}else pe=(await x.createThread(`thread-${dt()}`,[])).id;let Y=V.annotations.map(ie=>ie.id),ke=Object.keys(ye).length>0,Ve=await $n(B,V,Re,ie=>console.warn(`[\u22B9 ${y}:${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:$t(V),subjectHints:Ps(V,Re),pendingGroundingExplanationIds:En(Ie),correctionExplanationIds:$s(Ie)}).catch(ie=>{console.warn(`[\u22B9 ${y}:${Z}] Imprint context unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))}),je=kr({jobId:Z,threadId:pe,artifactIds:bs(V,Z)}),ee={id:Z,status:"queued",screenshotPath:ne,feedback:V,createdAt:Date.now(),color:A,threadId:pe,annotationIds:Y,provider:Zt(R),model:N||void 0,agentSettings:Vt({reasoningEffort:J,serviceTier:U}),...Object.keys(be).length>0?{imagePaths:be}:{},...re&&Object.keys(re).length>0?{attachmentFiles:re}:{},sourceId:F||void 0,...ke?{screenshotPaths:ye}:{},...Ve?{memoryReview:Ve}:{},...We?{imprintContext:We}:{},lifecycle:je},we=new Set(V.annotations.map(ie=>ie.pathname).filter(Boolean)),Be;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||Os({...V,annotations:[z]}))}Be=[...ie.entries()].map(([z,ae])=>`\`${z}\`
229
199
  ${ae.map(ue=>`- ${ue}`).join(`
230
200
  `)}`).join(`
231
- `)}else Ne=Ns(V);let Ue=Sn(V,Object.keys(be).length>0?be:void 0,re),Ce=As(V);await x.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:Z,screenshotPath:ne,...ke?{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,...We?{memoryReview:We}:{},...Ke?{imprintContext:Ke}:{},lifecycle:je});let Ae=k.enqueue(ee);C(w,200,{jobId:Z,position:Ae,threadId:pe})}async function ut(d,w){let A=d.headers["content-type"]||"",I,M,R,N,J,U,F,L,ge=[];if(A.includes("multipart/form-data")){let z=await wr(d),ae=z.feedback?JSON.parse(z.feedback):{};I=ae.threadId,M=ae.reply,R=ae.color,N=ae.provider,J=ae.model,U=Vt(ae),F=ae.sourceId||z.sourceId,L=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(w,400,{error:"Invalid JSON"});return}I=ue.threadId,M=ue.reply,R=ue.color,N=ue.provider,J=ue.model,U=Vt(ue),F=ue.sourceId,L=ue.memoryReviewProposalId}if(!I||!M){C(w,400,{error:"Missing threadId or reply"});return}let V=await x.getThread(I);if(!V){C(w,404,{error:"Thread not found"});return}let me;if(L){let z=await se.findModelProposalsByThread(I);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===L),!me){C(w,409,{error:"The requested memory decision is not pending in this thread."});return}}let re="";{let z=await x.getThreadHistory(I);for(let ae=z.length-1;ae>=0;ae--)if(z[ae].screenshotPath){re=z[ae].screenshotPath;break}}let Z=await Ks(I);if(!re&&!Z){C(w,400,{error:"No screenshot available"});return}let ye=k.hasActiveThread(I),ne=ye?k.getQueuedThreadJob(I,z=>z._replyText!==void 0||z._replyPrompt!==void 0):null,be=ne?.id??ct().slice(0,8),Re=kr({jobId:be,threadId:I}),pe=[],Y=`${be}-${Date.now()}`;for(let z=0;z<ge.length;z++){let ae=qe(c,`reply-${Y}-${z}.webp`);await Mo(ae,ge[z]),pe.push(ae)}await x.appendMessage(I,{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 ke=await x.getThreadHistory(I),We=[...ke].reverse().find(z=>z.memoryReview)?.memoryReview,Ie=await Q.contextualize({text:M,subjectHints:js(ke,V.elementIdentifiers),pendingGroundingExplanationIds:En(ke),correctionExplanationIds:Ds(ke)}).catch(z=>{console.warn(`[\u22B9 ${y}:${be}] Imprint context unavailable for reply; continuing without it:`,z instanceof Error?z.message:String(z))});Ie&&await x.updateMessage(I,be,{imprintContext:Ie});let Ke=new Set(ke.flatMap(z=>z.memoryReceipt?.status==="committed"?[z.memoryReceipt.proposalId]:[])),je=[...ke].reverse().find(z=>z.memoryReviewCard&&!Ke.has(z.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let z of ke)if(z.annotationIds)for(let ae of z.annotationIds)ee.includes(ae)||ee.push(ae);let we=Zt(N),Ne=me,Ue=Ne?[Ne.underlying.proposalId]:je?[je.proposalId]:[],Ce=ss(re,ke,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(`
201
+ `)}else Be=Os(V);let Fe=Sn(V,Object.keys(be).length>0?be:void 0,re),Ce=js(V);await x.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:Z,screenshotPath:ne,...ke?{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:A||void 0},feedbackSummary:Be,...Ce?{requestText:Ce}:{},feedbackContext:Fe||void 0,...Ve?{memoryReview:Ve}:{},...We?{imprintContext:We}:{},lifecycle:je});let Ae=k.enqueue(ee);$(v,200,{jobId:Z,position:Ae,threadId:pe})}async function ot(d,v){let _=d.headers["content-type"]||"",I,A,R,N,J,U,F,L,ge=[];if(_.includes("multipart/form-data")){let z=await wr(d),ae=z.feedback?JSON.parse(z.feedback):{};I=ae.threadId,A=ae.reply,R=ae.color,N=ae.provider,J=ae.model,U=Vt(ae),F=ae.sourceId||z.sourceId,L=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let ue of z.pastedImages)ge.push(ue.data)}else{let z=[];for await(let Ke of d)z.push(typeof Ke=="string"?Buffer.from(Ke):Ke);let ae=Buffer.concat(z).toString("utf-8"),ue;try{ue=JSON.parse(ae)}catch{$(v,400,{error:"Invalid JSON"});return}I=ue.threadId,A=ue.reply,R=ue.color,N=ue.provider,J=ue.model,U=Vt(ue),F=ue.sourceId,L=ue.memoryReviewProposalId}if(!I||!A){$(v,400,{error:"Missing threadId or reply"});return}let V=await x.getThread(I);if(!V){$(v,404,{error:"Thread not found"});return}let me;if(L){let z=await se.findModelProposalsByThread(I);if(me=(await Promise.all(z.flatMap(ue=>ue.authorityStatus==="accepted"?[]:ue.decisionIds.map(async Ke=>({modelProposalId:ue.id,underlying:await B.findPendingProposalForLegacyDecision(Ke)}))))).filter(ue=>!!ue.underlying).find(ue=>ue.underlying.proposalId===L),!me){$(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let re="";{let z=await x.getThreadHistory(I);for(let ae=z.length-1;ae>=0;ae--)if(z[ae].screenshotPath){re=z[ae].screenshotPath;break}}let Z=await Co(I);if(!re&&!Z){$(v,400,{error:"No screenshot available"});return}let ye=k.hasActiveThread(I),ne=ye?k.getQueuedThreadJob(I,z=>z._replyText!==void 0||z._replyPrompt!==void 0):null,be=ne?.id??dt().slice(0,8),Re=kr({jobId:be,threadId:I}),pe=[],Y=`${be}-${Date.now()}`;for(let z=0;z<ge.length;z++){let ae=Xe(c,`reply-${Y}-${z}.webp`);await Po(ae,ge[z]),pe.push(ae)}await x.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:be,replyToQuestion:A,screenshotPath:re,...ye?{queued:!0}:{},...pe.length>0?{replyImagePaths:pe}:{},lifecycle:{...Re,artifactIds:pe.map((z,ae)=>`reply-image:${be}:${ae}`)}});let ke=await x.getThreadHistory(I),Ve=[...ke].reverse().find(z=>z.memoryReview)?.memoryReview,Ie=await Q.contextualize({text:A,subjectHints:Ms(ke,V.elementIdentifiers),pendingGroundingExplanationIds:En(ke),correctionExplanationIds:$s(ke)}).catch(z=>{console.warn(`[\u22B9 ${y}:${be}] Imprint context unavailable for reply; continuing without it:`,z instanceof Error?z.message:String(z))});Ie&&await x.updateMessage(I,be,{imprintContext:Ie});let We=new Set(ke.flatMap(z=>z.memoryReceipt?.status==="committed"?[z.memoryReceipt.proposalId]:[])),je=[...ke].reverse().find(z=>z.memoryReviewCard&&!We.has(z.memoryReviewCard.proposalId))?.memoryReviewCard,ee=[];for(let z of ke)if(z.annotationIds)for(let ae of z.annotationIds)ee.includes(ae)||ee.push(ae);let we=Zt(N),Be=me,Fe=Be?[Be.underlying.proposalId]:je?[je.proposalId]:[],Ce=is(re,ke,we,pe.length>0?pe:void 0);if(Be?Ce+=["","## Decision review card",`Privately review proposal ${Be.underlying.proposalId}: ${Be.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
202
  `):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=Os(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=We??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(w,200,{jobId:be,position:1,threadId:I,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:I,annotationIds:ee.length>0?ee:void 0,provider:we,model:J||void 0,agentSettings:U,sourceId:F||void 0,...We?{memoryReview:We}:{},...Ie?{imprintContext:Ie}:{},...Ue.length?{surfacedProposalIds:Ue}:{},lifecycle:Re};Z&&(Ae.kind=Z),Ae._replyPrompt=Ce,Ae._replyTexts=[M],Ae._replyText=Os([M]),pe.length>0&&(Ae._replyImagePaths=pe);let ie=ye?k.enqueueNext(Ae):k.enqueue(Ae);C(w,200,{jobId:be,position:ie,threadId:I})}function wt(d,w){w.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),w.write(`event: connected
203
+ `)),ne){let z=ne,ue=[...z._replyTexts??(z._replyText?[z._replyText]:[]),A],Ke=[...z._replyImagePaths??[],...pe];z._replyTexts=ue,z._replyText=Cs(ue),z._replyImagePaths=Ke.length>0?Ke:void 0,z._replyPrompt=Ce,z.annotationIds=ee.length>0?ee:z.annotationIds,z.agentSettings=U??z.agentSettings,z.memoryReview=Ve??z.memoryReview,z.imprintContext=Ie??z.imprintContext,z.surfacedProposalIds=[...new Set([...z.surfacedProposalIds??[],...Fe])],z.lifecycle={...z.lifecycle??Re,submissionIds:[...new Set([...z.lifecycle?.submissionIds??[],...Re.submissionIds])],artifactIds:[...new Set([...z.lifecycle?.artifactIds??[],...Re.artifactIds])]},$(v,200,{jobId:be,position:1,threadId:I,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:I,annotationIds:ee.length>0?ee:void 0,provider:we,model:J||void 0,agentSettings:U,sourceId:F||void 0,...Ve?{memoryReview:Ve}:{},...Ie?{imprintContext:Ie}:{},...Fe.length?{surfacedProposalIds:Fe}:{},lifecycle:Re};Z&&(Ae.kind=Z),Ae._replyPrompt=Ce,Ae._replyTexts=[A],Ae._replyText=Cs([A]),pe.length>0&&(Ae._replyImagePaths=pe);let ie=ye?k.enqueueNext(Ae):k.enqueue(Ae);$(v,200,{jobId:be,position:ie,threadId:I})}function lt(d,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
234
204
  data: {"status":"connected"}
235
205
 
236
- `);let I=new URL(d.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,M={id:ct().slice(0,8),res:w,sourceId:I};oe.add(M),d.on("close",()=>{oe.delete(M)})}async function Eo(d,w,A){a??=ys(d.headers),ot();let I=[...k.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=[],L=Y=>Y.reason instanceof Error?Y.reason.message:String(Y.reason);M.status==="rejected"&&F.push({subsystem:"projection",message:L(M)}),R.status==="rejected"&&F.push({subsystem:"projection",message:L(R)}),N.status==="rejected"?F.push({subsystem:"memory",message:L(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:L(J)}),U.status==="rejected"&&F.push({subsystem:"threads",message:L(U)});let ge=M.status==="fulfilled"?M.value.runs:[],V=R.status==="fulfilled"?R.value.proposals:[],me=Is(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:L(N)},ye=U.status==="fulfilled"?[...new Set(Object.values(U.value.threads).flatMap(Y=>En(Y.messages)))]:[],ne=J.status==="fulfilled"?ye.filter(Y=>J.value.graph.explanations.some(ke=>ke.id===Y&&ke.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:L(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(w,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Re,issues:F},version:An,restartMode:g,projectId:i,storeId:s.storeId,projectName:jo(r),projectRoot:r,requestProjectId:A,projectIdVerified:A===i,devOrigin:a,capture:{native:{configured:!!u,endpoint:u?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.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:k.depth+O.depth,projectionQueueDepth:O.depth,leases:{active:K.isActivated,count:K.size,nextExpiryAt:K.nextExpiryAt,shutdownPending:W},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:en,recentJobs:Me})}async function _o(d,w){let A=await new Promise(I=>{let M="";d.on("data",R=>{M+=R.toString()}),d.on("end",()=>I(M))});try{let I=JSON.parse(A);typeof I.devOrigin=="string"&&(a=I.devOrigin||null),C(w,200,{ok:!0,devOrigin:a})}catch{C(w,400,{error:"Invalid JSON"})}}async function tn(d){let w=await he.load();C(d,200,{ok:!0,...w})}async function Le(d,w){let A=await $e(d);if(!Ps(A.theme)){C(w,400,{error:"theme must be light, dark, or auto"});return}let I=await he.setTheme(A.theme);C(w,200,{ok:!0,exists:!0,preferences:I})}async function Fe(d,w){let I=new URL(d.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),M=I?k.allActive.filter(L=>L.id===I):k.allActive,R=I?O.allActive.filter(L=>L.id===I):O.allActive,N=[...M.map(L=>L.threadId),...R.map(L=>L.threadId)].filter(Boolean),J=I?k.cancelJob(I):k.cancelActive(),U=I?O.cancelJob(I):O.cancelActive(),F=!!(J||U);for(let L of N)await x.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:I||U?.id||"",cancelled:!0});C(w,200,{cancelled:F})}async function Ye(d){let w=ct().slice(0,8),A=d.threadId,I=!A;A||(A=(await x.createThread(`thread-${ct()}`,[])).id,yt.set(A,"project_model")),I&&await x.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:w,feedbackSummary:d.reason}),await x.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:w,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:d.model,provider:d.provider});let M={id:w,status:"queued",createdAt:Date.now(),provider:d.provider,model:d.model,agentSettings:d.agentSettings,threadId:A,annotationIds:d.annotationIds,sourceId:d.sourceId,standalone:I},R=O.enqueue(M);return{jobId:w,position:R,threadId:A}}async function Et(d,w){let A=decodeURIComponent(d),I=await se.findModelProposal(A);if(!I){C(w,404,{error:"Model proposal not found"});return}C(w,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:I})}async function vt(d,w,A){let I=decodeURIComponent(d),M=[];for await(let V of w)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(I);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}}),L=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(I,N,J);if(!ge){C(A,404,{error:"Model proposal not found"});return}if(ge.threadId){let V=Zt(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:L})}async function Co(d,w,A){let I=decodeURIComponent(d),{provider:M,model:R}=await Cn(w),N=await se.dismissModelProposal(I);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 Cn(d){try{let w=[];for await(let I of d)w.push(typeof I=="string"?Buffer.from(I):I);if(w.length===0)return{};let A=JSON.parse(Buffer.concat(w).toString());return{provider:Zt(typeof A.provider=="string"?A.provider:void 0),model:typeof A.model=="string"&&A.model?A.model:void 0,agentSettings:Vt(A)}}catch{return{}}}async function Ks(d){let w=yt.get(d);if(w)return w;let M=(await x.getThread(d))?.messages.find(R=>R.role==="human")?.feedbackSummary??"";if(M.startsWith("Synthesize rules"))return yt.set(d,"synthesize"),"synthesize";if(M.startsWith("Materialize model")||M.startsWith("Project model"))return yt.set(d,"project_model"),"project_model"}async function Gs(d,w){let A=[];for await(let U of d)A.push(typeof U=="string"?Buffer.from(U):U);let I;if(A.length>0)try{I=JSON.parse(Buffer.concat(A).toString("utf-8")).serverUrl}catch{}let M=[];l.claude?.available&&l.claude.mcp&&!l.claude.mcp.found&&M.push(await Ki(I)),l.codex?.available&&l.codex.mcp&&!l.codex.mcp.found&&M.push(await Gi(I)),l.copilot?.available&&l.copilot.mcp&&!l.copilot.mcp.found&&M.push(await Hi(I,l.copilot.path??P));let[R,N,J]=await Promise.all([fr(r),hr(r),gr(r,l.copilot?.path??P)]);l.claude&&(l.claude.mcp=R),l.codex&&(l.codex.mcp=N),l.copilot&&(l.copilot.mcp=J),C(w,200,{results:M,capabilities:{providers:l}})}async function Hs(d,w){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(w,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){C(w,400,{error:"Missing or invalid name"});return}let M=await B.recordDirectModelMutation({key:`components.${I.name}`,value:{description:""},claim:`${I.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(w,200,{added:!0,alreadyExists:!1,...M})}async function Qs(d,w){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(w,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){C(w,400,{error:"Missing or invalid name"});return}let M=await B.recordDirectModelMutation({key:`components.${I.name}`,value:null,claim:`${I.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(w,200,{removed:!0,...M})}async function Xs(d,w){let A=[];for await(let N of d)A.push(typeof N=="string"?Buffer.from(N):N);let I;try{I=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(w,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){C(w,400,{error:"Missing or invalid path/value"});return}let M=I.value;try{let N=JSON.parse(I.value);N&&typeof N=="object"&&(M=N)}catch{}let R=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:M,claim:`${I.path} uses ${I.value} in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(w,200,{updated:!0,...R})}async function Ys(d,w){let A=[];for await(let R of d)A.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{C(w,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){C(w,400,{error:"Missing or invalid path"});return}let M=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),C(w,200,{removed:!0,...M})}function Zs(d,w){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 I=Cr(y,A);w.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),w.end(I)}async function ea(d){let w=Date.now();if(It&&w<It.expires){C(d,200,It.data);return}try{let{scanForComponents:A}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:I}=await import("./render-generator-HWFLZYC3.mjs"),M=await A(r);It={data:M,expires:w+5e3},I(M,r,_n).then(R=>{_n=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 ta(d){let w=[qe(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),qe(r,"packages","popmelt","dist","canvas.mjs")];try{let A=op(import.meta.url);w.unshift(qe(ep(A),"canvas.mjs"))}catch{}for(let A of w)try{let I=await Cs(A,"utf-8");d.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),d.end(I);return}catch{}console.error("[Bridge] Canvas bundle not found in:",w),C(d,404,{error:"Canvas bundle not found"})}async function na(d,w){if(!d||d.includes("/")||d.includes("\\")||d.includes("..")){C(w,400,{error:"Invalid filename"});return}try{let A=[qe(c,d),qe(r,".popmelt","artifacts","thread-media",d),qe(r,".popmelt","artifacts","eval-screenshots",d),qe(r,".popmelt","evals","screenshots",d),qe(r,".popmelt","screenshots",d)],I;for(let N of A)try{I=await Cs(N);break}catch{}if(!I)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";w.writeHead(200,{"Content-Type":R,"Cache-Control":"public, max-age=3600"}),w.end(I)}catch{C(w,404,{error:"File not found"})}}function nn(d){return`/files/${jo(d)}`}async function oa(d,w){let A=await x.getThread(d);if(!A){C(w,404,{error:"Thread not found"});return}let I=A.messages.filter(F=>F.role==="assistant"&&F.responseText?.includes("Model suggestion ready")),M=await(I.length>0?se.findModelProposalsByThread(d):Promise.resolve([])),R=await Promise.all(M.map(async(F,L)=>{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??I[L]?.jobId??I.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),N=[...R].sort((F,L)=>L.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:L,imagePaths:ge,attachmentFiles:V,replyImagePaths:me,...re})=>({...re,...F?{screenshotUrl:nn(F)}:{},...L?{screenshotUrls:Object.fromEntries(Object.entries(L).map(([Z,ye])=>[Z,nn(ye)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([Z,ye])=>[Z,ye.map(nn)]))}:{},...V?{attachments:Object.fromEntries(Object.entries(V).map(([Z,ye])=>[Z,ye.map(({path:ne,...be})=>({...be,url:nn(ne)}))]))}:{},...me?{replyImageUrls:me.map(nn)}:{}}));C(w,200,{id:A.id,createdAt:A.createdAt,messages:U,modelProposal:N,modelProposals:R,decisionCandidates:J})}async function ra(d,w){let A=decodeURIComponent(d);if(!await x.deleteThread(A)){C(w,404,{deleted:!1,error:"Thread not found"});return}C(w,200,{deleted:!0})}let Mr=9,jr=!1;for(let d=t;d<t+Mr;d++)try{await xp(xe,d),y=d,jr=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(w){if(w.code==="EADDRINUSE"){let A=await bp(d);if(gs(A,{projectId:i,version:An,restartMode:g}))return console.log(`[\u22B9 already watching :${d}]`),{port:d,projectId:i,close:async()=>{}};continue}throw w}if(!jr)throw new Error(`[Bridge] All ports ${t}\u2013${t+Mr-1} in use`);for(let[d,w]of Object.entries(l))!w.available||!w.path||f(d,w.path).then(A=>{if(A)console.log(`[Bridge] ${d} warmed up`);else{console.warn(`[Bridge] ${d} warm-up failed \u2014 marking unavailable`),w.available=!1,w.path=null;for(let I of oe)Ao(I,{type:"capabilities_changed",data:{}})}});let ia=setInterval(()=>{Bs(c).catch(()=>{}),q.sweep().catch(()=>{})},sp),Ar=setInterval(()=>{K.expireStale().becameEmpty&&X()},dp);return Ar.unref?.(),{port:y,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(ia),clearInterval(Ar),G(),K.clear(),await q.cleanupPartials(),await k.destroyAsync(),O.destroy();for(let d of oe)try{d.res.end()}catch{}return oe.clear(),new Promise(d=>{xe.close(()=>d())})}}}async function Bs(o){try{let e=await Gl(o),t=Date.now();for(let n of e){let r=qe(o,n);try{let i=await Ql(r);t-i.mtimeMs>ap&&await Xl(r)}catch{}}}catch{}}var Rp=parseInt(process.env.POPMELT_PORT||"1111",10),Us=process.env.POPMELT_PROJECT_ROOT||process.cwd(),Pp=process.env.POPMELT_DEV_ORIGIN||void 0,Mp=process.env.POPMELT_COPILOT_PATH||void 0,jp=process.env.POPMELT_CDP_URL||void 0,zs=Fs(Us,".popmelt"),Vs=Fs(zs,"bridge.lock");async function Ap(o){await Sp(zs,{recursive:!0}),await kp(Vs,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
237
- `)}async function Ws(){try{await Tp(Vs)}catch{}}async function Ep(){let o=await Ls({port:Rp,projectRoot:Us,devOrigin:Pp,copilotPath:Mp,nativeCaptureUrl:jp,restartMode:"detached"});await Ap(o.port),await new Promise(e=>{let t=!1,n=async()=>{t||(t=!0,await o.close(),await Ws(),e(),process.exit(0))};process.on("SIGTERM",n),process.on("SIGINT",n)})}Ep().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),Ws().finally(()=>process.exit(1))});
206
+ `);let I=new URL(d.url||"/",`http://127.0.0.1:${y}`).searchParams.get("sourceId")||void 0,A={id:dt().slice(0,8),res:v,sourceId:I};oe.add(A),d.on("close",()=>{oe.delete(A)})}async function pt(d,v,_){a??=gs(d.headers),nt();let I=[...k.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}))],[A,R,N,J,U]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),B.status(),Q.store.load(),x.load()]),F=[],L=Y=>Y.reason instanceof Error?Y.reason.message:String(Y.reason);A.status==="rejected"&&F.push({subsystem:"projection",message:L(A)}),R.status==="rejected"&&F.push({subsystem:"projection",message:L(R)}),N.status==="rejected"?F.push({subsystem:"memory",message:L(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:L(J)}),U.status==="rejected"&&F.push({subsystem:"threads",message:L(U)});let ge=A.status==="fulfilled"?A.value.runs:[],V=R.status==="fulfilled"?R.value.proposals:[],me=ys(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:L(N)},ye=U.status==="fulfilled"?[...new Set(Object.values(U.value.threads).flatMap(Y=>En(Y.messages)))]:[],ne=J.status==="fulfilled"?ye.filter(Y=>J.value.graph.explanations.some(ke=>ke.id===Y&&ke.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:L(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();$(v,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Re,issues:F},version:An,restartMode:g,projectId:i,storeId:s.storeId,projectName:Mo(r),projectRoot:r,requestProjectId:_,projectIdVerified:_===i,devOrigin:a,capture:{native:{configured:!!u,endpoint:u?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.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:k.depth+O.depth,projectionQueueDepth:O.depth,leases:{active:K.isActivated,count:K.size,nextExpiryAt:K.nextExpiryAt,shutdownPending:W},projection:{state:A.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:en,recentJobs:Me})}async function It(d,v){let _=await new Promise(I=>{let A="";d.on("data",R=>{A+=R.toString()}),d.on("end",()=>I(A))});try{let I=JSON.parse(_);typeof I.devOrigin=="string"&&(a=I.devOrigin||null),$(v,200,{ok:!0,devOrigin:a})}catch{$(v,400,{error:"Invalid JSON"})}}async function Eo(d){let v=await he.load();$(d,200,{ok:!0,...v})}async function _o(d,v){let _=await Oe(d);if(!Rs(_.theme)){$(v,400,{error:"theme must be light, dark, or auto"});return}let I=await he.setTheme(_.theme);$(v,200,{ok:!0,exists:!0,preferences:I})}async function tn(d,v){let I=new URL(d.url||"/",`http://127.0.0.1:${y}`).searchParams.get("jobId"),A=I?k.allActive.filter(L=>L.id===I):k.allActive,R=I?O.allActive.filter(L=>L.id===I):O.allActive,N=[...A.map(L=>L.threadId),...R.map(L=>L.threadId)].filter(Boolean),J=I?k.cancelJob(I):k.cancelActive(),U=I?O.cancelJob(I):O.cancelActive(),F=!!(J||U);for(let L of N)await x.appendMessage(L,{role:"assistant",timestamp:Date.now(),jobId:I||U?.id||"",cancelled:!0});$(v,200,{cancelled:F})}async function $e(d){let v=dt().slice(0,8),_=d.threadId,I=!_;_||(_=(await x.createThread(`thread-${dt()}`,[])).id,yt.set(_,"project_model")),I&&await x.appendMessage(_,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:d.reason}),await x.appendMessage(_,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:d.model,provider:d.provider});let A={id:v,status:"queued",createdAt:Date.now(),provider:d.provider,model:d.model,agentSettings:d.agentSettings,threadId:_,annotationIds:d.annotationIds,sourceId:d.sourceId,standalone:I},R=O.enqueue(A);return{jobId:v,position:R,threadId:_}}async function Le(d,v){let _=decodeURIComponent(d),I=await se.findModelProposal(_);if(!I){$(v,404,{error:"Model proposal not found"});return}$(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:I})}async function ut(d,v,_){let I=decodeURIComponent(d),A=[];for await(let V of v)A.push(typeof V=="string"?Buffer.from(V):V);let R;try{R=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{$(_,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){$(_,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(I);if(!U){$(_,404,{error:"Model proposal not found"});return}if(U.authorityStatus!=="accepted"){$(_,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(U.status!=="pending"){$(_,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}}),L=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(I,N,J);if(!ge){$(_,404,{error:"Model proposal not found"});return}if(ge.threadId){let V=Zt(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})}$(_,200,{proposal:ge,projection:L})}async function Et(d,v,_){let I=decodeURIComponent(d),{provider:A,model:R}=await wt(v),N=await se.dismissModelProposal(I);if(!N){$(_,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:A,model:R}),$(_,200,{proposal:N})}async function wt(d){try{let v=[];for await(let I of d)v.push(typeof I=="string"?Buffer.from(I):I);if(v.length===0)return{};let _=JSON.parse(Buffer.concat(v).toString());return{provider:Zt(typeof _.provider=="string"?_.provider:void 0),model:typeof _.model=="string"&&_.model?_.model:void 0,agentSettings:Vt(_)}}catch{return{}}}async function Co(d){let v=yt.get(d);if(v)return v;let A=(await x.getThread(d))?.messages.find(R=>R.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return yt.set(d,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return yt.set(d,"project_model"),"project_model"}async function _n(d,v){let _=[];for await(let U of d)_.push(typeof U=="string"?Buffer.from(U):U);let I;if(_.length>0)try{I=JSON.parse(Buffer.concat(_).toString("utf-8")).serverUrl}catch{}let A=[];l.claude?.available&&l.claude.mcp&&!l.claude.mcp.found&&A.push(await Wi(I)),l.codex?.available&&l.codex.mcp&&!l.codex.mcp.found&&A.push(await Ki(I)),l.copilot?.available&&l.copilot.mcp&&!l.copilot.mcp.found&&A.push(await Gi(I,l.copilot.path??P));let[R,N,J]=await Promise.all([fr(r),hr(r),gr(r,l.copilot?.path??P)]);l.claude&&(l.claude.mcp=R),l.codex&&(l.codex.mcp=N),l.copilot&&(l.copilot.mcp=J),$(v,200,{results:A,capabilities:{providers:l}})}async function Vs(d,v){let _=[];for await(let R of d)_.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{$(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){$(v,400,{error:"Missing or invalid name"});return}let A=await B.recordDirectModelMutation({key:`components.${I.name}`,value:{description:""},claim:`${I.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),$(v,200,{added:!0,alreadyExists:!1,...A})}async function Ws(d,v){let _=[];for await(let R of d)_.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{$(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){$(v,400,{error:"Missing or invalid name"});return}let A=await B.recordDirectModelMutation({key:`components.${I.name}`,value:null,claim:`${I.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),$(v,200,{removed:!0,...A})}async function Ks(d,v){let _=[];for await(let N of d)_.push(typeof N=="string"?Buffer.from(N):N);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{$(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){$(v,400,{error:"Missing or invalid path/value"});return}let A=I.value;try{let N=JSON.parse(I.value);N&&typeof N=="object"&&(A=N)}catch{}let R=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:A,claim:`${I.path} uses ${I.value} in the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),$(v,200,{updated:!0,...R})}async function Gs(d,v){let _=[];for await(let R of d)_.push(typeof R=="string"?Buffer.from(R):R);let I;try{I=JSON.parse(Buffer.concat(_).toString("utf-8"))}catch{$(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){$(v,400,{error:"Missing or invalid path"});return}let A=await B.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await B.getCanonicalModelEntries()),$(v,200,{removed:!0,...A})}async function Hs(d,v){if(!d||d.includes("/")||d.includes("\\")||d.includes("..")){$(v,400,{error:"Invalid filename"});return}try{let _=[Xe(c,d),Xe(r,".popmelt","artifacts","thread-media",d),Xe(r,".popmelt","artifacts","eval-screenshots",d),Xe(r,".popmelt","evals","screenshots",d),Xe(r,".popmelt","screenshots",d)],I;for(let N of _)try{I=await Ll(N);break}catch{}if(!I)throw new Error("File not found");let A=d.split(".").pop()?.toLowerCase(),R=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";v.writeHead(200,{"Content-Type":R,"Cache-Control":"public, max-age=3600"}),v.end(I)}catch{$(v,404,{error:"File not found"})}}function nn(d){return`/files/${Mo(d)}`}async function Qs(d,v){let _=await x.getThread(d);if(!_){$(v,404,{error:"Thread not found"});return}let I=_.messages.filter(F=>F.role==="assistant"&&F.responseText?.includes("Model suggestion ready")),A=await(I.length>0?se.findModelProposalsByThread(d):Promise.resolve([])),R=await Promise.all(A.map(async(F,L)=>{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??I[L]?.jobId??I.at(-1)?.jobId,underlyingProposalId:ge?.proposalId,underlyingClaim:ge?.claim}})),N=[...R].sort((F,L)=>L.updatedAt-F.updatedAt)[0]??null,J=_.elementIdentifiers.some(F=>F.startsWith("codex-session:"))?await B.findPendingProposalsForThread(d):[],U=_.messages.map(({screenshotPath:F,screenshotPaths:L,imagePaths:ge,attachmentFiles:V,replyImagePaths:me,...re})=>({...re,...F?{screenshotUrl:nn(F)}:{},...L?{screenshotUrls:Object.fromEntries(Object.entries(L).map(([Z,ye])=>[Z,nn(ye)]))}:{},...ge?{imageUrls:Object.fromEntries(Object.entries(ge).map(([Z,ye])=>[Z,ye.map(nn)]))}:{},...V?{attachments:Object.fromEntries(Object.entries(V).map(([Z,ye])=>[Z,ye.map(({path:ne,...be})=>({...be,url:nn(ne)}))]))}:{},...me?{replyImageUrls:me.map(nn)}:{}}));$(v,200,{id:_.id,createdAt:_.createdAt,messages:U,modelProposal:N,modelProposals:R,decisionCandidates:J})}async function Xs(d,v){let _=decodeURIComponent(d);if(!await x.deleteThread(_)){$(v,404,{deleted:!1,error:"Thread not found"});return}$(v,200,{deleted:!0})}let Mr=9,jr=!1;for(let d=t;d<t+Mr;d++)try{await fp(At,d),y=d,jr=!0,console.log(`[\u22B9 is watching :${y}]`);break}catch(v){if(v.code==="EADDRINUSE"){let _=await mp(d);if(hs(_,{projectId:i,version:An,restartMode:g}))return console.log(`[\u22B9 already watching :${d}]`),{port:d,projectId:i,close:async()=>{}};continue}throw v}if(!jr)throw new Error(`[Bridge] All ports ${t}\u2013${t+Mr-1} in use`);for(let[d,v]of Object.entries(l))!v.available||!v.path||f(d,v.path).then(_=>{if(_)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 I of oe)jo(I,{type:"capabilities_changed",data:{}})}});let Ys=setInterval(()=>{Ds(c).catch(()=>{}),q.sweep().catch(()=>{})},Yl),Ar=setInterval(()=>{K.expireStale().becameEmpty&&X()},ep);return Ar.unref?.(),{port:y,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(Ys),clearInterval(Ar),G(),K.clear(),await q.cleanupPartials(),await k.destroyAsync(),O.destroy();for(let d of oe)try{d.res.end()}catch{}return oe.clear(),new Promise(d=>{At.close(()=>d())})}}}async function Ds(o){try{let e=await Fl(o),t=Date.now();for(let n of e){let r=Xe(o,n);try{let i=await zl(r);t-i.mtimeMs>Zl&&await Vl(r)}catch{}}}catch{}}var Ip=parseInt(process.env.POPMELT_PORT||"1111",10),Ls=process.env.POPMELT_PROJECT_ROOT||process.cwd(),wp=process.env.POPMELT_DEV_ORIGIN||void 0,vp=process.env.POPMELT_COPILOT_PATH||void 0,bp=process.env.POPMELT_CDP_URL||void 0,Fs=qs(Ls,".popmelt"),Us=qs(Fs,"bridge.lock");async function xp(o){await hp(Fs,{recursive:!0}),await yp(Us,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
207
+ `)}async function zs(){try{await gp(Us)}catch{}}async function Sp(){let o=await Js({port:Ip,projectRoot:Ls,devOrigin:wp,copilotPath:vp,nativeCaptureUrl:bp,restartMode:"detached"});await xp(o.port),await new Promise(e=>{let t=!1,n=async()=>{t||(t=!0,await o.close(),await zs(),e(),process.exit(0))};process.on("SIGTERM",n),process.on("SIGINT",n)})}Sp().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),zs().finally(()=>process.exit(1))});