@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
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
2
|
+
import{spawn as lm}from"child_process";import{readFile as pm,unlink as um}from"fs/promises";import{join as mm}from"path";import{execFileSync as _p,spawn as ea}from"child_process";import{randomUUID as pt}from"crypto";import{mkdir as Cp,readFile as ta,readdir as $p,realpath as Op,stat as Dp,unlink as Np,writeFile as Ho}from"fs/promises";import{createServer as Bp}from"http";import{tmpdir as Jp}from"os";import{basename as Wo,dirname as Lp,isAbsolute as aa,join as Je,relative as qp,resolve as Fp}from"path";import{fileURLToPath as Up}from"url";function ci(t,e){return`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -29,25 +29,27 @@ import{spawn as am}from"child_process";import{readFile as dm,unlink as cm}from"f
|
|
|
29
29
|
});
|
|
30
30
|
</script>
|
|
31
31
|
</body>
|
|
32
|
-
</html>`}import{createHash as
|
|
33
|
-
`)}async function In(t,e,n,o){let r=
|
|
34
|
-
`)}import{randomUUID as dt}from"crypto";var
|
|
35
|
-
`,"utf8"),await o.sync()}finally{await o.close()}try{await dd(n,t)}catch(r){throw await cd(n).catch(()=>{}),r}}function pd(t,e){return{version:1,projectId:t,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function ud(t,e){let n=t.explanations.findIndex(o=>o.id===e.id);n>=0?t.explanations[n]=Ne(e):t.explanations.push(Ne(e))}function tr(t,e){let n=Ne(t);for(let o of e)if(o.op==="add_explanation"){if(n.explanations.some(r=>r.id===o.explanation.id))throw new Error(`Imprint explanation already exists: ${o.explanation.id}`);n.explanations.push(Ne(o.explanation))}else if(o.op==="replace_explanation")ud(n,o.explanation);else if(o.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==o.explanationId),n.relations=n.relations.filter(r=>r.fromId!==o.explanationId&&r.toId!==o.explanationId);else if(o.op==="add_concrete")n.concrete.some(r=>r.id===o.concrete.id)||n.concrete.push(Ne(o.concrete));else if(o.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==o.concreteId),n.relations=n.relations.filter(r=>r.fromId!==o.concreteId&&r.toId!==o.concreteId);else if(o.op==="add_evidence"){let r=n.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);r.evidence.some(i=>i.id===o.evidence.id)||(r.evidence.push(Ne(o.evidence)),r.updatedAt=o.evidence.createdAt)}else if(o.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);Object.assign(r,Ne(o.patch),{updatedAt:o.updatedAt})}else if(o.op==="add_relation"){let r=o.relation,i=n.explanations.find(l=>l.id===r.fromId),s=n.explanations.find(l=>l.id===r.toId),a=n.concrete.some(l=>l.id===r.fromId),d=n.concrete.some(l=>l.id===r.toId);if(pi(r.type)){if(!(r.type==="expresses"?!!((i||a)&&s):!!(i&&s)))throw new Error(`Imprint ${r.type} relation has invalid endpoints: ${r.id}`);if(n.relations.some(v=>v.type===r.type&&v.fromId===r.fromId&&v.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toId}`);if(r.type==="expresses"&&i&&s){if(Ft(i,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let v=new Map;for(let R of n.relations)R.type==="expresses"&&v.set(R.fromId,[...v.get(R.fromId)??[],R.toId]);let x=[r.toId],b=new Set;for(;x.length;){let R=x.pop();if(R===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);b.has(R)||(b.add(R),x.push(...v.get(R)??[]))}}}else if(!i||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);n.relations.some(l=>l.id===r.id)||n.relations.push(Ne(r))}else o.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==o.relationId));return n}function md(t,e){let n=[],o=Ne(t);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=o.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:Ne(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=o.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:Ne(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=o.explanations.find(a=>a.id===i);s&&n.unshift({op:"replace_explanation",explanation:Ne(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=o.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:Ne(i)})}o=tr(o,[r])}return n}function fi(t){return t.op==="add_explanation"||t.op==="replace_explanation"?[t.explanation.id]:t.op==="remove_explanation"||t.op==="add_evidence"||t.op==="revise_explanation"?[t.explanationId]:t.op==="add_relation"?[t.relation.fromId,t.relation.toId]:[]}var Yn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=zt(e,".popmelt","imprint"),this.manifestPath=zt(this.imprintDir,"manifest.json"),this.graphPath=zt(this.imprintDir,"graph.json"),this.journalDir=zt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ui(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 n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),o=(await ad(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=pd(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<o.length;a++){let d=JSON.parse(await ui(zt(this.journalDir,o[a]),"utf8")),{hash:l,...v}=d;if(d.sequence!==a+1||d.previousHash!==s||l!==mi(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=tr(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:At(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let n=await this.loadRaw(),o=At(n.graph),r=new Map(o.relations.map(s=>[s.id,s])),i=[];for(let s of n.graph.relations){let a=r.get(s.id);a&&a.type===s.type&&a.fromId===s.fromId&&a.toId===s.toId||(i.push({op:"remove_relation",relationId:s.id}),a&&i.push({op:"add_relation",relation:a}))}if(i.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${n.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:i}),{migrated:!0,relationMutations:i.length}}return await Mt(this.graphPath,o),await Mt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let o=await this.load();if(o.transactions.some(x=>x.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=o.graph.head.sequence+1,i=md(o.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:o.graph.head.hash,source:e.source,summary:e.summary,mutations:Ne(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:mi(s)},d=tr(o.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Mt(zt(this.journalDir,l),a);let v={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Mt(this.graphPath,d),await Mt(this.manifestPath,v),n={graph:d,transaction:a}}),await this.writeChain,n}async undo(e,n,o,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(fi));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(v=>fi(v).some(x=>a.has(x)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:o,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Mt(this.graphPath,e.graph),await Mt(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 fd=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),hd=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"]),gd=[/\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],yd=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function or(t){return!!(t&&yd.test(t))}function Id(t){return t.scope.kind==="project"||or(`${t.statement} ${t.rationale}`)}function wd(t){let e=t?.scope.values.filter(n=>n!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function vd(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function bd(t){return t.length>4&&t.endsWith("ies")?[t,`${t.slice(0,-3)}y`]:t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?[t,t.slice(0,-1)]:[t]}function at(t){return new Set(vd(t).split(" ").filter(e=>e.length>2&&!hd.has(e)).flatMap(bd))}function hi(t){return t.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function xd(t){if(t)for(let e of gd){let n=e.exec(t);if(!n||n.index<=0)continue;let o=hi(t.slice(0,n.index)),r=hi(t.slice(n.index+n[0].length));if(o&&r)return{target:o,reference:r}}}function gt(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function nr(t){return!t||!Array.isArray(t.values)||t.values.length===0?{kind:"project",values:["*"]}:{kind:t.kind,values:[...new Set(t.values.map(e=>e.trim()).filter(Boolean))]}}function yt(t,e,n){return{id:dt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:t.threadId,jobId:t.jobId,createdAt:t.occurredAt??new Date().toISOString()}}function ve(t,e=800){return typeof t=="string"?t.trim().slice(0,e):""}function gi(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(o=>typeof o=="string"&&!!o.trim());return n.length?{kind:e.kind,values:n}:void 0}function yi(t,e){if(!t||!e.trim())return{found:!1};let n=t;for(let o of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(o);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,o))n=n[o];else return{found:!1};return{found:!0,value:n}}function bn(t,e={}){let n=[...t.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],o=t.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),r=n.at(-1)?.[1],i,s=[];if(r)i=r;else{let d=[...t.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:o,error:"imprint assessment is missing"};try{let l=JSON.parse(d);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:o,error:"imprint assessment is missing"};let v=l;i=v.imprint,s=Array.isArray(v.annotations)?v.annotations:[]}catch{return{visibleText:o,error:"resolution envelope is invalid"}}}try{let a=typeof i=="string"?JSON.parse(i):i;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("imprint assessment is invalid");if(a.decision==="none"){let f=String(a.reason);if(!fd.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(a.usedExplanationIds)?a.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],w=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...g])].some(E=>!w.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(k=>{let C=e.context?.explanations.find(z=>z.id===k);return w.has(k)&&C&&(C.state==="emerging"||C.state==="testing")&&!E.has(k)});if(D.length){let k=a.grounding,C=typeof k?.explanationId=="string"&&D.includes(k.explanationId)?k.explanationId:D[0],z=ve(k?.question,300);return{draft:{decision:"apply",summary:{title:ve(a.summary?.title,120)||"Applied shared understanding",detail:ve(a.summary?.detail,500)||ve(e.requestText||o,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:o}}}if(f==="duplicate"){let E=ve(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!E)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let k=e.context?.explanations.find(C=>C.id===E);if(!k)throw new Error("duplicate assessment must cite a surfaced explanation");if(or(e.requestText)&&!Id(k))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:o}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:o}}if(a.decision==="recognize"){let f=ve(a.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=a.summary,w={title:ve(g?.title,120),detail:ve(g?.detail,500)};if(!w.title||!w.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:w},visibleText:o}}if(a.decision==="apply"){let f=a.summary,p={title:ve(f?.title,120),detail:ve(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let w=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!w.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:o};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(E=>{let D=w.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!u.has(E)});if(!M.length){if(g.every(D=>w.get(D)?.state==="grounded"||u.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:o};throw new Error("application must cite a surfaced ungrounded explanation")}let h=a.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:ve(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:o}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,l=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let v={kind:l,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!v.title||!v.detail)throw new Error("summary title and detail are required");let x=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],b=[];for(let f of Array.isArray(a.mutations)?a.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let g=ve(p.statement),w=ve(p.rationale);if(!g||!w)continue;b.push({op:"add",clientId:ve(p.clientId,100)||void 0,kind:p.kind,statement:g,rationale:w,scope:gi(p.scope),rootReason:ve(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let g={op:"revise",explanationId:p.explanationId,statement:ve(p.statement)||void 0,rationale:ve(p.rationale)||void 0,scope:gi(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=ve(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=ve(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=ve(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=ve(p.modelPath,300);g&&b.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:g,rationale:ve(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&b.push({op:"retire",explanationId:p.explanationId,reason:ve(p.reason)})}let R=a.grounding,P=R&&typeof R.explanationId=="string"&&ve(R.question)?{explanationId:R.explanationId,question:ve(R.question,300)}:void 0;return{draft:{decision:"mutate",summary:v,appliedExplanationIds:x,mutations:b,grounding:P},visibleText:o}}catch(a){return{visibleText:o,error:a instanceof Error?a.message:String(a)}}}function xn(t,e={}){let n=t?.explanations??[],o=new Set(t?.pendingGroundingExplanationIds??[]),r=new Set(t?.correctionExplanationIds??[]),i=or(e.requestText),s=t?.retrievalIntent,a=t?.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.",...n.length?["","Relevant explanations from the project imprint:",...n.map((d,l)=>[`${l+1}. [${d.state}; ${d.kind}] ${d.statement}`,` - Why: ${d.rationale}`,` - Scope: ${d.scope.kind} ${d.scope.values.join(", ")}`,` - Explanation: ${d.id}`,...o.has(d.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(d.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...d.concrete.map(v=>` - Concrete terminal: ${v.modelPath} = ${JSON.stringify(v.value)}`)].join(`
|
|
32
|
+
</html>`}import{createHash as Pd,randomUUID as kd}from"crypto";import{isAbsolute as Td,relative as Rd}from"path";function qt(t,e){return!t||e||t.attention!=="response_requested"?t:{...t,attention:"response_available"}}function yn(t){let e=Array.from(new Set((t.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],o=t.decisionRequired?"decision_required":t.question||t.groundingRequired?"response_requested":t.reviewRequired||t.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return t.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:t.imprintTransactionId}),{attention:o,outcomes:n}}function Ft(t){return t.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
33
|
+
`)}async function In(t,e,n,o){let r=Ft(e);if(!(!r&&n.length===0))try{let i=await t.contextualize({action:r||void 0,subjectHints:n,maxPackets:2,maxEstimatedTokens:700});if(i.actionPacket.decisions.length===0&&i.reviewSelection.packets.length===0)return;let s=new Map(i.actionPacket.implementation.map(d=>[d.decisionId,d.state])),a=new Map(i.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:i.source,...i.actionPacket.decisions.length>0?{acceptedTruth:{decisions:i.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:a.get(d.id)??"unverified"})),conflicts:i.actionPacket.conflicts,truncated:i.actionPacket.completeness.status==="truncated"}}:{},packets:i.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(l=>l.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:i.reviewSelection.completeness.status==="truncated",estimatedTokens:i.actionPacket.budget.estimatedTokens+i.reviewSelection.completeness.estimatedTokens}}catch(i){o?.(i);return}}function wn(t){if(!t?.packets.length&&!t?.acceptedTruth?.decisions.length)return"";let e=t.packets.some(o=>o.presentation==="surface_before_action");return["","## Contextual product memory","",...t.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.",...t.acceptedTruth.decisions.flatMap((o,r)=>["",`${r+1}. [${o.kind}; ${o.effectiveState}] ${o.claim}`,` - Implementation: ${o.implementation}`,` - Verification: ${o.verification}`,...o.freshness.length?[` - Freshness warnings: ${o.freshness.join(", ")}`]:[],` - Decision: ${o.id}`]),...t.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...t.acceptedTruth.conflicts.map(o=>`- ${o.unresolvedQuestion}`)]:[],...t.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...t.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...t.packets.flatMap((o,r)=>["",`${r+1}. ${o.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${o.proposedKind??"unspecified"}`,` - Presentation: ${o.presentation}`,` - Packet: ${o.packetId}`,` - Evidence references available: ${o.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","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(`
|
|
34
|
+
`)}import{randomUUID as dt}from"crypto";var li={project:0,route:1,component:2,selector:2,file:3},pi={intention:0,principle:1,pattern:2};function Ut(t,e){let n=li[t.scope.kind]-li[e.scope.kind];return n!==0?n:pi[t.kind]-pi[e.kind]}function ui(t){return t==="expresses"||t==="excepts"}function rd(t,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 n=t.explanations.find(i=>i.id===e.fromId),o=t.explanations.find(i=>i.id===e.toId);if(!n||!o)return;let r=Ut(n,o);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function At(t){let e=structuredClone(t),n=new Set;return e.relations=t.relations.flatMap(o=>{let r=rd(t,o);if(!r)return[];let i=`${r.type}:${r.fromId}:${r.toId}`;return n.has(i)?[]:(n.add(i),[r])}),e}import{createHash as id}from"crypto";import{mkdir as sd,open as ad,readFile as mi,readdir as dd,rename as cd,unlink as ld}from"fs/promises";import{dirname as pd,join as zt}from"path";function Ne(t){return structuredClone(t)}function fi(t){return id("sha256").update(JSON.stringify(t)).digest("hex")}async function Mt(t,e){await sd(pd(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`,o=await ad(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
35
|
+
`,"utf8"),await o.sync()}finally{await o.close()}try{await cd(n,t)}catch(r){throw await ld(n).catch(()=>{}),r}}function ud(t,e){return{version:1,projectId:t,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function md(t,e){let n=t.explanations.findIndex(o=>o.id===e.id);n>=0?t.explanations[n]=Ne(e):t.explanations.push(Ne(e))}function nr(t,e){let n=Ne(t);for(let o of e)if(o.op==="add_explanation"){if(n.explanations.some(r=>r.id===o.explanation.id))throw new Error(`Imprint explanation already exists: ${o.explanation.id}`);n.explanations.push(Ne(o.explanation))}else if(o.op==="replace_explanation")md(n,o.explanation);else if(o.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==o.explanationId),n.relations=n.relations.filter(r=>r.fromId!==o.explanationId&&r.toId!==o.explanationId);else if(o.op==="add_concrete")n.concrete.some(r=>r.id===o.concrete.id)||n.concrete.push(Ne(o.concrete));else if(o.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==o.concreteId),n.relations=n.relations.filter(r=>r.fromId!==o.concreteId&&r.toId!==o.concreteId);else if(o.op==="add_evidence"){let r=n.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);r.evidence.some(i=>i.id===o.evidence.id)||(r.evidence.push(Ne(o.evidence)),r.updatedAt=o.evidence.createdAt)}else if(o.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===o.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${o.explanationId}`);Object.assign(r,Ne(o.patch),{updatedAt:o.updatedAt})}else if(o.op==="add_relation"){let r=o.relation,i=n.explanations.find(l=>l.id===r.fromId),s=n.explanations.find(l=>l.id===r.toId),a=n.concrete.some(l=>l.id===r.fromId),d=n.concrete.some(l=>l.id===r.toId);if(ui(r.type)){if(!(r.type==="expresses"?!!((i||a)&&s):!!(i&&s)))throw new Error(`Imprint ${r.type} relation has invalid endpoints: ${r.id}`);if(n.relations.some(v=>v.type===r.type&&v.fromId===r.fromId&&v.toId===r.toId))throw new Error(`Duplicate imprint relation: ${r.type}:${r.fromId}:${r.toId}`);if(r.type==="expresses"&&i&&s){if(Ut(i,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${r.id}`);let v=new Map;for(let R of n.relations)R.type==="expresses"&&v.set(R.fromId,[...v.get(R.fromId)??[],R.toId]);let T=[r.toId],b=new Set;for(;T.length;){let R=T.pop();if(R===r.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${r.id}`);b.has(R)||(b.add(R),T.push(...v.get(R)??[]))}}}else if(!i||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${r.id}`);n.relations.some(l=>l.id===r.id)||n.relations.push(Ne(r))}else o.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==o.relationId));return n}function fd(t,e){let n=[],o=Ne(t);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=o.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:Ne(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=o.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:Ne(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=o.explanations.find(a=>a.id===i);s&&n.unshift({op:"replace_explanation",explanation:Ne(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=o.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:Ne(i)})}o=nr(o,[r])}return n}function hi(t){return t.op==="add_explanation"||t.op==="replace_explanation"?[t.explanation.id]:t.op==="remove_explanation"||t.op==="add_evidence"||t.op==="revise_explanation"?[t.explanationId]:t.op==="add_relation"?[t.relation.fromId,t.relation.toId]:[]}var Yn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=zt(e,".popmelt","imprint"),this.manifestPath=zt(this.imprintDir,"manifest.json"),this.graphPath=zt(this.imprintDir,"graph.json"),this.journalDir=zt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await mi(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),o=(await dd(this.journalDir).catch(a=>{if(a.code==="ENOENT")return[];throw a})).filter(a=>/^\d{12}-.+\.json$/.test(a)).sort(),r=ud(this.projectId,e.createdAt),i=[],s=null;for(let a=0;a<o.length;a++){let d=JSON.parse(await mi(zt(this.journalDir,o[a]),"utf8")),{hash:l,...v}=d;if(d.sequence!==a+1||d.previousHash!==s||l!==fi(v))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=nr(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:At(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let n=await this.loadRaw(),o=At(n.graph),r=new Map(o.relations.map(s=>[s.id,s])),i=[];for(let s of n.graph.relations){let a=r.get(s.id);a&&a.type===s.type&&a.fromId===s.fromId&&a.toId===s.toId||(i.push({op:"remove_relation",relationId:s.id}),a&&i.push({op:"add_relation",relation:a}))}if(i.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${n.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:i}),{migrated:!0,relationMutations:i.length}}return await Mt(this.graphPath,o),await Mt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let o=await this.load();if(o.transactions.some(T=>T.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=o.graph.head.sequence+1,i=fd(o.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:o.graph.head.hash,source:e.source,summary:e.summary,mutations:Ne(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},a={...s,hash:fi(s)},d=nr(o.graph,a.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:a.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await Mt(zt(this.journalDir,l),a);let v={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Mt(this.graphPath,d),await Mt(this.manifestPath,v),n={graph:d,transaction:a}}),await this.writeChain,n}async undo(e,n,o,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let a=new Set(s.mutations.flatMap(hi));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(v=>hi(v).some(T=>a.has(T)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:o,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Mt(this.graphPath,e.graph),await Mt(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 hd=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),gd=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"]),yd=[/\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],Id=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function rr(t){return!!(t&&Id.test(t))}function wd(t){return t.scope.kind==="project"||rr(`${t.statement} ${t.rationale}`)}function vd(t){let e=t?.scope.values.filter(n=>n!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function bd(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function xd(t){return t.length>4&&t.endsWith("ies")?[t,`${t.slice(0,-3)}y`]:t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?[t,t.slice(0,-1)]:[t]}function at(t){return new Set(bd(t).split(" ").filter(e=>e.length>2&&!gd.has(e)).flatMap(xd))}function gi(t){return t.replace(/^\s*(?:please\s+)?(?:let(?:'|’)s\s+)?(?:make|apply|use|keep|change|update)\s+/i,"").replace(/[\s,.:;!?]+$/g,"").trim().slice(0,240)}function Sd(t){if(t)for(let e of yd){let n=e.exec(t);if(!n||n.index<=0)continue;let o=gi(t.slice(0,n.index)),r=gi(t.slice(n.index+n[0].length));if(o&&r)return{target:o,reference:r}}}function gt(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function or(t){return!t||!Array.isArray(t.values)||t.values.length===0?{kind:"project",values:["*"]}:{kind:t.kind,values:[...new Set(t.values.map(e=>e.trim()).filter(Boolean))]}}function yt(t,e,n){return{id:dt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:t.threadId,jobId:t.jobId,createdAt:t.occurredAt??new Date().toISOString()}}function ve(t,e=800){return typeof t=="string"?t.trim().slice(0,e):""}function yi(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let n=e.values.filter(o=>typeof o=="string"&&!!o.trim());return n.length?{kind:e.kind,values:n}:void 0}function Ii(t,e){if(!t||!e.trim())return{found:!1};let n=t;for(let o of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(o);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,o))n=n[o];else return{found:!1};return{found:!0,value:n}}function bn(t,e={}){let n=[...t.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],o=t.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),r=n.at(-1)?.[1],i,s=[];if(r)i=r;else{let d=[...t.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:o,error:"imprint assessment is missing"};try{let l=JSON.parse(d);if(!l||typeof l!="object"||Array.isArray(l)||!Object.prototype.hasOwnProperty.call(l,"imprint"))return{visibleText:o,error:"imprint assessment is missing"};let v=l;i=v.imprint,s=Array.isArray(v.annotations)?v.annotations:[]}catch{return{visibleText:o,error:"resolution envelope is invalid"}}}try{let a=typeof i=="string"?JSON.parse(i):i;if(!a||typeof a!="object"||Array.isArray(a))throw new Error("imprint assessment is invalid");if(a.decision==="none"){let f=String(a.reason);if(!hd.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(a.usedExplanationIds)?a.usedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[],w=new Set(e.context?.explanations.map(E=>E.id)??[]);if([...new Set([...p,...g])].some(E=>!w.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(P=>{let C=e.context?.explanations.find(z=>z.id===P);return w.has(P)&&C&&(C.state==="emerging"||C.state==="testing")&&!E.has(P)});if(D.length){let P=a.grounding,C=typeof P?.explanationId=="string"&&D.includes(P.explanationId)?P.explanationId:D[0],z=ve(P?.question,300);return{draft:{decision:"apply",summary:{title:ve(a.summary?.title,120)||"Applied shared understanding",detail:ve(a.summary?.detail,500)||ve(e.requestText||o,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:o}}}if(f==="duplicate"){let E=ve(a.duplicateOfExplanationId,100),D=a.scopeComparison;if(!E)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(D!=="equivalent"&&D!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let P=e.context?.explanations.find(C=>C.id===E);if(!P)throw new Error("duplicate assessment must cite a surfaced explanation");if(rr(e.requestText)&&!wd(P))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:o}}return{draft:{decision:"none",reason:f,...M.length?{usedExplanationIds:M}:{},...m?{appliedExplanationIds:m}:{}},visibleText:o}}if(a.decision==="recognize"){let f=ve(a.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=a.summary,w={title:ve(g?.title,120),detail:ve(g?.detail,500)};if(!w.title||!w.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:w},visibleText:o}}if(a.decision==="apply"){let f=a.summary,p={title:ve(f?.title,120),detail:ve(f?.detail,500)};if(!p.title||!p.detail)throw new Error("application summary title and detail are required");let g=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(E=>typeof E=="string"&&!!E.trim()):[];if(!g.length)throw new Error("application requires appliedExplanationIds");let w=new Map(e.context?.explanations.map(E=>[E.id,E])??[]);if(g.some(E=>!w.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:o};let u=new Set(e.context?.pendingGroundingExplanationIds??[]),M=g.filter(E=>{let D=w.get(E);return D&&(D.state==="emerging"||D.state==="testing")&&!u.has(E)});if(!M.length){if(g.every(D=>w.get(D)?.state==="grounded"||u.has(D)))return{draft:{decision:"none",reason:"application_only",appliedExplanationIds:g},visibleText:o};throw new Error("application must cite a surfaced ungrounded explanation")}let h=a.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:ve(h?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:o}}if(a.decision!==void 0&&a.decision!=="mutate")throw new Error("imprint decision is invalid");let d=a.summary,l=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(l)))throw new Error("summary.kind is invalid");let v={kind:l,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!v.title||!v.detail)throw new Error("summary title and detail are required");let T=Array.isArray(a.appliedExplanationIds)?a.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],b=[];for(let f of Array.isArray(a.mutations)?a.mutations:[]){if(!f||typeof f!="object")continue;let p=f;if(p.op==="add"&&["intention","principle","pattern"].includes(String(p.kind))){let g=ve(p.statement),w=ve(p.rationale);if(!g||!w)continue;b.push({op:"add",clientId:ve(p.clientId,100)||void 0,kind:p.kind,statement:g,rationale:w,scope:yi(p.scope),rootReason:ve(p.rootReason,300)||void 0})}else if(p.op==="revise"&&typeof p.explanationId=="string"){let g={op:"revise",explanationId:p.explanationId,statement:ve(p.statement)||void 0,rationale:ve(p.rationale)||void 0,scope:yi(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=ve(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=ve(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=ve(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=ve(p.modelPath,300);g&&b.push({op:"bind_concrete",explanationId:p.explanationId,modelPath:g,rationale:ve(p.rationale)})}else p.op==="retire"&&typeof p.explanationId=="string"&&b.push({op:"retire",explanationId:p.explanationId,reason:ve(p.reason)})}let R=a.grounding,S=R&&typeof R.explanationId=="string"&&ve(R.question)?{explanationId:R.explanationId,question:ve(R.question,300)}:void 0;return{draft:{decision:"mutate",summary:v,appliedExplanationIds:T,mutations:b,grounding:S},visibleText:o}}catch(a){return{visibleText:o,error:a instanceof Error?a.message:String(a)}}}function xn(t,e={}){let n=t?.explanations??[],o=new Set(t?.pendingGroundingExplanationIds??[]),r=new Set(t?.correctionExplanationIds??[]),i=rr(e.requestText),s=t?.retrievalIntent,a=t?.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.",...n.length?["","Relevant explanations from the project imprint:",...n.map((d,l)=>[`${l+1}. [${d.state}; ${d.kind}] ${d.statement}`,` - Why: ${d.rationale}`,` - Scope: ${d.scope.kind} ${d.scope.values.join(", ")}`,` - Explanation: ${d.id}`,...o.has(d.id)?[" - Grounding: already pending; do not ask again"]:[],...r.has(d.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...d.concrete.map(v=>` - Concrete terminal: ${v.modelPath} = ${JSON.stringify(v.value)}`)].join(`
|
|
36
36
|
`)),...t?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...t?.relations?.length?["","Known explanation topology:",...t.relations.map(d=>`- ${d.fromId} --${d.type}--> ${d.toId}: ${d.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."]:[],...a.length?["","Directly relevant challenged history (historical caveats, not current Imprint truth):",...a.map((d,l)=>[`${l+1}. [challenged; ${d.kind}] ${d.statement}`,` - Why it was previously proposed: ${d.rationale}`,` - Scope: ${d.scope.kind} ${d.scope.values.join(", ")}`,` - Historical explanation: ${d.id}`].join(`
|
|
37
37
|
`)),"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.",...i?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.",'As soon as one or more surfaced explanations become actively useful during the work, emit `<imprint-use>{"explanationIds":["<every actively useful surfaced explanation id>"]}</imprint-use>` immediately. This live receipt is hidden from conversational prose. Emit it at the point of use rather than waiting for the final response. Emit a later marker only when additional explanations become actively useful. Never emit it for explanations that were merely retrieved, read, searched, or considered.',"Treat Imprint as actively useful when a surfaced explanation materially informs an answer, recommendation, implementation choice, or other decision. Whenever it is actively useful, always cite every materially used surfaced explanation in `usedExplanationIds`. This produces a usage receipt only; it does not strengthen or mutate shared understanding. Do not cite explanations that were merely retrieved, read, or considered but did not influence the result.","`appliedExplanationIds` is narrower: include an explanation there only when it governed a completed implementation or other observable action that genuinely tests the explanation. Never use `appliedExplanationIds` for an answer-only, informational, research, or read-only request. An explanation may be used without being applied; every applied explanation is also understood to be used.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change","usedExplanationIds":["<every surfaced explanation that was actively useful, or omit when none>"]}',"A no-op reason cannot suppress genuine application evidence. When a completed action was governed by an ungrounded explanation, report decision apply directly so the summary and grounding question are intentional. Answering a question with that explanation is usage, not application.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"imprint":{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"expresses|excepts","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(`
|
|
38
|
-
`)}var vn=class{constructor(e,n){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Yn(e,n)}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 n=at(e.text??""),o=at((e.subjectHints??[]).join(" ")),r=xd(e.text),i=at(r?.target??""),s=at(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!n.size&&!o.size&&!a.size&&!d.size)return;let{graph:l}=await this.store.load(),v=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||d.has(h.id))).map(h=>{let m=at([h.statement,h.rationale].join(" ")),E=at(h.scope.values.join(" ")),D=gt(m,n),k=gt(E,n),C=gt(E,o),z=gt(m,o),X=D+k*.2+C*.25+z*.75+(h.state==="grounded"?.08:0)+(a.has(h.id)?1:0)+(d.has(h.id)?1:0),G=a.has(h.id)||d.has(h.id)||D>=.12||k>=.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)),x=Math.max(1,e.maxExplanations??6),b=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=gt(at(`${m.statement} ${m.rationale}`),h),D=gt(at(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=[],P=h=>{R.length<x&&!R.some(m=>m.id===h.id)&&R.push(h)};if(r&&(b(i).slice(0,2).forEach(({item:h})=>P(h)),b(s).slice(0,2).forEach(({item:h})=>P(h))),v.forEach(({item:h})=>P(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]:[])),w=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,...w];for(let h of w)f.add(h.id);let M=r?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=at(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),E=gt(m,i),D=gt(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:v.length>R.length||w.length<g.size,...r?{retrievalIntent:r}:{},...M.length?{historicalCaveats:M}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},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,n){let o=e.decision==="mutate"?e.mutations:[],r=n.applicationOccurred?o.flatMap(S=>S.op==="add"&&S.clientId?[S.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(o.length===0&&i.length===0)return;let s=n.occurredAt??new Date().toISOString(),a=await this.store.load(),d=new Map(a.graph.explanations.map(S=>[S.id,S])),l=new Map,v=new Map,x=[],b=new Set,R=new Set(n.pendingGroundingExplanationIds??[]),P=new Set(o.flatMap(S=>S.op==="revise"&&o.some(Q=>Q.op==="evidence"&&Q.stance==="challenges"&&Q.explanationId===S.explanationId)?[S.explanationId]:[])),f=new Set(o.flatMap(S=>S.op==="add"&&S.clientId?[S.clientId]:[])),p=S=>d.has(S)||f.has(S),g=new Set;for(let S of o)S.op==="relation"&&S.fromId!==S.toId&&p(S.fromId)&&p(S.toId)?(g.add(S.fromId),g.add(S.toId)):S.op==="supersede"&&S.explanationId!==S.replacementId&&p(S.explanationId)&&p(S.replacementId)?(g.add(S.explanationId),g.add(S.replacementId)):S.op==="bind_concrete"&&p(S.explanationId)&&yi(n.concreteModel,S.modelPath).found&&g.add(S.explanationId);let w=a.graph.explanations.length===0;for(let S of o){if(S.op!=="add")continue;let Q=!!(S.clientId&&g.has(S.clientId)),L=!!S.rootReason?.trim()||w;if(!Q&&!L)continue;w&&(w=!1);let K=dt();S.clientId&&l.set(S.clientId,K);let W=S.clientId?i.includes(S.clientId):!1,B={id:K,kind:S.kind,statement:S.statement,rationale:S.rationale,scope:nr(S.scope),state:W?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[yt(n,"supports",e.summary.detail)]};d.set(K,B),b.add(K),x.push({op:"add_explanation",explanation:B})}let u=S=>l.get(S)??S;for(let S of o){if(S.op!=="revise")continue;let Q=u(S.explanationId),L=d.get(Q);if(L?.state!=="grounded")continue;let K=dt(),W={id:K,kind:L.kind,statement:S.statement??L.statement,rationale:S.rationale??L.rationale,scope:S.scope?nr(S.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[yt(n,"supports",e.summary.detail)]};d.set(K,W),v.set(Q,K),b.add(K),x.push({op:"add_explanation",explanation:W});let B=Ft(L,W);B!==0&&x.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:B>0?Q:K,toId:B>0?K:Q,rationale:S.rationale??e.summary.detail,createdAt:s}})}let M=S=>{let Q=u(S);return v.get(Q)??Q};for(let S of o){if(S.op==="add")continue;if(S.op==="bind_concrete"){let L=M(S.explanationId);if(!d.has(L))continue;let K=yi(n.concreteModel,S.modelPath);if(!K.found)continue;let W=a.graph.concrete.find(B=>B.modelPath===S.modelPath&&JSON.stringify(B.value)===JSON.stringify(K.value));W||(W={id:dt(),modelPath:S.modelPath,value:structuredClone(K.value),createdAt:s,updatedAt:s},x.push({op:"add_concrete",concrete:W})),x.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:W.id,toId:L,rationale:S.rationale,createdAt:s}}),b.add(L);continue}if(S.op==="relation"){let L=M(S.fromId),K=M(S.toId);if(!d.has(L)||!d.has(K)||L===K)continue;S.type==="expresses"&&Ft(d.get(L),d.get(K))<0&&([L,K]=[K,L]),x.push({op:"add_relation",relation:{id:dt(),type:S.type,fromId:L,toId:K,rationale:S.rationale,createdAt:s}}),b.add(L),b.add(K);continue}if(S.op==="supersede"){let L=M(S.explanationId),K=M(S.replacementId);if(!d.has(L)||!d.has(K)||L===K)continue;x.push({op:"add_evidence",explanationId:L,evidence:yt(n,"challenges",S.reason)}),x.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:K},updatedAt:s}),b.add(L),b.add(K);continue}let Q=M(S.explanationId);if(d.has(Q))if(b.add(Q),S.op==="revise"){if(v.has(u(S.explanationId)))continue;let L=d.get(Q);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let K={...S.statement?{statement:S.statement}:{},...S.rationale?{rationale:S.rationale}:{},...S.scope?{scope:nr(S.scope)}:{},...S.reopenGrounding||P.has(S.explanationId)?{state:"testing"}:{}};x.push({op:"revise_explanation",explanationId:Q,patch:K,updatedAt:s})}else if(S.op==="evidence"){if(S.stance==="challenges"&&P.has(S.explanationId))continue;x.push({op:"add_evidence",explanationId:Q,evidence:yt(n,S.stance,S.summary)}),S.stance==="challenges"&&x.push({op:"revise_explanation",explanationId:Q,patch:{state:"challenged"},updatedAt:s})}else S.op==="retire"&&(x.push({op:"add_evidence",explanationId:Q,evidence:yt(n,"challenges",S.reason||"Retired after contradictory collaboration evidence.")}),x.push({op:"revise_explanation",explanationId:Q,patch:{state:"retired"},updatedAt:s}))}for(let S of i){let Q=M(S),L=d.get(Q);!L||L.state==="grounded"||L.state==="retired"||R.has(Q)&&!b.has(Q)||(b.has(Q)||(b.add(Q),x.push({op:"add_evidence",explanationId:Q,evidence:{...yt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&x.push({op:"revise_explanation",explanationId:Q,patch:{state:"testing"},updatedAt:s}))}let h=new Set(a.graph.relations.map(S=>`${S.type}:${S.fromId}:${S.toId}`)),m=x.filter(S=>{if(S.op!=="add_relation")return!0;let Q=`${S.relation.type}:${S.relation.fromId}:${S.relation.toId}`;return h.has(Q)?!1:(h.add(Q),!0)});if(!m.length)return;let E=dt(),D=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:m}),k=new Map(D.graph.explanations.map(S=>[S.id,S])),C=[...b].flatMap(S=>{let Q=k.get(S);if(!Q)return[];let L=!a.graph.explanations.some(W=>W.id===S),K=Q.state==="challenged"||Q.state==="retired";return[{explanationId:S,action:L?"added":K?"challenged":"revised",statement:Q.statement,state:Q.state}]}),z=i.map(M).find(S=>k.get(S)?.state==="testing"&&!R.has(S)),X=e.grounding?M(e.grounding.explanationId):z,G=X?k.get(X):void 0,Y=G?.state==="testing"&&!R.has(G.id)?{explanationId:G.id,question:e.grounding?.question||wd(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 n=e.occurredAt??new Date().toISOString(),o=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!o)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===o);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},a=[],d="";if(e.action==="yes"?(a.push({op:"add_evidence",explanationId:o,evidence:{...yt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:o,evidence:{...yt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"emerging"},updatedAt:n}),d=`Observed this time: ${i.statement}`),!a.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:dt(),committedAt:n,source:s,summary:d,mutations:a}),"applied"}};var Et=1,Sn="bridge";function Ii(t){return`codex-session:${t}`}function Rd(t,e){return`codex-${Sd("sha256").update(`${t}:${e}`).digest("hex").slice(0,16)}`}function wi(t){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:t,elements:[]}],styleModifications:[]}}function jd(t,e){let n=new Set,o=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();n.add(kd(s)?Td(e,s):s)},r=(i,s="",a=0)=>{if(!(a>5||i===null||i===void 0)){if(typeof i=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&o(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))o(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,l]of Object.entries(i))r(l,d,a+1)}};for(let i of t)r(i.toolInput);return[...n]}function vi(t,e,n,o,r,i){let s=bi(r,i);return["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${n}; the tool session is ${t}.`,"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.",wn(o),s].filter(Boolean).join(`
|
|
39
|
-
`)
|
|
38
|
+
`)}var vn=class{constructor(e,n){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Yn(e,n)}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 n=at(e.text??""),o=at((e.subjectHints??[]).join(" ")),r=Sd(e.text),i=at(r?.target??""),s=at(r?.reference??""),a=new Set(e.pendingGroundingExplanationIds??[]),d=new Set(e.correctionExplanationIds??[]);if(!n.size&&!o.size&&!a.size&&!d.size)return;let{graph:l}=await this.store.load(),v=l.explanations.filter(h=>h.state!=="retired"&&(h.state!=="challenged"||d.has(h.id))).map(h=>{let m=at([h.statement,h.rationale].join(" ")),E=at(h.scope.values.join(" ")),D=gt(m,n),P=gt(E,n),C=gt(E,o),z=gt(m,o),X=D+P*.2+C*.25+z*.75+(h.state==="grounded"?.08:0)+(a.has(h.id)?1:0)+(d.has(h.id)?1:0),G=a.has(h.id)||d.has(h.id)||D>=.12||P>=.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)),T=Math.max(1,e.maxExplanations??6),b=h=>l.explanations.filter(m=>m.state!=="retired"&&m.state!=="challenged").map(m=>{let E=gt(at(`${m.statement} ${m.rationale}`),h),D=gt(at(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=[],S=h=>{R.length<T&&!R.some(m=>m.id===h.id)&&R.push(h)};if(r&&(b(i).slice(0,2).forEach(({item:h})=>S(h)),b(s).slice(0,2).forEach(({item:h})=>S(h))),v.forEach(({item:h})=>S(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]:[])),w=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,...w];for(let h of w)f.add(h.id);let M=r?l.explanations.filter(h=>h.state==="challenged").map(h=>{let m=at(`${h.statement} ${h.rationale} ${h.scope.values.join(" ")}`),E=gt(m,i),D=gt(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:v.length>R.length||w.length<g.size,...r?{retrievalIntent:r}:{},...M.length?{historicalCaveats:M}:{},...a.size?{pendingGroundingExplanationIds:[...a]}:{},...d.size?{correctionExplanationIds:[...d]}:{},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,n){let o=e.decision==="mutate"?e.mutations:[],r=n.applicationOccurred?o.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[]):[],i=[...new Set([...e.appliedExplanationIds,...r])];if(o.length===0&&i.length===0)return;let s=n.occurredAt??new Date().toISOString(),a=await this.store.load(),d=new Map(a.graph.explanations.map(x=>[x.id,x])),l=new Map,v=new Map,T=[],b=new Set,R=new Set(n.pendingGroundingExplanationIds??[]),S=new Set(o.flatMap(x=>x.op==="revise"&&o.some(Q=>Q.op==="evidence"&&Q.stance==="challenges"&&Q.explanationId===x.explanationId)?[x.explanationId]:[])),f=new Set(o.flatMap(x=>x.op==="add"&&x.clientId?[x.clientId]:[])),p=x=>d.has(x)||f.has(x),g=new Set;for(let x of o)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)&&Ii(n.concreteModel,x.modelPath).found&&g.add(x.explanationId);let w=a.graph.explanations.length===0;for(let x of o){if(x.op!=="add")continue;let Q=!!(x.clientId&&g.has(x.clientId)),L=!!x.rootReason?.trim()||w;if(!Q&&!L)continue;w&&(w=!1);let K=dt();x.clientId&&l.set(x.clientId,K);let W=x.clientId?i.includes(x.clientId):!1,B={id:K,kind:x.kind,statement:x.statement,rationale:x.rationale,scope:or(x.scope),state:W?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[yt(n,"supports",e.summary.detail)]};d.set(K,B),b.add(K),T.push({op:"add_explanation",explanation:B})}let u=x=>l.get(x)??x;for(let x of o){if(x.op!=="revise")continue;let Q=u(x.explanationId),L=d.get(Q);if(L?.state!=="grounded")continue;let K=dt(),W={id:K,kind:L.kind,statement:x.statement??L.statement,rationale:x.rationale??L.rationale,scope:x.scope?or(x.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[yt(n,"supports",e.summary.detail)]};d.set(K,W),v.set(Q,K),b.add(K),T.push({op:"add_explanation",explanation:W});let B=Ut(L,W);B!==0&&T.push({op:"add_relation",relation:{id:dt(),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 v.get(Q)??Q};for(let x of o){if(x.op==="add")continue;if(x.op==="bind_concrete"){let L=M(x.explanationId);if(!d.has(L))continue;let K=Ii(n.concreteModel,x.modelPath);if(!K.found)continue;let W=a.graph.concrete.find(B=>B.modelPath===x.modelPath&&JSON.stringify(B.value)===JSON.stringify(K.value));W||(W={id:dt(),modelPath:x.modelPath,value:structuredClone(K.value),createdAt:s,updatedAt:s},T.push({op:"add_concrete",concrete:W})),T.push({op:"add_relation",relation:{id:dt(),type:"expresses",fromId:W.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(!d.has(L)||!d.has(K)||L===K)continue;x.type==="expresses"&&Ut(d.get(L),d.get(K))<0&&([L,K]=[K,L]),T.push({op:"add_relation",relation:{id:dt(),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(!d.has(L)||!d.has(K)||L===K)continue;T.push({op:"add_evidence",explanationId:L,evidence:yt(n,"challenges",x.reason)}),T.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(d.has(Q))if(b.add(Q),x.op==="revise"){if(v.has(u(x.explanationId)))continue;let L=d.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:or(x.scope)}:{},...x.reopenGrounding||S.has(x.explanationId)?{state:"testing"}:{}};T.push({op:"revise_explanation",explanationId:Q,patch:K,updatedAt:s})}else if(x.op==="evidence"){if(x.stance==="challenges"&&S.has(x.explanationId))continue;T.push({op:"add_evidence",explanationId:Q,evidence:yt(n,x.stance,x.summary)}),x.stance==="challenges"&&T.push({op:"revise_explanation",explanationId:Q,patch:{state:"challenged"},updatedAt:s})}else x.op==="retire"&&(T.push({op:"add_evidence",explanationId:Q,evidence:yt(n,"challenges",x.reason||"Retired after contradictory collaboration evidence.")}),T.push({op:"revise_explanation",explanationId:Q,patch:{state:"retired"},updatedAt:s}))}for(let x of i){let Q=M(x),L=d.get(Q);!L||L.state==="grounded"||L.state==="retired"||R.has(Q)&&!b.has(Q)||(b.has(Q)||(b.add(Q),T.push({op:"add_evidence",explanationId:Q,evidence:{...yt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&T.push({op:"revise_explanation",explanationId:Q,patch:{state:"testing"},updatedAt:s}))}let h=new Set(a.graph.relations.map(x=>`${x.type}:${x.fromId}:${x.toId}`)),m=T.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=dt(),D=await this.store.commit({transactionId:E,committedAt:s,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:m}),P=new Map(D.graph.explanations.map(x=>[x.id,x])),C=[...b].flatMap(x=>{let Q=P.get(x);if(!Q)return[];let L=!a.graph.explanations.some(W=>W.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=i.map(M).find(x=>P.get(x)?.state==="testing"&&!R.has(x)),X=e.grounding?M(e.grounding.explanationId):z,G=X?P.get(X):void 0,Y=G?.state==="testing"&&!R.has(G.id)?{explanationId:G.id,question:e.grounding?.question||vd(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 n=e.occurredAt??new Date().toISOString(),o=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!o)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===o);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},a=[],d="";if(e.action==="yes"?(a.push({op:"add_evidence",explanationId:o,evidence:{...yt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`):e.action==="this_time"&&(a.push({op:"add_evidence",explanationId:o,evidence:{...yt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),a.push({op:"revise_explanation",explanationId:o,patch:{state:"emerging"},updatedAt:n}),d=`Observed this time: ${i.statement}`),!a.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:dt(),committedAt:n,source:s,summary:d,mutations:a}),"applied"}};var Et=1,Sn="bridge";function wi(t){return`codex-session:${t}`}function jd(t,e){return`codex-${Pd("sha256").update(`${t}:${e}`).digest("hex").slice(0,16)}`}function vi(t){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:t,elements:[]}],styleModifications:[]}}function Ad(t,e){let n=new Set,o=i=>{if(typeof i!="string"||!i.trim())return;let s=i.trim();n.add(Td(s)?Rd(e,s):s)},r=(i,s="",a=0)=>{if(!(a>5||i===null||i===void 0)){if(typeof i=="string"){if(/^(file|path|file_path|filepath|target)$/i.test(s)&&o(i),s==="command")for(let d of i.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm))o(d[1]);return}if(Array.isArray(i)){i.forEach(d=>r(d,s,a+1));return}if(typeof i=="object")for(let[d,l]of Object.entries(i))r(l,d,a+1)}};for(let i of t)r(i.toolInput);return[...n]}function Zn(t){return t?Math.ceil(t.length/4):0}function bi(t,e,n,o,r,i){let s=["## Ambient Popmelt Core","",`This Codex conversation is paired with Popmelt thread ${e}; the current turn is ${n}; the tool session is ${t}.`,"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(`
|
|
39
|
+
`),a=wn(o),d=xi(r,i),l=[s,a,d].filter(Boolean).join(`
|
|
40
|
+
`);return{additionalContext:l,contextBudget:{protocolEstimatedTokens:Zn(s),memoryEstimatedTokens:Zn(a),imprintEstimatedTokens:Zn(d),totalEstimatedTokens:Zn(l)}}}function xi(t,e){return t?xn(t,{requestText:e}).split(`
|
|
40
41
|
`).map(n=>n.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.":n.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.':n).join(`
|
|
41
|
-
`)
|
|
42
|
-
`)}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`)
|
|
49
|
-
`)}
|
|
50
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:o?`${e} ${o.split("/").pop()}`:e,...o?{file:o}:{}};if(o&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${o.split("/").pop()}`,file:o}}}function mc(t){if(typeof t.error=="string")return t.error;if(t.error&&typeof t.error=="object"){let e=t.error;if(typeof e.message=="string")return e.message}if(typeof t.message=="string"&&Rn(t).toLowerCase().includes("error"))return t.message}function Tn(t,e,n=[]){for(let o of e){let r=t[o];if(typeof r=="string")return r}for(let[o,r]of Object.entries(t)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>o.toLowerCase().includes(s)))continue;let i=Tn(r,e);if(i)return i}}function lr(t){let e=Rn(t).toLowerCase();return(typeof t.role=="string"?t.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as fc,readFile as hc}from"fs/promises";import{join as pr}from"path";var ao=class{constructor(e){let n=pr(e,".popmelt");this.decisionsDir=pr(n,"decisions")}async listDecisionIds(){try{return(await fc(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await hc(pr(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(o=>this.loadDecision(o)))).filter(o=>o!==null)}};import{createHash as gc,randomUUID as yc}from"crypto";import{mkdir as ur,readFile as Bi,readdir as Ji,rename as co,stat as Li,unlink as lo,writeFile as po}from"fs/promises";import{extname as Ic,join as Ke}from"path";var wc=10080*60*1e3,vc=600*1e3,bc=3600*1e3;function xc(t){return t==="image/svg+xml"?".svg":t==="text/plain"?".txt":".bin"}function Sc(t,e){return[...t.trim()].map(o=>o==="/"||o==="\\"||o.charCodeAt(0)<32?"-":o).join("").slice(0,120)||e}var uo=class{constructor(e){this.draftsDir=Ke(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ke(e,".popmelt","artifacts","thread-media")}async stage(e){let n=yc(),o=xc(e.mimeType),r=`${n}${o}`,i=Date.now(),s={id:n,annotationId:e.annotationId,name:Sc(e.name,`pasted-context${o}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await ur(this.draftsDir,{recursive:!0});let a=Ke(this.draftsDir,r),d=Ke(this.draftsDir,`${n}.json`),l=`${a}.part`,v=`${d}.part`;return await po(l,e.data),await co(l,a),await po(v,JSON.stringify(s,null,2)),await co(v,d),s}async claim(e){await Promise.all(e.map(async n=>{let o=await this.readManifest(n);o&&(delete o.releasedAt,o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async release(e){await Promise.all(e.map(async n=>{let o=await this.readManifest(n);o&&(o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async promote(e){let n={};for(let o of e){let r=await this.readManifest(o.id);if(!r)throw new Error(`Draft attachment ${o.id} is unavailable or expired.`);if(r.annotationId!==o.annotationId)throw new Error(`Draft attachment ${o.id} does not belong to annotation ${o.annotationId}.`);let i=Ke(this.draftsDir,r.contentFile),s=await Bi(i),a=gc("sha256").update(s).digest("hex"),d=Ke(this.mediaDir,`${a}${Ic(r.contentFile)||".bin"}`);await ur(this.mediaDir,{recursive:!0});try{await Li(d)}catch{let l=`${d}.part`;await po(l,s),await co(l,d)}(n[o.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:d}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return n}async sweep(e=Date.now()){let n;try{n=await Ji(this.draftsDir)}catch{return}await Promise.all(n.map(async o=>{let r=Ke(this.draftsDir,o);if(o.endsWith(".part")){let a=await Li(r).catch(()=>null);a&&e-a.mtimeMs>bc&&await lo(r).catch(()=>{});return}if(!o.endsWith(".json"))return;let i=await this.readManifest(o.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>vc:e-i.lastSeenAt>wc)||await Promise.all([lo(r).catch(()=>{}),lo(Ke(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Ji(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>lo(Ke(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Bi(Ke(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await ur(this.draftsDir,{recursive:!0});let n=Ke(this.draftsDir,`${e.id}.json`),o=`${n}.part`;await po(o,JSON.stringify(e,null,2)),await co(o,n)}};import{randomUUID as qi}from"crypto";import{mkdir as mr,readFile as fr,writeFile as mo}from"fs/promises";import{dirname as hr,join as Gt}from"path";var Qe="[ProjectionWorker]",Pc={version:1,runs:[]},kc={version:1,updatedAt:0,proposals:[]},Tc=12;function Rc(t){return Array.isArray(t)?t.map((e,n)=>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 Ui(t){let e=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n;if(typeof o.id!="string"||typeof o.text!="string"){console.warn(`${Qe} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:o.id,scope:typeof o.scope=="string"?o.scope:"general",text:o.text,sources:Array.isArray(o.sources)?o.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Qe} Rule count ${e.length} exceeds cap of 30`),e}function jc(t,e,n){return{decisionCount:t.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Ac(t,e,n){let o=new Set(e),r=new Set,i=Array.isArray(t.rules)?t.rules:[];for(let P of i){if(!P||typeof P!="object")continue;let f=P.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&o.has(p)&&r.add(p)}let s=t.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},a=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=i.filter(P=>{if(!P||typeof P!="object")return!1;let f=P.id,p=typeof f=="string"?d.find(g=>g&&typeof g=="object"&&g.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(P)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},x=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(s).filter(P=>JSON.stringify(s[P])!==JSON.stringify(v[P])).length,R=Object.keys(a).filter(P=>JSON.stringify(a[P])!==JSON.stringify(x[P])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:R,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(P=>!r.has(P))}}function Mc(t){if(t!==void 0)return JSON.parse(JSON.stringify(t))}function Ec(t,e,n){let o=t[e];if(o&&typeof o=="object")return o;let r=typeof n=="number"?[]:{};return t[String(e)]=r,r}function fo(t,e,n){let o=t;for(let i=0;i<e.length-1;i++)o=Ec(o,e[i],e[i+1]);let r=e[e.length-1];o[String(r)]=Mc(n)}function Fi(t,e){let n=t;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let o=e[e.length-1];Array.isArray(n)&&typeof o=="number"?n.splice(o,1):delete n[String(o)]}function _c(t,e){if(!t)return{exists:!1};let n=t;for(let o of e){if(!n||typeof n!="object"||!(String(o)in n))return{exists:!1};n=n[String(o)]}return{exists:!0,value:n}}function Cc(t,e){return Array.isArray(e)?t===void 0?e.length>0:!Array.isArray(t)||e.length<=t.length?!1:t.every((n,o)=>JSON.stringify(n)===JSON.stringify(e[o])):!1}function zi(t,e){if(t.authorityStatus!=="accepted"||!t.changes?.length)return null;for(let n of t.changes){let o=_c(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Cc(o.exists?o.value:void 0,n.value):!o.exists))return null}return t.changes}var ho=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let o=Gt(e,".popmelt");this.runsPath=Gt(o,"projection-runs.json"),this.legacyRunsPath=Gt(o,"materialization-runs.json"),this.proposalsPath=Gt(o,"projection-queue.json"),this.legacyProposalsPath=Gt(o,"model-proposals.json"),this.modelPath=Gt(o,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await fr(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Rc(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let o of e){let r=o.key.split(".");o.value===null?Fi(n,r):fo(n,r,o.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Tc),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let o=await this.selectUnprojectedPatternDecisions(),r=o.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(P=>P.id);console.log(`${Qe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=Nc(r,s),d=jc(r,o.totalCandidateDecisionCount,a);n=qi().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,x,b,R;try{let P=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(P,a,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)v=!1,x=g.error,console.error(`${Qe} ${f} spawn error:`,x);else{let w=Dc(g.text,i);if(w){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of w)fo(u,m.path,m.value);Array.isArray(u.rules)&&(u.rules=Ui(u.rules));let M=Ac(u,i,s);if(w){let m=[...new Set(w.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=i.filter(E=>!m.includes(E))}b=M;let h=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:b,changes:w});R=h.id,console.log(`${Qe} Created model proposal ${h.id} for ${i.length} decision(s)`)}else v=!1,x="No valid bounded <model-changes> block found in response",console.error(`${Qe} ${x}`)}}catch(P){v=!1,x=P instanceof Error?P.message:String(P),console.error(`${Qe} Error:`,x)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:x,outputStats:b,proposalId:R}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:v,error:x}),{processedIds:i,success:v,error:x,runId:n,proposalId:R}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ui(e.rules)),await mo(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Qe} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await mr(hr(this.runsPath),{recursive:!0}),await mo(this.runsPath,JSON.stringify(n,null,2)),n):{...Pc,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...kc,proposals:[]},o=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(o);for(let s of r.changes??[])fo(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(o=>o.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>r.updatedAt-o.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>o.createdAt-r.createdAt||o.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,o,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?Fi(s,d.path):fo(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:o})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:qi().slice(0,8),status:"pending",title:$c(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"}.`:Oc(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},o=await this.loadModelProposals();return o.proposals=[n,...o.proposals.filter(r=>r.id!==n.id)].slice(0,100),o.updatedAt=Date.now(),await this.persistModelProposals(o),n}async updateModelProposal(e,n){let o=await this.loadModelProposals(),r=null;return o.proposals=o.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(o.updatedAt=Date.now(),await this.persistModelProposals(o),r):null}async persistModelProposals(e){try{await mr(hr(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:o,...r})=>r)};await mo(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Qe} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),o=n.runs.findIndex(r=>r.id===e.id);o>=0?n.runs[o]=e:n.runs.push(e),await mr(hr(this.runsPath),{recursive:!0}),await mo(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Qe} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await fr(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await fr(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,o,r){let i=o.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...so(e,{prompt:n,projectRoot:this.projectRoot,model:o.model??this.options.model,configOverrides:to(o.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...no(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?o.model??this.options.model:void 0,reasoningEffort:o.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function $c(t){let n=(Array.isArray(t.rules)?t.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let o=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?Object.keys(t.components):[];return o.length>0?`Model update for ${o[0]}`:"Model update"}function Oc(t,e){let n=Array.isArray(t.rules)?t.rules.length:0,o=t.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?Object.keys(t.tokens).length:0,r=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?Object.keys(t.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${o} token section${o===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Dc(t,e){let n=t.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let o=JSON.parse(n[1]);if(!Array.isArray(o)||o.length===0||o.length>40)return null;let r=new Set(e),i=o.flatMap((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(x=>typeof x=="string"||typeof x=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(x=>typeof x=="string"&&r.has(x)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===o.length?i:null}catch{return null}}function Nc(t,e){let n=t.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
42
|
+
`):["","## 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(`
|
|
43
|
+
`)}function Md(t){if(!t)return;if(t.decision==="recognize")return[t.explanationId];let e=[...new Set([...t.usedExplanationIds??[],...t.appliedExplanationIds??[]])];return e.length?e:void 0}function Ed(t,e){let n=e.flatMap((o,r)=>{let i=t[r];return i?[{packetId:`ambient:${o}`,proposalId:o,claim:i.claim.trim(),proposedKind:i.proposedKind,authority:"unaccepted",presentation:"advisory",subjectLabels:["Project"],evidenceCount:1,expansionRefs:[{kind:"proposal",id:o}]}]:[]});return n.length>0?{source:"journal",packets:n,truncated:!1,estimatedTokens:0}:void 0}var eo=class{constructor(e){this.options=e;this.turns=new Map}key(e,n){return`${e}:${n}`}async findThread(e){return this.options.threadStore.findContinuationThread([wi(e)])}async prepare(e){if(e.executionOwner===Sn)return{status:"managed_by_bridge",protocolVersion:Et};let n=this.key(e.sessionId,e.turnId),o=this.turns.get(n);if(o){let b=bi(o.sessionId,o.threadId,o.jobId,o.memoryContext,o.imprintContext,o.prompt);return{status:"already_prepared",protocolVersion:Et,threadId:o.threadId,jobId:o.jobId,...b}}let r=await this.findThread(e.sessionId);r||(r=await this.options.threadStore.createThread(`thread-${kd()}`,[wi(e.sessionId)]));let i=jd(e.sessionId,e.turnId),s=r.messages.find(b=>b.jobId===i&&b.role==="human"),a=vi(e.prompt),d=s?.memoryReview??await In(this.options.memoryService,a,[]),l=s?.imprintContext??await this.options.imprintService.contextualize({text:e.prompt,pendingGroundingExplanationIds:r.messages.flatMap(b=>b.role==="assistant"&&b.imprintSummary?.grounding&&!b.imprintSummary.resolvedAction?[b.imprintSummary.grounding.explanationId]:[])});s||await this.options.threadStore.appendMessage(r.id,{role:"human",timestamp:Date.now(),jobId:i,requestText:e.prompt,feedbackSummary:e.prompt,sessionId:e.sessionId,...d?{memoryReview:d}:{},...l?{imprintContext:l}:{}});let v={sessionId:e.sessionId,turnId:e.turnId,threadId:r.id,jobId:i,prompt:e.prompt,createdAt:s?.timestamp??Date.now(),memoryContext:d,imprintContext:l,events:[]};this.turns.set(n,v);let T=bi(e.sessionId,r.id,i,d,l,e.prompt);return{status:s?"already_prepared":"prepared",protocolVersion:Et,threadId:r.id,jobId:i,...T}}async recordEvent(e){if(e.executionOwner===Sn)return{status:"ignored"};let n=this.turns.get(this.key(e.sessionId,e.turnId));return n?e.toolUseId&&n.events.some(o=>o.toolUseId===e.toolUseId)?{status:"recorded"}:(n.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 n=[...this.turns.values()].find(o=>o.threadId===e.threadId&&o.jobId===e.jobId);return n?(n.assessment={assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates.slice(0,8)},{status:"recorded"}):{status:"turn_not_found"}}async complete(e){if(e.executionOwner===Sn)return{status:"managed_by_bridge",protocolVersion:Et};let n=this.turns.get(this.key(e.sessionId,e.turnId));if(!n)return{status:"turn_not_prepared",protocolVersion:Et};let r=(await this.options.threadStore.getThread(n.threadId))?.messages.find(p=>p.role==="assistant"&&p.jobId===n.jobId);if(r)return e.lastAssistantMessage&&e.lastAssistantMessage!==r.responseText&&await this.options.threadStore.updateAssistantMessage(n.threadId,n.jobId,{responseText:e.lastAssistantMessage}),{status:"already_completed",protocolVersion:Et,threadId:n.threadId,jobId:n.jobId};let i=Ad(n.events,this.options.projectRoot),s=i.length>0,a,d={state:"not_applicable"},l,v;if(n.assessment?.assessmentText){let p=bn(n.assessment.assessmentText,{context:n.imprintContext,requestText:n.prompt,applicationOccurred:s});p.error?d={state:p.error.includes("missing")?"missing":"invalid",reason:p.error}:p.draft?.decision==="none"?(this.options.imprintService.recordNoop(p.draft.reason),d={state:"none",reason:p.draft.reason}):p.draft?.decision==="recognize"?d={state:"none",reason:"recognized existing grounded understanding"}:(p.draft?.decision==="mutate"||p.draft?.decision==="apply")&&(a=await this.options.imprintService.capture(p.draft,{threadId:n.threadId,jobId:n.jobId,concreteModel:await this.options.loadConcreteModel?.()??null,pendingGroundingExplanationIds:n.imprintContext?.pendingGroundingExplanationIds,applicationOccurred:s}),d=a?{state:"mutated"}:{state:"invalid",reason:"imprint mutation failed admission or produced no durable change"},a&&await this.options.memoryService.recordImprintEvidence({summary:a,threadId:n.threadId,jobId:n.jobId}).catch(()=>{})),l=Md(p.draft),v=p.draft&&p.draft.decision!=="recognize"?p.draft.appliedExplanationIds:void 0}let T=s?"completed":"no_change",b=yn({changedFiles:i}),R={role:"assistant",timestamp:Date.now(),jobId:n.jobId,responseText:e.lastAssistantMessage??"",sessionId:e.sessionId,toolsUsed:n.events.map(p=>p.toolName),turn:{phase:"complete",orientation:[],result:b},result:b,provider:"codex",model:e.model,imprintSummary:a,imprintUsedExplanationIds:l,imprintAppliedExplanationIds:v};await this.options.threadStore.appendMessage(n.threadId,R);let S=await this.options.memoryService.captureCompletedJob({jobId:n.jobId,threadId:n.threadId,createdAt:n.createdAt,completedAt:Date.now(),requestSummary:n.prompt,responseSummary:e.lastAssistantMessage,outcome:T,execution:{provider:"codex",model:e.model,sessionId:e.sessionId},subjectHints:[],filePaths:i,resolutions:s?[{status:"resolved",summary:`Changed ${i.join(", ")}`}]:[],semanticCandidates:n.assessment?.semanticCandidates,governingDecisionIds:n.memoryContext?.acceptedTruth?.decisions.map(p=>p.id),imprintAssessment:d}),f=Ed(n.assessment?.semanticCandidates??[],S.proposalIds);return f&&await this.options.threadStore.updateAssistantMessage(n.threadId,n.jobId,{memoryReview:f}),{status:"completed",protocolVersion:Et,threadId:n.threadId,jobId:n.jobId}}async expandContext(e){let n=vi(e.query),o=await In(this.options.memoryService,n,e.subjectHints??[]),r=await this.options.imprintService.contextualize({text:e.query,subjectHints:e.subjectHints});return{memoryContext:o,imprintContext:r,formattedContext:[wn(o),xi(r,e.query)].filter(Boolean).join(`
|
|
44
|
+
`)}}};import{mkdir as Od,readFile as Si,realpath as Dd,writeFile as Nd}from"fs/promises";import{join as to}from"path";function It(t){return Cd(t).slice(0,12)}var _d=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Cd(t){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(t)):$d(t),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let b=7;b>=0;b--)e.push(n/Math.pow(2,b*8)&255);let o=1779033703,r=3144134277,i=1013904242,s=2773480762,a=1359893119,d=2600822924,l=528734635,v=1541459225,T=new Array(64);for(let b=0;b<e.length;b+=64){for(let h=0;h<16;h++){let m=b+h*4;T[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=tt(T[h-15],7)^tt(T[h-15],18)^T[h-15]>>>3,E=tt(T[h-2],17)^tt(T[h-2],19)^T[h-2]>>>10;T[h]=T[h-16]+m+T[h-7]+E>>>0}let R=o,S=r,f=i,p=s,g=a,w=d,u=l,M=v;for(let h=0;h<64;h++){let m=tt(g,6)^tt(g,11)^tt(g,25),E=g&w^~g&u,D=M+m+E+_d[h]+T[h]>>>0,P=tt(R,2)^tt(R,13)^tt(R,22),C=R&S^R&f^S&f,z=P+C>>>0;M=u,u=w,w=g,g=p+D>>>0,p=f,f=S,S=R,R=D+z>>>0}o=o+R>>>0,r=r+S>>>0,i=i+f>>>0,s=s+p>>>0,a=a+g>>>0,d=d+w>>>0,l=l+u>>>0,v=v+M>>>0}return[o,r,i,s,a,d,l,v].map(b=>b.toString(16).padStart(8,"0")).join("")}function tt(t,e){return t>>>e|t<<32-e}function $d(t){let e=[];for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?e.push(o):o<2048?e.push(192|o>>6,128|o&63):e.push(224|o>>12,128|o>>6&63,128|o&63)}return e}async function sr(t){return Dd(t).catch(()=>t)}function Pi(t){return to(t,".popmelt","store.json")}function Bd(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.version===1&&typeof e.storeId=="string"&&!!e.storeId.trim()&&typeof e.createdAt=="string"&&!Number.isNaN(Date.parse(e.createdAt))}async function ir(t){let e=await sr(t);try{let n=JSON.parse(await Si(Pi(e),"utf8"));return Bd(n)?n:null}catch{return null}}async function ar(t){let e=await sr(t),n=await ir(e);if(n)return n;let o;for(let r of[to(e,".popmelt","memory","manifest.json"),to(e,".popmelt","imprint","manifest.json")])try{let i=JSON.parse(await Si(r,"utf8"));if(typeof i.projectId=="string"&&i.projectId.trim()){o=i.projectId.trim();break}}catch{}return{version:1,storeId:`store-${o??It(e)}`,createdAt:new Date().toISOString()}}async function Ht(t){let e=await sr(t),n=await ir(e);if(n)return n;let o=await ar(e),r=to(e,".popmelt");await Od(r,{recursive:!0});try{return await Nd(Pi(e),`${JSON.stringify(o,null,2)}
|
|
45
|
+
`,{encoding:"utf8",flag:"wx"}),o}catch(i){let s=await ir(e);if(s)return s;throw i}}var Jd=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),Ld=new Set(["default","flex","fast","priority"]);function Wt(t){let e=typeof t.reasoningEffort=="string"&&Jd.has(t.reasoningEffort)?t.reasoningEffort:void 0,n=typeof t.serviceTier=="string"&&Ld.has(t.serviceTier)?t.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function no(t){let e=[];return t?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(t.reasoningEffort)}`),t?.serviceTier&&e.push(`service_tier=${JSON.stringify(t.serviceTier)}`),e}import{spawn as qd}from"child_process";import{createInterface as Fd}from"readline";function Pn(t,e){let n=e.trim();if(!n)return"";let o=t.length>0?`
|
|
46
|
+
|
|
47
|
+
${n}`:n;return t.push(o),o}var Ud=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ki=1e5;function zd(t){let e=t.input?.file_path||t.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Ud.has(n))return;let o;if(t.name==="Write"&&typeof t.input?.content=="string"?o=t.input.content:t.name==="Edit"&&typeof t.input?.new_string=="string"&&(o=t.input.new_string),!!o)return o.length>ki?o.slice(0,ki)+`
|
|
48
|
+
\u2026[truncated]`:o}function oo(t,e){let{prompt:n,projectRoot:o,maxTurns:r=40,maxBudgetUsd:i=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:a="claude",resumeSessionId:d,model:l,reasoningEffort:v,timeoutMs:T=3e5,onEvent:b}=e,R=[];d?R.push("--resume",d,"-p",n):R.push("-p",n),R.push("--output-format","stream-json","--verbose","--max-turns",String(r),"--max-budget-usd",String(i)),l&&R.push("--model",l),v&&R.push("--effort",v);for(let p of s)R.push("--allowedTools",p);let S=qd(a,R,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),f=new Promise(p=>{let g,w=[],u=[],M=[],h=!1,m="",E,D,P=!1,C=setTimeout(()=>{P=!0,S.kill("SIGTERM"),setTimeout(()=>{try{S.kill("SIGKILL")}catch{}},5e3)},T),z=Fd({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&&w.length===0){let L=typeof x.result=="string"?x.result:"";if(L){let K=Pn(w,L);K&&b?.({type:"delta",jobId:t,text:K},t)}}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=Pn(w,L.text);K&&b?.({type:"delta",jobId:t,text:K},t)}if(L.type==="tool_use"&&L.name){let K=L.input?.file_path||L.input?.path||void 0,W=zd(L);if(b?.({type:"tool_use",jobId:t,tool:L.name,...K?{file:K}:{},...W?{content:W}:{}},t),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:t,text:L.thinking},t)}}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:t,tool:"Read",file:x.tool_use_result.file.filePath},t)}catch{}});let G=[];S.stderr?.on("data",Y=>{G.push(Y.toString())}),S.on("close",Y=>{if(clearTimeout(C),z.close(),w.length===0&&X.size>0&&console.warn(`[Claude:${t}] No text captured. Event types seen: ${[...X].join(", ")}`),P)h=!0,m=`Timed out after ${Math.round(T/6e4)} minutes`;else if(Y!==0&&Y!==null){h=!0;let Q=G.join("").trim(),L=w.join("").trim(),K=w.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=Hd(m,E);p({sessionId:g,text:w.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:w.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 Hd(t,e){let n=t.trim()||"Claude CLI failed",o=`${e??""} ${n}`.toLowerCase();return o.includes("authentication_failed")||o.includes("not logged in")||o.includes("please run /login")||o.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:o.includes("model")&&(o.includes("not found")||o.includes("unknown")||o.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as Gd,spawnSync as Ci}from"child_process";import{readFileSync as Vd,statSync as Kd}from"fs";import{basename as Qd,extname as Xd,isAbsolute as Yd,relative as $i,resolve as Zd}from"path";import{createInterface as ec}from"readline";function io(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function ro(t,e){for(let n of t)if(n)for(let o of e){let r=n[o];if(typeof r=="string"&&r.trim())return r.trim()}}function Ti(t){let e=io(t);if(e)return e;if(typeof t=="string")try{return io(JSON.parse(t))}catch{return}}function dr(t){return t.replace(/^mcp__/,"").replace(/[_-]+/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Wd(t,e,n,o){return t!=="node_repl"||e!=="js"?!1:o&&/(?:setupBrowserRuntime|browser-client|\b(?:browser|tab|iab|chrome)\s*\.)/.test(o)?!0:!!(n&&/\b(?:browser|page|tab|rendered|geometry|FAQ)\b/i.test(n))}function Ri(t){let e=io(t)??{},n=io(e.invocation),o=Ti(e.arguments)??Ti(n?.arguments),r=ro([e,n],["server","server_name"]),i=ro([e,n],["tool","tool_name","name"]),s=ro([o,e,n],["title","display_name","description"]),a=ro([o],["code","script"]),d=Wd(r,i,s,a)?"Browser":r?dr(r):i?dr(i):"MCP",l=i&&dr(i),v=s??l,T=v&&v!==d?`${d}: ${v}`:d;return{tool:d,...v?{content:v}:{},telemetryLabel:T}}function ji(t){let e=t.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t}var Ai=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),cr=2e5,tc=1e5,Oi=2e5;function Di(t){let e=Qd(t).toLowerCase(),n=Xd(t).toLowerCase();return Ai.has(n)||Ai.has(e)}function kn(t,e){let n=Yd(e)?e:Zd(t,e),o=$i(t,n);return o===""||o.startsWith("..")?null:n}function so(t,e){if(!Di(e))return;let n=kn(t,e);if(n)try{let o=Kd(n);return o.isFile()?o.size>cr?{exists:!0,truncated:!0}:{exists:!0,content:Vd(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function nc(t,e){for(let n of e){let o=t[n];if(typeof o=="string")return o}}function oc(t){let e=t?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function Mi(t){return nc(t,["patch","diff","unifiedDiff","unified_diff"])}function lr(t,e){return t.length<=e?{text:t}:{text:t.slice(0,e),truncated:!0}}function Ei(t,e){let n=Ci("git",e,{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:Oi+65536});return n.status!==0?null:n.stdout??""}function rc(t){let e=new Set;for(let n of t.split(`
|
|
49
|
+
`)){if(n.length<4)continue;let o=n.slice(3).trim();if(!o)continue;o.startsWith('"')&&o.endsWith('"')&&(o=o.slice(1,-1));let r=o.split(" -> ");for(let i of r)i&&e.add(i)}return[...e]}function _i(t){let e=Ei(t,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=Ei(t,["diff","--no-ext-diff","HEAD","--"])??"",o=lr(n,Oi);return{status:e,changedFiles:rc(e),...o.text?{diff:o.text}:{},...o.truncated?{diffTruncated:!0}:{}}}function ic(t,e){return!t||!e?!1:t.status!==e.status||(t.diff??"")!==(e.diff??"")}function sc(t,e){if(!Di(e))return;let n=kn(t,e);if(!n)return;let o=$i(t,n);if(o===""||o.startsWith(".."))return;let r=Ci("git",["show",`HEAD:${o}`],{cwd:t,encoding:"utf8",timeout:5e3,maxBuffer:cr+65536});if(r.status!==0)return{exists:!1};let i=r.stdout??"",s=lr(i,cr);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function ac(t,e,n){return e.map(o=>{let r=n.has(o)?n.get(o):sc(t,o),i=so(t,o);return{filePath:o,...r?{before:r}:{},...i?{after:i}:{}}})}function ao(t,e){let{prompt:n,projectRoot:o,screenshotPath:r,resumeSessionId:i,model:s,onEvent:a,sandboxMode:d="workspace-write",configOverrides:l=[]}=e,v=[];if(i){v.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let R of l)v.push("-c",R);s&&v.push("-m",s),v.push(i),v.push(n),r&&v.push("--image",r)}else{v.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let R of l)v.push("-c",R);s&&v.push("-m",s),v.push(n),r&&v.push("--image",r)}let T=Gd("codex",v,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0,POPMELT_EXECUTION_OWNER:"bridge",POPMELT_PARENT_JOB_ID:t}}),b=new Promise(R=>{let S,f=[],p=[],g=[],w=new Map,u=new Map,M=!1,h="",m=ec({input:T.stdout}),E=new Set;m.on("line",P=>{if(P.trim())try{let C=JSON.parse(P),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),a?.({type:"delta",jobId:t,text:C.delta.text},t)),(z==="item.reasoning.delta"||z==="item/reasoning/delta")&&C.delta?.text&&a?.({type:"thinking",jobId:t,text:C.delta.text},t),(z==="item.started"||z==="item/started")&&C.item){let X=C.item.type;if(X==="command_execution"){let G=C.item.command,Y=G?ji(G):void 0,x=_i(o),Q=new Map;for(let K of x?.changedFiles??[])Q.set(K,so(o,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(`
|
|
50
|
+
`)[0].slice(0,80)}`:"Bash";p.push(L),a?.({type:"tool_use",jobId:t,tool:"Bash",...Y?{content:Y}:{}},t)}else if(X==="file_change"){let G=C.item.filename||C.item.path;G&&!w.has(G)&&w.set(G,so(o,G)),p.push(G?`Edit ${G.split("/").pop()}`:"Edit");let Y=G?kn(o,G)??G:void 0;a?.({type:"tool_use",jobId:t,tool:"Edit",...Y?{file:Y}:{}},t)}else if(X==="file_read"){let G=C.item.filename||C.item.path;p.push(G?`Read ${G.split("/").pop()}`:"Read");let Y=G?kn(o,G)??G:void 0;a?.({type:"tool_use",jobId:t,tool:"Read",...Y?{file:Y}:{}},t)}else if(X==="web_search")p.push("WebSearch"),a?.({type:"tool_use",jobId:t,tool:"WebSearch"},t);else if(X==="mcp_tool_call"){let G=Ri(C.item);p.push(G.telemetryLabel),a?.({type:"tool_use",jobId:t,tool:G.tool,...G.content?{content:G.content}:{}},t)}}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=Pn(f,X);G&&a?.({type:"delta",jobId:t,text:G},t)}}else if(C.item.type==="reasoning"){let X=C.item.text;typeof X=="string"&&X&&a?.({type:"thinking",jobId:t,text:X},t)}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=kn(o,G)??G;a?.({type:"tool_use",jobId:t,tool:Y,file:x},t);let Q=X,L=typeof Q.kind=="string"?Q.kind:void 0,K=oc(L),W=w.get(G),B=so(o,G);g.push({sequence:g.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:K,filePath:G,...W?{before:W}:{},...B?{after:B}:{},...Mi(Q)?{patch:Mi(Q)}:{},...L?{rawKind:L}:{}}),w.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?ji(Y):G?.command,Q=_i(o);if(ic(G?.beforeWorktree,Q)){let L=[...new Set([...G?.beforeWorktree?.changedFiles??[],...Q?.changedFiles??[]])],K=typeof C.item.aggregated_output=="string"?lr(C.item.aggregated_output,tc):void 0,W=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}:{},...W!==void 0?{exitCode:W}:{},...B?{status:B}:{},...K?{output:K.text}:{},...K?.truncated?{outputTruncated:!0}:{},...G?.beforeWorktree?{beforeWorktree:G.beforeWorktree}:{},...Q?{afterWorktree:Q}:{},...L.length>0?{touchedFiles:ac(o,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=[];T.stderr?.on("data",P=>{D.push(P.toString())}),T.on("close",P=>{m.close(),f.length===0&&E.size>0&&console.warn(`[Codex:${t}] No text captured. Event types seen: ${[...E].join(", ")}`),P!==0&&P!==null&&(M=!0,h=D.join("")||`Codex process exited with code ${P}`),R({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})}),T.on("error",P=>{M=!0,h=P.message,R({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:T,result:b}}import{spawn as dc}from"child_process";import{createInterface as cc}from"readline";function Ni(t,e){let n=t.trim()||"Copilot CLI failed",o=n.toLowerCase();return o.includes("no authentication information")||o.includes("not authenticated")||o.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:o.includes("model")&&(o.includes("not available")||o.includes("not found")||o.includes("disabled")||o.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:o.includes("mcp")&&(o.includes("blocked")||o.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:o.includes("permission")||o.includes("denied")||o.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function Bi(t,e){let{prompt:n,projectRoot:o,resumeSessionId:r,model:i,timeoutMs:s=3e5,onEvent:a,copilotPath:d="copilot"}=e,l=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];r&&l.push(`--resume=${r}`),i&&l.push("--model",i),l.push("-p",n);let v=dc(d,l,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),T=new Promise(b=>{let R,S=[],f=[],p=!1,g="",w=!1,u=setTimeout(()=>{w=!0,v.kill("SIGTERM"),setTimeout(()=>{try{v.kill("SIGKILL")}catch{}},5e3)},s),M=cc({input:v.stdout}),h=new Set,m=[];M.on("line",D=>{if(D.trim())try{let P=JSON.parse(D),C=Rn(P);h.add(C),m.length<5&&pc(C)&&m.push(D.slice(0,800));let z=Tn(P,["sessionId","session_id","id"],["session","conversation","thread"]);z&&!R&&(R=z);let X=lc(P,S.length===0);X&&(S.push(X),a?.({type:"delta",jobId:t,text:X},t));let G=uc(P);G&&a?.({type:"thinking",jobId:t,text:G},t);let Y=mc(P);Y&&(f.push(Y.label),a?.({type:"tool_use",jobId:t,tool:Y.tool,...Y.file?{file:Y.file}:{},...Y.content?{content:Y.content}:{}},t));let x=fc(P);x&&(p=!0,g=x)}catch{}});let E=[];v.stderr?.on("data",D=>{E.push(D.toString())}),v.on("close",D=>{clearTimeout(u),M.close(),S.length===0&&h.size>0&&(console.warn(`[Copilot:${t}] No text captured. Event types seen: ${[...h].join(", ")}`),m.length>0&&console.warn(`[Copilot:${t}] Sample text-bearing candidates: ${m.join(`
|
|
51
|
+
`)}`)),w?(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 P=p?Ni(g,i):null;b({sessionId:R,text:S.join(""),success:!p,error:P?.message,errorCode:P?.code,recoverableError:P?.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})}),v.on("error",D=>{clearTimeout(u);let P=Ni(D.message,i);b({sessionId:R,text:S.join(""),success:!1,error:P.message,errorCode:P.code,recoverableError:P.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})})});return{process:v,result:T}}function Rn(t){if(typeof t.type=="string")return t.type;let e=t.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof t.event=="string"?t.event:"unknown"}function lc(t,e=!1){let n=Rn(t).toLowerCase(),o=t.update,r=o?.content;if(o?.sessionUpdate==="agent_message_chunk"&&r?.type==="text"&&typeof r.text=="string")return r.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return ze(t.delta)??ze(t.content)??ze(t.message);if(n==="assistant.message"&&e)return ze(t.message)??ze(t.content)??ze(t);if(n==="result"&&e)return ze(t.result)??ze(t.output)??ze(t.message)??ze(t);let i=t.content;if(i?.type==="text"&&typeof i.text=="string")return i.text;if(typeof t.text=="string"&&pr(t))return t.text;if(typeof t.message=="string"&&pr(t))return t.message;if(typeof t.delta=="string"&&pr(t))return t.delta}function ze(t){if(typeof t=="string")return t;if(!t)return;if(Array.isArray(t)){let n=t.map(ze).filter(o=>!!o);return n.length>0?n.join(""):void 0}if(typeof t!="object")return;let e=t;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let o=ze(e[n]);if(o)return o}}function pc(t){let e=t.toLowerCase();return e.includes("assistant.message")||e==="result"}function uc(t){if(typeof t.thinking=="string")return t.thinking;if(typeof t.reasoning=="string")return t.reasoning;let e=t.update;if(e?.sessionUpdate==="reasoning_chunk"){let n=e.content;if(typeof n?.text=="string")return n.text}}function mc(t){let e=Tn(t,["tool","toolName","tool_name","name"]),n=Tn(t,["command","cmd"]),o=Tn(t,["file","path","filename","filePath"]),r=Rn(t);if(n||r.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
52
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:o?`${e} ${o.split("/").pop()}`:e,...o?{file:o}:{}};if(o&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${o.split("/").pop()}`,file:o}}}function fc(t){if(typeof t.error=="string")return t.error;if(t.error&&typeof t.error=="object"){let e=t.error;if(typeof e.message=="string")return e.message}if(typeof t.message=="string"&&Rn(t).toLowerCase().includes("error"))return t.message}function Tn(t,e,n=[]){for(let o of e){let r=t[o];if(typeof r=="string")return r}for(let[o,r]of Object.entries(t)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>o.toLowerCase().includes(s)))continue;let i=Tn(r,e);if(i)return i}}function pr(t){let e=Rn(t).toLowerCase();return(typeof t.role=="string"?t.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as hc,readFile as gc}from"fs/promises";import{join as ur}from"path";var co=class{constructor(e){let n=ur(e,".popmelt");this.decisionsDir=ur(n,"decisions")}async listDecisionIds(){try{return(await hc(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await gc(ur(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(o=>this.loadDecision(o)))).filter(o=>o!==null)}};import{createHash as yc,randomUUID as Ic}from"crypto";import{mkdir as mr,readFile as Ji,readdir as Li,rename as lo,stat as qi,unlink as po,writeFile as uo}from"fs/promises";import{extname as wc,join as Ke}from"path";var vc=10080*60*1e3,bc=600*1e3,xc=3600*1e3;function Sc(t){return t==="image/svg+xml"?".svg":t==="text/plain"?".txt":".bin"}function Pc(t,e){return[...t.trim()].map(o=>o==="/"||o==="\\"||o.charCodeAt(0)<32?"-":o).join("").slice(0,120)||e}var mo=class{constructor(e){this.draftsDir=Ke(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ke(e,".popmelt","artifacts","thread-media")}async stage(e){let n=Ic(),o=Sc(e.mimeType),r=`${n}${o}`,i=Date.now(),s={id:n,annotationId:e.annotationId,name:Pc(e.name,`pasted-context${o}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await mr(this.draftsDir,{recursive:!0});let a=Ke(this.draftsDir,r),d=Ke(this.draftsDir,`${n}.json`),l=`${a}.part`,v=`${d}.part`;return await uo(l,e.data),await lo(l,a),await uo(v,JSON.stringify(s,null,2)),await lo(v,d),s}async claim(e){await Promise.all(e.map(async n=>{let o=await this.readManifest(n);o&&(delete o.releasedAt,o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async release(e){await Promise.all(e.map(async n=>{let o=await this.readManifest(n);o&&(o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o))}))}async promote(e){let n={};for(let o of e){let r=await this.readManifest(o.id);if(!r)throw new Error(`Draft attachment ${o.id} is unavailable or expired.`);if(r.annotationId!==o.annotationId)throw new Error(`Draft attachment ${o.id} does not belong to annotation ${o.annotationId}.`);let i=Ke(this.draftsDir,r.contentFile),s=await Ji(i),a=yc("sha256").update(s).digest("hex"),d=Ke(this.mediaDir,`${a}${wc(r.contentFile)||".bin"}`);await mr(this.mediaDir,{recursive:!0});try{await qi(d)}catch{let l=`${d}.part`;await uo(l,s),await lo(l,d)}(n[o.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:d}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return n}async sweep(e=Date.now()){let n;try{n=await Li(this.draftsDir)}catch{return}await Promise.all(n.map(async o=>{let r=Ke(this.draftsDir,o);if(o.endsWith(".part")){let a=await qi(r).catch(()=>null);a&&e-a.mtimeMs>xc&&await po(r).catch(()=>{});return}if(!o.endsWith(".json"))return;let i=await this.readManifest(o.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>bc:e-i.lastSeenAt>vc)||await Promise.all([po(r).catch(()=>{}),po(Ke(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Li(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>po(Ke(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Ji(Ke(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await mr(this.draftsDir,{recursive:!0});let n=Ke(this.draftsDir,`${e.id}.json`),o=`${n}.part`;await uo(o,JSON.stringify(e,null,2)),await lo(o,n)}};import{randomUUID as Fi}from"crypto";import{mkdir as fr,readFile as hr,writeFile as fo}from"fs/promises";import{dirname as gr,join as Gt}from"path";var Qe="[ProjectionWorker]",kc={version:1,runs:[]},Tc={version:1,updatedAt:0,proposals:[]},Rc=12;function jc(t){return Array.isArray(t)?t.map((e,n)=>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 Ui(t){let e=[];for(let n of t){if(!n||typeof n!="object")continue;let o=n;if(typeof o.id!="string"||typeof o.text!="string"){console.warn(`${Qe} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:o.id,scope:typeof o.scope=="string"?o.scope:"general",text:o.text,sources:Array.isArray(o.sources)?o.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Qe} Rule count ${e.length} exceeds cap of 30`),e}function Ac(t,e,n){return{decisionCount:t.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function Mc(t,e,n){let o=new Set(e),r=new Set,i=Array.isArray(t.rules)?t.rules:[];for(let S of i){if(!S||typeof S!="object")continue;let f=S.sources;if(Array.isArray(f))for(let p of f)typeof p=="string"&&o.has(p)&&r.add(p)}let s=t.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},a=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},d=Array.isArray(n?.rules)?n.rules:[],l=i.filter(S=>{if(!S||typeof S!="object")return!1;let f=S.id,p=typeof f=="string"?d.find(g=>g&&typeof g=="object"&&g.id===f):void 0;return JSON.stringify(p)!==JSON.stringify(S)}).length,v=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},T=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},b=Object.keys(s).filter(S=>JSON.stringify(s[S])!==JSON.stringify(v[S])).length,R=Object.keys(a).filter(S=>JSON.stringify(a[S])!==JSON.stringify(T[S])).length;return{ruleCount:l,tokenSectionCount:b,componentCount:R,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(S=>!r.has(S))}}function Ec(t){if(t!==void 0)return JSON.parse(JSON.stringify(t))}function _c(t,e,n){let o=t[e];if(o&&typeof o=="object")return o;let r=typeof n=="number"?[]:{};return t[String(e)]=r,r}function ho(t,e,n){let o=t;for(let i=0;i<e.length-1;i++)o=_c(o,e[i],e[i+1]);let r=e[e.length-1];o[String(r)]=Ec(n)}function zi(t,e){let n=t;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let o=e[e.length-1];Array.isArray(n)&&typeof o=="number"?n.splice(o,1):delete n[String(o)]}function Cc(t,e){if(!t)return{exists:!1};let n=t;for(let o of e){if(!n||typeof n!="object"||!(String(o)in n))return{exists:!1};n=n[String(o)]}return{exists:!0,value:n}}function $c(t,e){return Array.isArray(e)?t===void 0?e.length>0:!Array.isArray(t)||e.length<=t.length?!1:t.every((n,o)=>JSON.stringify(n)===JSON.stringify(e[o])):!1}function Hi(t,e){if(t.authorityStatus!=="accepted"||!t.changes?.length)return null;for(let n of t.changes){let o=Cc(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?$c(o.exists?o.value:void 0,n.value):!o.exists))return null}return t.changes}var go=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let o=Gt(e,".popmelt");this.runsPath=Gt(o,"projection-runs.json"),this.legacyRunsPath=Gt(o,"materialization-runs.json"),this.proposalsPath=Gt(o,"projection-queue.json"),this.legacyProposalsPath=Gt(o,"model-proposals.json"),this.modelPath=Gt(o,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await hr(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=jc(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let o of e){let r=o.key.split(".");o.value===null?zi(n,r):ho(n,r,o.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Rc),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let o=await this.selectUnprojectedPatternDecisions(),r=o.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(S=>S.id);console.log(`${Qe} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),a=Bc(r,s),d=Ac(r,o.totalCandidateDecisionCount,a);n=Fi().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"codex",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let v=!0,T,b,R;try{let S=`projection-${Date.now()}`,{provider:f,result:p}=this.spawnModelAgent(S,a,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)v=!1,T=g.error,console.error(`${Qe} ${f} spawn error:`,T);else{let w=Nc(g.text,i);if(w){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let m of w)ho(u,m.path,m.value);Array.isArray(u.rules)&&(u.rules=Ui(u.rules));let M=Mc(u,i,s);if(w){let m=[...new Set(w.flatMap(E=>E.decisionIds))];M.coveredDecisionIds=m,M.uncoveredDecisionIds=i.filter(E=>!m.includes(E))}b=M;let h=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:b,changes:w});R=h.id,console.log(`${Qe} Created model proposal ${h.id} for ${i.length} decision(s)`)}else v=!1,T="No valid bounded <model-changes> block found in response",console.error(`${Qe} ${T}`)}}catch(S){v=!1,T=S instanceof Error?S.message:String(S),console.error(`${Qe} Error:`,T)}return await this.persistRun({...l,status:v?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:b,proposalId:R}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:v,error:T}),{processedIds:i,success:v,error:T,runId:n,proposalId:R}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ui(e.rules)),await fo(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Qe} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await fr(gr(this.runsPath),{recursive:!0}),await fo(this.runsPath,JSON.stringify(n,null,2)),n):{...kc,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Tc,proposals:[]},o=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(o);for(let s of r.changes??[])ho(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(o=>o.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>r.updatedAt-o.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(o=>o.threadId===e).sort((o,r)=>o.createdAt-r.createdAt||o.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,o,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?zi(s,d.path):ho(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:o})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:Fi().slice(0,8),status:"pending",title:Oc(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"}.`:Dc(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},o=await this.loadModelProposals();return o.proposals=[n,...o.proposals.filter(r=>r.id!==n.id)].slice(0,100),o.updatedAt=Date.now(),await this.persistModelProposals(o),n}async updateModelProposal(e,n){let o=await this.loadModelProposals(),r=null;return o.proposals=o.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(o.updatedAt=Date.now(),await this.persistModelProposals(o),r):null}async persistModelProposals(e){try{await fr(gr(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:o,...r})=>r)};await fo(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Qe} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),o=n.runs.findIndex(r=>r.id===e.id);o>=0?n.runs[o]=e:n.runs.push(e),await fr(gr(this.runsPath),{recursive:!0}),await fo(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Qe} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await hr(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await hr(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,o,r){let i=o.provider??this.options.provider??"codex",s=this.options.onEvent?(a,d)=>this.options.onEvent?.(a):void 0;return i==="codex"?{provider:"codex",...ao(e,{prompt:n,projectRoot:this.projectRoot,model:o.model??this.options.model,configOverrides:no(o.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...oo(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?o.model??this.options.model:void 0,reasoningEffort:o.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function Oc(t){let n=(Array.isArray(t.rules)?t.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let o=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?Object.keys(t.components):[];return o.length>0?`Model update for ${o[0]}`:"Model update"}function Dc(t,e){let n=Array.isArray(t.rules)?t.rules.length:0,o=t.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?Object.keys(t.tokens).length:0,r=t.components&&typeof t.components=="object"&&!Array.isArray(t.components)?Object.keys(t.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${o} token section${o===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function Nc(t,e){let n=t.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let o=JSON.parse(n[1]);if(!Array.isArray(o)||o.length===0||o.length>40)return null;let r=new Set(e),i=o.flatMap((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(T=>typeof T=="string"||typeof T=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let v=Array.isArray(d.decisionIds)?d.decisionIds.filter(T=>typeof T=="string"&&r.has(T)):[];return v.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${a+1}`,path:d.path,value:d.value,decisionIds:v,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return i.length===o.length?i:null}catch{return null}}function Bc(t,e){let n=t.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
51
53
|
Kind: ${i.kind}
|
|
52
54
|
Claim: ${i.claim}
|
|
53
55
|
${i.rationale?`Rationale: ${i.rationale}`:""}
|
|
@@ -126,15 +128,15 @@ Example:
|
|
|
126
128
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
127
129
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
128
130
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
129
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
130
|
-
`),n=[],o=null;for(let r of e){let i=r.match(
|
|
131
|
+
Include property and bindings when the decision context has class-level evidence.`}var yo=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,n,o){for(let r of this.listeners)r(e,n,o)}cancelJob(e){let n=this.queue.findIndex(r=>r.id===e);if(n>=0){let[r]=this.queue.splice(n,1);return r?(r.status="cancelled",r.error="Cancelled by user",this.broadcast({type:"error",jobId:r.id,threadId:r.threadId,message:r.error,cancelled:!0,provider:r.provider,model:r.model},r.id,r.sourceId),r):null}let o=this.activeJob;return!o||o.id!==e?null:(o.status="cancelled",o.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:o.error,cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},o.id),this.processNext(),o)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}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(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),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 Jc}from"child_process";import{readFile as Vi}from"fs/promises";import{homedir as Ir}from"os";import{join as nt}from"path";var wr=/popmelt/i;function _t(){return{found:!1,name:null,scope:null,disabled:!1}}function Vt(t,e,n=!1){return{found:!0,name:t,scope:e,disabled:n}}function jn(t){for(let e of Object.keys(t))if(wr.test(e))return e;return null}async function Io(t){try{let e=await Vi(t,"utf-8");return JSON.parse(e)}catch{return null}}async function vr(t){let e=Ir(),n=await Io(nt(e,".claude.json"));if(n&&typeof n=="object"){let r=n;if(r.mcpServers&&typeof r.mcpServers=="object"){let i=jn(r.mcpServers);if(i)return Vt(i,"user")}if(r.projects&&typeof r.projects=="object"){let s=r.projects[t];if(s&&typeof s=="object"){let a=s;if(a.mcpServers&&typeof a.mcpServers=="object"){let d=jn(a.mcpServers);if(d){let l=Array.isArray(a.disabledMcpjsonServers)&&a.disabledMcpjsonServers.some(v=>wr.test(v));return Vt(d,"project",l)}}}}}let o=await Io(nt(t,".mcp.json"));if(o&&typeof o=="object"){let r=o;if(r.mcpServers&&typeof r.mcpServers=="object"){let s=jn(r.mcpServers);if(s){let a=await Wi(t,s);return Vt(s,"mcp.json",a)}}let i=jn(r);if(i&&i!=="mcpServers"){let s=await Wi(t,i);return Vt(i,"mcp.json",s)}}return _t()}async function Wi(t,e){let n=nt(t,".claude","settings.local.json"),o=await Io(n);if(o&&typeof o=="object"){let r=o;if(Array.isArray(r.disabledMcpjsonServers))return r.disabledMcpjsonServers.some(i=>i===e)}return!1}var Lc=/^\[mcp_servers\.([^\]]+)\]/;function qc(t){let e=t.split(`
|
|
132
|
+
`),n=[],o=null;for(let r of e){let i=r.match(Lc);i?(o&&n.push({name:o.name,body:o.bodyLines.join(`
|
|
131
133
|
`)}),o={name:i[1],bodyLines:[]}):r.startsWith("[")?o&&(n.push({name:o.name,body:o.bodyLines.join(`
|
|
132
134
|
`)}),o=null):o&&o.bodyLines.push(r)}return o&&n.push({name:o.name,body:o.bodyLines.join(`
|
|
133
|
-
`)}),n}function
|
|
134
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
135
|
+
`)}),n}function Fc(t){return/enabled\s*=\s*false/i.test(t)}async function br(t){let e=process.env.CODEX_HOME||nt(Ir(),".codex"),n=await Gi(nt(e,"config.toml"),"user");if(n.found)return n;let o=await Gi(nt(t,".codex","config.toml"),"project");return o.found?o:_t()}async function xr(t,e="copilot"){let n=await Uc(e);if(n.found)return n;let o=process.env.COPILOT_HOME||nt(Ir(),".copilot"),r=await yr(nt(o,"mcp-config.json"),"user");if(r.found)return r;let i=await yr(nt(t,".mcp.json"),"mcp.json");if(i.found)return i;let s=await yr(nt(t,".github","mcp.json"),"mcp.json");return s.found?s:_t()}async function Uc(t){try{let e=await new Promise((n,o)=>{Jc(t,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}n(i)})});return Ki(JSON.parse(e),"user")}catch{return _t()}}async function yr(t,e){let n=await Io(t);return Ki(n,e)}function Ki(t,e){if(!t||typeof t!="object")return _t();let n=t,o=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,r=jn(o);return r?Vt(r,e):_t()}async function Gi(t,e){try{let n=await Vi(t,"utf-8"),o=qc(n);for(let r of o)if(wr.test(r.name)){let i=Fc(r.body);return Vt(r.name,e,i)}}catch{}return _t()}import{execFile as Qi}from"child_process";import{mkdir as zc,readFile as Xi,writeFile as Yi}from"fs/promises";import{homedir as Zi}from"os";import{dirname as Hc,join as Sr}from"path";var Pr="https://mcp.popmelt.com/mcp";async function es(t=Pr){let e=Sr(Zi(),".claude.json"),n;try{let r=await Xi(e,"utf-8");n=JSON.parse(r)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let o=n.mcpServers;for(let r of Object.keys(o))if(/popmelt/i.test(r))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return o.popmelt={type:"http",url:t},await Yi(e,JSON.stringify(n,null,2)+`
|
|
136
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function ts(t=Pr){let e=process.env.CODEX_HOME||Sr(Zi(),".codex"),n=Sr(e,"config.toml"),o;try{o=await Xi(n,"utf-8")}catch{o=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(o))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await zc(Hc(n),{recursive:!0});let r=`
|
|
135
137
|
[mcp_servers.popmelt]
|
|
136
138
|
url = "${t}"
|
|
137
|
-
`;return await
|
|
139
|
+
`;return await Yi(n,o+r,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function ns(t=Pr,e="copilot"){let n=await Wc(e);if(Gc(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((o,r)=>{Qi(e,["mcp","add","--transport","http","--json","popmelt",t],{encoding:"utf-8",timeout:1e4},i=>{if(i){r(i);return}o()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(o){return{installed:!1,provider:"copilot",scope:null,reason:o instanceof Error?o.message:"install_failed"}}}async function Wc(t){try{let e=await new Promise((n,o)=>{Qi(t,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(r,i)=>{if(r){o(r);return}n(i)})});return JSON.parse(e)}catch{return null}}function Gc(t){if(!t||typeof t!="object")return!1;let e=t,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(o=>/popmelt/i.test(o))}var wo=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 n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,o=Date.now()){let r=this.leases.get(e),i={id:e,ownerPid:n,createdAt:r?.createdAt??o,expiresAt:o+this.ttlMs};return this.activated=!0,this.leases.set(e,i),i}heartbeat(e,n=Date.now()){let o=this.leases.get(e);return o?(o.expiresAt=n+this.ttlMs,o):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[o,r]of this.leases)r.expiresAt>e||(this.leases.delete(o),n.push(o));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};var Vc=String.raw`
|
|
138
140
|
(() => {
|
|
139
141
|
const hidden = [];
|
|
140
142
|
const visit = (root) => {
|
|
@@ -155,7 +157,7 @@ url = "${t}"
|
|
|
155
157
|
visit(document);
|
|
156
158
|
window.__popmeltNativeCaptureHidden = hidden;
|
|
157
159
|
})()
|
|
158
|
-
`,
|
|
160
|
+
`,Kc=String.raw`
|
|
159
161
|
(() => {
|
|
160
162
|
for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
|
|
161
163
|
if (value) element.style.setProperty('visibility', value, priority);
|
|
@@ -163,22 +165,22 @@ url = "${t}"
|
|
|
163
165
|
}
|
|
164
166
|
delete window.__popmeltNativeCaptureHidden;
|
|
165
167
|
})()
|
|
166
|
-
`;function wo(t){try{let e=new URL(t);return e.hash="",e.href}catch{return null}}function Kc(t,e){let n=wo(e);if(!n)return null;let o=new URL(n),r=t.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&wo(s.url)),i=r.find(s=>wo(s.url)===n);return i||(r.find(s=>{let a=new URL(wo(s.url));return a.origin===o.origin&&a.pathname===o.pathname})??null)}function Qc(t){let e={x:Number(t.x),y:Number(t.y),width:Number(t.width),height:Number(t.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Xc(t){let e=new AbortController,n=setTimeout(()=>e.abort(),1e3);try{let o=new URL("/json/list",t).href,r=await fetch(o,{signal:e.signal});if(!r.ok)throw new Error(`CDP discovery returned ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}finally{clearTimeout(n)}}async function Yc(t){let{WebSocket:e}=await import("ws");return new Promise((n,o)=>{let r=new e(t,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),n(r)},s=a=>{r.off("open",i),o(a)};r.once("open",i),r.once("error",s)})}function Zc(t){let e=1,n=new Map;return t.on("message",o=>{let r;try{r=JSON.parse(String(o))}catch{return}if(!r.id)return;let i=n.get(r.id);i&&(n.delete(r.id),clearTimeout(i.timeout),r.error?i.reject(new Error(r.error.message||`CDP error ${r.error.code??""}`.trim())):i.resolve(r.result??{}))}),t.on("close",()=>{for(let[o,r]of n)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),n.delete(o)}),(o,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{n.delete(a),s(new Error(`CDP ${o} timed out`))},4e3);n.set(a,{resolve:i,reject:s,timeout:d}),t.send(JSON.stringify({id:a,method:o,params:r}),l=>{l&&(clearTimeout(d),n.delete(a),s(l))})})}async function ns(t,e){let n=Qc(e.clip),o=await Xc(t),r=Kc(o,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Yc(r.webSocketDebuggerUrl),s=Zc(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Gc,returnByValue:!0}),a=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...n,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{a&&await s("Runtime.evaluate",{expression:Vc,returnByValue:!0}).catch(()=>{}),i.close()}}import{mkdir as gs,readFile as _n,writeFile as ys}from"fs/promises";import{join as Yt}from"path";var el=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Pr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function vo(t){return new Set(Pr(t).split(" ").filter(e=>e.length>2&&!el.has(e)))}function os(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function tl(t){return[{value:t.label,by:"label"},...t.aliases.map(e=>({value:e,by:"alias"})),...t.locators.map(e=>({value:e.value,by:"locator"}))]}function nl(t,e){let n=new Map,o=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Pr).filter(Boolean),i=vo([e.action,e.text].filter(Boolean).join(" "));for(let s of t){if(o.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a;for(let d of tl(s)){let l=Pr(d.value);for(let b of r){let R=l===b?95:l.includes(b)||b.includes(l)?75:0;R>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:R>=90?"exact":"strong",matchedBy:d.by,score:R})}let x=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(os(vo(l),i)*55);x>=30&&x>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:x>=45?"strong":"weak",matchedBy:"query_text",score:x})}a&&n.set(s.id,a)}return n}function ol(t,e){let n=new Set(t.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),o=new Set(t.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(a=>n.has(a))||s.sourceRefs.some(a=>a.kind==="thread"&&o.has(a.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function rl(t){return Math.ceil(JSON.stringify(t).length/4)}function An(t,e){let n=t.records.filter(p=>p.recordType==="subject"),o=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=t.records.filter(p=>{if(p.recordType!=="proposal"||r&&!r.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let g=[...t.events].reverse().find(w=>w.entity.entityType==="proposal"&&w.entity.entityId===p.id&&w.toState==="deferred"&&w.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(o)>=Date.parse(g.revisitAfter)):!1}),s=t.records.filter(p=>p.recordType==="implementation_attempt"),a=nl(n,e),d=[...a.values()].sort((p,g)=>g.score-p.score),l=vo([e.action,e.text].filter(Boolean).join(" ")),v=i.flatMap(p=>{let g=p.subjects.map(h=>a.get(h.subjectId)).filter(h=>!!h),w=Math.max(0,...g.map(h=>h.score)),u=Math.round(os(vo(p.claim),l)*35),M=w+u;return M>=50?[{proposal:p,proposalMatches:g,score:M}]:[]}).sort((p,g)=>g.score-p.score||p.proposal.id.localeCompare(g.proposal.id)),x=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),R=[],P=0;for(let p of v){if(R.length>=x)break;let g=p.proposal.sourceRefs.slice(0,4),w={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:t.manifest.projectId,generatedAt:o,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:ol(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={...w,estimatedTokens:rl(w)};if(P+u.estimatedTokens>b)break;R.push(u),P+=u.estimatedTokens}let f=Math.max(0,v.length-R.length);return{packets:R,subjectMatches:d.map(({score:p,...g})=>g),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:f,maxEstimatedTokens:b,estimatedTokens:P},uncertainty:a.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var il=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function kr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function bo(t){return new Set(kr(t).split(" ").filter(e=>e.length>2&&!il.has(e)))}function rs(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function sl(t,e){let n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(kr).filter(Boolean),r=bo([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of t){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=kr(l.value);for(let R of o){let P=v===R?95:v.includes(R)||R.includes(v)?75:0;P>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:l.by,score:P})}let b=["/","#","[","]","="].some(R=>l.value.includes(R))?0:Math.round(rs(bo(v),r)*55);b>=30&&b>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function al(t){return Math.ceil(JSON.stringify(t).length/4)}function Kt(t,e){return t.relationshipType===e&&t.from.entityType==="decision"&&t.to.entityType==="decision"}function dl(t,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let o=n.filter(i=>i.state==="completed"),r=o.some(i=>i.coverageClaims.some(s=>s.decisionId===t&&s.coverage==="full"));return{decisionId:t,state:r?"implemented":o.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function cl(t,e,n){let o=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===t)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=n.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===t),i=o[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:s,attemptIds:o.map(a=>a.id)}}function is(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),o=Math.max(1,e.maxDecisions??6),r=t.records.filter(m=>m.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=t.records.filter(m=>m.recordType==="decision"&&m.state==="active"),a=i?s.filter(m=>i.has(m.id)):s,d=t.records.filter(m=>m.recordType==="implementation_attempt"),l=t.records.filter(m=>m.recordType==="verification_attempt"),v=t.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),x=t.records.filter(m=>m.recordType==="evidence"),b=t.records.filter(m=>m.recordType==="model_entry"),R=sl(r,e),P=new Map(R.map(m=>[m.subjectId,m.score])),f=bo([e.action,e.text].filter(Boolean).join(" ")),p=a.flatMap(m=>{let E=Math.max(0,...m.subjects.map(C=>P.get(C.subjectId)??0)),D=Math.round(rs(bo(m.claim),f)*35),k=E+D;return k>=50?[{decision:m,score:k}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of p.slice(0,o))g.set(m.decision.id,m.decision);for(let m of t.relationships){if(!Kt(m,"excepts")&&!Kt(m,"contradicts"))continue;let E=s.find(k=>k.id===m.from.entityId),D=s.find(k=>k.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<o&&g.set(E.id,E),g.size<o&&g.set(D.id,D))}let w=[...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)),k=v.filter(B=>B.target.entityType==="decision"&&D.has(B.target.entityId)),C=new Set(t.relationships.filter(B=>Kt(B,"excepts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),X=t.relationships.filter(B=>Kt(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=x.filter(B=>B.sourceRefs.some(V=>V.kind==="record"&&D.has(V.id))||t.relationships.some(V=>V.relationshipType==="supports"&&V.from.entityType==="evidence"&&V.from.entityId===B.id&&V.to.entityType==="decision"&&D.has(V.to.entityId))),S=Math.max(0,p.length-m.length),Q=t.relationships.some(B=>Kt(B,"contradicts")&&u(B)&&(!D.has(B.from.entityId)||!D.has(B.to.entityId))),L=E||S>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(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:t.manifest.projectId}]});let W={contractVersion:1,projectId:t.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:R.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:k.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=>dl(B.id,d)),verification:m.map(B=>cl(B.id,l,k)),evidence:Y.map(B=>({evidenceId:B.id,summary:B.summary,availability:B.availability,sourceRefs:B.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:S,omittedEvidenceCount:0,conflictsComplete:!Q}};return W.budget.estimatedTokens=al(W),W},h=M(w);for(;h.budget.estimatedTokens>n&&w.length>0;){let m=w.pop(),E=t.relationships.filter(D=>Kt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);w=w.filter(D=>!E.includes(D.id)),h=M(w,!0)}return h}var ll=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Qt(t){return ll.test(t)}function pl(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function oe(t,e,n,o){t.push({path:e,code:n,message:o,severity:"error"})}function Tr(t,e,n,o){t.push({path:e,code:n,message:o,severity:"warning"})}function Ee(t,e,n){Qt(n)||oe(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Xe(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&oe(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Ct(t,e,n,o=!1){o&&n.level==="contributor"&&oe(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&oe(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ul={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"])},ml=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function fl(t,e,n){Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Ee(t,`${n}.entity.entityId`,e.entity.entityId),Xe(t,`${n}.createdAt`,e.createdAt),Ct(t,`${n}.authority`,e.authority);let o=ul[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;o&&!o.has(r)&&oe(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(ml.has(i)&&(Ct(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||oe(t,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&oe(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&oe(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Xe(t,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function hl(t,e,n,o){Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Xe(t,`${n}.createdAt`,e.createdAt),e.projectId!==o&&oe(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&oe(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&oe(t,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&oe(t,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Ct(t,`${n}.authority`,e.authority,!0),e.claim.trim()||oe(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Tr(t,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&oe(t,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Xe(t,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&oe(t,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&oe(t,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&oe(t,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Xe(t,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),Xe(t,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&oe(t,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Xe(t,`${n}.appliedAt`,e.appliedAt),Ct(t,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&oe(t,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&oe(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&oe(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Tr(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Tr(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function gl(t,e,n){if(Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Ee(t,`${n}.from.entityId`,e.from.entityId),Ee(t,`${n}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&oe(t,`${n}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&oe(t,`${n}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),Xe(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||oe(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&oe(t,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?oe(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Ct(t,`${n}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&oe(t,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&oe(t,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&oe(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&oe(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function $t(t){let e=[];Ee(e,"manifest.projectId",t.manifest.projectId),Xe(e,"manifest.createdAt",t.manifest.createdAt),Xe(e,"manifest.updatedAt",t.manifest.updatedAt);let n=new Map,o=(f,p)=>{let g=n.get(f);g?oe(e,p,"duplicate_id",`ID is already used at ${g}.`):n.set(f,p)};t.records.forEach((f,p)=>{let g=`records[${p}]`;o(f.id,g),hl(e,f,g,t.manifest.projectId)}),t.events.forEach((f,p)=>{let g=`events[${p}]`;o(f.id,g),fl(e,f,g),f.projectId!==t.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((f,p)=>{let g=`relationships[${p}]`;o(f.id,g),gl(e,f,g),f.projectId!==t.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((f,p)=>{o(f.id,`artifacts[${p}]`),Ee(e,`artifacts[${p}].id`,f.id)}),t.tombstones.forEach((f,p)=>{let g=`tombstones[${p}]`;o(f.id,g),Ee(e,`${g}.id`,f.id),Ee(e,`${g}.objectId`,f.objectId),Ee(e,`${g}.deletedById`,f.deletedById),Xe(e,`${g}.deletedAt`,f.deletedAt),Ct(e,`${g}.authority`,f.authority,!0)});let r=new Set(t.records.map(f=>`${f.recordType}:${f.id}`)),i=new Set(t.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{if(f.storeId)return;let g=`${f.entityType}:${f.entityId}`;!r.has(g)&&!i.has(g)&&oe(e,p,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};t.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),t.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let a=new Set(t.artifacts.map(f=>f.id)),d=(f,p)=>{a.has(f)||oe(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,g)=>{!r.has(`${f}:${p}`)&&!i.has(`${f}:${p}`)&&oe(e,g,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};t.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((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`));break;case"observation":f.captureContext.subjectIds.forEach((w,u)=>l("subject",w,`${g}.captureContext.subjectIds[${u}]`)),f.captureContext.artifactIds.forEach((w,u)=>d(w,`${g}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":f.subjects.forEach((w,u)=>l("subject",w.subjectId,`${g}.subjects[${u}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((w,u)=>d(w,`${g}.messageArtifactIds[${u}]`)),f.resultRefs.forEach((w,u)=>s(w,`${g}.resultRefs[${u}]`));break;case"iteration":f.threadIds.forEach((w,u)=>l("thread",w,`${g}.threadIds[${u}]`)),f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"evidence":f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"advisory_explanation":f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${g}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((w,u)=>l("iteration",w,`${g}.iterationIds[${u}]`)),f.coverageClaims.forEach((w,u)=>l("decision",w.decisionId,`${g}.coverageClaims[${u}].decisionId`)),f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${g}.replacesSpecId`),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`)),f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),(f.dependencies??[]).forEach((w,u)=>{w.kind==="subject"&&w.subjectId&&l("subject",w.subjectId,`${g}.dependencies[${u}].subjectId`)}),(f.scenarios??[]).forEach((w,u)=>{w.subjectIds?.forEach((M,h)=>l("subject",M,`${g}.scenarios[${u}].subjectIds[${h}]`))}),f.targets.forEach((w,u)=>l(w.entityType,w.entityId,`${g}.targets[${u}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${g}.evalSpecId`),f.targets.forEach((w,u)=>l(w.entityType,w.entityId,`${g}.targets[${u}]`)),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`));break;case"model_entry":f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`));break;case"model_projection":Ct(e,`${g}.authority`,f.authority,!0),l("participant",f.appliedById,`${g}.appliedById`),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`)),f.entryIds.forEach((w,u)=>l("model_entry",w,`${g}.entryIds[${u}]`)),f.coverage.forEach((w,u)=>l("decision",w.decisionId,`${g}.coverage[${u}].decisionId`));break;case"freshness_signal":s(f.target,`${g}.target`),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`));break;default:break}});let v=new Map(t.events.map(f=>[f.id,f])),x=new Map(t.records.map(f=>[`${f.recordType}:${f.id}`,f])),b=new Map;t.events.forEach((f,p)=>{let g=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,w=b.get(g)??new Set;w.add(f.toState),b.set(g,w),w.size>1&&oe(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let R=new Map(t.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),P=(f,p,g,w,u)=>{if(f.level!=="delegate"||!f.grantId)return;let M=R.get(f.grantId);if(!M){oe(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&oe(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(g);(h<Date.parse(M.startsAt)||M.endsAt&&h>Date.parse(M.endsAt)||M.revokedAt&&h>=Date.parse(M.revokedAt))&&oe(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&w.length&&!w.every(m=>M.subjectIds.includes(m))&&oe(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of t.records)f.recordType==="decision"&&P(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);t.events.forEach((f,p)=>{let g=x.get(`${f.entity.entityType}:${f.entity.entityId}`),w=g&&"subjects"in g?g.subjects.map(u=>u.subjectId):[];P(f.authority,f.participantId,f.createdAt,w,`events[${p}].authority`)}),t.relationships.forEach((f,p)=>{if(!f.authority)return;let g=[f.from,f.to].flatMap(w=>{let u=x.get(`${w.entityType}:${w.entityId}`);return u&&"subjects"in u?u.subjects.map(M=>M.subjectId):[]});P(f.authority,f.participantId,f.createdAt,g,`relationships[${p}].authority`)});for(let f of t.records){if(f.recordType!=="decision")continue;let p=v.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&oe(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&oe(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),x.has(`proposal:${f.proposalId}`)||oe(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(t.relationships.some(w=>w.relationshipType==="supersedes"&&w.to.entityType==="decision"&&w.to.entityId===f.id)||oe(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(t.events.some(w=>w.entity.entityType==="decision"&&w.entity.entityId===f.id&&w.toState==="revoked"&&!!w.reason?.trim())||oe(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of t.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;t.records.some(g=>g.recordType==="decision"&&g.proposalId===f.id)||oe(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return pl(e)}function Mn(t,e,n,o){return{id:o,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function ss(t,e,n,o,r){return{id:r,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:o,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function yl(t){switch(t.action){case"accept":return[t.eventId,t.decisionId];case"edit_and_accept":return[t.withdrawalEventId,t.replacementProposalId,t.acceptanceEventId,t.decisionId,t.relationshipId];case"reject":case"defer":return[t.eventId]}}function xo(t,e){let n=[],o=t.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);o?o.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${o.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Qt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of yl(e))Qt(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!o)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=ss(t,o,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Mn(t,o,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...Mn(t,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=ss(t,i,e,a.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:o.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[i,d],events:[s,a],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}let r={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}import{createHash as Il}from"crypto";import{readFile as wl,readdir as vl,realpath as bl}from"fs/promises";import{join as En,relative as xl}from"path";var Sl=["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 Xt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function He(t,e=0){return new Date(Number.isFinite(t)?t:e).toISOString()}function as(...t){return t.find(e=>!!e?.trim())?.trim()}function le(t,e,n,o){let i=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),s=Il("sha256").update(`${t}\0${e}\0${n}`).digest("hex"),a=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${a}${s.slice(4,7)}-${s.slice(7,19)}`}async function Rr(t,e){try{return JSON.parse(await wl(t,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:t,message:n instanceof Error?n.message:String(n)}),null}}function Pl(t){let e=Xt(t);if(!e)return 0;let n=0,o=r=>{let i=Xt(r);if(!i){n+=1;return}for(let s of Object.values(i))o(s)};for(let r of Object.values(e))o(r);return n}function kl(t){let e={};for(let n of t)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Ot(t){let e=[],n=await bl(t.projectRoot).catch(()=>t.projectRoot),o=En(n,".popmelt"),r=await Rr(En(o,"threads.json"),e),i=await Rr(En(o,"model.json"),e),s=Xt(r),a=Xt(s?.threads)??{},d=Object.entries(a).map(([V,H])=>({key:V,value:Xt(H)})).filter(V=>!!V.value),l=En(o,"decisions"),v=await vl(l).catch(()=>[]),x=[];for(let V of v.filter(H=>H.endsWith(".json")).sort()){let H=Xt(await Rr(En(l,V),e));H&&x.push({file:V,value:H})}let b=d.flatMap(({value:V})=>[V.createdAt,V.updatedAt]).filter(V=>typeof V=="number"&&Number.isFinite(V)),R=b.length?Math.min(...b):0,P=t.projectKey??n;t.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(P,"project",P,R),p=le(P,"participant","legacy-owner",R),g=le(P,"participant","legacy-agent",R),w=le(P,"subject","project",R),u=He(Math.max(R,...b)),M=[],h=[],m=new Map,E=new Map,D=new Map(x.map(V=>[V.value.id??V.file.replace(/^d-|\.json$/g,""),V.value])),k=new Map,C=(V,H,ee,Re,Le)=>{let ue=m.get(ee);if(ue)return ue;let $e=le(P,"artifact",V,Re);return h.push({id:$e,kind:H,mediaType:Le,location:ee,availability:"available"}),m.set(ee,$e),$e};for(let{file:V,value:H}of x){let ee=H.id??V.replace(/^d-|\.json$/g,""),Re=H.createdAt??R,Le=[C(`${ee}:envelope`,"other",`.popmelt/decisions/${V}`,Re,"application/json")];H.screenshotPath&&Le.push(C(`${ee}:screenshot`,"screenshot",`.popmelt/${H.screenshotPath.replace(/^\.popmelt\//,"")}`,Re,H.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,$e]of(H.pastedImagePaths??[]).entries())Le.push(C(`${ee}:image:${ue}`,"image",$e,Re));k.set(ee,Le)}let z=(V,H,ee)=>({id:V,schemaVersion:1,projectId:f,createdAt:u,participantId:H,sourceRefs:ee}),X=(V,H)=>{M.push(H);let ee=E.get(V)??[];ee.push(H.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(w,p,[]),recordType:"subject",subjectType:"project",label:xl(process.cwd(),n)||n,aliases:[],locators:[{id:le(P,"locator",n,R),kind:"project_root",value:n,status:"current",validFrom:He(R),sourceRefs:[]}]});let Y=new Map,S=(V,H)=>{let ee=Y.get(V);if(ee)return ee;let Re=le(P,"subject",V,H),Le={...z(Re,p,[{kind:"external",id:V}]),createdAt:He(H),recordType:"subject",subjectType:"element",label:V,aliases:[],locators:[{id:le(P,"locator",V,H),kind:"dom_selector",value:V,status:"current",validFrom:He(H),sourceRefs:[{kind:"external",id:V}]}]};return M.push(Le),Y.set(V,Re),Re};for(let{key:V,value:H}of d){let ee=H.id??V,Re=H.createdAt??R,Le=le(P,"thread",ee,Re),ue={kind:"thread",id:ee},$e=[],St=[],fn=Array.isArray(H.messages)?H.messages:[],je,it,Pt=0;fn.forEach((xe,mt)=>{let Oe=xe.timestamp??Re,st=le(P,"artifact",`${ee}:message:${mt}`,Oe);if($e.push(st),h.push({id:st,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ee}/messages/${mt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${ee}/messages/${mt}`,st),xe.screenshotPath&&C(`${ee}:message:${mt}:screenshot`,"screenshot",xe.screenshotPath,Oe),xe.role==="human"){je=xe;let qe=xe.feedbackSummary??xe.replyToQuestion;if(qe?.trim()){let Ue=le(P,"observation",`${ee}:${mt}`,Oe),Ze=H.elementIdentifiers??[],Jt={...z(Ue,p,[ue,{kind:"message",id:st}]),createdAt:He(Oe),recordType:"observation",state:"open",statement:qe,captureContext:{subjectIds:Ze.map(Rt=>S(Rt,Re)),artifactIds:[st]},resolvedByIds:[]};X(ee,Jt),it=Ue,St.push({entityType:"observation",entityId:Ue})}return}if(xe.role!=="assistant")return;let ft=xe.jobId??`${ee}:${mt}`,ht=le(P,"iteration",ft,Oe),Tt=D.get(ft),Ko=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",Qo={...z(ht,g,[ue,{kind:"message",id:st},...(k.get(ft)??[]).map(qe=>({kind:"artifact",id:qe}))]),createdAt:He(Oe),recordType:"iteration",threadIds:[Le],startedAt:He(je?.timestamp,Oe),completedAt:He(Oe),requestSummary:as(je?.feedbackSummary,je?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:Ko,execution:{provider:xe.provider??Tt?.provider,model:xe.model??Tt?.model,sessionId:xe.sessionId??Tt?.sessionId},artifactIds:[st,...k.get(ft)??[]]};X(ee,Qo),St.push({entityType:"iteration",entityId:ht});let hn=xe.resolutions??Tt?.resolutions??[];for(let[qe,Ue]of hn.entries()){if(Ue.status!=="resolved"||!Ue.summary?.trim())continue;let Ze=H.elementIdentifiers??[],Jt=(Ze.length?Ze:[n]).map(Qn=>({subjectId:Qn===n?w:S(Qn,Re),role:"governed"})),Rt=le(P,"proposal",`${ft}:${Ue.annotationId??"resolution"}:${qe}`,Oe),Xo={...z(Rt,g,[ue,{kind:"iteration",id:ht}]),createdAt:He(Oe),recordType:"proposal",state:"pending",claim:Ue.summary,subjects:Jt,subjectSemantics:Jt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:as(je?.feedbackSummary,je?.replyToQuestion,Ue.summary),iterationId:ht,inferredById:g}};X(ee,Xo),St.push({entityType:"proposal",entityId:Rt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ee,message:`Proposal ${Rt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(hn.some(qe=>qe.status==="resolved")||Tt?.gitDiff){let qe=le(P,"implementation",ft,Oe),Ue={...z(qe,g,[ue,{kind:"iteration",id:ht}]),createdAt:He(Oe),recordType:"implementation_attempt",state:"completed",iterationIds:[ht],coverageClaims:[],summary:hn.map(Ze=>Ze.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};X(ee,Ue),St.push({entityType:"implementation_attempt",entityId:qe}),Pt+=1}it&&(it=void 0)});let kt=fn.at(-1),Kn={...z(Le,p,[ue]),createdAt:He(Re),recordType:"thread",state:kt?.question?"open":"resolved",messageArtifactIds:$e,outcome:kt?.question?"question_unresolved":Pt?"implementation_only":"no_outcome",resultRefs:St};M.push(Kn),E.set(ee,[Le,...E.get(ee)??[]])}let Q=Pl(i);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:He(R),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:t.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:h,tombstones:[]},K=$t(L),B=(t.proofCaseIds??Sl).map(V=>({legacyId:V,threadFound:d.some(({key:H,value:ee})=>(ee.id??H)===V),decisionEnvelopeFound:D.has(V),recordIds:E.get(V)??[]}));return{bundle:L,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((V,H)=>V+(H.value.messages?.length??0),0),decisionEnvelopes:x.length,modelEntries:Q,artifactsReferenced:h.length},imported:kl(M),unresolvedAcceptance:e.filter(V=>V.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:B,issues:e,schemaIssues:K.issues}}}import{createHash as Tl}from"crypto";import{mkdir as ds,open as jr,readFile as Ar,readdir as Rl,rename as jl,unlink as Mr}from"fs/promises";import{join as ct}from"path";var Al={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Po(t){return Tl("sha256").update(JSON.stringify(t)).digest("hex")}function cs(t){return Po(t)}function ls(t,e,n){[...e.records,...e.recordReplacements??[]].some(o=>o.recordType==="advisory_explanation")&&!t.manifest.features.includes("advisory_explanations")&&t.manifest.features.push("advisory_explanations");for(let o of e.recordReplacements??[]){if(o.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${o.recordType}.`);let r=t.records.findIndex(s=>s.recordType===o.recordType&&s.id===o.id);if(r<0)throw new Error(`Record replacement target not found: ${o.recordType} ${o.id}`);let i=t.records[r];if(i.projectId!==o.projectId||i.createdAt!==o.createdAt||i.participantId!==o.participantId)throw new Error(`Record replacement changed immutable identity for ${o.id}.`);t.records[r]=structuredClone(o)}for(let o of e.projectionUpdates){let r=t.records.find(i=>i.recordType===o.entityType&&i.id===o.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${o.entityType} ${o.entityId}`);if(r.state!==o.fromState)throw new Error(`Projection state conflict for ${o.entityType} ${o.entityId}: expected ${o.fromState}, found ${r.state}`);r.state=o.state}return t.records.push(...e.records),t.events.push(...e.events),t.relationships.push(...e.relationships),t.artifacts.push(...e.artifacts),t.tombstones.push(...e.tombstones),t.manifest.updatedAt=n,t}function Ml(t,e,n){return ls(structuredClone(t),e,n)}async function Dt(t,e){let n=`${t}.${process.pid}.${Date.now()}.tmp`,o=await jr(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
167
|
-
`,"utf8"),await o.sync()}finally{await o.close()}try{await jl(n,t)}catch(r){throw await Mr(n).catch(()=>{}),r}}async function So(t){return JSON.parse(await Ar(t,"utf8"))}var ko=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=ct(e,".popmelt","memory"),this.journalDir=ct(this.memoryDir,"journal"),this.manifestPath=ct(this.memoryDir,"manifest.json"),this.checkpointPath=ct(this.memoryDir,"checkpoint.json"),this.lockPath=ct(this.memoryDir,"writer.lock")}async initialize(e){let n=$t(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await ds(this.journalDir,{recursive:!0});try{throw await Ar(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(o){if(o instanceof Error&&o.message==="Memory journal is already initialized."||o.code!=="ENOENT")throw o}await this.withWriterLock(async()=>{try{throw await Ar(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let o=Po(e),r={storageVersion:1,sequence:0,hash:o,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:o},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await Dt(this.checkpointPath,r),await Dt(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await Dt(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 n=Po(e.bundle),o=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await Dt(ct(this.memoryDir,o),r),e.manifest.checkpoint={file:o,sequence:r.sequence,hash:n},await Dt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Qt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let o=await this.loadInternal();if(o.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=o.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:o.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:o.report.headHash,mutation:e},s={...i,hash:cs(i)},a=Ml(o.bundle,e,n.committedAt),d=$t(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await Dt(ct(this.journalDir,l),s),o.manifest.head={sequence:r,hash:s.hash},o.manifest.updatedAt=n.committedAt,await Dt(this.manifestPath,o.manifest),{bundle:a,report:{checkpointSequence:o.report.checkpointSequence,appliedTransactions:o.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:o.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Al,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await So(this.manifestPath),n=await So(ct(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==Po(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let o=await Rl(this.journalDir),r=o.filter(b=>b.endsWith(".tmp")),s=o.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),a=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of s){let R=await So(ct(this.journalDir,b)),{hash:P,...f}=R;if(P!==cs(f))throw new Error(`Journal hash mismatch: ${b}`);if(R.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(R.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(R.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(R.transactionId))throw new Error(`Duplicate transaction ID: ${R.transactionId}`);ls(a,R.mutation,R.committedAt),d=R.sequence,l=R.hash,v.add(R.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let x=$t(a);if(!x.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(x.issues)}`);return{bundle:a,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await ds(this.memoryDir,{recursive:!0});let n;try{n=await jr(this.lockPath,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let r=await So(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await Mr(this.lockPath),n=await jr(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Mr(this.lockPath).catch(()=>{})}}};import{randomBytes as El}from"crypto";function Se(t=Date.now()){let n=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),o=El(10).toString("hex"),r=(Number.parseInt(o[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${o.slice(0,3)}-${r}${o.slice(4,7)}-${o.slice(7,19)}`}var _l=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function ps(t,e){let n=t.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),o=t.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!o)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=t.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=_l(),l=d.records,v=t.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));v||(v={id:le(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.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(v));let x=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let M=t.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===u&&m.status==="current"));M||(M={id:le(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),x.push(M)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=t.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===u&&m.status==="current"));M||(M={id:le(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),x.push(M)}let b=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),R;if(b.length>0){R=le(r,"live-observation",i,e.createdAt);let u={id:R,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:x.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let P=le(r,"live-iteration",i,e.completedAt),f={id:P,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...R?[{kind:"record",id:R}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:s,completedAt:a,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};l.push(f);let p=[],g=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),w=x.length>0?x:t.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(b.length>0&&w.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(r,"live-proposal",`${i}:${u}`,e.completedAt),m=w.map(D=>({subjectId:D.id,role:"governed"})),E={id:h,schemaVersion:1,projectId:t.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:P},{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:P,inferredById:o.id}};l.push(E),p.push(h)}if(g.length>0){let u=new Set(e.governingDecisionIds??[]),M=t.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&u.has(m.id)),h={id:le(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:a,participantId:o.id,sourceRefs:[{kind:"iteration",id:P}],recordType:"implementation_attempt",state:"completed",iterationIds:[P],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:P}]})),summary:g.map(m=>m.summary).join(" "),artifactIds:[]};l.push(h)}return{mutation:d,iterationId:P,proposalIds:p,observationId:R}}import{createHash as Cl}from"crypto";import{mkdir as $l,open as Ol,readFile as Dl,rename as Nl,unlink as Bl}from"fs/promises";import{join as us}from"path";function ms(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function fs(t){return Cl("sha256").update(JSON.stringify(t)).digest("hex")}async function Jl(t,e){let n=`${t}.${process.pid}.${Date.now()}.tmp`,o=await Ol(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
168
|
-
`,"utf8"),await o.sync()}finally{await o.close()}try{await Nl(n,t)}catch(r){throw await Bl(n).catch(()=>{}),r}}function Ll(t,e,n=new Date().toISOString()){let o={},r={},i={},s=(d,l,v)=>{let x=d[l]??=[];x.includes(v)||x.push(v)};for(let d of t.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(x=>x.status==="current").map(x=>x.value)]){let x=ms(v);x&&s(o,x,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let a={version:1,projectId:t.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:o,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:fs(a)}}function hs(t,e){let n=[...new Set(e.flatMap(o=>t.subjectIdsByValue[ms(o)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(o=>t.decisionIdsBySubject[o]??[]))],proposalIds:[...new Set(n.flatMap(o=>t.proposalIdsBySubject[o]??[]))]}}var To=class{constructor(e){this.indexDir=us(e,".popmelt","memory","indexes"),this.indexPath=us(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Dl(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===fs(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let o=Ll(e,n);return await $l(this.indexDir,{recursive:!0}),await Jl(this.indexPath,o),o}};var Cn="popmelt:imprint",Is="popmelt:imprint-evidence",Zt="popmelt:imprint-relation";function Ro(t){return t.sourceRefs.find(e=>e.kind==="external"&&e.uri===Cn)?.id}function Er(t){let e=new Set;return t.filter(n=>{let o=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(o)?!1:(e.add(o),!0)})}function jo(t,e){if(!t)return[];let n=new Set(t.relations.flatMap(o=>o.type==="expresses"&&o.toId===e?[o.fromId]:[]));return t.concrete.filter(o=>n.has(o.id)).map(o=>({id:o.id,modelPath:o.modelPath,value:structuredClone(o.value),createdAt:o.createdAt,updatedAt:o.updatedAt}))}function _r(t){if(t==="expresses")return"expresses";if(t==="excepts")return"excepts"}var Ao=class{constructor(e){this.projectRoot=e;this.store=new ko(e),this.indexStore=new To(e),this.manifestPath=Yt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await _n(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let o=await Ot({...e,projectRoot:this.projectRoot});if(o.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(o.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Ot({...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=Yt(this.projectRoot,".popmelt","memory","migrations"),n=Yt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await _n(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let o;try{o=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!o?.explanations)return await gs(e,{recursive:!0}),await ys(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),a=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!a||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,v=new Set(r.bundle.records.map(u=>u.id)),x=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Zt?[M.id]:[]))),b=new Map,R=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of o.explanations){let M=R.find(h=>Ro(h)===u.id);b.set(u.id,M?.id??le(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let P=[],f=[],p=[],g=0;for(let u of o.explanations){let M=b.get(u.id),h=R.find(k=>k.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 k of E){let C=le(l,"imprint-evidence-record",k.id,Date.parse(k.createdAt));m.push(C),!v.has(C)&&(P.push({id:C,schemaVersion:1,projectId:l,createdAt:k.createdAt,participantId:a.id,sourceRefs:Er([{kind:"external",id:k.id,uri:Is},{kind:"external",id:u.id,uri:Cn},{kind:"thread",id:k.threadId},{kind:"message",id:k.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(k.kind)?"user_feedback":"judgment",summary:k.summary,availability:"available",artifactIds:[]}),p.push({id:le(l,"imprint-evidence-link",`${u.id}:${k.id}`,Date.parse(k.createdAt)),schemaVersion:1,projectId:l,createdAt:k.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:k.id,uri:Is}],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??a.id,sourceRefs:Er([...h?.sourceRefs??[],{kind:"external",id:u.id,uri:Cn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:jo(o,u.id),supersededById:u.supersededBy?b.get(u.supersededBy):void 0,updatedAt:u.updatedAt};h?f.push(D):P.push(D)}for(let u of o.relations){let M=_r(u.type);if(!M)continue;let h=b.get(u.fromId),m=b.get(u.toId);!h||!m||x.has(u.id)||p.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:u.id,uri:Zt}],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 w=new Date().toISOString();if(P.length||f.length||p.length)try{let u=await this.store.commit({records:P,recordReplacements:f,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:le(l,"imprint-advisories-v2",o.projectId,Date.parse(o.updatedAt)),committedAt:w});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await gs(e,{recursive:!0}),await ys(n,JSON.stringify({version:2,migratedAt:w,explanations:o.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:o.explanations.length,evidence:g}}async review(e,n={}){let o=await this.loadSource(n),r=await this.withIndexedCandidates(o,e);return{source:o.source,selection:An(o.bundle,r)}}async contextualize(e,n={}){let o=await this.loadSource(n),r=await this.withIndexedCandidates(o,e);return{source:o.source,actionPacket:is(o.bundle,r),reviewSelection:An(o.bundle,r)}}async planReview(e,n={}){let o=await this.loadSource(n);return{source:o.source,result:xo(o.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Ot({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(o=>o.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let o=await this.store.load(),r=xo(o.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),o=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!o||o.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:o?o.state!=="pending"?`The proposal is already ${o.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),a={proposalId:o.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:Se(i),decisionId:Se(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:Se(i),replacementProposalId:Se(i),acceptanceEventId:Se(i),decisionId:Se(i),relationshipId:Se(i),claim:e.claim,kind:e.kind,subjects:o.subjects,subjectSemantics:o.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:Se(i),reason:e.reason}:{...a,action:"defer",eventId:Se(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:o.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=xo(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:Se(i),committedAt:s});await this.refreshIndex(v);let x=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:x,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),o=ps(n.bundle,e),r=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(o.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:o.iterationId,proposalIds:o.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:o.iterationId,proposalIds:o.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let o=await this.store.load(),r=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),i=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="ai"&&w.status==="active"),s=e.action?r:i??r,a=o.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),v=o.bundle.manifest.projectId,x=[],b=[],R=[],P=o.bundle.records.filter(w=>w.recordType==="advisory_explanation"),f=new Map(P.flatMap(w=>{let u=Ro(w);return u?[[u,w.id]]:[]}));for(let w of e.summary.changes)if(!f.has(w.explanationId)){let u=n?.explanations.find(M=>M.id===w.explanationId);f.set(w.explanationId,le(v,"imprint-explanation",w.explanationId,Date.parse(u?.createdAt??d)))}for(let w of e.summary.changes){let u={kind:"external",id:w.explanationId,uri:Cn},M=f.get(w.explanationId),h=P.find(k=>k.id===M),m=n?.explanations.find(k=>k.id===w.explanationId),E={id:le(v,"imprint-live-evidence",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};x.push(E);let D={id:M,schemaVersion:1,projectId:v,createdAt:h?.createdAt??m?.createdAt??d,participantId:h?.participantId??s.id,sourceRefs:Er([...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??w.state,statement:m?.statement??w.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[a.id],evidenceIds:[...new Set([...h?.evidenceIds??[],E.id])],concreteBindings:m?jo(n,w.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?f.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??d};h?b.push(D):x.push(D),R.push({id:le(v,"imprint-live-evidence-link",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,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(o.bundle.relationships.flatMap(w=>w.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Zt?[u.id]:[])));for(let w of n?.relations??[]){let u=_r(w.type);if(!u)continue;let M=f.get(w.fromId),h=f.get(w.toId);!M||!h||p.has(w.id)||R.push({id:le(v,"imprint-relation",w.id,Date.parse(w.createdAt)),schemaVersion:1,projectId:v,createdAt:w.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:w.id,uri:Zt}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:h},reason:w.rationale||"The Imprint graph connected these explanations."})}let g=le(o.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let w=await this.store.commit({records:x,recordReplacements:b,events:[],relationships:R,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:d});await this.refreshIndex(w)}catch(w){if(!(w instanceof Error)||!w.message.includes("Transaction already exists"))throw w}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),o=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??o;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let a=n.bundle.manifest.projectId,d=n.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(d.flatMap(m=>{let E=Ro(m);return E?[[E,m]]:[]})),v=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(a,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),x=[],b=[],R=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=l.get(m.id);if(!E){x.push({id:v.get(m.id),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Cn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:jo(e,m.id),supersededById:m.supersededBy?v.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:jo(e,m.id),supersededById:m.supersededBy?v.get(m.supersededBy):void 0,updatedAt:m.updatedAt},k=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});k(E)!==k(D)&&b.push(D)}for(let[m,E]of l)R.has(m)||E.state==="retired"||b.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let P=new Set(n.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),f=new Map(n.bundle.relationships.flatMap(m=>{if(P.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Zt)?.id;return E?[[E,m]]:[]})),p=[],g=new Set;for(let m of e.relations){let E=_r(m.type);if(!E)continue;let D=v.get(m.fromId),k=v.get(m.toId);if(!D||!k)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===k||(C&&g.add(m.id),p.push({id:le(a,"imprint-relation",`${m.id}:${E}:${D}:${k}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Zt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:k},reason:m.rationale||"The Imprint graph connected these explanations."}))}let w=new Set(e.relations.map(m=>m.id)),u=o?[...f].filter(([m])=>!w.has(m)||g.has(m)).map(([,m])=>({id:le(a,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:o.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!x.length&&!b.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let M=e.updatedAt,h=le(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:x,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:x.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:n.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 n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let o={};for(let r of n.bundle.records)o[r.recordType]=(o[r.recordType]??0)+1;return{status:e,journal:n.report,records:o,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),o=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(a=>a.status==="projected").map(a=>a.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!o.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,a)=>a.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),o=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&o.set(r.key,r);return[...o.values()]}async getImprintView(e=[],n){let o=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return o();let r=await this.store.load(),i=r.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(i.map(p=>[p.id,p])),a=new Map(i.flatMap(p=>{let g=Ro(p);return g?[[g,p.id]]:[]})),d=new Set(e.map(p=>a.get(p)??p)),l=new Map(r.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),v=new Map(r.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),x=new Set(r.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),b=new Set(["expresses","operationalizes","excepts"]),R={testing:0,emerging:1,grounded:2,challenged:3,retired:4},P=i.map(p=>{let g=p.evidenceIds.flatMap(h=>{let m=v.get(h);if(!m)return[];let E=m.sourceRefs.find(z=>z.kind==="thread")?.id,D=m.sourceRefs.find(z=>z.kind==="message")?.id,k=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:k,summary:m.summary,createdAt:m.createdAt,participantKind:C,threadId:E,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),w=r.bundle.relationships.flatMap(h=>{if(x.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,k=s.get(D);return k?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:k.id,statement:k.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."}]:[]}),...i.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=>!n||n.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:[...w,...u],sourceThreadIds:M,needsGrounding:p.state==="testing"&&d.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:P.filter(p=>p.state!=="retired").length,emerging:P.filter(p=>p.state==="emerging").length,testing:P.filter(p=>p.state==="testing").length,grounded:P.filter(p=>p.state==="grounded").length,challenged:P.filter(p=>p.state==="challenged").length,retired:P.filter(p=>p.state==="retired").length,needsGrounding:P.filter(p=>p.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:f,explanations:P}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(a=>a.recordType==="decision"&&a.state==="active"?[a.id]:[])),o=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))a.decisionIds.some(d=>n.has(d))&&o.set(a.key,a);let r=[...o.values()],i=e.records.filter(a=>a.recordType==="verification_attempt");return{decisions:e.records.filter(a=>a.recordType==="decision"&&a.state==="active").map(a=>{let d=i.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===a.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(l=>l.decisionIds.includes(a.id)),verification:d?d.state:"unverified"}}),entries:r.map(a=>({id:a.id,key:a.key,value:a.value,decisionIds:a.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),o=n.bundle.records.find(k=>k.recordType==="participant"&&k.kind==="human"&&k.status==="active"),r=n.bundle.records.find(k=>k.recordType==="subject"&&k.subjectType==="project");if(!o||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=Se(i),d=Se(i),l=Se(i),v=Se(i),x=Se(i),b=new Set(n.bundle.records.flatMap(k=>k.recordType==="model_entry"&&k.key===e.key?k.decisionIds:[])),R=n.bundle.records.filter(k=>k.recordType==="decision"&&k.state==="active"&&b.has(k.id)),P={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:r.id,role:"governed"}],p={...P,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:o.id}},g={...P,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:a},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},w={...P,id:l,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:o.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},u={...P,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},M={...P,id:x,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:o.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},h={...P,id:Se(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},m=R.map(k=>({...P,id:Se(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:k.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=R.map(k=>({...P,id:Se(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:w.id},to:{entityType:"decision",entityId:k.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[p,w,u,M],events:[g,...m],relationships:[h,...E],artifacts:[],tombstones:[],projectionUpdates:R.map(k=>({entityType:"decision",entityId:k.id,fromState:"active",state:"superseded"}))},{transactionId:Se(i),committedAt:s});return await this.refreshIndex(D),{decisionId:l,entryId:v}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),o=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return o?{proposalId:o.id,claim:o.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),o=new Map(n.records.flatMap(r=>r.recordType==="subject"?[[r.id,r.label]]:[]));return n.records.filter(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.kind==="thread"&&i.id===e)).sort((r,i)=>r.createdAt.localeCompare(i.createdAt)).map(r=>({proposalId:r.id,claim:r.claim,rationale:r.rationale,proposedKind:r.proposedKind,subjectLabels:r.subjects.flatMap(i=>{let s=o.get(i.subjectId);return s?[s]:[]})}))}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),o=n.bundle.records.find(P=>P.recordType==="model_projection"&&P.state==="applied"&&P.runId===e.runId);if(o)return{projectionId:o.id,entryIds:o.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(P=>P.recordType==="decision"&&e.decisionIds.includes(P.id)&&P.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=Se(s),l=e.changes.map(P=>{let f=P.decisionIds?.filter(w=>e.decisionIds.includes(w)),p=f?.length?f:e.decisionIds,g=[...new Set(r.filter(w=>p.includes(w.id)).flatMap(w=>w.subjects.map(u=>u.subjectId)))];return{id:Se(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:p.map(w=>({kind:"record",id:w})),recordType:"model_entry",key:P.path.map(String).join("."),subjectIds:g,decisionIds:p,value:P.value}}),v=new Set(l.flatMap(P=>P.decisionIds)),x={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(P=>({kind:"record",id:P})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:a,decisionIds:e.decisionIds,entryIds:l.map(P=>P.id),coverage:e.decisionIds.map(P=>e.coverage?.find(f=>f.decisionId===P)??{decisionId:P,status:v.has(P)?"projected":"unprojected"})},b=l.flatMap(P=>P.decisionIds.map(f=>({id:Se(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:x.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:P.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,x],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Se(s),committedAt:a});return await this.refreshIndex(R),{projectionId:d,entryIds:l.map(P=>P.id),headSequence:R.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Ot({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let o=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=hs(o,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}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 tn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object.");return t}function Te(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} must be a non-empty string.`);return t}function en(t,e,n){let o=Te(t,e);if(!n.includes(o))throw new Error(`${e} is invalid.`);return o}function Cr(t){let e=tn(t),n=tn(e.authority),o=n.level,r=n.mode,i=en(o,"authority.level",["owner","delegate","contributor"]),s=en(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Te(e.proposalId,"proposalId"),participantId:Te(e.participantId,"participantId"),occurredAt:Te(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...a,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:en(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Te(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Te(e.eventId,"eventId"),reason:Te(e.reason,"reason")};case"defer":{let d=tn(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...a,action:"defer",eventId:Te(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Te(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>en(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...a,action:"edit_and_accept",withdrawalEventId:Te(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Te(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Te(e.acceptanceEventId,"acceptanceEventId"),decisionId:Te(e.decisionId,"decisionId"),relationshipId:Te(e.relationshipId,"relationshipId"),claim:Te(e.claim,"claim"),kind:en(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=tn(d);return{subjectId:Te(l.subjectId,"subjectId"),role:en(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:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function $r(t){let e=tn(t),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Te(a,s))}},o=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:tn(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:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:o(e.maxPackets,"maxPackets"),maxEstimatedTokens:o(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function ws(t){let e=t.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let o=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((o==="accept"||o==="edit_and_accept")&&!r||o==="edit_and_accept"&&typeof n.claim!="string"||o!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(a=>typeof a=="string"&&i.has(a)):void 0;return{proposalId:n.proposalId,action:o,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function vs(t){let e=t.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),o=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!o||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:o,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function Or(t){let n=(t.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let o=n[1]||n[2],r=await ql(t),i=Buffer.from(`--${o}`),s=Buffer.from(`--${o}--`),a,d,l,v,x,b,R,P,f,p,g,w,u,M,h=[],m=[],E=0,D=[];for(;E<r.length;){let k=r.indexOf(i,E);if(k===-1)break;let C=k+i.length;if(r.slice(k,k+s.length).equals(s))break;let z=C;r[z]===13&&r[z+1]===10&&(z+=2);let X=r.indexOf(`\r
|
|
168
|
+
`;function vo(t){try{let e=new URL(t);return e.hash="",e.href}catch{return null}}function Qc(t,e){let n=vo(e);if(!n)return null;let o=new URL(n),r=t.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&vo(s.url)),i=r.find(s=>vo(s.url)===n);return i||(r.find(s=>{let a=new URL(vo(s.url));return a.origin===o.origin&&a.pathname===o.pathname})??null)}function Xc(t){let e={x:Number(t.x),y:Number(t.y),width:Number(t.width),height:Number(t.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 Yc(t){let e=new AbortController,n=setTimeout(()=>e.abort(),1e3);try{let o=new URL("/json/list",t).href,r=await fetch(o,{signal:e.signal});if(!r.ok)throw new Error(`CDP discovery returned ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}finally{clearTimeout(n)}}async function Zc(t){let{WebSocket:e}=await import("ws");return new Promise((n,o)=>{let r=new e(t,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),n(r)},s=a=>{r.off("open",i),o(a)};r.once("open",i),r.once("error",s)})}function el(t){let e=1,n=new Map;return t.on("message",o=>{let r;try{r=JSON.parse(String(o))}catch{return}if(!r.id)return;let i=n.get(r.id);i&&(n.delete(r.id),clearTimeout(i.timeout),r.error?i.reject(new Error(r.error.message||`CDP error ${r.error.code??""}`.trim())):i.resolve(r.result??{}))}),t.on("close",()=>{for(let[o,r]of n)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),n.delete(o)}),(o,r={})=>new Promise((i,s)=>{let a=e++,d=setTimeout(()=>{n.delete(a),s(new Error(`CDP ${o} timed out`))},4e3);n.set(a,{resolve:i,reject:s,timeout:d}),t.send(JSON.stringify({id:a,method:o,params:r}),l=>{l&&(clearTimeout(d),n.delete(a),s(l))})})}async function os(t,e){let n=Xc(e.clip),o=await Yc(t),r=Qc(o,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Zc(r.webSocketDebuggerUrl),s=el(i),a=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Vc,returnByValue:!0}),a=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...n,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{a&&await s("Runtime.evaluate",{expression:Kc,returnByValue:!0}).catch(()=>{}),i.close()}}import{mkdir as ys,readFile as _n,writeFile as Is}from"fs/promises";import{join as Yt}from"path";var tl=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function kr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function bo(t){return new Set(kr(t).split(" ").filter(e=>e.length>2&&!tl.has(e)))}function rs(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function nl(t){return[{value:t.label,by:"label"},...t.aliases.map(e=>({value:e,by:"alias"})),...t.locators.map(e=>({value:e.value,by:"locator"}))]}function ol(t,e){let n=new Map,o=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(kr).filter(Boolean),i=bo([e.action,e.text].filter(Boolean).join(" "));for(let s of t){if(o.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a;for(let d of nl(s)){let l=kr(d.value);for(let b of r){let R=l===b?95:l.includes(b)||b.includes(l)?75:0;R>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:R>=90?"exact":"strong",matchedBy:d.by,score:R})}let T=["/","#","[","]","="].some(b=>d.value.includes(b))?0:Math.round(rs(bo(l),i)*55);T>=30&&T>(a?.score??0)&&(a={subjectId:s.id,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}a&&n.set(s.id,a)}return n}function rl(t,e){let n=new Set(t.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),o=new Set(t.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(a=>n.has(a))||s.sourceRefs.some(a=>a.kind==="thread"&&o.has(a.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function il(t){return Math.ceil(JSON.stringify(t).length/4)}function An(t,e){let n=t.records.filter(p=>p.recordType==="subject"),o=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=t.records.filter(p=>{if(p.recordType!=="proposal"||r&&!r.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let g=[...t.events].reverse().find(w=>w.entity.entityType==="proposal"&&w.entity.entityId===p.id&&w.toState==="deferred"&&w.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(o)>=Date.parse(g.revisitAfter)):!1}),s=t.records.filter(p=>p.recordType==="implementation_attempt"),a=ol(n,e),d=[...a.values()].sort((p,g)=>g.score-p.score),l=bo([e.action,e.text].filter(Boolean).join(" ")),v=i.flatMap(p=>{let g=p.subjects.map(h=>a.get(h.subjectId)).filter(h=>!!h),w=Math.max(0,...g.map(h=>h.score)),u=Math.round(rs(bo(p.claim),l)*35),M=w+u;return M>=50?[{proposal:p,proposalMatches:g,score:M}]:[]}).sort((p,g)=>g.score-p.score||p.proposal.id.localeCompare(g.proposal.id)),T=Math.max(1,e.maxPackets??3),b=Math.max(200,e.maxEstimatedTokens??1200),R=[],S=0;for(let p of v){if(R.length>=T)break;let g=p.proposal.sourceRefs.slice(0,4),w={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:t.manifest.projectId,generatedAt:o,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:rl(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={...w,estimatedTokens:il(w)};if(S+u.estimatedTokens>b)break;R.push(u),S+=u.estimatedTokens}let f=Math.max(0,v.length-R.length);return{packets:R,subjectMatches:d.map(({score:p,...g})=>g),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:v.length,omittedPacketCount:f,maxEstimatedTokens:b,estimatedTokens:S},uncertainty:a.size===0?"subject_unresolved":v.length===0?"no_relevant_pending_proposal":void 0}}var sl=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Tr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function xo(t){return new Set(Tr(t).split(" ").filter(e=>e.length>2&&!sl.has(e)))}function is(t,e){if(!t.size||!e.size)return 0;let n=0;for(let o of t)e.has(o)&&(n+=1);return n/Math.min(t.size,e.size)}function al(t,e){let n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(Tr).filter(Boolean),r=xo([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of t){if(n.has(s.id)){i.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let a,d=[{value:s.label,by:"semantic"},...s.aliases.map(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let v=Tr(l.value);for(let R of o){let S=v===R?95:v.includes(R)||R.includes(v)?75:0;S>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:S>=90?"exact":"strong",matchedBy:l.by,score:S})}let b=["/","#","[","]","="].some(R=>l.value.includes(R))?0:Math.round(is(xo(v),r)*55);b>=30&&b>(a?.score??0)&&(a={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:b>=45?"strong":"weak",matchedBy:"semantic",score:b})}a&&i.push(a)}return i.sort((s,a)=>a.score-s.score||s.subjectId.localeCompare(a.subjectId))}function dl(t){return Math.ceil(JSON.stringify(t).length/4)}function Kt(t,e){return t.relationshipType===e&&t.from.entityType==="decision"&&t.to.entityType==="decision"}function cl(t,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let o=n.filter(i=>i.state==="completed"),r=o.some(i=>i.coverageClaims.some(s=>s.decisionId===t&&s.coverage==="full"));return{decisionId:t,state:r?"implemented":o.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function ll(t,e,n){let o=e.filter(a=>a.targets.some(d=>d.entityType==="decision"&&d.entityId===t)).sort((a,d)=>d.createdAt.localeCompare(a.createdAt)),r=n.some(a=>a.signalType==="verification_expired"&&a.target.entityType==="decision"&&a.target.entityId===t),i=o[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:s,attemptIds:o.map(a=>a.id)}}function ss(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),o=Math.max(1,e.maxDecisions??6),r=t.records.filter(m=>m.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=t.records.filter(m=>m.recordType==="decision"&&m.state==="active"),a=i?s.filter(m=>i.has(m.id)):s,d=t.records.filter(m=>m.recordType==="implementation_attempt"),l=t.records.filter(m=>m.recordType==="verification_attempt"),v=t.records.filter(m=>m.recordType==="freshness_signal"&&m.state==="open"),T=t.records.filter(m=>m.recordType==="evidence"),b=t.records.filter(m=>m.recordType==="model_entry"),R=al(r,e),S=new Map(R.map(m=>[m.subjectId,m.score])),f=xo([e.action,e.text].filter(Boolean).join(" ")),p=a.flatMap(m=>{let E=Math.max(0,...m.subjects.map(C=>S.get(C.subjectId)??0)),D=Math.round(is(xo(m.claim),f)*35),P=E+D;return P>=50?[{decision:m,score:P}]:[]}).sort((m,E)=>E.score-m.score||m.decision.id.localeCompare(E.decision.id)),g=new Map;for(let m of p.slice(0,o))g.set(m.decision.id,m.decision);for(let m of t.relationships){if(!Kt(m,"excepts")&&!Kt(m,"contradicts"))continue;let E=s.find(P=>P.id===m.from.entityId),D=s.find(P=>P.id===m.to.entityId);!E||!D||!g.has(E.id)&&!g.has(D.id)||(g.size<o&&g.set(E.id,E),g.size<o&&g.set(D.id,D))}let w=[...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)),P=v.filter(B=>B.target.entityType==="decision"&&D.has(B.target.entityId)),C=new Set(t.relationships.filter(B=>Kt(B,"excepts")&&D.has(B.from.entityId)&&D.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),X=t.relationships.filter(B=>Kt(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=T.filter(B=>B.sourceRefs.some(V=>V.kind==="record"&&D.has(V.id))||t.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=t.relationships.some(B=>Kt(B,"contradicts")&&u(B)&&(!D.has(B.from.entityId)||!D.has(B.to.entityId))),L=E||x>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(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:t.manifest.projectId}]});let W={contractVersion:1,projectId:t.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:R.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:P.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=>cl(B.id,d)),verification:m.map(B=>ll(B.id,l,P)),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 W.budget.estimatedTokens=dl(W),W},h=M(w);for(;h.budget.estimatedTokens>n&&w.length>0;){let m=w.pop(),E=t.relationships.filter(D=>Kt(D,"contradicts")&&(D.from.entityId===m.id||D.to.entityId===m.id)).flatMap(D=>[D.from.entityId,D.to.entityId]);w=w.filter(D=>!E.includes(D.id)),h=M(w,!0)}return h}var pl=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Qt(t){return pl.test(t)}function ul(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function oe(t,e,n,o){t.push({path:e,code:n,message:o,severity:"error"})}function Rr(t,e,n,o){t.push({path:e,code:n,message:o,severity:"warning"})}function Ee(t,e,n){Qt(n)||oe(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Xe(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&oe(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function Ct(t,e,n,o=!1){o&&n.level==="contributor"&&oe(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&oe(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ml={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"])},fl=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function hl(t,e,n){Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Ee(t,`${n}.entity.entityId`,e.entity.entityId),Xe(t,`${n}.createdAt`,e.createdAt),Ct(t,`${n}.authority`,e.authority);let o=ml[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;o&&!o.has(r)&&oe(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(fl.has(i)&&(Ct(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||oe(t,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&oe(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&oe(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Xe(t,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function gl(t,e,n,o){Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Xe(t,`${n}.createdAt`,e.createdAt),e.projectId!==o&&oe(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&oe(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&oe(t,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&oe(t,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(Ct(t,`${n}.authority`,e.authority,!0),e.claim.trim()||oe(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Rr(t,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&oe(t,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Xe(t,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&oe(t,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&oe(t,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&oe(t,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Xe(t,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),Xe(t,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&oe(t,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Xe(t,`${n}.appliedAt`,e.appliedAt),Ct(t,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&oe(t,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&oe(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&oe(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Rr(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Rr(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function yl(t,e,n){if(Ee(t,`${n}.id`,e.id),Ee(t,`${n}.projectId`,e.projectId),Ee(t,`${n}.participantId`,e.participantId),Ee(t,`${n}.from.entityId`,e.from.entityId),Ee(t,`${n}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&oe(t,`${n}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&oe(t,`${n}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),Xe(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||oe(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&oe(t,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?oe(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&Ct(t,`${n}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&oe(t,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&oe(t,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&oe(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&oe(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function $t(t){let e=[];Ee(e,"manifest.projectId",t.manifest.projectId),Xe(e,"manifest.createdAt",t.manifest.createdAt),Xe(e,"manifest.updatedAt",t.manifest.updatedAt);let n=new Map,o=(f,p)=>{let g=n.get(f);g?oe(e,p,"duplicate_id",`ID is already used at ${g}.`):n.set(f,p)};t.records.forEach((f,p)=>{let g=`records[${p}]`;o(f.id,g),gl(e,f,g,t.manifest.projectId)}),t.events.forEach((f,p)=>{let g=`events[${p}]`;o(f.id,g),hl(e,f,g),f.projectId!==t.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((f,p)=>{let g=`relationships[${p}]`;o(f.id,g),yl(e,f,g),f.projectId!==t.manifest.projectId&&oe(e,`${g}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((f,p)=>{o(f.id,`artifacts[${p}]`),Ee(e,`artifacts[${p}].id`,f.id)}),t.tombstones.forEach((f,p)=>{let g=`tombstones[${p}]`;o(f.id,g),Ee(e,`${g}.id`,f.id),Ee(e,`${g}.objectId`,f.objectId),Ee(e,`${g}.deletedById`,f.deletedById),Xe(e,`${g}.deletedAt`,f.deletedAt),Ct(e,`${g}.authority`,f.authority,!0)});let r=new Set(t.records.map(f=>`${f.recordType}:${f.id}`)),i=new Set(t.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,p)=>{if(f.storeId)return;let g=`${f.entityType}:${f.entityId}`;!r.has(g)&&!i.has(g)&&oe(e,p,"dangling_entity_reference",`No record or tombstone exists for ${g}.`)};t.events.forEach((f,p)=>s(f.entity,`events[${p}].entity`)),t.relationships.forEach((f,p)=>{s(f.from,`relationships[${p}].from`),s(f.to,`relationships[${p}].to`)});let a=new Set(t.artifacts.map(f=>f.id)),d=(f,p)=>{a.has(f)||oe(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(f,p,g)=>{!r.has(`${f}:${p}`)&&!i.has(`${f}:${p}`)&&oe(e,g,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};t.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((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`));break;case"observation":f.captureContext.subjectIds.forEach((w,u)=>l("subject",w,`${g}.captureContext.subjectIds[${u}]`)),f.captureContext.artifactIds.forEach((w,u)=>d(w,`${g}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":f.subjects.forEach((w,u)=>l("subject",w.subjectId,`${g}.subjects[${u}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((w,u)=>d(w,`${g}.messageArtifactIds[${u}]`)),f.resultRefs.forEach((w,u)=>s(w,`${g}.resultRefs[${u}]`));break;case"iteration":f.threadIds.forEach((w,u)=>l("thread",w,`${g}.threadIds[${u}]`)),f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"evidence":f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"advisory_explanation":f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`)),f.supersededById&&l("advisory_explanation",f.supersededById,`${g}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((w,u)=>l("iteration",w,`${g}.iterationIds[${u}]`)),f.coverageClaims.forEach((w,u)=>l("decision",w.decisionId,`${g}.coverageClaims[${u}].decisionId`)),f.artifactIds.forEach((w,u)=>d(w,`${g}.artifactIds[${u}]`));break;case"eval_spec":f.replacesSpecId&&l("eval_spec",f.replacesSpecId,`${g}.replacesSpecId`),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`)),f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),(f.dependencies??[]).forEach((w,u)=>{w.kind==="subject"&&w.subjectId&&l("subject",w.subjectId,`${g}.dependencies[${u}].subjectId`)}),(f.scenarios??[]).forEach((w,u)=>{w.subjectIds?.forEach((M,h)=>l("subject",M,`${g}.scenarios[${u}].subjectIds[${h}]`))}),f.targets.forEach((w,u)=>l(w.entityType,w.entityId,`${g}.targets[${u}]`));break;case"verification_attempt":f.evalSpecId&&l("eval_spec",f.evalSpecId,`${g}.evalSpecId`),f.targets.forEach((w,u)=>l(w.entityType,w.entityId,`${g}.targets[${u}]`)),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`));break;case"model_entry":f.subjectIds.forEach((w,u)=>l("subject",w,`${g}.subjectIds[${u}]`)),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`));break;case"model_projection":Ct(e,`${g}.authority`,f.authority,!0),l("participant",f.appliedById,`${g}.appliedById`),f.decisionIds.forEach((w,u)=>l("decision",w,`${g}.decisionIds[${u}]`)),f.entryIds.forEach((w,u)=>l("model_entry",w,`${g}.entryIds[${u}]`)),f.coverage.forEach((w,u)=>l("decision",w.decisionId,`${g}.coverage[${u}].decisionId`));break;case"freshness_signal":s(f.target,`${g}.target`),f.evidenceIds.forEach((w,u)=>l("evidence",w,`${g}.evidenceIds[${u}]`));break;default:break}});let v=new Map(t.events.map(f=>[f.id,f])),T=new Map(t.records.map(f=>[`${f.recordType}:${f.id}`,f])),b=new Map;t.events.forEach((f,p)=>{let g=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,w=b.get(g)??new Set;w.add(f.toState),b.set(g,w),w.size>1&&oe(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let R=new Map(t.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),S=(f,p,g,w,u)=>{if(f.level!=="delegate"||!f.grantId)return;let M=R.get(f.grantId);if(!M){oe(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(M.granteeId!==p||M.level!=="delegate")&&oe(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let h=Date.parse(g);(h<Date.parse(M.startsAt)||M.endsAt&&h>Date.parse(M.endsAt)||M.revokedAt&&h>=Date.parse(M.revokedAt))&&oe(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),M.subjectIds.length&&w.length&&!w.every(m=>M.subjectIds.includes(m))&&oe(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of t.records)f.recordType==="decision"&&S(f.authority,f.acceptedById,f.createdAt,f.subjects.map(p=>p.subjectId),`records:${f.id}.authority`);t.events.forEach((f,p)=>{let g=T.get(`${f.entity.entityType}:${f.entity.entityId}`),w=g&&"subjects"in g?g.subjects.map(u=>u.subjectId):[];S(f.authority,f.participantId,f.createdAt,w,`events[${p}].authority`)}),t.relationships.forEach((f,p)=>{if(!f.authority)return;let g=[f.from,f.to].flatMap(w=>{let u=T.get(`${w.entityType}:${w.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 t.records){if(f.recordType!=="decision")continue;let p=v.get(f.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==f.proposalId||p.toState!=="accepted")&&oe(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==f.acceptedById&&oe(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${f.proposalId}`)||oe(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(t.relationships.some(w=>w.relationshipType==="supersedes"&&w.to.entityType==="decision"&&w.to.entityId===f.id)||oe(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(t.events.some(w=>w.entity.entityType==="decision"&&w.entity.entityId===f.id&&w.toState==="revoked"&&!!w.reason?.trim())||oe(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of t.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;t.records.some(g=>g.recordType==="decision"&&g.proposalId===f.id)||oe(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ul(e)}function Mn(t,e,n,o){return{id:o,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function as(t,e,n,o,r){return{id:r,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:o,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Il(t){switch(t.action){case"accept":return[t.eventId,t.decisionId];case"edit_and_accept":return[t.withdrawalEventId,t.replacementProposalId,t.acceptanceEventId,t.decisionId,t.relationshipId];case"reject":case"defer":return[t.eventId]}}function So(t,e){let n=[],o=t.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);o?o.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${o.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Qt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of Il(e))Qt(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!o)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=as(t,o,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Mn(t,o,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},a={...Mn(t,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=as(t,i,e,a.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:o.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:o.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[i,d],events:[s,a],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}let r={...Mn(t,o,e,e.eventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:o.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:o.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:o.id}]}}}import{createHash as wl}from"crypto";import{readFile as vl,readdir as bl,realpath as xl}from"fs/promises";import{join as En,relative as Sl}from"path";var Pl=["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 Xt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function He(t,e=0){return new Date(Number.isFinite(t)?t:e).toISOString()}function ds(...t){return t.find(e=>!!e?.trim())?.trim()}function le(t,e,n,o){let i=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),s=wl("sha256").update(`${t}\0${e}\0${n}`).digest("hex"),a=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${a}${s.slice(4,7)}-${s.slice(7,19)}`}async function jr(t,e){try{return JSON.parse(await vl(t,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:t,message:n instanceof Error?n.message:String(n)}),null}}function kl(t){let e=Xt(t);if(!e)return 0;let n=0,o=r=>{let i=Xt(r);if(!i){n+=1;return}for(let s of Object.values(i))o(s)};for(let r of Object.values(e))o(r);return n}function Tl(t){let e={};for(let n of t)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Ot(t){let e=[],n=await xl(t.projectRoot).catch(()=>t.projectRoot),o=En(n,".popmelt"),r=await jr(En(o,"threads.json"),e),i=await jr(En(o,"model.json"),e),s=Xt(r),a=Xt(s?.threads)??{},d=Object.entries(a).map(([V,H])=>({key:V,value:Xt(H)})).filter(V=>!!V.value),l=En(o,"decisions"),v=await bl(l).catch(()=>[]),T=[];for(let V of v.filter(H=>H.endsWith(".json")).sort()){let H=Xt(await jr(En(l,V),e));H&&T.push({file:V,value:H})}let b=d.flatMap(({value:V})=>[V.createdAt,V.updatedAt]).filter(V=>typeof V=="number"&&Number.isFinite(V)),R=b.length?Math.min(...b):0,S=t.projectKey??n;t.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,R),p=le(S,"participant","legacy-owner",R),g=le(S,"participant","legacy-agent",R),w=le(S,"subject","project",R),u=He(Math.max(R,...b)),M=[],h=[],m=new Map,E=new Map,D=new Map(T.map(V=>[V.value.id??V.file.replace(/^d-|\.json$/g,""),V.value])),P=new Map,C=(V,H,ee,Re,Le)=>{let ue=m.get(ee);if(ue)return ue;let $e=le(S,"artifact",V,Re);return h.push({id:$e,kind:H,mediaType:Le,location:ee,availability:"available"}),m.set(ee,$e),$e};for(let{file:V,value:H}of T){let ee=H.id??V.replace(/^d-|\.json$/g,""),Re=H.createdAt??R,Le=[C(`${ee}:envelope`,"other",`.popmelt/decisions/${V}`,Re,"application/json")];H.screenshotPath&&Le.push(C(`${ee}:screenshot`,"screenshot",`.popmelt/${H.screenshotPath.replace(/^\.popmelt\//,"")}`,Re,H.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ue,$e]of(H.pastedImagePaths??[]).entries())Le.push(C(`${ee}:image:${ue}`,"image",$e,Re));P.set(ee,Le)}let z=(V,H,ee)=>({id:V,schemaVersion:1,projectId:f,createdAt:u,participantId:H,sourceRefs:ee}),X=(V,H)=>{M.push(H);let ee=E.get(V)??[];ee.push(H.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(w,p,[]),recordType:"subject",subjectType:"project",label:Sl(process.cwd(),n)||n,aliases:[],locators:[{id:le(S,"locator",n,R),kind:"project_root",value:n,status:"current",validFrom:He(R),sourceRefs:[]}]});let Y=new Map,x=(V,H)=>{let ee=Y.get(V);if(ee)return ee;let Re=le(S,"subject",V,H),Le={...z(Re,p,[{kind:"external",id:V}]),createdAt:He(H),recordType:"subject",subjectType:"element",label:V,aliases:[],locators:[{id:le(S,"locator",V,H),kind:"dom_selector",value:V,status:"current",validFrom:He(H),sourceRefs:[{kind:"external",id:V}]}]};return M.push(Le),Y.set(V,Re),Re};for(let{key:V,value:H}of d){let ee=H.id??V,Re=H.createdAt??R,Le=le(S,"thread",ee,Re),ue={kind:"thread",id:ee},$e=[],St=[],fn=Array.isArray(H.messages)?H.messages:[],je,it,Pt=0;fn.forEach((xe,mt)=>{let Oe=xe.timestamp??Re,st=le(S,"artifact",`${ee}:message:${mt}`,Oe);if($e.push(st),h.push({id:st,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ee}/messages/${mt}`,availability:"available"}),m.set(`.popmelt/threads.json#/threads/${ee}/messages/${mt}`,st),xe.screenshotPath&&C(`${ee}:message:${mt}:screenshot`,"screenshot",xe.screenshotPath,Oe),xe.role==="human"){je=xe;let qe=xe.feedbackSummary??xe.replyToQuestion;if(qe?.trim()){let Fe=le(S,"observation",`${ee}:${mt}`,Oe),Ze=H.elementIdentifiers??[],Jt={...z(Fe,p,[ue,{kind:"message",id:st}]),createdAt:He(Oe),recordType:"observation",state:"open",statement:qe,captureContext:{subjectIds:Ze.map(Rt=>x(Rt,Re)),artifactIds:[st]},resolvedByIds:[]};X(ee,Jt),it=Fe,St.push({entityType:"observation",entityId:Fe})}return}if(xe.role!=="assistant")return;let ft=xe.jobId??`${ee}:${mt}`,ht=le(S,"iteration",ft,Oe),Tt=D.get(ft),Qo=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",Xo={...z(ht,g,[ue,{kind:"message",id:st},...(P.get(ft)??[]).map(qe=>({kind:"artifact",id:qe}))]),createdAt:He(Oe),recordType:"iteration",threadIds:[Le],startedAt:He(je?.timestamp,Oe),completedAt:He(Oe),requestSummary:ds(je?.feedbackSummary,je?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:Qo,execution:{provider:xe.provider??Tt?.provider,model:xe.model??Tt?.model,sessionId:xe.sessionId??Tt?.sessionId},artifactIds:[st,...P.get(ft)??[]]};X(ee,Xo),St.push({entityType:"iteration",entityId:ht});let hn=xe.resolutions??Tt?.resolutions??[];for(let[qe,Fe]of hn.entries()){if(Fe.status!=="resolved"||!Fe.summary?.trim())continue;let Ze=H.elementIdentifiers??[],Jt=(Ze.length?Ze:[n]).map(Qn=>({subjectId:Qn===n?w:x(Qn,Re),role:"governed"})),Rt=le(S,"proposal",`${ft}:${Fe.annotationId??"resolution"}:${qe}`,Oe),Yo={...z(Rt,g,[ue,{kind:"iteration",id:ht}]),createdAt:He(Oe),recordType:"proposal",state:"pending",claim:Fe.summary,subjects:Jt,subjectSemantics:Jt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:ds(je?.feedbackSummary,je?.replyToQuestion,Fe.summary),iterationId:ht,inferredById:g}};X(ee,Yo),St.push({entityType:"proposal",entityId:Rt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ee,message:`Proposal ${Rt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(hn.some(qe=>qe.status==="resolved")||Tt?.gitDiff){let qe=le(S,"implementation",ft,Oe),Fe={...z(qe,g,[ue,{kind:"iteration",id:ht}]),createdAt:He(Oe),recordType:"implementation_attempt",state:"completed",iterationIds:[ht],coverageClaims:[],summary:hn.map(Ze=>Ze.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};X(ee,Fe),St.push({entityType:"implementation_attempt",entityId:qe}),Pt+=1}it&&(it=void 0)});let kt=fn.at(-1),Kn={...z(Le,p,[ue]),createdAt:He(Re),recordType:"thread",state:kt?.question?"open":"resolved",messageArtifactIds:$e,outcome:kt?.question?"question_unresolved":Pt?"implementation_only":"no_outcome",resultRefs:St};M.push(Kn),E.set(ee,[Le,...E.get(ee)??[]])}let Q=kl(i);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:He(R),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:t.writerVersion??"0.8.4-dev"}},records:M,events:[],relationships:[],artifacts:h,tombstones:[]},K=$t(L),B=(t.proofCaseIds??Pl).map(V=>({legacyId:V,threadFound:d.some(({key:H,value:ee})=>(ee.id??H)===V),decisionEnvelopeFound:D.has(V),recordIds:E.get(V)??[]}));return{bundle:L,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((V,H)=>V+(H.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:Q,artifactsReferenced:h.length},imported:Tl(M),unresolvedAcceptance:e.filter(V=>V.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:B,issues:e,schemaIssues:K.issues}}}import{createHash as Rl}from"crypto";import{mkdir as cs,open as Ar,readFile as Mr,readdir as jl,rename as Al,unlink as Er}from"fs/promises";import{join as ct}from"path";var Ml={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function ko(t){return Rl("sha256").update(JSON.stringify(t)).digest("hex")}function ls(t){return ko(t)}function ps(t,e,n){[...e.records,...e.recordReplacements??[]].some(o=>o.recordType==="advisory_explanation")&&!t.manifest.features.includes("advisory_explanations")&&t.manifest.features.push("advisory_explanations");for(let o of e.recordReplacements??[]){if(o.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${o.recordType}.`);let r=t.records.findIndex(s=>s.recordType===o.recordType&&s.id===o.id);if(r<0)throw new Error(`Record replacement target not found: ${o.recordType} ${o.id}`);let i=t.records[r];if(i.projectId!==o.projectId||i.createdAt!==o.createdAt||i.participantId!==o.participantId)throw new Error(`Record replacement changed immutable identity for ${o.id}.`);t.records[r]=structuredClone(o)}for(let o of e.projectionUpdates){let r=t.records.find(i=>i.recordType===o.entityType&&i.id===o.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${o.entityType} ${o.entityId}`);if(r.state!==o.fromState)throw new Error(`Projection state conflict for ${o.entityType} ${o.entityId}: expected ${o.fromState}, found ${r.state}`);r.state=o.state}return t.records.push(...e.records),t.events.push(...e.events),t.relationships.push(...e.relationships),t.artifacts.push(...e.artifacts),t.tombstones.push(...e.tombstones),t.manifest.updatedAt=n,t}function El(t,e,n){return ps(structuredClone(t),e,n)}async function Dt(t,e){let n=`${t}.${process.pid}.${Date.now()}.tmp`,o=await Ar(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
169
|
+
`,"utf8"),await o.sync()}finally{await o.close()}try{await Al(n,t)}catch(r){throw await Er(n).catch(()=>{}),r}}async function Po(t){return JSON.parse(await Mr(t,"utf8"))}var To=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=ct(e,".popmelt","memory"),this.journalDir=ct(this.memoryDir,"journal"),this.manifestPath=ct(this.memoryDir,"manifest.json"),this.checkpointPath=ct(this.memoryDir,"checkpoint.json"),this.lockPath=ct(this.memoryDir,"writer.lock")}async initialize(e){let n=$t(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await cs(this.journalDir,{recursive:!0});try{throw await Mr(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(o){if(o instanceof Error&&o.message==="Memory journal is already initialized."||o.code!=="ENOENT")throw o}await this.withWriterLock(async()=>{try{throw await Mr(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let o=ko(e),r={storageVersion:1,sequence:0,hash:o,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:o},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await Dt(this.checkpointPath,r),await Dt(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await Dt(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 n=ko(e.bundle),o=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await Dt(ct(this.memoryDir,o),r),e.manifest.checkpoint={file:o,sequence:r.sequence,hash:n},await Dt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Qt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let o=await this.loadInternal();if(o.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=o.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:o.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:o.report.headHash,mutation:e},s={...i,hash:ls(i)},a=El(o.bundle,e,n.committedAt),d=$t(a);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await Dt(ct(this.journalDir,l),s),o.manifest.head={sequence:r,hash:s.hash},o.manifest.updatedAt=n.committedAt,await Dt(this.manifestPath,o.manifest),{bundle:a,report:{checkpointSequence:o.report.checkpointSequence,appliedTransactions:o.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:o.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...Ml,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Po(this.manifestPath),n=await Po(ct(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==ko(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let o=await jl(this.journalDir),r=o.filter(b=>b.endsWith(".tmp")),s=o.filter(b=>/^\d{12}-[0-9a-f-]+\.json$/i.test(b)).sort().filter(b=>Number(b.slice(0,12))>n.sequence),a=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,v=new Set;for(let b of s){let R=await Po(ct(this.journalDir,b)),{hash:S,...f}=R;if(S!==ls(f))throw new Error(`Journal hash mismatch: ${b}`);if(R.sequence!==d+1)throw new Error(`Journal sequence gap at ${b}`);if(R.previousHash!==l)throw new Error(`Journal chain mismatch at ${b}`);if(R.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${b}`);if(v.has(R.transactionId))throw new Error(`Duplicate transaction ID: ${R.transactionId}`);ps(a,R.mutation,R.committedAt),d=R.sequence,l=R.hash,v.add(R.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let T=$t(a);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:a,manifest:e,transactionIds:v,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await cs(this.memoryDir,{recursive:!0});let n;try{n=await Ar(this.lockPath,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let r=await Po(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await Er(this.lockPath),n=await Ar(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Er(this.lockPath).catch(()=>{})}}};import{randomBytes as _l}from"crypto";function Se(t=Date.now()){let n=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),o=_l(10).toString("hex"),r=(Number.parseInt(o[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${o.slice(0,3)}-${r}${o.slice(4,7)}-${o.slice(7,19)}`}var Cl=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function us(t,e){let n=t.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),o=t.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!o)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=t.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),a=new Date(e.completedAt).toISOString(),d=Cl(),l=d.records,v=t.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(M=>M.kind==="thread"&&M.id===e.threadId));v||(v={id:le(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.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(v));let T=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let M=t.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.value===u&&m.status==="current"));M||(M={id:le(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:le(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),T.push(M)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let M=t.records.find(h=>h.recordType==="subject"&&h.locators.some(m=>m.kind==="source_file"&&m.value===u&&m.status==="current"));M||(M={id:le(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:le(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(M)),T.push(M)}let b=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),R;if(b.length>0){R=le(r,"live-observation",i,e.createdAt);let u={id:R,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:b.map(M=>M.claim.trim()).join(" "),captureContext:{subjectIds:T.map(M=>M.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let S=le(r,"live-iteration",i,e.completedAt),f={id:S,schemaVersion:1,projectId:t.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(u=>({kind:"external",id:u,uri:"popmelt:imprint-evidence"})),...R?[{kind:"record",id:R}]:[]],recordType:"iteration",threadIds:[v.id],startedAt:s,completedAt:a,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};l.push(f);let p=[],g=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),w=T.length>0?T:t.records.filter(u=>u.recordType==="subject"&&u.subjectType==="project").slice(0,1);if(b.length>0&&w.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(r,"live-proposal",`${i}:${u}`,e.completedAt),m=w.map(D=>({subjectId:D.id,role:"governed"})),E={id:h,schemaVersion:1,projectId:t.manifest.projectId,createdAt:a,participantId:o.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:o.id}};l.push(E),p.push(h)}if(g.length>0){let u=new Set(e.governingDecisionIds??[]),M=t.records.filter(m=>m.recordType==="decision"&&m.state==="active"&&u.has(m.id)),h={id:le(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:t.manifest.projectId,createdAt:a,participantId:o.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:d,iterationId:S,proposalIds:p,observationId:R}}import{createHash as $l}from"crypto";import{mkdir as Ol,open as Dl,readFile as Nl,rename as Bl,unlink as Jl}from"fs/promises";import{join as ms}from"path";function fs(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function hs(t){return $l("sha256").update(JSON.stringify(t)).digest("hex")}async function Ll(t,e){let n=`${t}.${process.pid}.${Date.now()}.tmp`,o=await Dl(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
170
|
+
`,"utf8"),await o.sync()}finally{await o.close()}try{await Bl(n,t)}catch(r){throw await Jl(n).catch(()=>{}),r}}function ql(t,e,n=new Date().toISOString()){let o={},r={},i={},s=(d,l,v)=>{let T=d[l]??=[];T.includes(v)||T.push(v)};for(let d of t.records)if(d.recordType==="subject"){let l=d;for(let v of[l.label,...l.aliases,...l.locators.filter(T=>T.status==="current").map(T=>T.value)]){let T=fs(v);T&&s(o,T,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let a={version:1,projectId:t.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:o,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...a,checksum:hs(a)}}function gs(t,e){let n=[...new Set(e.flatMap(o=>t.subjectIdsByValue[fs(o)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(o=>t.decisionIdsBySubject[o]??[]))],proposalIds:[...new Set(n.flatMap(o=>t.proposalIdsBySubject[o]??[]))]}}var Ro=class{constructor(e){this.indexDir=ms(e,".popmelt","memory","indexes"),this.indexPath=ms(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Nl(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===hs(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let o=ql(e,n);return await Ol(this.indexDir,{recursive:!0}),await Ll(this.indexPath,o),o}};var Cn="popmelt:imprint",ws="popmelt:imprint-evidence",Zt="popmelt:imprint-relation";function jo(t){return t.sourceRefs.find(e=>e.kind==="external"&&e.uri===Cn)?.id}function _r(t){let e=new Set;return t.filter(n=>{let o=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(o)?!1:(e.add(o),!0)})}function Ao(t,e){if(!t)return[];let n=new Set(t.relations.flatMap(o=>o.type==="expresses"&&o.toId===e?[o.fromId]:[]));return t.concrete.filter(o=>n.has(o.id)).map(o=>({id:o.id,modelPath:o.modelPath,value:structuredClone(o.value),createdAt:o.createdAt,updatedAt:o.updatedAt}))}function Cr(t){if(t==="expresses")return"expresses";if(t==="excepts")return"excepts"}var Mo=class{constructor(e){this.projectRoot=e;this.store=new To(e),this.indexStore=new Ro(e),this.manifestPath=Yt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await _n(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let o=await Ot({...e,projectRoot:this.projectRoot});if(o.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(o.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Ot({...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=Yt(this.projectRoot,".popmelt","memory","migrations"),n=Yt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await _n(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let o;try{o=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!o?.explanations)return await ys(e,{recursive:!0}),await Is(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),a=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!a||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,v=new Set(r.bundle.records.map(u=>u.id)),T=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(M=>M.kind==="external"&&M.uri===Zt?[M.id]:[]))),b=new Map,R=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of o.explanations){let M=R.find(h=>jo(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 o.explanations){let M=b.get(u.id),h=R.find(P=>P.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 P of E){let C=le(l,"imprint-evidence-record",P.id,Date.parse(P.createdAt));m.push(C),!v.has(C)&&(S.push({id:C,schemaVersion:1,projectId:l,createdAt:P.createdAt,participantId:a.id,sourceRefs:_r([{kind:"external",id:P.id,uri:ws},{kind:"external",id:u.id,uri:Cn},{kind:"thread",id:P.threadId},{kind:"message",id:P.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(P.kind)?"user_feedback":"judgment",summary:P.summary,availability:"available",artifactIds:[]}),p.push({id:le(l,"imprint-evidence-link",`${u.id}:${P.id}`,Date.parse(P.createdAt)),schemaVersion:1,projectId:l,createdAt:P.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:P.id,uri:ws}],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??a.id,sourceRefs:_r([...h?.sourceRefs??[],{kind:"external",id:u.id,uri:Cn}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...h?.evidenceIds??[],...m])],concreteBindings:Ao(o,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 o.relations){let M=Cr(u.type);if(!M)continue;let h=b.get(u.fromId),m=b.get(u.toId);!h||!m||T.has(u.id)||p.push({id:le(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:a.id,sourceRefs:[{kind:"external",id:u.id,uri:Zt}],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 w=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",o.projectId,Date.parse(o.updatedAt)),committedAt:w});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await ys(e,{recursive:!0}),await Is(n,JSON.stringify({version:2,migratedAt:w,explanations:o.explanations.length,evidence:g,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:o.explanations.length,evidence:g}}async review(e,n={}){let o=await this.loadSource(n),r=await this.withIndexedCandidates(o,e);return{source:o.source,selection:An(o.bundle,r)}}async contextualize(e,n={}){let o=await this.loadSource(n),r=await this.withIndexedCandidates(o,e);return{source:o.source,actionPacket:ss(o.bundle,r),reviewSelection:An(o.bundle,r)}}async planReview(e,n={}){let o=await this.loadSource(n);return{source:o.source,result:So(o.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Ot({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(o=>o.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let o=await this.store.load(),r=So(o.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),o=n.bundle.records.find(b=>b.recordType==="proposal"&&b.id===e.proposalId),r=n.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active");if(!o||o.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:o?o.state!=="pending"?`The proposal is already ${o.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),a={proposalId:o.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...a,action:"accept",eventId:Se(i),decisionId:Se(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...a,action:"edit_and_accept",withdrawalEventId:Se(i),replacementProposalId:Se(i),acceptanceEventId:Se(i),decisionId:Se(i),relationshipId:Se(i),claim:e.claim,kind:e.kind,subjects:o.subjects,subjectSemantics:o.subjectSemantics,reason:e.reason}:e.action==="reject"?{...a,action:"reject",eventId:Se(i),reason:e.reason}:{...a,action:"defer",eventId:Se(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:o.subjects.map(b=>b.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=So(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(b=>b.message).join(" ")};let v=await this.store.commitReviewPlan(l.plan,{transactionId:Se(i),committedAt:s});await this.refreshIndex(v);let T=l.plan.resultRefs.find(b=>b.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:T,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:v.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),o=us(n.bundle,e),r=le(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(o.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:o.iterationId,proposalIds:o.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:o.iterationId,proposalIds:o.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let o=await this.store.load(),r=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="human"&&w.status==="active"),i=o.bundle.records.find(w=>w.recordType==="participant"&&w.kind==="ai"&&w.status==="active"),s=e.action?r:i??r,a=o.bundle.records.find(w=>w.recordType==="subject"&&w.subjectType==="project");if(!s||!a)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),v=o.bundle.manifest.projectId,T=[],b=[],R=[],S=o.bundle.records.filter(w=>w.recordType==="advisory_explanation"),f=new Map(S.flatMap(w=>{let u=jo(w);return u?[[u,w.id]]:[]}));for(let w of e.summary.changes)if(!f.has(w.explanationId)){let u=n?.explanations.find(M=>M.id===w.explanationId);f.set(w.explanationId,le(v,"imprint-explanation",w.explanationId,Date.parse(u?.createdAt??d)))}for(let w of e.summary.changes){let u={kind:"external",id:w.explanationId,uri:Cn},M=f.get(w.explanationId),h=S.find(P=>P.id===M),m=n?.explanations.find(P=>P.id===w.explanationId),E={id:le(v,"imprint-live-evidence",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};T.push(E);let D={id:M,schemaVersion:1,projectId:v,createdAt:h?.createdAt??m?.createdAt??d,participantId:h?.participantId??s.id,sourceRefs:_r([...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??w.state,statement:m?.statement??w.statement,rationale:m?.rationale??h?.rationale??e.summary.detail,scope:structuredClone(m?.scope??h?.scope??{kind:"project",values:[]}),subjectIds:h?.subjectIds??[a.id],evidenceIds:[...new Set([...h?.evidenceIds??[],E.id])],concreteBindings:m?Ao(n,w.explanationId):h?.concreteBindings??[],supersededById:m?.supersededBy?f.get(m.supersededBy):h?.supersededById,updatedAt:m?.updatedAt??d};h?b.push(D):T.push(D),R.push({id:le(v,"imprint-live-evidence-link",`${e.summary.transactionId}:${w.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:v,createdAt:d,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(o.bundle.relationships.flatMap(w=>w.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===Zt?[u.id]:[])));for(let w of n?.relations??[]){let u=Cr(w.type);if(!u)continue;let M=f.get(w.fromId),h=f.get(w.toId);!M||!h||p.has(w.id)||R.push({id:le(v,"imprint-relation",w.id,Date.parse(w.createdAt)),schemaVersion:1,projectId:v,createdAt:w.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:w.id,uri:Zt}],recordType:"relationship",relationshipType:u,from:{entityType:"advisory_explanation",entityId:M},to:{entityType:"advisory_explanation",entityId:h},reason:w.rationale||"The Imprint graph connected these explanations."})}let g=le(o.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let w=await this.store.commit({records:T,recordReplacements:b,events:[],relationships:R,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:g,committedAt:d});await this.refreshIndex(w)}catch(w){if(!(w instanceof Error)||!w.message.includes("Transaction already exists"))throw w}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=At(JSON.parse(await _n(Yt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),o=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??o;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let a=n.bundle.manifest.projectId,d=n.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(d.flatMap(m=>{let E=jo(m);return E?[[E,m]]:[]})),v=new Map([...[...l].map(([m,E])=>[m,E.id]),...e.explanations.filter(m=>!l.has(m.id)).map(m=>[m.id,le(a,"imprint-explanation",m.id,Date.parse(m.createdAt))])]),T=[],b=[],R=new Set(e.explanations.map(m=>m.id));for(let m of e.explanations){let E=l.get(m.id);if(!E){T.push({id:v.get(m.id),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Cn}],recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Ao(e,m.id),supersededById:m.supersededBy?v.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:Ao(e,m.id),supersededById:m.supersededBy?v.get(m.supersededBy):void 0,updatedAt:m.updatedAt},P=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});P(E)!==P(D)&&b.push(D)}for(let[m,E]of l)R.has(m)||E.state==="retired"||b.push({...structuredClone(E),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let S=new Set(n.bundle.tombstones.flatMap(m=>m.objectType==="relationship"?[m.objectId]:[])),f=new Map(n.bundle.relationships.flatMap(m=>{if(S.has(m.id))return[];let E=m.sourceRefs.find(D=>D.kind==="external"&&D.uri===Zt)?.id;return E?[[E,m]]:[]})),p=[],g=new Set;for(let m of e.relations){let E=Cr(m.type);if(!E)continue;let D=v.get(m.fromId),P=v.get(m.toId);if(!D||!P)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===P||(C&&g.add(m.id),p.push({id:le(a,"imprint-relation",`${m.id}:${E}:${D}:${P}`,Date.parse(m.createdAt)),schemaVersion:1,projectId:a,createdAt:m.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:m.id,uri:Zt}],recordType:"relationship",relationshipType:E,from:{entityType:"advisory_explanation",entityId:D},to:{entityType:"advisory_explanation",entityId:P},reason:m.rationale||"The Imprint graph connected these explanations."}))}let w=new Set(e.relations.map(m=>m.id)),u=o?[...f].filter(([m])=>!w.has(m)||g.has(m)).map(([,m])=>({id:le(a,"imprint-relationship-tombstone",m.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:a,objectId:m.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:o.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!T.length&&!b.length&&!p.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let M=e.updatedAt,h=le(a,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(M));try{let m=await this.store.commit({records:T,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:T.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:n.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 n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let o={};for(let r of n.bundle.records)o[r.recordType]=(o[r.recordType]??0)+1;return{status:e,journal:n.report,records:o,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),o=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(a=>a.status==="projected").map(a=>a.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!o.has(s.id)&&!r.has(s.id)&&!i.has(s.id)).sort((s,a)=>a.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),o=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&o.set(r.key,r);return[...o.values()]}async getImprintView(e=[],n){let o=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return o();let r=await this.store.load(),i=r.bundle.records.filter(p=>p.recordType==="advisory_explanation"),s=new Map(i.map(p=>[p.id,p])),a=new Map(i.flatMap(p=>{let g=jo(p);return g?[[g,p.id]]:[]})),d=new Set(e.map(p=>a.get(p)??p)),l=new Map(r.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),v=new Map(r.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),T=new Set(r.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),b=new Set(["expresses","operationalizes","excepts"]),R={testing:0,emerging:1,grounded:2,challenged:3,retired:4},S=i.map(p=>{let g=p.evidenceIds.flatMap(h=>{let m=v.get(h);if(!m)return[];let E=m.sourceRefs.find(z=>z.kind==="thread")?.id,D=m.sourceRefs.find(z=>z.kind==="message")?.id,P=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:P,summary:m.summary,createdAt:m.createdAt,participantKind:C,threadId:E,jobId:D}]}).sort((h,m)=>m.createdAt.localeCompare(h.createdAt)),w=r.bundle.relationships.flatMap(h=>{if(T.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,P=s.get(D);return P?[{id:h.id,type:h.relationshipType==="excepts"?"excepts":"expresses",direction:m?"outgoing":"incoming",explanationId:P.id,statement:P.statement,rationale:h.reason}]:[]}),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."}]:[]}),...i.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=>!n||n.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:[...w,...u],sourceThreadIds:M,needsGrounding:p.state==="testing"&&d.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: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:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:f,explanations:S}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(a=>a.recordType==="decision"&&a.state==="active"?[a.id]:[])),o=new Map;for(let a of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))a.decisionIds.some(d=>n.has(d))&&o.set(a.key,a);let r=[...o.values()],i=e.records.filter(a=>a.recordType==="verification_attempt");return{decisions:e.records.filter(a=>a.recordType==="decision"&&a.state==="active").map(a=>{let d=i.filter(l=>l.targets.some(v=>v.entityType==="decision"&&v.entityId===a.id)).sort((l,v)=>v.createdAt.localeCompare(l.createdAt))[0];return{id:a.id,kind:a.kind,claim:a.claim,projected:r.some(l=>l.decisionIds.includes(a.id)),verification:d?d.state:"unverified"}}),entries:r.map(a=>({id:a.id,key:a.key,value:a.value,decisionIds:a.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let n=await this.store.load(),o=n.bundle.records.find(P=>P.recordType==="participant"&&P.kind==="human"&&P.status==="active"),r=n.bundle.records.find(P=>P.recordType==="subject"&&P.subjectType==="project");if(!o||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),a=Se(i),d=Se(i),l=Se(i),v=Se(i),T=Se(i),b=new Set(n.bundle.records.flatMap(P=>P.recordType==="model_entry"&&P.key===e.key?P.decisionIds:[])),R=n.bundle.records.filter(P=>P.recordType==="decision"&&P.state==="active"&&b.has(P.id)),S={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:o.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:r.id,role:"governed"}],p={...S,id:a,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:o.id}},g={...S,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:a},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},w={...S,id:l,recordType:"decision",proposalId:a,acceptanceEventId:d,acceptedById:o.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},u={...S,id:v,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},M={...S,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:o.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[v],coverage:[{decisionId:l,status:"projected"}]},h={...S,id:Se(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},m=R.map(P=>({...S,id:Se(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:P.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),E=R.map(P=>({...S,id:Se(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:w.id},to:{entityType:"decision",entityId:P.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),D=await this.store.commit({records:[p,w,u,M],events:[g,...m],relationships:[h,...E],artifacts:[],tombstones:[],projectionUpdates:R.map(P=>({entityType:"decision",entityId:P.id,fromState:"active",state:"superseded"}))},{transactionId:Se(i),committedAt:s});return await this.refreshIndex(D),{decisionId:l,entryId:v}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),o=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return o?{proposalId:o.id,claim:o.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),o=new Map(n.records.flatMap(r=>r.recordType==="subject"?[[r.id,r.label]]:[]));return n.records.filter(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.kind==="thread"&&i.id===e)).sort((r,i)=>r.createdAt.localeCompare(i.createdAt)).map(r=>({proposalId:r.id,claim:r.claim,rationale:r.rationale,proposedKind:r.proposedKind,subjectLabels:r.subjects.flatMap(i=>{let s=o.get(i.subjectId);return s?[s]:[]})}))}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let n=await this.store.load(),o=n.bundle.records.find(S=>S.recordType==="model_projection"&&S.state==="applied"&&S.runId===e.runId);if(o)return{projectionId:o.id,entryIds:o.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(S=>S.recordType==="decision"&&e.decisionIds.includes(S.id)&&S.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),a=new Date(s).toISOString(),d=Se(s),l=e.changes.map(S=>{let f=S.decisionIds?.filter(w=>e.decisionIds.includes(w)),p=f?.length?f:e.decisionIds,g=[...new Set(r.filter(w=>p.includes(w.id)).flatMap(w=>w.subjects.map(u=>u.subjectId)))];return{id:Se(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:p.map(w=>({kind:"record",id:w})),recordType:"model_entry",key:S.path.map(String).join("."),subjectIds:g,decisionIds:p,value:S.value}}),v=new Set(l.flatMap(S=>S.decisionIds)),T={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:e.decisionIds.map(S=>({kind:"record",id:S})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:a,decisionIds:e.decisionIds,entryIds:l.map(S=>S.id),coverage:e.decisionIds.map(S=>e.coverage?.find(f=>f.decisionId===S)??{decisionId:S,status:v.has(S)?"projected":"unprojected"})},b=l.flatMap(S=>S.decisionIds.map(f=>({id:Se(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:a,participantId:i.id,sourceRefs:[{kind:"record",id:T.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."}))),R=await this.store.commit({records:[...l,T],events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Se(s),committedAt:a});return await this.refreshIndex(R),{projectionId:d,entryIds:l.map(S=>S.id),headSequence:R.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Ot({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let o=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=gs(o,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}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 tn(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object.");return t}function Te(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} must be a non-empty string.`);return t}function en(t,e,n){let o=Te(t,e);if(!n.includes(o))throw new Error(`${e} is invalid.`);return o}function $r(t){let e=tn(t),n=tn(e.authority),o=n.level,r=n.mode,i=en(o,"authority.level",["owner","delegate","contributor"]),s=en(r,"authority.mode",["local_trusted","hosted"]),a={proposalId:Te(e.proposalId,"proposalId"),participantId:Te(e.participantId,"participantId"),occurredAt:Te(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...a,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:en(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Te(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...a,action:"reject",eventId:Te(e.eventId,"eventId"),reason:Te(e.reason,"reason")};case"defer":{let d=tn(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...a,action:"defer",eventId:Te(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Te(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>en(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...a,action:"edit_and_accept",withdrawalEventId:Te(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Te(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Te(e.acceptanceEventId,"acceptanceEventId"),decisionId:Te(e.decisionId,"decisionId"),relationshipId:Te(e.relationshipId,"relationshipId"),claim:Te(e.claim,"claim"),kind:en(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=tn(d);return{subjectId:Te(l.subjectId,"subjectId"),role:en(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:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Or(t){let e=tn(t),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(a=>Te(a,s))}},o=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:tn(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:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:o(e.maxPackets,"maxPackets"),maxEstimatedTokens:o(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function vs(t){let e=t.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let o=n.action,r=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((o==="accept"||o==="edit_and_accept")&&!r||o==="edit_and_accept"&&typeof n.claim!="string"||o!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let i=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(a=>typeof a=="string"&&i.has(a)):void 0;return{proposalId:n.proposalId,action:o,kind:r,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function bs(t){let e=t.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),o=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!o||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:o,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function Dr(t){let n=(t.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let o=n[1]||n[2],r=await Fl(t),i=Buffer.from(`--${o}`),s=Buffer.from(`--${o}--`),a,d,l,v,T,b,R,S,f,p,g,w,u,M,h=[],m=[],E=0,D=[];for(;E<r.length;){let P=r.indexOf(i,E);if(P===-1)break;let C=P+i.length;if(r.slice(P,P+s.length).equals(s))break;let z=C;r[z]===13&&r[z+1]===10&&(z+=2);let X=r.indexOf(`\r
|
|
169
171
|
\r
|
|
170
|
-
`,z);if(X===-1)break;let G=r.slice(z,X).toString("utf-8"),Y=X+4,
|
|
172
|
+
`,z);if(X===-1)break;let G=r.slice(z,X).toString("utf-8"),Y=X+4,x=r.indexOf(i,Y),Q=x!==-1?x-2:r.length;D.push({headers:G,body:r.slice(Y,Q)}),E=x!==-1?x:r.length}for(let P of D){let C=P.headers.match(/name="([^"]+)"/);if(!C)continue;let z=C[1];if(z==="screenshot")a=P.body;else if(z==="feedback")d=P.body.toString("utf-8");else if(z==="color")l=P.body.toString("utf-8");else if(z==="provider")v=P.body.toString("utf-8");else if(z==="model")T=P.body.toString("utf-8");else if(z==="reasoningEffort")b=P.body.toString("utf-8");else if(z==="serviceTier")R=P.body.toString("utf-8");else if(z==="goal")S=P.body.toString("utf-8");else if(z==="pageUrl")f=P.body.toString("utf-8");else if(z==="viewport")p=P.body.toString("utf-8");else if(z==="planId")g=P.body.toString("utf-8");else if(z==="manifest")w=P.body.toString("utf-8");else if(z==="tasks")u=P.body.toString("utf-8");else if(z==="sourceId")M=P.body.toString("utf-8");else if(z.startsWith("screenshot-")){let X=z.slice(11);try{let G=decodeURIComponent(X);m.push({pathname:G,data:P.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:P.body})}}if(!a)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:a,feedback:d,color:l,provider:v,model:T,reasoningEffort:b,serviceTier:R,goal:S,pageUrl:f,viewport:p,planId:g,manifest:w,tasks:u,sourceId:M,pastedImages:h,pageScreenshots:m}}function Fl(t){return new Promise((e,n)=>{let o=[];t.on("data",r=>o.push(r)),t.on("end",()=>e(Buffer.concat(o))),t.on("error",n)})}import{randomUUID as Ul}from"crypto";var $n="<orientation>",lt="</orientation>";function nn(t,e){let n=e;for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)return{status:"incomplete",start:n};if(t[n]!=="{")return{status:"invalid",start:n};let o=0,r=!1,i=!1;for(let s=n;s<t.length;s++){let a=t[s];if(r){i?i=!1:a==="\\"?i=!0:a==='"'&&(r=!1);continue}if(a==='"')r=!0;else if(a==="{")o++;else if(a==="}"){if(o--,o===0)return{status:"complete",start:n,end:s+1};if(o<0)return{status:"invalid",start:n}}}return{status:"incomplete",start:n}}function xs(t,e){if(!e)return;let n=t[t.length-1];n?.kind==="text"?n.text+=e:t.push({kind:"text",text:e})}function Ss(t){let e=[],n=0;for(;n<t.length;){let o=t.indexOf($n,n);if(o<0){xs(e,t.slice(n));break}xs(e,t.slice(n,o));let r=o+$n.length,i=nn(t,r);if(i.status!=="complete"){let a=t.indexOf(lt,r);if(a>=0){n=a+lt.length;continue}n=r;continue}e.push({kind:"orientation",json:t.slice(i.start,i.end)}),n=i.end;let s=n;for(;s<t.length&&/\s/.test(t[s]);)s++;t.startsWith(lt,s)&&(n=s+lt.length)}return e}var zl=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),Hl=new Set(["strengthened","weakened","mixed","unknown"]);function On(t,e=180){if(typeof t!="string")return;let n=t.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function Wl(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function Ps(t,e,n,o=Date.now()){let r=Wl(t);if(!r)return null;let i=typeof r.transition=="string"&&zl.has(r.transition)?r.transition:null,s=On(r.focus);if(!i||!s)return null;let a=typeof r.evidencePosture=="string"&&Hl.has(r.evidencePosture)?r.evidencePosture:void 0;return{id:Ul(),jobId:e,sequence:n,timestamp:o,transition:i,snapshot:{focus:s,seeking:On(r.seeking),workingHypothesis:On(r.workingHypothesis),evidencePosture:a,update:On(r.update),nextObservation:On(r.nextObservation)},contextPolicy:"exclude"}}function Nr(t){return JSON.stringify({transition:t.transition,snapshot:t.snapshot})}function Br(t,e,n=0){let o=[],r=[],i=new Set,s=n;for(let d of Ss(t)){if(d.kind==="text"){d.text&&r.push(d);continue}try{let l=Ps(JSON.parse(d.json),e,s);if(!l)continue;let v=Nr(l);if(i.has(v))continue;i.add(v),o.push(l),r.push({kind:"orientation",orientation:l}),s++}catch{}}return{visibleText:r.map(d=>d.kind==="text"?d.text:`
|
|
171
173
|
|
|
172
174
|
`).join("").replace(/\n{3,}/g,`
|
|
173
175
|
|
|
174
|
-
`).trim(),orientations:o,segments:r}}function
|
|
176
|
+
`).trim(),orientations:o,segments:r}}function Gl(t){let e="<orientation>",n=Math.min(t.length,e.length-1);for(let o=n;o>0;o--)if(e.startsWith(t.slice(-o)))return o;return 0}var Eo=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let n="",o=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(lt.startsWith(l)&&l.length<lt.length||(l.startsWith(lt)&&(this.buffer=this.buffer.slice(d+lt.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf($n);if(r<0){let d=Gl(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,r);let i=r+$n.length,s=nn(this.buffer,i);if(s.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(i);continue}let a=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=Ps(JSON.parse(a),this.jobId,this.sequence);if(!d)continue;let l=Nr(d);if(this.signatures.has(l))continue;this.signatures.add(l),o.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:o}}finalize(e){let n=Br(e,this.jobId,this.sequence),o=n.orientations.filter(r=>{let i=Nr(r);return this.signatures.has(i)?!1:(this.signatures.add(i),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:n.visibleText,orientations:o}}},ks=`## Public orientation updates
|
|
175
177
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
176
178
|
<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>
|
|
177
179
|
|
|
178
180
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
179
181
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
180
182
|
|
|
181
|
-
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
|
|
183
|
+
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 Ts=`## Project collaboration history
|
|
182
184
|
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.
|
|
183
185
|
|
|
184
186
|
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.
|
|
@@ -189,27 +191,27 @@ Use Popmelt history to explain why a decision was made or how shared understandi
|
|
|
189
191
|
|
|
190
192
|
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 Dn(t,e,n){let o=[];if(t.annotations.length>0){o.push("## Annotations");for(let r of t.annotations){let i=r.elements.map(l=>{let v=[l.selector];return l.reactComponent&&v.push(`(${l.reactComponent})`),v.join(" ")}).join(", "),s=r.instruction||"No text";o.push(`- id=${r.id} [${r.type}] ${s} \u2192 Elements: ${i||"none"}`);let a=e?.[r.id];if(a&&a.length>0)for(let l of a)o.push(` Attached image: use the Read tool to view ${l}`);let d=n?.[r.id];if(d?.length)for(let l of d)o.push(` Attached context (${l.name}, ${l.mimeType}): use the Read tool to inspect ${l.path}`)}}if(t.styleModifications.length>0){o.push(""),o.push("## Style Changes (make permanent in source)"),o.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let r of t.styleModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"";for(let s of r.changes)o.push(`- ${r.selector} ${i}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(t.textModifications?.length){o.push(""),o.push("## Text Changes (make permanent in source)"),o.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let r of t.textModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=JSON.stringify(r.original),a=JSON.stringify(r.modified),d=r.textNodePath.length>0?` textNodePath=${r.textNodePath.join(".")}`:"";o.push(`- ${r.selector} ${i}${d}: ${s} \u2192 ${a}`)}}if(t.domModifications?.length){o.push(""),o.push("## DOM Structure Changes (make permanent in source)"),o.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let r of t.domModifications){let i=r.element?.reactComponent?`(${r.element.reactComponent})`:"",s=r.sourceElement?.reactComponent?` from ${r.sourceSelector} (${r.sourceElement.reactComponent})`:r.sourceSelector?` from ${r.sourceSelector}`:"",a=r.referenceSelector?` ${r.placement} ${r.referenceSelector}`:` at index ${r.targetIndex}`;o.push(`- ${r.operation}: ${r.selector} ${i}${s} \u2192 ${r.targetParentSelector}${a}`)}}if(t.spacingTokenChanges?.length){o.push(""),o.push("## Spacing Token Changes"),o.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let r of t.spacingTokenChanges){o.push(`
|
|
191
193
|
### ${r.tokenName}: ${r.originalPx}px \u2192 ${r.newPx}px`);for(let i of r.affectedElements){let s=i.reactComponent?` (${i.reactComponent})`:"";i.matchedClass&&i.suggestedClass?o.push(`- ${i.selector}${s}: \`${i.matchedClass}\` \u2192 \`${i.suggestedClass}\``):o.push(`- ${i.selector}${s}: ${i.property} ${r.originalPx}px \u2192 ${r.newPx}px`),o.push(` class="${i.className}"`)}}}if(t.inspectedElement){let r=t.inspectedElement;o.push(""),o.push("## Inspected Element"),o.push("The developer has this element selected in the inspector:");let i=[r.selector];r.reactComponent&&i.push(`(${r.reactComponent})`),r.context&&i.push(`in ${r.context}`),r.textContent&&i.push(`"${r.textContent.slice(0,80)}"`),o.push(`- ${i.join(" ")}`)}return o.join(`
|
|
192
|
-
`)}function
|
|
193
|
-
`)}function
|
|
194
|
-
`)}function
|
|
195
|
-
`)){if(/^\s*`model`:/.test(o)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(o))break;if(!n)continue;let r=o.match(
|
|
196
|
-
`));return Co([..._o,...d])}function Eo(t,e,n=5e3){return new Promise((o,r)=>{Ql(t,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}o(s)})})}async function Os(t){return Yl(t,"utf-8")}async function rp(t){let e=[ot(t,"projects"),ot(t,"telemetry")],n=[];for(let o of e)await Ds(o,n,4);return n.sort((o,r)=>r.mtimeMs-o.mtimeMs).slice(0,80).map(o=>o.path)}async function Ds(t,e,n){if(n<0)return;let o;try{o=await Xl(t,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async r=>{let i=ot(t,r.name);if(r.isDirectory()){await Ds(i,e,n-1);return}if(!(!r.isFile()||!ip(r.name)))try{let s=await Zl(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function ip(t){return t.endsWith(".json")||t.endsWith(".jsonl")||t.endsWith(".md")||t.endsWith(".txt")}function Co(t){let e=new Set,n=[];for(let o of t)e.has(o.id)||(e.add(o.id),n.push(o));return n}function sp(t){return[...new Set(t)]}function ap(t){return t.charAt(0).toUpperCase()+t.slice(1)}var $o=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,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let o=n>=0?n+1:0,r=this.activeJobs.size+o+1;return this.queue.splice(o,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(o=>o.threadId===e&&(!n||n(o)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,o){let r=this.bufferEvent(n,e);for(let i of this.listeners)i(r,n,o)}bufferEvent(e,n){let o=this.eventBuffers.get(e);o||(o={events:[],nextSeq:0},this.eventBuffers.set(e,o));let r={...n,seq:o.nextSeq++};return o.events.push(r),o.events.length>1e4&&o.events.splice(0,o.events.length-1e4),r}getBufferedEvents(e,n=-1){let o=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!o)return null;let s=n<0?o.events:o.events.filter(a=>a.seq>n);return{jobId:e,events:s,currentSeq:o.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,n,o){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=o}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let o=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,o)}cancelJob(e){let n=this.activeProcesses.get(e),o=this.activeJobs.get(e);return!n||!o?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),o.status="error",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:"Cancelled by user",cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);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 n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let o of n)try{o.kill("SIGTERM")}catch{}await Promise.all(n.map(o=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};o.on("exit",s),o.on("error",s),setTimeout(()=>{if(!i){try{o.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let o of this.cleanupTimers.values())clearTimeout(o);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),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 dp}from"crypto";var on="<imprint-use>",Oo="</imprint-use>";function cp(t){let e=Math.min(t.length,on.length-1);for(let n=e;n>0;n--)if(on.startsWith(t.slice(-n)))return n;return 0}function Ns(t,e,n,o,r=Date.now()){if(!t||typeof t!="object"||Array.isArray(t))return null;let i=t,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let l=e?.explanations.find(v=>v.id===d);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return a.length===0?null:{id:dp(),jobId:n,sequence:o,timestamp:r,explanations:a}}var Do=class{constructor(e,n){this.jobId=e;this.context=n;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let n=e.explanations.filter(o=>!this.explanationIds.has(o.id));if(n.length===0)return null;for(let o of n)this.explanationIds.add(o.id);return{...e,sequence:this.sequence++,explanations:n}}push(e){this.buffer+=e;let n="",o=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(Oo.startsWith(l)&&l.length<Oo.length||(l.startsWith(Oo)&&(this.buffer=this.buffer.slice(d+Oo.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(on);if(r<0){let d=cp(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,r);let i=r+on.length,s=nn(this.buffer,i);if(s.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(i);continue}let a=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=Ns(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let l=this.takeNewExplanations(d);l&&o.push(l)}catch{}}return{visibleText:n,usages:o}}finalize(e){this.buffer="",this.optionalClosePending=!1;let n=[],o="",r=0;for(;r<e.length;){let i=e.indexOf(on,r);if(i<0){o+=e.slice(r);break}o+=e.slice(r,i);let s=i+on.length,a=nn(e,s);if(a.status!=="complete"){r=s;continue}try{let v=Ns(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(v){let x=this.takeNewExplanations(v);x&&n.push(x)}}catch{}let l=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+l}return{visibleText:o.trim(),usages:n}}};function Ln(t,e){return t?.projectId===e.projectId&&t.version===e.version&&t.restartMode===e.restartMode}function No(t){return(Array.isArray(t)?t[0]:t)?.split(",")[0]?.trim()||void 0}function Jr(t){if(!t)return null;try{let e=new URL(t);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Bs(t){let e=Jr(No(t.origin));if(e)return e;let n=Jr(No(t.referer));if(n)return n;let o=No(t["x-forwarded-host"]);if(!o)return null;let r=No(t["x-forwarded-proto"])==="https"?"https":"http";return Jr(`${r}://${o}`)}function Js(t,e,n=5){let o=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...t].sort(o).slice(0,n),i=t.filter(d=>d.status==="applied"||d.status==="failed").sort(o).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{createHash as Lo}from"crypto";import{mkdir as Un,readFile as Nt,unlink as hp,writeFile as rn}from"fs/promises";import{dirname as qo,extname as gp,join as Be}from"path";var lp={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 pp(t){let e=typeof t=="string"?t:(()=>{try{return JSON.stringify(t)}catch{return String(t??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function Ls(t,e){let n=e??pp(t);return{kind:n,...lp[n]}}import{createHash as up,randomUUID as mp}from"crypto";var qs=t=>`${t}-${mp()}`;function Lr(t,...e){return`${t}-${up("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function qr(t){return{schemaVersion:1,submissionIds:[qs("submission")],jobId:t.jobId,threadId:t.threadId,artifactIds:[...new Set(t.artifactIds??[])]}}function qn(t,e=[],n){return{...t,outcomeId:t.outcomeId??qs("outcome"),imprintEvidenceIds:[...new Set([...t.imprintEvidenceIds??[],...e])],...n?{imprintAssessment:n}:{}}}function fp(t){try{return new URL(t).pathname||"/"}catch{return"/"}}function Bo(t,e){return e?[`${t||"/"}:${e}`]:[]}function Us(t){let e=fp(t.url);return[...new Set([...t.annotations.flatMap(n=>Bo(n.pathname??e,n.linkedSelector)),...t.styleModifications.flatMap(n=>Bo(e,n.durableSelector??n.selector)),...(t.textModifications??[]).flatMap(n=>Bo(n.pathname??e,n.durableSelector??n.selector)),...(t.domModifications??[]).flatMap(n=>Bo(n.pathname??e,n.durableSelector??n.selector))])]}function Fs(t,e){return[...new Set([`screenshot:${e}`,...t.annotations.map(n=>`annotation:${n.id}`),...t.annotations.flatMap(n=>(n.attachments??[]).map(o=>`attachment:${o.id}`))])]}function Jo(t,e){if(e.lifecycle?.schemaVersion===1)return!1;let n=Lr("submission",t,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[n],jobId:e.jobId,threadId:t,artifactIds:[...(e.annotationIds??[]).map(o=>`annotation:${o}`),...e.screenshotPath?[Lr("artifact",t,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:Lr("outcome",t,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Ur(t){let e=t.lifecycleVersion!==1;t.lifecycleVersion=1;for(let n of t.messages)e=Jo(t.id,n)||e;return e}function zs(t){let e=t.messages.at(-1),n=[...t.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:t.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:t.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let o=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:n?.jobId,threadId:t.id,status:o?"waiting_input":"resolved",label:o?"Question":"Replied",outcomeId:n?.lifecycle?.outcomeId,imprintEvidenceIds:n?.lifecycle?.imprintEvidenceIds??[]}}var yp={version:1,threads:{}},Hs=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Fn={version:2,updatedAt:0,files:{}};function Ip(t){return JSON.stringify(t,null,2)}function wp(t){return Object.fromEntries(Hs.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}function vp(t){let e={...t};for(let n of Hs)delete e[n];return e}function sn(t){let e=t;if(t.error){let n=Ls(t.error,t.errorKind);(t.error!==n.message||t.errorKind!==n.kind||t.responseText!==void 0)&&(e={...t,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=qt(e.result,!1),o=qt(e.turn?.result,!1);(n!==e.result||o!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...o?{result:o}:{}}}:{}})}return e}var Uo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Be(e,".popmelt");this.legacyFilePath=Be(n,"threads.json"),this.threadsDir=Be(n,"threads"),this.indexPath=Be(this.threadsDir,"index.json"),this.artifactsDir=Be(n,"artifacts","thread-messages"),this.mediaDir=Be(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Nt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[r,i]of Object.entries(e.files)){let s=await this.readThread(Be(this.threadsDir,i));s&&(n[r]=s)}this.cache={version:1,threads:n};let o=!1;for(let r of Object.values(n))o=Ur(r)||o;return o&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Nt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,o])=>[n,{...o,messages:o.messages.map(sn)}]))},this.index={...Fn,files:{},migratedFromLegacyAt:Date.now()};for(let n of Object.values(this.cache.threads))Ur(n);return await this.persistAll(),this.cache}}catch{}return this.cache={...yp,threads:{}},this.index={...Fn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),o=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>o.has(s)))return r;return null}async createThread(e,n){let o=await this.load(),r={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return o.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(Jo(e,n),r.messages.push(sn(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;Jo(e,n);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,sn(n)):r.messages.push(sn(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(a=>a.jobId===n);if(s.length===0)return!1;for(let a of s)if(Object.assign(a,o),a.error){let d=sn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(a=>a.role==="assistant"&&a.jobId===n);return s?(Object.assign(s,o),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),o=Object.values(n.threads);return o.sort((r,i)=>i.updatedAt-r.updatedAt),o.slice(0,e).map(r=>{let s=r.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",a=r.messages.filter(p=>p.role==="assistant"),d=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=r.messages.findLastIndex(p=>!!d(p)),v=r.messages.findLastIndex(p=>p.role==="human"),x=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,R=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),P=a.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=a.some(p=>!!p.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:P,hasError:f,lastMessageRole:b,pendingQuestion:x,acknowledgedJobIds:R,elementIdentifiers:r.elementIdentifiers,lifecycle:zs(r)}})}async recoverInterruptedTurns(){let e=await this.load(),n=0;for(let o of Object.values(e.threads)){let r=o.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=qn(r.lifecycle);r.queued&&await this.updateMessage(o.id,r.jobId,{queued:!1}),await this.appendMessage(o.id,{role:"assistant",timestamp:Date.now(),jobId:r.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:i}),n+=1}return n}async getThreadHistory(e,n=6){let o=await this.getThread(e);return!o||o.messages.length===0?[]:o.messages.length<=n?o.messages:[o.messages[0],...o.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await Nt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let o=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let a=await Nt(Be(qo(this.legacyFilePath),r.path),"utf8");Lo("sha256").update(a).digest("hex")===r.sha256&&(s=JSON.parse(a))}catch{}return sn({...i,...s})}));return{id:n.id,lifecycleVersion:n.lifecycleVersion,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:o}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=wp(e),o=vp(e);if(Object.keys(n).length===0)return o;let r=Ip(n),i=Lo("sha256").update(r).digest("hex"),s=Be("artifacts","thread-messages",`${i}.json`);await Un(this.artifactsDir,{recursive:!0});try{await Nt(Be(qo(this.legacyFilePath),s),"utf8")}catch{await rn(Be(qo(this.legacyFilePath),s),r)}return{...o,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async o=>{if(qo(o)===this.mediaDir)return o;try{let r=await Nt(o),i=Lo("sha256").update(r).digest("hex"),s=Be(this.mediaDir,`${i}${gp(o)||".bin"}`);await Un(this.mediaDir,{recursive:!0});try{await Nt(s)}catch{await rn(s,r)}return s}catch{return o}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([o,r])=>[o,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([o,r])=>[o,await Promise.all(r.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([o,r])=>[o,await Promise.all(r.map(async i=>({...i,path:await n(i.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await Un(this.threadsDir,{recursive:!0});let n=this.index??{...Fn,files:{}},o=n.files[e.id]??`${Lo("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await rn(Be(this.threadsDir,o),JSON.stringify(i,null,2)),n.files[e.id]=o,n.updatedAt=Date.now(),this.index=n,await rn(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),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 Un(this.threadsDir,{recursive:!0}),this.index=this.index??{...Fn,files:{}},await rn(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...Fn,files:{}},o=n.files[e];o&&await hp(Be(this.threadsDir,o)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await Un(this.threadsDir,{recursive:!0}),await rn(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as bp,open as xp,readFile as Sp,rename as Pp,unlink as kp}from"fs/promises";import{dirname as Tp,join as Rp}from"path";var Ws={schemaVersion:1,theme:"auto",updatedAt:null};function Gs(t){return t==="light"||t==="dark"||t==="auto"?t:null}async function jp(t,e){await bp(Tp(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;try{let o=await xp(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
197
|
-
`,"utf8"),await o.sync()}finally{await o.close()}await
|
|
194
|
+
`)}function Rs(t,e,n){let o=[],i=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(o.push("You are reviewing a UI screenshot with developer annotations."),o.push(""),!i&&n?.provider!=="codex"&&(o.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${t}`),o.push("")),o.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){o.push(""),o.push("## Previous Conversation");let s=0;for(let a of n.threadHistory)if(a.role==="human")s++,a.replyToQuestion?(o.push(`### Round ${s} (human) \u2014 reply`),o.push(`"${a.replyToQuestion}"`)):(o.push(`### Round ${s} (human)`),a.feedbackSummary&&o.push(`Annotations: ${a.feedbackSummary}`),a.annotationIds&&a.annotationIds.length>0&&o.push(`Annotation IDs: ${a.annotationIds.join(", ")}`));else if(a.question)o.push(`### Round ${s} (assistant) \u2014 question`),o.push(`"${a.question}"`);else{if(o.push(`### Round ${s} (assistant)`),a.responseText&&o.push(`Response: ${a.responseText}`),a.resolutions&&a.resolutions.length>0)for(let d of a.resolutions){let l=d.finalScope??d.inferredScope,v=l?` [${l.breadth} ${l.target}]`:"";o.push(`- ${d.annotationId}: ${d.status}${v} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&o.push(` Files: ${d.filesModified.join(", ")}`)}a.toolsUsed&&a.toolsUsed.length>0&&o.push(`Tools used: ${a.toolsUsed.join(", ")}`)}o.push(""),o.push("The current round is shown in full below.")}if(n?.designModel){o.push(""),o.push("## Established Design Policies"),o.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(o.push(""),o.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let v=new Map;for(let T of s)if(typeof T=="object"&&T!==null&&"text"in T){let b=T,R=b.scope||"general";v.has(R)||v.set(R,[]),v.get(R).push(b.text)}for(let[T,b]of v){o.push(`**${T.charAt(0).toUpperCase()+T.slice(1)}**`);for(let R of b)o.push(`- ${R}`)}}else for(let v of s)typeof v=="string"&&o.push(`- ${v}`);let a=n.designModel.tokens;a&&typeof a=="object"&&(o.push(""),o.push("Design tokens:"),o.push("```json"),o.push(JSON.stringify(a,null,2)),o.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(o.push(""),o.push("Component patterns:"),o.push("```json"),o.push(JSON.stringify(d,null,2)),o.push("```")),o.push(""),o.push("### Applied Model-Gap Details"),o.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),o.push("<novel>"),o.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),o.push("</novel>"),o.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),o.push("- `element`: What you are styling or creating"),o.push("- `decision`: What you actually implemented (specific values)"),o.push("- `reason`: Why this is novel (what is missing from the model)"),o.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),o.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(n?.designModel||(o.push(""),o.push("## Design Context"),o.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),i){let s=n?.screenshotPaths??{},a=new Map;for(let d of e.annotations){let l=d.pathname||new URL(e.url).pathname;a.has(l)||a.set(l,[]),a.get(l).push(d)}o.push(""),o.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,l]of a){o.push(""),o.push(`## Page: ${d}`);let v=s[d];v&&n?.provider!=="codex"?o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${v}`):!v&&n?.provider!=="codex"&&(Object.keys(s).length===0?(o.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${t}`),o.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):o.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let T={...e,annotations:l,styleModifications:e.styleModifications},b=Dn(T,n?.imagePaths,n?.attachmentFiles);b&&(o.push(""),o.push(b))}}else{let s=Dn(e,n?.imagePaths,n?.attachmentFiles);s&&(o.push(""),o.push(s))}return o.push(""),o.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),o.push(""),o.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),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(""),o.push("## Questions"),o.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),o.push('<question>What do you mean by "..."?</question>'),o.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),o.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),o.join(`
|
|
195
|
+
`)}function js(t){return t.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function As(t,e,n,o){let r=[];r.push("You are continuing work on a UI based on the developer's reply to your question."),r.push(""),n!=="codex"&&r.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${t}`);let i=e.find(s=>s.role==="human"&&s.feedbackContext);if(i?.feedbackContext&&(r.push(""),r.push(i.feedbackContext)),e.length>0){r.push(""),r.push("## Conversation History");let s=0;for(let a of e)a.role==="human"?(s++,a.replyToQuestion?(r.push(`### Round ${s} (human) \u2014 reply`),r.push(`"${a.replyToQuestion}"`)):(r.push(`### Round ${s} (human)`),a.feedbackSummary&&r.push(`Annotations: ${a.feedbackSummary}`))):a.question?(r.push(`### Round ${s} (assistant) \u2014 question`),r.push(`"${a.question}"`)):(r.push(`### Round ${s} (assistant)`),a.responseText&&r.push(`Response: ${a.responseText}`))}if(r.push(""),r.push("The developer answered your question. Continue working based on their reply."),r.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),r.push(""),r.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),o&&o.length>0){r.push(""),r.push("## Attached Images"),r.push("The developer attached reference images with their reply:");for(let s of o)r.push(`Attached image: use the Read tool to view the image at: ${s}`)}return r.push(""),r.push("## Resolution"),r.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),r.push("<resolution>"),r.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),r.push("</resolution>"),r.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),r.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),r.push(""),r.push("### Scope classification"),r.push("Each resolution MUST include scope fields:"),r.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),r.push("- `inferredScope`: What scope the change actually has, based on what you modified."),r.push("Scope has two dimensions:"),r.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),r.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),r.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),r.push("If you cannot confidently determine scope, set it to null."),r.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),r.push(""),r.push("## Questions"),r.push("If you still need clarification, output:"),r.push("<question>Your question here</question>"),r.push("You may output BOTH a <resolution> and a <question> in the same response."),r.join(`
|
|
196
|
+
`)}function Vl(t){if(typeof t!="object"||t===null)return!1;let e=t;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function Kl(t){if(typeof t!="object"||t===null||typeof t.annotationId!="string"||t.status!=="resolved"&&t.status!=="needs_review"||typeof t.summary!="string")return!1;let e=t;for(let n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!Vl(e[n]))return!1;return!0}function Ms(t){let n=[...t.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!n)return[];try{let o=JSON.parse(n);return(Array.isArray(o)?o:o&&typeof o=="object"&&Array.isArray(o.annotations)?o.annotations:[]).filter(Kl)}catch{return[]}}function Ql(t){let e=t.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(o=>{if(typeof o!="object"||o===null)return!1;let r=o;return(r.category==="token"||r.category==="component"||r.category==="element")&&typeof r.element=="string"&&typeof r.decision=="string"&&typeof r.reason=="string"}):[]}catch{return[]}}function Es(t,e){return e>0?Ql(t):[]}import{execFile as Xl}from"child_process";import{readdir as Yl,readFile as Zl,stat as ep}from"fs/promises";import{homedir as Nn}from"os";import{join as ot}from"path";var Co=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:_s()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:_s()}],Bn=[{id:"gpt-5.4",label:"GPT 5.4",source:"static"},{id:"gpt-5.3-codex",label:"Codex 5.3",source:"static"},{id:"gpt-5.3-codex-spark",label:"Spark 5.3",source:"static"}],Jn={id:"",label:"Default",source:"cli"},tp=/^\s*-\s+"([^"]+)"/;function np(t){let e=[],n=!1;for(let o of t.split(`
|
|
197
|
+
`)){if(/^\s*`model`:/.test(o)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(o))break;if(!n)continue;let r=o.match(tp);if(!r?.[1])continue;let i=r[1];e.push({id:i,label:Jr(i),source:"cli"})}return $o([Jn,...e])}function op(t){let e=JSON.parse(t);return(Array.isArray(e.models)?e.models:[]).filter(o=>o.visibility===void 0||o.visibility==="list").sort((o,r)=>{let i=typeof o.priority=="number"?o.priority:Number.MAX_SAFE_INTEGER,s=typeof r.priority=="number"?r.priority:Number.MAX_SAFE_INTEGER;return i-s}).flatMap(o=>{let r=typeof o.slug=="string"?o.slug:typeof o.id=="string"?o.id:"";if(!r)return[];let i=typeof o.display_name=="string"&&o.display_name.trim()?o.display_name.trim():Jr(r),s=Array.isArray(o.supported_reasoning_levels)?o.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.effort!="string"?[]:[{effort:l.effort,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0,a=Array.isArray(o.service_tiers)?o.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let l=d;return typeof l.id!="string"?[]:[{id:l.id,label:typeof l.name=="string"?l.name:l.id,...typeof l.description=="string"?{description:l.description}:{}}]}):void 0;return[{id:r,label:i,source:"cli",...typeof o.default_reasoning_level=="string"?{defaultReasoningLevel:o.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...a&&a.length>0?{speedTiers:a}:{}}]})}function _s(){return["low","medium","high","xhigh","max"].map(t=>({effort:t}))}function rp(t){let e=t.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return $o(e.map(n=>({id:n,label:Jr(n),source:"cli"})))}function Jr(t){if(!t)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"},n=t.replace(/-\d{8,}$/,"");if(e[t])return e[t];if(e[n])return e[n];let o=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(o){let i=o[1]==="sonnet"?"Sonn":dp(o[1]),s=o[2]&&o[3]?` ${o[2]}.${o[3]}`:"";return`${i}${s}${o[4]?" Fast":""}`}let r=n.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(r){let i=r[2]?`${r[1]}.${r[2]}`:r[1];return r[3]==="mini"?`Mini ${i}`:r[3]==="codex"?`Codex ${i}`:r[3]==="spark"?`Spark ${i}`:`GPT ${i}`}return n}async function Cs(t="copilot"){let e=await _o(t,["help","config"]),n=np(e);return n.length>1?n:[Jn]}async function $s(t="codex"){let e=await _o(t,["debug","models"]).catch(async()=>{let o=process.env.CODEX_HOME||ot(Nn(),".codex");return Ds(ot(o,"models_cache.json"))}),n=op(e);return n.length>0?$o([...n,...Bn]):Bn}async function Os(t="claude"){let e=ot(Nn(),".claude"),n=[ot(Nn(),".claude","stats-cache.json"),ot(Nn(),".claude","settings.json"),ot(Nn(),".claude.json"),ot(e,"cache","changelog.md")],[o,r,i]=await Promise.all([_o(t,["--help"]).catch(()=>""),_o(t,["--version"]).catch(()=>""),ip(e).catch(()=>[])]),s=ap([...n,...i]),a=await Promise.all(s.map(l=>Ds(l).catch(()=>""))),d=rp([o,r,...a].join(`
|
|
198
|
+
`));return $o([...Co,...d])}function _o(t,e,n=5e3){return new Promise((o,r)=>{Xl(t,e,{encoding:"utf-8",timeout:n},(i,s)=>{if(i){r(i);return}o(s)})})}async function Ds(t){return Zl(t,"utf-8")}async function ip(t){let e=[ot(t,"projects"),ot(t,"telemetry")],n=[];for(let o of e)await Ns(o,n,4);return n.sort((o,r)=>r.mtimeMs-o.mtimeMs).slice(0,80).map(o=>o.path)}async function Ns(t,e,n){if(n<0)return;let o;try{o=await Yl(t,{withFileTypes:!0})}catch{return}await Promise.all(o.map(async r=>{let i=ot(t,r.name);if(r.isDirectory()){await Ns(i,e,n-1);return}if(!(!r.isFile()||!sp(r.name)))try{let s=await ep(i);if(s.size>2e6)return;e.push({path:i,mtimeMs:s.mtimeMs})}catch{}}))}function sp(t){return t.endsWith(".json")||t.endsWith(".jsonl")||t.endsWith(".md")||t.endsWith(".txt")}function $o(t){let e=new Set,n=[];for(let o of t)e.has(o.id)||(e.add(o.id),n.push(o));return n}function ap(t){return[...new Set(t)]}function dp(t){return t.charAt(0).toUpperCase()+t.slice(1)}var Oo=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,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let i=this.queue.length-1;i>=0;i--)if(this.queue[i]?.threadId===e.threadId){n=i;break}}let o=n>=0?n+1:0,r=this.activeJobs.size+o+1;return this.queue.splice(o,0,e),this.processNext(),r}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(o=>o.threadId===e&&(!n||n(o)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,o){let r=this.bufferEvent(n,e);for(let i of this.listeners)i(r,n,o)}bufferEvent(e,n){let o=this.eventBuffers.get(e);o||(o={events:[],nextSeq:0},this.eventBuffers.set(e,o));let r={...n,seq:o.nextSeq++};return o.events.push(r),o.events.length>1e4&&o.events.splice(0,o.events.length-1e4),r}getBufferedEvents(e,n=-1){let o=this.eventBuffers.get(e),r=this.accumulators.get(e)??{response:"",thinking:""},i=this.activeJobs.has(e);if(!o)return null;let s=n<0?o.events:o.events.filter(a=>a.seq>n);return{jobId:e,events:s,currentSeq:o.nextSeq-1,accumulated:{...r},jobActive:i}}accumulateText(e,n,o){let r=this.accumulators.get(e);r||(r={response:"",thinking:""},this.accumulators.set(e,r)),r[n]+=o}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let o=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,o)}cancelJob(e){let n=this.activeProcesses.get(e),o=this.activeJobs.get(e);return!n||!o?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),o.status="error",o.error="Cancelled by user",this.broadcast({type:"error",jobId:o.id,threadId:o.threadId,message:"Cancelled by user",cancelled:!0,provider:o.provider,model:o.model},o.id,o.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);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 n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let o of n)try{o.kill("SIGTERM")}catch{}await Promise.all(n.map(o=>new Promise(r=>{let i=!1,s=()=>{i||(i=!0,r())};o.on("exit",s),o.on("error",s),setTimeout(()=>{if(!i){try{o.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let o of this.cleanupTimers.values())clearTimeout(o);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),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 cp}from"crypto";var on="<imprint-use>",Do="</imprint-use>";function lp(t){let e=Math.min(t.length,on.length-1);for(let n=e;n>0;n--)if(on.startsWith(t.slice(-n)))return n;return 0}function Bs(t,e,n,o,r=Date.now()){if(!t||typeof t!="object"||Array.isArray(t))return null;let i=t,s=Array.isArray(i.explanationIds)?i.explanationIds.filter(d=>typeof d=="string"&&!!d.trim()):[],a=[...new Set(s)].flatMap(d=>{let l=e?.explanations.find(v=>v.id===d);return l?[{id:l.id,kind:l.kind,statement:l.statement,state:l.state,scope:l.scope}]:[]});return a.length===0?null:{id:cp(),jobId:n,sequence:o,timestamp:r,explanations:a}}var No=class{constructor(e,n){this.jobId=e;this.context=n;this.buffer="";this.sequence=0;this.explanationIds=new Set;this.optionalClosePending=!1}takeNewExplanations(e){let n=e.explanations.filter(o=>!this.explanationIds.has(o.id));if(n.length===0)return null;for(let o of n)this.explanationIds.add(o.id);return{...e,sequence:this.sequence++,explanations:n}}push(e){this.buffer+=e;let n="",o=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let l=this.buffer.slice(d);if(Do.startsWith(l)&&l.length<Do.length||(l.startsWith(Do)&&(this.buffer=this.buffer.slice(d+Do.length)),this.optionalClosePending=!1,!this.buffer))break}let r=this.buffer.indexOf(on);if(r<0){let d=lp(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,r);let i=r+on.length,s=nn(this.buffer,i);if(s.status==="incomplete"){this.buffer=this.buffer.slice(r);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(i);continue}let a=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=Bs(JSON.parse(a),this.context,this.jobId,this.sequence);if(!d)continue;let l=this.takeNewExplanations(d);l&&o.push(l)}catch{}}return{visibleText:n,usages:o}}finalize(e){this.buffer="",this.optionalClosePending=!1;let n=[],o="",r=0;for(;r<e.length;){let i=e.indexOf(on,r);if(i<0){o+=e.slice(r);break}o+=e.slice(r,i);let s=i+on.length,a=nn(e,s);if(a.status!=="complete"){r=s;continue}try{let v=Bs(JSON.parse(e.slice(a.start,a.end)),this.context,this.jobId,this.sequence);if(v){let T=this.takeNewExplanations(v);T&&n.push(T)}}catch{}let l=e.slice(a.end).match(/^\s*<\/imprint-use>/)?.[0].length??0;r=a.end+l}return{visibleText:o.trim(),usages:n}}};function Ln(t,e){return t?.projectId===e.projectId&&t.version===e.version&&t.restartMode===e.restartMode}function Bo(t){return(Array.isArray(t)?t[0]:t)?.split(",")[0]?.trim()||void 0}function Lr(t){if(!t)return null;try{let e=new URL(t);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Js(t){let e=Lr(Bo(t.origin));if(e)return e;let n=Lr(Bo(t.referer));if(n)return n;let o=Bo(t["x-forwarded-host"]);if(!o)return null;let r=Bo(t["x-forwarded-proto"])==="https"?"https":"http";return Lr(`${r}://${o}`)}function Ls(t,e,n=5){let o=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...t].sort(o).slice(0,n),i=t.filter(d=>d.status==="applied"||d.status==="failed").sort(o).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),a=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:a,actionableProposals:s}}import{createHash as qo}from"crypto";import{mkdir as Fn,readFile as Nt,unlink as gp,writeFile as rn}from"fs/promises";import{dirname as Fo,extname as yp,join as Be}from"path";var pp={capacity:{label:"At capacity",message:"The model provider is temporarily unavailable. Try again shortly."},rate_limited:{label:"Rate limited",message:"The model provider is receiving too many requests. Try again shortly."},timeout:{label:"Timed out",message:"The model took too long to respond. Try again."},connection:{label:"Connection lost",message:"The model provider disconnected before the run completed. Try again."},authentication:{label:"Sign-in required",message:"The model provider needs to be authenticated before this run can continue."},failed:{label:"Failed",message:"The model could not complete this run. Try again, or inspect the job diagnostics if the problem continues."}};function up(t){let e=typeof t=="string"?t:(()=>{try{return JSON.stringify(t)}catch{return String(t??"")}})();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 qs(t,e){let n=e??up(t);return{kind:n,...pp[n]}}import{createHash as mp,randomUUID as fp}from"crypto";var Fs=t=>`${t}-${fp()}`;function qr(t,...e){return`${t}-${mp("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function Fr(t){return{schemaVersion:1,submissionIds:[Fs("submission")],jobId:t.jobId,threadId:t.threadId,artifactIds:[...new Set(t.artifactIds??[])]}}function qn(t,e=[],n){return{...t,outcomeId:t.outcomeId??Fs("outcome"),imprintEvidenceIds:[...new Set([...t.imprintEvidenceIds??[],...e])],...n?{imprintAssessment:n}:{}}}function hp(t){try{return new URL(t).pathname||"/"}catch{return"/"}}function Jo(t,e){return e?[`${t||"/"}:${e}`]:[]}function Us(t){let e=hp(t.url);return[...new Set([...t.annotations.flatMap(n=>Jo(n.pathname??e,n.linkedSelector)),...t.styleModifications.flatMap(n=>Jo(e,n.durableSelector??n.selector)),...(t.textModifications??[]).flatMap(n=>Jo(n.pathname??e,n.durableSelector??n.selector)),...(t.domModifications??[]).flatMap(n=>Jo(n.pathname??e,n.durableSelector??n.selector))])]}function zs(t,e){return[...new Set([`screenshot:${e}`,...t.annotations.map(n=>`annotation:${n.id}`),...t.annotations.flatMap(n=>(n.attachments??[]).map(o=>`attachment:${o.id}`))])]}function Lo(t,e){if(e.lifecycle?.schemaVersion===1)return!1;let n=qr("submission",t,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[n],jobId:e.jobId,threadId:t,artifactIds:[...(e.annotationIds??[]).map(o=>`annotation:${o}`),...e.screenshotPath?[qr("artifact",t,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:qr("outcome",t,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function Ur(t){let e=t.lifecycleVersion!==1;t.lifecycleVersion=1;for(let n of t.messages)e=Lo(t.id,n)||e;return e}function Hs(t){let e=t.messages.at(-1),n=[...t.messages].reverse().find(r=>r.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:t.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:t.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let o=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:n?.jobId,threadId:t.id,status:o?"waiting_input":"resolved",label:o?"Question":"Replied",outcomeId:n?.lifecycle?.outcomeId,imprintEvidenceIds:n?.lifecycle?.imprintEvidenceIds??[]}}var Ip={version:1,threads:{}},Ws=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],Un={version:2,updatedAt:0,files:{}};function wp(t){return JSON.stringify(t,null,2)}function vp(t){return Object.fromEntries(Ws.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}function bp(t){let e={...t};for(let n of Ws)delete e[n];return e}function sn(t){let e=t;if(t.error){let n=qs(t.error,t.errorKind);(t.error!==n.message||t.errorKind!==n.kind||t.responseText!==void 0)&&(e={...t,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=qt(e.result,!1),o=qt(e.turn?.result,!1);(n!==e.result||o!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...o?{result:o}:{}}}:{}})}return e}var Uo=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Be(e,".popmelt");this.legacyFilePath=Be(n,"threads.json"),this.threadsDir=Be(n,"threads"),this.indexPath=Be(this.threadsDir,"index.json"),this.artifactsDir=Be(n,"artifacts","thread-messages"),this.mediaDir=Be(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Nt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[r,i]of Object.entries(e.files)){let s=await this.readThread(Be(this.threadsDir,i));s&&(n[r]=s)}this.cache={version:1,threads:n};let o=!1;for(let r of Object.values(n))o=Ur(r)||o;return o&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Nt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,o])=>[n,{...o,messages:o.messages.map(sn)}]))},this.index={...Un,files:{},migratedFromLegacyAt:Date.now()};for(let n of Object.values(this.cache.threads))Ur(n);return await this.persistAll(),this.cache}}catch{}return this.cache={...Ip,threads:{}},this.index={...Un,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),o=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>o.has(s)))return r;return null}async createThread(e,n){let o=await this.load(),r={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return o.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(Lo(e,n),r.messages.push(sn(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;Lo(e,n);let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,sn(n)):r.messages.push(sn(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(a=>a.jobId===n);if(s.length===0)return!1;for(let a of s)if(Object.assign(a,o),a.error){let d=sn(a);Object.assign(a,d),delete a.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,o){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(a=>a.role==="assistant"&&a.jobId===n);return s?(Object.assign(s,o),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),o=Object.values(n.threads);return o.sort((r,i)=>i.updatedAt-r.updatedAt),o.slice(0,e).map(r=>{let s=r.messages.find(p=>p.role==="human")?.feedbackSummary||"[thread]",a=r.messages.filter(p=>p.role==="assistant"),d=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=r.messages.findLastIndex(p=>!!d(p)),v=r.messages.findLastIndex(p=>p.role==="human"),T=l>v?d(r.messages[l]):void 0,b=r.messages.at(-1)?.role,R=Array.from(new Set(r.messages.slice(0,Math.max(0,v)).filter(p=>p.role==="assistant"&&!!p.jobId).map(p=>p.jobId))),S=a.some(p=>!!p.responseText||!!p.question||!!p.result||!!p.memoryReviewCard||!!p.memoryReceipt),f=a.some(p=>!!p.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:S,hasError:f,lastMessageRole:b,pendingQuestion:T,acknowledgedJobIds:R,elementIdentifiers:r.elementIdentifiers,lifecycle:Hs(r)}})}async recoverInterruptedTurns(){let e=await this.load(),n=0;for(let o of Object.values(e.threads)){let r=o.messages.at(-1);if(!r||r.role!=="human"||/^(imprint|memory)-/.test(r.jobId))continue;let i=qn(r.lifecycle);r.queued&&await this.updateMessage(o.id,r.jobId,{queued:!1}),await this.appendMessage(o.id,{role:"assistant",timestamp:Date.now(),jobId:r.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:i}),n+=1}return n}async getThreadHistory(e,n=6){let o=await this.getThread(e);return!o||o.messages.length===0?[]:o.messages.length<=n?o.messages:[o.messages[0],...o.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await Nt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let o=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let a=await Nt(Be(Fo(this.legacyFilePath),r.path),"utf8");qo("sha256").update(a).digest("hex")===r.sha256&&(s=JSON.parse(a))}catch{}return sn({...i,...s})}));return{id:n.id,lifecycleVersion:n.lifecycleVersion,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:o}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=vp(e),o=bp(e);if(Object.keys(n).length===0)return o;let r=wp(n),i=qo("sha256").update(r).digest("hex"),s=Be("artifacts","thread-messages",`${i}.json`);await Fn(this.artifactsDir,{recursive:!0});try{await Nt(Be(Fo(this.legacyFilePath),s),"utf8")}catch{await rn(Be(Fo(this.legacyFilePath),s),r)}return{...o,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async o=>{if(Fo(o)===this.mediaDir)return o;try{let r=await Nt(o),i=qo("sha256").update(r).digest("hex"),s=Be(this.mediaDir,`${i}${yp(o)||".bin"}`);await Fn(this.mediaDir,{recursive:!0});try{await Nt(s)}catch{await rn(s,r)}return s}catch{return o}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([o,r])=>[o,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([o,r])=>[o,await Promise.all(r.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([o,r])=>[o,await Promise.all(r.map(async i=>({...i,path:await n(i.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await Fn(this.threadsDir,{recursive:!0});let n=this.index??{...Un,files:{}},o=n.files[e.id]??`${qo("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await rn(Be(this.threadsDir,o),JSON.stringify(i,null,2)),n.files[e.id]=o,n.updatedAt=Date.now(),this.index=n,await rn(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),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 Fn(this.threadsDir,{recursive:!0}),this.index=this.index??{...Un,files:{}},await rn(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...Un,files:{}},o=n.files[e];o&&await gp(Be(this.threadsDir,o)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await Fn(this.threadsDir,{recursive:!0}),await rn(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as xp,open as Sp,readFile as Pp,rename as kp,unlink as Tp}from"fs/promises";import{dirname as Rp,join as jp}from"path";var Gs={schemaVersion:1,theme:"auto",updatedAt:null};function Vs(t){return t==="light"||t==="dark"||t==="auto"?t:null}async function Ap(t,e){await xp(Rp(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;try{let o=await Sp(n,"w");try{await o.writeFile(`${JSON.stringify(e,null,2)}
|
|
199
|
+
`,"utf8"),await o.sync()}finally{await o.close()}await kp(n,t)}catch(o){throw await Tp(n).catch(()=>{}),o}}var zo=class{constructor(e){this.path=jp(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await Pp(this.path,"utf8")),n=Vs(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Gs}}}catch{return{exists:!1,preferences:{...Gs}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Ap(this.path,n),n}};function Ks(t){return Vs(t)!==null}function wt(t,e=240){if(!t)return;let n=t.replace(/\s+/g," ").trim();if(n)return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function an(t){return t?[wt(t.selector,400),wt(t.context,200),wt(t.reactComponent,120),wt(t.textContent)].filter(e=>!!e):[]}function zr(t){return[...new Set(t.filter(e=>!!e))]}function Qs(t,e){return zr([...e,...t.annotations.flatMap(n=>[wt(n.pathname,200),wt(n.linkedSelector,400),...n.elements.flatMap(an)]),...t.styleModifications.flatMap(n=>an(n.element)),...(t.textModifications??[]).flatMap(n=>an(n.element)),...(t.domModifications??[]).flatMap(n=>[...an(n.element),...an(n.sourceElement)])])}function Xs(t,e){let n=[...t].reverse().find(o=>o.annotationSnapshot)?.annotationSnapshot;return zr(n?[...e,...n.annotations.flatMap(o=>[wt(o.pathname,200),wt(o.linkedSelector,400),...o.elements.flatMap(an)])]:e)}function Mp(t){let e=t.instruction?.trim();return e?t.attachments?.some(o=>o.name?.trim()===e)?null:e:null}function Ys(t){let e=t.annotations.flatMap(r=>{let i=Mp(r);return i?[{instruction:i,pathname:r.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(r=>r.pathname).filter(Boolean)).size<=1)return e.map(r=>r.instruction).join(`
|
|
198
200
|
|
|
199
201
|
`);let o=new Map;for(let r of e){let i=r.pathname||"(unknown)",s=o.get(i)??[];s.push(r.instruction),o.set(i,s)}return[...o.entries()].map(([r,i])=>`\`${r}\`
|
|
200
202
|
${i.map(s=>`- ${s}`).join(`
|
|
201
203
|
`)}`).join(`
|
|
202
|
-
`)}var
|
|
203
|
-
`)}function zn(t){return[...new Set(t.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function
|
|
204
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let v=s??a??void 0,
|
|
205
|
-
`)}function
|
|
204
|
+
`)}var Zs={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 Ye=Zs.version;var zp=1111,Hp=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Wp=1800*1e3,Gp=3600*1e3,na=45e3,Vp=5e3,Kp=1e4,Qp=2*1024*1024;function oa(t){return t.length<=1?t[0]??"":["The developer sent these queued steering messages while you were working:","",...t.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
205
|
+
`)}function zn(t){return[...new Set(t.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function ra(t){let e=t.findLastIndex(r=>r.role==="assistant");if(e<0)return[];let n=t[e];if(!n?.question||!n.jobId.startsWith("imprint-"))return[];let o=t.slice(0,e).findLast(r=>r.role==="assistant"&&r.imprintSummary?.resolvedAction==="no"&&!!r.imprintSummary.grounding);return o?.imprintSummary?.grounding?[o.imprintSummary.grounding.explanationId]:[]}function Xp(t,e){if(e.size===1)return[...t].reverse().find(n=>{let o=n.imprintSummary;return n.role==="assistant"&&!!o?.grounding&&!o?.resolvedAction&&e.has(o.grounding.explanationId)})}function da(t){if(!t)return!1;try{let e=new URL(t);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Yp(t,e,n){let o=[...n];for(let r of t)if(r.type==="tool_use"){let i=r.tool||"",s=r.file??void 0,a=r.content??void 0,d=s?s.split("/").pop()??s:void 0,l;switch(i){case"Read":l=d?`Reading ${d}`:"Reading file";break;case"Edit":l=d?`Editing ${d}`:"Editing file";break;case"Write":l=d?`Writing ${d}`:"Writing file";break;case"Bash":l=a?a.split(`
|
|
206
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":l="Searching files";break;case"Grep":l="Searching code";break;case"WebFetch":l="Fetching page";break;case"WebSearch":l="Searching web";break;default:l=i?`Using ${i}`:"tool";break}let v=s??a??void 0,T=s?aa(s)?s:Fp(e,s):void 0,b=o[o.length-1];b&&b.kind==="tool_group"&&b.tool===i?b.items.push({label:l,detail:v,...T?{filePath:T}:{}}):o.push({kind:"tool_group",tool:i,items:[{label:l,detail:v,...T?{filePath:T}:{}}]})}return o}function Zp(t,e){if(t.processedIds.length===0&&t.success)return"No accepted decisions were ready for model projection.";if(t.success&&t.proposalId)return"";let n=[];return t.success?n.push("Model suggestion ready."):n.push("Model projection failed."),t.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.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"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),t.error&&(n.push(""),n.push(`Error: ${t.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
|
|
207
|
+
`)}function eu(t,e=96){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function ia(t){let e=t.styleModifications.flatMap(s=>{let a=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${a}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),n=(t.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),o=(t.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),r=t.annotations.map(s=>{let a=s.instruction?.trim();if(a)return a;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),i=[...e,...o,...n,...r].map(s=>eu(s)).filter(Boolean);return i.length===0?"Annotation":i.length<=3?i.join("; "):`${i.slice(0,3).join("; ")}; +${i.length-3} more`}function tu(t,e){let n=t.headers.origin;da(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}var nu=16384,ou=131072;async function Ce(t,e=nu){let n=[],o=0;for await(let i of t){let s=typeof i=="string"?Buffer.from(i):i;if(o+=s.length,o>e)throw new Error("Request body too large");n.push(s)}if(n.length===0)return{};let r=JSON.parse(Buffer.concat(n).toString("utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object");return r}async function ru(t,e){let n=[],o=0;for await(let r of t){let i=typeof r=="string"?Buffer.from(r):r;if(o+=i.length,o>e)throw new Error("Request body too large");n.push(i)}return Buffer.concat(n)}function iu(t,e){let n=t.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function su(t,e){if(!t)return e;let n=t.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,o,r,i]=n;return`\x1B[38;2;${parseInt(o,16)};${parseInt(r,16)};${parseInt(i,16)}m${e}\x1B[0m`}function Go(t,e){try{t.res.write(`event: ${e.type}
|
|
206
208
|
data: ${JSON.stringify(e)}
|
|
207
209
|
|
|
208
|
-
`)}catch{}}function dn(t){return t==="claude"||t==="codex"||t==="copilot"?t:void 0}async function
|
|
210
|
+
`)}catch{}}function dn(t){return t==="claude"||t==="codex"||t==="copilot"?t:void 0}async function Vo(t){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),o=await fetch(`http://127.0.0.1:${t}/status`,{signal:e.signal});return clearTimeout(n),o.ok?await o.json():null}catch{return null}}function au(t,e){return new Promise((n,o)=>{let r=s=>{t.removeListener("listening",i),o(s)},i=()=>{t.removeListener("error",r),n()};t.once("error",r),t.once("listening",i),t.listen(e,"127.0.0.1")})}async function Hn(t={}){let e=new Date().toISOString(),n=t.port??zp,o=t.projectRoot??process.cwd(),r=await Op(o).catch(()=>o),i=It(r),s=await Ht(r),a=t.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),d=t.tempDir??Je(Jp(),"popmelt-bridge"),l=t.maxTurns??40,v=t.maxBudgetUsd??1,T=[...t.allowedTools??Hp],b=t.claudePath??"claude",R=t.copilotPath??"copilot",S=t.provider??"codex",f=t.timeoutMs,p=t.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,g=t.restartMode??"embedded",w=n,u={},M={claude:b,codex:"codex",copilot:R};for(let[c,I]of Object.entries(M))try{let A=I.includes("/")?I:_p("which",[I],{encoding:"utf-8"}).trim();u[c]={available:!0,path:A}}catch{u[c]={available:!1,path:null}}function h(c,I){return new Promise(A=>{let y=ea(I,["--version"],{stdio:["ignore","ignore","ignore"]}),j=!1,k=$=>{j||(j=!0,A($))},O=setTimeout(()=>{y.kill("SIGTERM"),k(!0)},5e3);y.on("error",()=>{clearTimeout(O),k(!1)}),y.on("close",$=>{clearTimeout(O),k($===0)})})}await Promise.all([(async()=>{u.claude&&(u.claude.models=u.claude.available&&u.claude.path?await Os(u.claude.path).catch(()=>Co):Co)})(),(async()=>{u.codex&&(u.codex.models=u.codex.available&&u.codex.path?await $s(u.codex.path).catch(()=>Bn):Bn)})(),(async()=>{u.copilot&&(u.copilot.models=u.copilot.available&&u.copilot.path?await Cs(u.copilot.path).catch(()=>[Jn]):[Jn])})()]);let[m,E,D]=await Promise.all([vr(r),br(r),xr(r,u.copilot?.path??R)]);u.claude&&(u.claude.mcp=m),u.codex&&(u.codex.mcp=E),u.copilot&&(u.copilot.mcp=D),m.found&&m.name&&T.push(`mcp__${m.name}__*`),await Cp(d,{recursive:!0}),sa(d).catch(()=>{});let P=new Oo(1),C=new yo,z=new wo(na),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 c=++G,I=Date.now()+Kp,A=()=>{if(c!==G)return;if(z.size>0){x();return}if(!(P.isRunning||P.depth>0||C.isRunning||C.depth>0)||Date.now()>=I){Y=!1,X=setTimeout(Q,50),X.unref?.();return}X=setTimeout(A,250),X.unref?.()};A()},K=new Set,W=new Uo(r),B=await W.recoverInterruptedTurns();B>0&&console.warn(`[Popmelt] Recovered ${B} interrupted thread turn(s) from durable history.`);let V=new mo(r);V.sweep();let H=new Mo(r),ee=new vn(r,i);try{let c=await ee.store.migrateTopology();c.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${c.relationMutations} relation mutation(s)).`)}catch(c){console.warn(`[Popmelt] Imprint topology migration deferred: ${c instanceof Error?c.message:String(c)}`)}let Re=new zo(r),Le=new co(r),ue=new go(r,{claudePath:b,provider:S,timeoutMs:f,loadProjectableDecisions:c=>H.getProjectableDecisions(c),onEvent:c=>{for(let I of K)Go(I,c)}}),$e=new eo({projectRoot:r,threadStore:W,memoryService:H,imprintService:ee,loadConcreteModel:()=>ue.loadModel()});H.beginAutomaticInitialization({writerVersion:Ye}).then(async c=>{c.state==="ready"?(await H.migrateImprintSnapshot(),await H.syncImprintGraph(),await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),S!=="copilot"&&(await ue.getUnprojectedPatternDecisions()).length>0&&await Ze({provider:S,reason:"Project accepted decisions that were waiting when the bridge restarted"})):c.state==="degraded"&&console.warn(`[\u22B9 ${w}] Product memory is degraded; legacy preview remains available: ${c.error}`)});let St=20,fn=300*1e3,je=[];function it(){let c=Date.now()-fn;for(;je.length>0&&(je[0].completedAt<c||je.length>St);)je.shift()}let Pt=new Map,kt=null,Kn;P.addListener((c,I,A)=>{for(let y of K)(!A||!y.sourceId||y.sourceId===A)&&Go(y,c)}),C.addListener((c,I,A)=>{for(let y of K)(!A||!y.sourceId||y.sourceId===A)&&Go(y,c)}),C.setProcessor(async c=>{let I=c.provider??S;try{let A=await ue.run({provider:I,model:c.model,threadId:c.threadId,presentationJobId:c.id,agentSettings:c.agentSettings});if(c.status==="cancelled")return;let y=await ue.loadRuns(),j=A.runId?y.runs.find(O=>O.id===A.runId):void 0;if(A.success&&A.proposalId){let O=await ue.findModelProposal(A.proposalId),$=await ue.loadModel(),q=O?Hi(O,$):null;if(O&&q){let N=O.decisionIds.map(J=>({decisionId:J,status:"projected"}));await H.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 k=Zp(A,j);if(c.threadId&&(await W.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:k,model:c.model,provider:I})||await W.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:k,model:c.model,provider:I})),A.success)c.status="done",c.result=k,C.broadcast({type:"done",jobId:c.id,success:!0,responseText:k,threadId:c.threadId},c.id,c.sourceId),je.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),it();else{if(c.status="error",c.error=A.error??"Projection failed",c.threadId){let O=`Model projection failed.
|
|
209
211
|
|
|
210
212
|
${c.error}`;await W.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:O,error:c.error,model:c.model,provider:I})||await W.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:O,error:c.error,model:c.model,provider:I})}C.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:I,model:c.model},c.id,c.sourceId),je.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),it()}}catch(A){if(c.status==="cancelled")return;if(c.status="error",c.error=A instanceof Error?A.message:String(A),c.threadId){let y=`Model projection failed.
|
|
211
213
|
|
|
212
|
-
${c.error}`;await W.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:y,error:c.error,model:c.model,provider:I})||await W.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:y,error:c.error,model:c.model,provider:I})}C.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:I,model:c.model},c.id,c.sourceId),je.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),it()}}),
|
|
214
|
+
${c.error}`;await W.updateMessage(c.threadId,c.id,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:y,error:c.error,model:c.model,provider:I})||await W.appendMessage(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:y,error:c.error,model:c.model,provider:I})}C.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:c.error,provider:I,model:c.model},c.id,c.sourceId),je.push({id:c.id,status:"error",completedAt:Date.now(),error:c.error,threadId:c.threadId,annotationIds:c.annotationIds,color:"#000000",kind:"project_model"}),it()}}),P.setProcessor(async c=>{let I=c,A=I._replyPrompt,y=I._replyText,j=I._replyImagePaths,k=c.provider??S,O=!!(c.surfacedProposalIds?.length&&A),$=!O&&!["synthesize","project_model"].includes(c.kind??"");c.threadId&&y!==void 0&&await W.updateMessage(c.threadId,c.id,{queued:!1});let q;if(c.threadId){let ne=await W.getThread(c.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&&A){if(N=y??A,j&&j.length>0){N+=`
|
|
213
215
|
|
|
214
216
|
The developer attached reference images with their reply:`;for(let ne of j)N+=`
|
|
215
217
|
Attached image: use the Read tool to view the image at: ${ne}`}c.kind==="synthesize"?N+=`
|
|
@@ -218,41 +220,41 @@ Continue the project workflow from the previous instructions. If the developer a
|
|
|
218
220
|
|
|
219
221
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
220
222
|
|
|
221
|
-
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(
|
|
223
|
+
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(k!=="codex"?`
|
|
222
224
|
|
|
223
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${c.screenshotPath}`:"");else{let ne=!A&&c.threadId?await W.getThreadHistory(c.threadId):void 0,Ie=A?null:await ue.loadModel();N=A??
|
|
225
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${c.screenshotPath}`:"");else{let ne=!A&&c.threadId?await W.getThreadHistory(c.threadId):void 0,Ie=A?null:await ue.loadModel();N=A??Rs(c.screenshotPath,c.feedback,{threadHistory:ne&&ne.length>0?ne:void 0,provider:k,imagePaths:c.imagePaths,attachmentFiles:c.attachmentFiles,designModel:Ie??void 0,screenshotPaths:c.screenshotPaths})}N+=wn(c.memoryReview),$&&(N+=xn(c.imprintContext,{requestText:y??Ft(c.feedback)})),c.threadId&&!O&&(N+=`
|
|
224
226
|
|
|
225
|
-
${
|
|
227
|
+
${Ts}`),N+=`
|
|
226
228
|
|
|
227
|
-
${Ps}`;let J=ou(c.color,`[\u22B9 ${w}:${c.id}]`),he=c.screenshotPaths&&Object.keys(c.screenshotPaths).length>0?`${Object.keys(c.screenshotPaths).length} pages [${Object.keys(c.screenshotPaths).join(", ")}]`:c.screenshotPath;console.log(`${J} Reviewing ${he} (provider: ${T})${c.threadId?` (thread: ${c.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let U=new Mo(c.id),se=new Do(c.id,c.imprintContext),me=(ne,Ie)=>{if(ne.type==="delta"&&"text"in ne){let De=se.push(ne.text),Fe=U.push(De.visibleText);Fe.visibleText&&(k.accumulateText(Ie,"response",Fe.visibleText),k.broadcast({...ne,text:Fe.visibleText},Ie,c.sourceId));for(let _e of Fe.orientations)k.broadcast({type:"orientation",jobId:Ie,orientation:_e},Ie,c.sourceId);for(let _e of De.usages)k.broadcast({type:"imprint_used",jobId:Ie,usage:_e},Ie,c.sourceId);return}else ne.type==="thinking"&&"text"in ne&&k.accumulateText(Ie,"thinking",ne.text);k.broadcast(ne,Ie,c.sourceId)},{process:te,result:ge}=T==="codex"?so(c.id,{prompt:N,projectRoot:r,screenshotPath:c.screenshotPath,resumeSessionId:q,model:c.model,sandboxMode:O?"read-only":void 0,configOverrides:to(c.agentSettings),onEvent:me}):T==="copilot"?Ni(c.id,{prompt:N,projectRoot:r,resumeSessionId:q,model:c.model,timeoutMs:f,copilotPath:u.copilot?.path??R,onEvent:me}):no(c.id,{prompt:N,projectRoot:r,maxTurns:l,maxBudgetUsd:v,allowedTools:O?["Read"]:x,claudePath:b,resumeSessionId:q,model:c.model,reasoningEffort:c.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:me});k.setActiveProcess(c.id,te);let re=await ge,we=[...(re.fileEdits??[]).map(ne=>ne.file_path),...(re.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],ke=se.finalize(re.text),pe=Nr(ke.visibleText,c.id),Z=U.finalize(ke.visibleText),Pe=pe.visibleText,We=As(Pe),ye=$?bn(Pe,{context:c.imprintContext,requestText:y??Ut(c.feedback),applicationOccurred:we.length>0||We.some(ne=>ne.status==="resolved")}):{visibleText:Pe,draft:void 0,error:void 0},Ge=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)k.broadcast({type:"orientation",jobId:c.id,orientation:ne},c.id,c.sourceId);for(let ne of ke.usages)k.broadcast({type:"imprint_used",jobId:c.id,usage:ne},c.id,c.sourceId);if(c.result=Ge,re.success){console.log(`${J} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${J} Captured ${re.fileEdits.length} file edit(s): ${re.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),re.editEvents&&re.editEvents.length>0&&console.log(`${J} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),c.status="done";let ne=Rs(Pe),Ie=We;if(Ie.length>0&&c.annotationIds&&c.annotationIds.length>0){let de=new Set(c.annotationIds);Ie.every(et=>de.has(et.annotationId))||(Ie=Ie.map((et,jt)=>({...et,annotationId:c.annotationIds[jt%c.annotationIds.length]})))}let De=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):re.toolsUsed,Fe=k.getBufferedEvents(c.id),_e=Xp(Fe?.events??[],r,pe.segments),Me,ie=vs(Pe),F=ws(Pe);if(F)if(!(c.memoryReview?.packets.some(ce=>ce.proposalId===F.proposalId)||c.surfacedProposalIds?.includes(F.proposalId)))Me={status:"rejected",action:F.action,proposalId:F.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Me=await H.commitConversationalReview(F)}catch(ce){Me={status:"rejected",action:F.action,proposalId:F.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=Ms(Pe,we.length),fe,Ve,si,ai,td=c.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??[]],et=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];ce.length>0&&(si=[...new Set(ce)]),et.length>0&&(ai=[...new Set(et)])}ye.draft?.decision==="none"&&ee.recordNoop(ye.draft.reason);let Xn=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Xn&&!F&&!ie){let de=c.imprintContext?.explanations.find(ce=>ce.id===Xn.explanationId&&ce.state==="grounded");de?Ve={explanationId:de.id,title:Xn.summary.title,detail:Xn.summary.detail,statement:de.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Yo=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(c.threadId&&Yo&&!F&&!ie)try{fe=await ee.capture(Yo,{threadId:c.threadId,jobId:c.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:td,applicationOccurred:we.length>0||Ie.some(de=>de.status==="resolved")}),fe?(Ae={state:"mutated"},await H.recordImprintEvidence({summary:fe,threadId:c.threadId,jobId:c.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 Yo&&(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 Zo=fe?.transactionId;if(c.threadId&&fe&&!fe.grounding){let de=await W.getThread(c.threadId),ce=new Set(fe.changes.map(jt=>jt.explanationId)),et=de?Qp(de.messages,ce):void 0;if(et?.imprintSummary){let jt=et.imprintSummary;await W.updateAssistantMessage(c.threadId,et.jobId,{imprintSummary:{...jt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(jt.additionalObservationCount??0)+1,coalescedTransactionIds:[...jt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let er=yn({question:ne,resolutions:Ie,changedFiles:we,decisionRequired:!!ie,imprintTransactionId:Zo,groundingRequired:!!fe?.grounding}),nd=_e?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Lt=c.lifecycle?qn(c.lifecycle,Zo?[Zo]:[],Ae):void 0;if(c.threadId){let de=O?ie?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ge;await W.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:de,resolutions:!O&&Ie.length>0?Ie:void 0,question:O?void 0:ne??void 0,sessionId:re.sessionId,toolsUsed:O?void 0:De,editEvents:!O&&re.editEvents&&re.editEvents.length>0?re.editEvents:void 0,segments:!O&&_e&&_e.length>0?_e:void 0,turn:{phase:"complete",orientation:nd,result:er},result:er,memoryReviewCard:ie??void 0,memoryReceipt:Me,imprintSummary:fe,imprintRecognition:Ve,imprintUsedExplanationIds:si,imprintAppliedExplanationIds:ai,modelDetails:ae.length>0?ae:void 0,model:c.model,provider:T,...Lt?{lifecycle:Lt}:{}})}if(c.threadId&&!F&&!c.surfacedProposalIds?.length&&c.kind!=="project_model"){let de=c.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await H.captureCompletedJob({jobId:c.id,threadId:c.threadId,createdAt:c.createdAt,completedAt:Date.now(),requestSummary:y??(Ut(c.feedback)||"[request unavailable]"),responseSummary:ne??Ge,outcome:ne?"question_asked":Ie.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:T,model:c.model,sessionId:re.sessionId},subjectHints:de,filePaths:[...(re.fileEdits??[]).map(ce=>ce.file_path),...(re.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>sa(ce)?Lp(r,ce):ce),resolutions:Ie.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:c.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Lt?.submissionIds,outcomeId:Lt?.outcomeId,imprintEvidenceIds:Lt?.imprintEvidenceIds,imprintAssessment:Lt?.imprintAssessment})}catch(ce){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}Me?.status==="committed"&&Me.decisionId&&T!=="copilot"&&await Ze({provider:T,model:c.model,agentSettings:c.agentSettings,threadId:c.threadId,annotationIds:c.annotationIds,sourceId:c.sourceId,reason:`Project accepted decision ${Me.decisionId}`}),ne&&(console.log(`${J} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${K.size} SSE clients (threadId=${c.threadId??c.id}, annotationIds=${c.annotationIds?.join(",")??"none"})`),k.broadcast({type:"question",jobId:c.id,threadId:c.threadId??c.id,question:ne,annotationIds:c.annotationIds},c.id,c.sourceId)),ae.length>0&&(console.log(`${J} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),k.broadcast({type:"novel_patterns",jobId:c.id,patterns:ae,threadId:c.threadId},c.id,c.sourceId)),k.broadcast({type:"done",jobId:c.id,success:!0,resolutions:Ie.length>0?Ie:void 0,responseText:Ge,threadId:c.threadId,annotationIds:c.annotationIds,result:er},c.id,c.sourceId),je.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds})}else console.error(`${J} Error: ${re.error}`),c.status="error",c.error=re.error,c.threadId&&await W.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,error:re.error||"Unknown error",model:c.model,provider:T,...c.lifecycle?{lifecycle:qn(c.lifecycle)}:{}}),k.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:re.error||"Unknown error",provider:T,model:c.model,recoverable:re.recoverableError,code:re.errorCode},c.id,c.sourceId),je.push({id:c.id,status:"error",completedAt:Date.now(),error:re.error,threadId:c.threadId,annotationIds:c.annotationIds});it()});let xe=Np(async(c,I)=>{if(eu(c,I),c.method==="OPTIONS"){I.writeHead(204),I.end();return}let A=c.url||"/",y=A.split("?")[0],j=new URL(A,`http://127.0.0.1:${w}`),T=j.pathname,O=nu(c,j);if(O&&O!==i){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:O,projectName:Ho(r)});return}if(T.startsWith("/ambient/")&&O!==i){_(I,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:O});return}if(c.headers.origin){if(!aa(c.headers.origin)){_(I,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(O!==i){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:O,projectName:Ho(r)});return}}try{if(T.startsWith("/ambient/"))await mt(c,I,T);else if(c.method==="POST"&&T==="/draft-attachments"){let $=j.searchParams.get("annotationId")?.trim()??"",q=j.searchParams.get("name")?.trim()??"",N=j.searchParams.get("kind"),J=String(c.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 tu(c,Kp);if(he.length===0){_(I,400,{error:"Attachment is empty."});return}let U=await V.stage({annotationId:$,name:q,mimeType:J,kind:N,data:he});_(I,201,{attachment:{id:U.id,name:U.name,mimeType:U.mimeType,size:U.size,kind:U.kind}})}else if(c.method==="POST"&&T==="/draft-attachments/claim"){let $=await Ce(c),q=Array.isArray($.ids)?$.ids.filter(N=>typeof N=="string").slice(0,100):[];await V.claim(q),_(I,200,{ok:!0})}else if(c.method==="DELETE"&&T.startsWith("/draft-attachments/"))await V.release([T.slice(19)]),_(I,200,{ok:!0});else if(c.method==="POST"&&T==="/send")await ft(c,I);else if(c.method==="POST"&&T==="/capture/native"){if(!p){_(I,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await Ce(c),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 ns(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(c.method==="GET"&&T==="/events")Tt(c,I);else if(c.method==="GET"&&T==="/status")await Ko(c,I,O);else if(c.method==="GET"&&T==="/ui-preferences")await hn(I);else if(c.method==="PATCH"&&T==="/ui-preferences")await qe(c,I);else if(c.method==="PATCH"&&T==="/config")await Qo(c,I);else if(c.method==="POST"&&T==="/leases"){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Ce(c),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}S();let J=z.acquire(q,N);_(I,201,{ok:!0,lease:J,ttlMs:ta})}catch{_(I,400,{error:"Invalid lease request."})}}else if(T.startsWith("/leases/")&&(c.method==="PATCH"||c.method==="DELETE")){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(T.slice(8))}catch{_(I,400,{error:"Invalid lease id."});return}if(!$){_(I,400,{error:"A lease id is required."});return}if(c.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(c.method==="POST"&&T==="/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(c.method==="POST"&&T==="/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{}xe.close(()=>{Zs(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(c.method==="GET"&&T==="/capabilities")_(I,200,{providers:u});else if(T.startsWith("/imprint/"))await st(c,I,T);else if(T.startsWith("/memory/"))await Oe(c,I,T);else if(c.method==="POST"&&T==="/mcp/install")await Fa(c,I);else if(c.method==="POST"&&T==="/reply")await ht(c,I);else if(c.method==="POST"&&T==="/cancel")Ue(c,I);else if(c.method==="POST"&&T==="/materialize")_(I,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(c.method==="GET"&&T==="/materialization-runs")_(I,410,{error:"Use /projection-runs."});else if(c.method==="GET"&&T==="/projection-runs"){let $=await ue.loadRuns();_(I,200,$)}else if(c.method==="GET"&&T==="/projection/proposals"){let $=await ue.loadModelProposals();_(I,200,$)}else if(c.method==="POST"&&T.startsWith("/projection/proposals/")&&T.endsWith("/apply-selected")){let $=T.slice(22,-15);await Rt($,c,I)}else if(c.method==="POST"&&T.startsWith("/projection/proposals/")&&T.endsWith("/apply")){let $=T.slice(22,-6);await Jt($,I)}else if(c.method==="POST"&&T.startsWith("/projection/proposals/")&&T.endsWith("/dismiss")){let $=T.slice(22,-8);await Xo($,c,I)}else if(T.startsWith("/model/proposals/"))_(I,410,{error:"Use /projection/proposals."});else if(c.method==="POST"&&T==="/model/component")await za(c,I);else if(c.method==="DELETE"&&T==="/model/component")await Ha(c,I);else if(c.method==="PATCH"&&T==="/model/token")await Wa(c,I);else if(c.method==="DELETE"&&T==="/model/token")await Ga(c,I);else if(c.method==="POST"&&T==="/model/consolidate")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="POST"&&T==="/model/synthesize")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="GET"&&T==="/model"){let $=await ue.loadModel();_(I,200,{model:$})}else if(c.method==="GET"&&T.startsWith("/jobs/")&&T.endsWith("/events")){let $=T.slice(6,T.length-7),q=parseInt(j.searchParams.get("afterSeq")??"-1",10),N=k.getBufferedEvents($,isNaN(q)?-1:q);N?_(I,200,N):_(I,404,{error:"Unknown job"})}else if(c.method==="GET"&&y.startsWith("/files/"))await Xa(y.slice(7),I);else if(c.method==="GET"&&T==="/threads/recent"){let $=Math.min(Math.max(parseInt(j.searchParams.get("limit")??"5",10)||5,1),20),q=await W.listRecent($);_(I,200,q)}else if(c.method==="GET"&&T.startsWith("/decision/")){let $=T.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(I,400,{error:"Invalid decision id"});else{let q=await W.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 Le.loadDecision($);J?_(I,200,{decision:J,authority:"legacy_archive"}):_(I,404,{error:"Decision not found"})}}}else if(c.method==="GET"&&T.startsWith("/thread/")){let $=T.slice(8);await Ya($,I)}else if(c.method==="DELETE"&&T.startsWith("/thread/")){let $=T.slice(8);await Za($,I)}else c.method==="GET"&&(T==="/canvas"||T==="/canvas/")?Va(c,I):c.method==="GET"&&T==="/canvas/manifest"?await Ka(I):c.method==="GET"&&T==="/canvas/app.mjs"?await Qa(I):_(I,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(I,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function mt(c,I,A){if(c.method!=="POST"){_(I,405,{error:"Ambient endpoints accept POST requests only."});return}let y=await Ce(c),j=typeof y.sessionId=="string"?y.sessionId.trim():"",T=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 $e.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 J=Array.isArray(y.semanticCandidates)?y.semanticCandidates.flatMap(U=>{if(!U||typeof U!="object"||Array.isArray(U))return[];let se=U,me=typeof se.claim=="string"?se.claim.trim():"",te=typeof se.proposedKind=="string"&&["principle","preference","rule","constraint"].includes(se.proposedKind)?se.proposedKind:void 0;return me?[{claim:me,rationale:typeof se.rationale=="string"?se.rationale.trim():void 0,proposedKind:te,sourceText:typeof se.sourceText=="string"?se.sourceText.trim():void 0}]:[]}).slice(0,8):[],he=await $e.assess({threadId:$,jobId:q,assessmentText:N,semanticCandidates:J});_(I,he.status==="recorded"?200:404,he);return}if(!j||!T||j.length>256||T.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 $e.prepare({sessionId:j,turnId:T,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 $e.recordEvent({sessionId:j,turnId:T,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 $e.complete({sessionId:j,turnId:T,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 Oe(c,I,A){try{if(c.method==="GET"&&A==="/memory/status"){_(I,200,await H.status());return}if(c.method==="GET"&&A==="/memory/diagnostics"){_(I,200,await H.diagnostics());return}if(c.method==="GET"&&A==="/memory/model-view"){_(I,200,await H.getModelView());return}if(c.method==="GET"&&A==="/memory/imprint-view"){let y=await W.load(),j=[...new Set(Object.values(y.threads).flatMap(T=>zn(T.messages)))];_(I,200,await H.getImprintView(j,new Set(Object.keys(y.threads))));return}if(c.method==="POST"&&A==="/memory/constraints"){let y=await Ce(c),j=typeof y.reactComponent=="string"?y.reactComponent.trim():"",T=await H.getModelView(),O=j?T.entries.filter($=>$.key===`components.${j}`||$.key.startsWith(`components.${j}.`)):[];_(I,200,{modelEntries:O});return}if(c.method==="POST"&&A==="/memory/conversation-action"){let y=await Ce(c),j=typeof y.threadId=="string"?y.threadId:"",T=typeof y.proposalId=="string"?y.proposalId:"",O=String(y.action);if(!j||!T||!["accept","edit_and_accept","reject","defer"].includes(O)){_(I,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await W.getThread(j),q=$?.messages.find(pe=>pe.memoryReviewCard?.proposalId===T)?.memoryReviewCard,N=$?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===T),J=$?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await H.findPendingProposalsForThread(j)).find(pe=>pe.proposalId===T):void 0,he=typeof y.kind=="string"&&["principle","preference","rule","constraint"].includes(y.kind)?y.kind:void 0,U=q?.kind??N?.proposedKind??J?.proposedKind??he;if(!$||!q&&!N&&!J){_(I,409,{error:"This decision candidate was not surfaced in the thread."});return}if((O==="accept"||O==="edit_and_accept")&&!U){_(I,400,{error:"The decision kind is required to accept this candidate."});return}let se=await ue.findModelProposalsByThread(j),me=(await Promise.all(se.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Z=>H.findPendingProposalForLegacyDecision(Z)))).some(Z=>Z?.proposalId===T)})))).find(pe=>pe.matches)?.proposal,te={proposalId:T,action:O,kind:U,claim:O==="edit_and_accept"&&typeof y.claim=="string"?y.claim.trim():void 0,reason:O==="defer"?void 0:`The owner explicitly chose ${O.replaceAll("_"," ")} from the decision review card.`,taskContext:O==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:O==="defer"?["different_action","owner_request"]:void 0};if(te.action==="edit_and_accept"&&!te.claim){_(I,400,{error:"Edited decision wording is required."});return}let ge=await H.commitConversationalReview(te),re=`memory-${pt().slice(0,8)}`,we=O==="accept"?"> Accepted decision":O==="edit_and_accept"?"> Edited and accepted decision":O==="reject"?"> Rejected decision":"> Deferred decision";await W.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:re,replyToQuestion:we}),await W.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:re,responseText:"",memoryReceipt:ge,provider:dn(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 ke=dn(typeof y.provider=="string"?y.provider:void 0);ge.status==="committed"&&ge.decisionId&&ke!=="copilot"&&await Ze({provider:ke,model:typeof y.model=="string"?y.model:void 0,agentSettings:Wt(y),threadId:j,reason:`Project accepted decision ${ge.decisionId}`}),_(I,ge.status==="committed"?200:409,{receipt:ge});return}if(c.method==="POST"&&A==="/memory/analyze"){let y=await Ce(c),j=await H.analyzeLegacy({projectKey:typeof y.projectKey=="string"?y.projectKey:void 0}),T=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:T});return}if(c.method==="POST"&&A==="/memory/review"){let y=await Ce(c),j=await H.review($r(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(c.method==="POST"&&A==="/memory/context"){let y=await Ce(c),j=await H.contextualize($r(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(c.method==="POST"&&A==="/memory/initialize"){let y=await Ce(c),j=await H.initializeFromLegacy({confirmed:y.confirm===!0,projectKey:typeof y.projectKey=="string"?y.projectKey:void 0,writerVersion:Ye});_(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(c.method==="POST"&&A==="/memory/plan"){let y=await Ce(c),j=await H.planReview(Cr(y.command),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,j.result.ok?200:422,j);return}if(c.method==="POST"&&A==="/memory/commit"){let y=await Ce(c),j=y.transaction&&typeof y.transaction=="object"&&!Array.isArray(y.transaction)?y.transaction:{},T=await H.commitReview(Cr(y.command),{transactionId:typeof j.transactionId=="string"?j.transactionId:"",committedAt:typeof j.committedAt=="string"?j.committedAt:""});_(I,200,{status:await H.status(),journal:T.report});return}if(c.method==="POST"&&A==="/memory/recover"){let y=await Ce(c),j=await H.recover(y.confirm===!0);_(I,200,{status:await H.status(),journal:j.report});return}_(I,404,{error:"Memory endpoint not found."})}catch(y){let j=y instanceof Error?y.message:String(y),T=/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(T||O){_(I,T?409:400,{error:j});return}throw y}}async function st(c,I,A){if(c.method==="GET"&&A==="/imprint/status"){let[y,j]=await Promise.all([ee.store.load(),W.load()]),T=[...new Set(Object.values(j.threads).flatMap(O=>zn(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:T.length,recoveredTransactions:y.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e});return}if(c.method==="POST"&&A==="/imprint/action"){let y=await Ce(c),j=typeof y.threadId=="string"?y.threadId:"",T=typeof y.transactionId=="string"?y.transactionId:"",O=String(y.action);if(!j||!T||!["yes","this_time","no"].includes(O)){_(I,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await W.getThread(j),N=[...q?.messages??[]].reverse().find(te=>te.role==="assistant"&&te.imprintSummary?.transactionId===T),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-${pt().slice(0,8)}`;await ee.applyGroundingAction({summary:J,action:O,threadId:j,jobId:he}),O!=="no"&&await H.recordImprintEvidence({summary:J,action:O,threadId:j,jobId:he}).catch(te=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",te));let U=qt(N.result,!!N.question),se=N.turn?{...N.turn,result:qt(N.turn.result,!!N.question)}:void 0;await W.updateAssistantMessage(j,N.jobId,{imprintSummary:{...J,resolvedAction:O},...U?{result:U}:{},...se?{turn:se}:{}});let me={yes:"> Yes",this_time:"> This time",no:"> No"};if(await W.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=yn({question:te});await W.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 ft(c,I){let{screenshot:A,feedback:y,color:j,provider:T,model:O,reasoningEffort:$,serviceTier:q,sourceId:N,pastedImages:J,pageScreenshots:he}=await Or(c),U;try{U=JSON.parse(y)}catch{_(I,400,{error:"Invalid feedback JSON"});return}let se=U.annotations.flatMap(ie=>(ie.attachments??[]).map(F=>({id:F.id,annotationId:ie.id}))),me;try{me=se.length>0?await V.promote(se):void 0}catch(ie){_(I,409,{error:ie instanceof Error?ie.message:"Draft attachment unavailable."});return}let te=pt().slice(0,8),ge={};if(he.length>0)for(let ie of he){let F=encodeURIComponent(ie.pathname),ae=Je(d,`screenshot-${te}-${F}.webp`);await zo(ae,ie.data),ge[ie.pathname]=ae}let re=Je(d,`screenshot-${te}.webp`);await zo(re,A);let we={};if(J.length>0)for(let ie of J){let F=Je(d,`pasted-${te}-${ie.annotationId}-${ie.index}.webp`);await zo(F,ie.data),we[ie.annotationId]||(we[ie.annotationId]=[]),we[ie.annotationId].push(F)}let ke=Us(U),pe;if(ke.length>0){let ie=await W.findContinuationThread(ke);ie?(pe=ie.id,await W.addElementIdentifiers(pe,ke)):pe=(await W.createThread(`thread-${pt()}`,ke)).id}else pe=(await W.createThread(`thread-${pt()}`,[])).id;let Z=U.annotations.map(ie=>ie.id),Pe=Object.keys(ge).length>0,We=await In(H,U,ke,ie=>console.warn(`[\u22B9 ${w}:${te}] Contextual memory unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))),ye=(await W.getThread(pe))?.messages??[],Ge=await ee.contextualize({text:Ut(U),subjectHints:Ks(U,ke),pendingGroundingExplanationIds:zn(ye),correctionExplanationIds:oa(ye)}).catch(ie=>{console.warn(`[\u22B9 ${w}:${te}] Imprint context unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))}),Ae=qr({jobId:te,threadId:pe,artifactIds:Fs(U,te)}),ne={id:te,status:"queued",screenshotPath:re,feedback:U,createdAt:Date.now(),color:j,threadId:pe,annotationIds:Z,provider:dn(T),model:O||void 0,agentSettings:Wt({reasoningEffort:$,serviceTier:q}),...Object.keys(we).length>0?{imagePaths:we}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:N||void 0,...Pe?{screenshotPaths:ge}:{},...We?{memoryReview:We}:{},...Ge?{imprintContext:Ge}:{},lifecycle:Ae},Ie=new Set(U.annotations.map(ie=>ie.pathname).filter(Boolean)),De;if(Ie.size>1){let ie=new Map;for(let F of U.annotations){let ae=F.pathname||"(unknown)";ie.has(ae)||ie.set(ae,[]),ie.get(ae).push(F.instruction||ra({...U,annotations:[F]}))}De=[...ie.entries()].map(([F,ae])=>`\`${F}\`
|
|
229
|
+
${ks}`;let J=su(c.color,`[\u22B9 ${w}:${c.id}]`),he=c.screenshotPaths&&Object.keys(c.screenshotPaths).length>0?`${Object.keys(c.screenshotPaths).length} pages [${Object.keys(c.screenshotPaths).join(", ")}]`:c.screenshotPath;console.log(`${J} Reviewing ${he} (provider: ${k})${c.threadId?` (thread: ${c.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let F=new Eo(c.id),se=new No(c.id,c.imprintContext),me=(ne,Ie)=>{if(ne.type==="delta"&&"text"in ne){let De=se.push(ne.text),Ue=F.push(De.visibleText);Ue.visibleText&&(P.accumulateText(Ie,"response",Ue.visibleText),P.broadcast({...ne,text:Ue.visibleText},Ie,c.sourceId));for(let _e of Ue.orientations)P.broadcast({type:"orientation",jobId:Ie,orientation:_e},Ie,c.sourceId);for(let _e of De.usages)P.broadcast({type:"imprint_used",jobId:Ie,usage:_e},Ie,c.sourceId);return}else ne.type==="thinking"&&"text"in ne&&P.accumulateText(Ie,"thinking",ne.text);P.broadcast(ne,Ie,c.sourceId)},{process:te,result:ge}=k==="codex"?ao(c.id,{prompt:N,projectRoot:r,screenshotPath:c.screenshotPath,resumeSessionId:q,model:c.model,sandboxMode:O?"read-only":void 0,configOverrides:no(c.agentSettings),onEvent:me}):k==="copilot"?Bi(c.id,{prompt:N,projectRoot:r,resumeSessionId:q,model:c.model,timeoutMs:f,copilotPath:u.copilot?.path??R,onEvent:me}):oo(c.id,{prompt:N,projectRoot:r,maxTurns:l,maxBudgetUsd:v,allowedTools:O?["Read"]:T,claudePath:b,resumeSessionId:q,model:c.model,reasoningEffort:c.agentSettings?.reasoningEffort,timeoutMs:f,onEvent:me});P.setActiveProcess(c.id,te);let re=await ge,we=[...(re.fileEdits??[]).map(ne=>ne.file_path),...(re.editEvents??[]).flatMap(ne=>ne.filePath?[ne.filePath]:[])],ke=se.finalize(re.text),pe=Br(ke.visibleText,c.id),Z=F.finalize(ke.visibleText),Pe=pe.visibleText,We=Ms(Pe),ye=$?bn(Pe,{context:c.imprintContext,requestText:y??Ft(c.feedback),applicationOccurred:we.length>0||We.some(ne=>ne.status==="resolved")}):{visibleText:Pe,draft:void 0,error:void 0},Ge=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)P.broadcast({type:"orientation",jobId:c.id,orientation:ne},c.id,c.sourceId);for(let ne of ke.usages)P.broadcast({type:"imprint_used",jobId:c.id,usage:ne},c.id,c.sourceId);if(c.result=Ge,re.success){console.log(`${J} Iteration complete`),re.fileEdits&&re.fileEdits.length>0&&console.log(`${J} Captured ${re.fileEdits.length} file edit(s): ${re.fileEdits.map(de=>`${de.tool} ${de.file_path}`).join(", ")}`),re.editEvents&&re.editEvents.length>0&&console.log(`${J} Captured ${re.editEvents.length} edit event(s): ${re.editEvents.map(de=>`${de.operation} ${de.filePath}`).join(", ")}`),c.status="done";let ne=js(Pe),Ie=We;if(Ie.length>0&&c.annotationIds&&c.annotationIds.length>0){let de=new Set(c.annotationIds);Ie.every(et=>de.has(et.annotationId))||(Ie=Ie.map((et,jt)=>({...et,annotationId:c.annotationIds[jt%c.annotationIds.length]})))}let De=re.fileEdits&&re.fileEdits.length>0?re.fileEdits.map(de=>`${de.tool} ${de.file_path.split("/").pop()}`):re.toolsUsed,Ue=P.getBufferedEvents(c.id),_e=Yp(Ue?.events??[],r,pe.segments),Me,ie=bs(Pe),U=vs(Pe);if(U)if(!(c.memoryReview?.packets.some(ce=>ce.proposalId===U.proposalId)||c.surfacedProposalIds?.includes(U.proposalId)))Me={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{Me=await H.commitConversationalReview(U)}catch(ce){Me={status:"rejected",action:U.action,proposalId:U.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let ae=Es(Pe,we.length),fe,Ve,ai,di,nd=c.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??[]],et=ye.draft.decision==="recognize"?[]:ye.draft.appliedExplanationIds??[];ce.length>0&&(ai=[...new Set(ce)]),et.length>0&&(di=[...new Set(et)])}ye.draft?.decision==="none"&&ee.recordNoop(ye.draft.reason);let Xn=ye.draft?.decision==="recognize"?ye.draft:void 0;if(Xn&&!U&&!ie){let de=c.imprintContext?.explanations.find(ce=>ce.id===Xn.explanationId&&ce.state==="grounded");de?Ve={explanationId:de.id,title:Xn.summary.title,detail:Xn.summary.detail,statement:de.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let Zo=ye.draft?.decision==="mutate"||ye.draft?.decision==="apply"?ye.draft:void 0;if(c.threadId&&Zo&&!U&&!ie)try{fe=await ee.capture(Zo,{threadId:c.threadId,jobId:c.id,concreteModel:await ue.loadModel(),pendingGroundingExplanationIds:nd,applicationOccurred:we.length>0||Ie.some(de=>de.status==="resolved")}),fe?(Ae={state:"mutated"},await H.recordImprintEvidence({summary:fe,threadId:c.threadId,jobId:c.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 Zo&&(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 er=fe?.transactionId;if(c.threadId&&fe&&!fe.grounding){let de=await W.getThread(c.threadId),ce=new Set(fe.changes.map(jt=>jt.explanationId)),et=de?Xp(de.messages,ce):void 0;if(et?.imprintSummary){let jt=et.imprintSummary;await W.updateAssistantMessage(c.threadId,et.jobId,{imprintSummary:{...jt,detail:fe.detail,changes:fe.changes,additionalObservationCount:(jt.additionalObservationCount??0)+1,coalescedTransactionIds:[...jt.coalescedTransactionIds??[],fe.transactionId]}}),fe=void 0}}let tr=yn({question:ne,resolutions:Ie,changedFiles:we,decisionRequired:!!ie,imprintTransactionId:er,groundingRequired:!!fe?.grounding}),od=_e?.flatMap(de=>de.kind==="orientation"?[de.orientation]:[])??[],Lt=c.lifecycle?qn(c.lifecycle,er?[er]:[],Ae):void 0;if(c.threadId){let de=O?ie?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Ge;await W.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,responseText:de,resolutions:!O&&Ie.length>0?Ie:void 0,question:O?void 0:ne??void 0,sessionId:re.sessionId,toolsUsed:O?void 0:De,editEvents:!O&&re.editEvents&&re.editEvents.length>0?re.editEvents:void 0,segments:!O&&_e&&_e.length>0?_e:void 0,turn:{phase:"complete",orientation:od,result:tr},result:tr,memoryReviewCard:ie??void 0,memoryReceipt:Me,imprintSummary:fe,imprintRecognition:Ve,imprintUsedExplanationIds:ai,imprintAppliedExplanationIds:di,modelDetails:ae.length>0?ae:void 0,model:c.model,provider:k,...Lt?{lifecycle:Lt}:{}})}if(c.threadId&&!U&&!c.surfacedProposalIds?.length&&c.kind!=="project_model"){let de=c.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await H.captureCompletedJob({jobId:c.id,threadId:c.threadId,createdAt:c.createdAt,completedAt:Date.now(),requestSummary:y??(Ft(c.feedback)||"[request unavailable]"),responseSummary:ne??Ge,outcome:ne?"question_asked":Ie.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:k,model:c.model,sessionId:re.sessionId},subjectHints:de,filePaths:[...(re.fileEdits??[]).map(ce=>ce.file_path),...(re.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>aa(ce)?qp(r,ce):ce),resolutions:Ie.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:c.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Lt?.submissionIds,outcomeId:Lt?.outcomeId,imprintEvidenceIds:Lt?.imprintEvidenceIds,imprintAssessment:Lt?.imprintAssessment})}catch(ce){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}Me?.status==="committed"&&Me.decisionId&&k!=="copilot"&&await Ze({provider:k,model:c.model,agentSettings:c.agentSettings,threadId:c.threadId,annotationIds:c.annotationIds,sourceId:c.sourceId,reason:`Project accepted decision ${Me.decisionId}`}),ne&&(console.log(`${J} \u{1F4AC} Question detected: "${ne.slice(0,120)}" \u2192 broadcasting to ${K.size} SSE clients (threadId=${c.threadId??c.id}, annotationIds=${c.annotationIds?.join(",")??"none"})`),P.broadcast({type:"question",jobId:c.id,threadId:c.threadId??c.id,question:ne,annotationIds:c.annotationIds},c.id,c.sourceId)),ae.length>0&&(console.log(`${J} Applied model gap(s): ${ae.map(de=>`${de.category}/${de.element}`).join(", ")}`),P.broadcast({type:"novel_patterns",jobId:c.id,patterns:ae,threadId:c.threadId},c.id,c.sourceId)),P.broadcast({type:"done",jobId:c.id,success:!0,resolutions:Ie.length>0?Ie:void 0,responseText:Ge,threadId:c.threadId,annotationIds:c.annotationIds,result:tr},c.id,c.sourceId),je.push({id:c.id,status:"done",completedAt:Date.now(),threadId:c.threadId,annotationIds:c.annotationIds})}else console.error(`${J} Error: ${re.error}`),c.status="error",c.error=re.error,c.threadId&&await W.appendMessageBeforeQueuedReplies(c.threadId,{role:"assistant",timestamp:Date.now(),jobId:c.id,error:re.error||"Unknown error",model:c.model,provider:k,...c.lifecycle?{lifecycle:qn(c.lifecycle)}:{}}),P.broadcast({type:"error",jobId:c.id,threadId:c.threadId,message:re.error||"Unknown error",provider:k,model:c.model,recoverable:re.recoverableError,code:re.errorCode},c.id,c.sourceId),je.push({id:c.id,status:"error",completedAt:Date.now(),error:re.error,threadId:c.threadId,annotationIds:c.annotationIds});it()});let xe=Bp(async(c,I)=>{if(tu(c,I),c.method==="OPTIONS"){I.writeHead(204),I.end();return}let A=c.url||"/",y=A.split("?")[0],j=new URL(A,`http://127.0.0.1:${w}`),k=j.pathname,O=iu(c,j);if(O&&O!==i){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:O,projectName:Wo(r)});return}if(k.startsWith("/ambient/")&&O!==i){_(I,409,{error:"Ambient Popmelt requests require an exact project identity.",bridgeProjectId:i,requestProjectId:O});return}if(c.headers.origin){if(!da(c.headers.origin)){_(I,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(O!==i){_(I,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:O,projectName:Wo(r)});return}}try{if(k.startsWith("/ambient/"))await mt(c,I,k);else if(c.method==="POST"&&k==="/draft-attachments"){let $=j.searchParams.get("annotationId")?.trim()??"",q=j.searchParams.get("name")?.trim()??"",N=j.searchParams.get("kind"),J=String(c.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 ru(c,Qp);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(c.method==="POST"&&k==="/draft-attachments/claim"){let $=await Ce(c),q=Array.isArray($.ids)?$.ids.filter(N=>typeof N=="string").slice(0,100):[];await V.claim(q),_(I,200,{ok:!0})}else if(c.method==="DELETE"&&k.startsWith("/draft-attachments/"))await V.release([k.slice(19)]),_(I,200,{ok:!0});else if(c.method==="POST"&&k==="/send")await ft(c,I);else if(c.method==="POST"&&k==="/capture/native"){if(!p){_(I,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await Ce(c),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 os(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(c.method==="GET"&&k==="/events")Tt(c,I);else if(c.method==="GET"&&k==="/status")await Qo(c,I,O);else if(c.method==="GET"&&k==="/ui-preferences")await hn(I);else if(c.method==="PATCH"&&k==="/ui-preferences")await qe(c,I);else if(c.method==="PATCH"&&k==="/config")await Xo(c,I);else if(c.method==="POST"&&k==="/leases"){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Ce(c),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:na})}catch{_(I,400,{error:"Invalid lease request."})}}else if(k.startsWith("/leases/")&&(c.method==="PATCH"||c.method==="DELETE")){if(g!=="detached"){_(I,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(k.slice(8))}catch{_(I,400,{error:"Invalid lease id."});return}if(!$){_(I,400,{error:"A lease id is required."});return}if(c.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(c.method==="POST"&&k==="/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(c.method==="POST"&&k==="/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{}xe.close(()=>{ea(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(c.method==="GET"&&k==="/capabilities")_(I,200,{providers:u});else if(k.startsWith("/imprint/"))await st(c,I,k);else if(k.startsWith("/memory/"))await Oe(c,I,k);else if(c.method==="POST"&&k==="/mcp/install")await za(c,I);else if(c.method==="POST"&&k==="/reply")await ht(c,I);else if(c.method==="POST"&&k==="/cancel")Fe(c,I);else if(c.method==="POST"&&k==="/materialize")_(I,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(c.method==="GET"&&k==="/materialization-runs")_(I,410,{error:"Use /projection-runs."});else if(c.method==="GET"&&k==="/projection-runs"){let $=await ue.loadRuns();_(I,200,$)}else if(c.method==="GET"&&k==="/projection/proposals"){let $=await ue.loadModelProposals();_(I,200,$)}else if(c.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/apply-selected")){let $=k.slice(22,-15);await Rt($,c,I)}else if(c.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/apply")){let $=k.slice(22,-6);await Jt($,I)}else if(c.method==="POST"&&k.startsWith("/projection/proposals/")&&k.endsWith("/dismiss")){let $=k.slice(22,-8);await Yo($,c,I)}else if(k.startsWith("/model/proposals/"))_(I,410,{error:"Use /projection/proposals."});else if(c.method==="POST"&&k==="/model/component")await Ha(c,I);else if(c.method==="DELETE"&&k==="/model/component")await Wa(c,I);else if(c.method==="PATCH"&&k==="/model/token")await Ga(c,I);else if(c.method==="DELETE"&&k==="/model/token")await Va(c,I);else if(c.method==="POST"&&k==="/model/consolidate")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="POST"&&k==="/model/synthesize")_(I,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(c.method==="GET"&&k==="/model"){let $=await ue.loadModel();_(I,200,{model:$})}else if(c.method==="GET"&&k.startsWith("/jobs/")&&k.endsWith("/events")){let $=k.slice(6,k.length-7),q=parseInt(j.searchParams.get("afterSeq")??"-1",10),N=P.getBufferedEvents($,isNaN(q)?-1:q);N?_(I,200,N):_(I,404,{error:"Unknown job"})}else if(c.method==="GET"&&y.startsWith("/files/"))await Ya(y.slice(7),I);else if(c.method==="GET"&&k==="/threads/recent"){let $=Math.min(Math.max(parseInt(j.searchParams.get("limit")??"5",10)||5,1),20),q=await W.listRecent($);_(I,200,q)}else if(c.method==="GET"&&k.startsWith("/decision/")){let $=k.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(I,400,{error:"Invalid decision id"});else{let q=await W.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 Le.loadDecision($);J?_(I,200,{decision:J,authority:"legacy_archive"}):_(I,404,{error:"Decision not found"})}}}else if(c.method==="GET"&&k.startsWith("/thread/")){let $=k.slice(8);await Za($,I)}else if(c.method==="DELETE"&&k.startsWith("/thread/")){let $=k.slice(8);await ed($,I)}else c.method==="GET"&&(k==="/canvas"||k==="/canvas/")?Ka(c,I):c.method==="GET"&&k==="/canvas/manifest"?await Qa(I):c.method==="GET"&&k==="/canvas/app.mjs"?await Xa(I):_(I,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(I,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function mt(c,I,A){if(c.method!=="POST"){_(I,405,{error:"Ambient endpoints accept POST requests only."});return}let y=await Ce(c,ou),j=typeof y.sessionId=="string"?y.sessionId.trim():"",k=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 $e.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 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 $e.assess({threadId:$,jobId:q,assessmentText:N,semanticCandidates:J});_(I,he.status==="recorded"?200:404,he);return}if(!j||!k||j.length>256||k.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 $e.prepare({sessionId:j,turnId:k,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 $e.recordEvent({sessionId:j,turnId:k,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 $e.complete({sessionId:j,turnId:k,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 Oe(c,I,A){try{if(c.method==="GET"&&A==="/memory/status"){_(I,200,await H.status());return}if(c.method==="GET"&&A==="/memory/diagnostics"){_(I,200,await H.diagnostics());return}if(c.method==="GET"&&A==="/memory/model-view"){_(I,200,await H.getModelView());return}if(c.method==="GET"&&A==="/memory/imprint-view"){let y=await W.load(),j=[...new Set(Object.values(y.threads).flatMap(k=>zn(k.messages)))];_(I,200,await H.getImprintView(j,new Set(Object.keys(y.threads))));return}if(c.method==="POST"&&A==="/memory/constraints"){let y=await Ce(c),j=typeof y.reactComponent=="string"?y.reactComponent.trim():"",k=await H.getModelView(),O=j?k.entries.filter($=>$.key===`components.${j}`||$.key.startsWith(`components.${j}.`)):[];_(I,200,{modelEntries:O});return}if(c.method==="POST"&&A==="/memory/conversation-action"){let y=await Ce(c),j=typeof y.threadId=="string"?y.threadId:"",k=typeof y.proposalId=="string"?y.proposalId:"",O=String(y.action);if(!j||!k||!["accept","edit_and_accept","reject","defer"].includes(O)){_(I,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await W.getThread(j),q=$?.messages.find(pe=>pe.memoryReviewCard?.proposalId===k)?.memoryReviewCard,N=$?.messages.flatMap(pe=>pe.memoryReview?.packets??[]).find(pe=>pe.proposalId===k),J=$?.elementIdentifiers.some(pe=>pe.startsWith("codex-session:"))?(await H.findPendingProposalsForThread(j)).find(pe=>pe.proposalId===k):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(j),me=(await Promise.all(se.map(async pe=>({proposal:pe,matches:(await Promise.all(pe.decisionIds.map(Z=>H.findPendingProposalForLegacyDecision(Z)))).some(Z=>Z?.proposalId===k)})))).find(pe=>pe.matches)?.proposal,te={proposalId:k,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 H.commitConversationalReview(te),re=`memory-${pt().slice(0,8)}`,we=O==="accept"?"> Accepted decision":O==="edit_and_accept"?"> Edited and accepted decision":O==="reject"?"> Rejected decision":"> Deferred decision";await W.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:re,replyToQuestion:we}),await W.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:re,responseText:"",memoryReceipt:ge,provider:dn(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 ke=dn(typeof y.provider=="string"?y.provider:void 0);ge.status==="committed"&&ge.decisionId&&ke!=="copilot"&&await Ze({provider:ke,model:typeof y.model=="string"?y.model:void 0,agentSettings:Wt(y),threadId:j,reason:`Project accepted decision ${ge.decisionId}`}),_(I,ge.status==="committed"?200:409,{receipt:ge});return}if(c.method==="POST"&&A==="/memory/analyze"){let y=await Ce(c),j=await H.analyzeLegacy({projectKey:typeof y.projectKey=="string"?y.projectKey:void 0}),k=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:k});return}if(c.method==="POST"&&A==="/memory/review"){let y=await Ce(c),j=await H.review(Or(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(c.method==="POST"&&A==="/memory/context"){let y=await Ce(c),j=await H.contextualize(Or(y.query),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,200,j);return}if(c.method==="POST"&&A==="/memory/initialize"){let y=await Ce(c),j=await H.initializeFromLegacy({confirmed:y.confirm===!0,projectKey:typeof y.projectKey=="string"?y.projectKey:void 0,writerVersion:Ye});_(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(c.method==="POST"&&A==="/memory/plan"){let y=await Ce(c),j=await H.planReview($r(y.command),{projectKey:typeof y.projectKey=="string"?y.projectKey:void 0});_(I,j.result.ok?200:422,j);return}if(c.method==="POST"&&A==="/memory/commit"){let y=await Ce(c),j=y.transaction&&typeof y.transaction=="object"&&!Array.isArray(y.transaction)?y.transaction:{},k=await H.commitReview($r(y.command),{transactionId:typeof j.transactionId=="string"?j.transactionId:"",committedAt:typeof j.committedAt=="string"?j.committedAt:""});_(I,200,{status:await H.status(),journal:k.report});return}if(c.method==="POST"&&A==="/memory/recover"){let y=await Ce(c),j=await H.recover(y.confirm===!0);_(I,200,{status:await H.status(),journal:j.report});return}_(I,404,{error:"Memory endpoint not found."})}catch(y){let j=y instanceof Error?y.message:String(y),k=/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(k||O){_(I,k?409:400,{error:j});return}throw y}}async function st(c,I,A){if(c.method==="GET"&&A==="/imprint/status"){let[y,j]=await Promise.all([ee.store.load(),W.load()]),k=[...new Set(Object.values(j.threads).flatMap(O=>zn(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:k.length,recoveredTransactions:y.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e});return}if(c.method==="POST"&&A==="/imprint/action"){let y=await Ce(c),j=typeof y.threadId=="string"?y.threadId:"",k=typeof y.transactionId=="string"?y.transactionId:"",O=String(y.action);if(!j||!k||!["yes","this_time","no"].includes(O)){_(I,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await W.getThread(j),N=[...q?.messages??[]].reverse().find(te=>te.role==="assistant"&&te.imprintSummary?.transactionId===k),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-${pt().slice(0,8)}`;await ee.applyGroundingAction({summary:J,action:O,threadId:j,jobId:he}),O!=="no"&&await H.recordImprintEvidence({summary:J,action:O,threadId:j,jobId:he}).catch(te=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",te));let F=qt(N.result,!!N.question),se=N.turn?{...N.turn,result:qt(N.turn.result,!!N.question)}:void 0;await W.updateAssistantMessage(j,N.jobId,{imprintSummary:{...J,resolvedAction:O},...F?{result:F}:{},...se?{turn:se}:{}});let me={yes:"> Yes",this_time:"> This time",no:"> No"};if(await W.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=yn({question:te});await W.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 ft(c,I){let{screenshot:A,feedback:y,color:j,provider:k,model:O,reasoningEffort:$,serviceTier:q,sourceId:N,pastedImages:J,pageScreenshots:he}=await Dr(c),F;try{F=JSON.parse(y)}catch{_(I,400,{error:"Invalid feedback JSON"});return}let se=F.annotations.flatMap(ie=>(ie.attachments??[]).map(U=>({id:U.id,annotationId:ie.id}))),me;try{me=se.length>0?await V.promote(se):void 0}catch(ie){_(I,409,{error:ie instanceof Error?ie.message:"Draft attachment unavailable."});return}let te=pt().slice(0,8),ge={};if(he.length>0)for(let ie of he){let U=encodeURIComponent(ie.pathname),ae=Je(d,`screenshot-${te}-${U}.webp`);await Ho(ae,ie.data),ge[ie.pathname]=ae}let re=Je(d,`screenshot-${te}.webp`);await Ho(re,A);let we={};if(J.length>0)for(let ie of J){let U=Je(d,`pasted-${te}-${ie.annotationId}-${ie.index}.webp`);await Ho(U,ie.data),we[ie.annotationId]||(we[ie.annotationId]=[]),we[ie.annotationId].push(U)}let ke=Us(F),pe;if(ke.length>0){let ie=await W.findContinuationThread(ke);ie?(pe=ie.id,await W.addElementIdentifiers(pe,ke)):pe=(await W.createThread(`thread-${pt()}`,ke)).id}else pe=(await W.createThread(`thread-${pt()}`,[])).id;let Z=F.annotations.map(ie=>ie.id),Pe=Object.keys(ge).length>0,We=await In(H,F,ke,ie=>console.warn(`[\u22B9 ${w}:${te}] Contextual memory unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))),ye=(await W.getThread(pe))?.messages??[],Ge=await ee.contextualize({text:Ft(F),subjectHints:Qs(F,ke),pendingGroundingExplanationIds:zn(ye),correctionExplanationIds:ra(ye)}).catch(ie=>{console.warn(`[\u22B9 ${w}:${te}] Imprint context unavailable; continuing without it:`,ie instanceof Error?ie.message:String(ie))}),Ae=Fr({jobId:te,threadId:pe,artifactIds:zs(F,te)}),ne={id:te,status:"queued",screenshotPath:re,feedback:F,createdAt:Date.now(),color:j,threadId:pe,annotationIds:Z,provider:dn(k),model:O||void 0,agentSettings:Wt({reasoningEffort:$,serviceTier:q}),...Object.keys(we).length>0?{imagePaths:we}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},sourceId:N||void 0,...Pe?{screenshotPaths:ge}:{},...We?{memoryReview:We}:{},...Ge?{imprintContext:Ge}:{},lifecycle:Ae},Ie=new Set(F.annotations.map(ie=>ie.pathname).filter(Boolean)),De;if(Ie.size>1){let ie=new Map;for(let U of F.annotations){let ae=U.pathname||"(unknown)";ie.has(ae)||ie.set(ae,[]),ie.get(ae).push(U.instruction||ia({...F,annotations:[U]}))}De=[...ie.entries()].map(([U,ae])=>`\`${U}\`
|
|
228
230
|
${ae.map(fe=>`- ${fe}`).join(`
|
|
229
231
|
`)}`).join(`
|
|
230
|
-
`)}else De=
|
|
232
|
+
`)}else De=ia(F);let Ue=Dn(F,Object.keys(we).length>0?we:void 0,me),_e=Ys(F);await W.appendMessage(pe,{role:"human",timestamp:Date.now(),jobId:te,screenshotPath:re,...Pe?{screenshotPaths:ge}:{},...Object.keys(we).length>0?{imagePaths:we}:{},...me&&Object.keys(me).length>0?{attachmentFiles:me}:{},annotationIds:Z,annotationSnapshot:{url:F.url,viewport:F.viewport,annotations:F.annotations,color:j||void 0},feedbackSummary:De,..._e?{requestText:_e}:{},feedbackContext:Ue||void 0,...We?{memoryReview:We}:{},...Ge?{imprintContext:Ge}:{},lifecycle:Ae});let Me=P.enqueue(ne);_(I,200,{jobId:te,position:Me,threadId:pe})}async function ht(c,I){let A=c.headers["content-type"]||"",y,j,k,O,$,q,N,J,he=[];if(A.includes("multipart/form-data")){let U=await Dr(c),ae=U.feedback?JSON.parse(U.feedback):{};y=ae.threadId,j=ae.reply,k=ae.color,O=ae.provider,$=ae.model,q=Wt(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 Ve of c)U.push(typeof Ve=="string"?Buffer.from(Ve):Ve);let ae=Buffer.concat(U).toString("utf-8"),fe;try{fe=JSON.parse(ae)}catch{_(I,400,{error:"Invalid JSON"});return}y=fe.threadId,j=fe.reply,k=fe.color,O=fe.provider,$=fe.model,q=Wt(fe),N=fe.sourceId,J=fe.memoryReviewProposalId}if(!y||!j){_(I,400,{error:"Missing threadId or reply"});return}let F=await W.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 Ve=>({modelProposalId:fe.id,underlying:await H.findPendingProposalForLegacyDecision(Ve)}))))).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 W.getThreadHistory(y);for(let ae=U.length-1;ae>=0;ae--)if(U[ae].screenshotPath){me=U[ae].screenshotPath;break}}let te=await Ua(y);if(!me&&!te){_(I,400,{error:"No screenshot available"});return}let ge=P.hasActiveThread(y),re=ge?P.getQueuedThreadJob(y,U=>U._replyText!==void 0||U._replyPrompt!==void 0):null,we=re?.id??pt().slice(0,8),ke=Fr({jobId:we,threadId:y}),pe=[],Z=`${we}-${Date.now()}`;for(let U=0;U<he.length;U++){let ae=Je(d,`reply-${Z}-${U}.webp`);await Ho(ae,he[U]),pe.push(ae)}await W.appendMessage(y,{role:"human",timestamp:Date.now(),jobId:we,replyToQuestion:j,screenshotPath:me,...ge?{queued:!0}:{},...pe.length>0?{replyImagePaths:pe}:{},lifecycle:{...ke,artifactIds:pe.map((U,ae)=>`reply-image:${we}:${ae}`)}});let Pe=await W.getThreadHistory(y),We=[...Pe].reverse().find(U=>U.memoryReview)?.memoryReview,ye=await ee.contextualize({text:j,subjectHints:Xs(Pe,F.elementIdentifiers),pendingGroundingExplanationIds:zn(Pe),correctionExplanationIds:ra(Pe)}).catch(U=>{console.warn(`[\u22B9 ${w}:${we}] Imprint context unavailable for reply; continuing without it:`,U instanceof Error?U.message:String(U))});ye&&await W.updateMessage(y,we,{imprintContext:ye});let Ge=new Set(Pe.flatMap(U=>U.memoryReceipt?.status==="committed"?[U.memoryReceipt.proposalId]:[])),Ae=[...Pe].reverse().find(U=>U.memoryReviewCard&&!Ge.has(U.memoryReviewCard.proposalId))?.memoryReviewCard,ne=[];for(let U of Pe)if(U.annotationIds)for(let ae of U.annotationIds)ne.includes(ae)||ne.push(ae);let Ie=dn(O),De=se,Ue=De?[De.underlying.proposalId]:Ae?[Ae.proposalId]:[],_e=As(me,Pe,Ie,pe.length>0?pe:void 0);if(De?_e+=["","## Decision review card",`Privately review proposal ${De.underlying.proposalId}: ${De.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
231
233
|
`):Ae&&(_e+=["","## 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(`
|
|
232
|
-
`)),re){let
|
|
234
|
+
`)),re){let U=re,fe=[...U._replyTexts??(U._replyText?[U._replyText]:[]),j],Ve=[...U._replyImagePaths??[],...pe];U._replyTexts=fe,U._replyText=oa(fe),U._replyImagePaths=Ve.length>0?Ve:void 0,U._replyPrompt=_e,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??[],...Ue])],U.lifecycle={...U.lifecycle??ke,submissionIds:[...new Set([...U.lifecycle?.submissionIds??[],...ke.submissionIds])],artifactIds:[...new Set([...U.lifecycle?.artifactIds??[],...ke.artifactIds])]},_(I,200,{jobId:we,position:1,threadId:y,bundled:!0});return}let Me={id:we,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:k,threadId:y,annotationIds:ne.length>0?ne:void 0,provider:Ie,model:$||void 0,agentSettings:q,sourceId:N||void 0,...We?{memoryReview:We}:{},...ye?{imprintContext:ye}:{},...Ue.length?{surfacedProposalIds:Ue}:{},lifecycle:ke};te&&(Me.kind=te),Me._replyPrompt=_e,Me._replyTexts=[j],Me._replyText=oa([j]),pe.length>0&&(Me._replyImagePaths=pe);let ie=ge?P.enqueueNext(Me):P.enqueue(Me);_(I,200,{jobId:we,position:ie,threadId:y})}function Tt(c,I){I.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),I.write(`event: connected
|
|
233
235
|
data: {"status":"connected"}
|
|
234
236
|
|
|
235
|
-
`);let y=new URL(c.url||"/",`http://127.0.0.1:${w}`).searchParams.get("sourceId")||void 0,j={id:pt().slice(0,8),res:I,sourceId:y};K.add(j),c.on("close",()=>{K.delete(j)})}async function Ko(c,I,A){a??=Bs(c.headers),it();let y=[...k.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,T,O,$,q]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),H.status(),ee.store.load(),W.load()]),N=[],J=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);j.status==="rejected"&&N.push({subsystem:"projection",message:J(j)}),T.status==="rejected"&&N.push({subsystem:"projection",message:J(T)}),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=j.status==="fulfilled"?j.value.runs:[],U=T.status==="fulfilled"?T.value.proposals:[],se=Js(he,U),me=se.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),te=O.status==="fulfilled"?O.value:{initialized:!1,state:"degraded",error:J(O)},ge=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>zn(Z.messages)))]:[],re=$.status==="fulfilled"?ge.filter(Z=>$.value.graph.explanations.some(Pe=>Pe.id===Z&&Pe.state==="testing")):[],we=$.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:re.length,recoveredTransactions:$.value.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J($),pendingGroundingCount:re.length,admission:ee.diagnostics(),admissionWindowStartedAt:e},ke=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:ke,issues:N},version:Ye,restartMode:g,projectId:i,storeId:s.storeId,projectName:Ho(r),projectRoot:r,requestProjectId:A,projectIdVerified:A===i,devOrigin:a,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:k.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:z.isActivated,count:z.size,nextExpiryAt:z.nextExpiryAt,shutdownPending:Y},projection:{state:j.status==="fulfilled"&&T.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:we,recentJobsRetentionMs:fn,recentJobs:je})}async function Qo(c,I){let A=await new Promise(y=>{let j="";c.on("data",T=>{j+=T.toString()}),c.on("end",()=>y(j))});try{let y=JSON.parse(A);typeof y.devOrigin=="string"&&(a=y.devOrigin||null),_(I,200,{ok:!0,devOrigin:a})}catch{_(I,400,{error:"Invalid JSON"})}}async function hn(c){let I=await Re.load();_(c,200,{ok:!0,...I})}async function qe(c,I){let A=await Ce(c);if(!Vs(A.theme)){_(I,400,{error:"theme must be light, dark, or auto"});return}let y=await Re.setTheme(A.theme);_(I,200,{ok:!0,exists:!0,preferences:y})}async function Ue(c,I){let y=new URL(c.url||"/",`http://127.0.0.1:${w}`).searchParams.get("jobId"),j=y?k.allActive.filter(J=>J.id===y):k.allActive,T=y?C.allActive.filter(J=>J.id===y):C.allActive,O=[...j.map(J=>J.threadId),...T.map(J=>J.threadId)].filter(Boolean),$=y?k.cancelJob(y):k.cancelActive(),q=y?C.cancelJob(y):C.cancelActive(),N=!!($||q);for(let J of O)await W.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:y||q?.id||"",cancelled:!0});_(I,200,{cancelled:N})}async function Ze(c){let I=pt().slice(0,8),A=c.threadId,y=!A;A||(A=(await W.createThread(`thread-${pt()}`,[])).id,Pt.set(A,"project_model")),y&&await W.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:c.reason}),await W.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:I,responseText:y?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:c.model,provider:c.provider});let j={id:I,status:"queued",createdAt:Date.now(),provider:c.provider,model:c.model,agentSettings:c.agentSettings,threadId:A,annotationIds:c.annotationIds,sourceId:c.sourceId,standalone:y},T=C.enqueue(j);return{jobId:I,position:T,threadId:A}}async function Jt(c,I){let A=decodeURIComponent(c),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 Rt(c,I,A){let y=decodeURIComponent(c),j=[];for await(let U of I)j.push(typeof U=="string"?Buffer.from(U):U);let T;try{T=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(A,400,{error:"Invalid JSON"});return}let O=(T.changes??[]).flatMap(U=>{if(!Array.isArray(U.path)||U.path.length===0)return[];let se=U.path.filter(te=>typeof te=="string"||typeof te=="number");if(se.length!==U.path.length)return[];let me=Array.isArray(U.decisionIds)?U.decisionIds.filter(te=>typeof te=="string"):void 0;return[{path:se,value:U.value,remove:U.remove===!0,decisionIds:me}]});if(O.length===0){_(A,400,{error:"No selected model changes"});return}let $=(T.changeSummaries??[]).flatMap(U=>{if(!U||typeof U!="object")return[];let se=Array.isArray(U.path)?U.path.filter(me=>typeof me=="string"||typeof me=="number"):void 0;return Array.isArray(U.path)&&se?.length!==U.path.length?[]:[{group:typeof U.group=="string"?U.group:void 0,label:typeof U.label=="string"?U.label:void 0,detail:typeof U.detail=="string"?U.detail:void 0,path:se,value:U.value,currentValue:U.currentValue}]}),q=await ue.findModelProposal(y);if(!q){_(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(U=>{let se=q.changes?.filter(ge=>ge.decisionIds.includes(U)).length??0,me=O.filter(ge=>ge.decisionIds?.includes(U)).length,te=me===0?"unprojected":se>me?"partially_projected":"projected";return{decisionId:U,status:te}}),J=await H.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:O.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:N}),he=await ue.applySelectedModelProposal(y,O,$);if(!he){_(A,404,{error:"Model proposal not found"});return}if(he.threadId){let U=dn(T.provider),se=typeof T.model=="string"&&T.model?T.model:void 0;await W.appendMessage(he.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${he.id}`,responseText:"",provider:U,model:se})}_(A,200,{proposal:he,projection:J})}async function Xo(c,I,A){let y=decodeURIComponent(c),{provider:j,model:T}=await Qn(I),O=await ue.dismissModelProposal(y);if(!O){_(A,404,{error:"Model proposal not found"});return}O.threadId&&await W.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${O.id}`,responseText:"",provider:j,model:T}),_(A,200,{proposal:O})}async function Qn(c){try{let I=[];for await(let y of c)I.push(typeof y=="string"?Buffer.from(y):y);if(I.length===0)return{};let A=JSON.parse(Buffer.concat(I).toString());return{provider:dn(typeof A.provider=="string"?A.provider:void 0),model:typeof A.model=="string"&&A.model?A.model:void 0,agentSettings:Wt(A)}}catch{return{}}}async function Ua(c){let I=Pt.get(c);if(I)return I;let j=(await W.getThread(c))?.messages.find(T=>T.role==="human")?.feedbackSummary??"";if(j.startsWith("Synthesize rules"))return Pt.set(c,"synthesize"),"synthesize";if(j.startsWith("Materialize model")||j.startsWith("Project model"))return Pt.set(c,"project_model"),"project_model"}async function Fa(c,I){let A=[];for await(let q of c)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 Zi(y)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&j.push(await es(y)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&j.push(await ts(y,u.copilot.path??R));let[T,O,$]=await Promise.all([wr(r),vr(r),br(r,u.copilot?.path??R)]);u.claude&&(u.claude.mcp=T),u.codex&&(u.codex.mcp=O),u.copilot&&(u.copilot.mcp=$),_(I,200,{results:j,capabilities:{providers:u}})}async function za(c,I){let A=[];for await(let T of c)A.push(typeof T=="string"?Buffer.from(T):T);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 H.recordDirectModelMutation({key:`components.${y.name}`,value:{description:""},claim:`${y.name} is an explicitly governed component in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{added:!0,alreadyExists:!1,...j})}async function Ha(c,I){let A=[];for await(let T of c)A.push(typeof T=="string"?Buffer.from(T):T);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 H.recordDirectModelMutation({key:`components.${y.name}`,value:null,claim:`${y.name} is not governed as a component in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}async function Wa(c,I){let A=[];for await(let O of c)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 T=await H.recordDirectModelMutation({key:`tokens.${y.path}`,value:j,claim:`${y.path} uses ${y.value} in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{updated:!0,...T})}async function Ga(c,I){let A=[];for await(let T of c)A.push(typeof T=="string"?Buffer.from(T):T);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 H.recordDirectModelMutation({key:`tokens.${y.path}`,value:null,claim:`${y.path} is intentionally absent from the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}function Va(c,I){let A=a??"http://localhost:3000";if(!a){let j=c.headers.referer||c.headers.origin;if(j)try{let T=new URL(typeof j=="string"?j:j[0]||"");(T.hostname==="localhost"||T.hostname==="127.0.0.1")&&(A=T.origin)}catch{}}let y=di(w,A);I.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),I.end(y)}async function Ka(c){let I=Date.now();if(kt&&I<kt.expires){_(c,200,kt.data);return}try{let{scanForComponents:A}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:y}=await import("./render-generator-EANIDD2E.mjs"),j=await A(r);kt={data:j,expires:I+5e3},y(j,r,Kn).then(T=>{Kn=T}).catch(T=>console.warn("[Bridge] Render generation failed:",T)),_(c,200,j)}catch(A){console.error("[Bridge] Scanner error:",A),_(c,500,{error:"Failed to scan components"})}}async function Qa(c){let I=[Je(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Je(r,"packages","popmelt","dist","canvas.mjs")];try{let A=Up(import.meta.url);I.unshift(Je(Jp(A),"canvas.mjs"))}catch{}for(let A of I)try{let y=await ea(A,"utf-8");c.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),c.end(y);return}catch{}console.error("[Bridge] Canvas bundle not found in:",I),_(c,404,{error:"Canvas bundle not found"})}async function Xa(c,I){if(!c||c.includes("/")||c.includes("\\")||c.includes("..")){_(I,400,{error:"Invalid filename"});return}try{let A=[Je(d,c),Je(r,".popmelt","artifacts","thread-media",c),Je(r,".popmelt","artifacts","eval-screenshots",c),Je(r,".popmelt","evals","screenshots",c),Je(r,".popmelt","screenshots",c)],y;for(let O of A)try{y=await ea(O);break}catch{}if(!y)throw new Error("File not found");let j=c.split(".").pop()?.toLowerCase(),T=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":T,"Cache-Control":"public, max-age=3600"}),I.end(y)}catch{_(I,404,{error:"File not found"})}}function gn(c){return`/files/${Ho(c)}`}async function Ya(c,I){let A=await W.getThread(c);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(c):Promise.resolve([])),T=await Promise.all(j.map(async(N,J)=>{if(N.authorityStatus==="accepted")return N;let he=(await Promise.all(N.decisionIds.map(U=>H.findPendingProposalForLegacyDecision(U)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??y[J]?.jobId??y.at(-1)?.jobId,underlyingProposalId:he?.proposalId,underlyingClaim:he?.claim}})),O=[...T].sort((N,J)=>J.updatedAt-N.updatedAt)[0]??null,$=A.elementIdentifiers.some(N=>N.startsWith("codex-session:"))?await H.findPendingProposalsForThread(c):[],q=A.messages.map(({screenshotPath:N,screenshotPaths:J,imagePaths:he,attachmentFiles:U,replyImagePaths:se,...me})=>({...me,...N?{screenshotUrl:gn(N)}:{},...J?{screenshotUrls:Object.fromEntries(Object.entries(J).map(([te,ge])=>[te,gn(ge)]))}:{},...he?{imageUrls:Object.fromEntries(Object.entries(he).map(([te,ge])=>[te,ge.map(gn)]))}:{},...U?{attachments:Object.fromEntries(Object.entries(U).map(([te,ge])=>[te,ge.map(({path:re,...we})=>({...we,url:gn(re)}))]))}:{},...se?{replyImageUrls:se.map(gn)}:{}}));_(I,200,{id:A.id,createdAt:A.createdAt,messages:q,modelProposal:O,modelProposals:T,decisionCandidates:$})}async function Za(c,I){let A=decodeURIComponent(c);if(!await W.deleteThread(A)){_(I,404,{deleted:!1,error:"Thread not found"});return}_(I,200,{deleted:!0})}let oi=9,ri=!1;for(let c=n;c<n+oi;c++)try{await ru(xe,c),w=c,ri=!0,console.log(`[\u22B9 is watching :${w}]`);break}catch(I){if(I.code==="EADDRINUSE"){let A=await Go(c);if(Ln(A,{projectId:i,version:Ye,restartMode:g}))return console.log(`[\u22B9 already watching :${c}]`),{port:c,projectId:i,close:async()=>{}};continue}throw I}if(!ri)throw new Error(`[Bridge] All ports ${n}\u2013${n+oi-1} in use`);for(let[c,I]of Object.entries(u))!I.available||!I.path||h(c,I.path).then(A=>{if(A)console.log(`[Bridge] ${c} warmed up`);else{console.warn(`[Bridge] ${c} warm-up failed \u2014 marking unavailable`),I.available=!1,I.path=null;for(let y of K)Wo(y,{type:"capabilities_changed",data:{}})}});let ed=setInterval(()=>{ia(d).catch(()=>{}),V.sweep().catch(()=>{})},Hp),ii=setInterval(()=>{z.expireStale().becameEmpty&&L()},Gp);return ii.unref?.(),{port:w,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(ed),clearInterval(ii),S(),z.clear(),await V.cleanupPartials(),await k.destroyAsync(),C.destroy();for(let c of K)try{c.res.end()}catch{}return K.clear(),new Promise(c=>{xe.close(()=>c())})}}}async function ia(t){try{let e=await Cp(t),n=Date.now();for(let o of e){let r=Je(t,o);try{let i=await Op(r);n-i.mtimeMs>Wp&&await Dp(r)}catch{}}}catch{}}import{readFile as Gr,readdir as bu,realpath as xu,stat as Su}from"fs/promises";import{dirname as Pu,join as Bt,parse as ku,relative as Tu,resolve as Vr,sep as Ru}from"path";import{spawn as du}from"child_process";import{closeSync as cu,openSync as lu}from"fs";import{appendFile as pu,mkdir as uu,readFile as mu,realpath as fu}from"fs/promises";import{dirname as hu,join as Hr}from"path";import{fileURLToPath as gu}from"url";import{randomUUID as iu}from"crypto";var su=5e3,au=250;function zr(t){return{"Content-Type":"application/json",...t.projectId?{"X-Popmelt-Project-Id":t.projectId}:{}}}async function Wn(t,e=fetch){let n=`${process.pid}-${iu()}`,o=`http://127.0.0.1:${t.port}`,r=!1,i=!1,s=async()=>(await e(`${o}/leases`,{method:"POST",headers:zr(t),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(v){return console.warn("[popmelt] failed to register bridge lease:",v instanceof Error?v.message:String(v)),null}let a=async()=>{if(!(r||i)){i=!0;try{(await e(`${o}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:zr(t)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{a()},su);return d.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${o}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:zr(t),keepalive:!0})}catch{}}}}}function da(t,e=process){let n=!1,o=new Map,r=()=>{if(!n){n=!0;for(let[i,s]of o)e.removeListener(i,s);o.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let a=e.listenerCount(i),d=t.release();if(a>0)return;let l=new Promise(v=>{setTimeout(v,au)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};o.set(i,s),e.prependOnceListener(i,s)}return r}var yu=1111,ca=3e4,Iu=8e3;async function wu(t){return fu(t).catch(()=>t)}async function la(t,e){let o=(await mu(e,"utf8").catch(()=>"")).slice(-Iu).trim();return new Error(o?`${t}
|
|
237
|
+
`);let y=new URL(c.url||"/",`http://127.0.0.1:${w}`).searchParams.get("sourceId")||void 0,j={id:pt().slice(0,8),res:I,sourceId:y};K.add(j),c.on("close",()=>{K.delete(j)})}async function Qo(c,I,A){a??=Js(c.headers),it();let y=[...P.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,k,O,$,q]=await Promise.allSettled([ue.loadRuns(),ue.loadModelProposals(),H.status(),ee.store.load(),W.load()]),N=[],J=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);j.status==="rejected"&&N.push({subsystem:"projection",message:J(j)}),k.status==="rejected"&&N.push({subsystem:"projection",message:J(k)}),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=j.status==="fulfilled"?j.value.runs:[],F=k.status==="fulfilled"?k.value.proposals:[],se=Ls(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=>zn(Z.messages)))]:[],re=$.status==="fulfilled"?ge.filter(Z=>$.value.graph.explanations.some(Pe=>Pe.id===Z&&Pe.state==="testing")):[],we=$.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:re.length,recoveredTransactions:$.value.recoveredTransactions,admission:ee.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J($),pendingGroundingCount:re.length,admission:ee.diagnostics(),admissionWindowStartedAt:e},ke=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:ke,issues:N},version:Ye,restartMode:g,projectId:i,storeId:s.storeId,projectName:Wo(r),projectRoot:r,requestProjectId:A,projectIdVerified:A===i,devOrigin:a,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:P.depth+C.depth,projectionQueueDepth:C.depth,leases:{active:z.isActivated,count:z.size,nextExpiryAt:z.nextExpiryAt,shutdownPending:Y},projection:{state:j.status==="fulfilled"&&k.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:we,recentJobsRetentionMs:fn,recentJobs:je})}async function Xo(c,I){let A=await new Promise(y=>{let j="";c.on("data",k=>{j+=k.toString()}),c.on("end",()=>y(j))});try{let y=JSON.parse(A);typeof y.devOrigin=="string"&&(a=y.devOrigin||null),_(I,200,{ok:!0,devOrigin:a})}catch{_(I,400,{error:"Invalid JSON"})}}async function hn(c){let I=await Re.load();_(c,200,{ok:!0,...I})}async function qe(c,I){let A=await Ce(c);if(!Ks(A.theme)){_(I,400,{error:"theme must be light, dark, or auto"});return}let y=await Re.setTheme(A.theme);_(I,200,{ok:!0,exists:!0,preferences:y})}async function Fe(c,I){let y=new URL(c.url||"/",`http://127.0.0.1:${w}`).searchParams.get("jobId"),j=y?P.allActive.filter(J=>J.id===y):P.allActive,k=y?C.allActive.filter(J=>J.id===y):C.allActive,O=[...j.map(J=>J.threadId),...k.map(J=>J.threadId)].filter(Boolean),$=y?P.cancelJob(y):P.cancelActive(),q=y?C.cancelJob(y):C.cancelActive(),N=!!($||q);for(let J of O)await W.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:y||q?.id||"",cancelled:!0});_(I,200,{cancelled:N})}async function Ze(c){let I=pt().slice(0,8),A=c.threadId,y=!A;A||(A=(await W.createThread(`thread-${pt()}`,[])).id,Pt.set(A,"project_model")),y&&await W.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:I,feedbackSummary:c.reason}),await W.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:I,responseText:y?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:c.model,provider:c.provider});let j={id:I,status:"queued",createdAt:Date.now(),provider:c.provider,model:c.model,agentSettings:c.agentSettings,threadId:A,annotationIds:c.annotationIds,sourceId:c.sourceId,standalone:y},k=C.enqueue(j);return{jobId:I,position:k,threadId:A}}async function Jt(c,I){let A=decodeURIComponent(c),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 Rt(c,I,A){let y=decodeURIComponent(c),j=[];for await(let F of I)j.push(typeof F=="string"?Buffer.from(F):F);let k;try{k=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(A,400,{error:"Invalid JSON"});return}let O=(k.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 $=(k.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}}),J=await H.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=dn(k.provider),se=typeof k.model=="string"&&k.model?k.model:void 0;await W.appendMessage(he.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${he.id}`,responseText:"",provider:F,model:se})}_(A,200,{proposal:he,projection:J})}async function Yo(c,I,A){let y=decodeURIComponent(c),{provider:j,model:k}=await Qn(I),O=await ue.dismissModelProposal(y);if(!O){_(A,404,{error:"Model proposal not found"});return}O.threadId&&await W.appendMessage(O.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${O.id}`,responseText:"",provider:j,model:k}),_(A,200,{proposal:O})}async function Qn(c){try{let I=[];for await(let y of c)I.push(typeof y=="string"?Buffer.from(y):y);if(I.length===0)return{};let A=JSON.parse(Buffer.concat(I).toString());return{provider:dn(typeof A.provider=="string"?A.provider:void 0),model:typeof A.model=="string"&&A.model?A.model:void 0,agentSettings:Wt(A)}}catch{return{}}}async function Ua(c){let I=Pt.get(c);if(I)return I;let j=(await W.getThread(c))?.messages.find(k=>k.role==="human")?.feedbackSummary??"";if(j.startsWith("Synthesize rules"))return Pt.set(c,"synthesize"),"synthesize";if(j.startsWith("Materialize model")||j.startsWith("Project model"))return Pt.set(c,"project_model"),"project_model"}async function za(c,I){let A=[];for await(let q of c)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 es(y)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&j.push(await ts(y)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&j.push(await ns(y,u.copilot.path??R));let[k,O,$]=await Promise.all([vr(r),br(r),xr(r,u.copilot?.path??R)]);u.claude&&(u.claude.mcp=k),u.codex&&(u.codex.mcp=O),u.copilot&&(u.copilot.mcp=$),_(I,200,{results:j,capabilities:{providers:u}})}async function Ha(c,I){let A=[];for await(let k of c)A.push(typeof k=="string"?Buffer.from(k):k);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 H.recordDirectModelMutation({key:`components.${y.name}`,value:{description:""},claim:`${y.name} is an explicitly governed component in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{added:!0,alreadyExists:!1,...j})}async function Wa(c,I){let A=[];for await(let k of c)A.push(typeof k=="string"?Buffer.from(k):k);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 H.recordDirectModelMutation({key:`components.${y.name}`,value:null,claim:`${y.name} is not governed as a component in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}async function Ga(c,I){let A=[];for await(let O of c)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 k=await H.recordDirectModelMutation({key:`tokens.${y.path}`,value:j,claim:`${y.path} uses ${y.value} in the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{updated:!0,...k})}async function Va(c,I){let A=[];for await(let k of c)A.push(typeof k=="string"?Buffer.from(k):k);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 H.recordDirectModelMutation({key:`tokens.${y.path}`,value:null,claim:`${y.path} is intentionally absent from the product model.`});await ue.applyCanonicalEntries(await H.getCanonicalModelEntries()),_(I,200,{removed:!0,...j})}function Ka(c,I){let A=a??"http://localhost:3000";if(!a){let j=c.headers.referer||c.headers.origin;if(j)try{let k=new URL(typeof j=="string"?j:j[0]||"");(k.hostname==="localhost"||k.hostname==="127.0.0.1")&&(A=k.origin)}catch{}}let y=ci(w,A);I.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),I.end(y)}async function Qa(c){let I=Date.now();if(kt&&I<kt.expires){_(c,200,kt.data);return}try{let{scanForComponents:A}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:y}=await import("./render-generator-EANIDD2E.mjs"),j=await A(r);kt={data:j,expires:I+5e3},y(j,r,Kn).then(k=>{Kn=k}).catch(k=>console.warn("[Bridge] Render generation failed:",k)),_(c,200,j)}catch(A){console.error("[Bridge] Scanner error:",A),_(c,500,{error:"Failed to scan components"})}}async function Xa(c){let I=[Je(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Je(r,"packages","popmelt","dist","canvas.mjs")];try{let A=Up(import.meta.url);I.unshift(Je(Lp(A),"canvas.mjs"))}catch{}for(let A of I)try{let y=await ta(A,"utf-8");c.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),c.end(y);return}catch{}console.error("[Bridge] Canvas bundle not found in:",I),_(c,404,{error:"Canvas bundle not found"})}async function Ya(c,I){if(!c||c.includes("/")||c.includes("\\")||c.includes("..")){_(I,400,{error:"Invalid filename"});return}try{let A=[Je(d,c),Je(r,".popmelt","artifacts","thread-media",c),Je(r,".popmelt","artifacts","eval-screenshots",c),Je(r,".popmelt","evals","screenshots",c),Je(r,".popmelt","screenshots",c)],y;for(let O of A)try{y=await ta(O);break}catch{}if(!y)throw new Error("File not found");let j=c.split(".").pop()?.toLowerCase(),k=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":k,"Cache-Control":"public, max-age=3600"}),I.end(y)}catch{_(I,404,{error:"File not found"})}}function gn(c){return`/files/${Wo(c)}`}async function Za(c,I){let A=await W.getThread(c);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(c):Promise.resolve([])),k=await Promise.all(j.map(async(N,J)=>{if(N.authorityStatus==="accepted")return N;let he=(await Promise.all(N.decisionIds.map(F=>H.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=[...k].sort((N,J)=>J.updatedAt-N.updatedAt)[0]??null,$=A.elementIdentifiers.some(N=>N.startsWith("codex-session:"))?await H.findPendingProposalsForThread(c):[],q=A.messages.map(({screenshotPath:N,screenshotPaths:J,imagePaths:he,attachmentFiles:F,replyImagePaths:se,...me})=>({...me,...N?{screenshotUrl:gn(N)}:{},...J?{screenshotUrls:Object.fromEntries(Object.entries(J).map(([te,ge])=>[te,gn(ge)]))}:{},...he?{imageUrls:Object.fromEntries(Object.entries(he).map(([te,ge])=>[te,ge.map(gn)]))}:{},...F?{attachments:Object.fromEntries(Object.entries(F).map(([te,ge])=>[te,ge.map(({path:re,...we})=>({...we,url:gn(re)}))]))}:{},...se?{replyImageUrls:se.map(gn)}:{}}));_(I,200,{id:A.id,createdAt:A.createdAt,messages:q,modelProposal:O,modelProposals:k,decisionCandidates:$})}async function ed(c,I){let A=decodeURIComponent(c);if(!await W.deleteThread(A)){_(I,404,{deleted:!1,error:"Thread not found"});return}_(I,200,{deleted:!0})}let ri=9,ii=!1;for(let c=n;c<n+ri;c++)try{await au(xe,c),w=c,ii=!0,console.log(`[\u22B9 is watching :${w}]`);break}catch(I){if(I.code==="EADDRINUSE"){let A=await Vo(c);if(Ln(A,{projectId:i,version:Ye,restartMode:g}))return console.log(`[\u22B9 already watching :${c}]`),{port:c,projectId:i,close:async()=>{}};continue}throw I}if(!ii)throw new Error(`[Bridge] All ports ${n}\u2013${n+ri-1} in use`);for(let[c,I]of Object.entries(u))!I.available||!I.path||h(c,I.path).then(A=>{if(A)console.log(`[Bridge] ${c} warmed up`);else{console.warn(`[Bridge] ${c} warm-up failed \u2014 marking unavailable`),I.available=!1,I.path=null;for(let y of K)Go(y,{type:"capabilities_changed",data:{}})}});let td=setInterval(()=>{sa(d).catch(()=>{}),V.sweep().catch(()=>{})},Wp),si=setInterval(()=>{z.expireStale().becameEmpty&&L()},Vp);return si.unref?.(),{port:w,projectId:i,storeId:s.storeId,close:async()=>{clearInterval(td),clearInterval(si),x(),z.clear(),await V.cleanupPartials(),await P.destroyAsync(),C.destroy();for(let c of K)try{c.res.end()}catch{}return K.clear(),new Promise(c=>{xe.close(()=>c())})}}}async function sa(t){try{let e=await $p(t),n=Date.now();for(let o of e){let r=Je(t,o);try{let i=await Dp(r);n-i.mtimeMs>Gp&&await Np(r)}catch{}}}catch{}}import{readFile as Vr,readdir as Pu,realpath as ku,stat as Tu}from"fs/promises";import{dirname as Ru,join as Bt,parse as ju,relative as Au,resolve as Kr,sep as Mu}from"path";import{spawn as pu}from"child_process";import{closeSync as uu,openSync as mu}from"fs";import{appendFile as fu,mkdir as hu,readFile as gu,realpath as yu}from"fs/promises";import{dirname as Iu,join as Wr}from"path";import{fileURLToPath as wu}from"url";import{randomUUID as du}from"crypto";var cu=5e3,lu=250;function Hr(t){return{"Content-Type":"application/json",...t.projectId?{"X-Popmelt-Project-Id":t.projectId}:{}}}async function Wn(t,e=fetch){let n=`${process.pid}-${du()}`,o=`http://127.0.0.1:${t.port}`,r=!1,i=!1,s=async()=>(await e(`${o}/leases`,{method:"POST",headers:Hr(t),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(v){return console.warn("[popmelt] failed to register bridge lease:",v instanceof Error?v.message:String(v)),null}let a=async()=>{if(!(r||i)){i=!0;try{(await e(`${o}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Hr(t)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{a()},cu);return d.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${o}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Hr(t),keepalive:!0})}catch{}}}}}function ca(t,e=process){let n=!1,o=new Map,r=()=>{if(!n){n=!0;for(let[i,s]of o)e.removeListener(i,s);o.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let a=e.listenerCount(i),d=t.release();if(a>0)return;let l=new Promise(v=>{setTimeout(v,lu)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};o.set(i,s),e.prependOnceListener(i,s)}return r}var vu=1111,la=3e4,bu=8e3;async function xu(t){return yu(t).catch(()=>t)}async function pa(t,e){let o=(await gu(e,"utf8").catch(()=>"")).slice(-bu).trim();return new Error(o?`${t}
|
|
236
238
|
Bridge log (${e}):
|
|
237
|
-
${o}`:t)}async function
|
|
239
|
+
${o}`:t)}async function ua(t){if(process.env.NODE_ENV==="production"&&!t?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(t?.detached){let n=await Su(t);if(t.manageLease===!1)return n;let o=await Wn({port:n.port,projectId:n.projectId});if(!o)return console.warn("[popmelt] detached bridge started without a process lease"),n;let r=ca(o);return{...n,close:async()=>{r(),await o.release()}}}let e=await Hn(t);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function Su(t){let e=t.port??vu,n=await xu(t.projectRoot??process.cwd()),o=It(n),r=await Ht(n);for(let b=e;b<e+10;b++){let R=await Vo(b);if(R&&R.projectId===o){if(R.version&&R.version!==Ye){if(R.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(!Ln(R,{projectId:o,version:Ye,restartMode:"detached"}))continue;let S=t.devOrigin;if(S&&R.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=o,{port:b,projectId:o,storeId:r.storeId,close:async()=>{}}}}let i=Wr(Iu(wu(import.meta.url)),"bridge-entry.mjs"),s=Wr(n,".popmelt"),a=Wr(s,"bridge.log");await hu(s,{recursive:!0}),await fu(a,`
|
|
238
240
|
[${new Date().toISOString()}] Starting detached bridge
|
|
239
|
-
`);let d=
|
|
240
|
-
`,{encoding:"utf8",mode:384})}async function pn(t){await
|
|
241
|
-
`,{encoding:"utf8",mode:384}),o}async function
|
|
242
|
-
`)}function
|
|
243
|
-
`)}function
|
|
241
|
+
`);let d=mu(a,"a"),l;try{l=pu(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",d],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:t.devOrigin??"",POPMELT_COPILOT_PATH:t.copilotPath??""}})}finally{uu(d)}let v=null;l.once("error",b=>{v=`spawn error: ${b.message}`}),l.once("exit",(b,R)=>{v=`child exited before becoming healthy (${R?`signal ${R}`:`code ${b??"unknown"}`})`}),l.unref();let T=Date.now()+la;for(;Date.now()<T;){if(await new Promise(b=>setTimeout(b,100)),v)throw await pa(`[Bridge] Detached bridge ${v}`,a);for(let b=e;b<e+10;b++){let R=await Vo(b);if(Ln(R,{projectId:o,version:Ye,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(b),process.env.POPMELT_PROJECT_ID=o,{port:b,projectId:o,storeId:r.storeId,close:async()=>{}}}}throw l.kill("SIGTERM"),await pa(`[Bridge] Detached bridge failed to start within ${la/1e3}s (port ${e})`,a)}async function ma(t){return Tu(t).then(()=>!0,()=>!1)}async function fa(t){try{let e=JSON.parse(await Vr(t,"utf8"));return e.name==="@popmelt.com/core"?!0:["dependencies","devDependencies","peerDependencies"].some(n=>{let o=e[n];return!!(o&&typeof o=="object"&&Object.prototype.hasOwnProperty.call(o,"@popmelt.com/core"))})}catch{return!1}}async function Gr(t){return ku(t).catch(()=>Kr(t))}async function ha(t){let e=new Set;try{let n=await Vr(Bt(t,"pnpm-workspace.yaml"),"utf8");for(let o of n.matchAll(/^\s*-\s*['"]?([^'"\r\n]+)['"]?\s*$/gm)){let i=o[1].trim().split(/[*{[]/,1)[0].replace(/\/$/,"");i&&e.add(Kr(t,i))}}catch{}try{let n=JSON.parse(await Vr(Bt(t,"package.json"),"utf8")),o=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[];for(let r of o){let i=r.split(/[*{[]/,1)[0].replace(/\/$/,"");i&&e.add(Kr(t,i))}}catch{}return[...e]}var Eu=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","vendor"]);async function _u(t,e=5){let n=[],o=async(r,i)=>{if(i>e)return;let s;try{s=await Pu(r,{withFileTypes:!0})}catch{return}s.some(a=>a.isDirectory()&&a.name===".popmelt")&&n.push(r),await Promise.all(s.flatMap(a=>!a.isDirectory()||a.name===".popmelt"||Eu.has(a.name)?[]:[o(Bt(r,a.name),i+1)]))};return await o(t,0),n}function ga(t,e){let n=Au(t,e);return n?n.split(Mu).filter(Boolean).length:0}async function cn(t=process.cwd()){let e=await Gr(t),n=e,o=ju(n).root,r=new Map,i=(d,l)=>{let v=r.get(d)??new Set;v.add(l),r.set(d,v)},s=[];for(;await ma(Bt(n,".popmelt"))&&i(n,"store"),await ma(Bt(n,".popmelt","ambient.json"))&&i(n,"marker"),await fa(Bt(n,"package.json"))&&i(n,"package"),await fa(Bt(n,"packages","popmelt","package.json"))&&i(n,"workspace_package"),(await ha(n)).length&&s.push(n),n!==o;)n=Ru(n);for(let d of s){let l=await ha(d),v=await Promise.all(l.map(T=>_u(T)));for(let T of v.flat())i(await Gr(T),"store")}return(await Promise.all([...r].map(async([d,l])=>{let v=await Gr(d),T=await ar(v),b=[...l].sort();return{root:v,storeId:T.storeId,projectId:It(v),reason:b[0],reasons:b,initialized:l.has("store")}}))).sort((d,l)=>d.initialized!==l.initialized?d.initialized?-1:1:ga(e,d.root)-ga(e,l.root)||d.root.localeCompare(l.root))}async function ya(t=process.cwd()){return(await cn(t))[0]??null}function Gn(){return process.env.POPMELT_EXECUTION_OWNER}function Vn(){return Gn()===Sn}async function vt(t){let e=await Ht(t.root);return{...await ua({projectRoot:t.root,detached:!0,manageLease:!1}),storeId:e.storeId}}async function ln(t,e,n={}){let o=await fetch(`http://127.0.0.1:${t.port}${e}`,{...n,headers:{"Content-Type":"application/json","X-Popmelt-Project-Id":t.projectId,...n.headers}}),r=await o.json().catch(()=>null);return{response:o,body:r}}import{createHash as Cu}from"crypto";import{mkdir as $u,readFile as Ou,writeFile as Du}from"fs/promises";import{tmpdir as Nu}from"os";import{join as Ia}from"path";function wa(t,e,n){let o=new Map(t.candidates.map(s=>[s.storeId,s])),r=o.get(e);if(!r)return null;let i=[...new Set(n)].filter(s=>s!==e);return i.some(s=>!o.has(s))?null:{primary:r,mountedStores:i.map(s=>{let a=o.get(s);return{storeId:a.storeId,projectRoot:a.root,projectId:a.projectId}})}}function va(){return process.env.POPMELT_CODEX_SESSION_DIR||Ia(Nu(),"popmelt-core","codex-sessions")}function ba(t){let e=Cu("sha256").update(t).digest("hex");return Ia(va(),`${e}.json`)}function Bu(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.storeId=="string"&&!!e.storeId&&typeof e.projectRoot=="string"&&!!e.projectRoot&&typeof e.projectId=="string"&&!!e.projectId}function Ju(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.root=="string"&&!!e.root&&typeof e.storeId=="string"&&!!e.storeId&&typeof e.projectId=="string"&&!!e.projectId&&typeof e.reason=="string"&&Array.isArray(e.reasons)&&e.reasons.every(n=>typeof n=="string")&&typeof e.initialized=="boolean"}function Lu(t){if(typeof t.sessionId!="string"||!t.sessionId||typeof t.projectRoot!="string"||!t.projectRoot||typeof t.projectId!="string"||!t.projectId||!Number.isInteger(t.bridgePort)||typeof t.updatedAt!="string"||Number.isNaN(Date.parse(t.updatedAt)))return null;let e=Array.isArray(t.mountedStores)?t.mountedStores.filter(Bu):[],n=t.orientation==="automatic"||t.orientation==="explicit"||t.orientation==="workspace_default"?t.orientation:"legacy";return{version:2,status:"active",sessionId:t.sessionId,storeId:typeof t.storeId=="string"&&t.storeId?t.storeId:`store-${t.projectId}`,projectRoot:t.projectRoot,projectId:t.projectId,bridgePort:t.bridgePort,mountedStores:e,orientation:n,updatedAt:t.updatedAt}}function qu(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.status==="orientation_required"?e.version!==2||typeof e.sessionId!="string"||!e.sessionId||typeof e.cwd!="string"||!e.cwd||!Array.isArray(e.candidates)||!e.candidates.every(Ju)||typeof e.updatedAt!="string"||Number.isNaN(Date.parse(e.updatedAt))?null:e:Lu(e)}async function xa(t){let e=va();await $u(e,{recursive:!0,mode:448}),await Du(ba(t.sessionId),`${JSON.stringify(t,null,2)}
|
|
242
|
+
`,{encoding:"utf8",mode:384})}async function pn(t){await xa(t)}async function Sa(t){await xa(t)}async function Pa(t){try{let e=JSON.parse(await Ou(ba(t),"utf8")),n=qu(e);return n?.sessionId===t?n:null}catch{return null}}async function Ko(t){let e=await Pa(t);return e?.status==="active"?e:null}async function ka(t){let e=await Pa(t);return e?.status==="orientation_required"?e:null}import{createHash as Fu}from"crypto";import{mkdir as Uu,readFile as zu,writeFile as Hu}from"fs/promises";import{homedir as Wu}from"os";import{join as Qr}from"path";function Ta(){return process.env.POPMELT_CODEX_ORIENTATION_DIR||Qr(process.env.CODEX_HOME||Qr(Wu(),".codex"),"state","popmelt-core","workspace-orientations")}function Xr(t){return[...new Set(t.map(e=>e.storeId))].sort()}function Yr(t){return Fu("sha256").update(Xr(t).join("\0")).digest("hex")}function Ra(t){return Qr(Ta(),`${Yr(t)}.json`)}function Gu(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return(e.relationshipType==="writable_primary"||e.relationshipType==="mounted_read")&&typeof e.storeId=="string"&&!!e.storeId.trim()}function Vu(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=Xr(e),r=new Set(o);if(n.version!==1||n.workspaceId!==Yr(e)||!Array.isArray(n.candidateStoreIds)||n.candidateStoreIds.length!==o.length||!o.every((d,l)=>n.candidateStoreIds?.[l]===d)||!Array.isArray(n.relations)||!n.relations.every(Gu)||n.selectedBy!=="human"||typeof n.updatedAt!="string"||Number.isNaN(Date.parse(n.updatedAt)))return null;let i=n.relations.filter(d=>d.relationshipType==="writable_primary"),s=n.relations.filter(d=>d.relationshipType==="mounted_read");if(i.length!==1)return null;let a=n.relations.map(d=>d.storeId);return new Set(a).size!==a.length||a.some(d=>!r.has(d))||s.some(d=>d.storeId===i[0].storeId)?null:n}async function ja(t){try{let e=JSON.parse(await zu(Ra(t),"utf8")),n=Vu(e,t);if(!n)return null;let o=new Map(t.map(s=>[s.storeId,s])),r=n.relations.find(s=>s.relationshipType==="writable_primary").storeId,i=o.get(r);return i?{primary:i,mountedStores:n.relations.flatMap(s=>{if(s.relationshipType!=="mounted_read")return[];let a=o.get(s.storeId);return a?[{storeId:a.storeId,projectRoot:a.root,projectId:a.projectId}]:[]})}:null}catch{return null}}async function Aa(t,e){let n=Ta(),o={version:1,workspaceId:Yr(t),candidateStoreIds:Xr(t),relations:[{relationshipType:"writable_primary",storeId:e.primary.storeId},...e.mountedStores.map(r=>({relationshipType:"mounted_read",storeId:r.storeId}))],selectedBy:"human",updatedAt:new Date().toISOString()};return await Uu(n,{recursive:!0,mode:448}),await Hu(Ra(t),`${JSON.stringify(o,null,2)}
|
|
243
|
+
`,{encoding:"utf8",mode:384}),o}async function Ku(){let t=[];for await(let e of process.stdin)t.push(Buffer.isBuffer(e)?e:Buffer.from(e));return Buffer.concat(t).toString("utf8")}function un(t,e){return t==="UserPromptSubmit"&&e?{hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:e}}:{}}function Qu(t,e){return["## Ambient Popmelt Core store orientation","",`Tool session ID: ${t}. Use this only as the sessionId for Popmelt Core tool calls. It is not a paired Popmelt thread ID.`,"More than one applicable Popmelt knowledge store was found, so no store was selected or started automatically.","No Popmelt thread or turn/job exists yet. Do not report the tool session ID as a thread, turn, or job ID.","Work with the human to choose one writable primary store and any mounted read stores. If this message already makes that choice explicit, call `popmelt_orient_stores`.","Otherwise, answer any immediate diagnostic question briefly and end with one concise, plain-language orientation question. Name stores by path; omit store IDs unless the human asks for technical details.","Do not infer that a parent, child, nearest, newest, or largest store is authoritative.","","Candidates:",...e.map(n=>`- ${n.storeId}: ${n.root} (${n.initialized?"existing store":"enabled project"}; ${n.reasons.join(", ")})`)].join(`
|
|
244
|
+
`)}function Xu(t){return{root:t.projectRoot,storeId:t.storeId,projectId:t.projectId,reason:"store",reasons:["store"],initialized:!0}}async function Yu(t,e){let n=await Ko(t);if(n&&n.orientation!=="legacy")return{binding:n,project:Xu(n)};let o=await cn(e);if(!o.length)return null;if(o.length>1){let a=await ja(o);if(a){let d=await vt(a.primary),l={version:2,status:"active",sessionId:t,storeId:d.storeId,projectRoot:a.primary.root,projectId:d.projectId,bridgePort:d.port,mountedStores:a.mountedStores,orientation:"workspace_default",updatedAt:new Date().toISOString()};return await pn(l),{binding:l,project:{...a.primary,storeId:d.storeId,projectId:d.projectId}}}return await Sa({version:2,status:"orientation_required",sessionId:t,cwd:e,candidates:o,updatedAt:new Date().toISOString()}),{orientationContext:Qu(t,o)}}let r=o[0],i=await vt(r),s={version:2,status:"active",sessionId:t,storeId:i.storeId,projectRoot:r.root,projectId:i.projectId,bridgePort:i.port,mountedStores:[],orientation:"automatic",updatedAt:new Date().toISOString()};return await pn(s),{binding:s,project:{...r,storeId:i.storeId,projectId:i.projectId}}}function Zu(t){return[`Primary Popmelt store: ${t.storeId} (${t.projectRoot}).`,...t.mountedStores.length?[`Mounted Popmelt stores: ${t.mountedStores.map(e=>`${e.storeId} (${e.projectRoot})`).join(", ")}.`]:[],"Store mounts are administrative context boundaries; they do not imply explanatory hierarchy or acceptance."].join(`
|
|
245
|
+
`)}function Ma(t,e=2e4){if(t!==void 0)try{let n=JSON.stringify(t);return n.length<=e?t:{truncated:!0,preview:n.slice(0,e)}}catch{return{unavailable:!0}}}async function Ea(){let t;try{t=JSON.parse(await Ku())}catch{process.stdout.write(`{}
|
|
244
246
|
`);return}let e=t.hook_event_name;if(Vn()){process.stdout.write(`${JSON.stringify(un(e))}
|
|
245
247
|
`);return}if(!t.session_id){process.stdout.write(`${JSON.stringify(un(e))}
|
|
246
|
-
`);return}try{let n=await
|
|
248
|
+
`);return}try{let n=await Yu(t.session_id,t.cwd??process.cwd());if(!n){process.stdout.write(`${JSON.stringify(un(e))}
|
|
247
249
|
`);return}if("orientationContext"in n){process.stdout.write(`${JSON.stringify(un(e,e==="UserPromptSubmit"?n.orientationContext:void 0))}
|
|
248
250
|
`);return}let{binding:o,project:r}=n,i=await vt(r),s={...o,storeId:i.storeId,projectId:i.projectId,bridgePort:i.port,updatedAt:new Date().toISOString()};if(await pn(s),e==="UserPromptSubmit"&&t.session_id&&t.turn_id&&t.prompt){let{response:a,body:d}=await ln(i,"/ambient/turns/prepare",{method:"POST",body:JSON.stringify({sessionId:t.session_id,turnId:t.turn_id,prompt:t.prompt,model:t.model,executionOwner:Gn()})}),l=d;process.stdout.write(`${JSON.stringify(un(e,a.ok&&l?.additionalContext?`${l.additionalContext}
|
|
249
251
|
|
|
250
|
-
${
|
|
251
|
-
`);return}e==="PostToolUse"&&t.session_id&&t.turn_id&&t.tool_name?await ln(i,"/ambient/turns/event",{method:"POST",body:JSON.stringify({sessionId:t.session_id,turnId:t.turn_id,executionOwner:Gn(),toolName:t.tool_name,toolUseId:t.tool_use_id,toolInput:
|
|
252
|
-
`)}var
|
|
252
|
+
${Zu(s)}`:void 0))}
|
|
253
|
+
`);return}e==="PostToolUse"&&t.session_id&&t.turn_id&&t.tool_name?await ln(i,"/ambient/turns/event",{method:"POST",body:JSON.stringify({sessionId:t.session_id,turnId:t.turn_id,executionOwner:Gn(),toolName:t.tool_name,toolUseId:t.tool_use_id,toolInput:Ma(t.tool_input),toolResponse:Ma(t.tool_response)})}):e==="Stop"&&t.session_id&&t.turn_id&&await ln(i,"/ambient/turns/complete",{method:"POST",body:JSON.stringify({sessionId:t.session_id,turnId:t.turn_id,executionOwner:Gn(),lastAssistantMessage:t.last_assistant_message??void 0,model:t.model})})}catch{}process.stdout.write(`${JSON.stringify(un(e))}
|
|
254
|
+
`)}var em=[{name:"popmelt_orient_stores",description:"Bind an ambiguous Codex session to one writable Popmelt store and optional mounted stores. Call only after the human explicitly chooses the store orientation.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact session ID supplied by the ambient store-orientation context."},primaryStoreId:{type:"string",description:"The explicitly chosen writable store."},mountedStoreIds:{type:"array",items:{type:"string"},description:"Optional explicitly chosen read-context stores."},persistence:{type:"string",enum:["workspace_default","session_only"],default:"workspace_default",description:"Save the human choice for future sessions with the same applicable stores, unless the human explicitly requests a session-only override."}},required:["sessionId","primaryStoreId"],additionalProperties:!1}},{name:"popmelt_expand_context",description:"Retrieve additional accepted product truth, historical candidates, and provisional Imprint explanations for the current Popmelt project.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact tool session supplied by Ambient Popmelt Core context."},query:{type:"string",description:"The current question, action, or subject to contextualize."},subjectHints:{type:"array",items:{type:"string"},description:"Optional files, routes, components, or selectors."}},required:["sessionId","query"],additionalProperties:!1},annotations:{readOnlyHint:!0}},{name:"popmelt_inspect_thread",description:"Inspect one Popmelt thread and its paired human-AI turns.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact tool session supplied by Ambient Popmelt Core context."},threadId:{type:"string"}},required:["sessionId","threadId"],additionalProperties:!1},annotations:{readOnlyHint:!0}},{name:"popmelt_assess_turn",description:"Record a structured Imprint assessment and optional reusable decision candidates for the current ambient turn. Use only when the collaboration changed reusable shared understanding; ordinary completion is captured automatically.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact tool session supplied by Ambient Popmelt Core context."},threadId:{type:"string"},jobId:{type:"string"},assessmentText:{type:"string",description:"A complete <resolution> envelope containing the Imprint assessment."},semanticCandidates:{type:"array",maxItems:8,items:{type:"object",properties:{claim:{type:"string"},rationale:{type:"string"},proposedKind:{type:"string",enum:["principle","preference","rule","constraint"]},sourceText:{type:"string"}},required:["claim"],additionalProperties:!1}}},required:["sessionId","threadId","jobId","assessmentText"],additionalProperties:!1}},{name:"popmelt_review_decision",description:"Apply an explicit human resolution to an already surfaced decision candidate. Never infer this action from implementation, praise, silence, or ambiguity.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact tool session supplied by Ambient Popmelt Core context."},threadId:{type:"string"},proposalId:{type:"string"},action:{type:"string",enum:["accept","edit_and_accept","reject","defer"]},kind:{type:"string",enum:["principle","preference","rule","constraint"],description:"Required for acceptance when the surfaced candidate did not already declare a kind."},claim:{type:"string",description:"Required only for edit_and_accept."}},required:["sessionId","threadId","proposalId","action"],additionalProperties:!1}},{name:"popmelt_ground_imprint",description:"Record the human response to a surfaced Imprint grounding question using the same Yes, This time, or No semantics as the Popmelt thread surface.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"The exact tool session supplied by Ambient Popmelt Core context."},threadId:{type:"string"},transactionId:{type:"string"},action:{type:"string",enum:["yes","this_time","no"]}},required:["sessionId","threadId","transactionId","action"],additionalProperties:!1}}];function bt(t,e){return{jsonrpc:"2.0",id:t??null,result:e}}function _a(t,e,n){return{jsonrpc:"2.0",id:t??null,error:{code:e,message:n}}}function rt(t,e=!1){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t,null,2)}],structuredContent:t&&typeof t=="object"?t:{result:t},...e?{isError:!0}:{}}}async function tm(t,e,n){if(Vn())return rt({status:"already_managed_by_bridge"},!0);let o="",r="POST",i;if(t==="popmelt_expand_context")o="/ambient/context",i={query:e.query,subjectHints:e.subjectHints};else if(t==="popmelt_inspect_thread")o=`/thread/${encodeURIComponent(String(e.threadId??""))}`,r="GET";else if(t==="popmelt_assess_turn")o="/ambient/turns/assess",i={threadId:e.threadId,jobId:e.jobId,assessmentText:e.assessmentText,semanticCandidates:e.semanticCandidates};else if(t==="popmelt_review_decision")o="/memory/conversation-action",i={threadId:e.threadId,proposalId:e.proposalId,action:e.action,kind:e.kind,claim:e.claim,provider:"codex"};else if(t==="popmelt_ground_imprint")o="/imprint/action",i={threadId:e.threadId,transactionId:e.transactionId,action:e.action};else return rt({error:`Unknown tool: ${t}`},!0);let s=await ln(n,o,{method:r,...i?{body:JSON.stringify(i)}:{}});return rt(s.body,!s.response.ok)}async function nm(t){let e=typeof t.sessionId=="string"?t.sessionId.trim():"",n=typeof t.primaryStoreId=="string"?t.primaryStoreId.trim():"",o=Array.isArray(t.mountedStoreIds)?[...new Set(t.mountedStoreIds.filter(l=>typeof l=="string"&&!!l.trim()).map(l=>l.trim()))]:[],r=t.persistence==="session_only"?"session_only":"workspace_default";if(!e||!n)return{result:rt({status:"invalid_orientation",message:"sessionId and primaryStoreId are required."},!0)};let i=await ka(e);if(!i)return{result:rt({status:"orientation_not_pending"},!0)};let s=wa(i,n,o);if(!s)return{result:rt({status:"invalid_store_selection",candidateStoreIds:i.candidates.map(l=>l.storeId)},!0)};r==="workspace_default"&&await Aa(i.candidates,s);let a=await vt(s.primary),d={version:2,status:"active",sessionId:e,storeId:a.storeId,projectRoot:s.primary.root,projectId:a.projectId,bridgePort:a.port,mountedStores:s.mountedStores,orientation:"explicit",updatedAt:new Date().toISOString()};return await pn(d),{binding:d,result:rt({status:"oriented",primaryStore:{storeId:d.storeId,projectRoot:d.projectRoot},mountedStores:s.mountedStores,persistence:r,message:r==="workspace_default"?"The store orientation is active and saved as the workspace default. Future sessions with the same applicable stores will inherit it.":"The store orientation is active for this session only."})}}async function Ca(){let t=new Map,e="",n=o=>process.stdout.write(`${JSON.stringify(o)}
|
|
253
255
|
`);for await(let o of process.stdin){e+=Buffer.isBuffer(o)?o.toString("utf8"):String(o);let r=e.indexOf(`
|
|
254
256
|
`);for(;r>=0;){let i=e.slice(0,r).trim();if(e=e.slice(r+1),r=e.indexOf(`
|
|
255
|
-
`),!i)continue;let s;try{s=JSON.parse(i)}catch{n(
|
|
256
|
-
`,"utf8")}async function
|
|
257
|
-
`,"utf8");let n=await
|
|
258
|
-
${be} Shutting down bridge...`),await t.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function
|
|
257
|
+
`),!i)continue;let s;try{s=JSON.parse(i)}catch{n(_a(null,-32700,"Parse error"));continue}if(!(s.id===void 0||s.id===null))if(s.method==="initialize"){let a=typeof s.params?.protocolVersion=="string"?s.params.protocolVersion:"2025-06-18";n(bt(s.id,{protocolVersion:a,capabilities:{tools:{listChanged:!1}},serverInfo:{name:"popmelt-core",version:Ye}}))}else if(s.method==="ping")n(bt(s.id,{}));else if(s.method==="tools/list")n(bt(s.id,{tools:em}));else if(s.method==="tools/call"){let a=typeof s.params?.name=="string"?s.params.name:"",d=s.params?.arguments&&typeof s.params.arguments=="object"?s.params.arguments:{};if(Vn())n(bt(s.id,rt({status:"already_managed_by_bridge"},!0)));else try{let l=typeof d.sessionId=="string"?d.sessionId:"";if(a==="popmelt_orient_stores"){let b=await nm(d);if(b.binding){let R={port:b.binding.bridgePort,projectId:b.binding.projectId};t.set(l,await Wn(R))}n(bt(s.id,b.result));continue}let v=l?await Ko(l):null;if(!v){n(bt(s.id,rt({status:"session_not_bound",message:"Pass the exact tool session supplied by Ambient Popmelt Core context."},!0)));continue}let T={port:v.bridgePort,projectId:v.projectId};t.has(l)||t.set(l,await Wn(T)),n(bt(s.id,await tm(a,d,T)))}catch(l){n(bt(s.id,rt({error:l instanceof Error?l.message:String(l)},!0)))}}else n(_a(s.id,-32601,`Method not found: ${s.method??""}`))}}await Promise.all([...t.values()].map(o=>o?.release()))}import{execFile as om}from"child_process";import{cp as rm,mkdir as $a,readFile as im,rm as Oa,stat as sm,writeFile as Da}from"fs/promises";import{homedir as am}from"os";import{dirname as Zr,join as xt}from"path";import{fileURLToPath as Na}from"url";var ut="popmelt-core";function ei(){let t=am();return{pluginPath:xt(t,"plugins",ut),marketplacePath:xt(t,".agents","plugins","marketplace.json"),codexHome:process.env.CODEX_HOME||xt(t,".codex")}}async function Ba(t){return sm(t).then(()=>!0,()=>!1)}async function dm(){let t=Zr(Na(import.meta.url)),e=[xt(t,"..","codex-plugin"),xt(t,"..","..","codex-plugin")];for(let n of e)if(await Ba(xt(n,".codex-plugin","plugin.json")))return n;throw new Error("The Popmelt Core Codex plugin template is missing from this package.")}async function ti(t){try{let e=JSON.parse(await im(t,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}}async function Ja(t,e){await $a(Zr(t),{recursive:!0}),await Da(t,`${JSON.stringify(e,null,2)}
|
|
258
|
+
`,"utf8")}async function ni(t){return new Promise(e=>{om("codex",t,{encoding:"utf8",timeout:3e4},(n,o,r)=>{let i=!n;e({ok:i,output:i?(o??"").trim():`${o??""}${r??""}`.trim()})})})}function cm(t){try{return JSON.parse(t).installed?.find(n=>n.name===ut)}catch{return}}async function La(){let t=ei(),e=await dm();await $a(Zr(t.pluginPath),{recursive:!0}),await Oa(t.pluginPath,{recursive:!0,force:!0}),await rm(e,t.pluginPath,{recursive:!0}),await Da(xt(t.pluginPath,"runtime.json"),`${JSON.stringify({cliPath:Na(import.meta.url)},null,2)}
|
|
259
|
+
`,"utf8");let n=await ti(t.marketplacePath);n.name||="personal",n.interface={displayName:n.interface?.displayName||"Personal"};let o={name:ut,source:{source:"local",path:`./plugins/${ut}`},policy:{installation:"AVAILABLE",authentication:"ON_INSTALL"},category:"Developer Tools"};n.plugins=[...(n.plugins??[]).filter(i=>i.name!==ut),o],await Ja(t.marketplacePath,n);let r=await ni(["plugin","add",`${ut}@${n.name}`,"--json"]);return{status:r.ok?"installed":"files_installed",pluginPath:t.pluginPath,marketplacePath:t.marketplacePath,marketplace:n.name,codex:r.output||(r.ok?"installed":"Codex plugin registration must be retried"),restartCodexRequired:!0,newConversationRequired:!0,nextSteps:["Restart Codex completely so the app reloads the plugin hooks and MCP server.","Review the Popmelt hooks only if Codex marks them new or changed.","Start a new conversation in the target project."]}}async function qa(){let t=ei(),e=await ni(["plugin","remove",ut,"--json"]),n=await ti(t.marketplacePath);return n.plugins=(n.plugins??[]).filter(o=>o.name!==ut),await Ja(t.marketplacePath,n),await Oa(t.pluginPath,{recursive:!0,force:!0}),{status:"uninstalled",pluginPath:t.pluginPath,marketplacePath:t.marketplacePath,codex:e.output}}async function oi(t=process.cwd()){let e=ei(),n=await cn(t),o=n.length===1?n[0]:null,r=await ti(e.marketplacePath),i=await ni(["plugin","list","--json"]),s=cm(i.output);return{plugin:{sourceInstalled:await Ba(xt(e.pluginPath,".codex-plugin","plugin.json")),marketplaceRegistered:!!r.plugins?.some(a=>a.name===ut),codexRegistered:!!s,enabled:s?.enabled,version:s?.version,path:e.pluginPath,...i.ok?{}:{codexError:i.output}},project:o,projects:n,orientationRequired:n.length>1}}async function Fa(t=process.cwd()){let e=await oi(t),n=await cn(t);if(n.length>1)return{ok:!1,...e,bridge:{status:"orientation_required",message:"Choose one writable store before starting a bridge.",candidateStoreIds:n.map(r=>r.storeId)}};let o=n[0]??await ya(t);if(!o)return{ok:!1,...e,bridge:{status:"project_not_enabled"}};try{let r=await vt(o),i=await fetch(`http://127.0.0.1:${r.port}/status`,{headers:{"X-Popmelt-Project-Id":r.projectId}});return{ok:i.ok,...e,bridge:{status:i.ok?"healthy":"unhealthy",port:r.port,projectId:r.projectId}}}catch(r){return{ok:!1,...e,bridge:{status:"unavailable",error:r instanceof Error?r.message:String(r)}}}}var be="\x1B[35m[popmelt]\x1B[0m";async function fm(){let t=process.argv.slice(2);if(t[0]==="memory"){await ym(t.slice(1));return}if(t[0]==="codex"){await hm(t.slice(1));return}if(t[0]==="wrap"){let e=t.indexOf("--");(e===-1||e===t.length-1)&&(console.error(`${be} Usage: popmelt wrap -- <dev command>`),console.error(`${be} Example: popmelt wrap -- next dev`),console.error(`${be} Example: popmelt wrap -- astro dev`),process.exit(1));let n=t.slice(e+1);await vm(n);return}if(t[0]==="bridge"){await Im();return}if(t[0]==="stop"){await wm();return}console.log(`${be} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(" popmelt codex install Install the ambient Codex plugin"),console.log(" popmelt codex status Inspect plugin and project activation"),console.log(" popmelt codex doctor Verify the plugin and local bridge"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}async function hm(t){let e=t[0];if(e==="hook"){await Ea();return}if(e==="mcp"){await Ca();return}let n=e==="install"?await La():e==="uninstall"?await qa():e==="status"?await oi():e==="doctor"?await Fa():null;if(!n){console.log(`${be} Codex integration commands`),console.log(""),console.log(" popmelt codex install Install/update the personal popmelt-core plugin"),console.log(" popmelt codex uninstall Remove the personal popmelt-core plugin"),console.log(" popmelt codex status Report plugin and project activation"),console.log(" popmelt codex doctor Start and verify the project bridge"),e&&e!=="help"&&e!=="--help"&&(process.exitCode=1);return}console.log(JSON.stringify(n,null,2))}function mn(t,e){let n=t.indexOf(e);return n>=0?t[n+1]:void 0}function gm(){console.log(`${be} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function ym(t){if(t[0]!=="import"&&t[0]!=="review"){gm(),t.length>0&&t[0]!=="help"&&t[0]!=="--help"&&(process.exitCode=1);return}if(t.includes("--write")||t.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=mn(t,"--project")??process.cwd(),n=mn(t,"--project-key"),o=await Ot({projectRoot:e,projectKey:n});if(t[0]==="review"){let a=mn(t,"--subject");if(!a)throw new Error("memory review requires --subject <hint>");let d=An(o.bundle,{subjectHints:[a],action:mn(t,"--action"),maxPackets:Number(mn(t,"--max-packets")??3),maxEstimatedTokens:Number(mn(t,"--max-tokens")??1200)});if(t.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${be} Contextual memory review (read-only)`),console.log(`${be} Subject: ${a}`),console.log(`${be} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${be} Uncertainty: ${d.uncertainty}`);for(let[l,v]of d.packets.entries())console.log(""),console.log(`${l+1}. ${v.proposal.claim}`),console.log(` Authority: ${v.authority}; presentation: ${v.presentation}; implementation: ${v.implementation.state}`),console.log(` Why now: ${v.trigger.reason}`),console.log(` Proposal: ${v.proposal.id}`);return}if(t.includes("--json")){console.log(JSON.stringify(o.report,null,2));return}let r=o.report,i=r.proofCases.filter(a=>a.threadFound).length,s=r.schemaIssues.filter(a=>a.severity==="error");if(console.log(`${be} Legacy memory analysis (read-only)`),console.log(`${be} Project: ${r.projectRoot}`),console.log(`${be} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${be} Imported: ${Object.entries(r.imported).map(([a,d])=>`${d} ${a}`).join(", ")}`),console.log(`${be} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${be} Model values deferred: ${r.deferredModelEntries}`),console.log(`${be} Proof coverage: ${i}/${r.proofCases.length} threads found`),console.log(`${be} Schema validation: ${s.length===0?"passed":`${s.length} errors`}`),r.issues.length){let a=new Map;for(let d of r.issues)a.set(d.code,(a.get(d.code)??0)+1);console.log(`${be} Review flags: ${[...a].map(([d,l])=>`${d}=${l}`).join(", ")}`)}}async function Im(){let t=await Hn({projectRoot:process.cwd()});console.log(`${be} Bridge running on http://localhost:${t.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
260
|
+
${be} Shutting down bridge...`),await t.close(),e()};process.on("SIGINT",n),process.on("SIGTERM",n)})}async function wm(){let t=mm(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await pm(t,"utf8"))}catch{console.log(`${be} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${be} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(n){if(n.code==="ESRCH")console.log(`${be} Bridge process ${e.pid} already dead`);else throw n}try{await um(t)}catch{}}async function vm(t){let e=await Hn({projectRoot:process.cwd()});console.log(`${be} Bridge running on http://localhost:${e.port}`);let[n,...o]=t;console.log(`${be} Starting: ${t.join(" ")}`);let r=lm(n,o,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),i=s=>{r.kill(s)};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),r.on("exit",async(s,a)=>{await e.close(),a?process.kill(process.pid,a):process.exit(s??0)})}fm().catch(t=>{console.error(`${be} Fatal:`,t),process.exit(1)});
|