@popmelt.com/core 0.10.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/bridge-entry.mjs +52 -50
- package/dist/{chunk-4RGL22V3.mjs → chunk-QLR2E4AW.mjs} +1 -1
- package/dist/cli.mjs +64 -62
- package/dist/index.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-FHMR7WJR.mjs → server-GSD37B5H.mjs} +53 -51
- package/dist/server.mjs +70 -68
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as $o,b as Oo}from"./chunk-NOHXTT24.mjs";import{spawn as sp}from"child_process";import{closeSync as ap,openSync as dp}from"fs";import{appendFile as cp,mkdir as lp,readFile as pp,realpath as up}from"fs/promises";import{dirname as mp,join as Ao}from"path";import{fileURLToPath as fp}from"url";import{execFileSync as Ml,spawn as Rs}from"child_process";import{randomUUID as ct}from"crypto";import{mkdir as El,readFile as As,readdir as _l,realpath as Cl,stat as $l,unlink as Ol,writeFile as Ri}from"fs/promises";import{createServer as Dl}from"http";import{tmpdir as Nl}from"os";import{basename as Ai,dirname as Bl,isAbsolute as $s,join as Be,relative as Jl,resolve as Ll}from"path";import{fileURLToPath as ql}from"url";function Do(i,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -28,25 +28,27 @@ import{a as Co,b as $o}from"./chunk-NOHXTT24.mjs";import{spawn as ip}from"child_
|
|
|
28
28
|
});
|
|
29
29
|
</script>
|
|
30
30
|
</body>
|
|
31
|
-
</html>`}import{createHash as
|
|
31
|
+
</html>`}import{createHash as ba,randomUUID as xa}from"crypto";import{isAbsolute as Sa,relative as Ta}from"path";function _t(i,e){return!i||e||i.attention!=="response_requested"?i:{...i,attention:"response_available"}}function an(i){let e=Array.from(new Set((i.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=i.decisionRequired?"decision_required":i.question||i.groundingRequired?"response_requested":i.reviewRequired||i.resolutions?.some(o=>o.status==="needs_review")?"review_required":"response_available";return i.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:i.imprintTransactionId}),{attention:n,outcomes:t}}function Ct(i){return i.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
32
32
|
`)}async function dn(i,e,t,n){let o=Ct(e);if(!(!o&&t.length===0))try{let r=await i.contextualize({action:o||void 0,subjectHints:t,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(c=>[c.decisionId,c.state])),d=new Map(r.actionPacket.verification.map(c=>[c.target.entityId,c.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(c=>({...c,implementation:s.get(c.id)??"unknown",verification:d.get(c.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.reviewSelection.packets.map(c=>({packetId:c.packetId,proposalId:c.proposal.id,claim:c.proposal.claim,proposedKind:c.proposal.proposedKind,authority:c.authority,presentation:c.presentation,subjectLabels:c.trigger.subjectMatches.map(l=>l.label),evidenceCount:c.evidence.sourceCount,expansionRefs:c.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){n?.(r);return}}function cn(i){if(!i?.packets.length&&!i?.acceptedTruth?.decisions.length)return"";let e=i.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...i.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.",...i.acceptedTruth.decisions.flatMap((n,o)=>["",`${o+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...i.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...i.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...i.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...i.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...i.packets.flatMap((n,o)=>["",`${o+1}. ${n.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
33
|
-
`)}import{randomUUID as rt}from"crypto";function
|
|
34
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await ra(t,i)}catch(o){throw await sa(t).catch(()=>{}),o}}function da(i,e){return{version:1,projectId:i,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function ca(i,e){let t=i.explanations.findIndex(n=>n.id===e.id);t>=0?i.explanations[t]=De(e):i.explanations.push(De(e))}function $n(i,e){let t=De(i);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(o=>o.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(De(n.explanation))}else if(n.op==="replace_explanation")ca(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(o=>o.id!==n.explanationId),t.relations=t.relations.filter(o=>o.fromId!==n.explanationId&&o.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(o=>o.id===n.concrete.id)||t.concrete.push(De(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(o=>o.id!==n.concreteId),t.relations=t.relations.filter(o=>o.fromId!==n.concreteId&&o.toId!==n.concreteId);else if(n.op==="add_evidence"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);o.evidence.some(r=>r.id===n.evidence.id)||(o.evidence.push(De(n.evidence)),o.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(o,De(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let o=n.relation,r=t.explanations.find(l=>l.id===o.fromId),s=t.explanations.find(l=>l.id===o.toId),d=t.concrete.some(l=>l.id===o.fromId),c=t.concrete.some(l=>l.id===o.toId);if(Jo(o.type)){if(!(o.type==="expresses"?!!((r||d)&&s):!!(r&&s)))throw new Error(`Imprint ${o.type} relation has invalid endpoints: ${o.id}`);if(t.relations.some(w=>w.type===o.type&&w.fromId===o.fromId&&w.toId===o.toId))throw new Error(`Duplicate imprint relation: ${o.type}:${o.fromId}:${o.toId}`);if(o.type==="expresses"&&r&&s){if($t(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${o.id}`);let w=new Map;for(let R of t.relations)R.type==="expresses"&&w.set(R.fromId,[...w.get(R.fromId)??[],R.toId]);let k=[o.toId],T=new Set;for(;k.length;){let R=k.pop();if(R===o.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${o.id}`);T.has(R)||(T.add(R),k.push(...w.get(R)??[]))}}}else if(!r||!s&&!c)throw new Error(`Imprint relation references an unknown explanation: ${o.id}`);t.relations.some(l=>l.id===o.id)||t.relations.push(De(o))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(o=>o.id!==n.relationId));return t}function la(i,e){let t=[],n=De(i);for(let o of e){if(o.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:o.explanation.id});else if(o.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===o.explanationId);r&&t.unshift({op:"add_explanation",explanation:De(r)})}else if(o.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:o.concrete.id});else if(o.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===o.concreteId);r&&t.unshift({op:"add_concrete",concrete:De(r)})}else if(o.op==="replace_explanation"||o.op==="revise_explanation"||o.op==="add_evidence"){let r=o.op==="replace_explanation"?o.explanation.id:o.explanationId,s=n.explanations.find(d=>d.id===r);s&&t.unshift({op:"replace_explanation",explanation:De(s)})}else if(o.op==="add_relation")t.unshift({op:"remove_relation",relationId:o.relation.id});else if(o.op==="remove_relation"){let r=n.relations.find(s=>s.id===o.relationId);r&&t.unshift({op:"add_relation",relation:De(r)})}n=$n(n,[o])}return t}function qo(i){return i.op==="add_explanation"||i.op==="replace_explanation"?[i.explanation.id]:i.op==="remove_explanation"||i.op==="add_evidence"||i.op==="revise_explanation"?[i.explanationId]:i.op==="add_relation"?[i.relation.fromId,i.relation.toId]:[]}var Dt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Bo(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 oa(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),o=da(this.projectId,e.createdAt),r=[],s=null;for(let d=0;d<n.length;d++){let c=JSON.parse(await Bo(Ot(this.journalDir,n[d]),"utf8")),{hash:l,...w}=c;if(c.sequence!==d+1||c.previousHash!==s||l!==Lo(w))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);o=$n(o,c.mutations),o.updatedAt=c.committedAt,o.head={sequence:c.sequence,hash:c.hash},r.push(c),s=c.hash}return{graph:o,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:xt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=xt(t.graph),o=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let d=o.get(s.id);d&&d.type===s.type&&d.fromId===s.fromId&&d.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),d&&r.push({op:"add_relation",relation:d}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await St(this.graphPath,n),await St(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(k=>k.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let o=n.graph.head.sequence+1,r=la(n.graph,e.mutations),s={version:1,sequence:o,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:De(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...s,hash:Lo(s)},c=$n(n.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:o,hash:d.hash};let l=`${String(o).padStart(12,"0")}-${e.transactionId}.json`;await St(Ot(this.journalDir,l),d);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await St(this.graphPath,c),await St(this.manifestPath,w),t={graph:c,transaction:d}}),await this.writeChain,t}async undo(e,t,n,o){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(s.mutations.flatMap(qo));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>qo(w).some(k=>d.has(k)))))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:o,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 pa=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),ua=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"]),ma=[/\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],fa=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Ji(i){return!!(i&&fa.test(i))}function ha(i){return i.scope.kind==="project"||Ji(`${i.statement} ${i.rationale}`)}function ga(i){let e=i?.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 ya(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Ia(i){return i.length>4&&i.endsWith("ies")?[i,`${i.slice(0,-3)}y`]:i.length>3&&i.endsWith("s")&&!i.endsWith("ss")?[i,i.slice(0,-1)]:[i]}function ot(i){return new Set(ya(i).split(" ").filter(e=>e.length>2&&!ua.has(e)).flatMap(Ia))}function Fo(i){return i.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function va(i){if(i)for(let e of ma){let t=e.exec(i);if(!t||t.index<=0)continue;let n=Fo(i.slice(0,t.index)),o=Fo(i.slice(t.index+t[0].length));if(n&&o)return{target:n,reference:o}}}function mt(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function Ni(i){return!i||!Array.isArray(i.values)||i.values.length===0?{kind:"project",values:["*"]}:{kind:i.kind,values:[...new Set(i.values.map(e=>e.trim()).filter(Boolean))]}}function ft(i,e,t){return{id:rt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:i.threadId,jobId:i.jobId,createdAt:i.occurredAt??new Date().toISOString()}}function we(i,e=800){return typeof i=="string"?i.trim().slice(0,e):""}function Uo(i){if(!i||typeof i!="object"||Array.isArray(i))return;let e=i;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 zo(i,e){if(!i||!e.trim())return{found:!1};let t=i;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let o=Number(n);if(!Number.isInteger(o)||o<0||o>=t.length)return{found:!1};t=t[o]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Jt(i,e={}){let t=[...i.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=i.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),o=t.at(-1)?.[1],r,s=[];if(o)r=o;else{let c=[...i.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!c)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(c);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let w=l;r=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let d=typeof r=="string"?JSON.parse(r):r;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("imprint assessment is invalid");if(d.decision==="none"){let f=String(d.reason);if(!pa.has(f))throw new Error("imprint no-op reason is invalid");if(f==="task_specific_detail"&&s.some(E=>{if(!E||typeof E!="object"||Array.isArray(E))return!1;let D=E;return(D.finalScope??D.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(d.usedExplanationIds)?d.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],v=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...g])].some(E=>!v.has(E)))throw new Error("imprint use must cite only surfaced explanations");let M=[...new Set([...p,...e.applicationOccurred?[]:g])],h=e.applicationOccurred?g:[],m;if(h.length){m=h;let E=new Set(e.context?.pendingGroundingExplanationIds??[]),D=h.filter(S=>{let C=e.context?.explanations.find(z=>z.id===S);return v.has(S)&&C&&(C.state==="emerging"||C.state==="testing")&&!E.has(S)});if(D.length){let S=d.grounding,C=typeof S?.explanationId=="string"&&D.includes(S.explanationId)?S.explanationId:D[0],z=we(S?.question,300);return{draft:{decision:"apply",summary:{title:we(d.summary?.title,120)||"Applied shared understanding",detail:we(d.summary?.detail,500)||we(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:h,grounding:{explanationId:C,question:z||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(f==="duplicate"){let E=we(d.duplicateOfExplanationId,100),D=d.scopeComparison;if(!E)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let S=e.context?.explanations.find(C=>C.id===E);if(!S)throw new Error("duplicate assessment must cite a surfaced explanation");if(Ji(e.requestText)&&!ha(S))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:E,scopeComparison:D,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}if(d.decision==="recognize"){let f=we(d.explanationId,100);if(!f)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(u=>u.id===f);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let g=d.summary,v={title:we(g?.title,120),detail:we(g?.detail,500)};if(!v.title||!v.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:v},visibleText:n}}if(d.decision==="apply"){let f=d.summary,p={title:we(f?.title,120),detail:we(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let v=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!v.has(E)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(g)]},visibleText:n};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(E=>{let D=v.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!u.has(E)});if(!M.length){if(g.every(D=>v.get(D)?.state==="grounded"||u.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let h=d.grounding,m=typeof h?.explanationId=="string"&&M.includes(h.explanationId)?h.explanationId:M[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:g,grounding:{explanationId:m,question:we(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(d.decision!==void 0&&d.decision!=="mutate")throw new Error("imprint decision is invalid");let c=d.summary,l=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let w={kind:l,title:we(c?.title,120),detail:we(c?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let k=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],T=[];for(let f of Array.isArray(d.mutations)?d.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let g=we(p.statement),v=we(p.rationale);if(!g||!v)continue;T.push({op:"add",clientId:we(p.clientId,100)||void 0,kind:p.kind,statement:g,rationale:v,scope:Uo(p.scope),rootReason:we(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let g={op:"revise",explanationId:p.explanationId,statement:we(p.statement)||void 0,rationale:we(p.rationale)||void 0,scope:Uo(p.scope),reopenGrounding:p.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&T.push(g)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let g=we(p.summary);g&&T.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:g})}else if(p.op==="relation"&&typeof p.fromId=="string"&&typeof p.toId=="string"&&["expresses","excepts"].includes(String(p.type))){let g=we(p.rationale);if(!g)continue;T.push({op:"relation",type:p.type,fromId:p.fromId,toId:p.toId,rationale:g})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let g=we(p.reason);g&&T.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:g})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let g=we(p.modelPath,300);g&&T.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:g,rationale:we(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&T.push({op:"retire",explanationId:p.explanationId,reason:we(p.reason)})}let R=d.grounding,x=R&&typeof R.explanationId=="string"&&we(R.question)?{explanationId:R.explanationId,question:we(R.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:k,mutations:T,grounding:x},visibleText:n}}catch(d){return{visibleText:n,error:d instanceof Error?d.message:String(d)}}}function Bt(i,e={}){let t=i?.explanations??[],n=new Set(i?.pendingGroundingExplanationIds??[]),o=new Set(i?.correctionExplanationIds??[]),r=Ji(e.requestText),s=i?.retrievalIntent,d=i?.historicalCaveats??[];return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((c,l)=>[`${l+1}. [${c.state}; ${c.kind}] ${c.statement}`,` - Why: ${c.rationale}`,` - Scope: ${c.scope.kind} ${c.scope.values.join(", ")}`,` - Explanation: ${c.id}`,...n.has(c.id)?[" - Grounding: already pending; do not ask again"]:[],...o.has(c.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...c.concrete.map(w=>` - Concrete terminal: ${w.modelPath} = ${JSON.stringify(w.value)}`)].join(`
|
|
33
|
+
`)}import{randomUUID as rt}from"crypto";function Ni(i,e){return{storeId:i,explanationId:e}}function ea(i,e){let{fromId:t,toId:n,...o}=e;return{...o,from:Ni(i,t),to:Ni(i,n)}}var No={project:0,route:1,component:2,selector:2,file:3},Bo={intention:0,principle:1,pattern:2};function $t(i,e){let t=No[i.scope.kind]-No[e.scope.kind];return t!==0?t:Bo[i.kind]-Bo[e.kind]}function Jo(i){return i==="expresses"||i==="excepts"}function ta(i,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=i.explanations.find(r=>r.id===e.fromId),n=i.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let o=$t(t,n);return o===0?void 0:o>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function xt(i){let e=structuredClone(i),t=new Set;return e.relations=i.relations.flatMap(n=>{let o=ta(i,n);if(!o)return[];let r=`${o.type}:${o.fromId}:${o.toId}`;return t.has(r)?[]:(t.add(r),[o])}),e}import{createHash as na}from"crypto";import{mkdir as ia,open as oa,readFile as Lo,readdir as ra,rename as sa,unlink as aa}from"fs/promises";import{dirname as da,join as Ot}from"path";function De(i){return structuredClone(i)}function qo(i){return na("sha256").update(JSON.stringify(i)).digest("hex")}async function St(i,e){await ia(da(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await oa(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
34
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await sa(t,i)}catch(o){throw await aa(t).catch(()=>{}),o}}function ca(i,e){return{version:1,projectId:i,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function la(i,e){let t=i.explanations.findIndex(n=>n.id===e.id);t>=0?i.explanations[t]=De(e):i.explanations.push(De(e))}function $n(i,e){let t=De(i);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(o=>o.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(De(n.explanation))}else if(n.op==="replace_explanation")la(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(o=>o.id!==n.explanationId),t.relations=t.relations.filter(o=>o.fromId!==n.explanationId&&o.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(o=>o.id===n.concrete.id)||t.concrete.push(De(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(o=>o.id!==n.concreteId),t.relations=t.relations.filter(o=>o.fromId!==n.concreteId&&o.toId!==n.concreteId);else if(n.op==="add_evidence"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);o.evidence.some(r=>r.id===n.evidence.id)||(o.evidence.push(De(n.evidence)),o.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(o,De(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let o=n.relation,r=t.explanations.find(l=>l.id===o.fromId),s=t.explanations.find(l=>l.id===o.toId),d=t.concrete.some(l=>l.id===o.fromId),c=t.concrete.some(l=>l.id===o.toId);if(Jo(o.type)){if(!(o.type==="expresses"?!!((r||d)&&s):!!(r&&s)))throw new Error(`Imprint ${o.type} relation has invalid endpoints: ${o.id}`);if(t.relations.some(w=>w.type===o.type&&w.fromId===o.fromId&&w.toId===o.toId))throw new Error(`Duplicate imprint relation: ${o.type}:${o.fromId}:${o.toId}`);if(o.type==="expresses"&&r&&s){if($t(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${o.id}`);let w=new Map;for(let k of t.relations)k.type==="expresses"&&w.set(k.fromId,[...w.get(k.fromId)??[],k.toId]);let R=[o.toId],b=new Set;for(;R.length;){let k=R.pop();if(k===o.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${o.id}`);b.has(k)||(b.add(k),R.push(...w.get(k)??[]))}}}else if(!r||!s&&!c)throw new Error(`Imprint relation references an unknown explanation: ${o.id}`);t.relations.some(l=>l.id===o.id)||t.relations.push(De(o))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(o=>o.id!==n.relationId));return t}function pa(i,e){let t=[],n=De(i);for(let o of e){if(o.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:o.explanation.id});else if(o.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===o.explanationId);r&&t.unshift({op:"add_explanation",explanation:De(r)})}else if(o.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:o.concrete.id});else if(o.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===o.concreteId);r&&t.unshift({op:"add_concrete",concrete:De(r)})}else if(o.op==="replace_explanation"||o.op==="revise_explanation"||o.op==="add_evidence"){let r=o.op==="replace_explanation"?o.explanation.id:o.explanationId,s=n.explanations.find(d=>d.id===r);s&&t.unshift({op:"replace_explanation",explanation:De(s)})}else if(o.op==="add_relation")t.unshift({op:"remove_relation",relationId:o.relation.id});else if(o.op==="remove_relation"){let r=n.relations.find(s=>s.id===o.relationId);r&&t.unshift({op:"add_relation",relation:De(r)})}n=$n(n,[o])}return t}function Fo(i){return i.op==="add_explanation"||i.op==="replace_explanation"?[i.explanation.id]:i.op==="remove_explanation"||i.op==="add_evidence"||i.op==="revise_explanation"?[i.explanationId]:i.op==="add_relation"?[i.relation.fromId,i.relation.toId]:[]}var Dt=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Ot(e,".popmelt","imprint"),this.manifestPath=Ot(this.imprintDir,"manifest.json"),this.graphPath=Ot(this.imprintDir,"graph.json"),this.journalDir=Ot(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Lo(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 ra(this.journalDir).catch(d=>{if(d.code==="ENOENT")return[];throw d})).filter(d=>/^\d{12}-.+\.json$/.test(d)).sort(),o=ca(this.projectId,e.createdAt),r=[],s=null;for(let d=0;d<n.length;d++){let c=JSON.parse(await Lo(Ot(this.journalDir,n[d]),"utf8")),{hash:l,...w}=c;if(c.sequence!==d+1||c.previousHash!==s||l!==qo(w))throw new Error(`Imprint journal hash mismatch at sequence ${c.sequence}.`);o=$n(o,c.mutations),o.updatedAt=c.committedAt,o.head={sequence:c.sequence,hash:c.hash},r.push(c),s=c.hash}return{graph:o,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:xt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=xt(t.graph),o=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let d=o.get(s.id);d&&d.type===s.type&&d.fromId===s.fromId&&d.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),d&&r.push({op:"add_relation",relation:d}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await St(this.graphPath,n),await St(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(R=>R.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let o=n.graph.head.sequence+1,r=pa(n.graph,e.mutations),s={version:1,sequence:o,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:De(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},d={...s,hash:qo(s)},c=$n(n.graph,d.mutations);c.updatedAt=e.committedAt,c.head={sequence:o,hash:d.hash};let l=`${String(o).padStart(12,"0")}-${e.transactionId}.json`;await St(Ot(this.journalDir,l),d);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:c.createdAt,updatedAt:e.committedAt,head:c.head};await St(this.graphPath,c),await St(this.manifestPath,w),t={graph:c,transaction:d}}),await this.writeChain,t}async undo(e,t,n,o){let r=await this.load(),s=r.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let d=new Set(s.mutations.flatMap(Fo));if(r.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(w=>Fo(w).some(R=>d.has(R)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:o,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 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 Ji(i){return!!(i&&ha.test(i))}function ga(i){return i.scope.kind==="project"||Ji(`${i.statement} ${i.rationale}`)}function ya(i){let e=i?.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(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function va(i){return i.length>4&&i.endsWith("ies")?[i,`${i.slice(0,-3)}y`]:i.length>3&&i.endsWith("s")&&!i.endsWith("ss")?[i,i.slice(0,-1)]:[i]}function ot(i){return new Set(Ia(i).split(" ").filter(e=>e.length>2&&!ma.has(e)).flatMap(va))}function Uo(i){return i.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function wa(i){if(i)for(let e of fa){let t=e.exec(i);if(!t||t.index<=0)continue;let n=Uo(i.slice(0,t.index)),o=Uo(i.slice(t.index+t[0].length));if(n&&o)return{target:n,reference:o}}}function mt(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function Bi(i){return!i||!Array.isArray(i.values)||i.values.length===0?{kind:"project",values:["*"]}:{kind:i.kind,values:[...new Set(i.values.map(e=>e.trim()).filter(Boolean))]}}function ft(i,e,t){return{id:rt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:i.threadId,jobId:i.jobId,createdAt:i.occurredAt??new Date().toISOString()}}function we(i,e=800){return typeof i=="string"?i.trim().slice(0,e):""}function zo(i){if(!i||typeof i!="object"||Array.isArray(i))return;let e=i;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 Wo(i,e){if(!i||!e.trim())return{found:!1};let t=i;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let o=Number(n);if(!Number.isInteger(o)||o<0||o>=t.length)return{found:!1};t=t[o]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Bt(i,e={}){let t=[...i.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=i.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),o=t.at(-1)?.[1],r,s=[];if(o)r=o;else{let c=[...i.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!c)return{visibleText:n,error:"imprint assessment is missing"};try{let l=JSON.parse(c);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let w=l;r=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let d=typeof r=="string"?JSON.parse(r):r;if(!d||typeof d!="object"||Array.isArray(d))throw new Error("imprint assessment is invalid");if(d.decision==="none"){let f=String(d.reason);if(!ua.has(f))throw new Error("imprint no-op reason is invalid");if(f==="task_specific_detail"&&s.some(E=>{if(!E||typeof E!="object"||Array.isArray(E))return!1;let D=E;return(D.finalScope??D.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let p=Array.isArray(d.usedExplanationIds)?d.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],v=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...g])].some(E=>!v.has(E)))throw new Error("imprint use must cite only surfaced explanations");let M=[...new Set([...p,...e.applicationOccurred?[]:g])],h=e.applicationOccurred?g:[],m;if(h.length){m=h;let E=new Set(e.context?.pendingGroundingExplanationIds??[]),D=h.filter(T=>{let C=e.context?.explanations.find(z=>z.id===T);return v.has(T)&&C&&(C.state==="emerging"||C.state==="testing")&&!E.has(T)});if(D.length){let T=d.grounding,C=typeof T?.explanationId=="string"&&D.includes(T.explanationId)?T.explanationId:D[0],z=we(T?.question,300);return{draft:{decision:"apply",summary:{title:we(d.summary?.title,120)||"Applied shared understanding",detail:we(d.summary?.detail,500)||we(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:h,grounding:{explanationId:C,question:z||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(f==="duplicate"){let E=we(d.duplicateOfExplanationId,100),D=d.scopeComparison;if(!E)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let T=e.context?.explanations.find(C=>C.id===E);if(!T)throw new Error("duplicate assessment must cite a surfaced explanation");if(Ji(e.requestText)&&!ga(T))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:E,scopeComparison:D,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:n}}if(d.decision==="recognize"){let f=we(d.explanationId,100);if(!f)throw new Error("recognition requires explanationId");let p=e.context?.explanations.find(u=>u.id===f);if(!p)throw new Error("recognition must cite a surfaced explanation");if(p.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let g=d.summary,v={title:we(g?.title,120),detail:we(g?.detail,500)};if(!v.title||!v.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:v},visibleText:n}}if(d.decision==="apply"){let f=d.summary,p={title:we(f?.title,120),detail:we(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let g=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let v=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!v.has(E)))throw new Error("application must cite only surfaced explanations");if(!e.applicationOccurred)return{draft:{decision:"none",reason:"application_only",usedExplanationIds:[...new Set(g)]},visibleText:n};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(E=>{let D=v.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!u.has(E)});if(!M.length){if(g.every(D=>v.get(D)?.state==="grounded"||u.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let h=d.grounding,m=typeof h?.explanationId=="string"&&M.includes(h.explanationId)?h.explanationId:M[0];return{draft:{decision:"apply",summary:p,appliedExplanationIds:g,grounding:{explanationId:m,question:we(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(d.decision!==void 0&&d.decision!=="mutate")throw new Error("imprint decision is invalid");let c=d.summary,l=c?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let w={kind:l,title:we(c?.title,120),detail:we(c?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let R=Array.isArray(d.appliedExplanationIds)?d.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],b=[];for(let f of Array.isArray(d.mutations)?d.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let g=we(p.statement),v=we(p.rationale);if(!g||!v)continue;b.push({op:"add",clientId:we(p.clientId,100)||void 0,kind:p.kind,statement:g,rationale:v,scope:zo(p.scope),rootReason:we(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let g={op:"revise",explanationId:p.explanationId,statement:we(p.statement)||void 0,rationale:we(p.rationale)||void 0,scope:zo(p.scope),reopenGrounding:p.reopenGrounding===!0};(g.statement||g.rationale||g.scope||g.reopenGrounding)&&b.push(g)}else if(p.op==="evidence"&&typeof p.explanationId=="string"&&["supports","challenges","excepts"].includes(String(p.stance))){let g=we(p.summary);g&&b.push({op:"evidence",explanationId:p.explanationId,stance:p.stance,summary:g})}else if(p.op==="relation"&&typeof p.fromId=="string"&&typeof p.toId=="string"&&["expresses","excepts"].includes(String(p.type))){let g=we(p.rationale);if(!g)continue;b.push({op:"relation",type:p.type,fromId:p.fromId,toId:p.toId,rationale:g})}else if(p.op==="supersede"&&typeof p.explanationId=="string"&&typeof p.replacementId=="string"){let g=we(p.reason);g&&b.push({op:"supersede",explanationId:p.explanationId,replacementId:p.replacementId,reason:g})}else if(p.op==="bind_concrete"&&typeof p.explanationId=="string"){let g=we(p.modelPath,300);g&&b.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:g,rationale:we(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&b.push({op:"retire",explanationId:p.explanationId,reason:we(p.reason)})}let k=d.grounding,S=k&&typeof k.explanationId=="string"&&we(k.question)?{explanationId:k.explanationId,question:we(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:R,mutations:b,grounding:S},visibleText:n}}catch(d){return{visibleText:n,error:d instanceof Error?d.message:String(d)}}}function Jt(i,e={}){let t=i?.explanations??[],n=new Set(i?.pendingGroundingExplanationIds??[]),o=new Set(i?.correctionExplanationIds??[]),r=Ji(e.requestText),s=i?.retrievalIntent,d=i?.historicalCaveats??[];return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((c,l)=>[`${l+1}. [${c.state}; ${c.kind}] ${c.statement}`,` - Why: ${c.rationale}`,` - Scope: ${c.scope.kind} ${c.scope.values.join(", ")}`,` - Explanation: ${c.id}`,...n.has(c.id)?[" - Grounding: already pending; do not ask again"]:[],...o.has(c.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...c.concrete.map(w=>` - Concrete terminal: ${w.modelPath} = ${JSON.stringify(w.value)}`)].join(`
|
|
35
35
|
`)),...i?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...i?.relations?.length?["","Known explanation topology:",...i.relations.map(c=>`- ${c.fromId} --${c.type}--> ${c.toId}: ${c.rationale}`)]:[],...s?["","Explicit pattern transfer detected:",`- Target: ${s.target}`,`- Reference: ${s.reference}`,"Before editing, state which dimensions you intend to transfer from the reference and which target-specific behavior you will preserve. Compare the relevant surface, spacing, typography, radius, and interaction behavior; transfer only the dimensions supported by the request and evidence. If the intended transfer remains materially ambiguous after inspecting both anchors, ask one focused question."]:[],...d.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...d.map((c,l)=>[`${l+1}. [challenged; ${c.kind}] ${c.statement}`,` - Why it was previously proposed: ${c.rationale}`,` - Scope: ${c.scope.kind} ${c.scope.values.join(", ")}`,` - Historical explanation: ${c.id}`].join(`
|
|
36
36
|
`)),"Use these caveats only to avoid repeating a rejected or over-broad transfer. Do not cite them as usedExplanationIds or treat them as active guidance."]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...r?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.",'As soon as one or more surfaced explanations become actively useful during the work, emit `<imprint-use>{"explanationIds":["<every actively useful surfaced explanation id>"]}</imprint-use>` immediately. This live receipt is hidden from conversational prose. Emit it at the point of use rather than waiting for the final response. Emit a later marker only when additional explanations become actively useful. Never emit it for explanations that were merely retrieved, read, searched, or considered.',"Treat Imprint as actively useful when a surfaced explanation materially informs an answer, recommendation, implementation choice, or other decision. Whenever it is actively useful, always cite every materially used surfaced explanation in `usedExplanationIds`. This produces a usage receipt only; it does not strengthen or mutate shared understanding. Do not cite explanations that were merely retrieved, read, or considered but did not influence the result.","`appliedExplanationIds` is narrower: include an explanation there only when it governed a completed implementation or other observable action that genuinely tests the explanation. Never use `appliedExplanationIds` for an answer-only, informational, research, or read-only request. An explanation may be used without being applied; every applied explanation is also understood to be used.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change","usedExplanationIds":["<every surfaced explanation that was actively useful, or omit when none>"]}',"A no-op reason cannot suppress genuine application evidence. When a completed action was governed by an ungrounded explanation, report decision apply directly so the summary and grounding question are intentional. Answering a question with that explanation is usage, not application.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"imprint":{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"expresses|excepts","fromId":"<specific id or clientId>","toId":"<abstract rule id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}','The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only mutation objects actually needed. A new explanation established through completed implementation must include its clientId in appliedExplanationIds; the bridge also derives this application from a completed change as a safeguard. Applying a grounded explanation never requires a mutation, but actively using it still requires its id in appliedExplanationIds. Never claim that a new explanation is grounded."].join(`
|
|
37
|
-
`)}var Nt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Dt(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=ot(e.text??""),n=ot((e.subjectHints??[]).join(" ")),o=va(e.text),r=ot(o?.target??""),s=ot(o?.reference??""),d=new Set(e.pendingGroundingExplanationIds??[]),c=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!d.size&&!c.size)return;let{graph:l}=await this.store.load(),w=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||c.has(h.id))).map(h=>{let m=ot([h.statement,h.rationale].join(" ")),E=ot(h.scope.values.join(" ")),D=mt(m,t),S=mt(E,t),C=mt(E,n),z=mt(m,n),X=D+S*.2+C*.25+z*.75+(h.state==="grounded"?.08:0)+(d.has(h.id)?1:0)+(c.has(h.id)?1:0),G=d.has(h.id)||c.has(h.id)||D>=.12||S>=.5||C>=.2||z>=.2;return{item:h,score:X,relevant:G}}).filter(h=>h.relevant&&h.score>=.18).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)),k=Math.max(1,e.maxExplanations??6),T=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=mt(ot(`${m.statement} ${m.rationale}`),h),D=mt(ot(m.scope.values.join(" ")),h);return{item:m,score:E+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,E)=>E.score-m.score||E.item.updatedAt.localeCompare(m.item.updatedAt)),R=[],x=h=>{R.length<k&&!R.some(m=>m.id===h.id)&&R.push(h)};if(o&&(T(r).slice(0,2).forEach(({item:h})=>x(h)),T(s).slice(0,2).forEach(({item:h})=>x(h))),w.forEach(({item:h})=>x(h)),!R.length)return;let f=new Set(R.map(h=>h.id)),p=new Set(l.relations.flatMap(h=>f.has(h.fromId)?[h.toId]:f.has(h.toId)?[h.fromId]:[])),g=new Set(l.explanations.flatMap(h=>p.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),v=l.explanations.filter(h=>g.has(h.id)&&!f.has(h.id)).sort((h,m)=>m.updatedAt.localeCompare(h.updatedAt)).slice(0,4),u=[...R,...v];for(let h of v)f.add(h.id);let M=o?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=ot(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),E=mt(m,r),D=mt(m,s);return{item:h,score:E+D,targetScore:E,referenceScore:D}}).filter(h=>h.targetScore>=.12&&h.referenceScore>=.12).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)).slice(0,3).map(({item:h})=>({id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state})):[];return{explanations:u.map(h=>{let m=new Set(l.relations.filter(E=>E.toId===h.id&&E.type==="expresses").map(E=>E.fromId));return{id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state,concrete:l.concrete.filter(E=>m.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:w.length>R.length||v.length<g.size,...o?{retrievalIntent:o}:{},...M.length?{historicalCaveats:M}:{},...d.size?{pendingGroundingExplanationIds:[...d]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:l.relations.filter(h=>f.has(h.fromId)&&f.has(h.toId)).map(h=>({id:h.id,type:h.type,fromId:h.fromId,toId:h.toId,rationale:h.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],o=t.applicationOccurred?n.flatMap(b=>b.op==="add"&&b.clientId?[b.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...o])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),d=await this.store.load(),c=new Map(d.graph.explanations.map(b=>[b.id,b])),l=new Map,w=new Map,k=[],T=new Set,R=new Set(t.pendingGroundingExplanationIds??[]),x=new Set(n.flatMap(b=>b.op==="revise"&&n.some(Q=>Q.op==="evidence"&&Q.stance==="challenges"&&Q.explanationId===b.explanationId)?[b.explanationId]:[])),f=new Set(n.flatMap(b=>b.op==="add"&&b.clientId?[b.clientId]:[])),p=b=>c.has(b)||f.has(b),g=new Set;for(let b of n)b.op==="relation"&&b.fromId!==b.toId&&p(b.fromId)&&p(b.toId)?(g.add(b.fromId),g.add(b.toId)):b.op==="supersede"&&b.explanationId!==b.replacementId&&p(b.explanationId)&&p(b.replacementId)?(g.add(b.explanationId),g.add(b.replacementId)):b.op==="bind_concrete"&&p(b.explanationId)&&zo(t.concreteModel,b.modelPath).found&&g.add(b.explanationId);let v=d.graph.explanations.length===0;for(let b of n){if(b.op!=="add")continue;let Q=!!(b.clientId&&g.has(b.clientId)),L=!!b.rootReason?.trim()||v;if(!Q&&!L)continue;v&&(v=!1);let K=rt();b.clientId&&l.set(b.clientId,K);let H=b.clientId?r.includes(b.clientId):!1,J={id:K,kind:b.kind,statement:b.statement,rationale:b.rationale,scope:Ni(b.scope),state:H?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,J),T.add(K),k.push({op:"add_explanation",explanation:J})}let u=b=>l.get(b)??b;for(let b of n){if(b.op!=="revise")continue;let Q=u(b.explanationId),L=c.get(Q);if(L?.state!=="grounded")continue;let K=rt(),H={id:K,kind:L.kind,statement:b.statement??L.statement,rationale:b.rationale??L.rationale,scope:b.scope?Ni(b.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,H),w.set(Q,K),T.add(K),k.push({op:"add_explanation",explanation:H});let J=$t(L,H);J!==0&&k.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:J>0?Q:K,toId:J>0?K:Q,rationale:b.rationale??e.summary.detail,createdAt:s}})}let M=b=>{let Q=u(b);return w.get(Q)??Q};for(let b of n){if(b.op==="add")continue;if(b.op==="bind_concrete"){let L=M(b.explanationId);if(!c.has(L))continue;let K=zo(t.concreteModel,b.modelPath);if(!K.found)continue;let H=d.graph.concrete.find(J=>J.modelPath===b.modelPath&&JSON.stringify(J.value)===JSON.stringify(K.value));H||(H={id:rt(),modelPath:b.modelPath,value:structuredClone(K.value),createdAt:s,updatedAt:s},k.push({op:"add_concrete",concrete:H})),k.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:H.id,toId:L,rationale:b.rationale,createdAt:s}}),T.add(L);continue}if(b.op==="relation"){let L=M(b.fromId),K=M(b.toId);if(!c.has(L)||!c.has(K)||L===K)continue;b.type==="expresses"&&$t(c.get(L),c.get(K))<0&&([L,K]=[K,L]),k.push({op:"add_relation",relation:{id:rt(),type:b.type,fromId:L,toId:K,rationale:b.rationale,createdAt:s}}),T.add(L),T.add(K);continue}if(b.op==="supersede"){let L=M(b.explanationId),K=M(b.replacementId);if(!c.has(L)||!c.has(K)||L===K)continue;k.push({op:"add_evidence",explanationId:L,evidence:ft(t,"challenges",b.reason)}),k.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:K},updatedAt:s}),T.add(L),T.add(K);continue}let Q=M(b.explanationId);if(c.has(Q))if(T.add(Q),b.op==="revise"){if(w.has(u(b.explanationId)))continue;let L=c.get(Q);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let K={...b.statement?{statement:b.statement}:{},...b.rationale?{rationale:b.rationale}:{},...b.scope?{scope:Ni(b.scope)}:{},...b.reopenGrounding||x.has(b.explanationId)?{state:"testing"}:{}};k.push({op:"revise_explanation",explanationId:Q,patch:K,updatedAt:s})}else if(b.op==="evidence"){if(b.stance==="challenges"&&x.has(b.explanationId))continue;k.push({op:"add_evidence",explanationId:Q,evidence:ft(t,b.stance,b.summary)}),b.stance==="challenges"&&k.push({op:"revise_explanation",explanationId:Q,patch:{state:"challenged"},updatedAt:s})}else b.op==="retire"&&(k.push({op:"add_evidence",explanationId:Q,evidence:ft(t,"challenges",b.reason||"Retired after contradictory collaboration evidence.")}),k.push({op:"revise_explanation",explanationId:Q,patch:{state:"retired"},updatedAt:s}))}for(let b of r){let Q=M(b),L=c.get(Q);!L||L.state==="grounded"||L.state==="retired"||R.has(Q)&&!T.has(Q)||(T.has(Q)||(T.add(Q),k.push({op:"add_evidence",explanationId:Q,evidence:{...ft(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&k.push({op:"revise_explanation",explanationId:Q,patch:{state:"testing"},updatedAt:s}))}let h=new Set(d.graph.relations.map(b=>`${b.type}:${b.fromId}:${b.toId}`)),m=k.filter(b=>{if(b.op!=="add_relation")return!0;let Q=`${b.relation.type}:${b.relation.fromId}:${b.relation.toId}`;return h.has(Q)?!1:(h.add(Q),!0)});if(!m.length)return;let E=rt(),D=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:m}),S=new Map(D.graph.explanations.map(b=>[b.id,b])),C=[...T].flatMap(b=>{let Q=S.get(b);if(!Q)return[];let L=!d.graph.explanations.some(H=>H.id===b),K=Q.state==="challenged"||Q.state==="retired";return[{explanationId:b,action:L?"added":K?"challenged":"revised",statement:Q.statement,state:Q.state}]}),z=r.map(M).find(b=>S.get(b)?.state==="testing"&&!R.has(b)),X=e.grounding?M(e.grounding.explanationId):z,G=X?S.get(X):void 0,Y=G?.state==="testing"&&!R.has(G.id)?{explanationId:G.id,question:e.grounding?.question||ga(G),state:"testing"}:void 0;return{transactionId:E,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:C,...Y?{grounding:Y}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(l=>l.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},d=[],c="";if(e.action==="yes"?(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),c=`Grounded: ${r.statement}`):e.action==="this_time"&&(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),c=`Observed this time: ${r.statement}`),!d.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:rt(),committedAt:t,source:s,summary:c,mutations:d}),"applied"}};var Tt=1,Bi="bridge";function Wo(i){return`codex-session:${i}`}function Ta(i,e){return`codex-${wa("sha256").update(`${i}:${e}`).digest("hex").slice(0,16)}`}function Ho(i){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:i,elements:[]}],styleModifications:[]}}function Pa(i,e){let t=new Set,n=r=>{if(typeof r!="string"||!r.trim())return;let s=r.trim();t.add(xa(s)?Sa(e,s):s)},o=(r,s="",d=0)=>{if(!(d>5||r===null||r===void 0)){if(typeof r=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&n(r),s==="command")for(let c of r.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(c[1]);return}if(Array.isArray(r)){r.forEach(c=>o(c,s,d+1));return}if(typeof r=="object")for(let[c,l]of Object.entries(r))o(l,c,d+1)}};for(let r of i)o(r.toolInput);return[...t]}function Go(i,e,t,n,o,r){let s=Vo(o,r);return["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${t}; the tool session is ${i}.`,"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.",cn(n),s].filter(Boolean).join(`
|
|
38
|
-
`)
|
|
37
|
+
`)}var Nt=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Dt(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=ot(e.text??""),n=ot((e.subjectHints??[]).join(" ")),o=wa(e.text),r=ot(o?.target??""),s=ot(o?.reference??""),d=new Set(e.pendingGroundingExplanationIds??[]),c=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!d.size&&!c.size)return;let{graph:l}=await this.store.load(),w=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||c.has(h.id))).map(h=>{let m=ot([h.statement,h.rationale].join(" ")),E=ot(h.scope.values.join(" ")),D=mt(m,t),T=mt(E,t),C=mt(E,n),z=mt(m,n),X=D+T*.2+C*.25+z*.75+(h.state==="grounded"?.08:0)+(d.has(h.id)?1:0)+(c.has(h.id)?1:0),G=d.has(h.id)||c.has(h.id)||D>=.12||T>=.5||C>=.2||z>=.2;return{item:h,score:X,relevant:G}}).filter(h=>h.relevant&&h.score>=.18).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)),R=Math.max(1,e.maxExplanations??6),b=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=mt(ot(`${m.statement} ${m.rationale}`),h),D=mt(ot(m.scope.values.join(" ")),h);return{item:m,score:E+D*.35+(m.state==="grounded"?.08:0)}}).filter(m=>m.score>=.18).sort((m,E)=>E.score-m.score||E.item.updatedAt.localeCompare(m.item.updatedAt)),k=[],S=h=>{k.length<R&&!k.some(m=>m.id===h.id)&&k.push(h)};if(o&&(b(r).slice(0,2).forEach(({item:h})=>S(h)),b(s).slice(0,2).forEach(({item:h})=>S(h))),w.forEach(({item:h})=>S(h)),!k.length)return;let f=new Set(k.map(h=>h.id)),p=new Set(l.relations.flatMap(h=>f.has(h.fromId)?[h.toId]:f.has(h.toId)?[h.fromId]:[])),g=new Set(l.explanations.flatMap(h=>p.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),v=l.explanations.filter(h=>g.has(h.id)&&!f.has(h.id)).sort((h,m)=>m.updatedAt.localeCompare(h.updatedAt)).slice(0,4),u=[...k,...v];for(let h of v)f.add(h.id);let M=o?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=ot(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),E=mt(m,r),D=mt(m,s);return{item:h,score:E+D,targetScore:E,referenceScore:D}}).filter(h=>h.targetScore>=.12&&h.referenceScore>=.12).sort((h,m)=>m.score-h.score||m.item.updatedAt.localeCompare(h.item.updatedAt)).slice(0,3).map(({item:h})=>({id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state})):[];return{explanations:u.map(h=>{let m=new Set(l.relations.filter(E=>E.toId===h.id&&E.type==="expresses").map(E=>E.fromId));return{id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state,concrete:l.concrete.filter(E=>m.has(E.id)).map(E=>({id:E.id,modelPath:E.modelPath,value:E.value}))}}),truncated:w.length>k.length||v.length<g.size,...o?{retrievalIntent:o}:{},...M.length?{historicalCaveats:M}:{},...d.size?{pendingGroundingExplanationIds:[...d]}:{},...c.size?{correctionExplanationIds:[...c]}:{},relations:l.relations.filter(h=>f.has(h.fromId)&&f.has(h.toId)).map(h=>({id:h.id,type:h.type,fromId:h.fromId,toId:h.toId,rationale:h.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],o=t.applicationOccurred?n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...o])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),d=await this.store.load(),c=new Map(d.graph.explanations.map(x=>[x.id,x])),l=new Map,w=new Map,R=[],b=new Set,k=new Set(t.pendingGroundingExplanationIds??[]),S=new Set(n.flatMap(x=>x.op==="revise"&&n.some(Q=>Q.op==="evidence"&&Q.stance==="challenges"&&Q.explanationId===x.explanationId)?[x.explanationId]:[])),f=new Set(n.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),p=x=>c.has(x)||f.has(x),g=new Set;for(let x of n)x.op==="relation"&&x.fromId!==x.toId&&p(x.fromId)&&p(x.toId)?(g.add(x.fromId),g.add(x.toId)):x.op==="supersede"&&x.explanationId!==x.replacementId&&p(x.explanationId)&&p(x.replacementId)?(g.add(x.explanationId),g.add(x.replacementId)):x.op==="bind_concrete"&&p(x.explanationId)&&Wo(t.concreteModel,x.modelPath).found&&g.add(x.explanationId);let v=d.graph.explanations.length===0;for(let x of n){if(x.op!=="add")continue;let Q=!!(x.clientId&&g.has(x.clientId)),L=!!x.rootReason?.trim()||v;if(!Q&&!L)continue;v&&(v=!1);let K=rt();x.clientId&&l.set(x.clientId,K);let H=x.clientId?r.includes(x.clientId):!1,B={id:K,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:Bi(x.scope),state:H?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,B),b.add(K),R.push({op:"add_explanation",explanation:B})}let u=x=>l.get(x)??x;for(let x of n){if(x.op!=="revise")continue;let Q=u(x.explanationId),L=c.get(Q);if(L?.state!=="grounded")continue;let K=rt(),H={id:K,kind:L.kind,statement:x.statement??L.statement,rationale:x.rationale??L.rationale,scope:x.scope?Bi(x.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ft(t,"supports",e.summary.detail)]};c.set(K,H),w.set(Q,K),b.add(K),R.push({op:"add_explanation",explanation:H});let B=$t(L,H);B!==0&&R.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:B>0?Q:K,toId:B>0?K:Q,rationale:x.rationale??e.summary.detail,createdAt:s}})}let M=x=>{let Q=u(x);return w.get(Q)??Q};for(let x of n){if(x.op==="add")continue;if(x.op==="bind_concrete"){let L=M(x.explanationId);if(!c.has(L))continue;let K=Wo(t.concreteModel,x.modelPath);if(!K.found)continue;let H=d.graph.concrete.find(B=>B.modelPath===x.modelPath&&JSON.stringify(B.value)===JSON.stringify(K.value));H||(H={id:rt(),modelPath:x.modelPath,value:structuredClone(K.value),createdAt:s,updatedAt:s},R.push({op:"add_concrete",concrete:H})),R.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:H.id,toId:L,rationale:x.rationale,createdAt:s}}),b.add(L);continue}if(x.op==="relation"){let L=M(x.fromId),K=M(x.toId);if(!c.has(L)||!c.has(K)||L===K)continue;x.type==="expresses"&&$t(c.get(L),c.get(K))<0&&([L,K]=[K,L]),R.push({op:"add_relation",relation:{id:rt(),type:x.type,fromId:L,toId:K,rationale:x.rationale,createdAt:s}}),b.add(L),b.add(K);continue}if(x.op==="supersede"){let L=M(x.explanationId),K=M(x.replacementId);if(!c.has(L)||!c.has(K)||L===K)continue;R.push({op:"add_evidence",explanationId:L,evidence:ft(t,"challenges",x.reason)}),R.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:K},updatedAt:s}),b.add(L),b.add(K);continue}let Q=M(x.explanationId);if(c.has(Q))if(b.add(Q),x.op==="revise"){if(w.has(u(x.explanationId)))continue;let L=c.get(Q);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let K={...x.statement?{statement:x.statement}:{},...x.rationale?{rationale:x.rationale}:{},...x.scope?{scope:Bi(x.scope)}:{},...x.reopenGrounding||S.has(x.explanationId)?{state:"testing"}:{}};R.push({op:"revise_explanation",explanationId:Q,patch:K,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&S.has(x.explanationId))continue;R.push({op:"add_evidence",explanationId:Q,evidence:ft(t,x.stance,x.summary)}),x.stance==="challenges"&&R.push({op:"revise_explanation",explanationId:Q,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(R.push({op:"add_evidence",explanationId:Q,evidence:ft(t,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),R.push({op:"revise_explanation",explanationId:Q,patch:{state:"retired"},updatedAt:s}))}for(let x of r){let Q=M(x),L=c.get(Q);!L||L.state==="grounded"||L.state==="retired"||k.has(Q)&&!b.has(Q)||(b.has(Q)||(b.add(Q),R.push({op:"add_evidence",explanationId:Q,evidence:{...ft(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&R.push({op:"revise_explanation",explanationId:Q,patch:{state:"testing"},updatedAt:s}))}let h=new Set(d.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toId}`)),m=R.filter(x=>{if(x.op!=="add_relation")return!0;let Q=`${x.relation.type}:${x.relation.fromId}:${x.relation.toId}`;return h.has(Q)?!1:(h.add(Q),!0)});if(!m.length)return;let E=rt(),D=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:m}),T=new Map(D.graph.explanations.map(x=>[x.id,x])),C=[...b].flatMap(x=>{let Q=T.get(x);if(!Q)return[];let L=!d.graph.explanations.some(H=>H.id===x),K=Q.state==="challenged"||Q.state==="retired";return[{explanationId:x,action:L?"added":K?"challenged":"revised",statement:Q.statement,state:Q.state}]}),z=r.map(M).find(x=>T.get(x)?.state==="testing"&&!k.has(x)),X=e.grounding?M(e.grounding.explanationId):z,G=X?T.get(X):void 0,Y=G?.state==="testing"&&!k.has(G.id)?{explanationId:G.id,question:e.grounding?.question||ya(G),state:"testing"}:void 0;return{transactionId:E,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:C,...Y?{grounding:Y}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(l=>l.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},d=[],c="";if(e.action==="yes"?(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),c=`Grounded: ${r.statement}`):e.action==="this_time"&&(d.push({op:"add_evidence",explanationId:n,evidence:{...ft(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),d.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),c=`Observed this time: ${r.statement}`),!d.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:rt(),committedAt:t,source:s,summary:c,mutations:d}),"applied"}};var Tt=1,Li="bridge";function Ho(i){return`codex-session:${i}`}function Pa(i,e){return`codex-${ba("sha256").update(`${i}:${e}`).digest("hex").slice(0,16)}`}function Go(i){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:i,elements:[]}],styleModifications:[]}}function ka(i,e){let t=new Set,n=r=>{if(typeof r!="string"||!r.trim())return;let s=r.trim();t.add(Sa(s)?Ta(e,s):s)},o=(r,s="",d=0)=>{if(!(d>5||r===null||r===void 0)){if(typeof r=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&n(r),s==="command")for(let c of r.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))n(c[1]);return}if(Array.isArray(r)){r.forEach(c=>o(c,s,d+1));return}if(typeof r=="object")for(let[c,l]of Object.entries(r))o(l,c,d+1)}};for(let r of i)o(r.toolInput);return[...t]}function On(i){return i?Math.ceil(i.length/4):0}function Vo(i,e,t,n,o,r){let s=["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${t}; the tool session is ${i}.`,"The human remains the authority for accepted product decisions and Imprint grounding. Never infer acceptance from implementation, praise, silence, or ambiguity.","Popmelt records the turn automatically. Use Popmelt Core tools only for intentional context expansion, explicit decision review, Imprint grounding, or a structured learning assessment."].join(`
|
|
38
|
+
`),d=cn(n),c=Ko(o,r),l=[s,d,c].filter(Boolean).join(`
|
|
39
|
+
`);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:On(s),memoryEstimatedTokens:On(d),imprintEstimatedTokens:On(c),totalEstimatedTokens:On(l)}}}function Ko(i,e){return i?Jt(i,{requestText:e}).split(`
|
|
39
40
|
`).map(t=>t.startsWith("At the end, emit exactly one machine-readable <resolution> envelope")?"Do not print a machine-readable resolution envelope in the visible Codex response. When this collaboration changes reusable shared understanding, call `popmelt_assess_turn` before the final response.":t.startsWith("The final shape is `<resolution>")?'Pass the complete `<resolution>{"annotations":[...],"imprint":{...}}</resolution>` shape as `assessmentText` to `popmelt_assess_turn`; do not include it in conversational prose.':t).join(`
|
|
40
|
-
`)
|
|
41
|
-
`)}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
`)
|
|
48
|
-
`)}
|
|
49
|
-
`)[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&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let r=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function pd(i){if(typeof i.error=="string")return i.error;if(i.error&&typeof i.error=="object"){let e=i.error;if(typeof e.message=="string")return e.message}if(typeof i.message=="string"&&mn(i).toLowerCase().includes("error"))return i.message}function un(i,e,t=[]){for(let n of e){let o=i[n];if(typeof o=="string")return o}for(let[n,o]of Object.entries(i)){if(!o||typeof o!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=un(o,e);if(r)return r}}function Wi(i){let e=mn(i).toLowerCase();return(typeof i.role=="string"?i.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as ud,readFile as md}from"fs/promises";import{join as Hi}from"path";var zn=class{constructor(e){let t=Hi(e,".popmelt");this.decisionsDir=Hi(t,"decisions")}async listDecisionIds(){try{return(await ud(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 md(Hi(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 fd,randomUUID as hd}from"crypto";import{mkdir as Gi,readFile as pr,readdir as ur,rename as Wn,stat as mr,unlink as Hn,writeFile as Gn}from"fs/promises";import{extname as gd,join as Ve}from"path";var yd=10080*60*1e3,Id=600*1e3,vd=3600*1e3;function wd(i){return i==="image/svg+xml"?".svg":i==="text/plain"?".txt":".bin"}function bd(i,e){return[...i.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var Vn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let t=hd(),n=wd(e.mimeType),o=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:bd(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:o};await Gi(this.draftsDir,{recursive:!0});let d=Ve(this.draftsDir,o),c=Ve(this.draftsDir,`${t}.json`),l=`${d}.part`,w=`${c}.part`;return await Gn(l,e.data),await Wn(l,d),await Gn(w,JSON.stringify(s,null,2)),await Wn(w,c),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let o=await this.readManifest(n.id);if(!o)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(o.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ve(this.draftsDir,o.contentFile),s=await pr(r),d=fd("sha256").update(s).digest("hex"),c=Ve(this.mediaDir,`${d}${gd(o.contentFile)||".bin"}`);await Gi(this.mediaDir,{recursive:!0});try{await mr(c)}catch{let l=`${c}.part`;await Gn(l,s),await Wn(l,c)}(t[n.annotationId]??=[]).push({id:o.id,name:o.name,mimeType:o.mimeType,size:o.size,kind:o.kind,path:c}),o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o)}return t}async sweep(e=Date.now()){let t;try{t=await ur(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let o=Ve(this.draftsDir,n);if(n.endsWith(".part")){let d=await mr(o).catch(()=>null);d&&e-d.mtimeMs>vd&&await Hn(o).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Id:e-r.lastSeenAt>yd)||await Promise.all([Hn(o).catch(()=>{}),Hn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await ur(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Hn(Ve(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await pr(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Gi(this.draftsDir,{recursive:!0});let t=Ve(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Gn(n,JSON.stringify(e,null,2)),await Wn(n,t)}};import{randomUUID as fr}from"crypto";import{mkdir as Vi,readFile as Ki,writeFile as Kn}from"fs/promises";import{dirname as Qi,join as Ft}from"path";var Ke="[ProjectionWorker]",xd={version:1,runs:[]},Sd={version:1,updatedAt:0,proposals:[]},Td=12;function Pd(i){return Array.isArray(i)?i.map((e,t)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function hr(i){let e=[];for(let t of i){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Ke} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function kd(i,e,t){return{decisionCount:i.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Rd(i,e,t){let n=new Set(e),o=new Set,r=Array.isArray(i.rules)?i.rules:[];for(let x of r){if(!x||typeof x!="object")continue;let f=x.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&n.has(p)&&o.add(p)}let s=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?i.tokens:{},d=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?i.components:{},c=Array.isArray(t?.rules)?t.rules:[],l=r.filter(x=>{if(!x||typeof x!="object")return!1;let f=x.id,p=typeof f=="string"?c.find(g=>g&&typeof g=="object"&&g.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(x)}).length,w=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},k=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},T=Object.keys(s).filter(x=>JSON.stringify(s[x])!==JSON.stringify(w[x])).length,R=Object.keys(d).filter(x=>JSON.stringify(d[x])!==JSON.stringify(k[x])).length;return{ruleCount:l,tokenSectionCount:T,componentCount:R,coveredDecisionIds:[...o],uncoveredDecisionIds:e.filter(x=>!o.has(x))}}function jd(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function Ad(i,e,t){let n=i[e];if(n&&typeof n=="object")return n;let o=typeof t=="number"?[]:{};return i[String(e)]=o,o}function Qn(i,e,t){let n=i;for(let r=0;r<e.length-1;r++)n=Ad(n,e[r],e[r+1]);let o=e[e.length-1];n[String(o)]=jd(t)}function gr(i,e){let t=i;for(let o=0;o<e.length-1;o++){let r=t[String(e[o])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function Md(i,e){if(!i)return{exists:!1};let t=i;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 Ed(i,e){return Array.isArray(e)?i===void 0?e.length>0:!Array.isArray(i)||e.length<=i.length?!1:i.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function yr(i,e){if(i.authorityStatus!=="accepted"||!i.changes?.length)return null;for(let t of i.changes){let n=Md(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?Ed(n.exists?n.value:void 0,t.value):!n.exists))return null}return i.changes}var Xn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Ft(e,".popmelt");this.runsPath=Ft(n,"projection-runs.json"),this.legacyRunsPath=Ft(n,"materialization-runs.json"),this.proposalsPath=Ft(n,"projection-queue.json"),this.legacyProposalsPath=Ft(n,"model-proposals.json"),this.modelPath=Ft(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Ki(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=Pd(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let o=n.key.split(".");n.value===null?gr(t,o):Qn(t,o,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(Td),t=new Set((await this.loadModelProposals()).proposals.flatMap(o=>o.status==="pending"&&o.authorityStatus==="accepted"?o.decisionIds:[]));return{decisions:e.filter(o=>!t.has(o.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(),o=n.decisions;if(o.length===0)return{processedIds:[],success:!0};let r=o.map(x=>x.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),d=Od(o,s),c=kd(o,n.totalCandidateDecisionCount,d);t=fr().slice(0,8);let l={id:t,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let w=!0,k,T,R;try{let x=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(x,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:f},await this.persistRun(l);let g=await p;if(!g.success)w=!1,k=g.error,console.error(`${Ke} ${f} spawn error:`,k);else{let v=$d(g.text,r);if(v){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of v)Qn(u,m.path,m.value);Array.isArray(u.rules)&&(u.rules=hr(u.rules));let M=Rd(u,r,s);if(v){let m=[...new Set(v.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=r.filter(E=>!m.includes(E))}T=M;let h=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:T,changes:v});R=h.id,console.log(`${Ke} Created model proposal ${h.id} for ${r.length} decision(s)`)}else w=!1,k="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${k}`)}}catch(x){w=!1,k=x instanceof Error?x.message:String(x),console.error(`${Ke} Error:`,k)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:k,outputStats:T,proposalId:R}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:w,error:k}),{processedIds:r,success:w,error:k,runId:t,proposalId:R}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=hr(e.rules)),await Kn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await Vi(Qi(this.runsPath),{recursive:!0}),await Kn(this.runsPath,JSON.stringify(t,null,2)),t):{...xd,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let o=await this.readProposalStore(this.legacyProposalsPath);o&&(e={version:1,updatedAt:Date.now(),proposals:o.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Sd,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(o=>{if(o.proposedModel)return o;let r=structuredClone(n);for(let s of o.changes??[])Qn(r,s.path,s.value);return{...o,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>o.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>n.createdAt-o.createdAt||n.updatedAt-o.updatedAt)}async applySelectedModelProposal(e,t,n,o="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let c of t)!Array.isArray(c.path)||c.path.length===0||(c.remove?gr(s,c.path):Qn(s,c.path,c.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:o,error:void 0,selectedChanges:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:fr().slice(0,8),status:"pending",title:_d(e.proposedModel),summary:e.outputStats?`Proposes ${e.outputStats.ruleCount} rule, ${e.outputStats.componentCount} component, and ${e.outputStats.tokenSectionCount} token change${e.outputStats.ruleCount+e.outputStats.componentCount+e.outputStats.tokenSectionCount===1?"":"s"} from ${e.decisionIds.length} accepted decision${e.decisionIds.length===1?"":"s"}.`:Cd(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(o=>o.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),o=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(o={...r,...t,updatedAt:Date.now()},o)),o?(n.updatedAt=Date.now(),await this.persistModelProposals(n),o):null}async persistModelProposals(e){try{await Vi(Qi(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...o})=>o)};await Kn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(o=>o.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await Vi(Qi(this.runsPath),{recursive:!0}),await Kn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Ki(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Ki(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,o){let r=n.provider??this.options.provider??"codex",s=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return r==="codex"?{provider:"codex",...Un(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Jn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...Bn(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function _d(i){let t=(Array.isArray(i.rules)?i.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function Cd(i,e){let t=Array.isArray(i.rules)?i.rules.length:0,n=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?Object.keys(i.tokens).length:0,o=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function $d(i,e){let t=i.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 o=new Set(e),r=n.flatMap((s,d)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let c=s;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(k=>typeof k=="string"||typeof k=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let w=Array.isArray(c.decisionIds)?c.decisionIds.filter(k=>typeof k=="string"&&o.has(k)):[];return w.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:w,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function Od(i,e){let t=i.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
41
|
+
`):["","## Continuous imprinting","","An imprint is provisional, advisory shared understanding; accepted product decisions always win. Ordinary completion, implementation, praise, silence, and ambiguity are not learning.","Before finishing, ask one level above the exact task whether human-supplied evidence established a reusable intention, rationale, relationship, or applicability boundary that would change a future decision. The default is no Imprint action.","Call `popmelt_assess_turn` only when reusable understanding changed. Before mutating, require all six: reusable, novel, durable, atomic, scoped, and supported by the human anywhere in the thread. If overlap with project knowledge is plausible, expand context before adding so the result can be consolidated or related instead of duplicated.",'For a genuinely new root, pass `assessmentText` as `<resolution>{"annotations":[],"imprint":{"decision":"mutate","summary":{"kind":"added","title":"<short title>","detail":"<what changed>"},"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one atomic claim>","rationale":"<human-supported reason>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<why no existing explanation is related>"}]}}</resolution>`.','Include `appliedExplanationIds:["new-1"]` and a `grounding` question only when completed implementation or another observable action genuinely tested the new explanation; otherwise omit them.',"When context expansion surfaces related explanations, follow its complete relationship, application, correction, and topology contract. Do not print a machine-readable resolution envelope in the visible response."].join(`
|
|
42
|
+
`)}function Ra(i){if(!i)return;if(i.decision==="recognize")return[i.explanationId];let e=[...new Set([...i.usedExplanationIds??[],...i.appliedExplanationIds??[]])];return e.length?e:void 0}function Aa(i,e){let t=e.flatMap((n,o)=>{let r=i[o];return r?[{packetId:`ambient:${n}`,proposalId:n,claim:r.claim.trim(),proposedKind:r.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:n}]}]:[]});return t.length>0?{source:"journal",packets:t,truncated:!1,estimatedTokens:0}:void 0}var Dn=class{constructor(e){this.options=e;this.turns=new Map}key(e,t){return`${e}:${t}`}async findThread(e){return this.options.threadStore.findContinuationThread([Ho(e)])}async prepare(e){if(e.executionOwner===Li)return{status:"managed_by_bridge",protocolVersion:Tt};let t=this.key(e.sessionId,e.turnId),n=this.turns.get(t);if(n){let b=Vo(n.sessionId,n.threadId,n.jobId,n.memoryContext,n.imprintContext,n.prompt);return{status:"already_prepared",protocolVersion:Tt,threadId:n.threadId,jobId:n.jobId,...b}}let o=await this.findThread(e.sessionId);o||(o=await this.options.threadStore.createThread(`thread-${xa()}`,[Ho(e.sessionId)]));let r=Pa(e.sessionId,e.turnId),s=o.messages.find(b=>b.jobId===r&&b.role==="human"),d=Go(e.prompt),c=s?.memoryReview??await dn(this.options.memoryService,d,[]),l=s?.imprintContext??await this.options.imprintService.contextualize({text:e.prompt,pendingGroundingExplanationIds:o.messages.flatMap(b=>b.role==="assistant"&&b.imprintSummary?.grounding&&!b.imprintSummary.resolvedAction?[b.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(o.id,{role:"human",timestamp:Date.now(),jobId:r,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...c?{memoryReview:c}:{},...l?{imprintContext:l}:{}});let w={sessionId:e.sessionId,turnId:e.turnId,threadId:o.id,jobId:r,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:c,imprintContext:l,events:[]};this.turns.set(t,w);let R=Vo(e.sessionId,o.id,r,c,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Tt,threadId:o.id,jobId:r,...R}}async recordEvent(e){if(e.executionOwner===Li)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===Li)return{status:"managed_by_bridge",protocolVersion:Tt};let t=this.turns.get(this.key(e.sessionId,e.turnId));if(!t)return{status:"turn_not_prepared",protocolVersion:Tt};let o=(await this.options.threadStore.getThread(t.threadId))?.messages.find(p=>p.role==="assistant"&&p.jobId===t.jobId);if(o)return e.lastAssistantMessage&&e.lastAssistantMessage!==o.responseText&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Tt,threadId:t.threadId,jobId:t.jobId};let r=ka(t.events,this.options.projectRoot),s=r.length>0,d,c={state:"not_applicable"},l,w;if(t.assessment?.assessmentText){let p=Bt(t.assessment.assessmentText,{context:t.imprintContext,requestText:t.prompt,applicationOccurred:s});p.error?c={state:p.error.includes("missing")?"missing":"invalid",reason:p.error}:p.draft?.decision==="none"?(this.options.imprintService.recordNoop(p.draft.reason),c={state:"none",reason:p.draft.reason}):p.draft?.decision==="recognize"?c={state:"none",reason:"recognized existing grounded understanding"}:(p.draft?.decision==="mutate"||p.draft?.decision==="apply")&&(d=await this.options.imprintService.capture(p.draft,{threadId:t.threadId,jobId:t.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:t.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:s}),c=d?{state:"mutated"}:{state:"invalid",reason:"imprint mutation failed admission or produced no durable change"},d&&await this.options.memoryService.recordImprintEvidence({summary:d,threadId:t.threadId,jobId:t.jobId}).catch(()=>{})),l=Ra(p.draft),w=p.draft&&p.draft.decision!=="recognize"?p.draft.appliedExplanationIds:void 0}let R=s?"completed":"no_change",b=an({changedFiles:r}),k={role:"assistant",timestamp:Date.now(),jobId:t.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:t.events.map(p=>p.toolName),turn:{phase:"complete",orientation:[],result:b},result:b,provider:"codex",model:e.model,imprintSummary:d,imprintUsedExplanationIds:l,imprintAppliedExplanationIds:w};await this.options.threadStore.appendMessage(t.threadId,k);let S=await this.options.memoryService.captureCompletedJob({jobId:t.jobId,threadId:t.threadId,createdAt:t.createdAt,completedAt:Date.now(),requestSummary:t.prompt,responseSummary:e.lastAssistantMessage,outcome:R,execution:{provider:"codex",model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:r,resolutions:s?[{status:"resolved",summary:`Changed ${r.join(", ")}`}]:[],semanticCandidates:t.assessment?.semanticCandidates,governingDecisionIds:t.memoryContext?.acceptedTruth?.decisions.map(p=>p.id),imprintAssessment:c}),f=Aa(t.assessment?.semanticCandidates??[],S.proposalIds);return f&&await this.options.threadStore.updateAssistantMessage(t.threadId,t.jobId,{memoryReview:f}),{status:"completed",protocolVersion:Tt,threadId:t.threadId,jobId:t.jobId}}async expandContext(e){let t=Go(e.query),n=await dn(this.options.memoryService,t,e.subjectHints??[]),o=await this.options.imprintService.contextualize({text:e.query,subjectHints:e.subjectHints});return{memoryContext:n,imprintContext:o,formattedContext:[cn(n),Ko(o,e.query)].filter(Boolean).join(`
|
|
43
|
+
`)}}};import{mkdir as _a,readFile as Qo,realpath as Ca,writeFile as $a}from"fs/promises";import{join as Nn}from"path";function Lt(i){return Ma(i).slice(0,12)}var ja=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Ma(i){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(i)):Ea(i),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(t/Math.pow(2,b*8)&255);let n=1779033703,o=3144134277,r=1013904242,s=2773480762,d=1359893119,c=2600822924,l=528734635,w=1541459225,R=new Array(64);for(let b=0;b<e.length;b+=64){for(let h=0;h<16;h++){let m=b+h*4;R[h]=(e[m]<<24|e[m+1]<<16|e[m+2]<<8|e[m+3])>>>0}for(let h=16;h<64;h++){let m=Ze(R[h-15],7)^Ze(R[h-15],18)^R[h-15]>>>3,E=Ze(R[h-2],17)^Ze(R[h-2],19)^R[h-2]>>>10;R[h]=R[h-16]+m+R[h-7]+E>>>0}let k=n,S=o,f=r,p=s,g=d,v=c,u=l,M=w;for(let h=0;h<64;h++){let m=Ze(g,6)^Ze(g,11)^Ze(g,25),E=g&v^~g&u,D=M+m+E+ja[h]+R[h]>>>0,T=Ze(k,2)^Ze(k,13)^Ze(k,22),C=k&S^k&f^S&f,z=T+C>>>0;M=u,u=v,v=g,g=p+D>>>0,p=f,f=S,S=k,k=D+z>>>0}n=n+k>>>0,o=o+S>>>0,r=r+f>>>0,s=s+p>>>0,d=d+g>>>0,c=c+v>>>0,l=l+u>>>0,w=w+M>>>0}return[n,o,r,s,d,c,l,w].map(b=>b.toString(16).padStart(8,"0")).join("")}function Ze(i,e){return i>>>e|i<<32-e}function Ea(i){let e=[];for(let t=0;t<i.length;t++){let n=i.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 Fi(i){return Ca(i).catch(()=>i)}function Xo(i){return Nn(i,".popmelt","store.json")}function Oa(i){if(!i||typeof i!="object"||Array.isArray(i))return!1;let e=i;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function qi(i){let e=await Fi(i);try{let t=JSON.parse(await Qo(Xo(e),"utf8"));return Oa(t)?t:null}catch{return null}}async function Da(i){let e=await Fi(i),t=await qi(e);if(t)return t;let n;for(let o of[Nn(e,".popmelt","memory","manifest.json"),Nn(e,".popmelt","imprint","manifest.json")])try{let r=JSON.parse(await Qo(o,"utf8"));if(typeof r.projectId=="string"&&r.projectId.trim()){n=r.projectId.trim();break}}catch{}return{version:1,storeId:`store-${n??Lt(e)}`,createdAt:new Date().toISOString()}}async function Bn(i){let e=await Fi(i),t=await qi(e);if(t)return t;let n=await Da(e),o=Nn(e,".popmelt");await _a(o,{recursive:!0});try{return await $a(Xo(e),`${JSON.stringify(n,null,2)}
|
|
44
|
+
`,{encoding:"utf8",flag:"wx"}),n}catch(r){let s=await qi(e);if(s)return s;throw r}}var Na=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ba=new Set(["default","flex","fast","priority"]);function qt(i){let e=typeof i.reasoningEffort=="string"&&Na.has(i.reasoningEffort)?i.reasoningEffort:void 0,t=typeof i.serviceTier=="string"&&Ba.has(i.serviceTier)?i.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function Jn(i){let e=[];return i?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(i.reasoningEffort)}`),i?.serviceTier&&e.push(`service_tier=${JSON.stringify(i.serviceTier)}`),e}import{spawn as Ja}from"child_process";import{createInterface as La}from"readline";function ln(i,e){let t=e.trim();if(!t)return"";let n=i.length>0?`
|
|
45
|
+
|
|
46
|
+
${t}`:t;return i.push(n),n}var qa=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"]),Yo=1e5;function Fa(i){let e=i.input?.file_path||i.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!qa.has(t))return;let n;if(i.name==="Write"&&typeof i.input?.content=="string"?n=i.input.content:i.name==="Edit"&&typeof i.input?.new_string=="string"&&(n=i.input.new_string),!!n)return n.length>Yo?n.slice(0,Yo)+`
|
|
47
|
+
\u2026[truncated]`:n}function Ln(i,e){let{prompt:t,projectRoot:n,maxTurns:o=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:d="claude",resumeSessionId:c,model:l,reasoningEffort:w,timeoutMs:R=3e5,onEvent:b}=e,k=[];c?k.push("--resume",c,"-p",t):k.push("-p",t),k.push("--output-format","stream-json","--verbose","--max-turns",String(o),"--max-budget-usd",String(r)),l&&k.push("--model",l),w&&k.push("--effort",w);for(let p of s)k.push("--allowedTools",p);let S=Ja(d,k,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),f=new Promise(p=>{let g,v=[],u=[],M=[],h=!1,m="",E,D,T=!1,C=setTimeout(()=>{T=!0,S.kill("SIGTERM"),setTimeout(()=>{try{S.kill("SIGKILL")}catch{}},5e3)},R),z=La({input:S.stdout}),X=new Set;z.on("line",Y=>{if(Y.trim())try{let x=JSON.parse(Y);x.session_id&&!g&&(g=x.session_id);let Q=x.type??(x.event?.type?`event.${x.event.type}`:"unknown");if(X.add(Q),x.type==="result"&&x.result&&v.length===0){let L=typeof x.result=="string"?x.result:"";if(L){let K=ln(v,L);K&&b?.({type:"delta",jobId:i,text:K},i)}}if(x.type==="assistant"&&Array.isArray(x.message?.content)){typeof x.error=="string"&&(E=x.error);for(let L of x.message.content){if(L.type==="text"&&L.text){let K=ln(v,L.text);K&&b?.({type:"delta",jobId:i,text:K},i)}if(L.type==="tool_use"&&L.name){let K=L.input?.file_path||L.input?.path||void 0,H=Fa(L);if(b?.({type:"tool_use",jobId:i,tool:L.name,...K?{file:K}:{},...H?{content:H}:{}},i),L.name==="Edit"&&L.input?.file_path){let B={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};u.push(B),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:B.file_path,oldString:typeof B.old_string=="string"?B.old_string:void 0,newString:typeof B.new_string=="string"?B.new_string:void 0,replaceAll:typeof B.replace_all=="boolean"?B.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(u.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),M.push({sequence:M.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:L.input.file_path,content:typeof L.input.content=="string"?L.input.content:void 0}))}L.type==="thinking"&&L.thinking&&b?.({type:"thinking",jobId:i,text:L.thinking},i)}}x.type==="result"&&x.is_error===!0&&(h=!0,typeof x.error=="string"&&(E=x.error),typeof x.result=="string"&&(D=x.result)),x.type==="user"&&x.tool_use_result?.file?.filePath&&b?.({type:"tool_use",jobId:i,tool:"Read",file:x.tool_use_result.file.filePath},i)}catch{}});let G=[];S.stderr?.on("data",Y=>{G.push(Y.toString())}),S.on("close",Y=>{if(clearTimeout(C),z.close(),v.length===0&&X.size>0&&console.warn(`[Claude:${i}] No text captured. Event types seen: ${[...X].join(", ")}`),T)h=!0,m=`Timed out after ${Math.round(R/6e4)} minutes`;else if(Y!==0&&Y!==null){h=!0;let Q=G.join("").trim(),L=v.join("").trim(),K=v.length===0&&X.size>0?` (no text captured, event types: ${[...X].join(", ")})`:"";m=Q||D||L||`Claude process exited with code ${Y}${K}`}h&&!m&&D&&(m=D);let x=Ua(m,E);p({sessionId:g,text:v.join(""),success:!h,error:h?x.message:void 0,errorCode:h?x.code:void 0,recoverableError:h?x.recoverable:void 0,fileEdits:u.length>0?u:void 0,editEvents:M.length>0?M:void 0})}),S.on("error",Y=>{clearTimeout(C),h=!0,m=Y.message,p({sessionId:g,text:v.join(""),success:!1,error:m,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:u.length>0?u:void 0,editEvents:M.length>0?M:void 0})})});return{process:S,result:f}}function Ua(i,e){let t=i.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 Wa,spawnSync as sr}from"child_process";import{readFileSync as Ha,statSync as Ga}from"fs";import{basename as Va,extname as Ka,isAbsolute as Qa,relative as ar,resolve as Xa}from"path";import{createInterface as Ya}from"readline";function Fn(i){return i&&typeof i=="object"&&!Array.isArray(i)?i:void 0}function qn(i,e){for(let t of i)if(t)for(let n of e){let o=t[n];if(typeof o=="string"&&o.trim())return o.trim()}}function Zo(i){let e=Fn(i);if(e)return e;if(typeof i=="string")try{return Fn(JSON.parse(i))}catch{return}}function Ui(i){return i.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function za(i,e,t,n){return i!=="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 er(i){let e=Fn(i)??{},t=Fn(e.invocation),n=Zo(e.arguments)??Zo(t?.arguments),o=qn([e,t],["server","server_name"]),r=qn([e,t],["tool","tool_name","name"]),s=qn([n,e,t],["title","display_name","description"]),d=qn([n],["code","script"]),c=za(o,r,s,d)?"Browser":o?Ui(o):r?Ui(r):"MCP",l=r&&Ui(r),w=s??l,R=w&&w!==c?`${c}: ${w}`:c;return{tool:c,...w?{content:w}:{},telemetryLabel:R}}function tr(i){let e=i.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):i}var nr=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"]),zi=2e5,Za=1e5,dr=2e5;function cr(i){let e=Va(i).toLowerCase(),t=Ka(i).toLowerCase();return nr.has(t)||nr.has(e)}function pn(i,e){let t=Qa(e)?e:Xa(i,e),n=ar(i,t);return n===""||n.startsWith("..")?null:t}function Un(i,e){if(!cr(e))return;let t=pn(i,e);if(t)try{let n=Ga(t);return n.isFile()?n.size>zi?{exists:!0,truncated:!0}:{exists:!0,content:Ha(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function ed(i,e){for(let t of e){let n=i[t];if(typeof n=="string")return n}}function td(i){let e=i?.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 ir(i){return ed(i,["patch","diff","unifiedDiff","unified_diff"])}function Wi(i,e){return i.length<=e?{text:i}:{text:i.slice(0,e),truncated:!0}}function or(i,e){let t=sr("git",e,{cwd:i,encoding:"utf8",timeout:5e3,maxBuffer:dr+65536});return t.status!==0?null:t.stdout??""}function nd(i){let e=new Set;for(let t of i.split(`
|
|
48
|
+
`)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let o=n.split(" -> ");for(let r of o)r&&e.add(r)}return[...e]}function rr(i){let e=or(i,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=or(i,["diff","--no-ext-diff","HEAD","--"])??"",n=Wi(t,dr);return{status:e,changedFiles:nd(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function id(i,e){return!i||!e?!1:i.status!==e.status||(i.diff??"")!==(e.diff??"")}function od(i,e){if(!cr(e))return;let t=pn(i,e);if(!t)return;let n=ar(i,t);if(n===""||n.startsWith(".."))return;let o=sr("git",["show",`HEAD:${n}`],{cwd:i,encoding:"utf8",timeout:5e3,maxBuffer:zi+65536});if(o.status!==0)return{exists:!1};let r=o.stdout??"",s=Wi(r,zi);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function rd(i,e,t){return e.map(n=>{let o=t.has(n)?t.get(n):od(i,n),r=Un(i,n);return{filePath:n,...o?{before:o}:{},...r?{after:r}:{}}})}function zn(i,e){let{prompt:t,projectRoot:n,screenshotPath:o,resumeSessionId:r,model:s,onEvent:d,sandboxMode:c="workspace-write",configOverrides:l=[]}=e,w=[];if(r){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${c}"`);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(r),w.push(t),o&&w.push("--image",o)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",c);for(let k of l)w.push("-c",k);s&&w.push("-m",s),w.push(t),o&&w.push("--image",o)}let R=Wa("codex",w,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:i}}),b=new Promise(k=>{let S,f=[],p=[],g=[],v=new Map,u=new Map,M=!1,h="",m=Ya({input:R.stdout}),E=new Set;m.on("line",T=>{if(T.trim())try{let C=JSON.parse(T),z=C.type??"unknown";if(E.add(z),z==="thread.started"&&C.thread_id&&!S&&(S=C.thread_id),(z==="item.agentMessage.delta"||z==="item/agentMessage/delta")&&C.delta?.text&&(f.push(C.delta.text),d?.({type:"delta",jobId:i,text:C.delta.text},i)),(z==="item.reasoning.delta"||z==="item/reasoning/delta")&&C.delta?.text&&d?.({type:"thinking",jobId:i,text:C.delta.text},i),(z==="item.started"||z==="item/started")&&C.item){let X=C.item.type;if(X==="command_execution"){let G=C.item.command,Y=G?tr(G):void 0,x=rr(n),Q=new Map;for(let K of x?.changedFiles??[])Q.set(K,Un(n,K));typeof C.item.id=="string"&&u.set(C.item.id,{...G?{rawCommand:G}:{},...Y?{command:Y}:{},...x?{beforeWorktree:x}:{},beforeSnapshots:Q});let L=Y?`Bash: ${Y.split(`
|
|
49
|
+
`)[0].slice(0,80)}`:"Bash";p.push(L),d?.({type:"tool_use",jobId:i,tool:"Bash",...Y?{content:Y}:{}},i)}else if(X==="file_change"){let G=C.item.filename||C.item.path;G&&!v.has(G)&&v.set(G,Un(n,G)),p.push(G?`Edit ${G.split("/").pop()}`:"Edit");let Y=G?pn(n,G)??G:void 0;d?.({type:"tool_use",jobId:i,tool:"Edit",...Y?{file:Y}:{}},i)}else if(X==="file_read"){let G=C.item.filename||C.item.path;p.push(G?`Read ${G.split("/").pop()}`:"Read");let Y=G?pn(n,G)??G:void 0;d?.({type:"tool_use",jobId:i,tool:"Read",...Y?{file:Y}:{}},i)}else if(X==="web_search")p.push("WebSearch"),d?.({type:"tool_use",jobId:i,tool:"WebSearch"},i);else if(X==="mcp_tool_call"){let G=er(C.item);p.push(G.telemetryLabel),d?.({type:"tool_use",jobId:i,tool:G.tool,...G.content?{content:G.content}:{}},i)}}if((z==="item.completed"||z==="item/completed")&&C.item){if(C.item.type==="agent_message"){let X=C.item.text;if(typeof X=="string"&&X){let G=ln(f,X);G&&d?.({type:"delta",jobId:i,text:G},i)}}else if(C.item.type==="reasoning"){let X=C.item.text;typeof X=="string"&&X&&d?.({type:"thinking",jobId:i,text:X},i)}else if(C.item.type==="file_change"&&Array.isArray(C.item.changes))for(let X of C.item.changes){let G=X.path||X.filename,Y=X.kind==="add"?"Write":"Edit";if(G){p.push(`${Y} ${G.split("/").pop()}`);let x=pn(n,G)??G;d?.({type:"tool_use",jobId:i,tool:Y,file:x},i);let Q=X,L=typeof Q.kind=="string"?Q.kind:void 0,K=td(L),H=v.get(G),B=Un(n,G);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:K,filePath:G,...H?{before:H}:{},...B?{after:B}:{},...ir(Q)?{patch:ir(Q)}:{},...L?{rawKind:L}:{}}),v.set(G,B)}}else if(C.item.type==="command_execution"){let X=typeof C.item.id=="string"?C.item.id:void 0,G=X?u.get(X):void 0,Y=typeof C.item.command=="string"?C.item.command:G?.rawCommand,x=Y?tr(Y):G?.command,Q=rr(n);if(id(G?.beforeWorktree,Q)){let L=[...new Set([...G?.beforeWorktree?.changedFiles??[],...Q?.changedFiles??[]])],K=typeof C.item.aggregated_output=="string"?Wi(C.item.aggregated_output,Za):void 0,H=typeof C.item.exit_code=="number"?C.item.exit_code:C.item.exit_code===null?null:void 0,B=typeof C.item.status=="string"?C.item.status:void 0;g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Y?{rawCommand:Y}:{},...x?{command:x}:{},...H!==void 0?{exitCode:H}:{},...B?{status:B}:{},...K?{output:K.text}:{},...K?.truncated?{outputTruncated:!0}:{},...G?.beforeWorktree?{beforeWorktree:G.beforeWorktree}:{},...Q?{afterWorktree:Q}:{},...L.length>0?{touchedFiles:rd(n,L,G?.beforeSnapshots??new Map)}:{}})}X&&u.delete(X)}}z==="turn.failed"&&(M=!0,h=C.error?.message||C.message||"Turn failed")}catch{}});let D=[];R.stderr?.on("data",T=>{D.push(T.toString())}),R.on("close",T=>{m.close(),f.length===0&&E.size>0&&console.warn(`[Codex:${i}] No text captured. Event types seen: ${[...E].join(", ")}`),T!==0&&T!==null&&(M=!0,h=D.join("")||`Codex process exited with code ${T}`),k({sessionId:S,text:f.join(""),success:!M,error:M?h:void 0,editEvents:g.length>0?g:void 0,toolsUsed:p.length>0?p:void 0})}),R.on("error",T=>{M=!0,h=T.message,k({sessionId:S,text:f.join(""),success:!1,error:h,editEvents:g.length>0?g:void 0,toolsUsed:p.length>0?p:void 0})})});return{process:R,result:b}}import{spawn as sd}from"child_process";import{createInterface as ad}from"readline";function lr(i,e){let t=i.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 pr(i,e){let{prompt:t,projectRoot:n,resumeSessionId:o,model:r,timeoutMs:s=3e5,onEvent:d,copilotPath:c="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];o&&l.push(`--resume=${o}`),r&&l.push("--model",r),l.push("-p",t);let w=sd(c,l,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),R=new Promise(b=>{let k,S=[],f=[],p=!1,g="",v=!1,u=setTimeout(()=>{v=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),M=ad({input:w.stdout}),h=new Set,m=[];M.on("line",D=>{if(D.trim())try{let T=JSON.parse(D),C=mn(T);h.add(C),m.length<5&&cd(C)&&m.push(D.slice(0,800));let z=un(T,["sessionId","session_id","id"],["session","conversation","thread"]);z&&!k&&(k=z);let X=dd(T,S.length===0);X&&(S.push(X),d?.({type:"delta",jobId:i,text:X},i));let G=ld(T);G&&d?.({type:"thinking",jobId:i,text:G},i);let Y=pd(T);Y&&(f.push(Y.label),d?.({type:"tool_use",jobId:i,tool:Y.tool,...Y.file?{file:Y.file}:{},...Y.content?{content:Y.content}:{}},i));let x=ud(T);x&&(p=!0,g=x)}catch{}});let E=[];w.stderr?.on("data",D=>{E.push(D.toString())}),w.on("close",D=>{clearTimeout(u),M.close(),S.length===0&&h.size>0&&(console.warn(`[Copilot:${i}] No text captured. Event types seen: ${[...h].join(", ")}`),m.length>0&&console.warn(`[Copilot:${i}] Sample text-bearing candidates: ${m.join(`
|
|
50
|
+
`)}`)),v?(p=!0,g=`Timed out after ${Math.round(s/6e4)} minutes`):D!==0&&D!==null&&(p=!0,g=E.join("").trim()||g||`Copilot process exited with code ${D}`);let T=p?lr(g,r):null;b({sessionId:k,text:S.join(""),success:!p,error:T?.message,errorCode:T?.code,recoverableError:T?.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})}),w.on("error",D=>{clearTimeout(u);let T=lr(D.message,r);b({sessionId:k,text:S.join(""),success:!1,error:T.message,errorCode:T.code,recoverableError:T.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})})});return{process:w,result:R}}function mn(i){if(typeof i.type=="string")return i.type;let e=i.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof i.event=="string"?i.event:"unknown"}function dd(i,e=!1){let t=mn(i).toLowerCase(),n=i.update,o=n?.content;if(n?.sessionUpdate==="agent_message_chunk"&&o?.type==="text"&&typeof o.text=="string")return o.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return Ue(i.delta)??Ue(i.content)??Ue(i.message);if(t==="assistant.message"&&e)return Ue(i.message)??Ue(i.content)??Ue(i);if(t==="result"&&e)return Ue(i.result)??Ue(i.output)??Ue(i.message)??Ue(i);let r=i.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof i.text=="string"&&Hi(i))return i.text;if(typeof i.message=="string"&&Hi(i))return i.message;if(typeof i.delta=="string"&&Hi(i))return i.delta}function Ue(i){if(typeof i=="string")return i;if(!i)return;if(Array.isArray(i)){let t=i.map(Ue).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof i!="object")return;let e=i;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=Ue(e[t]);if(n)return n}}function cd(i){let e=i.toLowerCase();return e.includes("assistant.message")||e==="result"}function ld(i){if(typeof i.thinking=="string")return i.thinking;if(typeof i.reasoning=="string")return i.reasoning;let e=i.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function pd(i){let e=un(i,["tool","toolName","tool_name","name"]),t=un(i,["command","cmd"]),n=un(i,["file","path","filename","filePath"]),o=mn(i);if(t||o.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
|
|
51
|
+
`)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let r=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function ud(i){if(typeof i.error=="string")return i.error;if(i.error&&typeof i.error=="object"){let e=i.error;if(typeof e.message=="string")return e.message}if(typeof i.message=="string"&&mn(i).toLowerCase().includes("error"))return i.message}function un(i,e,t=[]){for(let n of e){let o=i[n];if(typeof o=="string")return o}for(let[n,o]of Object.entries(i)){if(!o||typeof o!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=un(o,e);if(r)return r}}function Hi(i){let e=mn(i).toLowerCase();return(typeof i.role=="string"?i.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as md,readFile as fd}from"fs/promises";import{join as Gi}from"path";var Wn=class{constructor(e){let t=Gi(e,".popmelt");this.decisionsDir=Gi(t,"decisions")}async listDecisionIds(){try{return(await md(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 fd(Gi(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 hd,randomUUID as gd}from"crypto";import{mkdir as Vi,readFile as ur,readdir as mr,rename as Hn,stat as fr,unlink as Gn,writeFile as Vn}from"fs/promises";import{extname as yd,join as Ve}from"path";var Id=10080*60*1e3,vd=600*1e3,wd=3600*1e3;function bd(i){return i==="image/svg+xml"?".svg":i==="text/plain"?".txt":".bin"}function xd(i,e){return[...i.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var Kn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let t=gd(),n=bd(e.mimeType),o=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:xd(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:o};await Vi(this.draftsDir,{recursive:!0});let d=Ve(this.draftsDir,o),c=Ve(this.draftsDir,`${t}.json`),l=`${d}.part`,w=`${c}.part`;return await Vn(l,e.data),await Hn(l,d),await Vn(w,JSON.stringify(s,null,2)),await Hn(w,c),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let o=await this.readManifest(n.id);if(!o)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(o.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ve(this.draftsDir,o.contentFile),s=await ur(r),d=hd("sha256").update(s).digest("hex"),c=Ve(this.mediaDir,`${d}${yd(o.contentFile)||".bin"}`);await Vi(this.mediaDir,{recursive:!0});try{await fr(c)}catch{let l=`${c}.part`;await Vn(l,s),await Hn(l,c)}(t[n.annotationId]??=[]).push({id:o.id,name:o.name,mimeType:o.mimeType,size:o.size,kind:o.kind,path:c}),o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o)}return t}async sweep(e=Date.now()){let t;try{t=await mr(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let o=Ve(this.draftsDir,n);if(n.endsWith(".part")){let d=await fr(o).catch(()=>null);d&&e-d.mtimeMs>wd&&await Gn(o).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>vd:e-r.lastSeenAt>Id)||await Promise.all([Gn(o).catch(()=>{}),Gn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await mr(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Gn(Ve(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await ur(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Vi(this.draftsDir,{recursive:!0});let t=Ve(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Vn(n,JSON.stringify(e,null,2)),await Hn(n,t)}};import{randomUUID as hr}from"crypto";import{mkdir as Ki,readFile as Qi,writeFile as Qn}from"fs/promises";import{dirname as Xi,join as Ft}from"path";var Ke="[ProjectionWorker]",Sd={version:1,runs:[]},Td={version:1,updatedAt:0,proposals:[]},Pd=12;function kd(i){return Array.isArray(i)?i.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 gr(i){let e=[];for(let t of i){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Ke} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function Rd(i,e,t){return{decisionCount:i.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function Ad(i,e,t){let n=new Set(e),o=new Set,r=Array.isArray(i.rules)?i.rules:[];for(let S of r){if(!S||typeof S!="object")continue;let f=S.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&n.has(p)&&o.add(p)}let s=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?i.tokens:{},d=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?i.components:{},c=Array.isArray(t?.rules)?t.rules:[],l=r.filter(S=>{if(!S||typeof S!="object")return!1;let f=S.id,p=typeof f=="string"?c.find(g=>g&&typeof g=="object"&&g.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(S)}).length,w=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},R=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},b=Object.keys(s).filter(S=>JSON.stringify(s[S])!==JSON.stringify(w[S])).length,k=Object.keys(d).filter(S=>JSON.stringify(d[S])!==JSON.stringify(R[S])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:k,coveredDecisionIds:[...o],uncoveredDecisionIds:e.filter(S=>!o.has(S))}}function jd(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function Md(i,e,t){let n=i[e];if(n&&typeof n=="object")return n;let o=typeof t=="number"?[]:{};return i[String(e)]=o,o}function Xn(i,e,t){let n=i;for(let r=0;r<e.length-1;r++)n=Md(n,e[r],e[r+1]);let o=e[e.length-1];n[String(o)]=jd(t)}function yr(i,e){let t=i;for(let o=0;o<e.length-1;o++){let r=t[String(e[o])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function Ed(i,e){if(!i)return{exists:!1};let t=i;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 _d(i,e){return Array.isArray(e)?i===void 0?e.length>0:!Array.isArray(i)||e.length<=i.length?!1:i.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Ir(i,e){if(i.authorityStatus!=="accepted"||!i.changes?.length)return null;for(let t of i.changes){let n=Ed(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?_d(n.exists?n.value:void 0,t.value):!n.exists))return null}return i.changes}var Yn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Ft(e,".popmelt");this.runsPath=Ft(n,"projection-runs.json"),this.legacyRunsPath=Ft(n,"materialization-runs.json"),this.proposalsPath=Ft(n,"projection-queue.json"),this.legacyProposalsPath=Ft(n,"model-proposals.json"),this.modelPath=Ft(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await Qi(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=kd(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let o=n.key.split(".");n.value===null?yr(t,o):Xn(t,o,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(Pd),t=new Set((await this.loadModelProposals()).proposals.flatMap(o=>o.status==="pending"&&o.authorityStatus==="accepted"?o.decisionIds:[]));return{decisions:e.filter(o=>!t.has(o.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(),o=n.decisions;if(o.length===0)return{processedIds:[],success:!0};let r=o.map(S=>S.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),d=Dd(o,s),c=Rd(o,n.totalCandidateDecisionCount,d);t=hr().slice(0,8);let l={id:t,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:c};await this.persistRun(l);let w=!0,R,b,k;try{let S=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(S,d,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:f},await this.persistRun(l);let g=await p;if(!g.success)w=!1,R=g.error,console.error(`${Ke} ${f} spawn error:`,R);else{let v=Od(g.text,r);if(v){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of v)Xn(u,m.path,m.value);Array.isArray(u.rules)&&(u.rules=gr(u.rules));let M=Ad(u,r,s);if(v){let m=[...new Set(v.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=r.filter(E=>!m.includes(E))}b=M;let h=await this.createModelProposal({decisionIds:r,proposedModel:u,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:b,changes:v});k=h.id,console.log(`${Ke} Created model proposal ${h.id} for ${r.length} decision(s)`)}else w=!1,R="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${R}`)}}catch(S){w=!1,R=S instanceof Error?S.message:String(S),console.error(`${Ke} Error:`,R)}return await this.persistRun({...l,status:w?"proposed":"failed",completedAt:Date.now(),error:R,outputStats:b,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:w,error:R}),{processedIds:r,success:w,error:R,runId:t,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=gr(e.rules)),await Qn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await Ki(Xi(this.runsPath),{recursive:!0}),await Qn(this.runsPath,JSON.stringify(t,null,2)),t):{...Sd,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let o=await this.readProposalStore(this.legacyProposalsPath);o&&(e={version:1,updatedAt:Date.now(),proposals:o.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Td,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(o=>{if(o.proposedModel)return o;let r=structuredClone(n);for(let s of o.changes??[])Xn(r,s.path,s.value);return{...o,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>o.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>n.createdAt-o.createdAt||n.updatedAt-o.updatedAt)}async applySelectedModelProposal(e,t,n,o="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let c of t)!Array.isArray(c.path)||c.path.length===0||(c.remove?yr(s,c.path):Xn(s,c.path,c.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:o,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:hr().slice(0,8),status:"pending",title:Cd(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"}.`:$d(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(o=>o.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),o=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(o={...r,...t,updatedAt:Date.now()},o)),o?(n.updatedAt=Date.now(),await this.persistModelProposals(n),o):null}async persistModelProposals(e){try{await Ki(Xi(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...o})=>o)};await Qn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(o=>o.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await Ki(Xi(this.runsPath),{recursive:!0}),await Qn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await Qi(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await Qi(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,o){let r=n.provider??this.options.provider??"codex",s=this.options.onEvent?(d,c)=>this.options.onEvent?.(d):void 0;return r==="codex"?{provider:"codex",...zn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:Jn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...Ln(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Cd(i){let t=(Array.isArray(i.rules)?i.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function $d(i,e){let t=Array.isArray(i.rules)?i.rules.length:0,n=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?Object.keys(i.tokens).length:0,o=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Od(i,e){let t=i.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 o=new Set(e),r=n.flatMap((s,d)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let c=s;if(!Array.isArray(c.path)||c.path.length===0||!c.path.every(R=>typeof R=="string"||typeof R=="number")||typeof c.rationale!="string"||!c.rationale.trim())return[];let l=c.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(c.path.length!==1||!Array.isArray(c.value)))return[];if(!Object.prototype.hasOwnProperty.call(c,"value")||c.value===void 0)return[];let w=Array.isArray(c.decisionIds)?c.decisionIds.filter(R=>typeof R=="string"&&o.has(R)):[];return w.length===0?[]:[{id:typeof c.id=="string"&&c.id?c.id:`change-${d+1}`,path:c.path,value:c.value,decisionIds:w,rationale:c.rationale,label:typeof c.label=="string"?c.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function Dd(i,e){let t=i.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
50
52
|
Kind: ${r.kind}
|
|
51
53
|
Claim: ${r.claim}
|
|
52
54
|
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
@@ -125,15 +127,15 @@ Example:
|
|
|
125
127
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
126
128
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
127
129
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
128
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
129
|
-
`),t=[],n=null;for(let o of e){let r=o.match(
|
|
130
|
+
Include property and bindings when the decision context has class-level evidence.`}var Zn=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){for(let o of this.listeners)o(e,t,n)}cancelJob(e){let t=this.queue.findIndex(o=>o.id===e);if(t>=0){let[o]=this.queue.splice(t,1);return o?(o.status="cancelled",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),o):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 Nd}from"child_process";import{readFile as br}from"fs/promises";import{homedir as Zi}from"os";import{join as et}from"path";var eo=/popmelt/i;function Pt(){return{found:!1,name:null,scope:null,disabled:!1}}function Ut(i,e,t=!1){return{found:!0,name:i,scope:e,disabled:t}}function fn(i){for(let e of Object.keys(i))if(eo.test(e))return e;return null}async function ei(i){try{let e=await br(i,"utf-8");return JSON.parse(e)}catch{return null}}async function to(i){let e=Zi(),t=await ei(et(e,".claude.json"));if(t&&typeof t=="object"){let o=t;if(o.mcpServers&&typeof o.mcpServers=="object"){let r=fn(o.mcpServers);if(r)return Ut(r,"user")}if(o.projects&&typeof o.projects=="object"){let s=o.projects[i];if(s&&typeof s=="object"){let d=s;if(d.mcpServers&&typeof d.mcpServers=="object"){let c=fn(d.mcpServers);if(c){let l=Array.isArray(d.disabledMcpjsonServers)&&d.disabledMcpjsonServers.some(w=>eo.test(w));return Ut(c,"project",l)}}}}}let n=await ei(et(i,".mcp.json"));if(n&&typeof n=="object"){let o=n;if(o.mcpServers&&typeof o.mcpServers=="object"){let s=fn(o.mcpServers);if(s){let d=await vr(i,s);return Ut(s,"mcp.json",d)}}let r=fn(o);if(r&&r!=="mcpServers"){let s=await vr(i,r);return Ut(r,"mcp.json",s)}}return Pt()}async function vr(i,e){let t=et(i,".claude","settings.local.json"),n=await ei(t);if(n&&typeof n=="object"){let o=n;if(Array.isArray(o.disabledMcpjsonServers))return o.disabledMcpjsonServers.some(r=>r===e)}return!1}var Bd=/^\[mcp_servers\.([^\]]+)\]/;function Jd(i){let e=i.split(`
|
|
131
|
+
`),t=[],n=null;for(let o of e){let r=o.match(Bd);r?(n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
130
132
|
`)}),n={name:r[1],bodyLines:[]}):o.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
|
|
131
133
|
`)}),n=null):n&&n.bodyLines.push(o)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
132
|
-
`)}),t}function
|
|
133
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
134
|
+
`)}),t}function Ld(i){return/enabled\s*=\s*false/i.test(i)}async function no(i){let e=process.env.CODEX_HOME||et(Zi(),".codex"),t=await wr(et(e,"config.toml"),"user");if(t.found)return t;let n=await wr(et(i,".codex","config.toml"),"project");return n.found?n:Pt()}async function io(i,e="copilot"){let t=await qd(e);if(t.found)return t;let n=process.env.COPILOT_HOME||et(Zi(),".copilot"),o=await Yi(et(n,"mcp-config.json"),"user");if(o.found)return o;let r=await Yi(et(i,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Yi(et(i,".github","mcp.json"),"mcp.json");return s.found?s:Pt()}async function qd(i){try{let e=await new Promise((t,n)=>{Nd(i,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,r)=>{if(o){n(o);return}t(r)})});return xr(JSON.parse(e),"user")}catch{return Pt()}}async function Yi(i,e){let t=await ei(i);return xr(t,e)}function xr(i,e){if(!i||typeof i!="object")return Pt();let t=i,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,o=fn(n);return o?Ut(o,e):Pt()}async function wr(i,e){try{let t=await br(i,"utf-8"),n=Jd(t);for(let o of n)if(eo.test(o.name)){let r=Ld(o.body);return Ut(o.name,e,r)}}catch{}return Pt()}import{execFile as Sr}from"child_process";import{mkdir as Fd,readFile as Tr,writeFile as Pr}from"fs/promises";import{homedir as kr}from"os";import{dirname as Ud,join as oo}from"path";var ro="https://mcp.popmelt.com/mcp";async function Rr(i=ro){let e=oo(kr(),".claude.json"),t;try{let o=await Tr(e,"utf-8");t=JSON.parse(o)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let o of Object.keys(n))if(/popmelt/i.test(o))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:i},await Pr(e,JSON.stringify(t,null,2)+`
|
|
135
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Ar(i=ro){let e=process.env.CODEX_HOME||oo(kr(),".codex"),t=oo(e,"config.toml"),n;try{n=await Tr(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Fd(Ud(t),{recursive:!0});let o=`
|
|
134
136
|
[mcp_servers.popmelt]
|
|
135
137
|
url = "${i}"
|
|
136
|
-
`;return await
|
|
138
|
+
`;return await Pr(t,n+o,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function jr(i=ro,e="copilot"){let t=await zd(e);if(Wd(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,o)=>{Sr(e,["mcp","add","--transport","http","--json","popmelt",i],{encoding:"utf-8",timeout:1e4},r=>{if(r){o(r);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function zd(i){try{let e=await new Promise((t,n)=>{Sr(i,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(o,r)=>{if(o){n(o);return}t(r)})});return JSON.parse(e)}catch{return null}}function Wd(i){if(!i||typeof i!="object")return!1;let e=i,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}var ti=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 o=this.leases.get(e),r={id:e,ownerPid:t,createdAt:o?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[n,o]of this.leases)o.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 Hd=String.raw`
|
|
137
139
|
(() => {
|
|
138
140
|
const hidden = [];
|
|
139
141
|
const visit = (root) => {
|
|
@@ -154,7 +156,7 @@ url = "${i}"
|
|
|
154
156
|
visit(document);
|
|
155
157
|
window.__popmeltNativeCaptureHidden = hidden;
|
|
156
158
|
})()
|
|
157
|
-
`,
|
|
159
|
+
`,Gd=String.raw`
|
|
158
160
|
(() => {
|
|
159
161
|
for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
|
|
160
162
|
if (value) element.style.setProperty('visibility', value, priority);
|
|
@@ -162,22 +164,22 @@ url = "${i}"
|
|
|
162
164
|
}
|
|
163
165
|
delete window.__popmeltNativeCaptureHidden;
|
|
164
166
|
})()
|
|
165
|
-
`;function ti(i){try{let e=new URL(i);return e.hash="",e.href}catch{return null}}function Gd(i,e){let t=ti(e);if(!t)return null;let n=new URL(t),o=i.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&ti(s.url)),r=o.find(s=>ti(s.url)===t);return r||(o.find(s=>{let d=new URL(ti(s.url));return d.origin===n.origin&&d.pathname===n.pathname})??null)}function Vd(i){let e={x:Number(i.x),y:Number(i.y),width:Number(i.width),height:Number(i.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 Kd(i){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",i).href,o=await fetch(n,{signal:e.signal});if(!o.ok)throw new Error(`CDP discovery returned ${o.status}`);let r=await o.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Qd(i){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let o=new e(i,{handshakeTimeout:1e3}),r=()=>{o.off("error",s),t(o)},s=d=>{o.off("open",r),n(d)};o.once("open",r),o.once("error",s)})}function Xd(i){let e=1,t=new Map;return i.on("message",n=>{let o;try{o=JSON.parse(String(n))}catch{return}if(!o.id)return;let r=t.get(o.id);r&&(t.delete(o.id),clearTimeout(r.timeout),o.error?r.reject(new Error(o.error.message||`CDP error ${o.error.code??""}`.trim())):r.resolve(o.result??{}))}),i.on("close",()=>{for(let[n,o]of t)clearTimeout(o.timeout),o.reject(new Error("CDP connection closed")),t.delete(n)}),(n,o={})=>new Promise((r,s)=>{let d=e++,c=setTimeout(()=>{t.delete(d),s(new Error(`CDP ${n} timed out`))},4e3);t.set(d,{resolve:r,reject:s,timeout:c}),i.send(JSON.stringify({id:d,method:n,params:o}),l=>{l&&(clearTimeout(c),t.delete(d),s(l))})})}async function Ar(i,e){let t=Vd(e.clip),n=await Kd(i),o=Gd(n,e.pageUrl);if(!o?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Qd(o.webSocketDebuggerUrl),s=Xd(r),d=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Wd,returnByValue:!0}),d=!0;let c=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof c.data=="string"?c.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{d&&await s("Runtime.evaluate",{expression:Hd,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as Ur,readFile as In,writeFile as zr}from"fs/promises";import{join as Gt}from"path";var Yd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ro(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ni(i){return new Set(ro(i).split(" ").filter(e=>e.length>2&&!Yd.has(e)))}function Mr(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function Zd(i){return[{value:i.label,by:"label"},...i.aliases.map(e=>({value:e,by:"alias"})),...i.locators.map(e=>({value:e.value,by:"locator"}))]}function ec(i,e){let t=new Map,n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(ro).filter(Boolean),r=ni([e.action,e.text].filter(Boolean).join(" "));for(let s of i){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let d;for(let c of Zd(s)){let l=ro(c.value);for(let T of o){let R=l===T?95:l.includes(T)||T.includes(l)?75:0;R>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:R>=90?"exact":"strong",matchedBy:c.by,score:R})}let k=["/","#","[","]","="].some(T=>c.value.includes(T))?0:Math.round(Mr(ni(l),r)*55);k>=30&&k>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"query_text",score:k})}d&&t.set(s.id,d)}return t}function tc(i,e){let t=new Set(i.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(i.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),o=e.filter(s=>s.iterationIds.some(d=>t.has(d))||s.sourceRefs.some(d=>d.kind==="thread"&&n.has(d.id)));if(!o.length)return{state:"none_found",attemptIds:[]};let r=new Set(o.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:o.map(s=>s.id)}}function nc(i){return Math.ceil(JSON.stringify(i).length/4)}function so(i,e){let t=i.records.filter(p=>p.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),o=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=i.records.filter(p=>{if(p.recordType!=="proposal"||o&&!o.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let g=[...i.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===p.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return g?g.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||g.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||g.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||g.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||g.resurfaceWhen.includes("after_date")&&!!(g.revisitAfter&&Date.parse(n)>=Date.parse(g.revisitAfter)):!1}),s=i.records.filter(p=>p.recordType==="implementation_attempt"),d=ec(t,e),c=[...d.values()].sort((p,g)=>g.score-p.score),l=ni([e.action,e.text].filter(Boolean).join(" ")),w=r.flatMap(p=>{let g=p.subjects.map(h=>d.get(h.subjectId)).filter(h=>!!h),v=Math.max(0,...g.map(h=>h.score)),u=Math.round(Mr(ni(p.claim),l)*35),M=v+u;return M>=50?[{proposal:p,proposalMatches:g,score:M}]:[]}).sort((p,g)=>g.score-p.score||p.proposal.id.localeCompare(g.proposal.id)),k=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),R=[],x=0;for(let p of w){if(R.length>=k)break;let g=p.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:i.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(M=>M.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:M,...h})=>h)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(M=>M.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:tc(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:g},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...g]},u={...v,estimatedTokens:nc(v)};if(x+u.estimatedTokens>T)break;R.push(u),x+=u.estimatedTokens}let f=Math.max(0,w.length-R.length);return{packets:R,subjectMatches:c.map(({score:p,...g})=>g),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:f,maxEstimatedTokens:T,estimatedTokens:x},uncertainty:d.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var ic=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ao(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ii(i){return new Set(ao(i).split(" ").filter(e=>e.length>2&&!ic.has(e)))}function Er(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function oc(i,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(ao).filter(Boolean),o=ii([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of i){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of c){let w=ao(l.value);for(let R of n){let x=w===R?95:w.includes(R)||R.includes(w)?75:0;x>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:l.by,score:x})}let T=["/","#","[","]","="].some(R=>l.value.includes(R))?0:Math.round(Er(ii(w),o)*55);T>=30&&T>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}d&&r.push(d)}return r.sort((s,d)=>d.score-s.score||s.subjectId.localeCompare(d.subjectId))}function rc(i){return Math.ceil(JSON.stringify(i).length/4)}function zt(i,e){return i.relationshipType===e&&i.from.entityType==="decision"&&i.to.entityType==="decision"}function sc(i,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===i));if(!t.length)return{decisionId:i,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),o=n.some(r=>r.coverageClaims.some(s=>s.decisionId===i&&s.coverage==="full"));return{decisionId:i,state:o?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function ac(i,e,t){let n=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===i)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),o=t.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===i),r=n[0],s=o?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:i},state:s,attemptIds:n.map(d=>d.id)}}function _r(i,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),o=i.records.filter(m=>m.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=i.records.filter(m=>m.recordType==="decision"&&m.state==="active"),d=r?s.filter(m=>r.has(m.id)):s,c=i.records.filter(m=>m.recordType==="implementation_attempt"),l=i.records.filter(m=>m.recordType==="verification_attempt"),w=i.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),k=i.records.filter(m=>m.recordType==="evidence"),T=i.records.filter(m=>m.recordType==="model_entry"),R=oc(o,e),x=new Map(R.map(m=>[m.subjectId,m.score])),f=ii([e.action,e.text].filter(Boolean).join(" ")),p=d.flatMap(m=>{let E=Math.max(0,...m.subjects.map(C=>x.get(C.subjectId)??0)),D=Math.round(Er(ii(m.claim),f)*35),S=E+D;return S>=50?[{decision:m,score:S}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of p.slice(0,n))g.set(m.decision.id,m.decision);for(let m of i.relationships){if(!zt(m,"excepts")&&!zt(m,"contradicts"))continue;let E=s.find(S=>S.id===m.from.entityId),D=s.find(S=>S.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<n&&g.set(E.id,E),g.size<n&&g.set(D.id,D))}let v=[...g.values()],u=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&g.has(m.from.entityId)&&g.has(m.to.entityId),M=(m,E=!1)=>{let D=new Set(m.map(J=>J.id)),S=w.filter(J=>J.target.entityType==="decision"&&D.has(J.target.entityId)),C=new Set(i.relationships.filter(J=>zt(J,"excepts")&&D.has(J.from.entityId)&&D.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),X=i.relationships.filter(J=>zt(J,"contradicts")&&D.has(J.from.entityId)&&D.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),G=new Set(X.flatMap(J=>J.decisionIds)),Y=k.filter(J=>J.sourceRefs.some(V=>V.kind==="record"&&D.has(V.id))||i.relationships.some(V=>V.relationshipType==="supports"&&V.from.entityType==="evidence"&&V.from.entityId===J.id&&V.to.entityType==="decision"&&D.has(V.to.entityId))),b=Math.max(0,p.length-m.length),Q=i.relationships.some(J=>zt(J,"contradicts")&&u(J)&&(!D.has(J.from.entityId)||!D.has(J.to.entityId))),L=E||b>0||Q,K=[];R.length===0&&(e.subjectHints?.length??0)>0?K.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):m.length===0&&K.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),X.length&&K.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:X.flatMap(J=>J.expansionRefs)}),Y.some(J=>J.availability!=="available")&&K.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Y.map(J=>({kind:"record",id:J.id}))}),L&&K.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:i.manifest.projectId}]});let H={contractVersion:1,projectId:i.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:R.map(({score:J,...V})=>V),modelEntries:T.filter(J=>J.decisionIds.some(V=>D.has(V))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:m.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(V=>V.subjectId),authority:J.authority,effectiveState:G.has(J.id)?"conflicted":C.has(J.id)?"excepted":"active",freshness:S.filter(V=>V.target.entityId===J.id).map(V=>V.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:X,uncertainties:K,implementation:m.map(J=>sc(J.id,c)),verification:m.map(J=>ac(J.id,l,S)),evidence:Y.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:b,omittedEvidenceCount:0,conflictsComplete:!Q}};return H.budget.estimatedTokens=rc(H),H},h=M(v);for(;h.budget.estimatedTokens>t&&v.length>0;){let m=v.pop(),E=i.relationships.filter(D=>zt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);v=v.filter(D=>!E.includes(D.id)),h=M(v,!0)}return h}var dc=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Wt(i){return dc.test(i)}function cc(i){return{valid:!i.some(e=>e.severity==="error"),issues:i}}function ie(i,e,t,n){i.push({path:e,code:t,message:n,severity:"error"})}function co(i,e,t,n){i.push({path:e,code:t,message:n,severity:"warning"})}function Me(i,e,t){Wt(t)||ie(i,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(i,e,t){(!t||Number.isNaN(Date.parse(t)))&&ie(i,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function kt(i,e,t,n=!1){n&&t.level==="contributor"&&ie(i,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&ie(i,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var lc={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"])},pc=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function uc(i,e,t){Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Me(i,`${t}.entity.entityId`,e.entity.entityId),Qe(i,`${t}.createdAt`,e.createdAt),kt(i,`${t}.authority`,e.authority);let n=lc[e.entity.entityType],o=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(o)&&ie(i,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${o}.`);let r=`${e.entity.entityType}:${e.toState}`;if(pc.has(r)&&(kt(i,`${t}.authority`,e.authority,!0),e.reason?.trim()||ie(i,`${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)&&ie(i,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ie(i,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(i,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function mc(i,e,t,n){Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Qe(i,`${t}.createdAt`,e.createdAt),e.projectId!==n&&ie(i,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ie(i,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ie(i,`${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)&&ie(i,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(kt(i,`${t}.authority`,e.authority,!0),e.claim.trim()||ie(i,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&co(i,`${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())&&ie(i,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(i,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ie(i,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(o=>!o.trim())&&ie(i,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((o,r)=>{(!o.id.trim()||!o.modelPath.trim())&&ie(i,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(i,`${t}.concreteBindings[${r}].createdAt`,o.createdAt),Qe(i,`${t}.concreteBindings[${r}].updatedAt`,o.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ie(i,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(i,`${t}.appliedAt`,e.appliedAt),kt(i,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&ie(i,`${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())&&ie(i,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(o=>!o.trim()))&&ie(i,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&co(i,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&co(i,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function fc(i,e,t){if(Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Me(i,`${t}.from.entityId`,e.from.entityId),Me(i,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&ie(i,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&ie(i,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),Qe(i,`${t}.createdAt`,e.createdAt),e.reason.trim()||ie(i,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let o=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!o&&!r&&ie(i,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),o&&!e.authority?ie(i,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):o&&e.authority&&kt(i,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ie(i,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ie(i,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))&&ie(i,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ie(i,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Rt(i){let e=[];Me(e,"manifest.projectId",i.manifest.projectId),Qe(e,"manifest.createdAt",i.manifest.createdAt),Qe(e,"manifest.updatedAt",i.manifest.updatedAt);let t=new Map,n=(f,p)=>{let g=t.get(f);g?ie(e,p,"duplicate_id",`ID is already used at ${g}.`):t.set(f,p)};i.records.forEach((f,p)=>{let g=`records[${p}]`;n(f.id,g),mc(e,f,g,i.manifest.projectId)}),i.events.forEach((f,p)=>{let g=`events[${p}]`;n(f.id,g),uc(e,f,g),f.projectId!==i.manifest.projectId&&ie(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),i.relationships.forEach((f,p)=>{let g=`relationships[${p}]`;n(f.id,g),fc(e,f,g),f.projectId!==i.manifest.projectId&&ie(e,`${g}.projectId`,"project_mismatch","Relationship belongs to another project.")}),i.artifacts.forEach((f,p)=>{n(f.id,`artifacts[${p}]`),Me(e,`artifacts[${p}].id`,f.id)}),i.tombstones.forEach((f,p)=>{let g=`tombstones[${p}]`;n(f.id,g),Me(e,`${g}.id`,f.id),Me(e,`${g}.objectId`,f.objectId),Me(e,`${g}.deletedById`,f.deletedById),Qe(e,`${g}.deletedAt`,f.deletedAt),kt(e,`${g}.authority`,f.authority,!0)});let o=new Set(i.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(i.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{if(f.storeId)return;let g=`${f.entityType}:${f.entityId}`;!o.has(g)&&!r.has(g)&&ie(e,p,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};i.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),i.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let d=new Set(i.artifacts.map(f=>f.id)),c=(f,p)=>{d.has(f)||ie(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,g)=>{!o.has(`${f}:${p}`)&&!r.has(`${f}:${p}`)&&ie(e,g,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};i.records.forEach((f,p)=>{let g=`records[${p}]`;switch(f.recordType){case"authority_grant":l("participant",f.granteeId,`${g}.granteeId`),l("participant",f.grantedById,`${g}.grantedById`),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`));break;case"observation":f.captureContext.subjectIds.forEach((v,u)=>l("subject",v,`${g}.captureContext.subjectIds[${u}]`)),f.captureContext.artifactIds.forEach((v,u)=>c(v,`${g}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":f.subjects.forEach((v,u)=>l("subject",v.subjectId,`${g}.subjects[${u}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((v,u)=>c(v,`${g}.messageArtifactIds[${u}]`)),f.resultRefs.forEach((v,u)=>s(v,`${g}.resultRefs[${u}]`));break;case"iteration":f.threadIds.forEach((v,u)=>l("thread",v,`${g}.threadIds[${u}]`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"evidence":f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"advisory_explanation":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${g}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((v,u)=>l("iteration",v,`${g}.iterationIds[${u}]`)),f.coverageClaims.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverageClaims[${u}].decisionId`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${g}.replacesSpecId`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),(f.dependencies??[]).forEach((v,u)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${g}.dependencies[${u}].subjectId`)}),(f.scenarios??[]).forEach((v,u)=>{v.subjectIds?.forEach((M,h)=>l("subject",M,`${g}.scenarios[${u}].subjectIds[${h}]`))}),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${g}.evalSpecId`),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;case"model_entry":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`));break;case"model_projection":kt(e,`${g}.authority`,f.authority,!0),l("participant",f.appliedById,`${g}.appliedById`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.entryIds.forEach((v,u)=>l("model_entry",v,`${g}.entryIds[${u}]`)),f.coverage.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverage[${u}].decisionId`));break;case"freshness_signal":s(f.target,`${g}.target`),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;default:break}});let w=new Map(i.events.map(f=>[f.id,f])),k=new Map(i.records.map(f=>[`${f.recordType}:${f.id}`,f])),T=new Map;i.events.forEach((f,p)=>{let g=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,v=T.get(g)??new Set;v.add(f.toState),T.set(g,v),v.size>1&&ie(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let R=new Map(i.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),x=(f,p,g,v,u)=>{if(f.level!=="delegate"||!f.grantId)return;let M=R.get(f.grantId);if(!M){ie(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&ie(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(g);(h<Date.parse(M.startsAt)||M.endsAt&&h>Date.parse(M.endsAt)||M.revokedAt&&h>=Date.parse(M.revokedAt))&&ie(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&v.length&&!v.every(m=>M.subjectIds.includes(m))&&ie(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of i.records)f.recordType==="decision"&&x(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);i.events.forEach((f,p)=>{let g=k.get(`${f.entity.entityType}:${f.entity.entityId}`),v=g&&"subjects"in g?g.subjects.map(u=>u.subjectId):[];x(f.authority,f.participantId,f.createdAt,v,`events[${p}].authority`)}),i.relationships.forEach((f,p)=>{if(!f.authority)return;let g=[f.from,f.to].flatMap(v=>{let u=k.get(`${v.entityType}:${v.entityId}`);return u&&"subjects"in u?u.subjects.map(M=>M.subjectId):[]});x(f.authority,f.participantId,f.createdAt,g,`relationships[${p}].authority`)});for(let f of i.records){if(f.recordType!=="decision")continue;let p=w.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&ie(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&ie(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),k.has(`proposal:${f.proposalId}`)||ie(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(i.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===f.id)||ie(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(i.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===f.id&&v.toState==="revoked"&&!!v.reason?.trim())||ie(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of i.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;i.records.some(g=>g.recordType==="decision"&&g.proposalId===f.id)||ie(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return cc(e)}function hn(i,e,t,n){return{id:n,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function Cr(i,e,t,n,o){return{id:o,schemaVersion:1,projectId:i.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 hc(i){switch(i.action){case"accept":return[i.eventId,i.decisionId];case"edit_and_accept":return[i.withdrawalEventId,i.replacementProposalId,i.acceptanceEventId,i.decisionId,i.relationshipId];case"reject":case"defer":return[i.eventId]}}function oi(i,e){let t=[],n=i.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Wt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of hc(e))Wt(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...hn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Cr(i,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...hn(i,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},d={...hn(i,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=Cr(i,r,e,d.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,c],events:[s,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...hn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let o={...hn(i,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:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}import{createHash as gc}from"crypto";import{readFile as yc,readdir as Ic,realpath as vc}from"fs/promises";import{join as gn,relative as wc}from"path";var bc=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Ht(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}function ze(i,e=0){return new Date(Number.isFinite(i)?i:e).toISOString()}function $r(...i){return i.find(e=>!!e?.trim())?.trim()}function le(i,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=gc("sha256").update(`${i}\0${e}\0${t}`).digest("hex"),d=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${d}${s.slice(4,7)}-${s.slice(7,19)}`}async function lo(i,e){try{return JSON.parse(await yc(i,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:i,message:t instanceof Error?t.message:String(t)}),null}}function xc(i){let e=Ht(i);if(!e)return 0;let t=0,n=o=>{let r=Ht(o);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let o of Object.values(e))n(o);return t}function Sc(i){let e={};for(let t of i)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function yn(i){let e=[],t=await vc(i.projectRoot).catch(()=>i.projectRoot),n=gn(t,".popmelt"),o=await lo(gn(n,"threads.json"),e),r=await lo(gn(n,"model.json"),e),s=Ht(o),d=Ht(s?.threads)??{},c=Object.entries(d).map(([V,W])=>({key:V,value:Ht(W)})).filter(V=>!!V.value),l=gn(n,"decisions"),w=await Ic(l).catch(()=>[]),k=[];for(let V of w.filter(W=>W.endsWith(".json")).sort()){let W=Ht(await lo(gn(l,V),e));W&&k.push({file:V,value:W})}let T=c.flatMap(({value:V})=>[V.createdAt,V.updatedAt]).filter(V=>typeof V=="number"&&Number.isFinite(V)),R=T.length?Math.min(...T):0,x=i.projectKey??t;i.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let f=le(x,"project",x,R),p=le(x,"participant","legacy-owner",R),g=le(x,"participant","legacy-agent",R),v=le(x,"subject","project",R),u=ze(Math.max(R,...T)),M=[],h=[],m=new Map,E=new Map,D=new Map(k.map(V=>[V.value.id??V.file.replace(/^d-|\.json$/g,""),V.value])),S=new Map,C=(V,W,ee,ke,Be)=>{let ue=m.get(ee);if(ue)return ue;let Ce=le(x,"artifact",V,ke);return h.push({id:Ce,kind:W,mediaType:Be,location:ee,availability:"available"}),m.set(ee,Ce),Ce};for(let{file:V,value:W}of k){let ee=W.id??V.replace(/^d-|\.json$/g,""),ke=W.createdAt??R,Be=[C(`${ee}:envelope`,"other",`.popmelt/decisions/${V}`,ke,"application/json")];W.screenshotPath&&Be.push(C(`${ee}:screenshot`,"screenshot",`.popmelt/${W.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,W.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,Ce]of(W.pastedImagePaths??[]).entries())Be.push(C(`${ee}:image:${ue}`,"image",Ce,ke));S.set(ee,Be)}let z=(V,W,ee)=>({id:V,schemaVersion:1,projectId:f,createdAt:u,participantId:W,sourceRefs:ee}),X=(V,W)=>{M.push(W);let ee=E.get(V)??[];ee.push(W.id),E.set(V,ee)},G=[{...z(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...z(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];M.push(...G),M.push({...z(v,p,[]),recordType:"subject",subjectType:"project",label:wc(process.cwd(),t)||t,aliases:[],locators:[{id:le(x,"locator",t,R),kind:"project_root",value:t,status:"current",validFrom:ze(R),sourceRefs:[]}]});let Y=new Map,b=(V,W)=>{let ee=Y.get(V);if(ee)return ee;let ke=le(x,"subject",V,W),Be={...z(ke,p,[{kind:"external",id:V}]),createdAt:ze(W),recordType:"subject",subjectType:"element",label:V,aliases:[],locators:[{id:le(x,"locator",V,W),kind:"dom_selector",value:V,status:"current",validFrom:ze(W),sourceRefs:[{kind:"external",id:V}]}]};return M.push(Be),Y.set(V,ke),ke};for(let{key:V,value:W}of c){let ee=W.id??V,ke=W.createdAt??R,Be=le(x,"thread",ee,ke),ue={kind:"thread",id:ee},Ce=[],gt=[],on=Array.isArray(W.messages)?W.messages:[],Re,nt,yt=0;on.forEach((be,lt)=>{let $e=be.timestamp??ke,it=le(x,"artifact",`${ee}:message:${lt}`,$e);if(Ce.push(it),h.push({id:it,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,it),be.screenshotPath&&C(`${ee}:message:${lt}:screenshot`,"screenshot",be.screenshotPath,$e),be.role==="human"){Re=be;let Le=be.feedbackSummary??be.replyToQuestion;if(Le?.trim()){let qe=le(x,"observation",`${ee}:${lt}`,$e),Xe=W.elementIdentifiers??[],Mt={...z(qe,p,[ue,{kind:"message",id:it}]),createdAt:ze($e),recordType:"observation",state:"open",statement:Le,captureContext:{subjectIds:Xe.map(wt=>b(wt,ke)),artifactIds:[it]},resolvedByIds:[]};X(ee,Mt),nt=qe,gt.push({entityType:"observation",entityId:qe})}return}if(be.role!=="assistant")return;let pt=be.jobId??`${ee}:${lt}`,ut=le(x,"iteration",pt,$e),vt=D.get(pt),Mi=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",Ei={...z(ut,g,[ue,{kind:"message",id:it},...(S.get(pt)??[]).map(Le=>({kind:"artifact",id:Le}))]),createdAt:ze($e),recordType:"iteration",threadIds:[Be],startedAt:ze(Re?.timestamp,$e),completedAt:ze($e),requestSummary:$r(Re?.feedbackSummary,Re?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:Mi,execution:{provider:be.provider??vt?.provider,model:be.model??vt?.model,sessionId:be.sessionId??vt?.sessionId},artifactIds:[it,...S.get(pt)??[]]};X(ee,Ei),gt.push({entityType:"iteration",entityId:ut});let rn=be.resolutions??vt?.resolutions??[];for(let[Le,qe]of rn.entries()){if(qe.status!=="resolved"||!qe.summary?.trim())continue;let Xe=W.elementIdentifiers??[],Mt=(Xe.length?Xe:[t]).map(_n=>({subjectId:_n===t?v:b(_n,ke),role:"governed"})),wt=le(x,"proposal",`${pt}:${qe.annotationId??"resolution"}:${Le}`,$e),_i={...z(wt,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"proposal",state:"pending",claim:qe.summary,subjects:Mt,subjectSemantics:Mt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:$r(Re?.feedbackSummary,Re?.replyToQuestion,qe.summary),iterationId:ut,inferredById:g}};X(ee,_i),gt.push({entityType:"proposal",entityId:wt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ee,message:`Proposal ${wt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(rn.some(Le=>Le.status==="resolved")||vt?.gitDiff){let Le=le(x,"implementation",pt,$e),qe={...z(Le,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"implementation_attempt",state:"completed",iterationIds:[ut],coverageClaims:[],summary:rn.map(Xe=>Xe.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};X(ee,qe),gt.push({entityType:"implementation_attempt",entityId:Le}),yt+=1}nt&&(nt=void 0)});let It=on.at(-1),En={...z(Be,p,[ue]),createdAt:ze(ke),recordType:"thread",state:It?.question?"open":"resolved",messageArtifactIds:Ce,outcome:It?.question?"question_unresolved":yt?"implementation_only":"no_outcome",resultRefs:gt};M.push(En),E.set(ee,[Be,...E.get(ee)??[]])}let Q=xc(r);Q&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${Q} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:f,createdAt:ze(R),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:i.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:h,tombstones:[]},K=Rt(L),J=(i.proofCaseIds??bc).map(V=>({legacyId:V,threadFound:c.some(({key:W,value:ee})=>(ee.id??W)===V),decisionEnvelopeFound:D.has(V),recordIds:E.get(V)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((V,W)=>V+(W.value.messages?.length??0),0),decisionEnvelopes:k.length,modelEntries:Q,artifactsReferenced:h.length},imported:Sc(M),unresolvedAcceptance:e.filter(V=>V.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:J,issues:e,schemaIssues:K.issues}}}import{createHash as Tc}from"crypto";import{mkdir as Or,open as po,readFile as uo,readdir as Pc,rename as kc,unlink as mo}from"fs/promises";import{join as st}from"path";var Rc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function si(i){return Tc("sha256").update(JSON.stringify(i)).digest("hex")}function Dr(i){return si(i)}function Nr(i,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!i.manifest.features.includes("advisory_explanations")&&i.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 o=i.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(o<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=i.records[o];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);i.records[o]=structuredClone(n)}for(let n of e.projectionUpdates){let o=i.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!o||o.recordType!=="proposal"&&o.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(o.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${o.state}`);o.state=n.state}return i.records.push(...e.records),i.events.push(...e.events),i.relationships.push(...e.relationships),i.artifacts.push(...e.artifacts),i.tombstones.push(...e.tombstones),i.manifest.updatedAt=t,i}function jc(i,e,t){return Nr(structuredClone(i),e,t)}async function jt(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await po(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
166
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await kc(t,i)}catch(o){throw await mo(t).catch(()=>{}),o}}async function ri(i){return JSON.parse(await uo(i,"utf8"))}var ai=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=st(e,".popmelt","memory"),this.journalDir=st(this.memoryDir,"journal"),this.manifestPath=st(this.memoryDir,"manifest.json"),this.checkpointPath=st(this.memoryDir,"checkpoint.json"),this.lockPath=st(this.memoryDir,"writer.lock")}async initialize(e){let t=Rt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Or(this.journalDir,{recursive:!0});try{throw await uo(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 uo(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=si(e),o={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await jt(this.checkpointPath,o),await jt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await jt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=si(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,o={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await jt(st(this.memoryDir,n),o),e.manifest.checkpoint={file:n,sequence:o.sequence,hash:t},await jt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:o.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Wt(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let o=n.report.headSequence+1,r={storageVersion:1,sequence:o,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Dr(r)},d=jc(n.bundle,e,t.committedAt),c=Rt(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(o).padStart(12,"0")}-${t.transactionId}.json`;return await jt(st(this.journalDir,l),s),n.manifest.head={sequence:o,hash:s.hash},n.manifest.updatedAt=t.committedAt,await jt(this.manifestPath,n.manifest),{bundle:d,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:o,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...Rc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await ri(this.manifestPath),t=await ri(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!==si(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await Pc(this.journalDir),o=n.filter(T=>T.endsWith(".tmp")),s=n.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>t.sequence),d=structuredClone(t.bundle),c=t.sequence,l=t.journalHash??null,w=new Set;for(let T of s){let R=await ri(st(this.journalDir,T)),{hash:x,...f}=R;if(x!==Dr(f))throw new Error(`Journal hash mismatch: ${T}`);if(R.sequence!==c+1)throw new Error(`Journal sequence gap at ${T}`);if(R.previousHash!==l)throw new Error(`Journal chain mismatch at ${T}`);if(R.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(w.has(R.transactionId))throw new Error(`Duplicate transaction ID: ${R.transactionId}`);Nr(d,R.mutation,R.committedAt),c=R.sequence,l=R.hash,w.add(R.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let k=Rt(d);if(!k.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(k.issues)}`);return{bundle:d,manifest:e,transactionIds:w,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:o.length,headSequence:c,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Or(this.memoryDir,{recursive:!0});let t;try{t=await po(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let o=await ri(this.lockPath).catch(()=>({})),r=!0;if(typeof o.pid=="number")try{process.kill(o.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await mo(this.lockPath),t=await po(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await mo(this.lockPath).catch(()=>{})}}};import{randomBytes as Ac}from"crypto";function xe(i=Date.now()){let t=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),n=Ac(10).toString("hex"),o=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${o}${n.slice(4,7)}-${n.slice(7,19)}`}var Mc=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Jr(i,e){let t=i.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),n=i.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let o=i.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=Mc(),l=c.records,w=i.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));w||(w={id:le(o,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let k=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let M=i.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===u&&m.status==="current"));M||(M={id:le(o,"live-subject",u,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(o,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),k.push(M)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=i.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===u&&m.status==="current"));M||(M={id:le(o,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(o,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),k.push(M)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),R;if(T.length>0){R=le(o,"live-observation",r,e.createdAt);let u={id:R,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:k.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let x=le(o,"live-iteration",r,e.completedAt),f={id:x,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...R?[{kind:"record",id:R}]:[]],recordType:"iteration",threadIds:[w.id],startedAt:s,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};l.push(f);let p=[],g=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),v=k.length>0?k:i.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(T.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,M]of T.entries()){let h=le(o,"live-proposal",`${r}:${u}`,e.completedAt),m=v.map(D=>({subjectId:D.id,role:"governed"})),E={id:h,schemaVersion:1,projectId:i.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:x},{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:x,inferredById:n.id}};l.push(E),p.push(h)}if(g.length>0){let u=new Set(e.governingDecisionIds??[]),M=i.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&u.has(m.id)),h={id:le(o,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:x}],recordType:"implementation_attempt",state:"completed",iterationIds:[x],coverageClaims:M.map(m=>({decisionId:m.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${g.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:x}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};l.push(h)}return{mutation:c,iterationId:x,proposalIds:p,observationId:R}}import{createHash as Ec}from"crypto";import{mkdir as _c,open as Cc,readFile as $c,rename as Oc,unlink as Dc}from"fs/promises";import{join as Br}from"path";function Lr(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qr(i){return Ec("sha256").update(JSON.stringify(i)).digest("hex")}async function Nc(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await Cc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
167
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await Oc(t,i)}catch(o){throw await Dc(t).catch(()=>{}),o}}function Jc(i,e,t=new Date().toISOString()){let n={},o={},r={},s=(c,l,w)=>{let k=c[l]??=[];k.includes(w)||k.push(w)};for(let c of i.records)if(c.recordType==="subject"){let l=c;for(let w of[l.label,...l.aliases,...l.locators.filter(k=>k.status==="current").map(k=>k.value)]){let k=Lr(w);k&&s(n,k,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)s(o,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)s(r,l.subjectId,c.id);let d={version:1,projectId:i.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:o,proposalIdsBySubject:r};return{...d,checksum:qr(d)}}function Fr(i,e){let t=[...new Set(e.flatMap(n=>i.subjectIdsByValue[Lr(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>i.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>i.proposalIdsBySubject[n]??[]))]}}var di=class{constructor(e){this.indexDir=Br(e,".popmelt","memory","indexes"),this.indexPath=Br(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let o=JSON.parse(await $c(this.indexPath,"utf8")),{checksum:r,...s}=o;if(o.version===1&&o.projectId===e.manifest.projectId&&o.journalHead.sequence===t.sequence&&o.journalHead.hash===t.hash&&r===qr(s))return o}catch(o){if(o.code!=="ENOENT"&&!(o instanceof SyntaxError))throw o}let n=Jc(e,t);return await _c(this.indexDir,{recursive:!0}),await Nc(this.indexPath,n),n}};var vn="popmelt:imprint",Wr="popmelt:imprint-evidence",Vt="popmelt:imprint-relation";function ci(i){return i.sourceRefs.find(e=>e.kind==="external"&&e.uri===vn)?.id}function fo(i){let e=new Set;return i.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function li(i,e){if(!i)return[];let t=new Set(i.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return i.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(i){if(i==="expresses")return"expresses";if(i==="excepts")return"excepts"}var pi=class{constructor(e){this.projectRoot=e;this.store=new ai(e),this.indexStore=new di(e),this.manifestPath=Gt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await In(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let o=await this.store.load();return o.report.recoveredTransactions>0&&(o=await this.store.recover()),await this.refreshIndex(o),await this.status()}let n=await yn({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(o=>o.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(o){if(!(o instanceof Error)||!o.message.includes("already initialized"))throw o}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await yn({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Gt(this.projectRoot,".popmelt","memory","migrations"),t=Gt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await In(t,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let n;try{n=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await Ur(e,{recursive:!0}),await zr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let o=await this.store.load(),r=o.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),d=o.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,c=o.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!d||!c)return{migrated:!1,explanations:0,evidence:0};let l=o.bundle.manifest.projectId,w=new Set(o.bundle.records.map(u=>u.id)),k=new Set(o.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Vt?[M.id]:[]))),T=new Map,R=o.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of n.explanations){let M=R.find(h=>ci(h)===u.id);T.set(u.id,M?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let x=[],f=[],p=[],g=0;for(let u of n.explanations){let M=T.get(u.id),h=R.find(S=>S.id===M),m=[],E=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let S of E){let C=le(l,"imprint-evidence-record",S.id,Date.parse(S.createdAt));m.push(C),!w.has(C)&&(x.push({id:C,schemaVersion:1,projectId:l,createdAt:S.createdAt,participantId:d.id,sourceRefs:fo([{kind:"external",id:S.id,uri:Wr},{kind:"external",id:u.id,uri:vn},{kind:"thread",id:S.threadId},{kind:"message",id:S.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(S.kind)?"user_feedback":"judgment",summary:S.summary,availability:"available",artifactIds:[]}),p.push({id:le(l,"imprint-evidence-link",`${u.id}:${S.id}`,Date.parse(S.createdAt)),schemaVersion:1,projectId:l,createdAt:S.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:S.id,uri:Wr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"evidence",entityId:C},reason:"This advisory explanation was derived from collaboration evidence."}),g+=1)}let D={id:M,schemaVersion:1,projectId:l,createdAt:h?.createdAt??u.createdAt,participantId:h?.participantId??d.id,sourceRefs:fo([...h?.sourceRefs??[],{kind:"external",id:u.id,uri:vn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[c.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:li(n,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};h?f.push(D):x.push(D)}for(let u of n.relations){let M=ho(u.type);if(!M)continue;let h=T.get(u.fromId),m=T.get(u.toId);!h||!m||k.has(u.id)||p.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:u.id,uri:Vt}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:h},to:{entityType:"advisory_explanation",entityId:m},reason:u.rationale||"The Imprint graph connected these explanations."})}let v=new Date().toISOString();if(x.length||f.length||p.length)try{let u=await this.store.commit({records:x,recordReplacements:f,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:v});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Ur(e,{recursive:!0}),await zr(t,JSON.stringify({version:2,migratedAt:v,explanations:n.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:g}}async review(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,selection:so(n.bundle,o)}}async contextualize(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:_r(n.bundle,o),reviewSelection:so(n.bundle,o)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:oi(n.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let t=await yn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),o=oi(n.bundle,e);if(!o.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(o.errors)}`);let r=await this.store.commitReviewPlan(o.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),o=t.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!n||n.state!=="pending"||!o)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),d={proposalId:n.id,participantId:o.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},c=e.action==="accept"?{...d,action:"accept",eventId:xe(r),decisionId:xe(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:xe(r),replacementProposalId:xe(r),acceptanceEventId:xe(r),decisionId:xe(r),relationshipId:xe(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:xe(r),reason:e.reason}:{...d,action:"defer",eventId:xe(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=oi(t.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(T=>T.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:xe(r),committedAt:s});await this.refreshIndex(w);let k=l.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:k,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:w.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=Jr(t.bundle,e),o=le(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:o,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),o=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active"),r=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="ai"&&v.status==="active"),s=e.action?o:r??o,d=n.bundle.records.find(v=>v.recordType==="subject"&&v.subjectType==="project");if(!s||!d)return;let c=e.occurredAt??new Date().toISOString(),l=Date.parse(c),w=n.bundle.manifest.projectId,k=[],T=[],R=[],x=n.bundle.records.filter(v=>v.recordType==="advisory_explanation"),f=new Map(x.flatMap(v=>{let u=ci(v);return u?[[u,v.id]]:[]}));for(let v of e.summary.changes)if(!f.has(v.explanationId)){let u=t?.explanations.find(M=>M.id===v.explanationId);f.set(v.explanationId,le(w,"imprint-explanation",v.explanationId,Date.parse(u?.createdAt??c)))}for(let v of e.summary.changes){let u={kind:"external",id:v.explanationId,uri:vn},M=f.get(v.explanationId),h=x.find(S=>S.id===M),m=t?.explanations.find(S=>S.id===v.explanationId),E={id:le(w,"imprint-live-evidence",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};k.push(E);let D={id:M,schemaVersion:1,projectId:w,createdAt:h?.createdAt??m?.createdAt??c,participantId:h?.participantId??s.id,sourceRefs:fo([...h?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??h?.kind??"pattern",state:m?.state??v.state,statement:m?.statement??v.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],E.id])],concreteBindings:m?li(t,v.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?f.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??c};h?T.push(D):k.push(D),R.push({id:le(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.id},to:{entityType:"evidence",entityId:E.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(n.bundle.relationships.flatMap(v=>v.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Vt?[u.id]:[])));for(let v of t?.relations??[]){let u=ho(v.type);if(!u)continue;let M=f.get(v.fromId),h=f.get(v.toId);!M||!h||p.has(v.id)||R.push({id:le(w,"imprint-relation",v.id,Date.parse(v.createdAt)),schemaVersion:1,projectId:w,createdAt:v.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:v.id,uri:Vt}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:h},reason:v.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let v=await this.store.commit({records:k,recordReplacements:T,events:[],relationships:R,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});await this.refreshIndex(v)}catch(v){if(!(v instanceof Error)||!v.message.includes("Transaction already exists"))throw v}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let d=t.bundle.manifest.projectId,c=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(c.flatMap(m=>{let E=ci(m);return E?[[E,m]]:[]})),w=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(d,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),k=[],T=[],R=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=l.get(m.id);if(!E){k.push({id:w.get(m.id),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:vn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:li(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(E),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:li(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt},S=C=>JSON.stringify({kind:C.kind,state:C.state,statement:C.statement,rationale:C.rationale,scope:C.scope,concreteBindings:C.concreteBindings,supersededById:C.supersededById,updatedAt:C.updatedAt});S(E)!==S(D)&&T.push(D)}for(let[m,E]of l)R.has(m)||E.state==="retired"||T.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let x=new Set(t.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),f=new Map(t.bundle.relationships.flatMap(m=>{if(x.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Vt)?.id;return E?[[E,m]]:[]})),p=[],g=new Set;for(let m of e.relations){let E=ho(m.type);if(!E)continue;let D=w.get(m.fromId),S=w.get(m.toId);if(!D||!S)continue;let C=f.get(m.id);C&&C.relationshipType===E&&C.from.entityType==="advisory_explanation"&&C.from.entityId===D&&C.to.entityType==="advisory_explanation"&&C.to.entityId===S||(C&&g.add(m.id),p.push({id:le(d,"imprint-relation",`${m.id}:${E}:${D}:${S}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:Vt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:S},reason:m.rationale||"The Imprint graph connected these explanations."}))}let v=new Set(e.relations.map(m=>m.id)),u=n?[...f].filter(([m])=>!v.has(m)||g.has(m)).map(([,m])=>({id:le(d,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:d,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!k.length&&!T.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let M=e.updatedAt,h=le(d,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:k,recordReplacements:T,events:[],relationships:p,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:h,committedAt:M});return await this.refreshIndex(m),{status:"synced",relationships:p.length+u.length,explanations:k.length+T.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 o of t.bundle.records)n[o.recordType]=(n[o.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(o=>o.recordType==="freshness_signal"&&o.state==="open").length,unavailableEvidence:t.bundle.records.filter(o=>o.recordType==="evidence"&&o.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),o=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!o.has(s.id)&&!r.has(s.id)).sort((s,d)=>d.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(o=>o.recordType==="decision"&&o.state==="active"?[o.id]:[])),n=new Map;for(let o of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))o.decisionIds.some(r=>t.has(r))&&n.set(o.key,o);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 o=await this.store.load(),r=o.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(r.map(p=>[p.id,p])),d=new Map(r.flatMap(p=>{let g=ci(p);return g?[[g,p.id]]:[]})),c=new Set(e.map(p=>d.get(p)??p)),l=new Map(o.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),w=new Map(o.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),k=new Set(o.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),T=new Set(["expresses","operationalizes","excepts"]),R={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=r.map(p=>{let g=p.evidenceIds.flatMap(h=>{let m=w.get(h);if(!m)return[];let E=m.sourceRefs.find(z=>z.kind==="thread")?.id,D=m.sourceRefs.find(z=>z.kind==="message")?.id,S=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",C=l.get(m.participantId)??"unknown";return[{id:m.id,kind:S,summary:m.summary,createdAt:m.createdAt,participantKind:C,threadId:E,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),v=o.bundle.relationships.flatMap(h=>{if(k.has(h.id))return[];if(!T.has(h.relationshipType))return[];let m=h.from.entityType==="advisory_explanation"&&h.from.entityId===p.id&&h.to.entityType==="advisory_explanation",E=h.to.entityType==="advisory_explanation"&&h.to.entityId===p.id&&h.from.entityType==="advisory_explanation";if(!m&&!E)return[];let D=m?h.to.entityId:h.from.entityId,S=s.get(D);return S?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:S.id,statement:S.statement,rationale:h.reason}]:[]}),u=[...(p.supersededById?[p.supersededById]:[]).flatMap(h=>{let m=s.get(h);return m?[{id:`supersedes:${p.id}:${m.id}`,type:"supersedes",direction:"incoming",explanationId:m.id,statement:m.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(h=>h.supersededById===p.id?[{id:`supersedes:${h.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:h.id,statement:h.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],M=[...new Set([...p.sourceRefs.flatMap(h=>h.kind==="thread"?[h.id]:[]),...g.flatMap(h=>h.threadId?[h.threadId]:[])])].filter(h=>!t||t.has(h));return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:g.length,recentEvidence:g.slice(0,4),concrete:p.concreteBindings.map(h=>({...structuredClone(h)})),relations:[...v,...u],sourceThreadIds:M,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,g)=>Number(g.needsGrounding)-Number(p.needsGrounding)||R[p.state]-R[g.state]||g.updatedAt.localeCompare(p.updatedAt)),f={total:x.filter(p=>p.state!=="retired").length,emerging:x.filter(p=>p.state==="emerging").length,testing:x.filter(p=>p.state==="testing").length,grounded:x.filter(p=>p.state==="grounded").length,challenged:x.filter(p=>p.state==="challenged").length,retired:x.filter(p=>p.state==="retired").length,needsGrounding:x.filter(p=>p.needsGrounding).length};return{head:{sequence:o.report.headSequence,updatedAt:o.bundle.manifest.updatedAt},counts:f,explanations:x}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),n=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>t.has(c))&&n.set(d.key,d);let o=[...n.values()],r=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=r.filter(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===d.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:o.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:o.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),n=t.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active"),o=t.bundle.records.find(S=>S.recordType==="subject"&&S.subjectType==="project");if(!n||!o)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),d=xe(r),c=xe(r),l=xe(r),w=xe(r),k=xe(r),T=new Set(t.bundle.records.flatMap(S=>S.recordType==="model_entry"&&S.key===e.key?S.decisionIds:[])),R=t.bundle.records.filter(S=>S.recordType==="decision"&&S.state==="active"&&T.has(S.id)),x={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:o.id,role:"governed"}],p={...x,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},g={...x,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...x,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},u={...x,id:w,recordType:"model_entry",key:e.key,subjectIds:[o.id],decisionIds:[l],value:e.value},M={...x,id:k,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},h={...x,id:xe(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},m=R.map(S=>({...x,id:xe(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:S.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=R.map(S=>({...x,id:xe(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:S.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[p,v,u,M],events:[g,...m],relationships:[h,...E],artifacts:[],tombstones:[],projectionUpdates:R.map(S=>({entityType:"decision",entityId:S.id,fromState:"active",state:"superseded"}))},{transactionId:xe(r),committedAt:s});return await this.refreshIndex(D),{decisionId:l,entryId:w}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Map(t.records.flatMap(o=>o.recordType==="subject"?[[o.id,o.label]]:[]));return t.records.filter(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.kind==="thread"&&r.id===e)).sort((o,r)=>o.createdAt.localeCompare(r.createdAt)).map(o=>({proposalId:o.id,claim:o.claim,rationale:o.rationale,proposedKind:o.proposedKind,subjectLabels:o.subjects.flatMap(r=>{let s=n.get(r.subjectId);return s?[s]:[]})}))}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),n=t.bundle.records.find(x=>x.recordType==="model_projection"&&x.state==="applied"&&x.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let o=t.bundle.records.filter(x=>x.recordType==="decision"&&e.decisionIds.includes(x.id)&&x.state==="active");if(o.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),d=new Date(s).toISOString(),c=xe(s),l=e.changes.map(x=>{let f=x.decisionIds?.filter(v=>e.decisionIds.includes(v)),p=f?.length?f:e.decisionIds,g=[...new Set(o.filter(v=>p.includes(v.id)).flatMap(v=>v.subjects.map(u=>u.subjectId)))];return{id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:p.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:x.path.map(String).join("."),subjectIds:g,decisionIds:p,value:x.value}}),w=new Set(l.flatMap(x=>x.decisionIds)),k={id:c,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:e.decisionIds.map(x=>({kind:"record",id:x})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(x=>x.id),coverage:e.decisionIds.map(x=>e.coverage?.find(f=>f.decisionId===x)??{decisionId:x,status:w.has(x)?"projected":"unprojected"})},T=l.flatMap(x=>x.decisionIds.map(f=>({id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:[{kind:"record",id:k.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),R=await this.store.commit({records:[...l,k],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:xe(s),committedAt:d});return await this.refreshIndex(R),{projectionId:c,entryIds:l.map(x=>x.id),headSequence:R.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await yn({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),o=Fr(n,t.subjectHints??[]);return o?{...t,subjectIds:[...new Set([...t.subjectIds??[],...o.subjectIds])],candidateDecisionIds:o.decisionIds,candidateProposalIds:o.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Qt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function Pe(i,e){if(typeof i!="string"||!i.trim())throw new Error(`${e} must be a non-empty string.`);return i}function Kt(i,e,t){let n=Pe(i,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function go(i){let e=Qt(i),t=Qt(e.authority),n=t.level,o=t.mode,r=Kt(n,"authority.level",["owner","delegate","contributor"]),s=Kt(o,"authority.mode",["local_trusted","hosted"]),d={proposalId:Pe(e.proposalId,"proposalId"),participantId:Pe(e.participantId,"participantId"),occurredAt:Pe(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Pe(e.eventId,"eventId"),decisionId:Pe(e.decisionId,"decisionId"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Pe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Pe(e.eventId,"eventId"),reason:Pe(e.reason,"reason")};case"defer":{let c=Qt(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Pe(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Pe(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>Kt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Pe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Pe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Pe(e.acceptanceEventId,"acceptanceEventId"),decisionId:Pe(e.decisionId,"decisionId"),relationshipId:Pe(e.relationshipId,"relationshipId"),claim:Pe(e.claim,"claim"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Qt(c);return{subjectId:Pe(l.subjectId,"subjectId"),role:Kt(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Pe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function yo(i){let e=Qt(i),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(d=>Pe(d,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},o=e.resurface===void 0?void 0:Qt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:o?{differentAction:o.differentAction===!0,newEvidence:o.newEvidence===!0,newConflict:o.newConflict===!0,ownerRequested:o.ownerRequested===!0}:void 0}}function Hr(i){let e=i.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,o=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!o||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(d=>typeof d=="string"&&r.has(d)):void 0;return{proposalId:t.proposalId,action:n,kind:o,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function Gr(i){let e=i.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 Io(i){let t=(i.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],o=await Bc(i),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),d,c,l,w,k,T,R,x,f,p,g,v,u,M,h=[],m=[],E=0,D=[];for(;E<o.length;){let S=o.indexOf(r,E);if(S===-1)break;let C=S+r.length;if(o.slice(S,S+s.length).equals(s))break;let z=C;o[z]===13&&o[z+1]===10&&(z+=2);let X=o.indexOf(`\r
|
|
167
|
+
`;function ni(i){try{let e=new URL(i);return e.hash="",e.href}catch{return null}}function Vd(i,e){let t=ni(e);if(!t)return null;let n=new URL(t),o=i.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&ni(s.url)),r=o.find(s=>ni(s.url)===t);return r||(o.find(s=>{let d=new URL(ni(s.url));return d.origin===n.origin&&d.pathname===n.pathname})??null)}function Kd(i){let e={x:Number(i.x),y:Number(i.y),width:Number(i.width),height:Number(i.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 Qd(i){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",i).href,o=await fetch(n,{signal:e.signal});if(!o.ok)throw new Error(`CDP discovery returned ${o.status}`);let r=await o.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Xd(i){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let o=new e(i,{handshakeTimeout:1e3}),r=()=>{o.off("error",s),t(o)},s=d=>{o.off("open",r),n(d)};o.once("open",r),o.once("error",s)})}function Yd(i){let e=1,t=new Map;return i.on("message",n=>{let o;try{o=JSON.parse(String(n))}catch{return}if(!o.id)return;let r=t.get(o.id);r&&(t.delete(o.id),clearTimeout(r.timeout),o.error?r.reject(new Error(o.error.message||`CDP error ${o.error.code??""}`.trim())):r.resolve(o.result??{}))}),i.on("close",()=>{for(let[n,o]of t)clearTimeout(o.timeout),o.reject(new Error("CDP connection closed")),t.delete(n)}),(n,o={})=>new Promise((r,s)=>{let d=e++,c=setTimeout(()=>{t.delete(d),s(new Error(`CDP ${n} timed out`))},4e3);t.set(d,{resolve:r,reject:s,timeout:c}),i.send(JSON.stringify({id:d,method:n,params:o}),l=>{l&&(clearTimeout(c),t.delete(d),s(l))})})}async function Mr(i,e){let t=Kd(e.clip),n=await Qd(i),o=Vd(n,e.pageUrl);if(!o?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Xd(o.webSocketDebuggerUrl),s=Yd(r),d=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Hd,returnByValue:!0}),d=!0;let c=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof c.data=="string"?c.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{d&&await s("Runtime.evaluate",{expression:Gd,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as zr,readFile as In,writeFile as Wr}from"fs/promises";import{join as Gt}from"path";var Zd=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function so(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ii(i){return new Set(so(i).split(" ").filter(e=>e.length>2&&!Zd.has(e)))}function Er(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function ec(i){return[{value:i.label,by:"label"},...i.aliases.map(e=>({value:e,by:"alias"})),...i.locators.map(e=>({value:e.value,by:"locator"}))]}function tc(i,e){let t=new Map,n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(so).filter(Boolean),r=ii([e.action,e.text].filter(Boolean).join(" "));for(let s of i){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let d;for(let c of ec(s)){let l=so(c.value);for(let b of o){let k=l===b?95:l.includes(b)||b.includes(l)?75:0;k>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:c.by,score:k})}let R=["/","#","[","]","="].some(b=>c.value.includes(b))?0:Math.round(Er(ii(l),r)*55);R>=30&&R>(d?.score??0)&&(d={subjectId:s.id,label:s.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}d&&t.set(s.id,d)}return t}function nc(i,e){let t=new Set(i.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(i.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),o=e.filter(s=>s.iterationIds.some(d=>t.has(d))||s.sourceRefs.some(d=>d.kind==="thread"&&n.has(d.id)));if(!o.length)return{state:"none_found",attemptIds:[]};let r=new Set(o.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:o.map(s=>s.id)}}function ic(i){return Math.ceil(JSON.stringify(i).length/4)}function ao(i,e){let t=i.records.filter(p=>p.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),o=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=i.records.filter(p=>{if(p.recordType!=="proposal"||o&&!o.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let g=[...i.events].reverse().find(v=>v.entity.entityType==="proposal"&&v.entity.entityId===p.id&&v.toState==="deferred"&&v.transitionContext?.kind==="proposal_deferral")?.transitionContext;return g?g.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||g.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||g.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||g.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||g.resurfaceWhen.includes("after_date")&&!!(g.revisitAfter&&Date.parse(n)>=Date.parse(g.revisitAfter)):!1}),s=i.records.filter(p=>p.recordType==="implementation_attempt"),d=tc(t,e),c=[...d.values()].sort((p,g)=>g.score-p.score),l=ii([e.action,e.text].filter(Boolean).join(" ")),w=r.flatMap(p=>{let g=p.subjects.map(h=>d.get(h.subjectId)).filter(h=>!!h),v=Math.max(0,...g.map(h=>h.score)),u=Math.round(Er(ii(p.claim),l)*35),M=v+u;return M>=50?[{proposal:p,proposalMatches:g,score:M}]:[]}).sort((p,g)=>g.score-p.score||p.proposal.id.localeCompare(g.proposal.id)),R=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),k=[],S=0;for(let p of w){if(k.length>=R)break;let g=p.proposal.sourceRefs.slice(0,4),v={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:i.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(M=>M.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:M,...h})=>h)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(M=>M.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:nc(p.proposal,s),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:g},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...g]},u={...v,estimatedTokens:ic(v)};if(S+u.estimatedTokens>b)break;k.push(u),S+=u.estimatedTokens}let f=Math.max(0,w.length-k.length);return{packets:k,subjectMatches:c.map(({score:p,...g})=>g),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:f,maxEstimatedTokens:b,estimatedTokens:S},uncertainty:d.size===0?"subject_unresolved":w.length===0?"no_relevant_pending_proposal":void 0}}var oc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function co(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function oi(i){return new Set(co(i).split(" ").filter(e=>e.length>2&&!oc.has(e)))}function _r(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function rc(i,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(co).filter(Boolean),o=oi([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of i){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let d,c=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of c){let w=co(l.value);for(let k of n){let S=w===k?95:w.includes(k)||k.includes(w)?75:0;S>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:l.by,score:S})}let b=["/","#","[","]","="].some(k=>l.value.includes(k))?0:Math.round(_r(oi(w),o)*55);b>=30&&b>(d?.score??0)&&(d={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}d&&r.push(d)}return r.sort((s,d)=>d.score-s.score||s.subjectId.localeCompare(d.subjectId))}function sc(i){return Math.ceil(JSON.stringify(i).length/4)}function zt(i,e){return i.relationshipType===e&&i.from.entityType==="decision"&&i.to.entityType==="decision"}function ac(i,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===i));if(!t.length)return{decisionId:i,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),o=n.some(r=>r.coverageClaims.some(s=>s.decisionId===i&&s.coverage==="full"));return{decisionId:i,state:o?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function dc(i,e,t){let n=e.filter(d=>d.targets.some(c=>c.entityType==="decision"&&c.entityId===i)).sort((d,c)=>c.createdAt.localeCompare(d.createdAt)),o=t.some(d=>d.signalType==="verification_expired"&&d.target.entityType==="decision"&&d.target.entityId===i),r=n[0],s=o?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:i},state:s,attemptIds:n.map(d=>d.id)}}function Cr(i,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),o=i.records.filter(m=>m.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=i.records.filter(m=>m.recordType==="decision"&&m.state==="active"),d=r?s.filter(m=>r.has(m.id)):s,c=i.records.filter(m=>m.recordType==="implementation_attempt"),l=i.records.filter(m=>m.recordType==="verification_attempt"),w=i.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),R=i.records.filter(m=>m.recordType==="evidence"),b=i.records.filter(m=>m.recordType==="model_entry"),k=rc(o,e),S=new Map(k.map(m=>[m.subjectId,m.score])),f=oi([e.action,e.text].filter(Boolean).join(" ")),p=d.flatMap(m=>{let E=Math.max(0,...m.subjects.map(C=>S.get(C.subjectId)??0)),D=Math.round(_r(oi(m.claim),f)*35),T=E+D;return T>=50?[{decision:m,score:T}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of p.slice(0,n))g.set(m.decision.id,m.decision);for(let m of i.relationships){if(!zt(m,"excepts")&&!zt(m,"contradicts"))continue;let E=s.find(T=>T.id===m.from.entityId),D=s.find(T=>T.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<n&&g.set(E.id,E),g.size<n&&g.set(D.id,D))}let v=[...g.values()],u=m=>m.from.entityType==="decision"&&m.to.entityType==="decision"&&g.has(m.from.entityId)&&g.has(m.to.entityId),M=(m,E=!1)=>{let D=new Set(m.map(B=>B.id)),T=w.filter(B=>B.target.entityType==="decision"&&D.has(B.target.entityId)),C=new Set(i.relationships.filter(B=>zt(B,"excepts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),X=i.relationships.filter(B=>zt(B,"contradicts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).map(B=>({id:B.id,decisionIds:[B.from.entityId,B.to.entityId],unresolvedQuestion:B.reason,expansionRefs:[{kind:"record",id:B.id}]})),G=new Set(X.flatMap(B=>B.decisionIds)),Y=R.filter(B=>B.sourceRefs.some(V=>V.kind==="record"&&D.has(V.id))||i.relationships.some(V=>V.relationshipType==="supports"&&V.from.entityType==="evidence"&&V.from.entityId===B.id&&V.to.entityType==="decision"&&D.has(V.to.entityId))),x=Math.max(0,p.length-m.length),Q=i.relationships.some(B=>zt(B,"contradicts")&&u(B)&&(!D.has(B.from.entityId)||!D.has(B.to.entityId))),L=E||x>0||Q,K=[];k.length===0&&(e.subjectHints?.length??0)>0?K.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):m.length===0&&K.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),X.length&&K.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:X.flatMap(B=>B.expansionRefs)}),Y.some(B=>B.availability!=="available")&&K.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Y.map(B=>({kind:"record",id:B.id}))}),L&&K.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:i.manifest.projectId}]});let H={contractVersion:1,projectId:i.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:k.map(({score:B,...V})=>V),modelEntries:b.filter(B=>B.decisionIds.some(V=>D.has(V))).map(B=>({id:B.id,key:B.key,value:B.value,decisionIds:B.decisionIds})),decisions:m.map(B=>({id:B.id,kind:B.kind,claim:B.claim,subjectIds:B.subjects.map(V=>V.subjectId),authority:B.authority,effectiveState:G.has(B.id)?"conflicted":C.has(B.id)?"excepted":"active",freshness:T.filter(V=>V.target.entityId===B.id).map(V=>V.signalType),expansionRef:{kind:"record",id:B.id}})),conflicts:X,uncertainties:K,implementation:m.map(B=>ac(B.id,c)),verification:m.map(B=>dc(B.id,l,T)),evidence:Y.map(B=>({evidenceId:B.id,summary:B.summary,availability:B.availability,sourceRefs:B.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:x,omittedEvidenceCount:0,conflictsComplete:!Q}};return H.budget.estimatedTokens=sc(H),H},h=M(v);for(;h.budget.estimatedTokens>t&&v.length>0;){let m=v.pop(),E=i.relationships.filter(D=>zt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);v=v.filter(D=>!E.includes(D.id)),h=M(v,!0)}return h}var cc=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Wt(i){return cc.test(i)}function lc(i){return{valid:!i.some(e=>e.severity==="error"),issues:i}}function ie(i,e,t,n){i.push({path:e,code:t,message:n,severity:"error"})}function lo(i,e,t,n){i.push({path:e,code:t,message:n,severity:"warning"})}function Me(i,e,t){Wt(t)||ie(i,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(i,e,t){(!t||Number.isNaN(Date.parse(t)))&&ie(i,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function kt(i,e,t,n=!1){n&&t.level==="contributor"&&ie(i,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&ie(i,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var pc={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"])},uc=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function mc(i,e,t){Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Me(i,`${t}.entity.entityId`,e.entity.entityId),Qe(i,`${t}.createdAt`,e.createdAt),kt(i,`${t}.authority`,e.authority);let n=pc[e.entity.entityType],o=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(o)&&ie(i,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${o}.`);let r=`${e.entity.entityType}:${e.toState}`;if(uc.has(r)&&(kt(i,`${t}.authority`,e.authority,!0),e.reason?.trim()||ie(i,`${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)&&ie(i,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&ie(i,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(i,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function fc(i,e,t,n){Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Qe(i,`${t}.createdAt`,e.createdAt),e.projectId!==n&&ie(i,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&ie(i,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&ie(i,`${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)&&ie(i,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(kt(i,`${t}.authority`,e.authority,!0),e.claim.trim()||ie(i,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&lo(i,`${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())&&ie(i,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(i,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&ie(i,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(o=>!o.trim())&&ie(i,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((o,r)=>{(!o.id.trim()||!o.modelPath.trim())&&ie(i,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(i,`${t}.concreteBindings[${r}].createdAt`,o.createdAt),Qe(i,`${t}.concreteBindings[${r}].updatedAt`,o.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&ie(i,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(i,`${t}.appliedAt`,e.appliedAt),kt(i,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&ie(i,`${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())&&ie(i,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(o=>!o.trim()))&&ie(i,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&lo(i,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&lo(i,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function hc(i,e,t){if(Me(i,`${t}.id`,e.id),Me(i,`${t}.projectId`,e.projectId),Me(i,`${t}.participantId`,e.participantId),Me(i,`${t}.from.entityId`,e.from.entityId),Me(i,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&ie(i,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&ie(i,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),Qe(i,`${t}.createdAt`,e.createdAt),e.reason.trim()||ie(i,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let o=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!o&&!r&&ie(i,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),o&&!e.authority?ie(i,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):o&&e.authority&&kt(i,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&ie(i,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&ie(i,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))&&ie(i,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&ie(i,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Rt(i){let e=[];Me(e,"manifest.projectId",i.manifest.projectId),Qe(e,"manifest.createdAt",i.manifest.createdAt),Qe(e,"manifest.updatedAt",i.manifest.updatedAt);let t=new Map,n=(f,p)=>{let g=t.get(f);g?ie(e,p,"duplicate_id",`ID is already used at ${g}.`):t.set(f,p)};i.records.forEach((f,p)=>{let g=`records[${p}]`;n(f.id,g),fc(e,f,g,i.manifest.projectId)}),i.events.forEach((f,p)=>{let g=`events[${p}]`;n(f.id,g),mc(e,f,g),f.projectId!==i.manifest.projectId&&ie(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),i.relationships.forEach((f,p)=>{let g=`relationships[${p}]`;n(f.id,g),hc(e,f,g),f.projectId!==i.manifest.projectId&&ie(e,`${g}.projectId`,"project_mismatch","Relationship belongs to another project.")}),i.artifacts.forEach((f,p)=>{n(f.id,`artifacts[${p}]`),Me(e,`artifacts[${p}].id`,f.id)}),i.tombstones.forEach((f,p)=>{let g=`tombstones[${p}]`;n(f.id,g),Me(e,`${g}.id`,f.id),Me(e,`${g}.objectId`,f.objectId),Me(e,`${g}.deletedById`,f.deletedById),Qe(e,`${g}.deletedAt`,f.deletedAt),kt(e,`${g}.authority`,f.authority,!0)});let o=new Set(i.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(i.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{if(f.storeId)return;let g=`${f.entityType}:${f.entityId}`;!o.has(g)&&!r.has(g)&&ie(e,p,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};i.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),i.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let d=new Set(i.artifacts.map(f=>f.id)),c=(f,p)=>{d.has(f)||ie(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,g)=>{!o.has(`${f}:${p}`)&&!r.has(`${f}:${p}`)&&ie(e,g,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};i.records.forEach((f,p)=>{let g=`records[${p}]`;switch(f.recordType){case"authority_grant":l("participant",f.granteeId,`${g}.granteeId`),l("participant",f.grantedById,`${g}.grantedById`),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`));break;case"observation":f.captureContext.subjectIds.forEach((v,u)=>l("subject",v,`${g}.captureContext.subjectIds[${u}]`)),f.captureContext.artifactIds.forEach((v,u)=>c(v,`${g}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":f.subjects.forEach((v,u)=>l("subject",v.subjectId,`${g}.subjects[${u}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((v,u)=>c(v,`${g}.messageArtifactIds[${u}]`)),f.resultRefs.forEach((v,u)=>s(v,`${g}.resultRefs[${u}]`));break;case"iteration":f.threadIds.forEach((v,u)=>l("thread",v,`${g}.threadIds[${u}]`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"evidence":f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"advisory_explanation":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${g}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((v,u)=>l("iteration",v,`${g}.iterationIds[${u}]`)),f.coverageClaims.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverageClaims[${u}].decisionId`)),f.artifactIds.forEach((v,u)=>c(v,`${g}.artifactIds[${u}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${g}.replacesSpecId`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),(f.dependencies??[]).forEach((v,u)=>{v.kind==="subject"&&v.subjectId&&l("subject",v.subjectId,`${g}.dependencies[${u}].subjectId`)}),(f.scenarios??[]).forEach((v,u)=>{v.subjectIds?.forEach((M,h)=>l("subject",M,`${g}.scenarios[${u}].subjectIds[${h}]`))}),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${g}.evalSpecId`),f.targets.forEach((v,u)=>l(v.entityType,v.entityId,`${g}.targets[${u}]`)),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;case"model_entry":f.subjectIds.forEach((v,u)=>l("subject",v,`${g}.subjectIds[${u}]`)),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`));break;case"model_projection":kt(e,`${g}.authority`,f.authority,!0),l("participant",f.appliedById,`${g}.appliedById`),f.decisionIds.forEach((v,u)=>l("decision",v,`${g}.decisionIds[${u}]`)),f.entryIds.forEach((v,u)=>l("model_entry",v,`${g}.entryIds[${u}]`)),f.coverage.forEach((v,u)=>l("decision",v.decisionId,`${g}.coverage[${u}].decisionId`));break;case"freshness_signal":s(f.target,`${g}.target`),f.evidenceIds.forEach((v,u)=>l("evidence",v,`${g}.evidenceIds[${u}]`));break;default:break}});let w=new Map(i.events.map(f=>[f.id,f])),R=new Map(i.records.map(f=>[`${f.recordType}:${f.id}`,f])),b=new Map;i.events.forEach((f,p)=>{let g=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,v=b.get(g)??new Set;v.add(f.toState),b.set(g,v),v.size>1&&ie(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(i.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),S=(f,p,g,v,u)=>{if(f.level!=="delegate"||!f.grantId)return;let M=k.get(f.grantId);if(!M){ie(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&ie(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(g);(h<Date.parse(M.startsAt)||M.endsAt&&h>Date.parse(M.endsAt)||M.revokedAt&&h>=Date.parse(M.revokedAt))&&ie(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&v.length&&!v.every(m=>M.subjectIds.includes(m))&&ie(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of i.records)f.recordType==="decision"&&S(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);i.events.forEach((f,p)=>{let g=R.get(`${f.entity.entityType}:${f.entity.entityId}`),v=g&&"subjects"in g?g.subjects.map(u=>u.subjectId):[];S(f.authority,f.participantId,f.createdAt,v,`events[${p}].authority`)}),i.relationships.forEach((f,p)=>{if(!f.authority)return;let g=[f.from,f.to].flatMap(v=>{let u=R.get(`${v.entityType}:${v.entityId}`);return u&&"subjects"in u?u.subjects.map(M=>M.subjectId):[]});S(f.authority,f.participantId,f.createdAt,g,`relationships[${p}].authority`)});for(let f of i.records){if(f.recordType!=="decision")continue;let p=w.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&ie(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&ie(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${f.proposalId}`)||ie(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(i.relationships.some(v=>v.relationshipType==="supersedes"&&v.to.entityType==="decision"&&v.to.entityId===f.id)||ie(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(i.events.some(v=>v.entity.entityType==="decision"&&v.entity.entityId===f.id&&v.toState==="revoked"&&!!v.reason?.trim())||ie(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of i.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;i.records.some(g=>g.recordType==="decision"&&g.proposalId===f.id)||ie(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return lc(e)}function hn(i,e,t,n){return{id:n,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function $r(i,e,t,n,o){return{id:o,schemaVersion:1,projectId:i.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 gc(i){switch(i.action){case"accept":return[i.eventId,i.decisionId];case"edit_and_accept":return[i.withdrawalEventId,i.replacementProposalId,i.acceptanceEventId,i.decisionId,i.relationshipId];case"reject":case"defer":return[i.eventId]}}function ri(i,e){let t=[],n=i.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Wt(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of gc(e))Wt(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...hn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=$r(i,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...hn(i,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},d={...hn(i,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},c=$r(i,r,e,d.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,c],events:[s,d],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:c.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...hn(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let o={...hn(i,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:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}import{createHash as yc}from"crypto";import{readFile as Ic,readdir as vc,realpath as wc}from"fs/promises";import{join as gn,relative as bc}from"path";var xc=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Ht(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}function ze(i,e=0){return new Date(Number.isFinite(i)?i:e).toISOString()}function Or(...i){return i.find(e=>!!e?.trim())?.trim()}function le(i,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=yc("sha256").update(`${i}\0${e}\0${t}`).digest("hex"),d=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${d}${s.slice(4,7)}-${s.slice(7,19)}`}async function po(i,e){try{return JSON.parse(await Ic(i,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:i,message:t instanceof Error?t.message:String(t)}),null}}function Sc(i){let e=Ht(i);if(!e)return 0;let t=0,n=o=>{let r=Ht(o);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let o of Object.values(e))n(o);return t}function Tc(i){let e={};for(let t of i)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function yn(i){let e=[],t=await wc(i.projectRoot).catch(()=>i.projectRoot),n=gn(t,".popmelt"),o=await po(gn(n,"threads.json"),e),r=await po(gn(n,"model.json"),e),s=Ht(o),d=Ht(s?.threads)??{},c=Object.entries(d).map(([V,W])=>({key:V,value:Ht(W)})).filter(V=>!!V.value),l=gn(n,"decisions"),w=await vc(l).catch(()=>[]),R=[];for(let V of w.filter(W=>W.endsWith(".json")).sort()){let W=Ht(await po(gn(l,V),e));W&&R.push({file:V,value:W})}let b=c.flatMap(({value:V})=>[V.createdAt,V.updatedAt]).filter(V=>typeof V=="number"&&Number.isFinite(V)),k=b.length?Math.min(...b):0,S=i.projectKey??t;i.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let f=le(S,"project",S,k),p=le(S,"participant","legacy-owner",k),g=le(S,"participant","legacy-agent",k),v=le(S,"subject","project",k),u=ze(Math.max(k,...b)),M=[],h=[],m=new Map,E=new Map,D=new Map(R.map(V=>[V.value.id??V.file.replace(/^d-|\.json$/g,""),V.value])),T=new Map,C=(V,W,ee,ke,Je)=>{let ue=m.get(ee);if(ue)return ue;let Ce=le(S,"artifact",V,ke);return h.push({id:Ce,kind:W,mediaType:Je,location:ee,availability:"available"}),m.set(ee,Ce),Ce};for(let{file:V,value:W}of R){let ee=W.id??V.replace(/^d-|\.json$/g,""),ke=W.createdAt??k,Je=[C(`${ee}:envelope`,"other",`.popmelt/decisions/${V}`,ke,"application/json")];W.screenshotPath&&Je.push(C(`${ee}:screenshot`,"screenshot",`.popmelt/${W.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,W.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,Ce]of(W.pastedImagePaths??[]).entries())Je.push(C(`${ee}:image:${ue}`,"image",Ce,ke));T.set(ee,Je)}let z=(V,W,ee)=>({id:V,schemaVersion:1,projectId:f,createdAt:u,participantId:W,sourceRefs:ee}),X=(V,W)=>{M.push(W);let ee=E.get(V)??[];ee.push(W.id),E.set(V,ee)},G=[{...z(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...z(g,g,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];M.push(...G),M.push({...z(v,p,[]),recordType:"subject",subjectType:"project",label:bc(process.cwd(),t)||t,aliases:[],locators:[{id:le(S,"locator",t,k),kind:"project_root",value:t,status:"current",validFrom:ze(k),sourceRefs:[]}]});let Y=new Map,x=(V,W)=>{let ee=Y.get(V);if(ee)return ee;let ke=le(S,"subject",V,W),Je={...z(ke,p,[{kind:"external",id:V}]),createdAt:ze(W),recordType:"subject",subjectType:"element",label:V,aliases:[],locators:[{id:le(S,"locator",V,W),kind:"dom_selector",value:V,status:"current",validFrom:ze(W),sourceRefs:[{kind:"external",id:V}]}]};return M.push(Je),Y.set(V,ke),ke};for(let{key:V,value:W}of c){let ee=W.id??V,ke=W.createdAt??k,Je=le(S,"thread",ee,ke),ue={kind:"thread",id:ee},Ce=[],gt=[],on=Array.isArray(W.messages)?W.messages:[],Re,nt,yt=0;on.forEach((be,lt)=>{let $e=be.timestamp??ke,it=le(S,"artifact",`${ee}:message:${lt}`,$e);if(Ce.push(it),h.push({id:it,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${ee}/messages/${lt}`,it),be.screenshotPath&&C(`${ee}:message:${lt}:screenshot`,"screenshot",be.screenshotPath,$e),be.role==="human"){Re=be;let Le=be.feedbackSummary??be.replyToQuestion;if(Le?.trim()){let qe=le(S,"observation",`${ee}:${lt}`,$e),Xe=W.elementIdentifiers??[],Mt={...z(qe,p,[ue,{kind:"message",id:it}]),createdAt:ze($e),recordType:"observation",state:"open",statement:Le,captureContext:{subjectIds:Xe.map(wt=>x(wt,ke)),artifactIds:[it]},resolvedByIds:[]};X(ee,Mt),nt=qe,gt.push({entityType:"observation",entityId:qe})}return}if(be.role!=="assistant")return;let pt=be.jobId??`${ee}:${lt}`,ut=le(S,"iteration",pt,$e),vt=D.get(pt),Ei=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",_i={...z(ut,g,[ue,{kind:"message",id:it},...(T.get(pt)??[]).map(Le=>({kind:"artifact",id:Le}))]),createdAt:ze($e),recordType:"iteration",threadIds:[Je],startedAt:ze(Re?.timestamp,$e),completedAt:ze($e),requestSummary:Or(Re?.feedbackSummary,Re?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:Ei,execution:{provider:be.provider??vt?.provider,model:be.model??vt?.model,sessionId:be.sessionId??vt?.sessionId},artifactIds:[it,...T.get(pt)??[]]};X(ee,_i),gt.push({entityType:"iteration",entityId:ut});let rn=be.resolutions??vt?.resolutions??[];for(let[Le,qe]of rn.entries()){if(qe.status!=="resolved"||!qe.summary?.trim())continue;let Xe=W.elementIdentifiers??[],Mt=(Xe.length?Xe:[t]).map(_n=>({subjectId:_n===t?v:x(_n,ke),role:"governed"})),wt=le(S,"proposal",`${pt}:${qe.annotationId??"resolution"}:${Le}`,$e),Ci={...z(wt,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"proposal",state:"pending",claim:qe.summary,subjects:Mt,subjectSemantics:Mt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Or(Re?.feedbackSummary,Re?.replyToQuestion,qe.summary),iterationId:ut,inferredById:g}};X(ee,Ci),gt.push({entityType:"proposal",entityId:wt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ee,message:`Proposal ${wt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(rn.some(Le=>Le.status==="resolved")||vt?.gitDiff){let Le=le(S,"implementation",pt,$e),qe={...z(Le,g,[ue,{kind:"iteration",id:ut}]),createdAt:ze($e),recordType:"implementation_attempt",state:"completed",iterationIds:[ut],coverageClaims:[],summary:rn.map(Xe=>Xe.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};X(ee,qe),gt.push({entityType:"implementation_attempt",entityId:Le}),yt+=1}nt&&(nt=void 0)});let It=on.at(-1),En={...z(Je,p,[ue]),createdAt:ze(ke),recordType:"thread",state:It?.question?"open":"resolved",messageArtifactIds:Ce,outcome:It?.question?"question_unresolved":yt?"implementation_only":"no_outcome",resultRefs:gt};M.push(En),E.set(ee,[Je,...E.get(ee)??[]])}let Q=Sc(r);Q&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${Q} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:f,createdAt:ze(k),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:i.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:h,tombstones:[]},K=Rt(L),B=(i.proofCaseIds??xc).map(V=>({legacyId:V,threadFound:c.some(({key:W,value:ee})=>(ee.id??W)===V),decisionEnvelopeFound:D.has(V),recordIds:E.get(V)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:c.length,messages:c.reduce((V,W)=>V+(W.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:Q,artifactsReferenced:h.length},imported:Tc(M),unresolvedAcceptance:e.filter(V=>V.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:B,issues:e,schemaIssues:K.issues}}}import{createHash as Pc}from"crypto";import{mkdir as Dr,open as uo,readFile as mo,readdir as kc,rename as Rc,unlink as fo}from"fs/promises";import{join as st}from"path";var Ac={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function ai(i){return Pc("sha256").update(JSON.stringify(i)).digest("hex")}function Nr(i){return ai(i)}function Br(i,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!i.manifest.features.includes("advisory_explanations")&&i.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 o=i.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(o<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=i.records[o];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);i.records[o]=structuredClone(n)}for(let n of e.projectionUpdates){let o=i.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!o||o.recordType!=="proposal"&&o.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(o.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${o.state}`);o.state=n.state}return i.records.push(...e.records),i.events.push(...e.events),i.relationships.push(...e.relationships),i.artifacts.push(...e.artifacts),i.tombstones.push(...e.tombstones),i.manifest.updatedAt=t,i}function jc(i,e,t){return Br(structuredClone(i),e,t)}async function At(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await uo(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
168
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await Rc(t,i)}catch(o){throw await fo(t).catch(()=>{}),o}}async function si(i){return JSON.parse(await mo(i,"utf8"))}var di=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=st(e,".popmelt","memory"),this.journalDir=st(this.memoryDir,"journal"),this.manifestPath=st(this.memoryDir,"manifest.json"),this.checkpointPath=st(this.memoryDir,"checkpoint.json"),this.lockPath=st(this.memoryDir,"writer.lock")}async initialize(e){let t=Rt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Dr(this.journalDir,{recursive:!0});try{throw await mo(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 mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let n=ai(e),o={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await At(this.checkpointPath,o),await At(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await At(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=ai(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,o={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await At(st(this.memoryDir,n),o),e.manifest.checkpoint={file:n,sequence:o.sequence,hash:t},await At(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:o.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Wt(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let o=n.report.headSequence+1,r={storageVersion:1,sequence:o,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Nr(r)},d=jc(n.bundle,e,t.committedAt),c=Rt(d);if(!c.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(c.issues)}`);let l=`${String(o).padStart(12,"0")}-${t.transactionId}.json`;return await At(st(this.journalDir,l),s),n.manifest.head={sequence:o,hash:s.hash},n.manifest.updatedAt=t.committedAt,await At(this.manifestPath,n.manifest),{bundle:d,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:o,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...Ac,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await si(this.manifestPath),t=await si(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!==ai(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await kc(this.journalDir),o=n.filter(b=>b.endsWith(".tmp")),s=n.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>t.sequence),d=structuredClone(t.bundle),c=t.sequence,l=t.journalHash??null,w=new Set;for(let b of s){let k=await si(st(this.journalDir,b)),{hash:S,...f}=k;if(S!==Nr(f))throw new Error(`Journal hash mismatch: ${b}`);if(k.sequence!==c+1)throw new Error(`Journal sequence gap at ${b}`);if(k.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(w.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);Br(d,k.mutation,k.committedAt),c=k.sequence,l=k.hash,w.add(k.transactionId)}if(e.head.sequence>c)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===c&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let R=Rt(d);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:d,manifest:e,transactionIds:w,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,c-e.head.sequence),ignoredTemporaryFiles:o.length,headSequence:c,headHash:l}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Dr(this.memoryDir,{recursive:!0});let t;try{t=await uo(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let o=await si(this.lockPath).catch(()=>({})),r=!0;if(typeof o.pid=="number")try{process.kill(o.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await fo(this.lockPath),t=await uo(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await fo(this.lockPath).catch(()=>{})}}};import{randomBytes as Mc}from"crypto";function xe(i=Date.now()){let t=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),n=Mc(10).toString("hex"),o=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${o}${n.slice(4,7)}-${n.slice(7,19)}`}var Ec=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Jr(i,e){let t=i.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),n=i.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let o=i.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),d=new Date(e.completedAt).toISOString(),c=Ec(),l=c.records,w=i.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));w||(w={id:le(o,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(w));let R=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let M=i.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===u&&m.status==="current"));M||(M={id:le(o,"live-subject",u,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(o,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),R.push(M)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=i.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===u&&m.status==="current"));M||(M={id:le(o,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(o,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),R.push(M)}let b=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),k;if(b.length>0){k=le(o,"live-observation",r,e.createdAt);let u={id:k,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:R.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let S=le(o,"live-iteration",r,e.completedAt),f={id:S,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[w.id],startedAt:s,completedAt:d,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};l.push(f);let p=[],g=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),v=R.length>0?R:i.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(b.length>0&&v.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[u,M]of b.entries()){let h=le(o,"live-proposal",`${r}:${u}`,e.completedAt),m=v.map(D=>({subjectId:D.id,role:"governed"})),E={id:h,schemaVersion:1,projectId:i.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:S},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:M.claim.trim(),rationale:M.rationale?.trim()||void 0,proposedKind:M.proposedKind,subjects:m,subjectSemantics:m.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:M.sourceText?.trim()||e.requestSummary,iterationId:S,inferredById:n.id}};l.push(E),p.push(h)}if(g.length>0){let u=new Set(e.governingDecisionIds??[]),M=i.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&u.has(m.id)),h={id:le(o,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:d,participantId:n.id,sourceRefs:[{kind:"iteration",id:S}],recordType:"implementation_attempt",state:"completed",iterationIds:[S],coverageClaims:M.map(m=>({decisionId:m.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${g.map(E=>E.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:S}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};l.push(h)}return{mutation:c,iterationId:S,proposalIds:p,observationId:k}}import{createHash as _c}from"crypto";import{mkdir as Cc,open as $c,readFile as Oc,rename as Dc,unlink as Nc}from"fs/promises";import{join as Lr}from"path";function qr(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Fr(i){return _c("sha256").update(JSON.stringify(i)).digest("hex")}async function Bc(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await $c(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
169
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await Dc(t,i)}catch(o){throw await Nc(t).catch(()=>{}),o}}function Jc(i,e,t=new Date().toISOString()){let n={},o={},r={},s=(c,l,w)=>{let R=c[l]??=[];R.includes(w)||R.push(w)};for(let c of i.records)if(c.recordType==="subject"){let l=c;for(let w of[l.label,...l.aliases,...l.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=qr(w);R&&s(n,R,l.id)}}else if(c.recordType==="decision"&&c.state==="active")for(let l of c.subjects)s(o,l.subjectId,c.id);else if(c.recordType==="proposal"&&["pending","deferred"].includes(c.state))for(let l of c.subjects)s(r,l.subjectId,c.id);let d={version:1,projectId:i.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:o,proposalIdsBySubject:r};return{...d,checksum:Fr(d)}}function Ur(i,e){let t=[...new Set(e.flatMap(n=>i.subjectIdsByValue[qr(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>i.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>i.proposalIdsBySubject[n]??[]))]}}var ci=class{constructor(e){this.indexDir=Lr(e,".popmelt","memory","indexes"),this.indexPath=Lr(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let o=JSON.parse(await Oc(this.indexPath,"utf8")),{checksum:r,...s}=o;if(o.version===1&&o.projectId===e.manifest.projectId&&o.journalHead.sequence===t.sequence&&o.journalHead.hash===t.hash&&r===Fr(s))return o}catch(o){if(o.code!=="ENOENT"&&!(o instanceof SyntaxError))throw o}let n=Jc(e,t);return await Cc(this.indexDir,{recursive:!0}),await Bc(this.indexPath,n),n}};var vn="popmelt:imprint",Hr="popmelt:imprint-evidence",Vt="popmelt:imprint-relation";function li(i){return i.sourceRefs.find(e=>e.kind==="external"&&e.uri===vn)?.id}function ho(i){let e=new Set;return i.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function pi(i,e){if(!i)return[];let t=new Set(i.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return i.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 go(i){if(i==="expresses")return"expresses";if(i==="excepts")return"excepts"}var ui=class{constructor(e){this.projectRoot=e;this.store=new di(e),this.indexStore=new ci(e),this.manifestPath=Gt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await In(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let o=await this.store.load();return o.report.recoveredTransactions>0&&(o=await this.store.recover()),await this.refreshIndex(o),await this.status()}let n=await yn({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(o=>o.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(o){if(!(o instanceof Error)||!o.message.includes("already initialized"))throw o}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await yn({...e,projectRoot:this.projectRoot})).report}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=Gt(this.projectRoot,".popmelt","memory","migrations"),t=Gt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await In(t,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let n;try{n=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await zr(e,{recursive:!0}),await Wr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let o=await this.store.load(),r=o.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),d=o.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??r,c=o.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!d||!c)return{migrated:!1,explanations:0,evidence:0};let l=o.bundle.manifest.projectId,w=new Set(o.bundle.records.map(u=>u.id)),R=new Set(o.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Vt?[M.id]:[]))),b=new Map,k=o.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of n.explanations){let M=k.find(h=>li(h)===u.id);b.set(u.id,M?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let S=[],f=[],p=[],g=0;for(let u of n.explanations){let M=b.get(u.id),h=k.find(T=>T.id===M),m=[],E=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let T of E){let C=le(l,"imprint-evidence-record",T.id,Date.parse(T.createdAt));m.push(C),!w.has(C)&&(S.push({id:C,schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:d.id,sourceRefs:ho([{kind:"external",id:T.id,uri:Hr},{kind:"external",id:u.id,uri:vn},{kind:"thread",id:T.threadId},{kind:"message",id:T.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(T.kind)?"user_feedback":"judgment",summary:T.summary,availability:"available",artifactIds:[]}),p.push({id:le(l,"imprint-evidence-link",`${u.id}:${T.id}`,Date.parse(T.createdAt)),schemaVersion:1,projectId:l,createdAt:T.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:T.id,uri:Hr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"evidence",entityId:C},reason:"This advisory explanation was derived from collaboration evidence."}),g+=1)}let D={id:M,schemaVersion:1,projectId:l,createdAt:h?.createdAt??u.createdAt,participantId:h?.participantId??d.id,sourceRefs:ho([...h?.sourceRefs??[],{kind:"external",id:u.id,uri:vn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[c.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:pi(n,u.id),supersededById:u.supersededBy?b.get(u.supersededBy):void 0,updatedAt:u.updatedAt};h?f.push(D):S.push(D)}for(let u of n.relations){let M=go(u.type);if(!M)continue;let h=b.get(u.fromId),m=b.get(u.toId);!h||!m||R.has(u.id)||p.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:u.id,uri:Vt}],recordType:"relationship",relationshipType:M,from:{entityType:"advisory_explanation",entityId:h},to:{entityType:"advisory_explanation",entityId:m},reason:u.rationale||"The Imprint graph connected these explanations."})}let v=new Date().toISOString();if(S.length||f.length||p.length)try{let u=await this.store.commit({records:S,recordReplacements:f,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:v});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await zr(e,{recursive:!0}),await Wr(t,JSON.stringify({version:2,migratedAt:v,explanations:n.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:g}}async review(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,selection:ao(n.bundle,o)}}async contextualize(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:Cr(n.bundle,o),reviewSelection:ao(n.bundle,o)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:ri(n.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let t=await yn({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),o=ri(n.bundle,e);if(!o.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(o.errors)}`);let r=await this.store.commitReviewPlan(o.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),o=t.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!n||n.state!=="pending"||!o)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),d={proposalId:n.id,participantId:o.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},c=e.action==="accept"?{...d,action:"accept",eventId:xe(r),decisionId:xe(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...d,action:"edit_and_accept",withdrawalEventId:xe(r),replacementProposalId:xe(r),acceptanceEventId:xe(r),decisionId:xe(r),relationshipId:xe(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...d,action:"reject",eventId:xe(r),reason:e.reason}:{...d,action:"defer",eventId:xe(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=ri(t.bundle,c);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let w=await this.store.commitReviewPlan(l.plan,{transactionId:xe(r),committedAt:s});await this.refreshIndex(w);let R=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:w.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=Jr(t.bundle,e),o=le(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:o,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),o=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active"),r=n.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="ai"&&v.status==="active"),s=e.action?o:r??o,d=n.bundle.records.find(v=>v.recordType==="subject"&&v.subjectType==="project");if(!s||!d)return;let c=e.occurredAt??new Date().toISOString(),l=Date.parse(c),w=n.bundle.manifest.projectId,R=[],b=[],k=[],S=n.bundle.records.filter(v=>v.recordType==="advisory_explanation"),f=new Map(S.flatMap(v=>{let u=li(v);return u?[[u,v.id]]:[]}));for(let v of e.summary.changes)if(!f.has(v.explanationId)){let u=t?.explanations.find(M=>M.id===v.explanationId);f.set(v.explanationId,le(w,"imprint-explanation",v.explanationId,Date.parse(u?.createdAt??c)))}for(let v of e.summary.changes){let u={kind:"external",id:v.explanationId,uri:vn},M=f.get(v.explanationId),h=S.find(T=>T.id===M),m=t?.explanations.find(T=>T.id===v.explanationId),E={id:le(w,"imprint-live-evidence",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};R.push(E);let D={id:M,schemaVersion:1,projectId:w,createdAt:h?.createdAt??m?.createdAt??c,participantId:h?.participantId??s.id,sourceRefs:ho([...h?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:m?.kind??h?.kind??"pattern",state:m?.state??v.state,statement:m?.statement??v.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],E.id])],concreteBindings:m?pi(t,v.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?f.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??c};h?b.push(D):R.push(D),k.push({id:le(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${v.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:w,createdAt:c,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:D.id},to:{entityType:"evidence",entityId:E.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(n.bundle.relationships.flatMap(v=>v.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Vt?[u.id]:[])));for(let v of t?.relations??[]){let u=go(v.type);if(!u)continue;let M=f.get(v.fromId),h=f.get(v.toId);!M||!h||p.has(v.id)||k.push({id:le(w,"imprint-relation",v.id,Date.parse(v.createdAt)),schemaVersion:1,projectId:w,createdAt:v.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:v.id,uri:Vt}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:h},reason:v.rationale||"The Imprint graph connected these explanations."})}let g=le(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let v=await this.store.commit({records:R,recordReplacements:b,events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:c});await this.refreshIndex(v)}catch(v){if(!(v instanceof Error)||!v.message.includes("Transaction already exists"))throw v}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=xt(JSON.parse(await In(Gt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let d=t.bundle.manifest.projectId,c=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(c.flatMap(m=>{let E=li(m);return E?[[E,m]]:[]})),w=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(d,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),R=[],b=[],k=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=l.get(m.id);if(!E){R.push({id:w.get(m.id),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:vn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:pi(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt});continue}let D={...structuredClone(E),kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),concreteBindings:pi(e,m.id),supersededById:m.supersededBy?w.get(m.supersededBy):void 0,updatedAt:m.updatedAt},T=C=>JSON.stringify({kind:C.kind,state:C.state,statement:C.statement,rationale:C.rationale,scope:C.scope,concreteBindings:C.concreteBindings,supersededById:C.supersededById,updatedAt:C.updatedAt});T(E)!==T(D)&&b.push(D)}for(let[m,E]of l)k.has(m)||E.state==="retired"||b.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let S=new Set(t.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),f=new Map(t.bundle.relationships.flatMap(m=>{if(S.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Vt)?.id;return E?[[E,m]]:[]})),p=[],g=new Set;for(let m of e.relations){let E=go(m.type);if(!E)continue;let D=w.get(m.fromId),T=w.get(m.toId);if(!D||!T)continue;let C=f.get(m.id);C&&C.relationshipType===E&&C.from.entityType==="advisory_explanation"&&C.from.entityId===D&&C.to.entityType==="advisory_explanation"&&C.to.entityId===T||(C&&g.add(m.id),p.push({id:le(d,"imprint-relation",`${m.id}:${E}:${D}:${T}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:d,createdAt:m.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:m.id,uri:Vt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:T},reason:m.rationale||"The Imprint graph connected these explanations."}))}let v=new Set(e.relations.map(m=>m.id)),u=n?[...f].filter(([m])=>!v.has(m)||g.has(m)).map(([,m])=>({id:le(d,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:d,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!R.length&&!b.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let M=e.updatedAt,h=le(d,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:R,recordReplacements:b,events:[],relationships:p,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:h,committedAt:M});return await this.refreshIndex(m),{status:"synced",relationships:p.length+u.length,explanations:R.length+b.length,headSequence:m.report.headSequence}}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m;return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let n={};for(let o of t.bundle.records)n[o.recordType]=(n[o.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(o=>o.recordType==="freshness_signal"&&o.state==="open").length,unavailableEvidence:t.bundle.records.filter(o=>o.recordType==="evidence"&&o.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(d=>d.status==="projected").map(d=>d.decisionId):[])),o=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!o.has(s.id)&&!r.has(s.id)).sort((s,d)=>d.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(o=>o.recordType==="decision"&&o.state==="active"?[o.id]:[])),n=new Map;for(let o of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))o.decisionIds.some(r=>t.has(r))&&n.set(o.key,o);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 o=await this.store.load(),r=o.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(r.map(p=>[p.id,p])),d=new Map(r.flatMap(p=>{let g=li(p);return g?[[g,p.id]]:[]})),c=new Set(e.map(p=>d.get(p)??p)),l=new Map(o.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),w=new Map(o.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),R=new Set(o.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),b=new Set(["expresses","operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},S=r.map(p=>{let g=p.evidenceIds.flatMap(h=>{let m=w.get(h);if(!m)return[];let E=m.sourceRefs.find(z=>z.kind==="thread")?.id,D=m.sourceRefs.find(z=>z.kind==="message")?.id,T=m.kind==="judgment"||m.kind==="user_feedback"||m.kind==="project_state"?m.kind:"other",C=l.get(m.participantId)??"unknown";return[{id:m.id,kind:T,summary:m.summary,createdAt:m.createdAt,participantKind:C,threadId:E,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),v=o.bundle.relationships.flatMap(h=>{if(R.has(h.id))return[];if(!b.has(h.relationshipType))return[];let m=h.from.entityType==="advisory_explanation"&&h.from.entityId===p.id&&h.to.entityType==="advisory_explanation",E=h.to.entityType==="advisory_explanation"&&h.to.entityId===p.id&&h.from.entityType==="advisory_explanation";if(!m&&!E)return[];let D=m?h.to.entityId:h.from.entityId,T=s.get(D);return T?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:T.id,statement:T.statement,rationale:h.reason}]:[]}),u=[...(p.supersededById?[p.supersededById]:[]).flatMap(h=>{let m=s.get(h);return m?[{id:`supersedes:${p.id}:${m.id}`,type:"supersedes",direction:"incoming",explanationId:m.id,statement:m.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(h=>h.supersededById===p.id?[{id:`supersedes:${h.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:h.id,statement:h.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],M=[...new Set([...p.sourceRefs.flatMap(h=>h.kind==="thread"?[h.id]:[]),...g.flatMap(h=>h.threadId?[h.threadId]:[])])].filter(h=>!t||t.has(h));return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:g.length,recentEvidence:g.slice(0,4),concrete:p.concreteBindings.map(h=>({...structuredClone(h)})),relations:[...v,...u],sourceThreadIds:M,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,g)=>Number(g.needsGrounding)-Number(p.needsGrounding)||k[p.state]-k[g.state]||g.updatedAt.localeCompare(p.updatedAt)),f={total:S.filter(p=>p.state!=="retired").length,emerging:S.filter(p=>p.state==="emerging").length,testing:S.filter(p=>p.state==="testing").length,grounded:S.filter(p=>p.state==="grounded").length,challenged:S.filter(p=>p.state==="challenged").length,retired:S.filter(p=>p.state==="retired").length,needsGrounding:S.filter(p=>p.needsGrounding).length};return{head:{sequence:o.report.headSequence,updatedAt:o.bundle.manifest.updatedAt},counts:f,explanations:S}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(d=>d.recordType==="decision"&&d.state==="active"?[d.id]:[])),n=new Map;for(let d of e.records.filter(c=>c.recordType==="model_entry").sort((c,l)=>c.createdAt.localeCompare(l.createdAt)))d.decisionIds.some(c=>t.has(c))&&n.set(d.key,d);let o=[...n.values()],r=e.records.filter(d=>d.recordType==="verification_attempt");return{decisions:e.records.filter(d=>d.recordType==="decision"&&d.state==="active").map(d=>{let c=r.filter(l=>l.targets.some(w=>w.entityType==="decision"&&w.entityId===d.id)).sort((l,w)=>w.createdAt.localeCompare(l.createdAt))[0];return{id:d.id,kind:d.kind,claim:d.claim,projected:o.some(l=>l.decisionIds.includes(d.id)),verification:c?c.state:"unverified"}}),entries:o.map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),n=t.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active"),o=t.bundle.records.find(T=>T.recordType==="subject"&&T.subjectType==="project");if(!n||!o)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),d=xe(r),c=xe(r),l=xe(r),w=xe(r),R=xe(r),b=new Set(t.bundle.records.flatMap(T=>T.recordType==="model_entry"&&T.key===e.key?T.decisionIds:[])),k=t.bundle.records.filter(T=>T.recordType==="decision"&&T.state==="active"&&b.has(T.id)),S={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:o.id,role:"governed"}],p={...S,id:d,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},g={...S,id:c,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:d},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},v={...S,id:l,recordType:"decision",proposalId:d,acceptanceEventId:c,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},u={...S,id:w,recordType:"model_entry",key:e.key,subjectIds:[o.id],decisionIds:[l],value:e.value},M={...S,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[w],coverage:[{decisionId:l,status:"projected"}]},h={...S,id:xe(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},m=k.map(T=>({...S,id:xe(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:T.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=k.map(T=>({...S,id:xe(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:v.id},to:{entityType:"decision",entityId:T.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[p,v,u,M],events:[g,...m],relationships:[h,...E],artifacts:[],tombstones:[],projectionUpdates:k.map(T=>({entityType:"decision",entityId:T.id,fromState:"active",state:"superseded"}))},{transactionId:xe(r),committedAt:s});return await this.refreshIndex(D),{decisionId:l,entryId:w}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Map(t.records.flatMap(o=>o.recordType==="subject"?[[o.id,o.label]]:[]));return t.records.filter(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.kind==="thread"&&r.id===e)).sort((o,r)=>o.createdAt.localeCompare(r.createdAt)).map(o=>({proposalId:o.id,claim:o.claim,rationale:o.rationale,proposedKind:o.proposedKind,subjectLabels:o.subjects.flatMap(r=>{let s=n.get(r.subjectId);return s?[s]:[]})}))}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),n=t.bundle.records.find(S=>S.recordType==="model_projection"&&S.state==="applied"&&S.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let o=t.bundle.records.filter(S=>S.recordType==="decision"&&e.decisionIds.includes(S.id)&&S.state==="active");if(o.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),d=new Date(s).toISOString(),c=xe(s),l=e.changes.map(S=>{let f=S.decisionIds?.filter(v=>e.decisionIds.includes(v)),p=f?.length?f:e.decisionIds,g=[...new Set(o.filter(v=>p.includes(v.id)).flatMap(v=>v.subjects.map(u=>u.subjectId)))];return{id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:p.map(v=>({kind:"record",id:v})),recordType:"model_entry",key:S.path.map(String).join("."),subjectIds:g,decisionIds:p,value:S.value}}),w=new Set(l.flatMap(S=>S.decisionIds)),R={id:c,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:e.decisionIds.map(S=>({kind:"record",id:S})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:e.decisionIds,entryIds:l.map(S=>S.id),coverage:e.decisionIds.map(S=>e.coverage?.find(f=>f.decisionId===S)??{decisionId:S,status:w.has(S)?"projected":"unprojected"})},b=l.flatMap(S=>S.decisionIds.map(f=>({id:xe(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:r.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:S.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...l,R],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:xe(s),committedAt:d});return await this.refreshIndex(k),{projectionId:c,entryIds:l.map(S=>S.id),headSequence:k.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await yn({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),o=Ur(n,t.subjectHints??[]);return o?{...t,subjectIds:[...new Set([...t.subjectIds??[],...o.subjectIds])],candidateDecisionIds:o.decisionIds,candidateProposalIds:o.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Qt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function Pe(i,e){if(typeof i!="string"||!i.trim())throw new Error(`${e} must be a non-empty string.`);return i}function Kt(i,e,t){let n=Pe(i,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function yo(i){let e=Qt(i),t=Qt(e.authority),n=t.level,o=t.mode,r=Kt(n,"authority.level",["owner","delegate","contributor"]),s=Kt(o,"authority.mode",["local_trusted","hosted"]),d={proposalId:Pe(e.proposalId,"proposalId"),participantId:Pe(e.participantId,"participantId"),occurredAt:Pe(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...d,action:"accept",eventId:Pe(e.eventId,"eventId"),decisionId:Pe(e.decisionId,"decisionId"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Pe(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...d,action:"reject",eventId:Pe(e.eventId,"eventId"),reason:Pe(e.reason,"reason")};case"defer":{let c=Qt(e.context);if(!Array.isArray(c.subjectIds)||!Array.isArray(c.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...d,action:"defer",eventId:Pe(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof c.taskContext=="string"?c.taskContext:void 0,subjectIds:c.subjectIds.map(l=>Pe(l,"subjectId")),resurfaceWhen:c.resurfaceWhen.map(l=>Kt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof c.revisitAfter=="string"?c.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...d,action:"edit_and_accept",withdrawalEventId:Pe(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Pe(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Pe(e.acceptanceEventId,"acceptanceEventId"),decisionId:Pe(e.decisionId,"decisionId"),relationshipId:Pe(e.relationshipId,"relationshipId"),claim:Pe(e.claim,"claim"),kind:Kt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(c=>{let l=Qt(c);return{subjectId:Pe(l.subjectId,"subjectId"),role:Kt(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Pe(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Io(i){let e=Qt(i),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(d=>Pe(d,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},o=e.resurface===void 0?void 0:Qt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:o?{differentAction:o.differentAction===!0,newEvidence:o.newEvidence===!0,newConflict:o.newConflict===!0,ownerRequested:o.ownerRequested===!0}:void 0}}function Gr(i){let e=i.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,o=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!o||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(d=>typeof d=="string"&&r.has(d)):void 0;return{proposalId:t.proposalId,action:n,kind:o,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 Vr(i){let e=i.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 vo(i){let t=(i.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],o=await Lc(i),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),d,c,l,w,R,b,k,S,f,p,g,v,u,M,h=[],m=[],E=0,D=[];for(;E<o.length;){let T=o.indexOf(r,E);if(T===-1)break;let C=T+r.length;if(o.slice(T,T+s.length).equals(s))break;let z=C;o[z]===13&&o[z+1]===10&&(z+=2);let X=o.indexOf(`\r
|
|
168
170
|
\r
|
|
169
|
-
`,z);if(X===-1)break;let G=o.slice(z,X).toString("utf-8"),Y=X+4,
|
|
171
|
+
`,z);if(X===-1)break;let G=o.slice(z,X).toString("utf-8"),Y=X+4,x=o.indexOf(r,Y),Q=x!==-1?x-2:o.length;D.push({headers:G,body:o.slice(Y,Q)}),E=x!==-1?x:o.length}for(let T of D){let C=T.headers.match(/name="([^"]+)"/);if(!C)continue;let z=C[1];if(z==="screenshot")d=T.body;else if(z==="feedback")c=T.body.toString("utf-8");else if(z==="color")l=T.body.toString("utf-8");else if(z==="provider")w=T.body.toString("utf-8");else if(z==="model")R=T.body.toString("utf-8");else if(z==="reasoningEffort")b=T.body.toString("utf-8");else if(z==="serviceTier")k=T.body.toString("utf-8");else if(z==="goal")S=T.body.toString("utf-8");else if(z==="pageUrl")f=T.body.toString("utf-8");else if(z==="viewport")p=T.body.toString("utf-8");else if(z==="planId")g=T.body.toString("utf-8");else if(z==="manifest")v=T.body.toString("utf-8");else if(z==="tasks")u=T.body.toString("utf-8");else if(z==="sourceId")M=T.body.toString("utf-8");else if(z.startsWith("screenshot-")){let X=z.slice(11);try{let G=decodeURIComponent(X);m.push({pathname:G,data:T.body})}catch{}}else if(z.startsWith("image-")){let X=z.split("-"),G=parseInt(X[X.length-1],10),Y=X.slice(1,-1).join("-");Y&&!isNaN(G)&&h.push({annotationId:Y,index:G,data:T.body})}}if(!d)throw new Error("Missing screenshot field");return c||(c=""),{screenshot:d,feedback:c,color:l,provider:w,model:R,reasoningEffort:b,serviceTier:k,goal:S,pageUrl:f,viewport:p,planId:g,manifest:v,tasks:u,sourceId:M,pastedImages:h,pageScreenshots:m}}function Lc(i){return new Promise((e,t)=>{let n=[];i.on("data",o=>n.push(o)),i.on("end",()=>e(Buffer.concat(n))),i.on("error",t)})}import{randomUUID as qc}from"crypto";var wn="<orientation>",at="</orientation>";function Xt(i,e){let t=e;for(;t<i.length&&/\s/.test(i[t]);)t++;if(t>=i.length)return{status:"incomplete",start:t};if(i[t]!=="{")return{status:"invalid",start:t};let n=0,o=!1,r=!1;for(let s=t;s<i.length;s++){let d=i[s];if(o){r?r=!1:d==="\\"?r=!0:d==='"'&&(o=!1);continue}if(d==='"')o=!0;else if(d==="{")n++;else if(d==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function Kr(i,e){if(!e)return;let t=i[i.length-1];t?.kind==="text"?t.text+=e:i.push({kind:"text",text:e})}function Qr(i){let e=[],t=0;for(;t<i.length;){let n=i.indexOf(wn,t);if(n<0){Kr(e,i.slice(t));break}Kr(e,i.slice(t,n));let o=n+wn.length,r=Xt(i,o);if(r.status!=="complete"){let d=i.indexOf(at,o);if(d>=0){t=d+at.length;continue}t=o;continue}e.push({kind:"orientation",json:i.slice(r.start,r.end)}),t=r.end;let s=t;for(;s<i.length&&/\s/.test(i[s]);)s++;i.startsWith(at,s)&&(t=s+at.length)}return e}var Fc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Uc=new Set(["strengthened","weakened","mixed","unknown"]);function bn(i,e=180){if(typeof i!="string")return;let t=i.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function zc(i){return!i||typeof i!="object"||Array.isArray(i)?null:i}function Xr(i,e,t,n=Date.now()){let o=zc(i);if(!o)return null;let r=typeof o.transition=="string"&&Fc.has(o.transition)?o.transition:null,s=bn(o.focus);if(!r||!s)return null;let d=typeof o.evidencePosture=="string"&&Uc.has(o.evidencePosture)?o.evidencePosture:void 0;return{id:qc(),jobId:e,sequence:t,timestamp:n,transition:r,snapshot:{focus:s,seeking:bn(o.seeking),workingHypothesis:bn(o.workingHypothesis),evidencePosture:d,update:bn(o.update),nextObservation:bn(o.nextObservation)},contextPolicy:"exclude"}}function wo(i){return JSON.stringify({transition:i.transition,snapshot:i.snapshot})}function bo(i,e,t=0){let n=[],o=[],r=new Set,s=t;for(let c of Qr(i)){if(c.kind==="text"){c.text&&o.push(c);continue}try{let l=Xr(JSON.parse(c.json),e,s);if(!l)continue;let w=wo(l);if(r.has(w))continue;r.add(w),n.push(l),o.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:o.map(c=>c.kind==="text"?c.text:`
|
|
170
172
|
|
|
171
173
|
`).join("").replace(/\n{3,}/g,`
|
|
172
174
|
|
|
173
|
-
`).trim(),orientations:n,segments:o}}function
|
|
175
|
+
`).trim(),orientations:n,segments:o}}function Wc(i){let e="<orientation>",t=Math.min(i.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(i.slice(-n)))return n;return 0}var mi=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(at.startsWith(l)&&l.length<at.length||(l.startsWith(at)&&(this.buffer=this.buffer.slice(c+at.length)),this.optionalClosePending=!1,!this.buffer))break}let o=this.buffer.indexOf(wn);if(o<0){let c=Wc(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,o);let r=o+wn.length,s=Xt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(o);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let d=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let c=Xr(JSON.parse(d),this.jobId,this.sequence);if(!c)continue;let l=wo(c);if(this.signatures.has(l))continue;this.signatures.add(l),n.push(c),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=bo(e,this.jobId,this.sequence),n=t.orientations.filter(o=>{let r=wo(o);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},Yr=`## Public orientation updates
|
|
174
176
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
175
177
|
<orientation>{"transition":"focus_shifted","focus":"Investigating the responsive overflow","seeking":"Which container introduces the extra width","update":"Padding is no longer the leading explanation","nextObservation":"Inspect computed widths at the failing breakpoint"}</orientation>
|
|
176
178
|
|
|
177
179
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
178
180
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
179
181
|
|
|
180
|
-
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
|
|
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 Zr=`## Project collaboration history
|
|
181
183
|
Popmelt's durable collaboration history lives in the project's \`.popmelt\` directory. High-confidence relevant Imprint explanations may already be surfaced elsewhere in this prompt. Start with that supplied Imprint context and use it directly when it adequately answers the developer's question. For questions about the current implementation, inspect the relevant source only as needed to confirm how that understanding is expressed.
|
|
182
184
|
|
|
183
185
|
For answer-only or explanation-only requests, use a narrow default evidence budget: begin with the supplied Imprint, inspect the selected component once, and inspect at most one directly surrounding layout source only if the component does not adequately explain the observation. Explain the dominant visible phenomenon rather than auditing every property in the screenshot. Stop once the answer is supported. Broaden beyond that only when evidence conflicts, the selected target remains materially ambiguous, or the developer explicitly asks for a comprehensive audit.
|
|
@@ -188,29 +190,29 @@ Use Popmelt history to explain why a decision was made or how shared understandi
|
|
|
188
190
|
|
|
189
191
|
Apply an evidence-sufficiency stopping rule: stop researching as soon as the relevant Imprint and current source adequately explain the observation. If one corroborating collaboration record is needed, stop after finding it unless the evidence conflicts or the developer requested a fuller history. Do not reconstruct an exhaustive timeline for a present-tense explanation, and do not search the full history for routine implementation work.`;function xn(i,e,t){let n=[];if(i.annotations.length>0){n.push("## Annotations");for(let o of i.annotations){let r=o.elements.map(l=>{let w=[l.selector];return l.reactComponent&&w.push(`(${l.reactComponent})`),w.join(" ")}).join(", "),s=o.instruction||"No text";n.push(`- id=${o.id} [${o.type}] ${s} \u2192 Elements: ${r||"none"}`);let d=e?.[o.id];if(d&&d.length>0)for(let l of d)n.push(` Attached image: use the Read tool to view ${l}`);let c=t?.[o.id];if(c?.length)for(let l of c)n.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(i.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 o of i.styleModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"";for(let s of o.changes)n.push(`- ${o.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(i.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 o of i.textModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"",s=JSON.stringify(o.original),d=JSON.stringify(o.modified),c=o.textNodePath.length>0?` textNodePath=${o.textNodePath.join(".")}`:"";n.push(`- ${o.selector} ${r}${c}: ${s} \u2192 ${d}`)}}if(i.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 o of i.domModifications){let r=o.element?.reactComponent?`(${o.element.reactComponent})`:"",s=o.sourceElement?.reactComponent?` from ${o.sourceSelector} (${o.sourceElement.reactComponent})`:o.sourceSelector?` from ${o.sourceSelector}`:"",d=o.referenceSelector?` ${o.placement} ${o.referenceSelector}`:` at index ${o.targetIndex}`;n.push(`- ${o.operation}: ${o.selector} ${r}${s} \u2192 ${o.targetParentSelector}${d}`)}}if(i.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 o of i.spacingTokenChanges){n.push(`
|
|
190
192
|
### ${o.tokenName}: ${o.originalPx}px \u2192 ${o.newPx}px`);for(let r of o.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${o.originalPx}px \u2192 ${o.newPx}px`),n.push(` class="${r.className}"`)}}}if(i.inspectedElement){let o=i.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[o.selector];o.reactComponent&&r.push(`(${o.reactComponent})`),o.context&&r.push(`in ${o.context}`),o.textContent&&r.push(`"${o.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
191
|
-
`)}function
|
|
192
|
-
`)}function
|
|
193
|
-
`)}function
|
|
194
|
-
`)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let o=n.match(
|
|
195
|
-
`));return hi([...fi,...c])}function mi(i,e,t=5e3){return new Promise((n,o)=>{Vc(i,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){o(r);return}n(s)})})}async function ds(i){return Qc(i,"utf-8")}async function nl(i){let e=[tt(i,"projects"),tt(i,"telemetry")],t=[];for(let n of e)await cs(n,t,4);return t.sort((n,o)=>o.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function cs(i,e,t){if(t<0)return;let n;try{n=await Kc(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async o=>{let r=tt(i,o.name);if(o.isDirectory()){await cs(r,e,t-1);return}if(!(!o.isFile()||!il(o.name)))try{let s=await Xc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function il(i){return i.endsWith(".json")||i.endsWith(".jsonl")||i.endsWith(".md")||i.endsWith(".txt")}function hi(i){let e=new Set,t=[];for(let n of i)e.has(n.id)||(e.add(n.id),t.push(n));return t}function ol(i){return[...new Set(i)]}function rl(i){return i.charAt(0).toUpperCase()+i.slice(1)}var gi=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,o=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),o}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 o=this.bufferEvent(t,e);for(let r of this.listeners)r(o,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let o={...t,seq:n.nextSeq++};return n.events.push(o),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),o}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(d=>d.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...o},jobActive:r}}accumulateText(e,t,n){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[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(o=>{let r=!1,s=()=>{r||(r=!0,o())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as sl}from"crypto";var Yt="<imprint-use>",yi="</imprint-use>";function al(i){let e=Math.min(i.length,Yt.length-1);for(let t=e;t>0;t--)if(Yt.startsWith(i.slice(-t)))return t;return 0}function ls(i,e,t,n,o=Date.now()){if(!i||typeof i!="object"||Array.isArray(i))return null;let r=i,s=Array.isArray(r.explanationIds)?r.explanationIds.filter(c=>typeof c=="string"&&!!c.trim()):[],d=[...new Set(s)].flatMap(c=>{let l=e?.explanations.find(w=>w.id===c);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return d.length===0?null:{id:sl(),jobId:t,sequence:n,timestamp:o,explanations:d}}var Ii=class{constructor(e,t){this.jobId=e;this.context=t;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let t=e.explanations.filter(n=>!this.explanationIds.has(n.id));if(t.length===0)return null;for(let n of t)this.explanationIds.add(n.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(yi.startsWith(l)&&l.length<yi.length||(l.startsWith(yi)&&(this.buffer=this.buffer.slice(c+yi.length)),this.optionalClosePending=!1,!this.buffer))break}let o=this.buffer.indexOf(Yt);if(o<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,o);let r=o+Yt.length,s=Xt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(o);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let d=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let c=ls(JSON.parse(d),this.context,this.jobId,this.sequence);if(!c)continue;let l=this.takeNewExplanations(c);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf(Yt,o);if(r<0){n+=e.slice(o);break}n+=e.slice(o,r);let s=r+Yt.length,d=Xt(e,s);if(d.status!=="complete"){o=s;continue}try{let w=ls(JSON.parse(e.slice(d.start,d.end)),this.context,this.jobId,this.sequence);if(w){let k=this.takeNewExplanations(w);k&&t.push(k)}}catch{}let l=e.slice(d.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;o=d.end+l}return{visibleText:n.trim(),usages:t}}};function kn(i,e){return i?.projectId===e.projectId&&i.version===e.version&&i.restartMode===e.restartMode}function vi(i){return(Array.isArray(i)?i[0]:i)?.split(",")[0]?.trim()||void 0}function xo(i){if(!i)return null;try{let e=new URL(i);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function ps(i){let e=xo(vi(i.origin));if(e)return e;let t=xo(vi(i.referer));if(t)return t;let n=vi(i["x-forwarded-host"]);if(!n)return null;let o=vi(i["x-forwarded-proto"])==="https"?"https":"http";return xo(`${o}://${n}`)}function us(i,e,t=5){let n=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),o=[...i].sort(n).slice(0,t),r=i.filter(c=>c.status==="applied"||c.status==="failed").sort(n).slice(0,t),s=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=s.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:o,recentAppliedRuns:r,actionableProposalCounts:d,actionableProposals:s}}import{createHash as xi}from"crypto";import{mkdir as jn,readFile as At,unlink as ml,writeFile as Zt}from"fs/promises";import{dirname as Si,extname as fl,join as Ne}from"path";var dl={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 cl(i){let e=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function ms(i,e){let t=e??cl(i);return{kind:t,...dl[t]}}import{createHash as ll,randomUUID as pl}from"crypto";var fs=i=>`${i}-${pl()}`;function So(i,...e){return`${i}-${ll("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function To(i){return{schemaVersion:1,submissionIds:[fs("submission")],jobId:i.jobId,threadId:i.threadId,artifactIds:[...new Set(i.artifactIds??[])]}}function Rn(i,e=[],t){return{...i,outcomeId:i.outcomeId??fs("outcome"),imprintEvidenceIds:[...new Set([...i.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function ul(i){try{return new URL(i).pathname||"/"}catch{return"/"}}function wi(i,e){return e?[`${i||"/"}:${e}`]:[]}function hs(i){let e=ul(i.url);return[...new Set([...i.annotations.flatMap(t=>wi(t.pathname??e,t.linkedSelector)),...i.styleModifications.flatMap(t=>wi(e,t.durableSelector??t.selector)),...(i.textModifications??[]).flatMap(t=>wi(t.pathname??e,t.durableSelector??t.selector)),...(i.domModifications??[]).flatMap(t=>wi(t.pathname??e,t.durableSelector??t.selector))])]}function gs(i,e){return[...new Set([`screenshot:${e}`,...i.annotations.map(t=>`annotation:${t.id}`),...i.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function bi(i,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=So("submission",i,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:i,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[So("artifact",i,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:So("outcome",i,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Po(i){let e=i.lifecycleVersion!==1;i.lifecycleVersion=1;for(let t of i.messages)e=bi(i.id,t)||e;return e}function ys(i){let e=i.messages.at(-1),t=[...i.messages].reverse().find(o=>o.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:i.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:i.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:i.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var hl={version:1,threads:{}},Is=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],An={version:2,updatedAt:0,files:{}};function gl(i){return JSON.stringify(i,null,2)}function yl(i){return Object.fromEntries(Is.flatMap(e=>i[e]===void 0?[]:[[e,i[e]]]))}function Il(i){let e={...i};for(let t of Is)delete e[t];return e}function en(i){let e=i;if(i.error){let t=ms(i.error,i.errorKind);(i.error!==t.message||i.errorKind!==t.kind||i.responseText!==void 0)&&(e={...i,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=_t(e.result,!1),n=_t(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var Ti=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Ne(e,".popmelt");this.legacyFilePath=Ne(t,"threads.json"),this.threadsDir=Ne(t,"threads"),this.indexPath=Ne(this.threadsDir,"index.json"),this.artifactsDir=Ne(t,"artifacts","thread-messages"),this.mediaDir=Ne(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await At(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[o,r]of Object.entries(e.files)){let s=await this.readThread(Ne(this.threadsDir,r));s&&(t[o]=s)}this.cache={version:1,threads:t};let n=!1;for(let o of Object.values(t))n=Po(o)||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(en)}]))},this.index={...An,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))Po(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...hl,threads:{}},this.index={...An,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 o of Object.values(t.threads))if(o.elementIdentifiers.some(s=>n.has(s)))return o;return null}async createThread(e,t){let n=await this.load(),o={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=o,await this.persistThread(o),o}async appendMessage(e,t){let o=(await this.load()).threads[e];o&&(bi(e,t),o.messages.push(en(t)),o.updatedAt=Date.now(),await this.persistThread(o))}async appendMessageBeforeQueuedReplies(e,t){let o=(await this.load()).threads[e];if(!o)return;bi(e,t);let r=o.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?o.messages.splice(r,0,en(t)):o.messages.push(en(t)),o.updatedAt=Date.now(),await this.persistThread(o)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(d=>d.jobId===t);if(s.length===0)return!1;for(let d of s)if(Object.assign(d,n),d.error){let c=en(d);Object.assign(d,c),delete d.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let o=(await this.load()).threads[e];if(!o)return;let r=new Set(o.elementIdentifiers);for(let s of t)r.has(s)||o.elementIdentifiers.push(s);o.updatedAt=Date.now(),await this.persistThread(o)}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((o,r)=>r.updatedAt-o.updatedAt),n.slice(0,e).map(o=>{let s=o.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",d=o.messages.filter(p=>p.role==="assistant"),c=p=>{if(p.role!=="assistant")return;if(p.question)return p.question;let g=p.imprintSummary?.grounding;if(g?.question&&!p.imprintSummary?.resolvedAction)return g.question},l=o.messages.findLastIndex(p=>!!c(p)),w=o.messages.findLastIndex(p=>p.role==="human"),k=l>w?c(o.messages[l]):void 0,T=o.messages.at(-1)?.role,R=Array.from(new Set(o.messages.slice(0,Math.max(0,w)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),x=d.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=d.some(p=>!!p.error);return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:s,messageCount:o.messages.length,hasReply:x,hasError:f,lastMessageRole:T,pendingQuestion:k,acknowledgedJobIds:R,elementIdentifiers:o.elementIdentifiers,lifecycle:ys(o)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let o=n.messages.at(-1);if(!o||o.role!=="human"||/^(imprint|memory)-/.test(o.jobId))continue;let r=Rn(o.lifecycle);o.queued&&await this.updateMessage(n.id,o.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:o.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await At(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:o,...r})=>{let s={};if(o?.path)try{let d=await At(Ne(Si(this.legacyFilePath),o.path),"utf8");xi("sha256").update(d).digest("hex")===o.sha256&&(s=JSON.parse(d))}catch{}return en({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=yl(e),n=Il(e);if(Object.keys(t).length===0)return n;let o=gl(t),r=xi("sha256").update(o).digest("hex"),s=Ne("artifacts","thread-messages",`${r}.json`);await jn(this.artifactsDir,{recursive:!0});try{await At(Ne(Si(this.legacyFilePath),s),"utf8")}catch{await Zt(Ne(Si(this.legacyFilePath),s),o)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(Si(n)===this.mediaDir)return n;try{let o=await At(n),r=xi("sha256").update(o).digest("hex"),s=Ne(this.mediaDir,`${r}${fl(n)||".bin"}`);await jn(this.mediaDir,{recursive:!0});try{await At(s)}catch{await Zt(s,o)}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,o])=>[n,await t(o)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,o])=>[n,await Promise.all(o.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,o])=>[n,await Promise.all(o.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await jn(this.threadsDir,{recursive:!0});let t=this.index??{...An,files:{}},n=t.files[e.id]??`${xi("sha256").update(e.id).digest("hex").slice(0,32)}.json`,o=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:o};await Zt(Ne(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Zt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await jn(this.threadsDir,{recursive:!0}),this.index=this.index??{...An,files:{}},await Zt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...An,files:{}},n=t.files[e];n&&await ml(Ne(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await jn(this.threadsDir,{recursive:!0}),await Zt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as vl,open as wl,readFile as bl,rename as xl,unlink as Sl}from"fs/promises";import{dirname as Tl,join as Pl}from"path";var vs={schemaVersion:1,theme:"auto",updatedAt:null};function ws(i){return i==="light"||i==="dark"||i==="auto"?i:null}async function kl(i,e){await vl(Tl(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`;try{let n=await wl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
196
|
-
`,"utf8"),await n.sync()}finally{await n.close()}await
|
|
193
|
+
`)}function es(i,e,t){let n=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!r&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let d of t.threadHistory)if(d.role==="human")s++,d.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${d.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),d.feedbackSummary&&n.push(`Annotations: ${d.feedbackSummary}`),d.annotationIds&&d.annotationIds.length>0&&n.push(`Annotation IDs: ${d.annotationIds.join(", ")}`));else if(d.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${d.question}"`);else{if(n.push(`### Round ${s} (assistant)`),d.responseText&&n.push(`Response: ${d.responseText}`),d.resolutions&&d.resolutions.length>0)for(let c of d.resolutions){let l=c.finalScope??c.inferredScope,w=l?` [${l.breadth} ${l.target}]`:"";n.push(`- ${c.annotationId}: ${c.status}${w} \u2014 ${c.summary}`),c.filesModified&&c.filesModified.length>0&&n.push(` Files: ${c.filesModified.join(", ")}`)}d.toolsUsed&&d.toolsUsed.length>0&&n.push(`Tools used: ${d.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let w=new Map;for(let R of s)if(typeof R=="object"&&R!==null&&"text"in R){let b=R,k=b.scope||"general";w.has(k)||w.set(k,[]),w.get(k).push(b.text)}for(let[R,b]of w){n.push(`**${R.charAt(0).toUpperCase()+R.slice(1)}**`);for(let k of b)n.push(`- ${k}`)}}else for(let w of s)typeof w=="string"&&n.push(`- ${w}`);let d=t.designModel.tokens;d&&typeof d=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```"));let c=t.designModel.components;c&&typeof c=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(c,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=t?.screenshotPaths??{},d=new Map;for(let c of e.annotations){let l=c.pathname||new URL(e.url).pathname;d.has(l)||d.set(l,[]),d.get(l).push(c)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[c,l]of d){n.push(""),n.push(`## Page: ${c}`);let w=s[c];w&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${w}`):!w&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${i}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let R={...e,annotations:l,styleModifications:e.styleModifications},b=xn(R,t?.imagePaths,t?.attachmentFiles);b&&(n.push(""),n.push(b))}}else{let s=xn(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
|
|
194
|
+
`)}function ts(i){return i.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function ns(i,e,t,n){let o=[];o.push("You are continuing work on a UI based on the developer's reply to your question."),o.push(""),t!=="codex"&&o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${i}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(o.push(""),o.push(r.feedbackContext)),e.length>0){o.push(""),o.push("## Conversation History");let s=0;for(let d of e)d.role==="human"?(s++,d.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${d.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),d.feedbackSummary&&o.push(`Annotations: ${d.feedbackSummary}`))):d.question?(o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${d.question}"`)):(o.push(`### Round ${s} (assistant)`),d.responseText&&o.push(`Response: ${d.responseText}`))}if(o.push(""),o.push("The developer answered your question. Continue working based on their reply."),o.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),o.push(""),o.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){o.push(""),o.push("## Attached Images"),o.push("The developer attached reference images with their reply:");for(let s of n)o.push(`Attached image: use the Read tool to view the image at: ${s}`)}return o.push(""),o.push("## Resolution"),o.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),o.push("<resolution>"),o.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),o.push("</resolution>"),o.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),o.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),o.push(""),o.push("### Scope classification"),o.push("Each resolution MUST include scope fields:"),o.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),o.push("- `inferredScope`: What scope the change actually has, based on what you modified."),o.push("Scope has two dimensions:"),o.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),o.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),o.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),o.push("If you cannot confidently determine scope, set it to null."),o.push('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.'),o.push(""),o.push("## Questions"),o.push("If you still need clarification, output:"),o.push("<question>Your question here</question>"),o.push("You may output BOTH a <resolution> and a <question> in the same response."),o.join(`
|
|
195
|
+
`)}function Hc(i){if(typeof i!="object"||i===null)return!1;let e=i;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Gc(i){if(typeof i!="object"||i===null||typeof i.annotationId!="string"||i.status!=="resolved"&&i.status!=="needs_review"||typeof i.summary!="string")return!1;let e=i;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!Hc(e[t]))return!1;return!0}function is(i){let t=[...i.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(Gc)}catch{return[]}}function Vc(i){let e=i.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 o=n;return(o.category==="token"||o.category==="component"||o.category==="element")&&typeof o.element=="string"&&typeof o.decision=="string"&&typeof o.reason=="string"}):[]}catch{return[]}}function os(i,e){return e>0?Vc(i):[]}import{execFile as Kc}from"child_process";import{readdir as Qc,readFile as Xc,stat as Yc}from"fs/promises";import{homedir as Sn}from"os";import{join as tt}from"path";var hi=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:rs()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:rs()}],Tn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Pn={id:"",label:"Default",source:"cli"},Zc=/^\s*-\s+"([^"]+)"/;function el(i){let e=[],t=!1;for(let n of i.split(`
|
|
196
|
+
`)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let o=n.match(Zc);if(!o?.[1])continue;let r=o[1];e.push({id:r,label:xo(r),source:"cli"})}return gi([Pn,...e])}function tl(i){let e=JSON.parse(i);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,o)=>{let r=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(n=>{let o=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!o)return[];let r=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():xo(o),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,d=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(c=>{if(!c||typeof c!="object")return[];let l=c;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:o,label:r,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...d&&d.length>0?{speedTiers:d}:{}}]})}function rs(){return["low","medium","high","xhigh","max"].map(i=>({effort:i}))}function nl(i){let e=i.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return gi(e.map(t=>({id:t,label:xo(t),source:"cli"})))}function xo(i){if(!i)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=i.replace(/-\d{8,}$/,"");if(e[i])return e[i];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let r=n[1]==="sonnet"?"Sonn":sl(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${r}${s}${n[4]?" Fast":""}`}let o=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(o){let r=o[2]?`${o[1]}.${o[2]}`:o[1];return o[3]==="mini"?`Mini ${r}`:o[3]==="codex"?`Codex ${r}`:o[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return t}async function ss(i="copilot"){let e=await fi(i,["help","config"]),t=el(e);return t.length>1?t:[Pn]}async function as(i="codex"){let e=await fi(i,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||tt(Sn(),".codex");return cs(tt(n,"models_cache.json"))}),t=tl(e);return t.length>0?gi([...t,...Tn]):Tn}async function ds(i="claude"){let e=tt(Sn(),".claude"),t=[tt(Sn(),".claude","stats-cache.json"),tt(Sn(),".claude","settings.json"),tt(Sn(),".claude.json"),tt(e,"cache","changelog.md")],[n,o,r]=await Promise.all([fi(i,["--help"]).catch(()=>""),fi(i,["--version"]).catch(()=>""),il(e).catch(()=>[])]),s=rl([...t,...r]),d=await Promise.all(s.map(l=>cs(l).catch(()=>""))),c=nl([n,o,...d].join(`
|
|
197
|
+
`));return gi([...hi,...c])}function fi(i,e,t=5e3){return new Promise((n,o)=>{Kc(i,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){o(r);return}n(s)})})}async function cs(i){return Xc(i,"utf-8")}async function il(i){let e=[tt(i,"projects"),tt(i,"telemetry")],t=[];for(let n of e)await ls(n,t,4);return t.sort((n,o)=>o.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function ls(i,e,t){if(t<0)return;let n;try{n=await Qc(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async o=>{let r=tt(i,o.name);if(o.isDirectory()){await ls(r,e,t-1);return}if(!(!o.isFile()||!ol(o.name)))try{let s=await Yc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function ol(i){return i.endsWith(".json")||i.endsWith(".jsonl")||i.endsWith(".md")||i.endsWith(".txt")}function gi(i){let e=new Set,t=[];for(let n of i)e.has(n.id)||(e.add(n.id),t.push(n));return t}function rl(i){return[...new Set(i)]}function sl(i){return i.charAt(0).toUpperCase()+i.slice(1)}var yi=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,o=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),o}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 o=this.bufferEvent(t,e);for(let r of this.listeners)r(o,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let o={...t,seq:n.nextSeq++};return n.events.push(o),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),o}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),o=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(d=>d.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...o},jobActive:r}}accumulateText(e,t,n){let o=this.accumulators.get(e);o||(o={response:"",thinking:""},this.accumulators.set(e,o)),o[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(o=>{let r=!1,s=()=>{r||(r=!0,o())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as al}from"crypto";var Yt="<imprint-use>",Ii="</imprint-use>";function dl(i){let e=Math.min(i.length,Yt.length-1);for(let t=e;t>0;t--)if(Yt.startsWith(i.slice(-t)))return t;return 0}function ps(i,e,t,n,o=Date.now()){if(!i||typeof i!="object"||Array.isArray(i))return null;let r=i,s=Array.isArray(r.explanationIds)?r.explanationIds.filter(c=>typeof c=="string"&&!!c.trim()):[],d=[...new Set(s)].flatMap(c=>{let l=e?.explanations.find(w=>w.id===c);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return d.length===0?null:{id:al(),jobId:t,sequence:n,timestamp:o,explanations:d}}var vi=class{constructor(e,t){this.jobId=e;this.context=t;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let t=e.explanations.filter(n=>!this.explanationIds.has(n.id));if(t.length===0)return null;for(let n of t)this.explanationIds.add(n.id);return{...e,sequence:this.sequence++,explanations:t}}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let c=0;for(;c<this.buffer.length&&/\s/.test(this.buffer[c]);)c++;let l=this.buffer.slice(c);if(Ii.startsWith(l)&&l.length<Ii.length||(l.startsWith(Ii)&&(this.buffer=this.buffer.slice(c+Ii.length)),this.optionalClosePending=!1,!this.buffer))break}let o=this.buffer.indexOf(Yt);if(o<0){let c=dl(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,o);let r=o+Yt.length,s=Xt(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(o);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let d=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let c=ps(JSON.parse(d),this.context,this.jobId,this.sequence);if(!c)continue;let l=this.takeNewExplanations(c);l&&n.push(l)}catch{}}return{visibleText:t,usages:n}}finalize(e){this.buffer="",this.optionalClosePending=!1;let t=[],n="",o=0;for(;o<e.length;){let r=e.indexOf(Yt,o);if(r<0){n+=e.slice(o);break}n+=e.slice(o,r);let s=r+Yt.length,d=Xt(e,s);if(d.status!=="complete"){o=s;continue}try{let w=ps(JSON.parse(e.slice(d.start,d.end)),this.context,this.jobId,this.sequence);if(w){let R=this.takeNewExplanations(w);R&&t.push(R)}}catch{}let l=e.slice(d.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;o=d.end+l}return{visibleText:n.trim(),usages:t}}};function kn(i,e){return i?.projectId===e.projectId&&i.version===e.version&&i.restartMode===e.restartMode}function wi(i){return(Array.isArray(i)?i[0]:i)?.split(",")[0]?.trim()||void 0}function So(i){if(!i)return null;try{let e=new URL(i);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function us(i){let e=So(wi(i.origin));if(e)return e;let t=So(wi(i.referer));if(t)return t;let n=wi(i["x-forwarded-host"]);if(!n)return null;let o=wi(i["x-forwarded-proto"])==="https"?"https":"http";return So(`${o}://${n}`)}function ms(i,e,t=5){let n=(c,l)=>(l.completedAt??l.startedAt)-(c.completedAt??c.startedAt),o=[...i].sort(n).slice(0,t),r=i.filter(c=>c.status==="applied"||c.status==="failed").sort(n).slice(0,t),s=e.filter(c=>c.status==="pending"&&c.authorityStatus==="accepted").sort((c,l)=>l.updatedAt-c.updatedAt).slice(0,10),d=s.reduce((c,l)=>(c[l.status]=(c[l.status]??0)+1,c),{});return{recentRuns:o,recentAppliedRuns:r,actionableProposalCounts:d,actionableProposals:s}}import{createHash as Si}from"crypto";import{mkdir as An,readFile as jt,unlink as fl,writeFile as Zt}from"fs/promises";import{dirname as Ti,extname as hl,join as Ne}from"path";var cl={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function ll(i){let e=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i??"")}})();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 fs(i,e){let t=e??ll(i);return{kind:t,...cl[t]}}import{createHash as pl,randomUUID as ul}from"crypto";var hs=i=>`${i}-${ul()}`;function To(i,...e){return`${i}-${pl("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Po(i){return{schemaVersion:1,submissionIds:[hs("submission")],jobId:i.jobId,threadId:i.threadId,artifactIds:[...new Set(i.artifactIds??[])]}}function Rn(i,e=[],t){return{...i,outcomeId:i.outcomeId??hs("outcome"),imprintEvidenceIds:[...new Set([...i.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function ml(i){try{return new URL(i).pathname||"/"}catch{return"/"}}function bi(i,e){return e?[`${i||"/"}:${e}`]:[]}function gs(i){let e=ml(i.url);return[...new Set([...i.annotations.flatMap(t=>bi(t.pathname??e,t.linkedSelector)),...i.styleModifications.flatMap(t=>bi(e,t.durableSelector??t.selector)),...(i.textModifications??[]).flatMap(t=>bi(t.pathname??e,t.durableSelector??t.selector)),...(i.domModifications??[]).flatMap(t=>bi(t.pathname??e,t.durableSelector??t.selector))])]}function ys(i,e){return[...new Set([`screenshot:${e}`,...i.annotations.map(t=>`annotation:${t.id}`),...i.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function xi(i,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=To("submission",i,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:i,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[To("artifact",i,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:To("outcome",i,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function ko(i){let e=i.lifecycleVersion!==1;i.lifecycleVersion=1;for(let t of i.messages)e=xi(i.id,t)||e;return e}function Is(i){let e=i.messages.at(-1),t=[...i.messages].reverse().find(o=>o.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:i.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:i.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:i.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var gl={version:1,threads:{}},vs=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],jn={version:2,updatedAt:0,files:{}};function yl(i){return JSON.stringify(i,null,2)}function Il(i){return Object.fromEntries(vs.flatMap(e=>i[e]===void 0?[]:[[e,i[e]]]))}function vl(i){let e={...i};for(let t of vs)delete e[t];return e}function en(i){let e=i;if(i.error){let t=fs(i.error,i.errorKind);(i.error!==t.message||i.errorKind!==t.kind||i.responseText!==void 0)&&(e={...i,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=_t(e.result,!1),n=_t(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var Pi=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Ne(e,".popmelt");this.legacyFilePath=Ne(t,"threads.json"),this.threadsDir=Ne(t,"threads"),this.indexPath=Ne(this.threadsDir,"index.json"),this.artifactsDir=Ne(t,"artifacts","thread-messages"),this.mediaDir=Ne(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await jt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[o,r]of Object.entries(e.files)){let s=await this.readThread(Ne(this.threadsDir,r));s&&(t[o]=s)}this.cache={version:1,threads:t};let n=!1;for(let o of Object.values(t))n=ko(o)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await jt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(en)}]))},this.index={...jn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))ko(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...gl,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 o of Object.values(t.threads))if(o.elementIdentifiers.some(s=>n.has(s)))return o;return null}async createThread(e,t){let n=await this.load(),o={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=o,await this.persistThread(o),o}async appendMessage(e,t){let o=(await this.load()).threads[e];o&&(xi(e,t),o.messages.push(en(t)),o.updatedAt=Date.now(),await this.persistThread(o))}async appendMessageBeforeQueuedReplies(e,t){let o=(await this.load()).threads[e];if(!o)return;xi(e,t);let r=o.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?o.messages.splice(r,0,en(t)):o.messages.push(en(t)),o.updatedAt=Date.now(),await this.persistThread(o)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(d=>d.jobId===t);if(s.length===0)return!1;for(let d of s)if(Object.assign(d,n),d.error){let c=en(d);Object.assign(d,c),delete d.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(d=>d.role==="assistant"&&d.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let o=(await this.load()).threads[e];if(!o)return;let r=new Set(o.elementIdentifiers);for(let s of t)r.has(s)||o.elementIdentifiers.push(s);o.updatedAt=Date.now(),await this.persistThread(o)}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((o,r)=>r.updatedAt-o.updatedAt),n.slice(0,e).map(o=>{let s=o.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",d=o.messages.filter(p=>p.role==="assistant"),c=p=>{if(p.role!=="assistant")return;if(p.question)return p.question;let g=p.imprintSummary?.grounding;if(g?.question&&!p.imprintSummary?.resolvedAction)return g.question},l=o.messages.findLastIndex(p=>!!c(p)),w=o.messages.findLastIndex(p=>p.role==="human"),R=l>w?c(o.messages[l]):void 0,b=o.messages.at(-1)?.role,k=Array.from(new Set(o.messages.slice(0,Math.max(0,w)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),S=d.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=d.some(p=>!!p.error);return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:s,messageCount:o.messages.length,hasReply:S,hasError:f,lastMessageRole:b,pendingQuestion:R,acknowledgedJobIds:k,elementIdentifiers:o.elementIdentifiers,lifecycle:Is(o)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let o=n.messages.at(-1);if(!o||o.role!=="human"||/^(imprint|memory)-/.test(o.jobId))continue;let r=Rn(o.lifecycle);o.queued&&await this.updateMessage(n.id,o.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:o.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await jt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:o,...r})=>{let s={};if(o?.path)try{let d=await jt(Ne(Ti(this.legacyFilePath),o.path),"utf8");Si("sha256").update(d).digest("hex")===o.sha256&&(s=JSON.parse(d))}catch{}return en({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=Il(e),n=vl(e);if(Object.keys(t).length===0)return n;let o=yl(t),r=Si("sha256").update(o).digest("hex"),s=Ne("artifacts","thread-messages",`${r}.json`);await An(this.artifactsDir,{recursive:!0});try{await jt(Ne(Ti(this.legacyFilePath),s),"utf8")}catch{await Zt(Ne(Ti(this.legacyFilePath),s),o)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(Ti(n)===this.mediaDir)return n;try{let o=await jt(n),r=Si("sha256").update(o).digest("hex"),s=Ne(this.mediaDir,`${r}${hl(n)||".bin"}`);await An(this.mediaDir,{recursive:!0});try{await jt(s)}catch{await Zt(s,o)}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,o])=>[n,await t(o)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,o])=>[n,await Promise.all(o.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,o])=>[n,await Promise.all(o.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await An(this.threadsDir,{recursive:!0});let t=this.index??{...jn,files:{}},n=t.files[e.id]??`${Si("sha256").update(e.id).digest("hex").slice(0,32)}.json`,o=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:o};await Zt(Ne(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Zt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await An(this.threadsDir,{recursive:!0}),this.index=this.index??{...jn,files:{}},await Zt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...jn,files:{}},n=t.files[e];n&&await fl(Ne(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await An(this.threadsDir,{recursive:!0}),await Zt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as wl,open as bl,readFile as xl,rename as Sl,unlink as Tl}from"fs/promises";import{dirname as Pl,join as kl}from"path";var ws={schemaVersion:1,theme:"auto",updatedAt:null};function bs(i){return i==="light"||i==="dark"||i==="auto"?i:null}async function Rl(i,e){await wl(Pl(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`;try{let n=await bl(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
198
|
+
`,"utf8"),await n.sync()}finally{await n.close()}await Sl(t,i)}catch(n){throw await Tl(t).catch(()=>{}),n}}var ki=class{constructor(e){this.path=kl(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await xl(this.path,"utf8")),t=bs(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...ws}}}catch{return{exists:!1,preferences:{...ws}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Rl(this.path,t),t}};function xs(i){return bs(i)!==null}function ht(i,e=240){if(!i)return;let t=i.replace(/\s+/g," ").trim();if(t)return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function tn(i){return i?[ht(i.selector,400),ht(i.context,200),ht(i.reactComponent,120),ht(i.textContent)].filter(e=>!!e):[]}function Ro(i){return[...new Set(i.filter(e=>!!e))]}function Ss(i,e){return Ro([...e,...i.annotations.flatMap(t=>[ht(t.pathname,200),ht(t.linkedSelector,400),...t.elements.flatMap(tn)]),...i.styleModifications.flatMap(t=>tn(t.element)),...(i.textModifications??[]).flatMap(t=>tn(t.element)),...(i.domModifications??[]).flatMap(t=>[...tn(t.element),...tn(t.sourceElement)])])}function Ts(i,e){let t=[...i].reverse().find(n=>n.annotationSnapshot)?.annotationSnapshot;return Ro(t?[...e,...t.annotations.flatMap(n=>[ht(n.pathname,200),ht(n.linkedSelector,400),...n.elements.flatMap(tn)])]:e)}function Al(i){let e=i.instruction?.trim();return e?i.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function Ps(i){let e=i.annotations.flatMap(o=>{let r=Al(o);return r?[{instruction:r,pathname:o.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(o=>o.pathname).filter(Boolean)).size<=1)return e.map(o=>o.instruction).join(`
|
|
197
199
|
|
|
198
200
|
`);let n=new Map;for(let o of e){let r=o.pathname||"(unknown)",s=n.get(r)??[];s.push(o.instruction),n.set(r,s)}return[...n.entries()].map(([o,r])=>`\`${o}\`
|
|
199
201
|
${r.map(s=>`- ${s}`).join(`
|
|
200
202
|
`)}`).join(`
|
|
201
|
-
`)}var
|
|
202
|
-
`)}function Mn(i){return[...new Set(i.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function
|
|
203
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=r?`Using ${r}`:"tool";break}let w=s??d??void 0,
|
|
204
|
-
`)}function
|
|
203
|
+
`)}var ks={name:"@popmelt.com/core",version:"0.10.1",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","codex-plugin","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var dt=ks.version;var Fl=1111,Ul=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],zl=1800*1e3,Wl=3600*1e3,js=45e3,Hl=5e3,Gl=1e4,Vl=2*1024*1024;function Ms(i){return i.length<=1?i[0]??"":["The developer sent these queued steering messages while you were working:","",...i.map((e,t)=>`${t+1}. ${e}`)].join(`
|
|
204
|
+
`)}function Mn(i){return[...new Set(i.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Es(i){let e=i.findLastIndex(o=>o.role==="assistant");if(e<0)return[];let t=i[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=i.slice(0,e).findLast(o=>o.role==="assistant"&&o.imprintSummary?.resolvedAction==="no"&&!!o.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function Kl(i,e){if(e.size===1)return[...i].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function Os(i){if(!i)return!1;try{let e=new URL(i);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Ql(i,e,t){let n=[...t];for(let o of i)if(o.type==="tool_use"){let r=o.tool||"",s=o.file??void 0,d=o.content??void 0,c=s?s.split("/").pop()??s:void 0,l;switch(r){case"Read":l=c?`Reading ${c}`:"Reading file";break;case"Edit":l=c?`Editing ${c}`:"Editing file";break;case"Write":l=c?`Writing ${c}`:"Writing file";break;case"Bash":l=d?d.split(`
|
|
205
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=r?`Using ${r}`:"tool";break}let w=s??d??void 0,R=s?$s(s)?s:Ll(e,s):void 0,b=n[n.length-1];b&&b.kind==="tool_group"&&b.tool===r?b.items.push({label:l,detail:w,...R?{filePath:R}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:l,detail:w,...R?{filePath:R}:{}}]})}return n}function Xl(i,e){if(i.processedIds.length===0&&i.success)return"No accepted decisions were ready for model projection.";if(i.success&&i.proposalId)return"";let t=[];return i.success?t.push("Model suggestion ready."):t.push("Model projection failed."),i.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.`)),i.error&&(t.push(""),t.push(`Error: ${i.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
|
|
206
|
+
`)}function Yl(i,e=96){let t=i.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function _s(i){let e=i.styleModifications.flatMap(s=>{let d=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(c=>`${d}: ${c.property} ${c.original||"unset"} -> ${c.modified||"unset"}`)}),t=(i.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(i.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),o=i.annotations.map(s=>{let d=s.instruction?.trim();if(d)return d;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let c=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${c}`}),r=[...e,...n,...t,...o].map(s=>Yl(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Zl(i,e){let t=i.headers.origin;Os(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 _(i,e,t){i.writeHead(e,{"Content-Type":"application/json"}),i.end(JSON.stringify(t))}var ep=16384,tp=131072;async function _e(i,e=ep){let t=[],n=0;for await(let r of i){let s=typeof r=="string"?Buffer.from(r):r;if(n+=s.length,n>e)throw new Error("Request body too large");t.push(s)}if(t.length===0)return{};let o=JSON.parse(Buffer.concat(t).toString("utf8"));if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object");return o}async function np(i,e){let t=[],n=0;for await(let o of i){let r=typeof o=="string"?Buffer.from(o):o;if(n+=r.length,n>e)throw new Error("Request body too large");t.push(r)}return Buffer.concat(t)}function ip(i,e){let t=i.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function op(i,e){if(!i)return e;let t=i.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,o,r]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(o,16)};${parseInt(r,16)}m${e}\x1B[0m`}function ji(i,e){try{i.res.write(`event: ${e.type}
|
|
205
207
|
data: ${JSON.stringify(e)}
|
|
206
208
|
|
|
207
|
-
`)}catch{}}function nn(i){return i==="claude"||i==="codex"||i==="copilot"?i:void 0}async function
|
|
209
|
+
`)}catch{}}function nn(i){return i==="claude"||i==="codex"||i==="copilot"?i:void 0}async function Mi(i){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${i}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}function rp(i,e){return new Promise((t,n)=>{let o=s=>{i.removeListener("listening",r),n(s)},r=()=>{i.removeListener("error",o),t()};i.once("error",o),i.once("listening",r),i.listen(e,"127.0.0.1")})}async function Ds(i={}){let e=new Date().toISOString(),t=i.port??Fl,n=i.projectRoot??process.cwd(),o=await Cl(n).catch(()=>n),r=Lt(o),s=await Bn(o),d=i.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=i.tempDir??Be(Nl(),"popmelt-bridge"),l=i.maxTurns??40,w=i.maxBudgetUsd??1,R=[...i.allowedTools??Ul],b=i.claudePath??"claude",k=i.copilotPath??"copilot",S=i.provider??"codex",f=i.timeoutMs,p=i.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=i.restartMode??"embedded",v=t,u={},M={claude:b,codex:"codex",copilot:k};for(let[a,I]of Object.entries(M))try{let j=I.includes("/")?I:Ml("which",[I],{encoding:"utf-8"}).trim();u[a]={available:!0,path:j}}catch{u[a]={available:!1,path:null}}function h(a,I){return new Promise(j=>{let y=Rs(I,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,P=$=>{A||(A=!0,j($))},O=setTimeout(()=>{y.kill("SIGTERM"),P(!0)},5e3);y.on("error",()=>{clearTimeout(O),P(!1)}),y.on("close",$=>{clearTimeout(O),P($===0)})})}await Promise.all([(async()=>{u.claude&&(u.claude.models=u.claude.available&&u.claude.path?await ds(u.claude.path).catch(()=>hi):hi)})(),(async()=>{u.codex&&(u.codex.models=u.codex.available&&u.codex.path?await as(u.codex.path).catch(()=>Tn):Tn)})(),(async()=>{u.copilot&&(u.copilot.models=u.copilot.available&&u.copilot.path?await ss(u.copilot.path).catch(()=>[Pn]):[Pn])})()]);let[m,E,D]=await Promise.all([to(o),no(o),io(o,u.copilot?.path??k)]);u.claude&&(u.claude.mcp=m),u.codex&&(u.codex.mcp=E),u.copilot&&(u.copilot.mcp=D),m.found&&m.name&&R.push(`mcp__${m.name}__*`),await El(c,{recursive:!0}),Cs(c).catch(()=>{});let T=new yi(1),C=new Zn,z=new ti(js),X=null,G=0,Y=!1,x=()=>{G+=1,Y=!1,X&&clearTimeout(X),X=null},Q=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},L=()=>{if(g!=="detached"||z.size>0||Y)return;Y=!0;let a=++G,I=Date.now()+Gl,j=()=>{if(a!==G)return;if(z.size>0){x();return}if(!(T.isRunning||T.depth>0||C.isRunning||C.depth>0)||Date.now()>=I){Y=!1,X=setTimeout(Q,50),X.unref?.();return}X=setTimeout(j,250),X.unref?.()};j()},K=new Set,H=new Pi(o),B=await H.recoverInterruptedTurns();B>0&&console.warn(`[Popmelt] Recovered ${B} interrupted thread turn(s) from durable history.`);let V=new Kn(o);V.sweep();let W=new ui(o),ee=new Nt(o,r);try{let a=await ee.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let ke=new ki(o),Je=new Wn(o),ue=new Yn(o,{claudePath:b,provider:S,timeoutMs:f,loadProjectableDecisions:a=>W.getProjectableDecisions(a),onEvent:a=>{for(let I of K)ji(I,a)}}),Ce=new Dn({projectRoot:o,threadStore:H,memoryService:W,imprintService:ee,loadConcreteModel:()=>ue.loadModel()});W.beginAutomaticInitialization({writerVersion:dt}).then(async a=>{a.state==="ready"?(await W.migrateImprintSnapshot(),await W.syncImprintGraph(),await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),S!=="copilot"&&(await ue.getUnprojectedPatternDecisions()).length>0&&await Xe({provider:S,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${v}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let gt=20,on=300*1e3,Re=[];function nt(){let a=Date.now()-on;for(;Re.length>0&&(Re[0].completedAt<a||Re.length>gt);)Re.shift()}let yt=new Map,It=null,En;T.addListener((a,I,j)=>{for(let y of K)(!j||!y.sourceId||y.sourceId===j)&&ji(y,a)}),C.addListener((a,I,j)=>{for(let y of K)(!j||!y.sourceId||y.sourceId===j)&&ji(y,a)}),C.setProcessor(async a=>{let I=a.provider??S;try{let j=await ue.run({provider:I,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let y=await ue.loadRuns(),A=j.runId?y.runs.find(O=>O.id===j.runId):void 0;if(j.success&&j.proposalId){let O=await ue.findModelProposal(j.proposalId),$=await ue.loadModel(),q=O?Ir(O,$):null;if(O&&q){let N=O.decisionIds.map(J=>({decisionId:J,status:"projected"}));await W.applyModelProjection({runId:O.runId??O.id,presentationJobId:O.presentationJobId,decisionIds:O.decisionIds,changes:q.map(J=>({path:J.path,value:J.value,decisionIds:J.decisionIds})),coverage:N}),await ue.applySelectedModelProposal(O.id,q.map(J=>({path:J.path,value:J.value})),q.map(J=>({group:J.path[0]==="rules"||J.path[0]==="components"||J.path[0]==="tokens"?J.path[0]:"model",label:J.label??J.id,detail:J.rationale,path:J.path,value:J.value})),"automatic")}}let P=Xl(j,A);if(a.threadId&&(await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:I})),j.success)a.status="done",a.result=P,C.broadcast({type:"done",jobId:a.id,success:!0,responseText:P,threadId:a.threadId},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt();else{if(a.status="error",a.error=j.error??"Projection failed",a.threadId){let O=`Model projection failed.
|
|
208
210
|
|
|
209
|
-
${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}catch(
|
|
211
|
+
${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:O,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}catch(j){if(a.status==="cancelled")return;if(a.status="error",a.error=j instanceof Error?j.message:String(j),a.threadId){let y=`Model projection failed.
|
|
210
212
|
|
|
211
|
-
${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}),
|
|
213
|
+
${a.error}`;await H.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})||await H.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:y,error:a.error,model:a.model,provider:I})}C.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:I,model:a.model},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),nt()}}),T.setProcessor(async a=>{let I=a,j=I._replyPrompt,y=I._replyText,A=I._replyImagePaths,P=a.provider??S,O=!!(a.surfacedProposalIds?.length&&j),$=!O&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&y!==void 0&&await H.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let ne=await H.getThread(a.threadId);if(ne){for(let Ie=ne.messages.length-1;Ie>=0;Ie--)if(ne.messages[Ie].sessionId){q=ne.messages[Ie].sessionId;break}}}O&&(q=void 0);let N;if(q&&j){if(N=y??j,A&&A.length>0){N+=`
|
|
212
214
|
|
|
213
|
-
The developer attached reference images with their reply:`;for(let ne of
|
|
215
|
+
The developer attached reference images with their reply:`;for(let ne of A)N+=`
|
|
214
216
|
Attached image: use the Read tool to view the image at: ${ne}`}a.kind==="synthesize"?N+=`
|
|
215
217
|
|
|
216
218
|
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:N+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(q)N=xn(a.feedback,a.imagePaths,a.attachmentFiles)+`
|
|
@@ -219,20 +221,20 @@ Follow the developer's instructions. If they ask for changes, apply them to the
|
|
|
219
221
|
|
|
220
222
|
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(P!=="codex"?`
|
|
221
223
|
|
|
222
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let ne=!
|
|
224
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let ne=!j&&a.threadId?await H.getThreadHistory(a.threadId):void 0,Ie=j?null:await ue.loadModel();N=j??es(a.screenshotPath,a.feedback,{threadHistory:ne&&ne.length>0?ne:void 0,provider:P,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:Ie??void 0,screenshotPaths:a.screenshotPaths})}N+=cn(a.memoryReview),$&&(N+=Jt(a.imprintContext,{requestText:y??Ct(a.feedback)})),a.threadId&&!O&&(N+=`
|
|
223
225
|
|
|
224
|
-
${
|
|
226
|
+
${Zr}`),N+=`
|
|
225
227
|
|
|
226
|
-
${Xr}`;let B=tp(a.color,`[\u22B9 ${v}:${a.id}]`),he=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${B} Reviewing ${he} (provider: ${P})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let F=new ui(a.id),se=new Ii(a.id,a.imprintContext),me=(ne,Ie)=>{if(ne.type==="delta"&&"text"in ne){let Oe=se.push(ne.text),Fe=F.push(Oe.visibleText);Fe.visibleText&&(S.accumulateText(Ie,"response",Fe.visibleText),S.broadcast({...ne,text:Fe.visibleText},Ie,a.sourceId));for(let Ee of Fe.orientations)S.broadcast({type:"orientation",jobId:Ie,orientation:Ee},Ie,a.sourceId);for(let Ee of Oe.usages)S.broadcast({type:"imprint_used",jobId:Ie,usage:Ee},Ie,a.sourceId);return}else ne.type==="thinking"&&"text"in ne&&S.accumulateText(Ie,"thinking",ne.text);S.broadcast(ne,Ie,a.sourceId)},{process:te,result:ge}=P==="codex"?Un(a.id,{prompt:N,projectRoot:o,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:O?"read-only":void 0,configOverrides:Jn(a.agentSettings),onEvent:me}):P==="copilot"?lr(a.id,{prompt:N,projectRoot:o,resumeSessionId:q,model:a.model,timeoutMs:f,copilotPath:u.copilot?.path??R,onEvent:me}):Bn(a.id,{prompt:N,projectRoot:o,maxTurns:l,maxBudgetUsd:w,allowedTools:O?["Read"]:k,claudePath:T,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:me});S.setActiveProcess(a.id,te);let oe=await ge,ve=[...(oe.fileEdits??[]).map(ne=>ne.file_path),...(oe.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],Te=se.finalize(oe.text),pe=wo(Te.visibleText,a.id),Z=F.finalize(Te.visibleText),Se=pe.visibleText,We=ns(Se),ye=$?Jt(Se,{context:a.imprintContext,requestText:y??Ct(a.feedback),applicationOccurred:ve.length>0||We.some(ne=>ne.status==="resolved")}):{visibleText:Se,draft:void 0,error:void 0},He=ye.visibleText,je=$?ye.error?{state:ye.error.includes("missing")?"missing":"invalid",reason:ye.error}:ye.draft?.decision==="none"?{state:"none",reason:ye.draft.reason}:ye.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ne of Z.orientations)S.broadcast({type:"orientation",jobId:a.id,orientation:ne},a.id,a.sourceId);for(let ne of Te.usages)S.broadcast({type:"imprint_used",jobId:a.id,usage:ne},a.id,a.sourceId);if(a.result=He,oe.success){console.log(`${B} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${B} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${B} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),a.status="done";let ne=es(Se),Ie=We;if(Ie.length>0&&a.annotationIds&&a.annotationIds.length>0){let de=new Set(a.annotationIds);Ie.every(Ye=>de.has(Ye.annotationId))||(Ie=Ie.map((Ye,bt)=>({...Ye,annotationId:a.annotationIds[bt%a.annotationIds.length]})))}let Oe=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):oe.toolsUsed,Fe=S.getBufferedEvents(a.id),Ee=Kl(Fe?.events??[],o,pe.segments),Ae,re=Gr(Se),U=Hr(Se);if(U)if(!(a.memoryReview?.packets.some(ce=>ce.proposalId===U.proposalId)||a.surfacedProposalIds?.includes(U.proposalId)))Ae={status:"rejected",action:U.action,proposalId:U.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Ae=await W.commitConversationalReview(U)}catch(ce){Ae={status:"rejected",action:U.action,proposalId:U.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=is(Se,ve.length),fe,Ge,Eo,_o,Xs=a.imprintContext?.pendingGroundingExplanationIds??[];if(ye.draft){let de=ye.draft.decision==="recognize"?[ye.draft.explanationId]:[],ce=ye.draft.decision==="recognize"?de:[...ye.draft.usedExplanationIds??[],...ye.draft.appliedExplanationIds??[]],Ye=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];ce.length>0&&(Eo=[...new Set(ce)]),Ye.length>0&&(_o=[...new Set(Ye)])}ye.draft?.decision==="none"&&ee.recordNoop(ye.draft.reason);let Cn=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Cn&&!U&&!re){let de=a.imprintContext?.explanations.find(ce=>ce.id===Cn.explanationId&&ce.state==="grounded");de?Ge={explanationId:de.id,title:Cn.summary.title,detail:Cn.summary.detail,statement:de.statement}:je={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Ci=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(a.threadId&&Ci&&!U&&!re)try{fe=await ee.capture(Ci,{threadId:a.threadId,jobId:a.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:Xs,applicationOccurred:ve.length>0||Ie.some(de=>de.status==="resolved")}),fe?(je={state:"mutated"},await W.recordImprintEvidence({summary:fe,threadId:a.threadId,jobId:a.id}).catch(de=>console.warn(`${B} 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(`${B} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else Ci&&(je={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ye.error&&console.warn(`${B} Ignored invalid imprint block: ${ye.error}`),(je.state==="missing"||je.state==="invalid")&&ee.recordAssessmentFailure(je.state);let $i=fe?.transactionId;if(a.threadId&&fe&&!fe.grounding){let de=await H.getThread(a.threadId),ce=new Set(fe.changes.map(bt=>bt.explanationId)),Ye=de?Vl(de.messages,ce):void 0;if(Ye?.imprintSummary){let bt=Ye.imprintSummary;await H.updateAssistantMessage(a.threadId,Ye.jobId,{imprintSummary:{...bt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(bt.additionalObservationCount??0)+1,coalescedTransactionIds:[...bt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let Oi=an({question:ne,resolutions:Ie,changedFiles:ve,decisionRequired:!!re,imprintTransactionId:$i,groundingRequired:!!fe?.grounding}),Ys=Ee?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Et=a.lifecycle?Rn(a.lifecycle,$i?[$i]:[],je):void 0;if(a.threadId){let de=O?re?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":He;await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:de,resolutions:!O&&Ie.length>0?Ie:void 0,question:O?void 0:ne??void 0,sessionId:oe.sessionId,toolsUsed:O?void 0:Oe,editEvents:!O&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!O&&Ee&&Ee.length>0?Ee:void 0,turn:{phase:"complete",orientation:Ys,result:Oi},result:Oi,memoryReviewCard:re??void 0,memoryReceipt:Ae,imprintSummary:fe,imprintRecognition:Ge,imprintUsedExplanationIds:Eo,imprintAppliedExplanationIds:_o,modelDetails:ae.length>0?ae:void 0,model:a.model,provider:P,...Et?{lifecycle:Et}:{}})}if(a.threadId&&!U&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let de=a.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await W.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:y??(Ct(a.feedback)||"[request unavailable]"),responseSummary:ne??He,outcome:ne?"question_asked":Ie.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:P,model:a.model,sessionId:oe.sessionId},subjectHints:de,filePaths:[...(oe.fileEdits??[]).map(ce=>ce.file_path),...(oe.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>Cs(ce)?Jl(o,ce):ce),resolutions:Ie.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Et?.submissionIds,outcomeId:Et?.outcomeId,imprintEvidenceIds:Et?.imprintEvidenceIds,imprintAssessment:Et?.imprintAssessment})}catch(ce){console.warn(`${B} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}Ae?.status==="committed"&&Ae.decisionId&&P!=="copilot"&&await Xe({provider:P,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Ae.decisionId}`}),ne&&(console.log(`${B} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${K.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),S.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:ne,annotationIds:a.annotationIds},a.id,a.sourceId)),ae.length>0&&(console.log(`${B} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),S.broadcast({type:"novel_patterns",jobId:a.id,patterns:ae,threadId:a.threadId},a.id,a.sourceId)),S.broadcast({type:"done",jobId:a.id,success:!0,resolutions:Ie.length>0?Ie:void 0,responseText:He,threadId:a.threadId,annotationIds:a.annotationIds,result:Oi},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${B} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:P,...a.lifecycle?{lifecycle:Rn(a.lifecycle)}:{}}),S.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:P,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});nt()});let be=Ol(async(a,I)=>{if(Yl(a,I),a.method==="OPTIONS"){I.writeHead(204),I.end();return}let A=a.url||"/",y=A.split("?")[0],j=new URL(A,`http://127.0.0.1:${v}`),P=j.pathname,O=ep(a,j);if(O&&O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:Ri(o)});return}if(P.startsWith("/ambient/")&&O!==r){_(I,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:r,requestProjectId:O});return}if(a.headers.origin){if(!$s(a.headers.origin)){_(I,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:Ri(o)});return}}try{if(P.startsWith("/ambient/"))await lt(a,I,P);else if(a.method==="POST"&&P==="/draft-attachments"){let $=j.searchParams.get("annotationId")?.trim()??"",q=j.searchParams.get("name")?.trim()??"",N=j.searchParams.get("kind"),B=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(I,400,{error:"A valid annotationId is required."});return}if(N!=="svg"&&N!=="text"||N==="svg"&&B!=="image/svg+xml"||N==="text"&&B!=="text/plain"){_(I,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let he=await Zl(a,Gl);if(he.length===0){_(I,400,{error:"Attachment is empty."});return}let F=await V.stage({annotationId:$,name:q,mimeType:B,kind:N,data:he});_(I,201,{attachment:{id:F.id,name:F.name,mimeType:F.mimeType,size:F.size,kind:F.kind}})}else if(a.method==="POST"&&P==="/draft-attachments/claim"){let $=await _e(a),q=Array.isArray($.ids)?$.ids.filter(N=>typeof N=="string").slice(0,100):[];await V.claim(q),_(I,200,{ok:!0})}else if(a.method==="DELETE"&&P.startsWith("/draft-attachments/"))await V.release([P.slice(19)]),_(I,200,{ok:!0});else if(a.method==="POST"&&P==="/send")await pt(a,I);else if(a.method==="POST"&&P==="/capture/native"){if(!p){_(I,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await _e(a),q=typeof $.pageUrl=="string"?$.pageUrl:"",N=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!q||!N){_(I,400,{error:"pageUrl and clip are required."});return}let B=await Ar(p,{pageUrl:q,clip:{x:Number(N.x),y:Number(N.y),width:Number(N.width),height:Number(N.height)},scale:typeof $.scale=="number"?$.scale:1});I.writeHead(200,{"Content-Type":"image/webp","Content-Length":B.length,"Cache-Control":"no-store"}),I.end(B)}else if(a.method==="GET"&&P==="/events")vt(a,I);else if(a.method==="GET"&&P==="/status")await Mi(a,I,O);else if(a.method==="GET"&&P==="/ui-preferences")await rn(I);else if(a.method==="PATCH"&&P==="/ui-preferences")await Le(a,I);else if(a.method==="PATCH"&&P==="/config")await Ei(a,I);else if(a.method==="POST"&&P==="/leases"){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await _e(a),q=typeof $.leaseId=="string"?$.leaseId.trim():"",N=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!q||q.length>128){_(I,400,{error:"A valid leaseId is required."});return}b();let B=z.acquire(q,N);_(I,201,{ok:!0,lease:B,ttlMs:js})}catch{_(I,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(P.slice(8))}catch{_(I,400,{error:"Invalid lease id."});return}if(!$){_(I,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=z.heartbeat($);if(!q){_(I,404,{error:"Lease not found."});return}_(I,200,{ok:!0,lease:q})}else{let q=z.release($);_(I,q.found?200:404,{ok:q.found}),q.becameEmpty&&L()}}else if(a.method==="POST"&&P==="/shutdown"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0}),setTimeout(Q,100)}else if(a.method==="POST"&&P==="/restart"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of K)try{$.res.end()}catch{}be.close(()=>{ks(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&P==="/capabilities")_(I,200,{providers:u});else if(P.startsWith("/imprint/"))await it(a,I,P);else if(P.startsWith("/memory/"))await $e(a,I,P);else if(a.method==="POST"&&P==="/mcp/install")await Bs(a,I);else if(a.method==="POST"&&P==="/reply")await ut(a,I);else if(a.method==="POST"&&P==="/cancel")qe(a,I);else if(a.method==="POST"&&P==="/materialize")_(I,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&P==="/materialization-runs")_(I,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&P==="/projection-runs"){let $=await ue.loadRuns();_(I,200,$)}else if(a.method==="GET"&&P==="/projection/proposals"){let $=await ue.loadModelProposals();_(I,200,$)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let $=P.slice(22,-15);await wt($,a,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let $=P.slice(22,-6);await Mt($,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let $=P.slice(22,-8);await _i($,a,I)}else if(P.startsWith("/model/proposals/"))_(I,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&P==="/model/component")await Ls(a,I);else if(a.method==="DELETE"&&P==="/model/component")await qs(a,I);else if(a.method==="PATCH"&&P==="/model/token")await Fs(a,I);else if(a.method==="DELETE"&&P==="/model/token")await Us(a,I);else if(a.method==="POST"&&P==="/model/consolidate")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&P==="/model/synthesize")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&P==="/model"){let $=await ue.loadModel();_(I,200,{model:$})}else if(a.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let $=P.slice(6,P.length-7),q=parseInt(j.searchParams.get("afterSeq")??"-1",10),N=S.getBufferedEvents($,isNaN(q)?-1:q);N?_(I,200,N):_(I,404,{error:"Unknown job"})}else if(a.method==="GET"&&y.startsWith("/files/"))await Gs(y.slice(7),I);else if(a.method==="GET"&&P==="/threads/recent"){let $=Math.min(Math.max(parseInt(j.searchParams.get("limit")??"5",10)||5,1),20),q=await H.listRecent($);_(I,200,q)}else if(a.method==="GET"&&P.startsWith("/decision/")){let $=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(I,400,{error:"Invalid decision id"});else{let q=await H.getThread($),N=[...q?.messages??[]].reverse().find(B=>B.annotationSnapshot);if(q&&N?.annotationSnapshot){let B=[...q.messages].reverse().find(he=>he.resolutions?.length);_(I,200,{decision:{id:q.id,createdAt:N.timestamp,url:N.annotationSnapshot.url,viewport:N.annotationSnapshot.viewport,color:N.annotationSnapshot.color,annotations:N.annotationSnapshot.annotations,resolutions:B?.resolutions??[]},authority:"thread_snapshot"})}else{let B=await Be.loadDecision($);B?_(I,200,{decision:B,authority:"legacy_archive"}):_(I,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&P.startsWith("/thread/")){let $=P.slice(8);await Vs($,I)}else if(a.method==="DELETE"&&P.startsWith("/thread/")){let $=P.slice(8);await Ks($,I)}else a.method==="GET"&&(P==="/canvas"||P==="/canvas/")?zs(a,I):a.method==="GET"&&P==="/canvas/manifest"?await Ws(I):a.method==="GET"&&P==="/canvas/app.mjs"?await Hs(I):_(I,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(I,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function lt(a,I,A){if(a.method!=="POST"){_(I,405,{error:"Ambient endpoints accept POST requests only."});return}let y=await _e(a),j=typeof y.sessionId=="string"?y.sessionId.trim():"",P=typeof y.turnId=="string"?y.turnId.trim():"",O=typeof y.executionOwner=="string"?y.executionOwner:void 0;if(A==="/ambient/context"){let $=typeof y.query=="string"?y.query.trim():"";if(!$){_(I,400,{error:"query is required."});return}let q=Array.isArray(y.subjectHints)?y.subjectHints.filter(N=>typeof N=="string"&&!!N.trim()).slice(0,20):void 0;_(I,200,await Ce.expandContext({query:$,subjectHints:q}));return}if(A==="/ambient/turns/assess"){let $=typeof y.threadId=="string"?y.threadId.trim():"",q=typeof y.jobId=="string"?y.jobId.trim():"",N=typeof y.assessmentText=="string"?y.assessmentText.trim():"";if(!$||!q||!N){_(I,400,{error:"threadId, jobId, and assessmentText are required."});return}let B=Array.isArray(y.semanticCandidates)?y.semanticCandidates.flatMap(F=>{if(!F||typeof F!="object"||Array.isArray(F))return[];let se=F,me=typeof se.claim=="string"?se.claim.trim():"",te=typeof se.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(se.proposedKind)?se.proposedKind:void 0;return me?[{claim:me,rationale:typeof se.rationale=="string"?se.rationale.trim():void 0,proposedKind:te,sourceText:typeof se.sourceText=="string"?se.sourceText.trim():void 0}]:[]}).slice(0,8):[],he=await Ce.assess({threadId:$,jobId:q,assessmentText:N,semanticCandidates:B});_(I,he.status==="recorded"?200:404,he);return}if(!j||!P||j.length>256||P.length>256){_(I,400,{error:"Valid sessionId and turnId values are required."});return}if(A==="/ambient/turns/prepare"){let $=typeof y.prompt=="string"?y.prompt.trim():"";if(!$){_(I,400,{error:"prompt is required."});return}_(I,200,await Ce.prepare({sessionId:j,turnId:P,prompt:$,model:typeof y.model=="string"?y.model:void 0,executionOwner:O}));return}if(A==="/ambient/turns/event"){let $=typeof y.toolName=="string"?y.toolName.trim():"";if(!$){_(I,400,{error:"toolName is required."});return}_(I,200,await Ce.recordEvent({sessionId:j,turnId:P,executionOwner:O,toolName:$,toolUseId:typeof y.toolUseId=="string"?y.toolUseId:void 0,toolInput:y.toolInput,toolResponse:y.toolResponse}));return}if(A==="/ambient/turns/complete"){_(I,200,await Ce.complete({sessionId:j,turnId:P,executionOwner:O,lastAssistantMessage:typeof y.lastAssistantMessage=="string"?y.lastAssistantMessage:void 0,model:typeof y.model=="string"?y.model:void 0}));return}_(I,404,{error:"Ambient endpoint not found."})}async function $e(a,I,A){try{if(a.method==="GET"&&A==="/memory/status"){_(I,200,await W.status());return}if(a.method==="GET"&&A==="/memory/diagnostics"){_(I,200,await W.diagnostics());return}if(a.method==="GET"&&A==="/memory/model-view"){_(I,200,await W.getModelView());return}if(a.method==="GET"&&A==="/memory/imprint-view"){let y=await H.load(),j=[...new Set(Object.values(y.threads).flatMap(P=>Mn(P.messages)))];_(I,200,await W.getImprintView(j,new Set(Object.keys(y.threads))));return}if(a.method==="POST"&&A==="/memory/constraints"){let y=await _e(a),j=typeof y.reactComponent=="string"?y.reactComponent.trim():"",P=await W.getModelView(),O=j?P.entries.filter($=>$.key===`components.${j}`||$.key.startsWith(`components.${j}.`)):[];_(I,200,{modelEntries:O});return}if(a.method==="POST"&&A==="/memory/conversation-action"){let y=await _e(a),j=typeof y.threadId=="string"?y.threadId:"",P=typeof y.proposalId=="string"?y.proposalId:"",O=String(y.action);if(!j||!P||!["accept","edit_and_accept","reject","defer"].includes(O)){_(I,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await H.getThread(j),q=$?.messages.find(pe=>pe.memoryReviewCard?.proposalId===P)?.memoryReviewCard,N=$?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===P),B=$?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await W.findPendingProposalsForThread(j)).find(pe=>pe.proposalId===P):void 0,he=typeof y.kind=="string"&&["principle","preference","rule","constraint"].includes(y.kind)?y.kind:void 0,F=q?.kind??N?.proposedKind??B?.proposedKind??he;if(!$||!q&&!N&&!B){_(I,409,{error:"This decision candidate was not surfaced in the thread."});return}if((O==="accept"||O==="edit_and_accept")&&!F){_(I,400,{error:"The decision kind is required to accept this candidate."});return}let se=await ue.findModelProposalsByThread(j),me=(await Promise.all(se.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Z=>W.findPendingProposalForLegacyDecision(Z)))).some(Z=>Z?.proposalId===P)})))).find(pe=>pe.matches)?.proposal,te={proposalId:P,action:O,kind:F,claim:O==="edit_and_accept"&&typeof y.claim=="string"?y.claim.trim():void 0,reason:O==="defer"?void 0:`The owner explicitly chose ${O.replaceAll("_"," ")} from the decision review card.`,taskContext:O==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:O==="defer"?["different_action","owner_request"]:void 0};if(te.action==="edit_and_accept"&&!te.claim){_(I,400,{error:"Edited decision wording is required."});return}let ge=await W.commitConversationalReview(te),oe=`memory-${ct().slice(0,8)}`,ve=O==="accept"?"> Accepted decision":O==="edit_and_accept"?"> Edited and accepted decision":O==="reject"?"> Rejected decision":"> Deferred decision";await H.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:oe,replyToQuestion:ve}),await H.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:oe,responseText:"",memoryReceipt:ge,provider:nn(typeof y.provider=="string"?y.provider:void 0),model:typeof y.model=="string"?y.model:void 0}),ge.status==="committed"&&me&&await ue.dismissModelProposal(me.id);let Te=nn(typeof y.provider=="string"?y.provider:void 0);ge.status==="committed"&&ge.decisionId&&Te!=="copilot"&&await Xe({provider:Te,model:typeof y.model=="string"?y.model:void 0,agentSettings:qt(y),threadId:j,reason:`Project accepted decision ${ge.decisionId}`}),_(I,ge.status==="committed"?200:409,{receipt:ge});return}if(a.method==="POST"&&A==="/memory/analyze"){let y=await _e(a),j=await W.analyzeLegacy({projectKey:typeof y.projectKey=="string"?y.projectKey:void 0}),P=Object.fromEntries([...new Set(j.issues.map(O=>O.code))].map(O=>[O,j.issues.filter($=>$.code===O).length]));_(I,200,{...j,issues:void 0,issueCounts:P});return}if(a.method==="POST"&&A==="/memory/review"){let y=await _e(a),j=await W.review(yo(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(a.method==="POST"&&A==="/memory/context"){let y=await _e(a),j=await W.contextualize(yo(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(a.method==="POST"&&A==="/memory/initialize"){let y=await _e(a),j=await W.initializeFromLegacy({confirmed:y.confirm===!0,projectKey:typeof y.projectKey=="string"?y.projectKey:void 0,writerVersion:dt});_(I,201,{status:j.status,report:{source:j.report.source,imported:j.report.imported,unresolvedAcceptance:j.report.unresolvedAcceptance,deferredModelEntries:j.report.deferredModelEntries,proofCases:j.report.proofCases,schemaIssues:j.report.schemaIssues}});return}if(a.method==="POST"&&A==="/memory/plan"){let y=await _e(a),j=await W.planReview(go(y.command),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,j.result.ok?200:422,j);return}if(a.method==="POST"&&A==="/memory/commit"){let y=await _e(a),j=y.transaction&&typeof y.transaction=="object"&&!Array.isArray(y.transaction)?y.transaction:{},P=await W.commitReview(go(y.command),{transactionId:typeof j.transactionId=="string"?j.transactionId:"",committedAt:typeof j.committedAt=="string"?j.committedAt:""});_(I,200,{status:await W.status(),journal:P.report});return}if(a.method==="POST"&&A==="/memory/recover"){let y=await _e(a),j=await W.recover(y.confirm===!0);_(I,200,{status:await W.status(),journal:j.report});return}_(I,404,{error:"Memory endpoint not found."})}catch(y){let j=y instanceof Error?y.message:String(y),P=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(j),O=/required|invalid|unsupported|expected|must be|confirmation/i.test(j);if(P||O){_(I,P?409:400,{error:j});return}throw y}}async function it(a,I,A){if(a.method==="GET"&&A==="/imprint/status"){let[y,j]=await Promise.all([ee.store.load(),H.load()]),P=[...new Set(Object.values(j.threads).flatMap(O=>Mn(O.messages)))].filter(O=>y.graph.explanations.some($=>$.id===O&&$.state==="testing"));_(I,200,{state:"ready",head:y.graph.head,updatedAt:y.graph.updatedAt,explanationCount:y.graph.explanations.filter(O=>O.state!=="retired").length,concreteCount:y.graph.concrete.length,relationCount:y.graph.relations.length,pendingGroundingCount:P.length,recoveredTransactions:y.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&A==="/imprint/action"){let y=await _e(a),j=typeof y.threadId=="string"?y.threadId:"",P=typeof y.transactionId=="string"?y.transactionId:"",O=String(y.action);if(!j||!P||!["yes","this_time","no"].includes(O)){_(I,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await H.getThread(j),N=[...q?.messages??[]].reverse().find(te=>te.role==="assistant"&&te.imprintSummary?.transactionId===P),B=N?.imprintSummary;if(!q||!N||!B){_(I,409,{error:"This imprint summary is not available in the thread."});return}if(B.resolvedAction){_(I,409,{error:"This imprint summary has already been resolved."});return}let he=`imprint-${ct().slice(0,8)}`;await ee.applyGroundingAction({summary:B,action:O,threadId:j,jobId:he}),O!=="no"&&await W.recordImprintEvidence({summary:B,action:O,threadId:j,jobId:he}).catch(te=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",te));let F=_t(N.result,!!N.question),se=N.turn?{...N.turn,result:_t(N.turn.result,!!N.question)}:void 0;await H.updateAssistantMessage(j,N.jobId,{imprintSummary:{...B,resolvedAction:O},...F?{result:F}:{},...se?{turn:se}:{}});let me={yes:"> Yes",this_time:"> This time",no:"> No"};if(await H.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:he,replyToQuestion:me[O]}),O==="no"){let te="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",ge=an({question:te});await H.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:he,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:te,turn:{phase:"complete",orientation:[],result:ge},result:ge})}_(I,200,{ok:!0,action:O});return}_(I,404,{error:"Imprint endpoint not found."})}async function pt(a,I){let{screenshot:A,feedback:y,color:j,provider:P,model:O,reasoningEffort:$,serviceTier:q,sourceId:N,pastedImages:B,pageScreenshots:he}=await Io(a),F;try{F=JSON.parse(y)}catch{_(I,400,{error:"Invalid feedback JSON"});return}let se=F.annotations.flatMap(re=>(re.attachments??[]).map(U=>({id:U.id,annotationId:re.id}))),me;try{me=se.length>0?await V.promote(se):void 0}catch(re){_(I,409,{error:re instanceof Error?re.message:"Draft attachment unavailable."});return}let te=ct().slice(0,8),ge={};if(he.length>0)for(let re of he){let U=encodeURIComponent(re.pathname),ae=Je(c,`screenshot-${te}-${U}.webp`);await ki(ae,re.data),ge[re.pathname]=ae}let oe=Je(c,`screenshot-${te}.webp`);await ki(oe,A);let ve={};if(B.length>0)for(let re of B){let U=Je(c,`pasted-${te}-${re.annotationId}-${re.index}.webp`);await ki(U,re.data),ve[re.annotationId]||(ve[re.annotationId]=[]),ve[re.annotationId].push(U)}let Te=hs(F),pe;if(Te.length>0){let re=await H.findContinuationThread(Te);re?(pe=re.id,await H.addElementIdentifiers(pe,Te)):pe=(await H.createThread(`thread-${ct()}`,Te)).id}else pe=(await H.createThread(`thread-${ct()}`,[])).id;let Z=F.annotations.map(re=>re.id),Se=Object.keys(ge).length>0,We=await dn(W,F,Te,re=>console.warn(`[\u22B9 ${v}:${te}] Contextual memory unavailable; continuing without it:`,re instanceof Error?re.message:String(re))),ye=(await H.getThread(pe))?.messages??[],He=await ee.contextualize({text:Ct(F),subjectHints:xs(F,Te),pendingGroundingExplanationIds:Mn(ye),correctionExplanationIds:Ms(ye)}).catch(re=>{console.warn(`[\u22B9 ${v}:${te}] Imprint context unavailable; continuing without it:`,re instanceof Error?re.message:String(re))}),je=To({jobId:te,threadId:pe,artifactIds:gs(F,te)}),ne={id:te,status:"queued",screenshotPath:oe,feedback:F,createdAt:Date.now(),color:j,threadId:pe,annotationIds:Z,provider:nn(P),model:O||void 0,agentSettings:qt({reasoningEffort:$,serviceTier:q}),...Object.keys(ve).length>0?{imagePaths:ve}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:N||void 0,...Se?{screenshotPaths:ge}:{},...We?{memoryReview:We}:{},...He?{imprintContext:He}:{},lifecycle:je},Ie=new Set(F.annotations.map(re=>re.pathname).filter(Boolean)),Oe;if(Ie.size>1){let re=new Map;for(let U of F.annotations){let ae=U.pathname||"(unknown)";re.has(ae)||re.set(ae,[]),re.get(ae).push(U.instruction||Es({...F,annotations:[U]}))}Oe=[...re.entries()].map(([U,ae])=>`\`${U}\`
|
|
228
|
+
${Yr}`;let J=op(a.color,`[\u22B9 ${v}:${a.id}]`),he=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${J} Reviewing ${he} (provider: ${P})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let F=new mi(a.id),se=new vi(a.id,a.imprintContext),me=(ne,Ie)=>{if(ne.type==="delta"&&"text"in ne){let Oe=se.push(ne.text),Fe=F.push(Oe.visibleText);Fe.visibleText&&(T.accumulateText(Ie,"response",Fe.visibleText),T.broadcast({...ne,text:Fe.visibleText},Ie,a.sourceId));for(let Ee of Fe.orientations)T.broadcast({type:"orientation",jobId:Ie,orientation:Ee},Ie,a.sourceId);for(let Ee of Oe.usages)T.broadcast({type:"imprint_used",jobId:Ie,usage:Ee},Ie,a.sourceId);return}else ne.type==="thinking"&&"text"in ne&&T.accumulateText(Ie,"thinking",ne.text);T.broadcast(ne,Ie,a.sourceId)},{process:te,result:ge}=P==="codex"?zn(a.id,{prompt:N,projectRoot:o,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:O?"read-only":void 0,configOverrides:Jn(a.agentSettings),onEvent:me}):P==="copilot"?pr(a.id,{prompt:N,projectRoot:o,resumeSessionId:q,model:a.model,timeoutMs:f,copilotPath:u.copilot?.path??k,onEvent:me}):Ln(a.id,{prompt:N,projectRoot:o,maxTurns:l,maxBudgetUsd:w,allowedTools:O?["Read"]:R,claudePath:b,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:me});T.setActiveProcess(a.id,te);let oe=await ge,ve=[...(oe.fileEdits??[]).map(ne=>ne.file_path),...(oe.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],Te=se.finalize(oe.text),pe=bo(Te.visibleText,a.id),Z=F.finalize(Te.visibleText),Se=pe.visibleText,We=is(Se),ye=$?Bt(Se,{context:a.imprintContext,requestText:y??Ct(a.feedback),applicationOccurred:ve.length>0||We.some(ne=>ne.status==="resolved")}):{visibleText:Se,draft:void 0,error:void 0},He=ye.visibleText,Ae=$?ye.error?{state:ye.error.includes("missing")?"missing":"invalid",reason:ye.error}:ye.draft?.decision==="none"?{state:"none",reason:ye.draft.reason}:ye.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ne of Z.orientations)T.broadcast({type:"orientation",jobId:a.id,orientation:ne},a.id,a.sourceId);for(let ne of Te.usages)T.broadcast({type:"imprint_used",jobId:a.id,usage:ne},a.id,a.sourceId);if(a.result=He,oe.success){console.log(`${J} Iteration complete`),oe.fileEdits&&oe.fileEdits.length>0&&console.log(`${J} Captured ${oe.fileEdits.length} file edit(s): ${oe.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),oe.editEvents&&oe.editEvents.length>0&&console.log(`${J} Captured ${oe.editEvents.length} edit event(s): ${oe.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),a.status="done";let ne=ts(Se),Ie=We;if(Ie.length>0&&a.annotationIds&&a.annotationIds.length>0){let de=new Set(a.annotationIds);Ie.every(Ye=>de.has(Ye.annotationId))||(Ie=Ie.map((Ye,bt)=>({...Ye,annotationId:a.annotationIds[bt%a.annotationIds.length]})))}let Oe=oe.fileEdits&&oe.fileEdits.length>0?oe.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):oe.toolsUsed,Fe=T.getBufferedEvents(a.id),Ee=Ql(Fe?.events??[],o,pe.segments),je,re=Vr(Se),U=Gr(Se);if(U)if(!(a.memoryReview?.packets.some(ce=>ce.proposalId===U.proposalId)||a.surfacedProposalIds?.includes(U.proposalId)))je={status:"rejected",action:U.action,proposalId:U.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{je=await W.commitConversationalReview(U)}catch(ce){je={status:"rejected",action:U.action,proposalId:U.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=os(Se,ve.length),fe,Ge,_o,Co,Ys=a.imprintContext?.pendingGroundingExplanationIds??[];if(ye.draft){let de=ye.draft.decision==="recognize"?[ye.draft.explanationId]:[],ce=ye.draft.decision==="recognize"?de:[...ye.draft.usedExplanationIds??[],...ye.draft.appliedExplanationIds??[]],Ye=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];ce.length>0&&(_o=[...new Set(ce)]),Ye.length>0&&(Co=[...new Set(Ye)])}ye.draft?.decision==="none"&&ee.recordNoop(ye.draft.reason);let Cn=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Cn&&!U&&!re){let de=a.imprintContext?.explanations.find(ce=>ce.id===Cn.explanationId&&ce.state==="grounded");de?Ge={explanationId:de.id,title:Cn.summary.title,detail:Cn.summary.detail,statement:de.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let $i=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(a.threadId&&$i&&!U&&!re)try{fe=await ee.capture($i,{threadId:a.threadId,jobId:a.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:Ys,applicationOccurred:ve.length>0||Ie.some(de=>de.status==="resolved")}),fe?(Ae={state:"mutated"},await W.recordImprintEvidence({summary:fe,threadId:a.threadId,jobId:a.id}).catch(de=>console.warn(`${J} Canonical Imprint evidence linkage failed:`,de))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(de){Ae={state:"invalid",reason:de instanceof Error?de.message:String(de)},console.warn(`${J} Continuous imprint update failed; the thread result remains available:`,de instanceof Error?de.message:String(de))}else $i&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ye.error&&console.warn(`${J} Ignored invalid imprint block: ${ye.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&ee.recordAssessmentFailure(Ae.state);let Oi=fe?.transactionId;if(a.threadId&&fe&&!fe.grounding){let de=await H.getThread(a.threadId),ce=new Set(fe.changes.map(bt=>bt.explanationId)),Ye=de?Kl(de.messages,ce):void 0;if(Ye?.imprintSummary){let bt=Ye.imprintSummary;await H.updateAssistantMessage(a.threadId,Ye.jobId,{imprintSummary:{...bt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(bt.additionalObservationCount??0)+1,coalescedTransactionIds:[...bt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let Di=an({question:ne,resolutions:Ie,changedFiles:ve,decisionRequired:!!re,imprintTransactionId:Oi,groundingRequired:!!fe?.grounding}),Zs=Ee?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Et=a.lifecycle?Rn(a.lifecycle,Oi?[Oi]:[],Ae):void 0;if(a.threadId){let de=O?re?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":He;await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:de,resolutions:!O&&Ie.length>0?Ie:void 0,question:O?void 0:ne??void 0,sessionId:oe.sessionId,toolsUsed:O?void 0:Oe,editEvents:!O&&oe.editEvents&&oe.editEvents.length>0?oe.editEvents:void 0,segments:!O&&Ee&&Ee.length>0?Ee:void 0,turn:{phase:"complete",orientation:Zs,result:Di},result:Di,memoryReviewCard:re??void 0,memoryReceipt:je,imprintSummary:fe,imprintRecognition:Ge,imprintUsedExplanationIds:_o,imprintAppliedExplanationIds:Co,modelDetails:ae.length>0?ae:void 0,model:a.model,provider:P,...Et?{lifecycle:Et}:{}})}if(a.threadId&&!U&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let de=a.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await W.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:y??(Ct(a.feedback)||"[request unavailable]"),responseSummary:ne??He,outcome:ne?"question_asked":Ie.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:P,model:a.model,sessionId:oe.sessionId},subjectHints:de,filePaths:[...(oe.fileEdits??[]).map(ce=>ce.file_path),...(oe.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>$s(ce)?Jl(o,ce):ce),resolutions:Ie.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Et?.submissionIds,outcomeId:Et?.outcomeId,imprintEvidenceIds:Et?.imprintEvidenceIds,imprintAssessment:Et?.imprintAssessment})}catch(ce){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}je?.status==="committed"&&je.decisionId&&P!=="copilot"&&await Xe({provider:P,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${je.decisionId}`}),ne&&(console.log(`${J} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${K.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),T.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:ne,annotationIds:a.annotationIds},a.id,a.sourceId)),ae.length>0&&(console.log(`${J} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),T.broadcast({type:"novel_patterns",jobId:a.id,patterns:ae,threadId:a.threadId},a.id,a.sourceId)),T.broadcast({type:"done",jobId:a.id,success:!0,resolutions:Ie.length>0?Ie:void 0,responseText:He,threadId:a.threadId,annotationIds:a.annotationIds,result:Di},a.id,a.sourceId),Re.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${J} Error: ${oe.error}`),a.status="error",a.error=oe.error,a.threadId&&await H.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:oe.error||"Unknown error",model:a.model,provider:P,...a.lifecycle?{lifecycle:Rn(a.lifecycle)}:{}}),T.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:oe.error||"Unknown error",provider:P,model:a.model,recoverable:oe.recoverableError,code:oe.errorCode},a.id,a.sourceId),Re.push({id:a.id,status:"error",completedAt:Date.now(),error:oe.error,threadId:a.threadId,annotationIds:a.annotationIds});nt()});let be=Dl(async(a,I)=>{if(Zl(a,I),a.method==="OPTIONS"){I.writeHead(204),I.end();return}let j=a.url||"/",y=j.split("?")[0],A=new URL(j,`http://127.0.0.1:${v}`),P=A.pathname,O=ip(a,A);if(O&&O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:Ai(o)});return}if(P.startsWith("/ambient/")&&O!==r){_(I,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:r,requestProjectId:O});return}if(a.headers.origin){if(!Os(a.headers.origin)){_(I,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(O!==r){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:O,projectName:Ai(o)});return}}try{if(P.startsWith("/ambient/"))await lt(a,I,P);else if(a.method==="POST"&&P==="/draft-attachments"){let $=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",N=A.searchParams.get("kind"),J=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(I,400,{error:"A valid annotationId is required."});return}if(N!=="svg"&&N!=="text"||N==="svg"&&J!=="image/svg+xml"||N==="text"&&J!=="text/plain"){_(I,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let he=await np(a,Vl);if(he.length===0){_(I,400,{error:"Attachment is empty."});return}let F=await V.stage({annotationId:$,name:q,mimeType:J,kind:N,data:he});_(I,201,{attachment:{id:F.id,name:F.name,mimeType:F.mimeType,size:F.size,kind:F.kind}})}else if(a.method==="POST"&&P==="/draft-attachments/claim"){let $=await _e(a),q=Array.isArray($.ids)?$.ids.filter(N=>typeof N=="string").slice(0,100):[];await V.claim(q),_(I,200,{ok:!0})}else if(a.method==="DELETE"&&P.startsWith("/draft-attachments/"))await V.release([P.slice(19)]),_(I,200,{ok:!0});else if(a.method==="POST"&&P==="/send")await pt(a,I);else if(a.method==="POST"&&P==="/capture/native"){if(!p){_(I,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await _e(a),q=typeof $.pageUrl=="string"?$.pageUrl:"",N=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!q||!N){_(I,400,{error:"pageUrl and clip are required."});return}let J=await Mr(p,{pageUrl:q,clip:{x:Number(N.x),y:Number(N.y),width:Number(N.width),height:Number(N.height)},scale:typeof $.scale=="number"?$.scale:1});I.writeHead(200,{"Content-Type":"image/webp","Content-Length":J.length,"Cache-Control":"no-store"}),I.end(J)}else if(a.method==="GET"&&P==="/events")vt(a,I);else if(a.method==="GET"&&P==="/status")await Ei(a,I,O);else if(a.method==="GET"&&P==="/ui-preferences")await rn(I);else if(a.method==="PATCH"&&P==="/ui-preferences")await Le(a,I);else if(a.method==="PATCH"&&P==="/config")await _i(a,I);else if(a.method==="POST"&&P==="/leases"){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await _e(a),q=typeof $.leaseId=="string"?$.leaseId.trim():"",N=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!q||q.length>128){_(I,400,{error:"A valid leaseId is required."});return}x();let J=z.acquire(q,N);_(I,201,{ok:!0,lease:J,ttlMs:js})}catch{_(I,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(P.slice(8))}catch{_(I,400,{error:"Invalid lease id."});return}if(!$){_(I,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=z.heartbeat($);if(!q){_(I,404,{error:"Lease not found."});return}_(I,200,{ok:!0,lease:q})}else{let q=z.release($);_(I,q.found?200:404,{ok:q.found}),q.becameEmpty&&L()}}else if(a.method==="POST"&&P==="/shutdown"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0}),setTimeout(Q,100)}else if(a.method==="POST"&&P==="/restart"){if(g!=="detached"){_(I,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:g});return}_(I,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of K)try{$.res.end()}catch{}be.close(()=>{Rs(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&P==="/capabilities")_(I,200,{providers:u});else if(P.startsWith("/imprint/"))await it(a,I,P);else if(P.startsWith("/memory/"))await $e(a,I,P);else if(a.method==="POST"&&P==="/mcp/install")await Ls(a,I);else if(a.method==="POST"&&P==="/reply")await ut(a,I);else if(a.method==="POST"&&P==="/cancel")qe(a,I);else if(a.method==="POST"&&P==="/materialize")_(I,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&P==="/materialization-runs")_(I,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&P==="/projection-runs"){let $=await ue.loadRuns();_(I,200,$)}else if(a.method==="GET"&&P==="/projection/proposals"){let $=await ue.loadModelProposals();_(I,200,$)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let $=P.slice(22,-15);await wt($,a,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let $=P.slice(22,-6);await Mt($,I)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let $=P.slice(22,-8);await Ci($,a,I)}else if(P.startsWith("/model/proposals/"))_(I,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&P==="/model/component")await qs(a,I);else if(a.method==="DELETE"&&P==="/model/component")await Fs(a,I);else if(a.method==="PATCH"&&P==="/model/token")await Us(a,I);else if(a.method==="DELETE"&&P==="/model/token")await zs(a,I);else if(a.method==="POST"&&P==="/model/consolidate")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&P==="/model/synthesize")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&P==="/model"){let $=await ue.loadModel();_(I,200,{model:$})}else if(a.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let $=P.slice(6,P.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),N=T.getBufferedEvents($,isNaN(q)?-1:q);N?_(I,200,N):_(I,404,{error:"Unknown job"})}else if(a.method==="GET"&&y.startsWith("/files/"))await Vs(y.slice(7),I);else if(a.method==="GET"&&P==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await H.listRecent($);_(I,200,q)}else if(a.method==="GET"&&P.startsWith("/decision/")){let $=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(I,400,{error:"Invalid decision id"});else{let q=await H.getThread($),N=[...q?.messages??[]].reverse().find(J=>J.annotationSnapshot);if(q&&N?.annotationSnapshot){let J=[...q.messages].reverse().find(he=>he.resolutions?.length);_(I,200,{decision:{id:q.id,createdAt:N.timestamp,url:N.annotationSnapshot.url,viewport:N.annotationSnapshot.viewport,color:N.annotationSnapshot.color,annotations:N.annotationSnapshot.annotations,resolutions:J?.resolutions??[]},authority:"thread_snapshot"})}else{let J=await Je.loadDecision($);J?_(I,200,{decision:J,authority:"legacy_archive"}):_(I,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&P.startsWith("/thread/")){let $=P.slice(8);await Ks($,I)}else if(a.method==="DELETE"&&P.startsWith("/thread/")){let $=P.slice(8);await Qs($,I)}else a.method==="GET"&&(P==="/canvas"||P==="/canvas/")?Ws(a,I):a.method==="GET"&&P==="/canvas/manifest"?await Hs(I):a.method==="GET"&&P==="/canvas/app.mjs"?await Gs(I):_(I,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(I,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function lt(a,I,j){if(a.method!=="POST"){_(I,405,{error:"Ambient endpoints accept POST requests only."});return}let y=await _e(a,tp),A=typeof y.sessionId=="string"?y.sessionId.trim():"",P=typeof y.turnId=="string"?y.turnId.trim():"",O=typeof y.executionOwner=="string"?y.executionOwner:void 0;if(j==="/ambient/context"){let $=typeof y.query=="string"?y.query.trim():"";if(!$){_(I,400,{error:"query is required."});return}let q=Array.isArray(y.subjectHints)?y.subjectHints.filter(N=>typeof N=="string"&&!!N.trim()).slice(0,20):void 0;_(I,200,await Ce.expandContext({query:$,subjectHints:q}));return}if(j==="/ambient/turns/assess"){let $=typeof y.threadId=="string"?y.threadId.trim():"",q=typeof y.jobId=="string"?y.jobId.trim():"",N=typeof y.assessmentText=="string"?y.assessmentText.trim():"";if(!$||!q||!N){_(I,400,{error:"threadId, jobId, and assessmentText are required."});return}let J=Array.isArray(y.semanticCandidates)?y.semanticCandidates.flatMap(F=>{if(!F||typeof F!="object"||Array.isArray(F))return[];let se=F,me=typeof se.claim=="string"?se.claim.trim():"",te=typeof se.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(se.proposedKind)?se.proposedKind:void 0;return me?[{claim:me,rationale:typeof se.rationale=="string"?se.rationale.trim():void 0,proposedKind:te,sourceText:typeof se.sourceText=="string"?se.sourceText.trim():void 0}]:[]}).slice(0,8):[],he=await Ce.assess({threadId:$,jobId:q,assessmentText:N,semanticCandidates:J});_(I,he.status==="recorded"?200:404,he);return}if(!A||!P||A.length>256||P.length>256){_(I,400,{error:"Valid sessionId and turnId values are required."});return}if(j==="/ambient/turns/prepare"){let $=typeof y.prompt=="string"?y.prompt.trim():"";if(!$){_(I,400,{error:"prompt is required."});return}_(I,200,await Ce.prepare({sessionId:A,turnId:P,prompt:$,model:typeof y.model=="string"?y.model:void 0,executionOwner:O}));return}if(j==="/ambient/turns/event"){let $=typeof y.toolName=="string"?y.toolName.trim():"";if(!$){_(I,400,{error:"toolName is required."});return}_(I,200,await Ce.recordEvent({sessionId:A,turnId:P,executionOwner:O,toolName:$,toolUseId:typeof y.toolUseId=="string"?y.toolUseId:void 0,toolInput:y.toolInput,toolResponse:y.toolResponse}));return}if(j==="/ambient/turns/complete"){_(I,200,await Ce.complete({sessionId:A,turnId:P,executionOwner:O,lastAssistantMessage:typeof y.lastAssistantMessage=="string"?y.lastAssistantMessage:void 0,model:typeof y.model=="string"?y.model:void 0}));return}_(I,404,{error:"Ambient endpoint not found."})}async function $e(a,I,j){try{if(a.method==="GET"&&j==="/memory/status"){_(I,200,await W.status());return}if(a.method==="GET"&&j==="/memory/diagnostics"){_(I,200,await W.diagnostics());return}if(a.method==="GET"&&j==="/memory/model-view"){_(I,200,await W.getModelView());return}if(a.method==="GET"&&j==="/memory/imprint-view"){let y=await H.load(),A=[...new Set(Object.values(y.threads).flatMap(P=>Mn(P.messages)))];_(I,200,await W.getImprintView(A,new Set(Object.keys(y.threads))));return}if(a.method==="POST"&&j==="/memory/constraints"){let y=await _e(a),A=typeof y.reactComponent=="string"?y.reactComponent.trim():"",P=await W.getModelView(),O=A?P.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(I,200,{modelEntries:O});return}if(a.method==="POST"&&j==="/memory/conversation-action"){let y=await _e(a),A=typeof y.threadId=="string"?y.threadId:"",P=typeof y.proposalId=="string"?y.proposalId:"",O=String(y.action);if(!A||!P||!["accept","edit_and_accept","reject","defer"].includes(O)){_(I,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await H.getThread(A),q=$?.messages.find(pe=>pe.memoryReviewCard?.proposalId===P)?.memoryReviewCard,N=$?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===P),J=$?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await W.findPendingProposalsForThread(A)).find(pe=>pe.proposalId===P):void 0,he=typeof y.kind=="string"&&["principle","preference","rule","constraint"].includes(y.kind)?y.kind:void 0,F=q?.kind??N?.proposedKind??J?.proposedKind??he;if(!$||!q&&!N&&!J){_(I,409,{error:"This decision candidate was not surfaced in the thread."});return}if((O==="accept"||O==="edit_and_accept")&&!F){_(I,400,{error:"The decision kind is required to accept this candidate."});return}let se=await ue.findModelProposalsByThread(A),me=(await Promise.all(se.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Z=>W.findPendingProposalForLegacyDecision(Z)))).some(Z=>Z?.proposalId===P)})))).find(pe=>pe.matches)?.proposal,te={proposalId:P,action:O,kind:F,claim:O==="edit_and_accept"&&typeof y.claim=="string"?y.claim.trim():void 0,reason:O==="defer"?void 0:`The owner explicitly chose ${O.replaceAll("_"," ")} from the decision review card.`,taskContext:O==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:O==="defer"?["different_action","owner_request"]:void 0};if(te.action==="edit_and_accept"&&!te.claim){_(I,400,{error:"Edited decision wording is required."});return}let ge=await W.commitConversationalReview(te),oe=`memory-${ct().slice(0,8)}`,ve=O==="accept"?"> Accepted decision":O==="edit_and_accept"?"> Edited and accepted decision":O==="reject"?"> Rejected decision":"> Deferred decision";await H.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:oe,replyToQuestion:ve}),await H.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:oe,responseText:"",memoryReceipt:ge,provider:nn(typeof y.provider=="string"?y.provider:void 0),model:typeof y.model=="string"?y.model:void 0}),ge.status==="committed"&&me&&await ue.dismissModelProposal(me.id);let Te=nn(typeof y.provider=="string"?y.provider:void 0);ge.status==="committed"&&ge.decisionId&&Te!=="copilot"&&await Xe({provider:Te,model:typeof y.model=="string"?y.model:void 0,agentSettings:qt(y),threadId:A,reason:`Project accepted decision ${ge.decisionId}`}),_(I,ge.status==="committed"?200:409,{receipt:ge});return}if(a.method==="POST"&&j==="/memory/analyze"){let y=await _e(a),A=await W.analyzeLegacy({projectKey:typeof y.projectKey=="string"?y.projectKey:void 0}),P=Object.fromEntries([...new Set(A.issues.map(O=>O.code))].map(O=>[O,A.issues.filter($=>$.code===O).length]));_(I,200,{...A,issues:void 0,issueCounts:P});return}if(a.method==="POST"&&j==="/memory/review"){let y=await _e(a),A=await W.review(Io(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,A);return}if(a.method==="POST"&&j==="/memory/context"){let y=await _e(a),A=await W.contextualize(Io(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,A);return}if(a.method==="POST"&&j==="/memory/initialize"){let y=await _e(a),A=await W.initializeFromLegacy({confirmed:y.confirm===!0,projectKey:typeof y.projectKey=="string"?y.projectKey:void 0,writerVersion:dt});_(I,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&j==="/memory/plan"){let y=await _e(a),A=await W.planReview(yo(y.command),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,A.result.ok?200:422,A);return}if(a.method==="POST"&&j==="/memory/commit"){let y=await _e(a),A=y.transaction&&typeof y.transaction=="object"&&!Array.isArray(y.transaction)?y.transaction:{},P=await W.commitReview(yo(y.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(I,200,{status:await W.status(),journal:P.report});return}if(a.method==="POST"&&j==="/memory/recover"){let y=await _e(a),A=await W.recover(y.confirm===!0);_(I,200,{status:await W.status(),journal:A.report});return}_(I,404,{error:"Memory endpoint not found."})}catch(y){let A=y instanceof Error?y.message:String(y),P=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),O=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(P||O){_(I,P?409:400,{error:A});return}throw y}}async function it(a,I,j){if(a.method==="GET"&&j==="/imprint/status"){let[y,A]=await Promise.all([ee.store.load(),H.load()]),P=[...new Set(Object.values(A.threads).flatMap(O=>Mn(O.messages)))].filter(O=>y.graph.explanations.some($=>$.id===O&&$.state==="testing"));_(I,200,{state:"ready",head:y.graph.head,updatedAt:y.graph.updatedAt,explanationCount:y.graph.explanations.filter(O=>O.state!=="retired").length,concreteCount:y.graph.concrete.length,relationCount:y.graph.relations.length,pendingGroundingCount:P.length,recoveredTransactions:y.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&j==="/imprint/action"){let y=await _e(a),A=typeof y.threadId=="string"?y.threadId:"",P=typeof y.transactionId=="string"?y.transactionId:"",O=String(y.action);if(!A||!P||!["yes","this_time","no"].includes(O)){_(I,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await H.getThread(A),N=[...q?.messages??[]].reverse().find(te=>te.role==="assistant"&&te.imprintSummary?.transactionId===P),J=N?.imprintSummary;if(!q||!N||!J){_(I,409,{error:"This imprint summary is not available in the thread."});return}if(J.resolvedAction){_(I,409,{error:"This imprint summary has already been resolved."});return}let he=`imprint-${ct().slice(0,8)}`;await ee.applyGroundingAction({summary:J,action:O,threadId:A,jobId:he}),O!=="no"&&await W.recordImprintEvidence({summary:J,action:O,threadId:A,jobId:he}).catch(te=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",te));let F=_t(N.result,!!N.question),se=N.turn?{...N.turn,result:_t(N.turn.result,!!N.question)}:void 0;await H.updateAssistantMessage(A,N.jobId,{imprintSummary:{...J,resolvedAction:O},...F?{result:F}:{},...se?{turn:se}:{}});let me={yes:"> Yes",this_time:"> This time",no:"> No"};if(await H.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:he,replyToQuestion:me[O]}),O==="no"){let te="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",ge=an({question:te});await H.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:he,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:te,turn:{phase:"complete",orientation:[],result:ge},result:ge})}_(I,200,{ok:!0,action:O});return}_(I,404,{error:"Imprint endpoint not found."})}async function pt(a,I){let{screenshot:j,feedback:y,color:A,provider:P,model:O,reasoningEffort:$,serviceTier:q,sourceId:N,pastedImages:J,pageScreenshots:he}=await vo(a),F;try{F=JSON.parse(y)}catch{_(I,400,{error:"Invalid feedback JSON"});return}let se=F.annotations.flatMap(re=>(re.attachments??[]).map(U=>({id:U.id,annotationId:re.id}))),me;try{me=se.length>0?await V.promote(se):void 0}catch(re){_(I,409,{error:re instanceof Error?re.message:"Draft attachment unavailable."});return}let te=ct().slice(0,8),ge={};if(he.length>0)for(let re of he){let U=encodeURIComponent(re.pathname),ae=Be(c,`screenshot-${te}-${U}.webp`);await Ri(ae,re.data),ge[re.pathname]=ae}let oe=Be(c,`screenshot-${te}.webp`);await Ri(oe,j);let ve={};if(J.length>0)for(let re of J){let U=Be(c,`pasted-${te}-${re.annotationId}-${re.index}.webp`);await Ri(U,re.data),ve[re.annotationId]||(ve[re.annotationId]=[]),ve[re.annotationId].push(U)}let Te=gs(F),pe;if(Te.length>0){let re=await H.findContinuationThread(Te);re?(pe=re.id,await H.addElementIdentifiers(pe,Te)):pe=(await H.createThread(`thread-${ct()}`,Te)).id}else pe=(await H.createThread(`thread-${ct()}`,[])).id;let Z=F.annotations.map(re=>re.id),Se=Object.keys(ge).length>0,We=await dn(W,F,Te,re=>console.warn(`[\u22B9 ${v}:${te}] Contextual memory unavailable; continuing without it:`,re instanceof Error?re.message:String(re))),ye=(await H.getThread(pe))?.messages??[],He=await ee.contextualize({text:Ct(F),subjectHints:Ss(F,Te),pendingGroundingExplanationIds:Mn(ye),correctionExplanationIds:Es(ye)}).catch(re=>{console.warn(`[\u22B9 ${v}:${te}] Imprint context unavailable; continuing without it:`,re instanceof Error?re.message:String(re))}),Ae=Po({jobId:te,threadId:pe,artifactIds:ys(F,te)}),ne={id:te,status:"queued",screenshotPath:oe,feedback:F,createdAt:Date.now(),color:A,threadId:pe,annotationIds:Z,provider:nn(P),model:O||void 0,agentSettings:qt({reasoningEffort:$,serviceTier:q}),...Object.keys(ve).length>0?{imagePaths:ve}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:N||void 0,...Se?{screenshotPaths:ge}:{},...We?{memoryReview:We}:{},...He?{imprintContext:He}:{},lifecycle:Ae},Ie=new Set(F.annotations.map(re=>re.pathname).filter(Boolean)),Oe;if(Ie.size>1){let re=new Map;for(let U of F.annotations){let ae=U.pathname||"(unknown)";re.has(ae)||re.set(ae,[]),re.get(ae).push(U.instruction||_s({...F,annotations:[U]}))}Oe=[...re.entries()].map(([U,ae])=>`\`${U}\`
|
|
227
229
|
${ae.map(fe=>`- ${fe}`).join(`
|
|
228
230
|
`)}`).join(`
|
|
229
|
-
`)}else Oe=
|
|
230
|
-
`):
|
|
231
|
-
`)),oe){let U=oe,fe=[...U._replyTexts??(U._replyText?[U._replyText]:[]),
|
|
231
|
+
`)}else Oe=_s(F);let Fe=xn(F,Object.keys(ve).length>0?ve:void 0,me),Ee=Ps(F);await H.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:te,screenshotPath:oe,...Se?{screenshotPaths:ge}:{},...Object.keys(ve).length>0?{imagePaths:ve}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},annotationIds:Z,annotationSnapshot:{url:F.url,viewport:F.viewport,annotations:F.annotations,color:A||void 0},feedbackSummary:Oe,...Ee?{requestText:Ee}:{},feedbackContext:Fe||void 0,...We?{memoryReview:We}:{},...He?{imprintContext:He}:{},lifecycle:Ae});let je=T.enqueue(ne);_(I,200,{jobId:te,position:je,threadId:pe})}async function ut(a,I){let j=a.headers["content-type"]||"",y,A,P,O,$,q,N,J,he=[];if(j.includes("multipart/form-data")){let U=await vo(a),ae=U.feedback?JSON.parse(U.feedback):{};y=ae.threadId,A=ae.reply,P=ae.color,O=ae.provider,$=ae.model,q=qt(ae),N=ae.sourceId||U.sourceId,J=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let fe of U.pastedImages)he.push(fe.data)}else{let U=[];for await(let Ge of a)U.push(typeof Ge=="string"?Buffer.from(Ge):Ge);let ae=Buffer.concat(U).toString("utf-8"),fe;try{fe=JSON.parse(ae)}catch{_(I,400,{error:"Invalid JSON"});return}y=fe.threadId,A=fe.reply,P=fe.color,O=fe.provider,$=fe.model,q=qt(fe),N=fe.sourceId,J=fe.memoryReviewProposalId}if(!y||!A){_(I,400,{error:"Missing threadId or reply"});return}let F=await H.getThread(y);if(!F){_(I,404,{error:"Thread not found"});return}let se;if(J){let U=await ue.findModelProposalsByThread(y);if(se=(await Promise.all(U.flatMap(fe=>fe.authorityStatus==="accepted"?[]:fe.decisionIds.map(async Ge=>({modelProposalId:fe.id,underlying:await W.findPendingProposalForLegacyDecision(Ge)}))))).filter(fe=>!!fe.underlying).find(fe=>fe.underlying.proposalId===J),!se){_(I,409,{error:"The requested memory decision is not pending in this thread."});return}}let me="";{let U=await H.getThreadHistory(y);for(let ae=U.length-1;ae>=0;ae--)if(U[ae].screenshotPath){me=U[ae].screenshotPath;break}}let te=await Js(y);if(!me&&!te){_(I,400,{error:"No screenshot available"});return}let ge=T.hasActiveThread(y),oe=ge?T.getQueuedThreadJob(y,U=>U._replyText!==void 0||U._replyPrompt!==void 0):null,ve=oe?.id??ct().slice(0,8),Te=Po({jobId:ve,threadId:y}),pe=[],Z=`${ve}-${Date.now()}`;for(let U=0;U<he.length;U++){let ae=Be(c,`reply-${Z}-${U}.webp`);await Ri(ae,he[U]),pe.push(ae)}await H.appendMessage(y,{role:"human",timestamp:Date.now(),jobId:ve,replyToQuestion:A,screenshotPath:me,...ge?{queued:!0}:{},...pe.length>0?{replyImagePaths:pe}:{},lifecycle:{...Te,artifactIds:pe.map((U,ae)=>`reply-image:${ve}:${ae}`)}});let Se=await H.getThreadHistory(y),We=[...Se].reverse().find(U=>U.memoryReview)?.memoryReview,ye=await ee.contextualize({text:A,subjectHints:Ts(Se,F.elementIdentifiers),pendingGroundingExplanationIds:Mn(Se),correctionExplanationIds:Es(Se)}).catch(U=>{console.warn(`[\u22B9 ${v}:${ve}] Imprint context unavailable for reply; continuing without it:`,U instanceof Error?U.message:String(U))});ye&&await H.updateMessage(y,ve,{imprintContext:ye});let He=new Set(Se.flatMap(U=>U.memoryReceipt?.status==="committed"?[U.memoryReceipt.proposalId]:[])),Ae=[...Se].reverse().find(U=>U.memoryReviewCard&&!He.has(U.memoryReviewCard.proposalId))?.memoryReviewCard,ne=[];for(let U of Se)if(U.annotationIds)for(let ae of U.annotationIds)ne.includes(ae)||ne.push(ae);let Ie=nn(O),Oe=se,Fe=Oe?[Oe.underlying.proposalId]:Ae?[Ae.proposalId]:[],Ee=ns(me,Se,Ie,pe.length>0?pe:void 0);if(Oe?Ee+=["","## Decision review card",`Privately review proposal ${Oe.underlying.proposalId}: ${Oe.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
232
|
+
`):Ae&&(Ee+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(Ae)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
|
|
233
|
+
`)),oe){let U=oe,fe=[...U._replyTexts??(U._replyText?[U._replyText]:[]),A],Ge=[...U._replyImagePaths??[],...pe];U._replyTexts=fe,U._replyText=Ms(fe),U._replyImagePaths=Ge.length>0?Ge:void 0,U._replyPrompt=Ee,U.annotationIds=ne.length>0?ne:U.annotationIds,U.agentSettings=q??U.agentSettings,U.memoryReview=We??U.memoryReview,U.imprintContext=ye??U.imprintContext,U.surfacedProposalIds=[...new Set([...U.surfacedProposalIds??[],...Fe])],U.lifecycle={...U.lifecycle??Te,submissionIds:[...new Set([...U.lifecycle?.submissionIds??[],...Te.submissionIds])],artifactIds:[...new Set([...U.lifecycle?.artifactIds??[],...Te.artifactIds])]},_(I,200,{jobId:ve,position:1,threadId:y,bundled:!0});return}let je={id:ve,status:"queued",screenshotPath:me,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:y,annotationIds:ne.length>0?ne:void 0,provider:Ie,model:$||void 0,agentSettings:q,sourceId:N||void 0,...We?{memoryReview:We}:{},...ye?{imprintContext:ye}:{},...Fe.length?{surfacedProposalIds:Fe}:{},lifecycle:Te};te&&(je.kind=te),je._replyPrompt=Ee,je._replyTexts=[A],je._replyText=Ms([A]),pe.length>0&&(je._replyImagePaths=pe);let re=ge?T.enqueueNext(je):T.enqueue(je);_(I,200,{jobId:ve,position:re,threadId:y})}function vt(a,I){I.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),I.write(`event: connected
|
|
232
234
|
data: {"status":"connected"}
|
|
233
235
|
|
|
234
|
-
`);let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("sourceId")||void 0,j={id:ct().slice(0,8),res:I,sourceId:y};K.add(j),a.on("close",()=>{K.delete(j)})}async function Mi(a,I,A){d??=ps(a.headers),nt();let y=[...S.allActive,...C.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[j,P,O,$,q]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),W.status(),ee.store.load(),H.load()]),N=[],B=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);j.status==="rejected"&&N.push({subsystem:"projection",message:B(j)}),P.status==="rejected"&&N.push({subsystem:"projection",message:B(P)}),O.status==="rejected"?N.push({subsystem:"memory",message:B(O)}):O.value.state==="degraded"&&N.push({subsystem:"memory",message:O.value.error??"Product memory is degraded."}),$.status==="rejected"&&N.push({subsystem:"imprint",message:B($)}),q.status==="rejected"&&N.push({subsystem:"threads",message:B(q)});let he=j.status==="fulfilled"?j.value.runs:[],F=P.status==="fulfilled"?P.value.proposals:[],se=us(he,F),me=se.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),te=O.status==="fulfilled"?O.value:{initialized:!1,state:"degraded",error:B(O)},ge=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>Mn(Z.messages)))]:[],oe=$.status==="fulfilled"?ge.filter(Z=>$.value.graph.explanations.some(Se=>Se.id===Z&&Se.state==="testing")):[],ve=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:oe.length,recoveredTransactions:$.value.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:B($),pendingGroundingCount:oe.length,admission:ee.diagnostics(),admissionWindowStartedAt:e},Te=N.length>0?"degraded":te.state==="absent"||te.state==="initializing"?"initializing":"healthy",pe=new Date().toISOString();_(I,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Te,issues:N},version:dt,restartMode:g,projectId:r,storeId:s.storeId,projectName:Ri(o),projectRoot:o,requestProjectId:A,projectIdVerified:A===r,devOrigin:d,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:y[0]?{id:y[0].id,status:y[0].status}:null,activeJobs:y.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:S.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:z.isActivated,count:z.size,nextExpiryAt:z.nextExpiryAt,shutdownPending:Y},projection:{state:j.status==="fulfilled"&&P.status==="fulfilled"?"ready":"degraded",activeJob:C.active?{id:C.active.id,status:C.active.status,threadId:C.active.threadId,annotationIds:C.active.annotationIds??[],provider:C.active.provider,model:C.active.model}:null,queueDepth:C.depth,recentRuns:se.recentRuns,recentAppliedRuns:se.recentAppliedRuns,actionableProposalCounts:se.actionableProposalCounts,actionableProposals:me},memory:te,imprint:ve,recentJobsRetentionMs:on,recentJobs:Re})}async function Ei(a,I){let A=await new Promise(y=>{let j="";a.on("data",P=>{j+=P.toString()}),a.on("end",()=>y(j))});try{let y=JSON.parse(A);typeof y.devOrigin=="string"&&(d=y.devOrigin||null),_(I,200,{ok:!0,devOrigin:d})}catch{_(I,400,{error:"Invalid JSON"})}}async function rn(a){let I=await ke.load();_(a,200,{ok:!0,...I})}async function Le(a,I){let A=await _e(a);if(!bs(A.theme)){_(I,400,{error:"theme must be light, dark, or auto"});return}let y=await ke.setTheme(A.theme);_(I,200,{ok:!0,exists:!0,preferences:y})}async function qe(a,I){let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("jobId"),j=y?S.allActive.filter(B=>B.id===y):S.allActive,P=y?C.allActive.filter(B=>B.id===y):C.allActive,O=[...j.map(B=>B.threadId),...P.map(B=>B.threadId)].filter(Boolean),$=y?S.cancelJob(y):S.cancelActive(),q=y?C.cancelJob(y):C.cancelActive(),N=!!($||q);for(let B of O)await H.appendMessage(B,{role:"assistant",timestamp:Date.now(),jobId:y||q?.id||"",cancelled:!0});_(I,200,{cancelled:N})}async function Xe(a){let I=ct().slice(0,8),A=a.threadId,y=!A;A||(A=(await H.createThread(`thread-${ct()}`,[])).id,yt.set(A,"project_model")),y&&await H.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:a.reason}),await H.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:I,responseText:y?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let j={id:I,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:A,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:y},P=C.enqueue(j);return{jobId:I,position:P,threadId:A}}async function Mt(a,I){let A=decodeURIComponent(a),y=await ue.findModelProposal(A);if(!y){_(I,404,{error:"Model proposal not found"});return}_(I,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:y})}async function wt(a,I,A){let y=decodeURIComponent(a),j=[];for await(let F of I)j.push(typeof F=="string"?Buffer.from(F):F);let P;try{P=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(A,400,{error:"Invalid JSON"});return}let O=(P.changes??[]).flatMap(F=>{if(!Array.isArray(F.path)||F.path.length===0)return[];let se=F.path.filter(te=>typeof te=="string"||typeof te=="number");if(se.length!==F.path.length)return[];let me=Array.isArray(F.decisionIds)?F.decisionIds.filter(te=>typeof te=="string"):void 0;return[{path:se,value:F.value,remove:F.remove===!0,decisionIds:me}]});if(O.length===0){_(A,400,{error:"No selected model changes"});return}let $=(P.changeSummaries??[]).flatMap(F=>{if(!F||typeof F!="object")return[];let se=Array.isArray(F.path)?F.path.filter(me=>typeof me=="string"||typeof me=="number"):void 0;return Array.isArray(F.path)&&se?.length!==F.path.length?[]:[{group:typeof F.group=="string"?F.group:void 0,label:typeof F.label=="string"?F.label:void 0,detail:typeof F.detail=="string"?F.detail:void 0,path:se,value:F.value,currentValue:F.currentValue}]}),q=await ue.findModelProposal(y);if(!q){_(A,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(A,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(A,409,{error:`Model proposal is already ${q.status}.`});return}let N=q.decisionIds.map(F=>{let se=q.changes?.filter(ge=>ge.decisionIds.includes(F)).length??0,me=O.filter(ge=>ge.decisionIds?.includes(F)).length,te=me===0?"unprojected":se>me?"partially_projected":"projected";return{decisionId:F,status:te}}),B=await W.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:O.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:N}),he=await ue.applySelectedModelProposal(y,O,$);if(!he){_(A,404,{error:"Model proposal not found"});return}if(he.threadId){let F=nn(P.provider),se=typeof P.model=="string"&&P.model?P.model:void 0;await H.appendMessage(he.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${he.id}`,responseText:"",provider:F,model:se})}_(A,200,{proposal:he,projection:B})}async function _i(a,I,A){let y=decodeURIComponent(a),{provider:j,model:P}=await _n(I),O=await ue.dismissModelProposal(y);if(!O){_(A,404,{error:"Model proposal not found"});return}O.threadId&&await H.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${O.id}`,responseText:"",provider:j,model:P}),_(A,200,{proposal:O})}async function _n(a){try{let I=[];for await(let y of a)I.push(typeof y=="string"?Buffer.from(y):y);if(I.length===0)return{};let A=JSON.parse(Buffer.concat(I).toString());return{provider:nn(typeof A.provider=="string"?A.provider:void 0),model:typeof A.model=="string"&&A.model?A.model:void 0,agentSettings:qt(A)}}catch{return{}}}async function Js(a){let I=yt.get(a);if(I)return I;let j=(await H.getThread(a))?.messages.find(P=>P.role==="human")?.feedbackSummary??"";if(j.startsWith("Synthesize rules"))return yt.set(a,"synthesize"),"synthesize";if(j.startsWith("Materialize model")||j.startsWith("Project model"))return yt.set(a,"project_model"),"project_model"}async function Bs(a,I){let A=[];for await(let q of a)A.push(typeof q=="string"?Buffer.from(q):q);let y;if(A.length>0)try{y=JSON.parse(Buffer.concat(A).toString("utf-8")).serverUrl}catch{}let j=[];u.claude?.available&&u.claude.mcp&&!u.claude.mcp.found&&j.push(await kr(y)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&j.push(await Rr(y)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&j.push(await jr(y,u.copilot.path??R));let[P,O,$]=await Promise.all([eo(o),to(o),no(o,u.copilot?.path??R)]);u.claude&&(u.claude.mcp=P),u.codex&&(u.codex.mcp=O),u.copilot&&(u.copilot.mcp=$),_(I,200,{results:j,capabilities:{providers:u}})}async function Ls(a,I){let A=[];for await(let P of a)A.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let j=await W.recordDirectModelMutation({key:`components.${y.name}`,value:{description:""},claim:`${y.name} is an explicitly governed component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{added:!0,alreadyExists:!1,...j})}async function qs(a,I){let A=[];for await(let P of a)A.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let j=await W.recordDirectModelMutation({key:`components.${y.name}`,value:null,claim:`${y.name} is not governed as a component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}async function Fs(a,I){let A=[];for await(let O of a)A.push(typeof O=="string"?Buffer.from(O):O);let y;try{y=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"||typeof y.value!="string"){_(I,400,{error:"Missing or invalid path/value"});return}let j=y.value;try{let O=JSON.parse(y.value);O&&typeof O=="object"&&(j=O)}catch{}let P=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:j,claim:`${y.path} uses ${y.value} in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{updated:!0,...P})}async function Us(a,I){let A=[];for await(let P of a)A.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"){_(I,400,{error:"Missing or invalid path"});return}let j=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:null,claim:`${y.path} is intentionally absent from the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}function zs(a,I){let A=d??"http://localhost:3000";if(!d){let j=a.headers.referer||a.headers.origin;if(j)try{let P=new URL(typeof j=="string"?j:j[0]||"");(P.hostname==="localhost"||P.hostname==="127.0.0.1")&&(A=P.origin)}catch{}}let y=Oo(v,A);I.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),I.end(y)}async function Ws(a){let I=Date.now();if(It&&I<It.expires){_(a,200,It.data);return}try{let{scanForComponents:A}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:y}=await import("./render-generator-HWFLZYC3.mjs"),j=await A(o);It={data:j,expires:I+5e3},y(j,o,En).then(P=>{En=P}).catch(P=>console.warn("[Bridge] Render generation failed:",P)),_(a,200,j)}catch(A){console.error("[Bridge] Scanner error:",A),_(a,500,{error:"Failed to scan components"})}}async function Hs(a){let I=[Je(o,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Je(o,"packages","popmelt","dist","canvas.mjs")];try{let A=Ll(import.meta.url);I.unshift(Je(Nl(A),"canvas.mjs"))}catch{}for(let A of I)try{let y=await Rs(A,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(y);return}catch{}console.error("[Bridge] Canvas bundle not found in:",I),_(a,404,{error:"Canvas bundle not found"})}async function Gs(a,I){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(I,400,{error:"Invalid filename"});return}try{let A=[Je(c,a),Je(o,".popmelt","artifacts","thread-media",a),Je(o,".popmelt","artifacts","eval-screenshots",a),Je(o,".popmelt","evals","screenshots",a),Je(o,".popmelt","screenshots",a)],y;for(let O of A)try{y=await Rs(O);break}catch{}if(!y)throw new Error("File not found");let j=a.split(".").pop()?.toLowerCase(),P=j==="png"?"image/png":j==="webp"?"image/webp":j==="jpg"||j==="jpeg"?"image/jpeg":j==="svg"?"image/svg+xml":j==="txt"?"text/plain; charset=utf-8":"application/octet-stream";I.writeHead(200,{"Content-Type":P,"Cache-Control":"public, max-age=3600"}),I.end(y)}catch{_(I,404,{error:"File not found"})}}function sn(a){return`/files/${Ri(a)}`}async function Vs(a,I){let A=await H.getThread(a);if(!A){_(I,404,{error:"Thread not found"});return}let y=A.messages.filter(N=>N.role==="assistant"&&N.responseText?.includes("Model suggestion ready")),j=await(y.length>0?ue.findModelProposalsByThread(a):Promise.resolve([])),P=await Promise.all(j.map(async(N,B)=>{if(N.authorityStatus==="accepted")return N;let he=(await Promise.all(N.decisionIds.map(F=>W.findPendingProposalForLegacyDecision(F)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??y[B]?.jobId??y.at(-1)?.jobId,underlyingProposalId:he?.proposalId,underlyingClaim:he?.claim}})),O=[...P].sort((N,B)=>B.updatedAt-N.updatedAt)[0]??null,$=A.elementIdentifiers.some(N=>N.startsWith("codex-session:"))?await W.findPendingProposalsForThread(a):[],q=A.messages.map(({screenshotPath:N,screenshotPaths:B,imagePaths:he,attachmentFiles:F,replyImagePaths:se,...me})=>({...me,...N?{screenshotUrl:sn(N)}:{},...B?{screenshotUrls:Object.fromEntries(Object.entries(B).map(([te,ge])=>[te,sn(ge)]))}:{},...he?{imageUrls:Object.fromEntries(Object.entries(he).map(([te,ge])=>[te,ge.map(sn)]))}:{},...F?{attachments:Object.fromEntries(Object.entries(F).map(([te,ge])=>[te,ge.map(({path:oe,...ve})=>({...ve,url:sn(oe)}))]))}:{},...se?{replyImageUrls:se.map(sn)}:{}}));_(I,200,{id:A.id,createdAt:A.createdAt,messages:q,modelProposal:O,modelProposals:P,decisionCandidates:$})}async function Ks(a,I){let A=decodeURIComponent(a);if(!await H.deleteThread(A)){_(I,404,{deleted:!1,error:"Thread not found"});return}_(I,200,{deleted:!0})}let jo=9,Ao=!1;for(let a=t;a<t+jo;a++)try{await np(be,a),v=a,Ao=!0,console.log(`[\u22B9 is watching :${v}]`);break}catch(I){if(I.code==="EADDRINUSE"){let A=await Ai(a);if(kn(A,{projectId:r,version:dt,restartMode:g}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw I}if(!Ao)throw new Error(`[Bridge] All ports ${t}\u2013${t+jo-1} in use`);for(let[a,I]of Object.entries(u))!I.available||!I.path||h(a,I.path).then(A=>{if(A)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),I.available=!1,I.path=null;for(let y of K)ji(y,{type:"capabilities_changed",data:{}})}});let Qs=setInterval(()=>{_s(c).catch(()=>{}),V.sweep().catch(()=>{})},Ul),Mo=setInterval(()=>{z.expireStale().becameEmpty&&L()},Wl);return Mo.unref?.(),{port:v,projectId:r,storeId:s.storeId,close:async()=>{clearInterval(Qs),clearInterval(Mo),b(),z.clear(),await V.cleanupPartials(),await S.destroyAsync(),C.destroy();for(let a of K)try{a.res.end()}catch{}return K.clear(),new Promise(a=>{be.close(()=>a())})}}}async function _s(i){try{let e=await El(i),t=Date.now();for(let n of e){let o=Je(i,n);try{let r=await Cl(o);t-r.mtimeMs>zl&&await $l(o)}catch{}}}catch{}}var up=1111,Ds=3e4,mp=8e3;async function fp(i){return cp(i).catch(()=>i)}async function Ns(i,e){let n=(await dp(e,"utf8").catch(()=>"")).slice(-mp).trim();return new Error(n?`${i}
|
|
236
|
+
`);let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("sourceId")||void 0,A={id:ct().slice(0,8),res:I,sourceId:y};K.add(A),a.on("close",()=>{K.delete(A)})}async function Ei(a,I,j){d??=us(a.headers),nt();let y=[...T.allActive,...C.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,P,O,$,q]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),W.status(),ee.store.load(),H.load()]),N=[],J=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&N.push({subsystem:"projection",message:J(A)}),P.status==="rejected"&&N.push({subsystem:"projection",message:J(P)}),O.status==="rejected"?N.push({subsystem:"memory",message:J(O)}):O.value.state==="degraded"&&N.push({subsystem:"memory",message:O.value.error??"Product memory is degraded."}),$.status==="rejected"&&N.push({subsystem:"imprint",message:J($)}),q.status==="rejected"&&N.push({subsystem:"threads",message:J(q)});let he=A.status==="fulfilled"?A.value.runs:[],F=P.status==="fulfilled"?P.value.proposals:[],se=ms(he,F),me=se.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),te=O.status==="fulfilled"?O.value:{initialized:!1,state:"degraded",error:J(O)},ge=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>Mn(Z.messages)))]:[],oe=$.status==="fulfilled"?ge.filter(Z=>$.value.graph.explanations.some(Se=>Se.id===Z&&Se.state==="testing")):[],ve=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:oe.length,recoveredTransactions:$.value.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J($),pendingGroundingCount:oe.length,admission:ee.diagnostics(),admissionWindowStartedAt:e},Te=N.length>0?"degraded":te.state==="absent"||te.state==="initializing"?"initializing":"healthy",pe=new Date().toISOString();_(I,200,{ok:!0,schemaVersion:3,generatedAt:pe,serverStartedAt:e,health:{state:Te,issues:N},version:dt,restartMode:g,projectId:r,storeId:s.storeId,projectName:Ai(o),projectRoot:o,requestProjectId:j,projectIdVerified:j===r,devOrigin:d,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:y[0]?{id:y[0].id,status:y[0].status}:null,activeJobs:y.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:T.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:z.isActivated,count:z.size,nextExpiryAt:z.nextExpiryAt,shutdownPending:Y},projection:{state:A.status==="fulfilled"&&P.status==="fulfilled"?"ready":"degraded",activeJob:C.active?{id:C.active.id,status:C.active.status,threadId:C.active.threadId,annotationIds:C.active.annotationIds??[],provider:C.active.provider,model:C.active.model}:null,queueDepth:C.depth,recentRuns:se.recentRuns,recentAppliedRuns:se.recentAppliedRuns,actionableProposalCounts:se.actionableProposalCounts,actionableProposals:me},memory:te,imprint:ve,recentJobsRetentionMs:on,recentJobs:Re})}async function _i(a,I){let j=await new Promise(y=>{let A="";a.on("data",P=>{A+=P.toString()}),a.on("end",()=>y(A))});try{let y=JSON.parse(j);typeof y.devOrigin=="string"&&(d=y.devOrigin||null),_(I,200,{ok:!0,devOrigin:d})}catch{_(I,400,{error:"Invalid JSON"})}}async function rn(a){let I=await ke.load();_(a,200,{ok:!0,...I})}async function Le(a,I){let j=await _e(a);if(!xs(j.theme)){_(I,400,{error:"theme must be light, dark, or auto"});return}let y=await ke.setTheme(j.theme);_(I,200,{ok:!0,exists:!0,preferences:y})}async function qe(a,I){let y=new URL(a.url||"/",`http://127.0.0.1:${v}`).searchParams.get("jobId"),A=y?T.allActive.filter(J=>J.id===y):T.allActive,P=y?C.allActive.filter(J=>J.id===y):C.allActive,O=[...A.map(J=>J.threadId),...P.map(J=>J.threadId)].filter(Boolean),$=y?T.cancelJob(y):T.cancelActive(),q=y?C.cancelJob(y):C.cancelActive(),N=!!($||q);for(let J of O)await H.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:y||q?.id||"",cancelled:!0});_(I,200,{cancelled:N})}async function Xe(a){let I=ct().slice(0,8),j=a.threadId,y=!j;j||(j=(await H.createThread(`thread-${ct()}`,[])).id,yt.set(j,"project_model")),y&&await H.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:a.reason}),await H.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:I,responseText:y?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:I,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:j,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:y},P=C.enqueue(A);return{jobId:I,position:P,threadId:j}}async function Mt(a,I){let j=decodeURIComponent(a),y=await ue.findModelProposal(j);if(!y){_(I,404,{error:"Model proposal not found"});return}_(I,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:y})}async function wt(a,I,j){let y=decodeURIComponent(a),A=[];for await(let F of I)A.push(typeof F=="string"?Buffer.from(F):F);let P;try{P=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(j,400,{error:"Invalid JSON"});return}let O=(P.changes??[]).flatMap(F=>{if(!Array.isArray(F.path)||F.path.length===0)return[];let se=F.path.filter(te=>typeof te=="string"||typeof te=="number");if(se.length!==F.path.length)return[];let me=Array.isArray(F.decisionIds)?F.decisionIds.filter(te=>typeof te=="string"):void 0;return[{path:se,value:F.value,remove:F.remove===!0,decisionIds:me}]});if(O.length===0){_(j,400,{error:"No selected model changes"});return}let $=(P.changeSummaries??[]).flatMap(F=>{if(!F||typeof F!="object")return[];let se=Array.isArray(F.path)?F.path.filter(me=>typeof me=="string"||typeof me=="number"):void 0;return Array.isArray(F.path)&&se?.length!==F.path.length?[]:[{group:typeof F.group=="string"?F.group:void 0,label:typeof F.label=="string"?F.label:void 0,detail:typeof F.detail=="string"?F.detail:void 0,path:se,value:F.value,currentValue:F.currentValue}]}),q=await ue.findModelProposal(y);if(!q){_(j,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(j,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(j,409,{error:`Model proposal is already ${q.status}.`});return}let N=q.decisionIds.map(F=>{let se=q.changes?.filter(ge=>ge.decisionIds.includes(F)).length??0,me=O.filter(ge=>ge.decisionIds?.includes(F)).length,te=me===0?"unprojected":se>me?"partially_projected":"projected";return{decisionId:F,status:te}}),J=await W.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:O.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:N}),he=await ue.applySelectedModelProposal(y,O,$);if(!he){_(j,404,{error:"Model proposal not found"});return}if(he.threadId){let F=nn(P.provider),se=typeof P.model=="string"&&P.model?P.model:void 0;await H.appendMessage(he.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${he.id}`,responseText:"",provider:F,model:se})}_(j,200,{proposal:he,projection:J})}async function Ci(a,I,j){let y=decodeURIComponent(a),{provider:A,model:P}=await _n(I),O=await ue.dismissModelProposal(y);if(!O){_(j,404,{error:"Model proposal not found"});return}O.threadId&&await H.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${O.id}`,responseText:"",provider:A,model:P}),_(j,200,{proposal:O})}async function _n(a){try{let I=[];for await(let y of a)I.push(typeof y=="string"?Buffer.from(y):y);if(I.length===0)return{};let j=JSON.parse(Buffer.concat(I).toString());return{provider:nn(typeof j.provider=="string"?j.provider:void 0),model:typeof j.model=="string"&&j.model?j.model:void 0,agentSettings:qt(j)}}catch{return{}}}async function Js(a){let I=yt.get(a);if(I)return I;let A=(await H.getThread(a))?.messages.find(P=>P.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return yt.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return yt.set(a,"project_model"),"project_model"}async function Ls(a,I){let j=[];for await(let q of a)j.push(typeof q=="string"?Buffer.from(q):q);let y;if(j.length>0)try{y=JSON.parse(Buffer.concat(j).toString("utf-8")).serverUrl}catch{}let A=[];u.claude?.available&&u.claude.mcp&&!u.claude.mcp.found&&A.push(await Rr(y)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&A.push(await Ar(y)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&A.push(await jr(y,u.copilot.path??k));let[P,O,$]=await Promise.all([to(o),no(o),io(o,u.copilot?.path??k)]);u.claude&&(u.claude.mcp=P),u.codex&&(u.codex.mcp=O),u.copilot&&(u.copilot.mcp=$),_(I,200,{results:A,capabilities:{providers:u}})}async function qs(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let A=await W.recordDirectModelMutation({key:`components.${y.name}`,value:{description:""},claim:`${y.name} is an explicitly governed component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{added:!0,alreadyExists:!1,...A})}async function Fs(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.name||typeof y.name!="string"){_(I,400,{error:"Missing or invalid name"});return}let A=await W.recordDirectModelMutation({key:`components.${y.name}`,value:null,claim:`${y.name} is not governed as a component in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...A})}async function Us(a,I){let j=[];for await(let O of a)j.push(typeof O=="string"?Buffer.from(O):O);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"||typeof y.value!="string"){_(I,400,{error:"Missing or invalid path/value"});return}let A=y.value;try{let O=JSON.parse(y.value);O&&typeof O=="object"&&(A=O)}catch{}let P=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:A,claim:`${y.path} uses ${y.value} in the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{updated:!0,...P})}async function zs(a,I){let j=[];for await(let P of a)j.push(typeof P=="string"?Buffer.from(P):P);let y;try{y=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(I,400,{error:"Invalid JSON"});return}if(!y.path||typeof y.path!="string"){_(I,400,{error:"Missing or invalid path"});return}let A=await W.recordDirectModelMutation({key:`tokens.${y.path}`,value:null,claim:`${y.path} is intentionally absent from the product model.`});await ue.applyCanonicalEntries(await W.getCanonicalModelEntries()),_(I,200,{removed:!0,...A})}function Ws(a,I){let j=d??"http://localhost:3000";if(!d){let A=a.headers.referer||a.headers.origin;if(A)try{let P=new URL(typeof A=="string"?A:A[0]||"");(P.hostname==="localhost"||P.hostname==="127.0.0.1")&&(j=P.origin)}catch{}}let y=Do(v,j);I.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),I.end(y)}async function Hs(a){let I=Date.now();if(It&&I<It.expires){_(a,200,It.data);return}try{let{scanForComponents:j}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:y}=await import("./render-generator-HWFLZYC3.mjs"),A=await j(o);It={data:A,expires:I+5e3},y(A,o,En).then(P=>{En=P}).catch(P=>console.warn("[Bridge] Render generation failed:",P)),_(a,200,A)}catch(j){console.error("[Bridge] Scanner error:",j),_(a,500,{error:"Failed to scan components"})}}async function Gs(a){let I=[Be(o,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Be(o,"packages","popmelt","dist","canvas.mjs")];try{let j=ql(import.meta.url);I.unshift(Be(Bl(j),"canvas.mjs"))}catch{}for(let j of I)try{let y=await As(j,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(y);return}catch{}console.error("[Bridge] Canvas bundle not found in:",I),_(a,404,{error:"Canvas bundle not found"})}async function Vs(a,I){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(I,400,{error:"Invalid filename"});return}try{let j=[Be(c,a),Be(o,".popmelt","artifacts","thread-media",a),Be(o,".popmelt","artifacts","eval-screenshots",a),Be(o,".popmelt","evals","screenshots",a),Be(o,".popmelt","screenshots",a)],y;for(let O of j)try{y=await As(O);break}catch{}if(!y)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),P=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";I.writeHead(200,{"Content-Type":P,"Cache-Control":"public, max-age=3600"}),I.end(y)}catch{_(I,404,{error:"File not found"})}}function sn(a){return`/files/${Ai(a)}`}async function Ks(a,I){let j=await H.getThread(a);if(!j){_(I,404,{error:"Thread not found"});return}let y=j.messages.filter(N=>N.role==="assistant"&&N.responseText?.includes("Model suggestion ready")),A=await(y.length>0?ue.findModelProposalsByThread(a):Promise.resolve([])),P=await Promise.all(A.map(async(N,J)=>{if(N.authorityStatus==="accepted")return N;let he=(await Promise.all(N.decisionIds.map(F=>W.findPendingProposalForLegacyDecision(F)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??y[J]?.jobId??y.at(-1)?.jobId,underlyingProposalId:he?.proposalId,underlyingClaim:he?.claim}})),O=[...P].sort((N,J)=>J.updatedAt-N.updatedAt)[0]??null,$=j.elementIdentifiers.some(N=>N.startsWith("codex-session:"))?await W.findPendingProposalsForThread(a):[],q=j.messages.map(({screenshotPath:N,screenshotPaths:J,imagePaths:he,attachmentFiles:F,replyImagePaths:se,...me})=>({...me,...N?{screenshotUrl:sn(N)}:{},...J?{screenshotUrls:Object.fromEntries(Object.entries(J).map(([te,ge])=>[te,sn(ge)]))}:{},...he?{imageUrls:Object.fromEntries(Object.entries(he).map(([te,ge])=>[te,ge.map(sn)]))}:{},...F?{attachments:Object.fromEntries(Object.entries(F).map(([te,ge])=>[te,ge.map(({path:oe,...ve})=>({...ve,url:sn(oe)}))]))}:{},...se?{replyImageUrls:se.map(sn)}:{}}));_(I,200,{id:j.id,createdAt:j.createdAt,messages:q,modelProposal:O,modelProposals:P,decisionCandidates:$})}async function Qs(a,I){let j=decodeURIComponent(a);if(!await H.deleteThread(j)){_(I,404,{deleted:!1,error:"Thread not found"});return}_(I,200,{deleted:!0})}let jo=9,Mo=!1;for(let a=t;a<t+jo;a++)try{await rp(be,a),v=a,Mo=!0,console.log(`[\u22B9 is watching :${v}]`);break}catch(I){if(I.code==="EADDRINUSE"){let j=await Mi(a);if(kn(j,{projectId:r,version:dt,restartMode:g}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw I}if(!Mo)throw new Error(`[Bridge] All ports ${t}\u2013${t+jo-1} in use`);for(let[a,I]of Object.entries(u))!I.available||!I.path||h(a,I.path).then(j=>{if(j)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),I.available=!1,I.path=null;for(let y of K)ji(y,{type:"capabilities_changed",data:{}})}});let Xs=setInterval(()=>{Cs(c).catch(()=>{}),V.sweep().catch(()=>{})},zl),Eo=setInterval(()=>{z.expireStale().becameEmpty&&L()},Hl);return Eo.unref?.(),{port:v,projectId:r,storeId:s.storeId,close:async()=>{clearInterval(Xs),clearInterval(Eo),x(),z.clear(),await V.cleanupPartials(),await T.destroyAsync(),C.destroy();for(let a of K)try{a.res.end()}catch{}return K.clear(),new Promise(a=>{be.close(()=>a())})}}}async function Cs(i){try{let e=await _l(i),t=Date.now();for(let n of e){let o=Be(i,n);try{let r=await $l(o);t-r.mtimeMs>Wl&&await Ol(o)}catch{}}}catch{}}var hp=1111,Ns=3e4,gp=8e3;async function yp(i){return up(i).catch(()=>i)}async function Bs(i,e){let n=(await pp(e,"utf8").catch(()=>"")).slice(-gp).trim();return new Error(n?`${i}
|
|
235
237
|
Bridge log (${e}):
|
|
236
|
-
${n}`:i)}async function
|
|
238
|
+
${n}`:i)}async function Yf(i){if(process.env.NODE_ENV==="production"&&!i?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(i?.detached){let t=await Ip(i);if(i.manageLease===!1)return t;let n=await $o({port:t.port,projectId:t.projectId});if(!n)return console.warn("[popmelt] detached bridge started without a process lease"),t;let o=Oo(n);return{...t,close:async()=>{o(),await n.release()}}}let e=await Ds(i);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Ip(i){let e=i.port??hp,t=await yp(i.projectRoot??process.cwd()),n=Lt(t),o=await Bn(t);for(let b=e;b<e+10;b++){let k=await Mi(b);if(k&&k.projectId===n){if(k.version&&k.version!==dt){if(k.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${b}/shutdown`,{method:"POST"})}catch{}await new Promise(f=>setTimeout(f,500));break}continue}if(!kn(k,{projectId:n,version:dt,restartMode:"detached"}))continue;let S=i.devOrigin;if(S&&k.devOrigin!==S)try{await fetch(`http://127.0.0.1:${b}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:S})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,storeId:o.storeId,close:async()=>{}}}}let r=Ao(mp(fp(import.meta.url)),"bridge-entry.mjs"),s=Ao(t,".popmelt"),d=Ao(s,"bridge.log");await lp(s,{recursive:!0}),await cp(d,`
|
|
237
239
|
[${new Date().toISOString()}] Starting detached bridge
|
|
238
|
-
`);let c=
|
|
240
|
+
`);let c=dp(d,"a"),l;try{l=sp(process.execPath,[r],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:t,POPMELT_DEV_ORIGIN:i.devOrigin??"",POPMELT_COPILOT_PATH:i.copilotPath??""}})}finally{ap(c)}let w=null;l.once("error",b=>{w=`spawn error: ${b.message}`}),l.once("exit",(b,k)=>{w=`child exited before becoming healthy (${k?`signal ${k}`:`code ${b??"unknown"}`})`}),l.unref();let R=Date.now()+Ns;for(;Date.now()<R;){if(await new Promise(b=>setTimeout(b,100)),w)throw await Bs(`[Bridge] Detached bridge ${w}`,d);for(let b=e;b<e+10;b++){let k=await Mi(b);if(kn(k,{projectId:n,version:dt,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=n,{port:b,projectId:n,storeId:o.storeId,close:async()=>{}}}}throw l.kill("SIGTERM"),await Bs(`[Bridge] Detached bridge failed to start within ${Ns/1e3}s (port ${e})`,d)}export{Nt as ImprintService,Dt as ImprintStore,Jt as formatImprintPrompt,Ni as imprintExplanationRef,Bt as parseImprintDraft,ea as qualifyImprintRelation,Yf as startPopmelt};
|