@popmelt.com/core 0.8.14 → 0.8.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +65 -57
- package/dist/canvas.mjs +1 -1
- package/dist/chunk-U35GCRMU.mjs +1 -0
- package/dist/cli.mjs +59 -51
- package/dist/index.mjs +64 -41
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-next.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-LYQ2TJFR.mjs +221 -0
- package/dist/server.d.mts +3 -1
- package/dist/server.mjs +60 -52
- package/package.json +1 -1
- package/dist/chunk-JJEESG5Y.mjs +0 -1
- package/dist/server-SESHQYMR.mjs +0 -213
package/dist/bridge-entry.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdir as
|
|
1
|
+
import{mkdir as el,unlink as tl,writeFile as nl}from"fs/promises";import{join as Zr}from"path";import{execFileSync as kd,spawn as Ur}from"child_process";import{randomUUID as it}from"crypto";import{mkdir as Rd,readFile as zr,readdir as Pd,realpath as jd,stat as Ad,unlink as Md,writeFile as io}from"fs/promises";import{createServer as Ed}from"http";import{tmpdir as _d}from"os";import{basename as ro,dirname as Cd,isAbsolute as Qr,join as De,relative as $d,resolve as Od}from"path";import{fileURLToPath as Dd}from"url";function ai(o,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -18,28 +18,31 @@ import{mkdir as Xd,unlink as Yd,writeFile as Zd}from"fs/promises";import{join as
|
|
|
18
18
|
}}
|
|
19
19
|
</script>
|
|
20
20
|
<script type="module">
|
|
21
|
-
|
|
21
|
+
const isProxied = location.pathname === '/popmelt' || location.pathname.startsWith('/popmelt/');
|
|
22
|
+
const bridgeOrigin = isProxied ? location.origin + '/popmelt' : location.origin;
|
|
23
|
+
const canvasModule = isProxied ? bridgeOrigin + '/app.mjs' : location.origin + '/canvas/app.mjs';
|
|
24
|
+
const { mountCanvas } = await import(canvasModule);
|
|
22
25
|
mountCanvas(document.getElementById('root'), {
|
|
23
|
-
devOrigin:
|
|
24
|
-
bridgeOrigin
|
|
26
|
+
devOrigin: isProxied ? location.origin : ${JSON.stringify(e)},
|
|
27
|
+
bridgeOrigin,
|
|
25
28
|
});
|
|
26
29
|
</script>
|
|
27
30
|
</body>
|
|
28
|
-
</html>`}var
|
|
29
|
-
|
|
30
|
-
${t}`:t;return
|
|
31
|
-
\u2026[truncated]`:n}function vn(
|
|
32
|
-
`)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash";l.push(L),c?.({type:"tool_use",jobId:
|
|
34
|
-
`)}`)),
|
|
35
|
-
`)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(o.includes("file")||o.includes("write")||o.includes("edit"))){let r=o.includes("write")?"Write":o.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function Fs(i){if(typeof i.error=="string")return i.error;if(i.error&&typeof i.error=="object"){let e=i.error;if(typeof e.message=="string")return e.message}if(typeof i.message=="string"&&Qt(i).toLowerCase().includes("error"))return i.message}function Kt(i,e,t=[]){for(let n of e){let o=i[n];if(typeof o=="string")return o}for(let[n,o]of Object.entries(i)){if(!o||typeof o!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=Kt(o,e);if(r)return r}}function gi(i){let e=Qt(i).toLowerCase();return(typeof i.role=="string"?i.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as qs,readFile as Us}from"fs/promises";import{join as yi}from"path";var bn=class{constructor(e){let t=yi(e,".popmelt");this.decisionsDir=yi(t,"decisions")}async listDecisionIds(){try{return(await qs(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await Us(yi(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as zs,randomUUID as Ws}from"crypto";import{mkdir as vi,readFile as wo,readdir as bo,rename as xn,stat as xo,unlink as Sn,writeFile as kn}from"fs/promises";import{extname as Gs,join as Ve}from"path";var Hs=10080*60*1e3,Vs=600*1e3,Ks=3600*1e3;function Qs(i){return i==="image/svg+xml"?".svg":i==="text/plain"?".txt":".bin"}function Xs(i,e){return[...i.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var Tn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let t=Ws(),n=Qs(e.mimeType),o=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:Xs(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:o};await vi(this.draftsDir,{recursive:!0});let c=Ve(this.draftsDir,o),d=Ve(this.draftsDir,`${t}.json`),p=`${c}.part`,x=`${d}.part`;return await kn(p,e.data),await xn(p,c),await kn(x,JSON.stringify(s,null,2)),await xn(x,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let o=await this.readManifest(n.id);if(!o)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(o.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ve(this.draftsDir,o.contentFile),s=await wo(r),c=zs("sha256").update(s).digest("hex"),d=Ve(this.mediaDir,`${c}${Gs(o.contentFile)||".bin"}`);await vi(this.mediaDir,{recursive:!0});try{await xo(d)}catch{let p=`${d}.part`;await kn(p,s),await xn(p,d)}(t[n.annotationId]??=[]).push({id:o.id,name:o.name,mimeType:o.mimeType,size:o.size,kind:o.kind,path:d}),o.releasedAt=Date.now(),o.lastSeenAt=Date.now(),await this.writeManifest(o)}return t}async sweep(e=Date.now()){let t;try{t=await bo(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let o=Ve(this.draftsDir,n);if(n.endsWith(".part")){let c=await xo(o).catch(()=>null);c&&e-c.mtimeMs>Ks&&await Sn(o).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Vs:e-r.lastSeenAt>Hs)||await Promise.all([Sn(o).catch(()=>{}),Sn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await bo(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Sn(Ve(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await wo(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await vi(this.draftsDir,{recursive:!0});let t=Ve(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await kn(n,JSON.stringify(e,null,2)),await xn(n,t)}};import{randomUUID as So}from"crypto";import{mkdir as Ii,readFile as wi,writeFile as Rn}from"fs/promises";import{dirname as bi,join as At}from"path";var Ke="[ProjectionWorker]",Ys={version:1,runs:[]},Zs={version:1,updatedAt:0,proposals:[]},ea=12;function ta(i){return Array.isArray(i)?i.map((e,t)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function ko(i){let e=[];for(let t of i){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Ke} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(o=>typeof o=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function na(i,e,t){return{decisionCount:i.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function ia(i,e,t){let n=new Set(e),o=new Set,r=Array.isArray(i.rules)?i.rules:[];for(let v of r){if(!v||typeof v!="object")continue;let f=v.sources;if(Array.isArray(f))for(let l of f)typeof l=="string"&&n.has(l)&&o.add(l)}let s=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?i.tokens:{},c=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?i.components:{},d=Array.isArray(t?.rules)?t.rules:[],p=r.filter(v=>{if(!v||typeof v!="object")return!1;let f=v.id,l=typeof f=="string"?d.find(h=>h&&typeof h=="object"&&h.id===f):void 0;return JSON.stringify(l)!==JSON.stringify(v)}).length,x=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},T=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},k=Object.keys(s).filter(v=>JSON.stringify(s[v])!==JSON.stringify(x[v])).length,P=Object.keys(c).filter(v=>JSON.stringify(c[v])!==JSON.stringify(T[v])).length;return{ruleCount:p,tokenSectionCount:k,componentCount:P,coveredDecisionIds:[...o],uncoveredDecisionIds:e.filter(v=>!o.has(v))}}function oa(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function ra(i,e,t){let n=i[e];if(n&&typeof n=="object")return n;let o=typeof t=="number"?[]:{};return i[String(e)]=o,o}function Pn(i,e,t){let n=i;for(let r=0;r<e.length-1;r++)n=ra(n,e[r],e[r+1]);let o=e[e.length-1];n[String(o)]=oa(t)}function To(i,e){let t=i;for(let o=0;o<e.length-1;o++){let r=t[String(e[o])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function sa(i,e){if(!i)return{exists:!1};let t=i;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function aa(i,e){return Array.isArray(e)?i===void 0?e.length>0:!Array.isArray(i)||e.length<=i.length?!1:i.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Ro(i,e){if(i.authorityStatus!=="accepted"||!i.changes?.length)return null;for(let t of i.changes){let n=sa(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?aa(n.exists?n.value:void 0,t.value):!n.exists))return null}return i.changes}var jn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=At(e,".popmelt");this.runsPath=At(n,"projection-runs.json"),this.legacyRunsPath=At(n,"materialization-runs.json"),this.proposalsPath=At(n,"projection-queue.json"),this.legacyProposalsPath=At(n,"model-proposals.json"),this.modelPath=At(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await wi(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=ta(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let o=n.key.split(".");n.value===null?To(t,o):Pn(t,o,n.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(ea),t=new Set((await this.loadModelProposals()).proposals.flatMap(o=>o.status==="pending"&&o.authorityStatus==="accepted"?o.decisionIds:[]));return{decisions:e.filter(o=>!t.has(o.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let n=await this.selectUnprojectedPatternDecisions(),o=n.decisions;if(o.length===0)return{processedIds:[],success:!0};let r=o.map(v=>v.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=pa(o,s),d=na(o,n.totalCandidateDecisionCount,c);t=So().slice(0,8);let p={id:t,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(p);let x=!0,T,k,P;try{let v=`projection-${Date.now()}`,{provider:f,result:l}=this.spawnModelAgent(v,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});p={...p,provider:f},await this.persistRun(p);let h=await l;if(!h.success)x=!1,T=h.error,console.error(`${Ke} ${f} spawn error:`,T);else{let u=la(h.text,r);if(u){let m=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of u)Pn(m,g.path,g.value);Array.isArray(m.rules)&&(m.rules=ko(m.rules));let j=ia(m,r,s);if(u){let g=[...new Set(u.flatMap(B=>B.decisionIds))];j.coveredDecisionIds=g,j.uncoveredDecisionIds=r.filter(B=>!g.includes(B))}k=j;let b=await this.createModelProposal({decisionIds:r,proposedModel:m,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:k,changes:u});P=b.id,console.log(`${Ke} Created model proposal ${b.id} for ${r.length} decision(s)`)}else x=!1,T="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${T}`)}}catch(v){x=!1,T=v instanceof Error?v.message:String(v),console.error(`${Ke} Error:`,T)}return await this.persistRun({...p,status:x?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:k,proposalId:P}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:x,error:T}),{processedIds:r,success:x,error:T,runId:t,proposalId:P}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ko(e.rules)),await Rn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await Ii(bi(this.runsPath),{recursive:!0}),await Rn(this.runsPath,JSON.stringify(t,null,2)),t):{...Ys,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let o=await this.readProposalStore(this.legacyProposalsPath);o&&(e={version:1,updatedAt:Date.now(),proposals:o.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Zs,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(o=>{if(o.proposedModel)return o;let r=structuredClone(n);for(let s of o.changes??[])Pn(r,s.path,s.value);return{...o,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>o.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,o)=>n.createdAt-o.createdAt||n.updatedAt-o.updatedAt)}async applySelectedModelProposal(e,t,n,o="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of t)!Array.isArray(d.path)||d.path.length===0||(d.remove?To(s,d.path):Pn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:o,error:void 0,selectedChanges:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:So().slice(0,8),status:"pending",title:ca(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"}.`:da(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(o=>o.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),o=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(o={...r,...t,updatedAt:Date.now()},o)),o?(n.updatedAt=Date.now(),await this.persistModelProposals(n),o):null}async persistModelProposals(e){try{await Ii(bi(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...o})=>o)};await Rn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(o=>o.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await Ii(bi(this.runsPath),{recursive:!0}),await Rn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await wi(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await wi(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,o){let r=n.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...wn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:yn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...vn(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:o.maxTurns,maxBudgetUsd:o.maxBudgetUsd,allowedTools:o.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function ca(i){let t=(Array.isArray(i.rules)?i.rules:[]).find(o=>o&&typeof o=="object"&&typeof o.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function da(i,e){let t=Array.isArray(i.rules)?i.rules.length:0,n=i.tokens&&typeof i.tokens=="object"&&!Array.isArray(i.tokens)?Object.keys(i.tokens).length:0,o=i.components&&typeof i.components=="object"&&!Array.isArray(i.components)?Object.keys(i.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${o} component entr${o===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function la(i,e){let t=i.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let o=new Set(e),r=n.flatMap((s,c)=>{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 p=d.path[0];if(p!=="tokens"&&p!=="components"&&p!=="rules")return[];if(p==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(T=>typeof T=="string"&&o.has(T)):[];return x.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:x,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function pa(i,e){let t=i.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
31
|
+
</html>`}var hs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),gs=new Set(["default","flex","fast","priority"]);function jt(o){let e=typeof o.reasoningEffort=="string"&&hs.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&gs.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function yn(o){let e=[];return o?.reasoningEffort&&e.push(`model_reasoning_effort=${JSON.stringify(o.reasoningEffort)}`),o?.serviceTier&&e.push(`service_tier=${JSON.stringify(o.serviceTier)}`),e}import{spawn as ys}from"child_process";import{createInterface as vs}from"readline";function Ht(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
|
|
32
|
+
|
|
33
|
+
${t}`:t;return o.push(n),n}var Is=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"]),ci=1e5;function ws(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Is.has(t))return;let n;if(o.name==="Write"&&typeof o.input?.content=="string"?n=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(n=o.input.new_string),!!n)return n.length>ci?n.slice(0,ci)+`
|
|
34
|
+
\u2026[truncated]`:n}function vn(o,e){let{prompt:t,projectRoot:n,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:u,reasoningEffort:I,timeoutMs:k=3e5,onEvent:T}=e,P=[];d?P.push("--resume",d,"-p",t):P.push("-p",t),P.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),u&&P.push("--model",u),I&&P.push("--effort",I);for(let l of s)P.push("--allowedTools",l);let x=ys(c,P,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(l=>{let f,m=[],h=[],j=[],b=!1,g="",B,E,R=!1,N=setTimeout(()=>{R=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},k),V=vs({input:x.stdout}),K=new Set;V.on("line",Q=>{if(Q.trim())try{let w=JSON.parse(Q);w.session_id&&!f&&(f=w.session_id);let H=w.type??(w.event?.type?`event.${w.event.type}`:"unknown");if(K.add(H),w.type==="result"&&w.result&&m.length===0){let L=typeof w.result=="string"?w.result:"";if(L){let O=Ht(m,L);O&&T?.({type:"delta",jobId:o,text:O},o)}}if(w.type==="assistant"&&Array.isArray(w.message?.content)){typeof w.error=="string"&&(B=w.error);for(let L of w.message.content){if(L.type==="text"&&L.text){let O=Ht(m,L.text);O&&T?.({type:"delta",jobId:o,text:O},o)}if(L.type==="tool_use"&&L.name){let O=L.input?.file_path||L.input?.path||void 0,he=ws(L);if(T?.({type:"tool_use",jobId:o,tool:L.name,...O?{file:O}:{},...he?{content:he}:{}},o),L.name==="Edit"&&L.input?.file_path){let J={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};h.push(J),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:J.file_path,oldString:typeof J.old_string=="string"?J.old_string:void 0,newString:typeof J.new_string=="string"?J.new_string:void 0,replaceAll:typeof J.replace_all=="boolean"?J.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(h.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),j.push({sequence:j.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&&T?.({type:"thinking",jobId:o,text:L.thinking},o)}}w.type==="result"&&w.is_error===!0&&(b=!0,typeof w.error=="string"&&(B=w.error),typeof w.result=="string"&&(E=w.result)),w.type==="user"&&w.tool_use_result?.file?.filePath&&T?.({type:"tool_use",jobId:o,tool:"Read",file:w.tool_use_result.file.filePath},o)}catch{}});let G=[];x.stderr?.on("data",Q=>{G.push(Q.toString())}),x.on("close",Q=>{if(clearTimeout(N),V.close(),m.length===0&&K.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...K].join(", ")}`),R)b=!0,g=`Timed out after ${Math.round(k/6e4)} minutes`;else if(Q!==0&&Q!==null){b=!0;let H=G.join("").trim(),L=m.join("").trim(),O=m.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";g=H||E||L||`Claude process exited with code ${Q}${O}`}b&&!g&&E&&(g=E);let w=bs(g,B);l({sessionId:f,text:m.join(""),success:!b,error:b?w.message:void 0,errorCode:b?w.code:void 0,recoverableError:b?w.recoverable:void 0,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})}),x.on("error",Q=>{clearTimeout(N),b=!0,g=Q.message,l({sessionId:f,text:m.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})})});return{process:x,result:p}}function bs(o,e){let t=o.trim()||"Claude CLI failed",n=`${e??""} ${t}`.toLowerCase();return n.includes("authentication_failed")||n.includes("not logged in")||n.includes("please run /login")||n.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:n.includes("model")&&(n.includes("not found")||n.includes("unknown")||n.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as xs,spawnSync as fi}from"child_process";import{readFileSync as Ss,statSync as Ts}from"fs";import{basename as ks,extname as Rs,isAbsolute as Ps,relative as hi,resolve as js}from"path";import{createInterface as As}from"readline";function di(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var li=new Set([".md",".txt",".json",".ts",".tsx",".js",".jsx",".css",".scss",".html",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".py",".rb",".go",".rs",".java",".c",".h",".cpp",".hpp",".swift",".kt",".sql",".graphql",".svg",".env",".gitignore",".prettierrc",".eslintrc"]),ho=2e5,Ms=1e5,gi=2e5;function yi(o){let e=ks(o).toLowerCase(),t=Rs(o).toLowerCase();return li.has(t)||li.has(e)}function Vt(o,e){let t=Ps(e)?e:js(o,e),n=hi(o,t);return n===""||n.startsWith("..")?null:t}function In(o,e){if(!yi(e))return;let t=Vt(o,e);if(t)try{let n=Ts(t);return n.isFile()?n.size>ho?{exists:!0,truncated:!0}:{exists:!0,content:Ss(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Es(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function _s(o){let e=o?.toLowerCase()??"";return e.includes("add")||e.includes("create")?"create":e.includes("delete")||e.includes("remove")?"delete":e.includes("rename")||e.includes("move")?"rename":e.includes("modify")||e.includes("update")||e.includes("edit")?"modify":"unknown"}function pi(o){return Es(o,["patch","diff","unifiedDiff","unified_diff"])}function go(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function ui(o,e){let t=fi("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:gi+65536});return t.status!==0?null:t.stdout??""}function Cs(o){let e=new Set;for(let t of o.split(`
|
|
35
|
+
`)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let i=n.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function mi(o){let e=ui(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=ui(o,["diff","--no-ext-diff","HEAD","--"])??"",n=go(t,gi);return{status:e,changedFiles:Cs(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function $s(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function Os(o,e){if(!yi(e))return;let t=Vt(o,e);if(!t)return;let n=hi(o,t);if(n===""||n.startsWith(".."))return;let i=fi("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:ho+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=go(r,ho);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Ds(o,e,t){return e.map(n=>{let i=t.has(n)?t.get(n):Os(o,n),r=In(o,n);return{filePath:n,...i?{before:i}:{},...r?{after:r}:{}}})}function wn(o,e){let{prompt:t,projectRoot:n,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:u=[]}=e,I=[];if(r){I.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let P of u)I.push("-c",P);s&&I.push("-m",s),I.push(r),I.push(t),i&&I.push("--image",i)}else{I.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let P of u)I.push("-c",P);s&&I.push("-m",s),I.push(t),i&&I.push("--image",i)}let k=xs("codex",I,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),T=new Promise(P=>{let x,p=[],l=[],f=[],m=new Map,h=new Map,j=!1,b="",g=As({input:k.stdout}),B=new Set;g.on("line",R=>{if(R.trim())try{let N=JSON.parse(R),V=N.type??"unknown";if(B.add(V),V==="thread.started"&&N.thread_id&&!x&&(x=N.thread_id),(V==="item.agentMessage.delta"||V==="item/agentMessage/delta")&&N.delta?.text&&(p.push(N.delta.text),c?.({type:"delta",jobId:o,text:N.delta.text},o)),(V==="item.reasoning.delta"||V==="item/reasoning/delta")&&N.delta?.text&&c?.({type:"thinking",jobId:o,text:N.delta.text},o),(V==="item.started"||V==="item/started")&&N.item){let K=N.item.type;if(K==="command_execution"){let G=N.item.command,Q=G?di(G):void 0,w=mi(n),H=new Map;for(let O of w?.changedFiles??[])H.set(O,In(n,O));typeof N.item.id=="string"&&h.set(N.item.id,{...G?{rawCommand:G}:{},...Q?{command:Q}:{},...w?{beforeWorktree:w}:{},beforeSnapshots:H});let L=Q?`Bash: ${Q.split(`
|
|
36
|
+
`)[0].slice(0,80)}`:"Bash";l.push(L),c?.({type:"tool_use",jobId:o,tool:"Bash",...Q?{content:Q}:{}},o)}else if(K==="file_change"){let G=N.item.filename||N.item.path;G&&!m.has(G)&&m.set(G,In(n,G)),l.push(G?`Edit ${G.split("/").pop()}`:"Edit");let Q=G?Vt(n,G)??G:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...Q?{file:Q}:{}},o)}else if(K==="file_read"){let G=N.item.filename||N.item.path;l.push(G?`Read ${G.split("/").pop()}`:"Read");let Q=G?Vt(n,G)??G:void 0;c?.({type:"tool_use",jobId:o,tool:"Read",...Q?{file:Q}:{}},o)}else if(K==="web_search")l.push("WebSearch"),c?.({type:"tool_use",jobId:o,tool:"WebSearch"},o);else if(K==="mcp_tool_call"){let G=N.item.tool_name||N.item.name||"MCP";l.push(G),c?.({type:"tool_use",jobId:o,tool:G},o)}}if((V==="item.completed"||V==="item/completed")&&N.item){if(N.item.type==="agent_message"){let K=N.item.text;if(typeof K=="string"&&K){let G=Ht(p,K);G&&c?.({type:"delta",jobId:o,text:G},o)}}else if(N.item.type==="reasoning"){let K=N.item.text;typeof K=="string"&&K&&c?.({type:"thinking",jobId:o,text:K},o)}else if(N.item.type==="file_change"&&Array.isArray(N.item.changes))for(let K of N.item.changes){let G=K.path||K.filename,Q=K.kind==="add"?"Write":"Edit";if(G){l.push(`${Q} ${G.split("/").pop()}`);let w=Vt(n,G)??G;c?.({type:"tool_use",jobId:o,tool:Q,file:w},o);let H=K,L=typeof H.kind=="string"?H.kind:void 0,O=_s(L),he=m.get(G),J=In(n,G);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:O,filePath:G,...he?{before:he}:{},...J?{after:J}:{},...pi(H)?{patch:pi(H)}:{},...L?{rawKind:L}:{}}),m.set(G,J)}}else if(N.item.type==="command_execution"){let K=typeof N.item.id=="string"?N.item.id:void 0,G=K?h.get(K):void 0,Q=typeof N.item.command=="string"?N.item.command:G?.rawCommand,w=Q?di(Q):G?.command,H=mi(n);if($s(G?.beforeWorktree,H)){let L=[...new Set([...G?.beforeWorktree?.changedFiles??[],...H?.changedFiles??[]])],O=typeof N.item.aggregated_output=="string"?go(N.item.aggregated_output,Ms):void 0,he=typeof N.item.exit_code=="number"?N.item.exit_code:N.item.exit_code===null?null:void 0,J=typeof N.item.status=="string"?N.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Q?{rawCommand:Q}:{},...w?{command:w}:{},...he!==void 0?{exitCode:he}:{},...J?{status:J}:{},...O?{output:O.text}:{},...O?.truncated?{outputTruncated:!0}:{},...G?.beforeWorktree?{beforeWorktree:G.beforeWorktree}:{},...H?{afterWorktree:H}:{},...L.length>0?{touchedFiles:Ds(n,L,G?.beforeSnapshots??new Map)}:{}})}K&&h.delete(K)}}V==="turn.failed"&&(j=!0,b=N.error?.message||N.message||"Turn failed")}catch{}});let E=[];k.stderr?.on("data",R=>{E.push(R.toString())}),k.on("close",R=>{g.close(),p.length===0&&B.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...B].join(", ")}`),R!==0&&R!==null&&(j=!0,b=E.join("")||`Codex process exited with code ${R}`),P({sessionId:x,text:p.join(""),success:!j,error:j?b:void 0,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})}),k.on("error",R=>{j=!0,b=R.message,P({sessionId:x,text:p.join(""),success:!1,error:b,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})})});return{process:k,result:T}}import{spawn as Ns}from"child_process";import{createInterface as Js}from"readline";function vi(o,e){let t=o.trim()||"Copilot CLI failed",n=t.toLowerCase();return n.includes("no authentication information")||n.includes("not authenticated")||n.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:n.includes("model")&&(n.includes("not available")||n.includes("not found")||n.includes("disabled")||n.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:n.includes("mcp")&&(n.includes("blocked")||n.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:n.includes("permission")||n.includes("denied")||n.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function Ii(o,e){let{prompt:t,projectRoot:n,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,u=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];i&&u.push(`--resume=${i}`),r&&u.push("--model",r),u.push("-p",t);let I=Ns(d,u,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),k=new Promise(T=>{let P,x=[],p=[],l=!1,f="",m=!1,h=setTimeout(()=>{m=!0,I.kill("SIGTERM"),setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},5e3)},s),j=Js({input:I.stdout}),b=new Set,g=[];j.on("line",E=>{if(E.trim())try{let R=JSON.parse(E),N=Qt(R);b.add(N),g.length<5&&Ls(N)&&g.push(E.slice(0,800));let V=Kt(R,["sessionId","session_id","id"],["session","conversation","thread"]);V&&!P&&(P=V);let K=Bs(R,x.length===0);K&&(x.push(K),c?.({type:"delta",jobId:o,text:K},o));let G=qs(R);G&&c?.({type:"thinking",jobId:o,text:G},o);let Q=Fs(R);Q&&(p.push(Q.label),c?.({type:"tool_use",jobId:o,tool:Q.tool,...Q.file?{file:Q.file}:{},...Q.content?{content:Q.content}:{}},o));let w=Us(R);w&&(l=!0,f=w)}catch{}});let B=[];I.stderr?.on("data",E=>{B.push(E.toString())}),I.on("close",E=>{clearTimeout(h),j.close(),x.length===0&&b.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...b].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
|
|
37
|
+
`)}`)),m?(l=!0,f=`Timed out after ${Math.round(s/6e4)} minutes`):E!==0&&E!==null&&(l=!0,f=B.join("").trim()||f||`Copilot process exited with code ${E}`);let R=l?vi(f,r):null;T({sessionId:P,text:x.join(""),success:!l,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),I.on("error",E=>{clearTimeout(h);let R=vi(E.message,r);T({sessionId:P,text:x.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:I,result:k}}function Qt(o){if(typeof o.type=="string")return o.type;let e=o.update;return e&&typeof e.sessionUpdate=="string"?e.sessionUpdate:typeof o.event=="string"?o.event:"unknown"}function Bs(o,e=!1){let t=Qt(o).toLowerCase(),n=o.update,i=n?.content;if(n?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return ze(o.delta)??ze(o.content)??ze(o.message);if(t==="assistant.message"&&e)return ze(o.message)??ze(o.content)??ze(o);if(t==="result"&&e)return ze(o.result)??ze(o.output)??ze(o.message)??ze(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&yo(o))return o.text;if(typeof o.message=="string"&&yo(o))return o.message;if(typeof o.delta=="string"&&yo(o))return o.delta}function ze(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(ze).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let n=ze(e[t]);if(n)return n}}function Ls(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function qs(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function Fs(o){let e=Kt(o,["tool","toolName","tool_name","name"]),t=Kt(o,["command","cmd"]),n=Kt(o,["file","path","filename","filePath"]),i=Qt(o);if(t||i.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
|
|
38
|
+
`)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function Us(o){if(typeof o.error=="string")return o.error;if(o.error&&typeof o.error=="object"){let e=o.error;if(typeof e.message=="string")return e.message}if(typeof o.message=="string"&&Qt(o).toLowerCase().includes("error"))return o.message}function Kt(o,e,t=[]){for(let n of e){let i=o[n];if(typeof i=="string")return i}for(let[n,i]of Object.entries(o)){if(!i||typeof i!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=Kt(i,e);if(r)return r}}function yo(o){let e=Qt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as zs,readFile as Ws}from"fs/promises";import{join as vo}from"path";var bn=class{constructor(e){let t=vo(e,".popmelt");this.decisionsDir=vo(t,"decisions")}async listDecisionIds(){try{return(await zs(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await Ws(vo(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as Gs,randomUUID as Hs}from"crypto";import{mkdir as Io,readFile as wi,readdir as bi,rename as xn,stat as xi,unlink as Sn,writeFile as Tn}from"fs/promises";import{extname as Vs,join as Ve}from"path";var Ks=10080*60*1e3,Qs=600*1e3,Xs=3600*1e3;function Ys(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function Zs(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var kn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let t=Hs(),n=Ys(e.mimeType),i=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:Zs(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await Io(this.draftsDir,{recursive:!0});let c=Ve(this.draftsDir,i),d=Ve(this.draftsDir,`${t}.json`),u=`${c}.part`,I=`${d}.part`;return await Tn(u,e.data),await xn(u,c),await Tn(I,JSON.stringify(s,null,2)),await xn(I,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let i=await this.readManifest(n.id);if(!i)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(i.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ve(this.draftsDir,i.contentFile),s=await wi(r),c=Gs("sha256").update(s).digest("hex"),d=Ve(this.mediaDir,`${c}${Vs(i.contentFile)||".bin"}`);await Io(this.mediaDir,{recursive:!0});try{await xi(d)}catch{let u=`${d}.part`;await Tn(u,s),await xn(u,d)}(t[n.annotationId]??=[]).push({id:i.id,name:i.name,mimeType:i.mimeType,size:i.size,kind:i.kind,path:d}),i.releasedAt=Date.now(),i.lastSeenAt=Date.now(),await this.writeManifest(i)}return t}async sweep(e=Date.now()){let t;try{t=await bi(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let i=Ve(this.draftsDir,n);if(n.endsWith(".part")){let c=await xi(i).catch(()=>null);c&&e-c.mtimeMs>Xs&&await Sn(i).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Qs:e-r.lastSeenAt>Ks)||await Promise.all([Sn(i).catch(()=>{}),Sn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await bi(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Sn(Ve(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await wi(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Io(this.draftsDir,{recursive:!0});let t=Ve(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Tn(n,JSON.stringify(e,null,2)),await xn(n,t)}};import{randomUUID as Si}from"crypto";import{mkdir as wo,readFile as bo,writeFile as Rn}from"fs/promises";import{dirname as xo,join as At}from"path";var Ke="[ProjectionWorker]",ea={version:1,runs:[]},ta={version:1,updatedAt:0,proposals:[]},na=12;function oa(o){return Array.isArray(o)?o.map((e,t)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ti(o){let e=[];for(let t of o){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Ke} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function ia(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function ra(o,e,t){let n=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let x of r){if(!x||typeof x!="object")continue;let p=x.sources;if(Array.isArray(p))for(let l of p)typeof l=="string"&&n.has(l)&&i.add(l)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(t?.rules)?t.rules:[],u=r.filter(x=>{if(!x||typeof x!="object")return!1;let p=x.id,l=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(l)!==JSON.stringify(x)}).length,I=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},k=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},T=Object.keys(s).filter(x=>JSON.stringify(s[x])!==JSON.stringify(I[x])).length,P=Object.keys(c).filter(x=>JSON.stringify(c[x])!==JSON.stringify(k[x])).length;return{ruleCount:u,tokenSectionCount:T,componentCount:P,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(x=>!i.has(x))}}function sa(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function aa(o,e,t){let n=o[e];if(n&&typeof n=="object")return n;let i=typeof t=="number"?[]:{};return o[String(e)]=i,i}function Pn(o,e,t){let n=o;for(let r=0;r<e.length-1;r++)n=aa(n,e[r],e[r+1]);let i=e[e.length-1];n[String(i)]=sa(t)}function ki(o,e){let t=o;for(let i=0;i<e.length-1;i++){let r=t[String(e[i])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function ca(o,e){if(!o)return{exists:!1};let t=o;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function da(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Ri(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=ca(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?da(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var jn=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=At(e,".popmelt");this.runsPath=At(n,"projection-runs.json"),this.legacyRunsPath=At(n,"materialization-runs.json"),this.proposalsPath=At(n,"projection-queue.json"),this.legacyProposalsPath=At(n,"model-proposals.json"),this.modelPath=At(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await bo(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=oa(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let i=n.key.split(".");n.value===null?ki(t,i):Pn(t,i,n.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(na),t=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!t.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let n=await this.selectUnprojectedPatternDecisions(),i=n.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(x=>x.id);console.log(`${Ke} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=ma(i,s),d=ia(i,n.totalCandidateDecisionCount,c);t=Si().slice(0,8);let u={id:t,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(u);let I=!0,k,T,P;try{let x=`projection-${Date.now()}`,{provider:p,result:l}=this.spawnModelAgent(x,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});u={...u,provider:p},await this.persistRun(u);let f=await l;if(!f.success)I=!1,k=f.error,console.error(`${Ke} ${p} spawn error:`,k);else{let m=ua(f.text,r);if(m){let h=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of m)Pn(h,g.path,g.value);Array.isArray(h.rules)&&(h.rules=Ti(h.rules));let j=ra(h,r,s);if(m){let g=[...new Set(m.flatMap(B=>B.decisionIds))];j.coveredDecisionIds=g,j.uncoveredDecisionIds=r.filter(B=>!g.includes(B))}T=j;let b=await this.createModelProposal({decisionIds:r,proposedModel:h,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:T,changes:m});P=b.id,console.log(`${Ke} Created model proposal ${b.id} for ${r.length} decision(s)`)}else I=!1,k="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${k}`)}}catch(x){I=!1,k=x instanceof Error?x.message:String(x),console.error(`${Ke} Error:`,k)}return await this.persistRun({...u,status:I?"proposed":"failed",completedAt:Date.now(),error:k,outputStats:T,proposalId:P}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:I,error:k}),{processedIds:r,success:I,error:k,runId:t,proposalId:P}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ti(e.rules)),await Rn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Ke} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await wo(xo(this.runsPath),{recursive:!0}),await Rn(this.runsPath,JSON.stringify(t,null,2)),t):{...ea,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...ta,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(n);for(let s of i.changes??[])Pn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>i.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>n.createdAt-i.createdAt||n.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,t,n,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of t)!Array.isArray(d.path)||d.path.length===0||(d.remove?ki(s,d.path):Pn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,error:void 0,selectedChanges:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:Si().slice(0,8),status:"pending",title:la(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"}.`:pa(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(i=>i.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),i=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(i={...r,...t,updatedAt:Date.now()},i)),i?(n.updatedAt=Date.now(),await this.persistModelProposals(n),i):null}async persistModelProposals(e){try{await wo(xo(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...i})=>i)};await Rn(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(i=>i.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await wo(xo(this.runsPath),{recursive:!0}),await Rn(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Ke} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await bo(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await bo(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,i){let r=n.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...wn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:yn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...vn(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function la(o){let t=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function pa(o,e){let t=Array.isArray(o.rules)?o.rules.length:0,n=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function ua(o,e){let t=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let i=new Set(e),r=n.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(k=>typeof k=="string"||typeof k=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let u=d.path[0];if(u!=="tokens"&&u!=="components"&&u!=="rules")return[];if(u==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let I=Array.isArray(d.decisionIds)?d.decisionIds.filter(k=>typeof k=="string"&&i.has(k)):[];return I.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:I,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function ma(o,e){let t=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
36
39
|
Kind: ${r.kind}
|
|
37
40
|
Claim: ${r.claim}
|
|
38
41
|
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
39
42
|
Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
|
|
40
43
|
Authority: ${r.authority.level}/${r.authority.mode}`).join(`
|
|
41
44
|
|
|
42
|
-
`),n=
|
|
45
|
+
`),n=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
|
|
43
46
|
|
|
44
47
|
## Instructions
|
|
45
48
|
1. Review the current model (if any) and the new decisions below.
|
|
@@ -111,15 +114,15 @@ Example:
|
|
|
111
114
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
112
115
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
113
116
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
114
|
-
Include property and bindings when the decision context has class-level evidence.`}var An=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){for(let
|
|
115
|
-
`),t=[],n=null;for(let
|
|
116
|
-
`)}),n={name:r[1],bodyLines:[]}):
|
|
117
|
-
`)}),n=null):n&&n.bodyLines.push(
|
|
118
|
-
`)}),t}function
|
|
119
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
117
|
+
Include property and bindings when the decision context has class-level evidence.`}var An=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){for(let i of this.listeners)i(e,t,n)}cancelJob(e){let t=this.queue.findIndex(i=>i.id===e);if(t>=0){let[i]=this.queue.splice(t,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):null}let n=this.activeJob;return!n||n.id!==e?null:(n.status="cancelled",n.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:n.error,cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id),this.processNext(),n)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(t=>{e.status!=="cancelled"&&(e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as fa}from"child_process";import{readFile as Ai}from"fs/promises";import{homedir as To}from"os";import{join as Xe}from"path";var ko=/popmelt/i;function vt(){return{found:!1,name:null,scope:null,disabled:!1}}function Mt(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function Xt(o){for(let e of Object.keys(o))if(ko.test(e))return e;return null}async function Mn(o){try{let e=await Ai(o,"utf-8");return JSON.parse(e)}catch{return null}}async function Ro(o){let e=To(),t=await Mn(Xe(e,".claude.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=Xt(i.mcpServers);if(r)return Mt(r,"user")}if(i.projects&&typeof i.projects=="object"){let s=i.projects[o];if(s&&typeof s=="object"){let c=s;if(c.mcpServers&&typeof c.mcpServers=="object"){let d=Xt(c.mcpServers);if(d){let u=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(I=>ko.test(I));return Mt(d,"project",u)}}}}}let n=await Mn(Xe(o,".mcp.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=Xt(i.mcpServers);if(s){let c=await Pi(o,s);return Mt(s,"mcp.json",c)}}let r=Xt(i);if(r&&r!=="mcpServers"){let s=await Pi(o,r);return Mt(r,"mcp.json",s)}}return vt()}async function Pi(o,e){let t=Xe(o,".claude","settings.local.json"),n=await Mn(t);if(n&&typeof n=="object"){let i=n;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var ha=/^\[mcp_servers\.([^\]]+)\]/;function ga(o){let e=o.split(`
|
|
118
|
+
`),t=[],n=null;for(let i of e){let r=i.match(ha);r?(n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
119
|
+
`)}),n={name:r[1],bodyLines:[]}):i.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
|
|
120
|
+
`)}),n=null):n&&n.bodyLines.push(i)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
121
|
+
`)}),t}function ya(o){return/enabled\s*=\s*false/i.test(o)}async function Po(o){let e=process.env.CODEX_HOME||Xe(To(),".codex"),t=await ji(Xe(e,"config.toml"),"user");if(t.found)return t;let n=await ji(Xe(o,".codex","config.toml"),"project");return n.found?n:vt()}async function jo(o,e="copilot"){let t=await va(e);if(t.found)return t;let n=process.env.COPILOT_HOME||Xe(To(),".copilot"),i=await So(Xe(n,"mcp-config.json"),"user");if(i.found)return i;let r=await So(Xe(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await So(Xe(o,".github","mcp.json"),"mcp.json");return s.found?s:vt()}async function va(o){try{let e=await new Promise((t,n)=>{fa(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return Mi(JSON.parse(e),"user")}catch{return vt()}}async function So(o,e){let t=await Mn(o);return Mi(t,e)}function Mi(o,e){if(!o||typeof o!="object")return vt();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,i=Xt(n);return i?Mt(i,e):vt()}async function ji(o,e){try{let t=await Ai(o,"utf-8"),n=ga(t);for(let i of n)if(ko.test(i.name)){let r=ya(i.body);return Mt(i.name,e,r)}}catch{}return vt()}import{execFile as Ei}from"child_process";import{mkdir as Ia,readFile as _i,writeFile as Ci}from"fs/promises";import{homedir as $i}from"os";import{dirname as wa,join as Ao}from"path";var Mo="https://mcp.popmelt.com/mcp";async function Oi(o=Mo){let e=Ao($i(),".claude.json"),t;try{let i=await _i(e,"utf-8");t=JSON.parse(i)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let i of Object.keys(n))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:o},await Ci(e,JSON.stringify(t,null,2)+`
|
|
122
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Di(o=Mo){let e=process.env.CODEX_HOME||Ao($i(),".codex"),t=Ao(e,"config.toml"),n;try{n=await _i(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ia(wa(t),{recursive:!0});let i=`
|
|
120
123
|
[mcp_servers.popmelt]
|
|
121
|
-
url = "${
|
|
122
|
-
`;return await
|
|
124
|
+
url = "${o}"
|
|
125
|
+
`;return await Ci(t,n+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Ni(o=Mo,e="copilot"){let t=await ba(e);if(xa(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,i)=>{Ei(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function ba(o){try{let e=await new Promise((t,n)=>{Ei(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return JSON.parse(e)}catch{return null}}function xa(o){if(!o||typeof o!="object")return!1;let e=o,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}var En=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let t of this.leases.values())(e===null||t.expiresAt<e)&&(e=t.expiresAt);return e}acquire(e,t,n=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:t,createdAt:i?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[n,i]of this.leases)i.expiresAt>e||(this.leases.delete(n),t.push(n));return{expiredIds:t,becameEmpty:t.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};var Sa=String.raw`
|
|
123
126
|
(() => {
|
|
124
127
|
const hidden = [];
|
|
125
128
|
const visit = (root) => {
|
|
@@ -140,7 +143,7 @@ url = "${i}"
|
|
|
140
143
|
visit(document);
|
|
141
144
|
window.__popmeltNativeCaptureHidden = hidden;
|
|
142
145
|
})()
|
|
143
|
-
`,
|
|
146
|
+
`,Ta=String.raw`
|
|
144
147
|
(() => {
|
|
145
148
|
for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
|
|
146
149
|
if (value) element.style.setProperty('visibility', value, priority);
|
|
@@ -148,63 +151,68 @@ url = "${i}"
|
|
|
148
151
|
}
|
|
149
152
|
delete window.__popmeltNativeCaptureHidden;
|
|
150
153
|
})()
|
|
151
|
-
`;function _n(i){try{let e=new URL(i);return e.hash="",e.href}catch{return null}}function Sa(i,e){let t=_n(e);if(!t)return null;let n=new URL(t),o=i.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&_n(s.url)),r=o.find(s=>_n(s.url)===t);return r||(o.find(s=>{let c=new URL(_n(s.url));return c.origin===n.origin&&c.pathname===n.pathname})??null)}function ka(i){let e={x:Number(i.x),y:Number(i.y),width:Number(i.width),height:Number(i.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Ta(i){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",i).href,o=await fetch(n,{signal:e.signal});if(!o.ok)throw new Error(`CDP discovery returned ${o.status}`);let r=await o.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Ra(i){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let o=new e(i,{handshakeTimeout:1e3}),r=()=>{o.off("error",s),t(o)},s=c=>{o.off("open",r),n(c)};o.once("open",r),o.once("error",s)})}function Pa(i){let e=1,t=new Map;return i.on("message",n=>{let o;try{o=JSON.parse(String(n))}catch{return}if(!o.id)return;let r=t.get(o.id);r&&(t.delete(o.id),clearTimeout(r.timeout),o.error?r.reject(new Error(o.error.message||`CDP error ${o.error.code??""}`.trim())):r.resolve(o.result??{}))}),i.on("close",()=>{for(let[n,o]of t)clearTimeout(o.timeout),o.reject(new Error("CDP connection closed")),t.delete(n)}),(n,o={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{t.delete(c),s(new Error(`CDP ${n} timed out`))},4e3);t.set(c,{resolve:r,reject:s,timeout:d}),i.send(JSON.stringify({id:c,method:n,params:o}),p=>{p&&(clearTimeout(d),t.delete(c),s(p))})})}async function Jo(i,e){let t=ka(e.clip),n=await Ta(i),o=Sa(n,e.pageUrl);if(!o?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Ra(o.webSocketDebuggerUrl),s=Pa(r),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:ba,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),p=typeof d.data=="string"?d.data:"";if(!p)throw new Error("CDP returned an empty screenshot");return Buffer.from(p,"base64")}finally{c&&await s("Runtime.evaluate",{expression:xa,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as tr,readFile as tn,writeFile as nr}from"fs/promises";import{join as Ot}from"path";var ja=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Mi(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Cn(i){return new Set(Mi(i).split(" ").filter(e=>e.length>2&&!ja.has(e)))}function Bo(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function Aa(i){return[{value:i.label,by:"label"},...i.aliases.map(e=>({value:e,by:"alias"})),...i.locators.map(e=>({value:e.value,by:"locator"}))]}function Ma(i,e){let t=new Map,n=new Set(e.subjectIds??[]),o=(e.subjectHints??[]).map(Mi).filter(Boolean),r=Cn([e.action,e.text].filter(Boolean).join(" "));for(let s of i){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of Aa(s)){let p=Mi(d.value);for(let k of o){let P=p===k?95:p.includes(k)||k.includes(p)?75:0;P>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:d.by,score:P})}let T=["/","#","[","]","="].some(k=>d.value.includes(k))?0:Math.round(Bo(Cn(p),r)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}c&&t.set(s.id,c)}return t}function Ea(i,e){let t=new Set(i.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(i.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),o=e.filter(s=>s.iterationIds.some(c=>t.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&n.has(c.id)));if(!o.length)return{state:"none_found",attemptIds:[]};let r=new Set(o.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:o.map(s=>s.id)}}function _a(i){return Math.ceil(JSON.stringify(i).length/4)}function Ei(i,e){let t=i.records.filter(l=>l.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),o=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=i.records.filter(l=>{if(l.recordType!=="proposal"||o&&!o.has(l.id))return!1;if(l.state==="pending")return!0;if(l.state!=="deferred")return!1;let h=[...i.events].reverse().find(u=>u.entity.entityType==="proposal"&&u.entity.entityId===l.id&&u.toState==="deferred"&&u.transitionContext?.kind==="proposal_deferral")?.transitionContext;return h?h.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||h.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||h.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||h.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||h.resurfaceWhen.includes("after_date")&&!!(h.revisitAfter&&Date.parse(n)>=Date.parse(h.revisitAfter)):!1}),s=i.records.filter(l=>l.recordType==="implementation_attempt"),c=Ma(t,e),d=[...c.values()].sort((l,h)=>h.score-l.score),p=Cn([e.action,e.text].filter(Boolean).join(" ")),x=r.flatMap(l=>{let h=l.subjects.map(b=>c.get(b.subjectId)).filter(b=>!!b),u=Math.max(0,...h.map(b=>b.score)),m=Math.round(Bo(Cn(l.claim),p)*35),j=u+m;return j>=50?[{proposal:l,proposalMatches:h,score:j}]:[]}).sort((l,h)=>h.score-l.score||l.proposal.id.localeCompare(h.proposal.id)),T=Math.max(1,e.maxPackets??3),k=Math.max(200,e.maxEstimatedTokens??1200),P=[],v=0;for(let l of x){if(P.length>=T)break;let h=l.proposal.sourceRefs.slice(0,4),u={contractVersion:1,packetId:`review:${l.proposal.id}`,projectId:i.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:l.proposalMatches.length?`Historical proposal intersects ${l.proposalMatches.map(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:l.proposalMatches.map(({score:j,...b})=>b)},proposal:{id:l.proposal.id,claim:l.proposal.claim,state:l.proposal.state,proposedKind:l.proposal.proposedKind,subjectIds:l.proposal.subjects.map(j=>j.subjectId),origin:l.proposal.origin.mode},authority:"unaccepted",presentation:l.score>=100&&["constraint","rule"].includes(l.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ea(l.proposal,s),evidence:{sourceCount:l.proposal.sourceRefs.length,sourceRefs:h},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:l.proposal.id},...h]},m={...u,estimatedTokens:_a(u)};if(v+m.estimatedTokens>k)break;P.push(m),v+=m.estimatedTokens}let f=Math.max(0,x.length-P.length);return{packets:P,subjectMatches:d.map(({score:l,...h})=>h),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:f,maxEstimatedTokens:k,estimatedTokens:v},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var Ca=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function _i(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function $n(i){return new Set(_i(i).split(" ").filter(e=>e.length>2&&!Ca.has(e)))}function Lo(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function $a(i,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(_i).filter(Boolean),o=$n([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of i){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of d){let x=_i(p.value);for(let P of n){let v=x===P?95:x.includes(P)||P.includes(x)?75:0;v>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:v>=90?"exact":"strong",matchedBy:p.by,score:v})}let k=["/","#","[","]","="].some(P=>p.value.includes(P))?0:Math.round(Lo($n(x),o)*55);k>=30&&k>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"semantic",score:k})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Oa(i){return Math.ceil(JSON.stringify(i).length/4)}function Et(i,e){return i.relationshipType===e&&i.from.entityType==="decision"&&i.to.entityType==="decision"}function Da(i,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===i));if(!t.length)return{decisionId:i,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),o=n.some(r=>r.coverageClaims.some(s=>s.decisionId===i&&s.coverage==="full"));return{decisionId:i,state:o?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function Na(i,e,t){let n=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===i)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),o=t.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===i),r=n[0],s=o?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:i},state:s,attemptIds:n.map(c=>c.id)}}function Fo(i,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),o=i.records.filter(g=>g.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=i.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=r?s.filter(g=>r.has(g.id)):s,d=i.records.filter(g=>g.recordType==="implementation_attempt"),p=i.records.filter(g=>g.recordType==="verification_attempt"),x=i.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),T=i.records.filter(g=>g.recordType==="evidence"),k=i.records.filter(g=>g.recordType==="model_entry"),P=$a(o,e),v=new Map(P.map(g=>[g.subjectId,g.score])),f=$n([e.action,e.text].filter(Boolean).join(" ")),l=c.flatMap(g=>{let B=Math.max(0,...g.subjects.map(N=>v.get(N.subjectId)??0)),E=Math.round(Lo($n(g.claim),f)*35),R=B+E;return R>=50?[{decision:g,score:R}]:[]}).sort((g,B)=>B.score-g.score||g.decision.id.localeCompare(B.decision.id)),h=new Map;for(let g of l.slice(0,n))h.set(g.decision.id,g.decision);for(let g of i.relationships){if(!Et(g,"excepts")&&!Et(g,"contradicts"))continue;let B=s.find(R=>R.id===g.from.entityId),E=s.find(R=>R.id===g.to.entityId);!B||!E||!h.has(B.id)&&!h.has(E.id)||(h.size<n&&h.set(B.id,B),h.size<n&&h.set(E.id,E))}let u=[...h.values()],m=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&h.has(g.from.entityId)&&h.has(g.to.entityId),j=(g,B=!1)=>{let E=new Set(g.map(J=>J.id)),R=x.filter(J=>J.target.entityType==="decision"&&E.has(J.target.entityId)),N=new Set(i.relationships.filter(J=>Et(J,"excepts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),K=i.relationships.filter(J=>Et(J,"contradicts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),G=new Set(K.flatMap(J=>J.decisionIds)),Q=T.filter(J=>J.sourceRefs.some(D=>D.kind==="record"&&E.has(D.id))||i.relationships.some(D=>D.relationshipType==="supports"&&D.from.entityType==="evidence"&&D.from.entityId===J.id&&D.to.entityType==="decision"&&E.has(D.to.entityId))),w=Math.max(0,l.length-g.length),H=i.relationships.some(J=>Et(J,"contradicts")&&m(J)&&(!E.has(J.from.entityId)||!E.has(J.to.entityId))),L=B||w>0||H,O=[];P.length===0&&(e.subjectHints?.length??0)>0?O.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&O.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&O.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap(J=>J.expansionRefs)}),Q.some(J=>J.availability!=="available")&&O.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(J=>({kind:"record",id:J.id}))}),L&&O.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:i.manifest.projectId}]});let fe={contractVersion:1,projectId:i.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:P.map(({score:J,...D})=>D),modelEntries:k.filter(J=>J.decisionIds.some(D=>E.has(D))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:g.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(D=>D.subjectId),authority:J.authority,effectiveState:G.has(J.id)?"conflicted":N.has(J.id)?"excepted":"active",freshness:R.filter(D=>D.target.entityId===J.id).map(D=>D.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:K,uncertainties:O,implementation:g.map(J=>Da(J.id,d)),verification:g.map(J=>Na(J.id,p,R)),evidence:Q.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:w,omittedEvidenceCount:0,conflictsComplete:!H}};return fe.budget.estimatedTokens=Oa(fe),fe},b=j(u);for(;b.budget.estimatedTokens>t&&u.length>0;){let g=u.pop(),B=i.relationships.filter(E=>Et(E,"contradicts")&&(E.from.entityId===g.id||E.to.entityId===g.id)).flatMap(E=>[E.from.entityId,E.to.entityId]);u=u.filter(E=>!B.includes(E.id)),b=j(u,!0)}return b}var Ja=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _t(i){return Ja.test(i)}function Ba(i){return{valid:!i.some(e=>e.severity==="error"),issues:i}}function te(i,e,t,n){i.push({path:e,code:t,message:n,severity:"error"})}function Ci(i,e,t,n){i.push({path:e,code:t,message:n,severity:"warning"})}function Pe(i,e,t){_t(t)||te(i,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(i,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(i,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function It(i,e,t,n=!1){n&&t.level==="contributor"&&te(i,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&te(i,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var La={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"])},Fa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function qa(i,e,t){Pe(i,`${t}.id`,e.id),Pe(i,`${t}.projectId`,e.projectId),Pe(i,`${t}.participantId`,e.participantId),Pe(i,`${t}.entity.entityId`,e.entity.entityId),Qe(i,`${t}.createdAt`,e.createdAt),It(i,`${t}.authority`,e.authority);let n=La[e.entity.entityType],o=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(o)&&te(i,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${o}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Fa.has(r)&&(It(i,`${t}.authority`,e.authority,!0),e.reason?.trim()||te(i,`${t}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&te(i,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(i,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(i,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ua(i,e,t,n){Pe(i,`${t}.id`,e.id),Pe(i,`${t}.projectId`,e.projectId),Pe(i,`${t}.participantId`,e.participantId),Qe(i,`${t}.createdAt`,e.createdAt),e.projectId!==n&&te(i,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(i,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(i,`${t}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&te(i,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(It(i,`${t}.authority`,e.authority,!0),e.claim.trim()||te(i,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Ci(i,`${t}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&te(i,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(i,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(i,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(o=>!o.trim())&&te(i,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((o,r)=>{(!o.id.trim()||!o.modelPath.trim())&&te(i,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(i,`${t}.concreteBindings[${r}].createdAt`,o.createdAt),Qe(i,`${t}.concreteBindings[${r}].updatedAt`,o.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(i,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(i,`${t}.appliedAt`,e.appliedAt),It(i,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&te(i,`${t}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&te(i,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(o=>!o.trim()))&&te(i,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Ci(i,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Ci(i,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function za(i,e,t){if(Pe(i,`${t}.id`,e.id),Pe(i,`${t}.projectId`,e.projectId),Pe(i,`${t}.participantId`,e.participantId),Pe(i,`${t}.from.entityId`,e.from.entityId),Pe(i,`${t}.to.entityId`,e.to.entityId),Qe(i,`${t}.createdAt`,e.createdAt),e.reason.trim()||te(i,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let o=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!o&&!r&&te(i,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),o&&!e.authority?te(i,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):o&&e.authority&&It(i,`${t}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(i,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(i,t,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&te(i,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(i,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function wt(i){let e=[];Pe(e,"manifest.projectId",i.manifest.projectId),Qe(e,"manifest.createdAt",i.manifest.createdAt),Qe(e,"manifest.updatedAt",i.manifest.updatedAt);let t=new Map,n=(f,l)=>{let h=t.get(f);h?te(e,l,"duplicate_id",`ID is already used at ${h}.`):t.set(f,l)};i.records.forEach((f,l)=>{let h=`records[${l}]`;n(f.id,h),Ua(e,f,h,i.manifest.projectId)}),i.events.forEach((f,l)=>{let h=`events[${l}]`;n(f.id,h),qa(e,f,h),f.projectId!==i.manifest.projectId&&te(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),i.relationships.forEach((f,l)=>{let h=`relationships[${l}]`;n(f.id,h),za(e,f,h),f.projectId!==i.manifest.projectId&&te(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),i.artifacts.forEach((f,l)=>{n(f.id,`artifacts[${l}]`),Pe(e,`artifacts[${l}].id`,f.id)}),i.tombstones.forEach((f,l)=>{let h=`tombstones[${l}]`;n(f.id,h),Pe(e,`${h}.id`,f.id),Pe(e,`${h}.objectId`,f.objectId),Pe(e,`${h}.deletedById`,f.deletedById),Qe(e,`${h}.deletedAt`,f.deletedAt),It(e,`${h}.authority`,f.authority,!0)});let o=new Set(i.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(i.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,l)=>{let h=`${f.entityType}:${f.entityId}`;!o.has(h)&&!r.has(h)&&te(e,l,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};i.events.forEach((f,l)=>s(f.entity,`events[${l}].entity`)),i.relationships.forEach((f,l)=>{s(f.from,`relationships[${l}].from`),s(f.to,`relationships[${l}].to`)});let c=new Set(i.artifacts.map(f=>f.id)),d=(f,l)=>{c.has(f)||te(e,l,"dangling_artifact_reference","No artifact manifest entry exists.")},p=(f,l,h)=>{!o.has(`${f}:${l}`)&&!r.has(`${f}:${l}`)&&te(e,h,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};i.records.forEach((f,l)=>{let h=`records[${l}]`;switch(f.recordType){case"authority_grant":p("participant",f.granteeId,`${h}.granteeId`),p("participant",f.grantedById,`${h}.grantedById`),f.subjectIds.forEach((u,m)=>p("subject",u,`${h}.subjectIds[${m}]`));break;case"observation":f.captureContext.subjectIds.forEach((u,m)=>p("subject",u,`${h}.captureContext.subjectIds[${m}]`)),f.captureContext.artifactIds.forEach((u,m)=>d(u,`${h}.captureContext.artifactIds[${m}]`));break;case"proposal":case"decision":f.subjects.forEach((u,m)=>p("subject",u.subjectId,`${h}.subjects[${m}].subjectId`));break;case"thread":f.messageArtifactIds.forEach((u,m)=>d(u,`${h}.messageArtifactIds[${m}]`)),f.resultRefs.forEach((u,m)=>s(u,`${h}.resultRefs[${m}]`));break;case"iteration":f.threadIds.forEach((u,m)=>p("thread",u,`${h}.threadIds[${m}]`)),f.artifactIds.forEach((u,m)=>d(u,`${h}.artifactIds[${m}]`));break;case"evidence":f.artifactIds.forEach((u,m)=>d(u,`${h}.artifactIds[${m}]`));break;case"advisory_explanation":f.subjectIds.forEach((u,m)=>p("subject",u,`${h}.subjectIds[${m}]`)),f.evidenceIds.forEach((u,m)=>p("evidence",u,`${h}.evidenceIds[${m}]`)),f.supersededById&&p("advisory_explanation",f.supersededById,`${h}.supersededById`);break;case"implementation_attempt":f.iterationIds.forEach((u,m)=>p("iteration",u,`${h}.iterationIds[${m}]`)),f.coverageClaims.forEach((u,m)=>p("decision",u.decisionId,`${h}.coverageClaims[${m}].decisionId`)),f.artifactIds.forEach((u,m)=>d(u,`${h}.artifactIds[${m}]`));break;case"eval_spec":f.replacesSpecId&&p("eval_spec",f.replacesSpecId,`${h}.replacesSpecId`),f.decisionIds.forEach((u,m)=>p("decision",u,`${h}.decisionIds[${m}]`)),f.subjectIds.forEach((u,m)=>p("subject",u,`${h}.subjectIds[${m}]`)),(f.dependencies??[]).forEach((u,m)=>{u.kind==="subject"&&u.subjectId&&p("subject",u.subjectId,`${h}.dependencies[${m}].subjectId`)}),(f.scenarios??[]).forEach((u,m)=>{u.subjectIds?.forEach((j,b)=>p("subject",j,`${h}.scenarios[${m}].subjectIds[${b}]`))}),f.targets.forEach((u,m)=>p(u.entityType,u.entityId,`${h}.targets[${m}]`));break;case"verification_attempt":f.evalSpecId&&p("eval_spec",f.evalSpecId,`${h}.evalSpecId`),f.targets.forEach((u,m)=>p(u.entityType,u.entityId,`${h}.targets[${m}]`)),f.evidenceIds.forEach((u,m)=>p("evidence",u,`${h}.evidenceIds[${m}]`));break;case"model_entry":f.subjectIds.forEach((u,m)=>p("subject",u,`${h}.subjectIds[${m}]`)),f.decisionIds.forEach((u,m)=>p("decision",u,`${h}.decisionIds[${m}]`));break;case"model_projection":It(e,`${h}.authority`,f.authority,!0),p("participant",f.appliedById,`${h}.appliedById`),f.decisionIds.forEach((u,m)=>p("decision",u,`${h}.decisionIds[${m}]`)),f.entryIds.forEach((u,m)=>p("model_entry",u,`${h}.entryIds[${m}]`)),f.coverage.forEach((u,m)=>p("decision",u.decisionId,`${h}.coverage[${m}].decisionId`));break;case"freshness_signal":s(f.target,`${h}.target`),f.evidenceIds.forEach((u,m)=>p("evidence",u,`${h}.evidenceIds[${m}]`));break;default:break}});let x=new Map(i.events.map(f=>[f.id,f])),T=new Map(i.records.map(f=>[`${f.recordType}:${f.id}`,f])),k=new Map;i.events.forEach((f,l)=>{let h=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,u=k.get(h)??new Set;u.add(f.toState),k.set(h,u),u.size>1&&te(e,`events[${l}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let P=new Map(i.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),v=(f,l,h,u,m)=>{if(f.level!=="delegate"||!f.grantId)return;let j=P.get(f.grantId);if(!j){te(e,m,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==l||j.level!=="delegate")&&te(e,m,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let b=Date.parse(h);(b<Date.parse(j.startsAt)||j.endsAt&&b>Date.parse(j.endsAt)||j.revokedAt&&b>=Date.parse(j.revokedAt))&&te(e,m,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&u.length&&!u.every(g=>j.subjectIds.includes(g))&&te(e,m,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let f of i.records)f.recordType==="decision"&&v(f.authority,f.acceptedById,f.createdAt,f.subjects.map(l=>l.subjectId),`records:${f.id}.authority`);i.events.forEach((f,l)=>{let h=T.get(`${f.entity.entityType}:${f.entity.entityId}`),u=h&&"subjects"in h?h.subjects.map(m=>m.subjectId):[];v(f.authority,f.participantId,f.createdAt,u,`events[${l}].authority`)}),i.relationships.forEach((f,l)=>{if(!f.authority)return;let h=[f.from,f.to].flatMap(u=>{let m=T.get(`${u.entityType}:${u.entityId}`);return m&&"subjects"in m?m.subjects.map(j=>j.subjectId):[]});v(f.authority,f.participantId,f.createdAt,h,`relationships[${l}].authority`)});for(let f of i.records){if(f.recordType!=="decision")continue;let l=x.get(f.acceptanceEventId);(!l||l.entity.entityType!=="proposal"||l.entity.entityId!==f.proposalId||l.toState!=="accepted")&&te(e,`records:${f.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),l&&l.participantId!==f.acceptedById&&te(e,`records:${f.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${f.proposalId}`)||te(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(i.relationships.some(u=>u.relationshipType==="supersedes"&&u.to.entityType==="decision"&&u.to.entityId===f.id)||te(e,`records:${f.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),f.state==="revoked"&&(i.events.some(u=>u.entity.entityType==="decision"&&u.entity.entityId===f.id&&u.toState==="revoked"&&!!u.reason?.trim())||te(e,`records:${f.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let f of i.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;i.records.some(h=>h.recordType==="decision"&&h.proposalId===f.id)||te(e,`records:${f.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ba(e)}function Yt(i,e,t,n){return{id:n,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function qo(i,e,t,n,o){return{id:o,schemaVersion:1,projectId:i.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Wa(i){switch(i.action){case"accept":return[i.eventId,i.decisionId];case"edit_and_accept":return[i.withdrawalEventId,i.replacementProposalId,i.acceptanceEventId,i.decisionId,i.relationshipId];case"reject":case"defer":return[i.eventId]}}function On(i,e){let t=[],n=i.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),_t(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Wa(e))_t(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...Yt(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=qo(i,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Yt(i,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Yt(i,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=qo(i,r,e,c.id,e.decisionId),p={id:e.relationshipId,schemaVersion:1,projectId:i.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,d],events:[s,c],relationships:[p]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.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 r={...Yt(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let o={...Yt(i,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}var Uo={project:0,route:1,component:2,selector:2,file:3},zo={intention:0,principle:1,pattern:2};function Ct(i,e){let t=Uo[i.scope.kind]-Uo[e.scope.kind];return t!==0?t:zo[i.kind]-zo[e.kind]}function Wo(i){return i==="expresses"||i==="excepts"}function Ga(i,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=i.explanations.find(r=>r.id===e.fromId),n=i.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let o=Ct(t,n);return o===0?void 0:o>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function bt(i){let e=structuredClone(i),t=new Set;return e.relations=i.relations.flatMap(n=>{let o=Ga(i,n);if(!o)return[];let r=`${o.type}:${o.fromId}:${o.toId}`;return t.has(r)?[]:(t.add(r),[o])}),e}import{createHash as Ha}from"crypto";import{readFile as Va,readdir as Ka,realpath as Qa}from"fs/promises";import{join as Zt,relative as Xa}from"path";var Ya=["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 $t(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:null}function We(i,e=0){return new Date(Number.isFinite(i)?i:e).toISOString()}function Go(...i){return i.find(e=>!!e?.trim())?.trim()}function oe(i,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ha("sha256").update(`${i}\0${e}\0${t}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function $i(i,e){try{return JSON.parse(await Va(i,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:i,message:t instanceof Error?t.message:String(t)}),null}}function Za(i){let e=$t(i);if(!e)return 0;let t=0,n=o=>{let r=$t(o);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let o of Object.values(e))n(o);return t}function ec(i){let e={};for(let t of i)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function en(i){let e=[],t=await Qa(i.projectRoot).catch(()=>i.projectRoot),n=Zt(t,".popmelt"),o=await $i(Zt(n,"threads.json"),e),r=await $i(Zt(n,"model.json"),e),s=$t(o),c=$t(s?.threads)??{},d=Object.entries(c).map(([D,Z])=>({key:D,value:$t(Z)})).filter(D=>!!D.value),p=Zt(n,"decisions"),x=await Ka(p).catch(()=>[]),T=[];for(let D of x.filter(Z=>Z.endsWith(".json")).sort()){let Z=$t(await $i(Zt(p,D),e));Z&&T.push({file:D,value:Z})}let k=d.flatMap(({value:D})=>[D.createdAt,D.updatedAt]).filter(D=>typeof D=="number"&&Number.isFinite(D)),P=k.length?Math.min(...k):0,v=i.projectKey??t;i.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let f=oe(v,"project",v,P),l=oe(v,"participant","legacy-owner",P),h=oe(v,"participant","legacy-agent",P),u=oe(v,"subject","project",P),m=We(Math.max(P,...k)),j=[],b=[],g=new Map,B=new Map,E=new Map(T.map(D=>[D.value.id??D.file.replace(/^d-|\.json$/g,""),D.value])),R=new Map,N=(D,Z,ae,Re,se)=>{let qe=g.get(ae);if(qe)return qe;let Ge=oe(v,"artifact",D,Re);return b.push({id:Ge,kind:Z,mediaType:se,location:ae,availability:"available"}),g.set(ae,Ge),Ge};for(let{file:D,value:Z}of T){let ae=Z.id??D.replace(/^d-|\.json$/g,""),Re=Z.createdAt??P,se=[N(`${ae}:envelope`,"other",`.popmelt/decisions/${D}`,Re,"application/json")];Z.screenshotPath&&se.push(N(`${ae}:screenshot`,"screenshot",`.popmelt/${Z.screenshotPath.replace(/^\.popmelt\//,"")}`,Re,Z.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[qe,Ge]of(Z.pastedImagePaths??[]).entries())se.push(N(`${ae}:image:${qe}`,"image",Ge,Re));R.set(ae,se)}let V=(D,Z,ae)=>({id:D,schemaVersion:1,projectId:f,createdAt:m,participantId:Z,sourceRefs:ae}),K=(D,Z)=>{j.push(Z);let ae=B.get(D)??[];ae.push(Z.id),B.set(D,ae)},G=[{...V(l,l,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...V(h,h,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(...G),j.push({...V(u,l,[]),recordType:"subject",subjectType:"project",label:Xa(process.cwd(),t)||t,aliases:[],locators:[{id:oe(v,"locator",t,P),kind:"project_root",value:t,status:"current",validFrom:We(P),sourceRefs:[]}]});let Q=new Map,w=(D,Z)=>{let ae=Q.get(D);if(ae)return ae;let Re=oe(v,"subject",D,Z),se={...V(Re,l,[{kind:"external",id:D}]),createdAt:We(Z),recordType:"subject",subjectType:"element",label:D,aliases:[],locators:[{id:oe(v,"locator",D,Z),kind:"dom_selector",value:D,status:"current",validFrom:We(Z),sourceRefs:[{kind:"external",id:D}]}]};return j.push(se),Q.set(D,Re),Re};for(let{key:D,value:Z}of d){let ae=Z.id??D,Re=Z.createdAt??P,se=oe(v,"thread",ae,Re),qe={kind:"thread",id:ae},Ge=[],je=[],at=Array.isArray(Z.messages)?Z.messages:[],He,ct,Wt=0;at.forEach((xe,dt)=>{let _e=xe.timestamp??Re,tt=oe(v,"artifact",`${ae}:message:${dt}`,_e);if(Ge.push(tt),b.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ae}/messages/${dt}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${ae}/messages/${dt}`,tt),xe.screenshotPath&&N(`${ae}:message:${dt}:screenshot`,"screenshot",xe.screenshotPath,_e),xe.role==="human"){He=xe;let Ne=xe.feedbackSummary??xe.replyToQuestion;if(Ne?.trim()){let Je=oe(v,"observation",`${ae}:${dt}`,_e),ut=Z.elementIdentifiers??[],Rt={...V(Je,l,[qe,{kind:"message",id:tt}]),createdAt:We(_e),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:ut.map(ht=>w(ht,Re)),artifactIds:[tt]},resolvedByIds:[]};K(ae,Rt),ct=Je,je.push({entityType:"observation",entityId:Je})}return}if(xe.role!=="assistant")return;let lt=xe.jobId??`${ae}:${dt}`,pt=oe(v,"iteration",lt,_e),mt=E.get(lt),ci=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",di={...V(pt,h,[qe,{kind:"message",id:tt},...(R.get(lt)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:We(_e),recordType:"iteration",threadIds:[se],startedAt:We(He?.timestamp,_e),completedAt:We(_e),requestSummary:Go(He?.feedbackSummary,He?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:ci,execution:{provider:xe.provider??mt?.provider,model:xe.model??mt?.model,sessionId:xe.sessionId??mt?.sessionId},artifactIds:[tt,...R.get(lt)??[]]};K(ae,di),je.push({entityType:"iteration",entityId:pt});let ft=xe.resolutions??mt?.resolutions??[];for(let[Ne,Je]of ft.entries()){if(Je.status!=="resolved"||!Je.summary?.trim())continue;let ut=Z.elementIdentifiers??[],Rt=(ut.length?ut:[t]).map(gn=>({subjectId:gn===t?u:w(gn,Re),role:"governed"})),ht=oe(v,"proposal",`${lt}:${Je.annotationId??"resolution"}:${Ne}`,_e),li={...V(ht,h,[qe,{kind:"iteration",id:pt}]),createdAt:We(_e),recordType:"proposal",state:"pending",claim:Je.summary,subjects:Rt,subjectSemantics:Rt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Go(He?.feedbackSummary,He?.replyToQuestion,Je.summary),iterationId:pt,inferredById:h}};K(ae,li),je.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ae,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(ft.some(Ne=>Ne.status==="resolved")||mt?.gitDiff){let Ne=oe(v,"implementation",lt,_e),Je={...V(Ne,h,[qe,{kind:"iteration",id:pt}]),createdAt:We(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[pt],coverageClaims:[],summary:ft.map(ut=>ut.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(ae,Je),je.push({entityType:"implementation_attempt",entityId:Ne}),Wt+=1}ct&&(ct=void 0)});let Tt=at.at(-1),ai={...V(se,l,[qe]),createdAt:We(Re),recordType:"thread",state:Tt?.question?"open":"resolved",messageArtifactIds:Ge,outcome:Tt?.question?"question_unresolved":Wt?"implementation_only":"no_outcome",resultRefs:je};j.push(ai),B.set(ae,[se,...B.get(ae)??[]])}let H=Za(r);H&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${H} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:f,createdAt:We(P),updatedAt:m,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:i.writerVersion??"0.8.4-dev"}},records:j,events:[],relationships:[],artifacts:b,tombstones:[]},O=wt(L),J=(i.proofCaseIds??Ya).map(D=>({legacyId:D,threadFound:d.some(({key:Z,value:ae})=>(ae.id??Z)===D),decisionEnvelopeFound:E.has(D),recordIds:B.get(D)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((D,Z)=>D+(Z.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:H,artifactsReferenced:b.length},imported:ec(j),unresolvedAcceptance:e.filter(D=>D.code==="acceptance_unresolved").length,deferredModelEntries:H,proofCases:J,issues:e,schemaIssues:O.issues}}}import{createHash as tc}from"crypto";import{mkdir as Ho,open as Oi,readFile as Di,readdir as nc,rename as ic,unlink as Ni}from"fs/promises";import{join as nt}from"path";var oc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Nn(i){return tc("sha256").update(JSON.stringify(i)).digest("hex")}function Vo(i){return Nn(i)}function Ko(i,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!i.manifest.features.includes("advisory_explanations")&&i.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let o=i.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(o<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=i.records[o];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);i.records[o]=structuredClone(n)}for(let n of e.projectionUpdates){let o=i.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!o||o.recordType!=="proposal"&&o.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(o.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${o.state}`);o.state=n.state}return i.records.push(...e.records),i.events.push(...e.events),i.relationships.push(...e.relationships),i.artifacts.push(...e.artifacts),i.tombstones.push(...e.tombstones),i.manifest.updatedAt=t,i}function rc(i,e,t){return Ko(structuredClone(i),e,t)}async function xt(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await Oi(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
152
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await ic(t,i)}catch(o){throw await Ni(t).catch(()=>{}),o}}async function Dn(i){return JSON.parse(await Di(i,"utf8"))}var Jn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let t=wt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Ho(this.journalDir,{recursive:!0});try{throw await Di(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await Di(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let n=Nn(e),o={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await xt(this.checkpointPath,o),await xt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await xt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=Nn(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,o={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await xt(nt(this.memoryDir,n),o),e.manifest.checkpoint={file:n,sequence:o.sequence,hash:t},await xt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:o.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!_t(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let o=n.report.headSequence+1,r={storageVersion:1,sequence:o,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Vo(r)},c=rc(n.bundle,e,t.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let p=`${String(o).padStart(12,"0")}-${t.transactionId}.json`;return await xt(nt(this.journalDir,p),s),n.manifest.head={sequence:o,hash:s.hash},n.manifest.updatedAt=t.committedAt,await xt(this.manifestPath,n.manifest),{bundle:c,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:o,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...oc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Dn(this.manifestPath),t=await Dn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==Nn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await nc(this.journalDir),o=n.filter(k=>k.endsWith(".tmp")),s=n.filter(k=>/^\d{12}-[0-9a-f-]+\.json$/i.test(k)).sort().filter(k=>Number(k.slice(0,12))>t.sequence),c=structuredClone(t.bundle),d=t.sequence,p=t.journalHash??null,x=new Set;for(let k of s){let P=await Dn(nt(this.journalDir,k)),{hash:v,...f}=P;if(v!==Vo(f))throw new Error(`Journal hash mismatch: ${k}`);if(P.sequence!==d+1)throw new Error(`Journal sequence gap at ${k}`);if(P.previousHash!==p)throw new Error(`Journal chain mismatch at ${k}`);if(P.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${k}`);if(x.has(P.transactionId))throw new Error(`Duplicate transaction ID: ${P.transactionId}`);Ko(c,P.mutation,P.committedAt),d=P.sequence,p=P.hash,x.add(P.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==p)throw new Error("Journal manifest head hash mismatch.");let T=wt(c);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:o.length,headSequence:d,headHash:p}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Ho(this.memoryDir,{recursive:!0});let t;try{t=await Oi(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let o=await Dn(this.lockPath).catch(()=>({})),r=!0;if(typeof o.pid=="number")try{process.kill(o.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await Ni(this.lockPath),t=await Oi(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Ni(this.lockPath).catch(()=>{})}}};import{randomBytes as sc}from"crypto";function we(i=Date.now()){let t=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),n=sc(10).toString("hex"),o=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${o}${n.slice(4,7)}-${n.slice(7,19)}`}var ac=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Qo(i,e){let t=i.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),n=i.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let o=i.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=ac(),p=d.records,x=i.records.find(m=>m.recordType==="thread"&&m.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));x||(x={id:oe(o,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(m=>m.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(x));let T=[];for(let m of[...new Set(e.subjectHints.filter(Boolean))]){let j=i.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.value===m&&g.status==="current"));j||(j={id:oe(o,"live-subject",m,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:m}],recordType:"subject",subjectType:"element",label:m,aliases:[],locators:[{id:oe(o,"live-locator",m,e.createdAt),kind:"dom_selector",value:m,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:m}]}]},p.push(j)),T.push(j)}for(let m of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=i.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.kind==="source_file"&&g.value===m&&g.status==="current"));j||(j={id:oe(o,"live-file-subject",m,e.createdAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:m}],recordType:"subject",subjectType:"file",label:m,aliases:[],locators:[{id:oe(o,"live-file-locator",m,e.createdAt),kind:"source_file",value:m,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:m}]}]},p.push(j)),T.push(j)}let k=(e.semanticCandidates??[]).filter(m=>m.claim.trim()),P;if(k.length>0){P=oe(o,"live-observation",r,e.createdAt);let m={id:P,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:k.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:T.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};p.push(m)}let v=oe(o,"live-iteration",r,e.completedAt),f={id:v,schemaVersion:1,projectId:i.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(m=>({kind:"external",id:m,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(m=>({kind:"external",id:m,uri:"popmelt:imprint-evidence"})),...P?[{kind:"record",id:P}]:[]],recordType:"iteration",threadIds:[x.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};p.push(f);let l=[],h=e.resolutions.filter(m=>m.status==="resolved"&&m.summary.trim()),u=T.length>0?T:i.records.filter(m=>m.recordType==="subject"&&m.subjectType==="project").slice(0,1);if(k.length>0&&u.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[m,j]of k.entries()){let b=oe(o,"live-proposal",`${r}:${m}`,e.completedAt),g=u.map(E=>({subjectId:E.id,role:"governed"})),B={id:b,schemaVersion:1,projectId:i.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:v},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:j.claim.trim(),rationale:j.rationale?.trim()||void 0,proposedKind:j.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:j.sourceText?.trim()||e.requestSummary,iterationId:v,inferredById:n.id}};p.push(B),l.push(b)}if(h.length>0){let m=new Set(e.governingDecisionIds??[]),j=i.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&m.has(g.id)),b={id:oe(o,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:i.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:v}],recordType:"implementation_attempt",state:"completed",iterationIds:[v],coverageClaims:j.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map(B=>B.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:v}]})),summary:h.map(g=>g.summary).join(" "),artifactIds:[]};p.push(b)}return{mutation:d,iterationId:v,proposalIds:l,observationId:P}}import{createHash as cc}from"crypto";import{mkdir as dc,open as lc,readFile as pc,rename as uc,unlink as mc}from"fs/promises";import{join as Xo}from"path";function Yo(i){return i.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Zo(i){return cc("sha256").update(JSON.stringify(i)).digest("hex")}async function fc(i,e){let t=`${i}.${process.pid}.${Date.now()}.tmp`,n=await lc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
153
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await uc(t,i)}catch(o){throw await mc(t).catch(()=>{}),o}}function hc(i,e,t=new Date().toISOString()){let n={},o={},r={},s=(d,p,x)=>{let T=d[p]??=[];T.includes(x)||T.push(x)};for(let d of i.records)if(d.recordType==="subject"){let p=d;for(let x of[p.label,...p.aliases,...p.locators.filter(T=>T.status==="current").map(T=>T.value)]){let T=Yo(x);T&&s(n,T,p.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let p of d.subjects)s(o,p.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let p of d.subjects)s(r,p.subjectId,d.id);let c={version:1,projectId:i.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:o,proposalIdsBySubject:r};return{...c,checksum:Zo(c)}}function er(i,e){let t=[...new Set(e.flatMap(n=>i.subjectIdsByValue[Yo(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>i.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>i.proposalIdsBySubject[n]??[]))]}}var Bn=class{constructor(e){this.indexDir=Xo(e,".popmelt","memory","indexes"),this.indexPath=Xo(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let o=JSON.parse(await pc(this.indexPath,"utf8")),{checksum:r,...s}=o;if(o.version===1&&o.projectId===e.manifest.projectId&&o.journalHead.sequence===t.sequence&&o.journalHead.hash===t.hash&&r===Zo(s))return o}catch(o){if(o.code!=="ENOENT"&&!(o instanceof SyntaxError))throw o}let n=hc(e,t);return await dc(this.indexDir,{recursive:!0}),await fc(this.indexPath,n),n}};var nn="popmelt:imprint",ir="popmelt:imprint-evidence",Dt="popmelt:imprint-relation";function Ln(i){return i.sourceRefs.find(e=>e.kind==="external"&&e.uri===nn)?.id}function Ji(i){let e=new Set;return i.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function Fn(i,e){if(!i)return[];let t=new Set(i.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return i.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function Bi(i){if(i==="expresses")return"operationalizes";if(i==="excepts")return"excepts"}var qn=class{constructor(e){this.projectRoot=e;this.store=new Jn(e),this.indexStore=new Bn(e),this.manifestPath=Ot(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await tn(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let o=await this.store.load();return o.report.recoveredTransactions>0&&(o=await this.store.recover()),await this.refreshIndex(o),await this.status()}let n=await en({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(o=>o.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(n.bundle)}catch(o){if(!(o instanceof Error)||!o.message.includes("already initialized"))throw o}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await en({...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=Ot(this.projectRoot,".popmelt","memory","migrations"),t=Ot(e,"imprint-advisories-v2.json");try{let m=JSON.parse(await tn(t,"utf8"));return{migrated:!1,explanations:m.explanations??0,evidence:m.evidence??0}}catch{}let n;try{n=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await tr(e,{recursive:!0}),await nr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let o=await this.store.load(),r=o.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),c=o.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??r,d=o.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let p=o.bundle.manifest.projectId,x=new Set(o.bundle.records.map(m=>m.id)),T=new Set(o.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Dt?[j.id]:[]))),k=new Map,P=o.bundle.records.filter(m=>m.recordType==="advisory_explanation");for(let m of n.explanations){let j=P.find(b=>Ln(b)===m.id);k.set(m.id,j?.id??oe(p,"imprint-explanation",m.id,Date.parse(m.createdAt)))}let v=[],f=[],l=[],h=0;for(let m of n.explanations){let j=k.get(m.id),b=P.find(R=>R.id===j),g=[],B=m.evidence.length?m.evidence:[{id:`fallback:${m.id}`,kind:"observation",stance:"supports",summary:m.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:m.createdAt}];for(let R of B){let N=oe(p,"imprint-evidence-record",R.id,Date.parse(R.createdAt));g.push(N),!x.has(N)&&(v.push({id:N,schemaVersion:1,projectId:p,createdAt:R.createdAt,participantId:c.id,sourceRefs:Ji([{kind:"external",id:R.id,uri:ir},{kind:"external",id:m.id,uri:nn},{kind:"thread",id:R.threadId},{kind:"message",id:R.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(R.kind)?"user_feedback":"judgment",summary:R.summary,availability:"available",artifactIds:[]}),l.push({id:oe(p,"imprint-evidence-link",`${m.id}:${R.id}`,Date.parse(R.createdAt)),schemaVersion:1,projectId:p,createdAt:R.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:R.id,uri:ir}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:N},reason:"This advisory explanation was derived from collaboration evidence."}),h+=1)}let E={id:j,schemaVersion:1,projectId:p,createdAt:b?.createdAt??m.createdAt,participantId:b?.participantId??c.id,sourceRefs:Ji([...b?.sourceRefs??[],{kind:"external",id:m.id,uri:nn}]),recordType:"advisory_explanation",kind:m.kind,state:m.state,statement:m.statement,rationale:m.rationale,scope:structuredClone(m.scope),subjectIds:[d.id],evidenceIds:[...new Set([...b?.evidenceIds??[],...g])],concreteBindings:Fn(n,m.id),supersededById:m.supersededBy?k.get(m.supersededBy):void 0,updatedAt:m.updatedAt};b?f.push(E):v.push(E)}for(let m of n.relations){let j=Bi(m.type);if(!j)continue;let b=k.get(m.fromId),g=k.get(m.toId);!b||!g||T.has(m.id)||l.push({id:oe(p,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:p,createdAt:m.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:m.id,uri:Dt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:b},to:{entityType:"advisory_explanation",entityId:g},reason:m.rationale||"The Imprint graph connected these explanations."})}let u=new Date().toISOString();if(v.length||f.length||l.length)try{let m=await this.store.commit({records:v,recordReplacements:f,events:[],relationships:l,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:oe(p,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:u});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}return await tr(e,{recursive:!0}),await nr(t,JSON.stringify({version:2,migratedAt:u,explanations:n.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:h}}async review(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,selection:Ei(n.bundle,o)}}async contextualize(e,t={}){let n=await this.loadSource(t),o=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:Fo(n.bundle,o),reviewSelection:Ei(n.bundle,o)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:On(n.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let t=await en({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),o=On(n.bundle,e);if(!o.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(o.errors)}`);let r=await this.store.commitReviewPlan(o.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(k=>k.recordType==="proposal"&&k.id===e.proposalId),o=t.bundle.records.find(k=>k.recordType==="participant"&&k.kind==="human"&&k.status==="active");if(!n||n.state!=="pending"||!o)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:n.id,participantId:o.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:we(r),decisionId:we(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:we(r),replacementProposalId:we(r),acceptanceEventId:we(r),decisionId:we(r),relationshipId:we(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:we(r),reason:e.reason}:{...c,action:"defer",eventId:we(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(k=>k.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=On(t.bundle,d);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(k=>k.message).join(" ")};let x=await this.store.commitReviewPlan(p.plan,{transactionId:we(r),committedAt:s});await this.refreshIndex(x);let T=p.plan.resultRefs.find(k=>k.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:x.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=Qo(t.bundle,e),o=oe(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:o,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),o=n.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),r=n.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active"),s=e.action?o:r??o,c=n.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),p=Date.parse(d),x=n.bundle.manifest.projectId,T=[],k=[],P=[],v=n.bundle.records.filter(u=>u.recordType==="advisory_explanation"),f=new Map(v.flatMap(u=>{let m=Ln(u);return m?[[m,u.id]]:[]}));for(let u of e.summary.changes)if(!f.has(u.explanationId)){let m=t?.explanations.find(j=>j.id===u.explanationId);f.set(u.explanationId,oe(x,"imprint-explanation",u.explanationId,Date.parse(m?.createdAt??d)))}for(let u of e.summary.changes){let m={kind:"external",id:u.explanationId,uri:nn},j=f.get(u.explanationId),b=v.find(R=>R.id===j),g=t?.explanations.find(R=>R.id===u.explanationId),B={id:oe(x,"imprint-live-evidence",`${e.summary.transactionId}:${u.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[m,{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(B);let E={id:j,schemaVersion:1,projectId:x,createdAt:b?.createdAt??g?.createdAt??d,participantId:b?.participantId??s.id,sourceRefs:Ji([...b?.sourceRefs??[],m,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??b?.kind??"pattern",state:g?.state??u.state,statement:g?.statement??u.statement,rationale:g?.rationale??b?.rationale??e.summary.detail,scope:structuredClone(g?.scope??b?.scope??{kind:"project",values:[]}),subjectIds:b?.subjectIds??[c.id],evidenceIds:[...new Set([...b?.evidenceIds??[],B.id])],concreteBindings:g?Fn(t,u.explanationId):b?.concreteBindings??[],supersededById:g?.supersededBy?f.get(g.supersededBy):b?.supersededById,updatedAt:g?.updatedAt??d};b?k.push(E):T.push(E),P.push({id:oe(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${u.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[m],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E.id},to:{entityType:"evidence",entityId:B.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let l=new Set(n.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(m=>m.kind==="external"&&m.uri===Dt?[m.id]:[])));for(let u of t?.relations??[]){let m=Bi(u.type);if(!m)continue;let j=f.get(u.fromId),b=f.get(u.toId);!j||!b||l.has(u.id)||P.push({id:oe(x,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:x,createdAt:u.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:u.id,uri:Dt}],recordType:"relationship",relationshipType:m,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:b},reason:u.rationale||"The Imprint graph connected these explanations."})}let h=oe(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let u=await this.store.commit({records:T,recordReplacements:k,events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:h,committedAt:d});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),r=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=t.bundle.manifest.projectId,d=t.bundle.records.filter(g=>g.recordType==="advisory_explanation"),p=new Map(d.flatMap(g=>{let B=Ln(g);return B?[[B,g]]:[]})),x=new Map([...[...p].map(([g,B])=>[g,B.id]),...e.explanations.filter(g=>!p.has(g.id)).map(g=>[g.id,oe(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),T=[],k=[],P=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let B=p.get(g.id);if(!B){T.push({id:x.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:nn}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Fn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let E={...structuredClone(B),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:Fn(e,g.id),supersededById:g.supersededBy?x.get(g.supersededBy):void 0,updatedAt:g.updatedAt},R=N=>JSON.stringify({kind:N.kind,state:N.state,statement:N.statement,rationale:N.rationale,scope:N.scope,concreteBindings:N.concreteBindings,supersededById:N.supersededById,updatedAt:N.updatedAt});R(B)!==R(E)&&k.push(E)}for(let[g,B]of p)P.has(g)||B.state==="retired"||k.push({...structuredClone(B),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let v=new Set(t.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),f=new Map(t.bundle.relationships.flatMap(g=>{if(v.has(g.id))return[];let B=g.sourceRefs.find(E=>E.kind==="external"&&E.uri===Dt)?.id;return B?[[B,g]]:[]})),l=[],h=new Set;for(let g of e.relations){let B=Bi(g.type);if(!B)continue;let E=x.get(g.fromId),R=x.get(g.toId);if(!E||!R)continue;let N=f.get(g.id);N&&N.relationshipType===B&&N.from.entityType==="advisory_explanation"&&N.from.entityId===E&&N.to.entityType==="advisory_explanation"&&N.to.entityId===R||(N&&h.add(g.id),l.push({id:oe(c,"imprint-relation",`${g.id}:${B}:${E}:${R}`,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Dt}],recordType:"relationship",relationshipType:B,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:R},reason:g.rationale||"The Imprint graph connected these explanations."}))}let u=new Set(e.relations.map(g=>g.id)),m=n?[...f].filter(([g])=>!u.has(g)||h.has(g)).map(([,g])=>({id:oe(c,"imprint-relationship-tombstone",g.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:g.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!T.length&&!k.length&&!l.length&&!m.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let j=e.updatedAt,b=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let g=await this.store.commit({records:T,recordReplacements:k,events:[],relationships:l,artifacts:[],tombstones:m,projectionUpdates:[]},{transactionId:b,committedAt:j});return await this.refreshIndex(g),{status:"synced",relationships:l.length+m.length,explanations:T.length+k.length,headSequence:g.report.headSequence}}catch(g){if(!(g instanceof Error)||!g.message.includes("Transaction already exists"))throw g;return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let n={};for(let o of t.bundle.records)n[o.recordType]=(n[o.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(o=>o.recordType==="freshness_signal"&&o.state==="open").length,unavailableEvidence:t.bundle.records.filter(o=>o.recordType==="evidence"&&o.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),o=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!o.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(o=>o.recordType==="decision"&&o.state==="active"?[o.id]:[])),n=new Map;for(let o of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))o.decisionIds.some(r=>t.has(r))&&n.set(o.key,o);return[...n.values()]}async getImprintView(e=[],t){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let o=await this.store.load(),r=o.bundle.records.filter(l=>l.recordType==="advisory_explanation"),s=new Map(r.map(l=>[l.id,l])),c=new Map(r.flatMap(l=>{let h=Ln(l);return h?[[h,l.id]]:[]})),d=new Set(e.map(l=>c.get(l)??l)),p=new Map(o.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),x=new Map(o.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),T=new Set(o.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),k=new Set(["operationalizes","excepts"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},v=r.map(l=>{let h=l.evidenceIds.flatMap(b=>{let g=x.get(b);if(!g)return[];let B=g.sourceRefs.find(V=>V.kind==="thread")?.id,E=g.sourceRefs.find(V=>V.kind==="message")?.id,R=g.kind==="judgment"||g.kind==="user_feedback"||g.kind==="project_state"?g.kind:"other",N=p.get(g.participantId)??"unknown";return[{id:g.id,kind:R,summary:g.summary,createdAt:g.createdAt,participantKind:N,threadId:B,jobId:E}]}).sort((b,g)=>g.createdAt.localeCompare(b.createdAt)),u=o.bundle.relationships.flatMap(b=>{if(T.has(b.id))return[];if(!k.has(b.relationshipType))return[];let g=b.from.entityType==="advisory_explanation"&&b.from.entityId===l.id&&b.to.entityType==="advisory_explanation",B=b.to.entityType==="advisory_explanation"&&b.to.entityId===l.id&&b.from.entityType==="advisory_explanation";if(!g&&!B)return[];let E=g?b.to.entityId:b.from.entityId,R=s.get(E);return R?[{id:b.id,type:b.relationshipType==="operationalizes"?"expresses":"excepts",direction:g?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:b.reason}]:[]}),m=[...(l.supersededById?[l.supersededById]:[]).flatMap(b=>{let g=s.get(b);return g?[{id:`supersedes:${l.id}:${g.id}`,type:"supersedes",direction:"incoming",explanationId:g.id,statement:g.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(b=>b.supersededById===l.id?[{id:`supersedes:${b.id}:${l.id}`,type:"supersedes",direction:"outgoing",explanationId:b.id,statement:b.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...l.sourceRefs.flatMap(b=>b.kind==="thread"?[b.id]:[]),...h.flatMap(b=>b.threadId?[b.threadId]:[])])].filter(b=>!t||t.has(b));return{id:l.id,kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),createdAt:l.createdAt,updatedAt:l.updatedAt,evidenceCount:h.length,recentEvidence:h.slice(0,4),concrete:l.concreteBindings.map(b=>({...structuredClone(b)})),relations:[...u,...m],sourceThreadIds:j,needsGrounding:l.state==="testing"&&d.has(l.id)}}).sort((l,h)=>Number(h.needsGrounding)-Number(l.needsGrounding)||P[l.state]-P[h.state]||h.updatedAt.localeCompare(l.updatedAt)),f={total:v.filter(l=>l.state!=="retired").length,emerging:v.filter(l=>l.state==="emerging").length,testing:v.filter(l=>l.state==="testing").length,grounded:v.filter(l=>l.state==="grounded").length,challenged:v.filter(l=>l.state==="challenged").length,retired:v.filter(l=>l.state==="retired").length,needsGrounding:v.filter(l=>l.needsGrounding).length};return{head:{sequence:o.report.headSequence,updatedAt:o.bundle.manifest.updatedAt},counts:f,explanations:v}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),n=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,p)=>d.createdAt.localeCompare(p.createdAt)))c.decisionIds.some(d=>t.has(d))&&n.set(c.key,c);let o=[...n.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(p=>p.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((p,x)=>x.createdAt.localeCompare(p.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:o.some(p=>p.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:o.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),n=t.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),o=t.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!n||!o)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=we(r),d=we(r),p=we(r),x=we(r),T=we(r),k=new Set(t.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),P=t.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&k.has(R.id)),v={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:o.id,role:"governed"}],l={...v,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},h={...v,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},u={...v,id:p,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},m={...v,id:x,recordType:"model_entry",key:e.key,subjectIds:[o.id],decisionIds:[p],value:e.value},j={...v,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[p],entryIds:[x],coverage:[{decisionId:p,status:"projected"}]},b={...v,id:we(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},g=P.map(R=>({...v,id:we(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:R.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),B=P.map(R=>({...v,id:we(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:u.id},to:{entityType:"decision",entityId:R.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),E=await this.store.commit({records:[l,u,m,j],events:[h,...g],relationships:[b,...B],artifacts:[],tombstones:[],projectionUpdates:P.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:we(r),committedAt:s});return await this.refreshIndex(E),{decisionId:p,entryId:x}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(o=>o.recordType==="proposal"&&o.state==="pending"&&o.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),n=t.bundle.records.find(v=>v.recordType==="model_projection"&&v.state==="applied"&&v.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let o=t.bundle.records.filter(v=>v.recordType==="decision"&&e.decisionIds.includes(v.id)&&v.state==="active");if(o.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=we(s),p=e.changes.map(v=>{let f=v.decisionIds?.filter(u=>e.decisionIds.includes(u)),l=f?.length?f:e.decisionIds,h=[...new Set(o.filter(u=>l.includes(u.id)).flatMap(u=>u.subjects.map(m=>m.subjectId)))];return{id:we(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:l.map(u=>({kind:"record",id:u})),recordType:"model_entry",key:v.path.map(String).join("."),subjectIds:h,decisionIds:l,value:v.value}}),x=new Set(p.flatMap(v=>v.decisionIds)),T={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(v=>({kind:"record",id:v})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:p.map(v=>v.id),coverage:e.decisionIds.map(v=>e.coverage?.find(f=>f.decisionId===v)??{decisionId:v,status:x.has(v)?"projected":"unprojected"})},k=p.flatMap(v=>v.decisionIds.map(f=>({id:we(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:T.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:v.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),P=await this.store.commit({records:[...p,T],events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:we(s),committedAt:c});return await this.refreshIndex(P),{projectionId:d,entryIds:p.map(v=>v.id),headSequence:P.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await en({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),o=er(n,t.subjectHints??[]);return o?{...t,subjectIds:[...new Set([...t.subjectIds??[],...o.subjectIds])],candidateDecisionIds:o.decisionIds,candidateProposalIds:o.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Jt(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Expected a JSON object.");return i}function ke(i,e){if(typeof i!="string"||!i.trim())throw new Error(`${e} must be a non-empty string.`);return i}function Nt(i,e,t){let n=ke(i,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function Li(i){let e=Jt(i),t=Jt(e.authority),n=t.level,o=t.mode,r=Nt(n,"authority.level",["owner","delegate","contributor"]),s=Nt(o,"authority.mode",["local_trusted","hosted"]),c={proposalId:ke(e.proposalId,"proposalId"),participantId:ke(e.participantId,"participantId"),occurredAt:ke(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:ke(e.eventId,"eventId"),decisionId:ke(e.decisionId,"decisionId"),kind:Nt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:ke(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:ke(e.eventId,"eventId"),reason:ke(e.reason,"reason")};case"defer":{let d=Jt(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:ke(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(p=>ke(p,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(p=>Nt(p,"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{...c,action:"edit_and_accept",withdrawalEventId:ke(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:ke(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:ke(e.acceptanceEventId,"acceptanceEventId"),decisionId:ke(e.decisionId,"decisionId"),relationshipId:ke(e.relationshipId,"relationshipId"),claim:ke(e.claim,"claim"),kind:Nt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let p=Jt(d);return{subjectId:ke(p.subjectId,"subjectId"),role:Nt(p.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:ke(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Fi(i){let e=Jt(i),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>ke(c,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},o=e.resurface===void 0?void 0:Jt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:o?{differentAction:o.differentAction===!0,newEvidence:o.newEvidence===!0,newConflict:o.newConflict===!0,ownerRequested:o.ownerRequested===!0}:void 0}}function Bt(i){return i.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
154
|
-
`)}async function
|
|
155
|
-
`)}function sr(
|
|
154
|
+
`;function _n(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function ka(o,e){let t=_n(e);if(!t)return null;let n=new URL(t),i=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&_n(s.url)),r=i.find(s=>_n(s.url)===t);return r||(i.find(s=>{let c=new URL(_n(s.url));return c.origin===n.origin&&c.pathname===n.pathname})??null)}function Ra(o){let e={x:Number(o.x),y:Number(o.y),width:Number(o.width),height:Number(o.height)};if(!Object.values(e).every(Number.isFinite)||e.x<0||e.y<0||e.width<=0||e.height<=0||e.width>1e5||e.height>1e5)throw new Error("Invalid native screenshot clip");return e}async function Pa(o){let e=new AbortController,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",o).href,i=await fetch(n,{signal:e.signal});if(!i.ok)throw new Error(`CDP discovery returned ${i.status}`);let r=await i.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function ja(o){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let i=new e(o,{handshakeTimeout:1e3}),r=()=>{i.off("error",s),t(i)},s=c=>{i.off("open",r),n(c)};i.once("open",r),i.once("error",s)})}function Aa(o){let e=1,t=new Map;return o.on("message",n=>{let i;try{i=JSON.parse(String(n))}catch{return}if(!i.id)return;let r=t.get(i.id);r&&(t.delete(i.id),clearTimeout(r.timeout),i.error?r.reject(new Error(i.error.message||`CDP error ${i.error.code??""}`.trim())):r.resolve(i.result??{}))}),o.on("close",()=>{for(let[n,i]of t)clearTimeout(i.timeout),i.reject(new Error("CDP connection closed")),t.delete(n)}),(n,i={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{t.delete(c),s(new Error(`CDP ${n} timed out`))},4e3);t.set(c,{resolve:r,reject:s,timeout:d}),o.send(JSON.stringify({id:c,method:n,params:i}),u=>{u&&(clearTimeout(d),t.delete(c),s(u))})})}async function Ji(o,e){let t=Ra(e.clip),n=await Pa(o),i=ka(n,e.pageUrl);if(!i?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await ja(i.webSocketDebuggerUrl),s=Aa(r),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Sa,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),u=typeof d.data=="string"?d.data:"";if(!u)throw new Error("CDP returned an empty screenshot");return Buffer.from(u,"base64")}finally{c&&await s("Runtime.evaluate",{expression:Ta,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as tr,readFile as tn,writeFile as nr}from"fs/promises";import{join as Ot}from"path";var Ma=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Eo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Cn(o){return new Set(Eo(o).split(" ").filter(e=>e.length>2&&!Ma.has(e)))}function Bi(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Ea(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function _a(o,e){let t=new Map,n=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(Eo).filter(Boolean),r=Cn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of Ea(s)){let u=Eo(d.value);for(let T of i){let P=u===T?95:u.includes(T)||T.includes(u)?75:0;P>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:d.by,score:P})}let k=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(Bi(Cn(u),r)*55);k>=30&&k>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"query_text",score:k})}c&&t.set(s.id,c)}return t}function Ca(o,e){let t=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>t.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&n.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function $a(o){return Math.ceil(JSON.stringify(o).length/4)}function _o(o,e){let t=o.records.filter(l=>l.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(l=>{if(l.recordType!=="proposal"||i&&!i.has(l.id))return!1;if(l.state==="pending")return!0;if(l.state!=="deferred")return!1;let f=[...o.events].reverse().find(m=>m.entity.entityType==="proposal"&&m.entity.entityId===l.id&&m.toState==="deferred"&&m.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(n)>=Date.parse(f.revisitAfter)):!1}),s=o.records.filter(l=>l.recordType==="implementation_attempt"),c=_a(t,e),d=[...c.values()].sort((l,f)=>f.score-l.score),u=Cn([e.action,e.text].filter(Boolean).join(" ")),I=r.flatMap(l=>{let f=l.subjects.map(b=>c.get(b.subjectId)).filter(b=>!!b),m=Math.max(0,...f.map(b=>b.score)),h=Math.round(Bi(Cn(l.claim),u)*35),j=m+h;return j>=50?[{proposal:l,proposalMatches:f,score:j}]:[]}).sort((l,f)=>f.score-l.score||l.proposal.id.localeCompare(f.proposal.id)),k=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),P=[],x=0;for(let l of I){if(P.length>=k)break;let f=l.proposal.sourceRefs.slice(0,4),m={contractVersion:1,packetId:`review:${l.proposal.id}`,projectId:o.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:l.proposalMatches.length?`Historical proposal intersects ${l.proposalMatches.map(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:l.proposalMatches.map(({score:j,...b})=>b)},proposal:{id:l.proposal.id,claim:l.proposal.claim,state:l.proposal.state,proposedKind:l.proposal.proposedKind,subjectIds:l.proposal.subjects.map(j=>j.subjectId),origin:l.proposal.origin.mode},authority:"unaccepted",presentation:l.score>=100&&["constraint","rule"].includes(l.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ca(l.proposal,s),evidence:{sourceCount:l.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:l.proposal.id},...f]},h={...m,estimatedTokens:$a(m)};if(x+h.estimatedTokens>T)break;P.push(h),x+=h.estimatedTokens}let p=Math.max(0,I.length-P.length);return{packets:P,subjectMatches:d.map(({score:l,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:I.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:x},uncertainty:c.size===0?"subject_unresolved":I.length===0?"no_relevant_pending_proposal":void 0}}var Oa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Co(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function $n(o){return new Set(Co(o).split(" ").filter(e=>e.length>2&&!Oa.has(e)))}function Li(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Da(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Co).filter(Boolean),i=$n([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(u=>({value:u,by:"alias"})),...s.locators.map(u=>({value:u.value,by:"locator"}))];for(let u of d){let I=Co(u.value);for(let P of n){let x=I===P?95:I.includes(P)||P.includes(I)?75:0;x>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:u.by,score:x})}let T=["/","#","[","]","="].some(P=>u.value.includes(P))?0:Math.round(Li($n(I),i)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"semantic",score:T})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Na(o){return Math.ceil(JSON.stringify(o).length/4)}function Et(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ja(o,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!t.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),i=n.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function Ba(o,e,t){let n=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),i=t.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=n[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:n.map(c=>c.id)}}function qi(o,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),i=o.records.filter(g=>g.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=r?s.filter(g=>r.has(g.id)):s,d=o.records.filter(g=>g.recordType==="implementation_attempt"),u=o.records.filter(g=>g.recordType==="verification_attempt"),I=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),k=o.records.filter(g=>g.recordType==="evidence"),T=o.records.filter(g=>g.recordType==="model_entry"),P=Da(i,e),x=new Map(P.map(g=>[g.subjectId,g.score])),p=$n([e.action,e.text].filter(Boolean).join(" ")),l=c.flatMap(g=>{let B=Math.max(0,...g.subjects.map(N=>x.get(N.subjectId)??0)),E=Math.round(Li($n(g.claim),p)*35),R=B+E;return R>=50?[{decision:g,score:R}]:[]}).sort((g,B)=>B.score-g.score||g.decision.id.localeCompare(B.decision.id)),f=new Map;for(let g of l.slice(0,n))f.set(g.decision.id,g.decision);for(let g of o.relationships){if(!Et(g,"excepts")&&!Et(g,"contradicts"))continue;let B=s.find(R=>R.id===g.from.entityId),E=s.find(R=>R.id===g.to.entityId);!B||!E||!f.has(B.id)&&!f.has(E.id)||(f.size<n&&f.set(B.id,B),f.size<n&&f.set(E.id,E))}let m=[...f.values()],h=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&f.has(g.from.entityId)&&f.has(g.to.entityId),j=(g,B=!1)=>{let E=new Set(g.map(J=>J.id)),R=I.filter(J=>J.target.entityType==="decision"&&E.has(J.target.entityId)),N=new Set(o.relationships.filter(J=>Et(J,"excepts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),K=o.relationships.filter(J=>Et(J,"contradicts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),G=new Set(K.flatMap(J=>J.decisionIds)),Q=k.filter(J=>J.sourceRefs.some(D=>D.kind==="record"&&E.has(D.id))||o.relationships.some(D=>D.relationshipType==="supports"&&D.from.entityType==="evidence"&&D.from.entityId===J.id&&D.to.entityType==="decision"&&E.has(D.to.entityId))),w=Math.max(0,l.length-g.length),H=o.relationships.some(J=>Et(J,"contradicts")&&h(J)&&(!E.has(J.from.entityId)||!E.has(J.to.entityId))),L=B||w>0||H,O=[];P.length===0&&(e.subjectHints?.length??0)>0?O.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&O.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&O.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap(J=>J.expansionRefs)}),Q.some(J=>J.availability!=="available")&&O.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(J=>({kind:"record",id:J.id}))}),L&&O.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:P.map(({score:J,...D})=>D),modelEntries:T.filter(J=>J.decisionIds.some(D=>E.has(D))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:g.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(D=>D.subjectId),authority:J.authority,effectiveState:G.has(J.id)?"conflicted":N.has(J.id)?"excepted":"active",freshness:R.filter(D=>D.target.entityId===J.id).map(D=>D.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:K,uncertainties:O,implementation:g.map(J=>Ja(J.id,d)),verification:g.map(J=>Ba(J.id,u,R)),evidence:Q.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:w,omittedEvidenceCount:0,conflictsComplete:!H}};return he.budget.estimatedTokens=Na(he),he},b=j(m);for(;b.budget.estimatedTokens>t&&m.length>0;){let g=m.pop(),B=o.relationships.filter(E=>Et(E,"contradicts")&&(E.from.entityId===g.id||E.to.entityId===g.id)).flatMap(E=>[E.from.entityId,E.to.entityId]);m=m.filter(E=>!B.includes(E.id)),b=j(m,!0)}return b}var La=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _t(o){return La.test(o)}function qa(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function te(o,e,t,n){o.push({path:e,code:t,message:n,severity:"error"})}function $o(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Re(o,e,t){_t(t)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function It(o,e,t,n=!1){n&&t.level==="contributor"&&te(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&te(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Fa={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"])},Ua=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function za(o,e,t){Re(o,`${t}.id`,e.id),Re(o,`${t}.projectId`,e.projectId),Re(o,`${t}.participantId`,e.participantId),Re(o,`${t}.entity.entityId`,e.entity.entityId),Qe(o,`${t}.createdAt`,e.createdAt),It(o,`${t}.authority`,e.authority);let n=Fa[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(i)&&te(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Ua.has(r)&&(It(o,`${t}.authority`,e.authority,!0),e.reason?.trim()||te(o,`${t}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&te(o,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(o,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Wa(o,e,t,n){Re(o,`${t}.id`,e.id),Re(o,`${t}.projectId`,e.projectId),Re(o,`${t}.participantId`,e.participantId),Qe(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&te(o,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(o,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(o,`${t}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&te(o,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(It(o,`${t}.authority`,e.authority,!0),e.claim.trim()||te(o,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&$o(o,`${t}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&te(o,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&te(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&te(o,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(o,`${t}.concreteBindings[${r}].createdAt`,i.createdAt),Qe(o,`${t}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(o,`${t}.appliedAt`,e.appliedAt),It(o,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&te(o,`${t}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&te(o,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&te(o,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&$o(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&$o(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ga(o,e,t){if(Re(o,`${t}.id`,e.id),Re(o,`${t}.projectId`,e.projectId),Re(o,`${t}.participantId`,e.participantId),Re(o,`${t}.from.entityId`,e.from.entityId),Re(o,`${t}.to.entityId`,e.to.entityId),Qe(o,`${t}.createdAt`,e.createdAt),e.reason.trim()||te(o,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&te(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?te(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&It(o,`${t}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(o,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(o,t,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&te(o,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(o,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function wt(o){let e=[];Re(e,"manifest.projectId",o.manifest.projectId),Qe(e,"manifest.createdAt",o.manifest.createdAt),Qe(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(p,l)=>{let f=t.get(p);f?te(e,l,"duplicate_id",`ID is already used at ${f}.`):t.set(p,l)};o.records.forEach((p,l)=>{let f=`records[${l}]`;n(p.id,f),Wa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,l)=>{let f=`events[${l}]`;n(p.id,f),za(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,l)=>{let f=`relationships[${l}]`;n(p.id,f),Ga(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,l)=>{n(p.id,`artifacts[${l}]`),Re(e,`artifacts[${l}].id`,p.id)}),o.tombstones.forEach((p,l)=>{let f=`tombstones[${l}]`;n(p.id,f),Re(e,`${f}.id`,p.id),Re(e,`${f}.objectId`,p.objectId),Re(e,`${f}.deletedById`,p.deletedById),Qe(e,`${f}.deletedAt`,p.deletedAt),It(e,`${f}.authority`,p.authority,!0)});let i=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),r=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,l)=>{let f=`${p.entityType}:${p.entityId}`;!i.has(f)&&!r.has(f)&&te(e,l,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,l)=>s(p.entity,`events[${l}].entity`)),o.relationships.forEach((p,l)=>{s(p.from,`relationships[${l}].from`),s(p.to,`relationships[${l}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,l)=>{c.has(p)||te(e,l,"dangling_artifact_reference","No artifact manifest entry exists.")},u=(p,l,f)=>{!i.has(`${p}:${l}`)&&!r.has(`${p}:${l}`)&&te(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,l)=>{let f=`records[${l}]`;switch(p.recordType){case"authority_grant":u("participant",p.granteeId,`${f}.granteeId`),u("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`));break;case"observation":p.captureContext.subjectIds.forEach((m,h)=>u("subject",m,`${f}.captureContext.subjectIds[${h}]`)),p.captureContext.artifactIds.forEach((m,h)=>d(m,`${f}.captureContext.artifactIds[${h}]`));break;case"proposal":case"decision":p.subjects.forEach((m,h)=>u("subject",m.subjectId,`${f}.subjects[${h}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((m,h)=>d(m,`${f}.messageArtifactIds[${h}]`)),p.resultRefs.forEach((m,h)=>s(m,`${f}.resultRefs[${h}]`));break;case"iteration":p.threadIds.forEach((m,h)=>u("thread",m,`${f}.threadIds[${h}]`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"evidence":p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"advisory_explanation":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`)),p.supersededById&&u("advisory_explanation",p.supersededById,`${f}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((m,h)=>u("iteration",m,`${f}.iterationIds[${h}]`)),p.coverageClaims.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverageClaims[${h}].decisionId`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"eval_spec":p.replacesSpecId&&u("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),(p.dependencies??[]).forEach((m,h)=>{m.kind==="subject"&&m.subjectId&&u("subject",m.subjectId,`${f}.dependencies[${h}].subjectId`)}),(p.scenarios??[]).forEach((m,h)=>{m.subjectIds?.forEach((j,b)=>u("subject",j,`${f}.scenarios[${h}].subjectIds[${b}]`))}),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`));break;case"verification_attempt":p.evalSpecId&&u("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;case"model_entry":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`));break;case"model_projection":It(e,`${f}.authority`,p.authority,!0),u("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.entryIds.forEach((m,h)=>u("model_entry",m,`${f}.entryIds[${h}]`)),p.coverage.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverage[${h}].decisionId`));break;case"freshness_signal":s(p.target,`${f}.target`),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;default:break}});let I=new Map(o.events.map(p=>[p.id,p])),k=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),T=new Map;o.events.forEach((p,l)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,m=T.get(f)??new Set;m.add(p.toState),T.set(f,m),m.size>1&&te(e,`events[${l}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let P=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),x=(p,l,f,m,h)=>{if(p.level!=="delegate"||!p.grantId)return;let j=P.get(p.grantId);if(!j){te(e,h,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==l||j.level!=="delegate")&&te(e,h,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let b=Date.parse(f);(b<Date.parse(j.startsAt)||j.endsAt&&b>Date.parse(j.endsAt)||j.revokedAt&&b>=Date.parse(j.revokedAt))&&te(e,h,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&m.length&&!m.every(g=>j.subjectIds.includes(g))&&te(e,h,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&x(p.authority,p.acceptedById,p.createdAt,p.subjects.map(l=>l.subjectId),`records:${p.id}.authority`);o.events.forEach((p,l)=>{let f=k.get(`${p.entity.entityType}:${p.entity.entityId}`),m=f&&"subjects"in f?f.subjects.map(h=>h.subjectId):[];x(p.authority,p.participantId,p.createdAt,m,`events[${l}].authority`)}),o.relationships.forEach((p,l)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(m=>{let h=k.get(`${m.entityType}:${m.entityId}`);return h&&"subjects"in h?h.subjects.map(j=>j.subjectId):[]});x(p.authority,p.participantId,p.createdAt,f,`relationships[${l}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let l=I.get(p.acceptanceEventId);(!l||l.entity.entityType!=="proposal"||l.entity.entityId!==p.proposalId||l.toState!=="accepted")&&te(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),l&&l.participantId!==p.acceptedById&&te(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),k.has(`proposal:${p.proposalId}`)||te(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(m=>m.relationshipType==="supersedes"&&m.to.entityType==="decision"&&m.to.entityId===p.id)||te(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(m=>m.entity.entityType==="decision"&&m.entity.entityId===p.id&&m.toState==="revoked"&&!!m.reason?.trim())||te(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||te(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return qa(e)}function Yt(o,e,t,n){return{id:n,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function Fi(o,e,t,n,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function Ha(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function On(o,e){let t=[],n=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),_t(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Ha(e))_t(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...Yt(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Fi(o,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...Yt(o,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Yt(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Fi(o,r,e,c.id,e.decisionId),u={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,d],events:[s,c],relationships:[u]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.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 r={...Yt(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let i={...Yt(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}var Ui={project:0,route:1,component:2,selector:2,file:3},zi={intention:0,principle:1,pattern:2};function Ct(o,e){let t=Ui[o.scope.kind]-Ui[e.scope.kind];return t!==0?t:zi[o.kind]-zi[e.kind]}function Wi(o){return o==="expresses"||o==="excepts"}function Va(o,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=o.explanations.find(r=>r.id===e.fromId),n=o.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let i=Ct(t,n);return i===0?void 0:i>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function bt(o){let e=structuredClone(o),t=new Set;return e.relations=o.relations.flatMap(n=>{let i=Va(o,n);if(!i)return[];let r=`${i.type}:${i.fromId}:${i.toId}`;return t.has(r)?[]:(t.add(r),[i])}),e}import{createHash as Ka}from"crypto";import{readFile as Qa,readdir as Xa,realpath as Ya}from"fs/promises";import{join as Zt,relative as Za}from"path";var ec=["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 $t(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function We(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Gi(...o){return o.find(e=>!!e?.trim())?.trim()}function ie(o,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ka("sha256").update(`${o}\0${e}\0${t}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function Oo(o,e){try{return JSON.parse(await Qa(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function tc(o){let e=$t(o);if(!e)return 0;let t=0,n=i=>{let r=$t(i);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let i of Object.values(e))n(i);return t}function nc(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function en(o){let e=[],t=await Ya(o.projectRoot).catch(()=>o.projectRoot),n=Zt(t,".popmelt"),i=await Oo(Zt(n,"threads.json"),e),r=await Oo(Zt(n,"model.json"),e),s=$t(i),c=$t(s?.threads)??{},d=Object.entries(c).map(([D,Y])=>({key:D,value:$t(Y)})).filter(D=>!!D.value),u=Zt(n,"decisions"),I=await Xa(u).catch(()=>[]),k=[];for(let D of I.filter(Y=>Y.endsWith(".json")).sort()){let Y=$t(await Oo(Zt(u,D),e));Y&&k.push({file:D,value:Y})}let T=d.flatMap(({value:D})=>[D.createdAt,D.updatedAt]).filter(D=>typeof D=="number"&&Number.isFinite(D)),P=T.length?Math.min(...T):0,x=o.projectKey??t;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ie(x,"project",x,P),l=ie(x,"participant","legacy-owner",P),f=ie(x,"participant","legacy-agent",P),m=ie(x,"subject","project",P),h=We(Math.max(P,...T)),j=[],b=[],g=new Map,B=new Map,E=new Map(k.map(D=>[D.value.id??D.file.replace(/^d-|\.json$/g,""),D.value])),R=new Map,N=(D,Y,ce,ke,se)=>{let Ue=g.get(ce);if(Ue)return Ue;let Ge=ie(x,"artifact",D,ke);return b.push({id:Ge,kind:Y,mediaType:se,location:ce,availability:"available"}),g.set(ce,Ge),Ge};for(let{file:D,value:Y}of k){let ce=Y.id??D.replace(/^d-|\.json$/g,""),ke=Y.createdAt??P,se=[N(`${ce}:envelope`,"other",`.popmelt/decisions/${D}`,ke,"application/json")];Y.screenshotPath&&se.push(N(`${ce}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,ke,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Ue,Ge]of(Y.pastedImagePaths??[]).entries())se.push(N(`${ce}:image:${Ue}`,"image",Ge,ke));R.set(ce,se)}let V=(D,Y,ce)=>({id:D,schemaVersion:1,projectId:p,createdAt:h,participantId:Y,sourceRefs:ce}),K=(D,Y)=>{j.push(Y);let ce=B.get(D)??[];ce.push(Y.id),B.set(D,ce)},G=[{...V(l,l,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...V(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(...G),j.push({...V(m,l,[]),recordType:"subject",subjectType:"project",label:Za(process.cwd(),t)||t,aliases:[],locators:[{id:ie(x,"locator",t,P),kind:"project_root",value:t,status:"current",validFrom:We(P),sourceRefs:[]}]});let Q=new Map,w=(D,Y)=>{let ce=Q.get(D);if(ce)return ce;let ke=ie(x,"subject",D,Y),se={...V(ke,l,[{kind:"external",id:D}]),createdAt:We(Y),recordType:"subject",subjectType:"element",label:D,aliases:[],locators:[{id:ie(x,"locator",D,Y),kind:"dom_selector",value:D,status:"current",validFrom:We(Y),sourceRefs:[{kind:"external",id:D}]}]};return j.push(se),Q.set(D,ke),ke};for(let{key:D,value:Y}of d){let ce=Y.id??D,ke=Y.createdAt??P,se=ie(x,"thread",ce,ke),Ue={kind:"thread",id:ce},Ge=[],Pe=[],rt=Array.isArray(Y.messages)?Y.messages:[],He,st,Wt=0;rt.forEach((be,at)=>{let Ee=be.timestamp??ke,et=ie(x,"artifact",`${ce}:message:${at}`,Ee);if(Ge.push(et),b.push({id:et,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ce}/messages/${at}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${ce}/messages/${at}`,et),be.screenshotPath&&N(`${ce}:message:${at}:screenshot`,"screenshot",be.screenshotPath,Ee),be.role==="human"){He=be;let Ne=be.feedbackSummary??be.replyToQuestion;if(Ne?.trim()){let Je=ie(x,"observation",`${ce}:${at}`,Ee),lt=Y.elementIdentifiers??[],Rt={...V(Je,l,[Ue,{kind:"message",id:et}]),createdAt:We(Ee),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:lt.map(ht=>w(ht,ke)),artifactIds:[et]},resolvedByIds:[]};K(ce,Rt),st=Je,Pe.push({entityType:"observation",entityId:Je})}return}if(be.role!=="assistant")return;let ct=be.jobId??`${ce}:${at}`,dt=ie(x,"iteration",ct,Ee),mt=E.get(ct),co=be.cancelled?"cancelled":be.error?"failed":be.question?"question_asked":(be.resolutions?.length??0)>0?"completed":"no_change",lo={...V(dt,f,[Ue,{kind:"message",id:et},...(R.get(ct)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:We(Ee),recordType:"iteration",threadIds:[se],startedAt:We(He?.timestamp,Ee),completedAt:We(Ee),requestSummary:Gi(He?.feedbackSummary,He?.replyToQuestion)??"[legacy request unavailable]",responseSummary:be.question??be.error??be.responseText?.slice(0,1e3),outcome:co,execution:{provider:be.provider??mt?.provider,model:be.model??mt?.model,sessionId:be.sessionId??mt?.sessionId},artifactIds:[et,...R.get(ct)??[]]};K(ce,lo),Pe.push({entityType:"iteration",entityId:dt});let ft=be.resolutions??mt?.resolutions??[];for(let[Ne,Je]of ft.entries()){if(Je.status!=="resolved"||!Je.summary?.trim())continue;let lt=Y.elementIdentifiers??[],Rt=(lt.length?lt:[t]).map(gn=>({subjectId:gn===t?m:w(gn,ke),role:"governed"})),ht=ie(x,"proposal",`${ct}:${Je.annotationId??"resolution"}:${Ne}`,Ee),po={...V(ht,f,[Ue,{kind:"iteration",id:dt}]),createdAt:We(Ee),recordType:"proposal",state:"pending",claim:Je.summary,subjects:Rt,subjectSemantics:Rt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Gi(He?.feedbackSummary,He?.replyToQuestion,Je.summary),iterationId:dt,inferredById:f}};K(ce,po),Pe.push({entityType:"proposal",entityId:ht}),e.push({severity:"warning",code:"acceptance_unresolved",source:ce,message:`Proposal ${ht} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(ft.some(Ne=>Ne.status==="resolved")||mt?.gitDiff){let Ne=ie(x,"implementation",ct,Ee),Je={...V(Ne,f,[Ue,{kind:"iteration",id:dt}]),createdAt:We(Ee),recordType:"implementation_attempt",state:"completed",iterationIds:[dt],coverageClaims:[],summary:ft.map(lt=>lt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(ce,Je),Pe.push({entityType:"implementation_attempt",entityId:Ne}),Wt+=1}st&&(st=void 0)});let kt=rt.at(-1),ao={...V(se,l,[Ue]),createdAt:We(ke),recordType:"thread",state:kt?.question?"open":"resolved",messageArtifactIds:Ge,outcome:kt?.question?"question_unresolved":Wt?"implementation_only":"no_outcome",resultRefs:Pe};j.push(ao),B.set(ce,[se,...B.get(ce)??[]])}let H=tc(r);H&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${H} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:p,createdAt:We(P),updatedAt:h,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:j,events:[],relationships:[],artifacts:b,tombstones:[]},O=wt(L),J=(o.proofCaseIds??ec).map(D=>({legacyId:D,threadFound:d.some(({key:Y,value:ce})=>(ce.id??Y)===D),decisionEnvelopeFound:E.has(D),recordIds:B.get(D)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((D,Y)=>D+(Y.value.messages?.length??0),0),decisionEnvelopes:k.length,modelEntries:H,artifactsReferenced:b.length},imported:nc(j),unresolvedAcceptance:e.filter(D=>D.code==="acceptance_unresolved").length,deferredModelEntries:H,proofCases:J,issues:e,schemaIssues:O.issues}}}import{createHash as oc}from"crypto";import{mkdir as Hi,open as Do,readFile as No,readdir as ic,rename as rc,unlink as Jo}from"fs/promises";import{join as tt}from"path";var sc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Nn(o){return oc("sha256").update(JSON.stringify(o)).digest("hex")}function Vi(o){return Nn(o)}function Ki(o,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let i=o.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(i<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=o.records[i];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);o.records[i]=structuredClone(n)}for(let n of e.projectionUpdates){let i=o.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(i.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${i.state}`);i.state=n.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=t,o}function ac(o,e,t){return Ki(structuredClone(o),e,t)}async function xt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Do(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
155
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await rc(t,o)}catch(i){throw await Jo(t).catch(()=>{}),i}}async function Dn(o){return JSON.parse(await No(o,"utf8"))}var Jn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=tt(e,".popmelt","memory"),this.journalDir=tt(this.memoryDir,"journal"),this.manifestPath=tt(this.memoryDir,"manifest.json"),this.checkpointPath=tt(this.memoryDir,"checkpoint.json"),this.lockPath=tt(this.memoryDir,"writer.lock")}async initialize(e){let t=wt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Hi(this.journalDir,{recursive:!0});try{throw await No(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await No(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let n=Nn(e),i={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await xt(this.checkpointPath,i),await xt(this.manifestPath,r)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await xt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=Nn(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await xt(tt(this.memoryDir,n),i),e.manifest.checkpoint={file:n,sequence:i.sequence,hash:t},await xt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!_t(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let i=n.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Vi(r)},c=ac(n.bundle,e,t.committedAt),d=wt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let u=`${String(i).padStart(12,"0")}-${t.transactionId}.json`;return await xt(tt(this.journalDir,u),s),n.manifest.head={sequence:i,hash:s.hash},n.manifest.updatedAt=t.committedAt,await xt(this.manifestPath,n.manifest),{bundle:c,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...sc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Dn(this.manifestPath),t=await Dn(tt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==Nn(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await ic(this.journalDir),i=n.filter(T=>T.endsWith(".tmp")),s=n.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>t.sequence),c=structuredClone(t.bundle),d=t.sequence,u=t.journalHash??null,I=new Set;for(let T of s){let P=await Dn(tt(this.journalDir,T)),{hash:x,...p}=P;if(x!==Vi(p))throw new Error(`Journal hash mismatch: ${T}`);if(P.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(P.previousHash!==u)throw new Error(`Journal chain mismatch at ${T}`);if(P.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(I.has(P.transactionId))throw new Error(`Duplicate transaction ID: ${P.transactionId}`);Ki(c,P.mutation,P.committedAt),d=P.sequence,u=P.hash,I.add(P.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==u)throw new Error("Journal manifest head hash mismatch.");let k=wt(c);if(!k.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(k.issues)}`);return{bundle:c,manifest:e,transactionIds:I,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:u}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Hi(this.memoryDir,{recursive:!0});let t;try{t=await Do(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;let i=await Dn(this.lockPath).catch(()=>({})),r=!0;if(typeof i.pid=="number")try{process.kill(i.pid,0)}catch(s){r=s.code!=="ESRCH"}if(r)throw new Error("Memory journal is locked by another writer.");await Jo(this.lockPath),t=await Do(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Jo(this.lockPath).catch(()=>{})}}};import{randomBytes as cc}from"crypto";function Ie(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=cc(10).toString("hex"),i=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${i}${n.slice(4,7)}-${n.slice(7,19)}`}var dc=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Qi(o,e){let t=o.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),n=o.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=dc(),u=d.records,I=o.records.find(h=>h.recordType==="thread"&&h.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));I||(I={id:ie(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(h=>h.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},u.push(I));let k=[];for(let h of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"element",label:h,aliases:[],locators:[{id:ie(i,"live-locator",h,e.createdAt),kind:"dom_selector",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),k.push(j)}for(let h of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.kind==="source_file"&&g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-file-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"file",label:h,aliases:[],locators:[{id:ie(i,"live-file-locator",h,e.createdAt),kind:"source_file",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),k.push(j)}let T=(e.semanticCandidates??[]).filter(h=>h.claim.trim()),P;if(T.length>0){P=ie(i,"live-observation",r,e.createdAt);let h={id:P,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:k.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};u.push(h)}let x=ie(i,"live-iteration",r,e.completedAt),p={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:imprint-evidence"})),...P?[{kind:"record",id:P}]:[]],recordType:"iteration",threadIds:[I.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};u.push(p);let l=[],f=e.resolutions.filter(h=>h.status==="resolved"&&h.summary.trim()),m=k.length>0?k:o.records.filter(h=>h.recordType==="subject"&&h.subjectType==="project").slice(0,1);if(T.length>0&&m.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[h,j]of T.entries()){let b=ie(i,"live-proposal",`${r}:${h}`,e.completedAt),g=m.map(E=>({subjectId:E.id,role:"governed"})),B={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:x},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:j.claim.trim(),rationale:j.rationale?.trim()||void 0,proposedKind:j.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:j.sourceText?.trim()||e.requestSummary,iterationId:x,inferredById:n.id}};u.push(B),l.push(b)}if(f.length>0){let h=new Set(e.governingDecisionIds??[]),j=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&h.has(g.id)),b={id:ie(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:x}],recordType:"implementation_attempt",state:"completed",iterationIds:[x],coverageClaims:j.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(B=>B.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:x}]})),summary:f.map(g=>g.summary).join(" "),artifactIds:[]};u.push(b)}return{mutation:d,iterationId:x,proposalIds:l,observationId:P}}import{createHash as lc}from"crypto";import{mkdir as pc,open as uc,readFile as mc,rename as fc,unlink as hc}from"fs/promises";import{join as Xi}from"path";function Yi(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Zi(o){return lc("sha256").update(JSON.stringify(o)).digest("hex")}async function gc(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await uc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
156
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await fc(t,o)}catch(i){throw await hc(t).catch(()=>{}),i}}function yc(o,e,t=new Date().toISOString()){let n={},i={},r={},s=(d,u,I)=>{let k=d[u]??=[];k.includes(I)||k.push(I)};for(let d of o.records)if(d.recordType==="subject"){let u=d;for(let I of[u.label,...u.aliases,...u.locators.filter(k=>k.status==="current").map(k=>k.value)]){let k=Yi(I);k&&s(n,k,u.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let u of d.subjects)s(i,u.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let u of d.subjects)s(r,u.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:Zi(c)}}function er(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[Yi(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>o.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>o.proposalIdsBySubject[n]??[]))]}}var Bn=class{constructor(e){this.indexDir=Xi(e,".popmelt","memory","indexes"),this.indexPath=Xi(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let i=JSON.parse(await mc(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===t.sequence&&i.journalHead.hash===t.hash&&r===Zi(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let n=yc(e,t);return await pc(this.indexDir,{recursive:!0}),await gc(this.indexPath,n),n}};var nn="popmelt:imprint",or="popmelt:imprint-evidence",Dt="popmelt:imprint-relation";function Ln(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===nn)?.id}function Bo(o){let e=new Set;return o.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function qn(o,e){if(!o)return[];let t=new Set(o.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return o.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function Lo(o){if(o==="expresses")return"operationalizes";if(o==="excepts")return"excepts"}var Fn=class{constructor(e){this.projectRoot=e;this.store=new Jn(e),this.indexStore=new Bn(e),this.manifestPath=Ot(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await tn(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let i=await this.store.load();return i.report.recoveredTransactions>0&&(i=await this.store.recover()),await this.refreshIndex(i),await this.status()}let n=await en({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(n.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await en({...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=Ot(this.projectRoot,".popmelt","memory","migrations"),t=Ot(e,"imprint-advisories-v2.json");try{let h=JSON.parse(await tn(t,"utf8"));return{migrated:!1,explanations:h.explanations??0,evidence:h.evidence??0}}catch{}let n;try{n=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await tr(e,{recursive:!0}),await nr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),c=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active")??r,d=i.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let u=i.bundle.manifest.projectId,I=new Set(i.bundle.records.map(h=>h.id)),k=new Set(i.bundle.relationships.flatMap(h=>h.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Dt?[j.id]:[]))),T=new Map,P=i.bundle.records.filter(h=>h.recordType==="advisory_explanation");for(let h of n.explanations){let j=P.find(b=>Ln(b)===h.id);T.set(h.id,j?.id??ie(u,"imprint-explanation",h.id,Date.parse(h.createdAt)))}let x=[],p=[],l=[],f=0;for(let h of n.explanations){let j=T.get(h.id),b=P.find(R=>R.id===j),g=[],B=h.evidence.length?h.evidence:[{id:`fallback:${h.id}`,kind:"observation",stance:"supports",summary:h.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:h.createdAt}];for(let R of B){let N=ie(u,"imprint-evidence-record",R.id,Date.parse(R.createdAt));g.push(N),!I.has(N)&&(x.push({id:N,schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:Bo([{kind:"external",id:R.id,uri:or},{kind:"external",id:h.id,uri:nn},{kind:"thread",id:R.threadId},{kind:"message",id:R.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(R.kind)?"user_feedback":"judgment",summary:R.summary,availability:"available",artifactIds:[]}),l.push({id:ie(u,"imprint-evidence-link",`${h.id}:${R.id}`,Date.parse(R.createdAt)),schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:R.id,uri:or}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:N},reason:"This advisory explanation was derived from collaboration evidence."}),f+=1)}let E={id:j,schemaVersion:1,projectId:u,createdAt:b?.createdAt??h.createdAt,participantId:b?.participantId??c.id,sourceRefs:Bo([...b?.sourceRefs??[],{kind:"external",id:h.id,uri:nn}]),recordType:"advisory_explanation",kind:h.kind,state:h.state,statement:h.statement,rationale:h.rationale,scope:structuredClone(h.scope),subjectIds:[d.id],evidenceIds:[...new Set([...b?.evidenceIds??[],...g])],concreteBindings:qn(n,h.id),supersededById:h.supersededBy?T.get(h.supersededBy):void 0,updatedAt:h.updatedAt};b?p.push(E):x.push(E)}for(let h of n.relations){let j=Lo(h.type);if(!j)continue;let b=T.get(h.fromId),g=T.get(h.toId);!b||!g||k.has(h.id)||l.push({id:ie(u,"imprint-relation",h.id,Date.parse(h.createdAt)),schemaVersion:1,projectId:u,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:Dt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:b},to:{entityType:"advisory_explanation",entityId:g},reason:h.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(x.length||p.length||l.length)try{let h=await this.store.commit({records:x,recordReplacements:p,events:[],relationships:l,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ie(u,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:m});await this.refreshIndex(h)}catch(h){if(!(h instanceof Error)||!h.message.includes("Transaction already exists"))throw h}return await tr(e,{recursive:!0}),await nr(t,JSON.stringify({version:2,migratedAt:m,explanations:n.explanations.length,evidence:f,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:f}}async review(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,selection:_o(n.bundle,i)}}async contextualize(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:qi(n.bundle,i),reviewSelection:_o(n.bundle,i)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:On(n.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let t=await en({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),i=On(n.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=t.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!n||n.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:n.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:Ie(r),decisionId:Ie(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:Ie(r),replacementProposalId:Ie(r),acceptanceEventId:Ie(r),decisionId:Ie(r),relationshipId:Ie(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:Ie(r),reason:e.reason}:{...c,action:"defer",eventId:Ie(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},u=On(t.bundle,d);if(!u.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:u.errors.map(T=>T.message).join(" ")};let I=await this.store.commitReviewPlan(u.plan,{transactionId:Ie(r),committedAt:s});await this.refreshIndex(I);let k=u.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:k,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:I.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=Qi(t.bundle,e),i=ie(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active"),s=e.action?i:r??i,c=n.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),u=Date.parse(d),I=n.bundle.manifest.projectId,k=[],T=[],P=[],x=n.bundle.records.filter(m=>m.recordType==="advisory_explanation"),p=new Map(x.flatMap(m=>{let h=Ln(m);return h?[[h,m.id]]:[]}));for(let m of e.summary.changes)if(!p.has(m.explanationId)){let h=t?.explanations.find(j=>j.id===m.explanationId);p.set(m.explanationId,ie(I,"imprint-explanation",m.explanationId,Date.parse(h?.createdAt??d)))}for(let m of e.summary.changes){let h={kind:"external",id:m.explanationId,uri:nn},j=p.get(m.explanationId),b=x.find(R=>R.id===j),g=t?.explanations.find(R=>R.id===m.explanationId),B={id:ie(I,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};k.push(B);let E={id:j,schemaVersion:1,projectId:I,createdAt:b?.createdAt??g?.createdAt??d,participantId:b?.participantId??s.id,sourceRefs:Bo([...b?.sourceRefs??[],h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??b?.kind??"pattern",state:g?.state??m.state,statement:g?.statement??m.statement,rationale:g?.rationale??b?.rationale??e.summary.detail,scope:structuredClone(g?.scope??b?.scope??{kind:"project",values:[]}),subjectIds:b?.subjectIds??[c.id],evidenceIds:[...new Set([...b?.evidenceIds??[],B.id])],concreteBindings:g?qn(t,m.explanationId):b?.concreteBindings??[],supersededById:g?.supersededBy?p.get(g.supersededBy):b?.supersededById,updatedAt:g?.updatedAt??d};b?T.push(E):k.push(E),P.push({id:ie(I,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E.id},to:{entityType:"evidence",entityId:B.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let l=new Set(n.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(h=>h.kind==="external"&&h.uri===Dt?[h.id]:[])));for(let m of t?.relations??[]){let h=Lo(m.type);if(!h)continue;let j=p.get(m.fromId),b=p.get(m.toId);!j||!b||l.has(m.id)||P.push({id:ie(I,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:I,createdAt:m.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:m.id,uri:Dt}],recordType:"relationship",relationshipType:h,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:b},reason:m.rationale||"The Imprint graph connected these explanations."})}let f=ie(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,u);try{let m=await this.store.commit({records:k,recordReplacements:T,events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:f,committedAt:d});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=bt(JSON.parse(await tn(Ot(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),r=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=t.bundle.manifest.projectId,d=t.bundle.records.filter(g=>g.recordType==="advisory_explanation"),u=new Map(d.flatMap(g=>{let B=Ln(g);return B?[[B,g]]:[]})),I=new Map([...[...u].map(([g,B])=>[g,B.id]),...e.explanations.filter(g=>!u.has(g.id)).map(g=>[g.id,ie(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),k=[],T=[],P=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let B=u.get(g.id);if(!B){k.push({id:I.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:nn}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:qn(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let E={...structuredClone(B),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:qn(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt},R=N=>JSON.stringify({kind:N.kind,state:N.state,statement:N.statement,rationale:N.rationale,scope:N.scope,concreteBindings:N.concreteBindings,supersededById:N.supersededById,updatedAt:N.updatedAt});R(B)!==R(E)&&T.push(E)}for(let[g,B]of u)P.has(g)||B.state==="retired"||T.push({...structuredClone(B),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let x=new Set(t.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),p=new Map(t.bundle.relationships.flatMap(g=>{if(x.has(g.id))return[];let B=g.sourceRefs.find(E=>E.kind==="external"&&E.uri===Dt)?.id;return B?[[B,g]]:[]})),l=[],f=new Set;for(let g of e.relations){let B=Lo(g.type);if(!B)continue;let E=I.get(g.fromId),R=I.get(g.toId);if(!E||!R)continue;let N=p.get(g.id);N&&N.relationshipType===B&&N.from.entityType==="advisory_explanation"&&N.from.entityId===E&&N.to.entityType==="advisory_explanation"&&N.to.entityId===R||(N&&f.add(g.id),l.push({id:ie(c,"imprint-relation",`${g.id}:${B}:${E}:${R}`,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Dt}],recordType:"relationship",relationshipType:B,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:R},reason:g.rationale||"The Imprint graph connected these explanations."}))}let m=new Set(e.relations.map(g=>g.id)),h=n?[...p].filter(([g])=>!m.has(g)||f.has(g)).map(([,g])=>({id:ie(c,"imprint-relationship-tombstone",g.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:g.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!k.length&&!T.length&&!l.length&&!h.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let j=e.updatedAt,b=ie(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let g=await this.store.commit({records:k,recordReplacements:T,events:[],relationships:l,artifacts:[],tombstones:h,projectionUpdates:[]},{transactionId:b,committedAt:j});return await this.refreshIndex(g),{status:"synced",relationships:l.length+h.length,explanations:k.length+T.length,headSequence:g.report.headSequence}}catch(g){if(!(g instanceof Error)||!g.message.includes("Transaction already exists"))throw g;return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let n={};for(let i of t.bundle.records)n[i.recordType]=(n[i.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:t.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!i.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),n=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>t.has(r))&&n.set(i.key,i);return[...n.values()]}async getImprintView(e=[],t){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let i=await this.store.load(),r=i.bundle.records.filter(l=>l.recordType==="advisory_explanation"),s=new Map(r.map(l=>[l.id,l])),c=new Map(r.flatMap(l=>{let f=Ln(l);return f?[[f,l.id]]:[]})),d=new Set(e.map(l=>c.get(l)??l)),u=new Map(i.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),I=new Map(i.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),k=new Set(i.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),T=new Set(["operationalizes","excepts"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=r.map(l=>{let f=l.evidenceIds.flatMap(b=>{let g=I.get(b);if(!g)return[];let B=g.sourceRefs.find(V=>V.kind==="thread")?.id,E=g.sourceRefs.find(V=>V.kind==="message")?.id,R=g.kind==="judgment"||g.kind==="user_feedback"||g.kind==="project_state"?g.kind:"other",N=u.get(g.participantId)??"unknown";return[{id:g.id,kind:R,summary:g.summary,createdAt:g.createdAt,participantKind:N,threadId:B,jobId:E}]}).sort((b,g)=>g.createdAt.localeCompare(b.createdAt)),m=i.bundle.relationships.flatMap(b=>{if(k.has(b.id))return[];if(!T.has(b.relationshipType))return[];let g=b.from.entityType==="advisory_explanation"&&b.from.entityId===l.id&&b.to.entityType==="advisory_explanation",B=b.to.entityType==="advisory_explanation"&&b.to.entityId===l.id&&b.from.entityType==="advisory_explanation";if(!g&&!B)return[];let E=g?b.to.entityId:b.from.entityId,R=s.get(E);return R?[{id:b.id,type:b.relationshipType==="operationalizes"?"expresses":"excepts",direction:g?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:b.reason}]:[]}),h=[...(l.supersededById?[l.supersededById]:[]).flatMap(b=>{let g=s.get(b);return g?[{id:`supersedes:${l.id}:${g.id}`,type:"supersedes",direction:"incoming",explanationId:g.id,statement:g.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(b=>b.supersededById===l.id?[{id:`supersedes:${b.id}:${l.id}`,type:"supersedes",direction:"outgoing",explanationId:b.id,statement:b.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...l.sourceRefs.flatMap(b=>b.kind==="thread"?[b.id]:[]),...f.flatMap(b=>b.threadId?[b.threadId]:[])])].filter(b=>!t||t.has(b));return{id:l.id,kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),createdAt:l.createdAt,updatedAt:l.updatedAt,evidenceCount:f.length,recentEvidence:f.slice(0,4),concrete:l.concreteBindings.map(b=>({...structuredClone(b)})),relations:[...m,...h],sourceThreadIds:j,needsGrounding:l.state==="testing"&&d.has(l.id)}}).sort((l,f)=>Number(f.needsGrounding)-Number(l.needsGrounding)||P[l.state]-P[f.state]||f.updatedAt.localeCompare(l.updatedAt)),p={total:x.filter(l=>l.state!=="retired").length,emerging:x.filter(l=>l.state==="emerging").length,testing:x.filter(l=>l.state==="testing").length,grounded:x.filter(l=>l.state==="grounded").length,challenged:x.filter(l=>l.state==="challenged").length,retired:x.filter(l=>l.state==="retired").length,needsGrounding:x.filter(l=>l.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:p,explanations:x}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),n=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,u)=>d.createdAt.localeCompare(u.createdAt)))c.decisionIds.some(d=>t.has(d))&&n.set(c.key,c);let i=[...n.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(u=>u.targets.some(I=>I.entityType==="decision"&&I.entityId===c.id)).sort((u,I)=>I.createdAt.localeCompare(u.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(u=>u.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),n=t.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=t.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!n||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=Ie(r),d=Ie(r),u=Ie(r),I=Ie(r),k=Ie(r),T=new Set(t.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),P=t.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&T.has(R.id)),x={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:i.id,role:"governed"}],l={...x,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},f={...x,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},m={...x,id:u,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},h={...x,id:I,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[u],value:e.value},j={...x,id:k,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[u],entryIds:[I],coverage:[{decisionId:u,status:"projected"}]},b={...x,id:Ie(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:I},to:{entityType:"decision",entityId:u},reason:"The model change is projected from the owner-confirmed decision."},g=P.map(R=>({...x,id:Ie(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:R.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),B=P.map(R=>({...x,id:Ie(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:m.id},to:{entityType:"decision",entityId:R.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),E=await this.store.commit({records:[l,m,h,j],events:[f,...g],relationships:[b,...B],artifacts:[],tombstones:[],projectionUpdates:P.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:Ie(r),committedAt:s});return await this.refreshIndex(E),{decisionId:u,entryId:I}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),n=t.bundle.records.find(x=>x.recordType==="model_projection"&&x.state==="applied"&&x.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let i=t.bundle.records.filter(x=>x.recordType==="decision"&&e.decisionIds.includes(x.id)&&x.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=Ie(s),u=e.changes.map(x=>{let p=x.decisionIds?.filter(m=>e.decisionIds.includes(m)),l=p?.length?p:e.decisionIds,f=[...new Set(i.filter(m=>l.includes(m.id)).flatMap(m=>m.subjects.map(h=>h.subjectId)))];return{id:Ie(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:l.map(m=>({kind:"record",id:m})),recordType:"model_entry",key:x.path.map(String).join("."),subjectIds:f,decisionIds:l,value:x.value}}),I=new Set(u.flatMap(x=>x.decisionIds)),k={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(x=>({kind:"record",id:x})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:u.map(x=>x.id),coverage:e.decisionIds.map(x=>e.coverage?.find(p=>p.decisionId===x)??{decisionId:x,status:I.has(x)?"projected":"unprojected"})},T=u.flatMap(x=>x.decisionIds.map(p=>({id:Ie(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:k.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),P=await this.store.commit({records:[...u,k],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:Ie(s),committedAt:c});return await this.refreshIndex(P),{projectionId:d,entryIds:u.map(x=>x.id),headSequence:P.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await en({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=er(n,t.subjectHints??[]);return i?{...t,subjectIds:[...new Set([...t.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Jt(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Te(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Nt(o,e,t){let n=Te(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function qo(o){let e=Jt(o),t=Jt(e.authority),n=t.level,i=t.mode,r=Nt(n,"authority.level",["owner","delegate","contributor"]),s=Nt(i,"authority.mode",["local_trusted","hosted"]),c={proposalId:Te(e.proposalId,"proposalId"),participantId:Te(e.participantId,"participantId"),occurredAt:Te(e.occurredAt,"occurredAt"),authority:{level:r,mode:s,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:Nt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Te(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Te(e.eventId,"eventId"),reason:Te(e.reason,"reason")};case"defer":{let d=Jt(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,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(u=>Te(u,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(u=>Nt(u,"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{...c,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:Nt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let u=Jt(d);return{subjectId:Te(u.subjectId,"subjectId"),role:Nt(u.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 Fo(o){let e=Jt(o),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Te(c,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Jt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function Bt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
157
|
+
`)}async function ir(o,e,t,n){let i=Bt(e);if(!(!i&&t.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:t,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.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(u=>u.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){n?.(r);return}}function rr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((n,i)=>["",`${i+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((n,i)=>["",`${i+1}. ${n.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
158
|
+
`)}function sr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]);if(typeof t.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(t.action)))return null;let n=t.action,i=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!i||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:t.proposalId,action:n,kind:i,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function ar(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),n=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!n||typeof t.proposalId!="string"||!t.proposalId||typeof t.title!="string"||!t.title.trim()||typeof t.claim!="string"||!t.claim.trim()||typeof t.rationale!="string"||!t.rationale.trim()?null:{proposalId:t.proposalId,kind:n,title:t.title.trim(),claim:t.claim.trim(),rationale:t.rationale.trim(),scope:typeof t.scope=="string"&&t.scope.trim()?t.scope.trim():void 0}}catch{return null}}async function Uo(o){let t=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],i=await vc(o),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),c,d,u,I,k,T,P,x,p,l,f,m,h,j,b=[],g=[],B=0,E=[];for(;B<i.length;){let R=i.indexOf(r,B);if(R===-1)break;let N=R+r.length;if(i.slice(R,R+s.length).equals(s))break;let V=N;i[V]===13&&i[V+1]===10&&(V+=2);let K=i.indexOf(`\r
|
|
156
159
|
\r
|
|
157
|
-
`,V);if(K===-1)break;let G=
|
|
160
|
+
`,V);if(K===-1)break;let G=i.slice(V,K).toString("utf-8"),Q=K+4,w=i.indexOf(r,Q),H=w!==-1?w-2:i.length;E.push({headers:G,body:i.slice(Q,H)}),B=w!==-1?w:i.length}for(let R of E){let N=R.headers.match(/name="([^"]+)"/);if(!N)continue;let V=N[1];if(V==="screenshot")c=R.body;else if(V==="feedback")d=R.body.toString("utf-8");else if(V==="color")u=R.body.toString("utf-8");else if(V==="provider")I=R.body.toString("utf-8");else if(V==="model")k=R.body.toString("utf-8");else if(V==="reasoningEffort")T=R.body.toString("utf-8");else if(V==="serviceTier")P=R.body.toString("utf-8");else if(V==="goal")x=R.body.toString("utf-8");else if(V==="pageUrl")p=R.body.toString("utf-8");else if(V==="viewport")l=R.body.toString("utf-8");else if(V==="planId")f=R.body.toString("utf-8");else if(V==="manifest")m=R.body.toString("utf-8");else if(V==="tasks")h=R.body.toString("utf-8");else if(V==="sourceId")j=R.body.toString("utf-8");else if(V.startsWith("screenshot-")){let K=V.slice(11);try{let G=decodeURIComponent(K);g.push({pathname:G,data:R.body})}catch{}}else if(V.startsWith("image-")){let K=V.split("-"),G=parseInt(K[K.length-1],10),Q=K.slice(1,-1).join("-");Q&&!isNaN(G)&&b.push({annotationId:Q,index:G,data:R.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:u,provider:I,model:k,reasoningEffort:T,serviceTier:P,goal:x,pageUrl:p,viewport:l,planId:f,manifest:m,tasks:h,sourceId:j,pastedImages:b,pageScreenshots:g}}function vc(o){return new Promise((e,t)=>{let n=[];o.on("data",i=>n.push(i)),o.on("end",()=>e(Buffer.concat(n))),o.on("error",t)})}import{randomUUID as Ic}from"crypto";var on="<orientation>",nt="</orientation>";function zo(o,e){let t=e;for(;t<o.length&&/\s/.test(o[t]);)t++;if(t>=o.length)return{status:"incomplete",start:t};if(o[t]!=="{")return{status:"invalid",start:t};let n=0,i=!1,r=!1;for(let s=t;s<o.length;s++){let c=o[s];if(i){r?r=!1:c==="\\"?r=!0:c==='"'&&(i=!1);continue}if(c==='"')i=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function cr(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function dr(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(on,t);if(n<0){cr(e,o.slice(t));break}cr(e,o.slice(t,n));let i=n+on.length,r=zo(o,i);if(r.status!=="complete"){let c=o.indexOf(nt,i);if(c>=0){t=c+nt.length;continue}t=i;continue}e.push({kind:"orientation",json:o.slice(r.start,r.end)}),t=r.end;let s=t;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(nt,s)&&(t=s+nt.length)}return e}var wc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),bc=new Set(["strengthened","weakened","mixed","unknown"]);function rn(o,e=180){if(typeof o!="string")return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function xc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function lr(o,e,t,n=Date.now()){let i=xc(o);if(!i)return null;let r=typeof i.transition=="string"&&wc.has(i.transition)?i.transition:null,s=rn(i.focus);if(!r||!s)return null;let c=typeof i.evidencePosture=="string"&&bc.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:Ic(),jobId:e,sequence:t,timestamp:n,transition:r,snapshot:{focus:s,seeking:rn(i.seeking),workingHypothesis:rn(i.workingHypothesis),evidencePosture:c,update:rn(i.update),nextObservation:rn(i.nextObservation)},contextPolicy:"exclude"}}function Wo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Go(o,e,t=0){let n=[],i=[],r=new Set,s=t;for(let d of dr(o)){if(d.kind==="text"){d.text&&i.push(d);continue}try{let u=lr(JSON.parse(d.json),e,s);if(!u)continue;let I=Wo(u);if(r.has(I))continue;r.add(I),n.push(u),i.push({kind:"orientation",orientation:u}),s++}catch{}}return{visibleText:i.map(d=>d.kind==="text"?d.text:`
|
|
158
161
|
|
|
159
162
|
`).join("").replace(/\n{3,}/g,`
|
|
160
163
|
|
|
161
|
-
`).trim(),orientations:n,segments:
|
|
164
|
+
`).trim(),orientations:n,segments:i}}function Sc(o){let e="<orientation>",t=Math.min(o.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(o.slice(-n)))return n;return 0}var Un=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let u=this.buffer.slice(d);if(nt.startsWith(u)&&u.length<nt.length||(u.startsWith(nt)&&(this.buffer=this.buffer.slice(d+nt.length)),this.optionalClosePending=!1,!this.buffer))break}let i=this.buffer.indexOf(on);if(i<0){let d=Sc(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,i);let r=i+on.length,s=zo(this.buffer,r);if(s.status==="incomplete"){this.buffer=this.buffer.slice(i);break}if(s.status==="invalid"){this.buffer=this.buffer.slice(r);continue}let c=this.buffer.slice(s.start,s.end);this.buffer=this.buffer.slice(s.end),this.optionalClosePending=!0;try{let d=lr(JSON.parse(c),this.jobId,this.sequence);if(!d)continue;let u=Wo(d);if(this.signatures.has(u))continue;this.signatures.add(u),n.push(d),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=Go(e,this.jobId,this.sequence),n=t.orientations.filter(i=>{let r=Wo(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},pr=`## Public orientation updates
|
|
162
165
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
163
166
|
<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>
|
|
164
167
|
|
|
165
168
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
166
169
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
167
170
|
|
|
168
|
-
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.`;function sn(
|
|
169
|
-
### ${
|
|
170
|
-
`)}function ur(
|
|
171
|
-
`)}function mr(
|
|
172
|
-
`)}function
|
|
173
|
-
`)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let
|
|
174
|
-
`));return Gn([...Wn,...d])}function zn(
|
|
175
|
-
`,"utf8"),await n.sync()}finally{await n.close()}try{await Fc(t,i)}catch(o){throw await qc(t).catch(()=>{}),o}}function zc(i,e){return{version:1,projectId:i,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Wc(i,e){let t=i.explanations.findIndex(n=>n.id===e.id);t>=0?i.explanations[t]=Ce(e):i.explanations.push(Ce(e))}function Hi(i,e){let t=Ce(i);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(o=>o.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(Ce(n.explanation))}else if(n.op==="replace_explanation")Wc(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(o=>o.id!==n.explanationId),t.relations=t.relations.filter(o=>o.fromId!==n.explanationId&&o.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(o=>o.id===n.concrete.id)||t.concrete.push(Ce(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(o=>o.id!==n.concreteId),t.relations=t.relations.filter(o=>o.fromId!==n.concreteId&&o.toId!==n.concreteId);else if(n.op==="add_evidence"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);o.evidence.some(r=>r.id===n.evidence.id)||(o.evidence.push(Ce(n.evidence)),o.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let o=t.explanations.find(r=>r.id===n.explanationId);if(!o)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(o,Ce(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let o=n.relation,r=t.explanations.find(p=>p.id===o.fromId),s=t.explanations.find(p=>p.id===o.toId),c=t.concrete.some(p=>p.id===o.fromId),d=t.concrete.some(p=>p.id===o.toId);if(Wo(o.type)){if(!(o.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${o.type} relation has invalid endpoints: ${o.id}`);if(t.relations.some(x=>x.type===o.type&&x.fromId===o.fromId&&x.toId===o.toId))throw new Error(`Duplicate imprint relation: ${o.type}:${o.fromId}:${o.toId}`);if(o.type==="expresses"&&r&&s){if(Ct(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${o.id}`);let x=new Map;for(let P of t.relations)P.type==="expresses"&&x.set(P.fromId,[...x.get(P.fromId)??[],P.toId]);let T=[o.toId],k=new Set;for(;T.length;){let P=T.pop();if(P===o.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${o.id}`);k.has(P)||(k.add(P),T.push(...x.get(P)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${o.id}`);t.relations.some(p=>p.id===o.id)||t.relations.push(Ce(o))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(o=>o.id!==n.relationId));return t}function Gc(i,e){let t=[],n=Ce(i);for(let o of e){if(o.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:o.explanation.id});else if(o.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===o.explanationId);r&&t.unshift({op:"add_explanation",explanation:Ce(r)})}else if(o.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:o.concrete.id});else if(o.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===o.concreteId);r&&t.unshift({op:"add_concrete",concrete:Ce(r)})}else if(o.op==="replace_explanation"||o.op==="revise_explanation"||o.op==="add_evidence"){let r=o.op==="replace_explanation"?o.explanation.id:o.explanationId,s=n.explanations.find(c=>c.id===r);s&&t.unshift({op:"replace_explanation",explanation:Ce(s)})}else if(o.op==="add_relation")t.unshift({op:"remove_relation",relationId:o.relation.id});else if(o.op==="remove_relation"){let r=n.relations.find(s=>s.id===o.relationId);r&&t.unshift({op:"add_relation",relation:Ce(r)})}n=Hi(n,[o])}return t}function Tr(i){return i.op==="add_explanation"||i.op==="replace_explanation"?[i.explanation.id]:i.op==="remove_explanation"||i.op==="add_evidence"||i.op==="revise_explanation"?[i.explanationId]:i.op==="add_relation"?[i.relation.fromId,i.relation.toId]:[]}var Vn=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Lt(e,".popmelt","imprint"),this.manifestPath=Lt(this.imprintDir,"manifest.json"),this.graphPath=Lt(this.imprintDir,"graph.json"),this.journalDir=Lt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Sr(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),n=(await Lc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),o=zc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<n.length;c++){let d=JSON.parse(await Sr(Lt(this.journalDir,n[c]),"utf8")),{hash:p,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||p!==kr(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);o=Hi(o,d.mutations),o.updatedAt=d.committedAt,o.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:o,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:bt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=bt(t.graph),o=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let c=o.get(s.id);c&&c.type===s.type&&c.fromId===s.fromId&&c.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),c&&r.push({op:"add_relation",relation:c}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await St(this.graphPath,n),await St(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(T=>T.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let o=n.graph.head.sequence+1,r=Gc(n.graph,e.mutations),s={version:1,sequence:o,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:Ce(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:kr(s)},d=Hi(n.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:o,hash:c.hash};let p=`${String(o).padStart(12,"0")}-${e.transactionId}.json`;await St(Lt(this.journalDir,p),c);let x={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await St(this.graphPath,d),await St(this.manifestPath,x),t={graph:d,transaction:c}}),await this.writeChain,t}async undo(e,t,n,o){let r=await this.load(),s=r.transactions.find(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(Tr));if(r.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(x=>Tr(x).some(T=>c.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:o,committedAt:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await St(this.graphPath,e.graph),await St(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Hc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Vc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]),Kc=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Ki(i){return!!(i&&Kc.test(i))}function Qc(i){return i.scope.kind==="project"||Ki(`${i.statement} ${i.rationale}`)}function Xc(i){let e=i?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function Yc(i){return i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Kn(i){return new Set(Yc(i).split(" ").filter(e=>e.length>2&&!Vc.has(e)))}function Qn(i,e){if(!i.size||!e.size)return 0;let t=0;for(let n of i)e.has(n)&&(t+=1);return t/Math.min(i.size,e.size)}function Vi(i){return!i||!Array.isArray(i.values)||i.values.length===0?{kind:"project",values:["*"]}:{kind:i.kind,values:[...new Set(i.values.map(e=>e.trim()).filter(Boolean))]}}function ot(i,e,t){return{id:rt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:i.threadId,jobId:i.jobId,createdAt:i.occurredAt??new Date().toISOString()}}function ve(i,e=800){return typeof i=="string"?i.trim().slice(0,e):""}function Rr(i){if(!i||typeof i!="object"||Array.isArray(i))return;let e=i;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Pr(i,e){if(!i||!e.trim())return{found:!1};let t=i;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let o=Number(n);if(!Number.isInteger(o)||o<0||o>=t.length)return{found:!1};t=t[o]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Qi(i,e={}){let t=[...i.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=i.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),o=t.at(-1)?.[1],r,s=[];if(o)r=o;else{let d=[...i.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let p=JSON.parse(d);if(!p||typeof p!="object"||Array.isArray(p)||!Object.prototype.hasOwnProperty.call(p,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let x=p;r=x.imprint,s=Array.isArray(x.annotations)?x.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("imprint assessment is invalid");if(c.decision==="none"){let f=String(c.reason);if(!Hc.has(f))throw new Error("imprint no-op reason is invalid");if(f==="task_specific_detail"&&s.some(h=>{if(!h||typeof h!="object"||Array.isArray(h))return!1;let u=h;return(u.finalScope??u.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let l=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(h=>typeof h=="string"&&!!h.trim()):[];if(l.length){let h=l,u=new Set(e.context?.explanations.map(b=>b.id)??[]),m=new Set(e.context?.pendingGroundingExplanationIds??[]),j=h.filter(b=>{let g=e.context?.explanations.find(B=>B.id===b);return u.has(b)&&g&&(g.state==="emerging"||g.state==="testing")&&!m.has(b)});if(j.length){let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0],B=ve(b?.question,300);return{draft:{decision:"apply",summary:{title:ve(c.summary?.title,120)||"Applied shared understanding",detail:ve(c.summary?.detail,500)||ve(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:j,grounding:{explanationId:g,question:B||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(f==="duplicate"){let h=ve(c.duplicateOfExplanationId,100),u=c.scopeComparison;if(!h)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(u!=="equivalent"&&u!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let m=e.context?.explanations.find(j=>j.id===h);if(!m)throw new Error("duplicate assessment must cite a surfaced explanation");if(Ki(e.requestText)&&!Qc(m))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:h,scopeComparison:u},visibleText:n}}return{draft:{decision:"none",reason:f},visibleText:n}}if(c.decision==="recognize"){let f=ve(c.explanationId,100);if(!f)throw new Error("recognition requires explanationId");let l=e.context?.explanations.find(m=>m.id===f);if(!l)throw new Error("recognition must cite a surfaced explanation");if(l.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let h=c.summary,u={title:ve(h?.title,120),detail:ve(h?.detail,500)};if(!u.title||!u.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:f,summary:u},visibleText:n}}if(c.decision==="apply"){let f=c.summary,l={title:ve(f?.title,120),detail:ve(f?.detail,500)};if(!l.title||!l.detail)throw new Error("application summary title and detail are required");let h=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(B=>typeof B=="string"&&!!B.trim()):[];if(!h.length)throw new Error("application requires appliedExplanationIds");let u=new Map(e.context?.explanations.map(B=>[B.id,B])??[]),m=new Set(e.context?.pendingGroundingExplanationIds??[]),j=h.filter(B=>{let E=u.get(B);return E&&(E.state==="emerging"||E.state==="testing")&&!m.has(B)});if(!j.length){if(h.every(E=>u.get(E)?.state==="grounded"||m.has(E)))return{draft:{decision:"none",reason:"application_only"},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0];return{draft:{decision:"apply",summary:l,appliedExplanationIds:j,grounding:{explanationId:g,question:ve(b?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(c.decision!==void 0&&c.decision!=="mutate")throw new Error("imprint decision is invalid");let d=c.summary,p=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(p)))throw new Error("summary.kind is invalid");let x={kind:p,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!x.title||!x.detail)throw new Error("summary title and detail are required");let T=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],k=[];for(let f of Array.isArray(c.mutations)?c.mutations:[]){if(!f||typeof f!="object")continue;let l=f;if(l.op==="add"&&["intention","principle","pattern"].includes(String(l.kind))){let h=ve(l.statement),u=ve(l.rationale);if(!h||!u)continue;k.push({op:"add",clientId:ve(l.clientId,100)||void 0,kind:l.kind,statement:h,rationale:u,scope:Rr(l.scope),rootReason:ve(l.rootReason,300)||void 0})}else if(l.op==="revise"&&typeof l.explanationId=="string"){let h={op:"revise",explanationId:l.explanationId,statement:ve(l.statement)||void 0,rationale:ve(l.rationale)||void 0,scope:Rr(l.scope),reopenGrounding:l.reopenGrounding===!0};(h.statement||h.rationale||h.scope||h.reopenGrounding)&&k.push(h)}else if(l.op==="evidence"&&typeof l.explanationId=="string"&&["supports","challenges","excepts"].includes(String(l.stance))){let h=ve(l.summary);h&&k.push({op:"evidence",explanationId:l.explanationId,stance:l.stance,summary:h})}else if(l.op==="relation"&&typeof l.fromId=="string"&&typeof l.toId=="string"&&["expresses","excepts"].includes(String(l.type))){let h=ve(l.rationale);if(!h)continue;k.push({op:"relation",type:l.type,fromId:l.fromId,toId:l.toId,rationale:h})}else if(l.op==="supersede"&&typeof l.explanationId=="string"&&typeof l.replacementId=="string"){let h=ve(l.reason);h&&k.push({op:"supersede",explanationId:l.explanationId,replacementId:l.replacementId,reason:h})}else if(l.op==="bind_concrete"&&typeof l.explanationId=="string"){let h=ve(l.modelPath,300);h&&k.push({op:"bind_concrete",explanationId:l.explanationId,modelPath:h,rationale:ve(l.rationale)})}else l.op==="retire"&&typeof l.explanationId=="string"&&k.push({op:"retire",explanationId:l.explanationId,reason:ve(l.reason)})}let P=c.grounding,v=P&&typeof P.explanationId=="string"&&ve(P.question)?{explanationId:P.explanationId,question:ve(P.question,300)}:void 0;return{draft:{decision:"mutate",summary:x,appliedExplanationIds:T,mutations:k,grounding:v},visibleText:n}}catch(c){return{visibleText:n,error:c instanceof Error?c.message:String(c)}}}function Xi(i,e={}){let t=i?.explanations??[],n=new Set(i?.pendingGroundingExplanationIds??[]),o=Ki(e.requestText);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((r,s)=>[`${s+1}. [${r.state}; ${r.kind}] ${r.statement}`,` - Why: ${r.rationale}`,` - Scope: ${r.scope.kind} ${r.scope.values.join(", ")}`,` - Explanation: ${r.id}`,...n.has(r.id)?[" - Grounding: already pending; do not ask again"]:[],...r.concrete.map(c=>` - Concrete terminal: ${c.modelPath} = ${JSON.stringify(c.value)}`)].join(`
|
|
176
|
-
`)),...i?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...i?.relations?.length?["","Known explanation topology:",...i.relations.map(r=>`- ${r.fromId} --${r.type}--> ${r.toId}: ${r.rationale}`)]:[],"","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.","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.","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, not merely acceptance of completed work.","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. 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.",...o?["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.","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.","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"}',"A no-op reason cannot suppress application evidence. When the completed action semantically matches the top retrieved ungrounded explanation, the bridge records that application regardless of the no-op label. Report decision apply directly so the summary and grounding question are intentional.","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 requires neither appliedExplanationIds nor a mutation. Never claim that a new explanation is grounded."].join(`
|
|
177
|
-
`)}var ln=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Vn(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=Kn(e.text??""),n=Kn((e.subjectHints??[]).join(" ")),o=new Set(e.pendingGroundingExplanationIds??[]);if(!t.size&&!n.size&&!o.size)return;let{graph:r}=await this.store.load(),s=r.explanations.filter(v=>v.state!=="retired"&&v.state!=="challenged").map(v=>{let f=Kn([v.statement,v.rationale].join(" ")),l=Kn(v.scope.values.join(" ")),h=Qn(f,t),u=Qn(l,t),m=Qn(l,n),j=Qn(f,n),b=h+u*.2+m*.25+j*.1+(v.state==="grounded"?.08:0)+(o.has(v.id)?1:0),g=o.has(v.id)||(t.size?h>=.12||u>=.5:m>=.2||j>=.2);return{item:v,score:b,relevant:g}}).filter(v=>v.relevant&&v.score>=.18).sort((v,f)=>f.score-v.score||f.item.updatedAt.localeCompare(v.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:v})=>v),p=new Set(d.map(v=>v.id)),x=new Set(r.relations.flatMap(v=>p.has(v.fromId)?[v.toId]:p.has(v.toId)?[v.fromId]:[])),T=new Set(r.explanations.flatMap(v=>x.has(v.id)&&v.state!=="retired"&&v.state!=="challenged"?[v.id]:[])),k=r.explanations.filter(v=>T.has(v.id)&&!p.has(v.id)).sort((v,f)=>f.updatedAt.localeCompare(v.updatedAt)).slice(0,4),P=[...d,...k];for(let v of k)p.add(v.id);return{explanations:P.map(v=>{let f=new Set(r.relations.filter(l=>l.toId===v.id&&l.type==="expresses").map(l=>l.fromId));return{id:v.id,kind:v.kind,statement:v.statement,rationale:v.rationale,scope:v.scope,state:v.state,concrete:r.concrete.filter(l=>f.has(l.id)).map(l=>({id:l.id,modelPath:l.modelPath,value:l.value}))}}),truncated:s.length>d.length||k.length<T.size,...o.size?{pendingGroundingExplanationIds:[...o]}:{},relations:r.relations.filter(v=>p.has(v.fromId)&&p.has(v.toId)).map(v=>({id:v.id,type:v.type,fromId:v.fromId,toId:v.toId,rationale:v.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],o=t.applicationOccurred?n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...o])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(w=>[w.id,w])),p=new Map,x=new Map,T=[],k=new Set,P=new Set(t.pendingGroundingExplanationIds??[]),v=new Set(n.flatMap(w=>w.op==="revise"&&n.some(H=>H.op==="evidence"&&H.stance==="challenges"&&H.explanationId===w.explanationId)?[w.explanationId]:[])),f=new Set(n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[])),l=w=>d.has(w)||f.has(w),h=new Set;for(let w of n)w.op==="relation"&&w.fromId!==w.toId&&l(w.fromId)&&l(w.toId)?(h.add(w.fromId),h.add(w.toId)):w.op==="supersede"&&w.explanationId!==w.replacementId&&l(w.explanationId)&&l(w.replacementId)?(h.add(w.explanationId),h.add(w.replacementId)):w.op==="bind_concrete"&&l(w.explanationId)&&Pr(t.concreteModel,w.modelPath).found&&h.add(w.explanationId);let u=c.graph.explanations.length===0;for(let w of n){if(w.op!=="add")continue;let H=!!(w.clientId&&h.has(w.clientId)),L=!!w.rootReason?.trim()||u;if(!H&&!L)continue;u&&(u=!1);let O=rt();w.clientId&&p.set(w.clientId,O);let fe=w.clientId?r.includes(w.clientId):!1,J={id:O,kind:w.kind,statement:w.statement,rationale:w.rationale,scope:Vi(w.scope),state:fe?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ot(t,"supports",e.summary.detail)]};d.set(O,J),k.add(O),T.push({op:"add_explanation",explanation:J})}let m=w=>p.get(w)??w;for(let w of n){if(w.op!=="revise")continue;let H=m(w.explanationId),L=d.get(H);if(L?.state!=="grounded")continue;let O=rt(),fe={id:O,kind:L.kind,statement:w.statement??L.statement,rationale:w.rationale??L.rationale,scope:w.scope?Vi(w.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ot(t,"supports",e.summary.detail)]};d.set(O,fe),x.set(H,O),k.add(O),T.push({op:"add_explanation",explanation:fe});let J=Ct(L,fe);J!==0&&T.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:J>0?H:O,toId:J>0?O:H,rationale:w.rationale??e.summary.detail,createdAt:s}})}let j=w=>{let H=m(w);return x.get(H)??H};for(let w of n){if(w.op==="add")continue;if(w.op==="bind_concrete"){let L=j(w.explanationId);if(!d.has(L))continue;let O=Pr(t.concreteModel,w.modelPath);if(!O.found)continue;let fe=c.graph.concrete.find(J=>J.modelPath===w.modelPath&&JSON.stringify(J.value)===JSON.stringify(O.value));fe||(fe={id:rt(),modelPath:w.modelPath,value:structuredClone(O.value),createdAt:s,updatedAt:s},T.push({op:"add_concrete",concrete:fe})),T.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:fe.id,toId:L,rationale:w.rationale,createdAt:s}}),k.add(L);continue}if(w.op==="relation"){let L=j(w.fromId),O=j(w.toId);if(!d.has(L)||!d.has(O)||L===O)continue;w.type==="expresses"&&Ct(d.get(L),d.get(O))<0&&([L,O]=[O,L]),T.push({op:"add_relation",relation:{id:rt(),type:w.type,fromId:L,toId:O,rationale:w.rationale,createdAt:s}}),k.add(L),k.add(O);continue}if(w.op==="supersede"){let L=j(w.explanationId),O=j(w.replacementId);if(!d.has(L)||!d.has(O)||L===O)continue;T.push({op:"add_evidence",explanationId:L,evidence:ot(t,"challenges",w.reason)}),T.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:O},updatedAt:s}),k.add(L),k.add(O);continue}let H=j(w.explanationId);if(d.has(H))if(k.add(H),w.op==="revise"){if(x.has(m(w.explanationId)))continue;let L=d.get(H);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let O={...w.statement?{statement:w.statement}:{},...w.rationale?{rationale:w.rationale}:{},...w.scope?{scope:Vi(w.scope)}:{},...w.reopenGrounding||v.has(w.explanationId)?{state:"testing"}:{}};T.push({op:"revise_explanation",explanationId:H,patch:O,updatedAt:s})}else if(w.op==="evidence"){if(w.stance==="challenges"&&v.has(w.explanationId))continue;T.push({op:"add_evidence",explanationId:H,evidence:ot(t,w.stance,w.summary)}),w.stance==="challenges"&&T.push({op:"revise_explanation",explanationId:H,patch:{state:"challenged"},updatedAt:s})}else w.op==="retire"&&(T.push({op:"add_evidence",explanationId:H,evidence:ot(t,"challenges",w.reason||"Retired after contradictory collaboration evidence.")}),T.push({op:"revise_explanation",explanationId:H,patch:{state:"retired"},updatedAt:s}))}for(let w of r){let H=j(w),L=d.get(H);!L||L.state==="grounded"||L.state==="retired"||P.has(H)&&!k.has(H)||(k.has(H)||(k.add(H),T.push({op:"add_evidence",explanationId:H,evidence:{...ot(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&T.push({op:"revise_explanation",explanationId:H,patch:{state:"testing"},updatedAt:s}))}let b=new Set(c.graph.relations.map(w=>`${w.type}:${w.fromId}:${w.toId}`)),g=T.filter(w=>{if(w.op!=="add_relation")return!0;let H=`${w.relation.type}:${w.relation.fromId}:${w.relation.toId}`;return b.has(H)?!1:(b.add(H),!0)});if(!g.length)return;let B=rt(),E=await this.store.commit({transactionId:B,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:g}),R=new Map(E.graph.explanations.map(w=>[w.id,w])),N=[...k].flatMap(w=>{let H=R.get(w);if(!H)return[];let L=!c.graph.explanations.some(fe=>fe.id===w),O=H.state==="challenged"||H.state==="retired";return[{explanationId:w,action:L?"added":O?"challenged":"revised",statement:H.statement,state:H.state}]}),V=r.map(j).find(w=>R.get(w)?.state==="testing"&&!P.has(w)),K=e.grounding?j(e.grounding.explanationId):V,G=K?R.get(K):void 0,Q=G?.state==="testing"&&!P.has(G.id)?{explanationId:G.id,question:e.grounding?.question||Xc(G),state:"testing"}:void 0;return{transactionId:B,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:N,...Q?{grounding:Q}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(p=>p.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="no"?"correction":"grounding",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="yes"?(c.push({op:"add_evidence",explanationId:n,evidence:{...ot(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${r.statement}`):e.action==="this_time"?(c.push({op:"add_evidence",explanationId:n,evidence:{...ot(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${r.statement}`):e.action==="no"&&(c.push({op:"add_evidence",explanationId:n,evidence:{...ot(e,"challenges","The developer said this understanding did not capture their intent and requested follow-up."),kind:"rejection"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"challenged"},updatedAt:t}),d=`Challenged: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:rt(),committedAt:t,source:s,summary:d,mutations:c})}};function jr(i,e){return i?.projectId===e.projectId&&i.version===e.version&&i.restartMode===e.restartMode}function Xn(i){return(Array.isArray(i)?i[0]:i)?.split(",")[0]?.trim()||void 0}function Yi(i){if(!i)return null;try{let e=new URL(i);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Ar(i){let e=Yi(Xn(i.origin));if(e)return e;let t=Yi(Xn(i.referer));if(t)return t;let n=Xn(i["x-forwarded-host"]);if(!n)return null;let o=Xn(i["x-forwarded-proto"])==="https"?"https":"http";return Yi(`${o}://${n}`)}function Mr(i,e,t=5){let n=(d,p)=>(p.completedAt??p.startedAt)-(d.completedAt??d.startedAt),o=[...i].sort(n).slice(0,t),r=i.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,p)=>p.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,p)=>(d[p.status]=(d[p.status]??0)+1,d),{});return{recentRuns:o,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as ei}from"crypto";import{mkdir as un,readFile as kt,unlink as od,writeFile as qt}from"fs/promises";import{dirname as ti,extname as rd,join as $e}from"path";var Zc={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 ed(i){let e=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function Er(i,e){let t=e??ed(i);return{kind:t,...Zc[t]}}function Ft(i,e){return!i||e||i.attention!=="response_requested"?i:{...i,attention:"response_available"}}function Zi(i){let e=Array.from(new Set((i.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=i.decisionRequired?"decision_required":i.question||i.groundingRequired?"response_requested":i.reviewRequired||i.resolutions?.some(o=>o.status==="needs_review")?"review_required":"response_available";return i.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:i.imprintTransactionId}),{attention:n,outcomes:t}}import{createHash as td,randomUUID as nd}from"crypto";var _r=i=>`${i}-${nd()}`;function eo(i,...e){return`${i}-${td("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function to(i){return{schemaVersion:1,submissionIds:[_r("submission")],jobId:i.jobId,threadId:i.threadId,artifactIds:[...new Set(i.artifactIds??[])]}}function pn(i,e=[],t){return{...i,outcomeId:i.outcomeId??_r("outcome"),imprintEvidenceIds:[...new Set([...i.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function id(i){try{return new URL(i).pathname||"/"}catch{return"/"}}function Yn(i,e){return e?[`${i||"/"}:${e}`]:[]}function Cr(i){let e=id(i.url);return[...new Set([...i.annotations.flatMap(t=>Yn(t.pathname??e,t.linkedSelector)),...i.styleModifications.flatMap(t=>Yn(e,t.durableSelector??t.selector)),...(i.textModifications??[]).flatMap(t=>Yn(t.pathname??e,t.durableSelector??t.selector)),...(i.domModifications??[]).flatMap(t=>Yn(t.pathname??e,t.durableSelector??t.selector))])]}function $r(i,e){return[...new Set([`screenshot:${e}`,...i.annotations.map(t=>`annotation:${t.id}`),...i.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function Zn(i,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=eo("submission",i,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:i,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[eo("artifact",i,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:eo("outcome",i,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function no(i){let e=i.lifecycleVersion!==1;i.lifecycleVersion=1;for(let t of i.messages)e=Zn(i.id,t)||e;return e}function Or(i){let e=i.messages.at(-1),t=[...i.messages].reverse().find(o=>o.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:i.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:i.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:i.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var sd={version:1,threads:{}},Dr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],mn={version:2,updatedAt:0,files:{}};function ad(i){return JSON.stringify(i,null,2)}function cd(i){return Object.fromEntries(Dr.flatMap(e=>i[e]===void 0?[]:[[e,i[e]]]))}function dd(i){let e={...i};for(let t of Dr)delete e[t];return e}function Ut(i){let e=i;if(i.error){let t=Er(i.error,i.errorKind);(i.error!==t.message||i.errorKind!==t.kind||i.responseText!==void 0)&&(e={...i,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=Ft(e.result,!1),n=Ft(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var ni=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=$e(e,".popmelt");this.legacyFilePath=$e(t,"threads.json"),this.threadsDir=$e(t,"threads"),this.indexPath=$e(this.threadsDir,"index.json"),this.artifactsDir=$e(t,"artifacts","thread-messages"),this.mediaDir=$e(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await kt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[o,r]of Object.entries(e.files)){let s=await this.readThread($e(this.threadsDir,r));s&&(t[o]=s)}this.cache={version:1,threads:t};let n=!1;for(let o of Object.values(t))n=no(o)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await kt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(Ut)}]))},this.index={...mn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))no(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...sd,threads:{}},this.index={...mn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let o of Object.values(t.threads))if(o.elementIdentifiers.some(s=>n.has(s)))return o;return null}async createThread(e,t){let n=await this.load(),o={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=o,await this.persistThread(o),o}async appendMessage(e,t){let o=(await this.load()).threads[e];o&&(Zn(e,t),o.messages.push(Ut(t)),o.updatedAt=Date.now(),await this.persistThread(o))}async appendMessageBeforeQueuedReplies(e,t){let o=(await this.load()).threads[e];if(!o)return;Zn(e,t);let r=o.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?o.messages.splice(r,0,Ut(t)):o.messages.push(Ut(t)),o.updatedAt=Date.now(),await this.persistThread(o)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===t);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,n),c.error){let d=Ut(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let o=(await this.load()).threads[e];if(!o)return;let r=new Set(o.elementIdentifiers);for(let s of t)r.has(s)||o.elementIdentifiers.push(s);o.updatedAt=Date.now(),await this.persistThread(o)}async deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((o,r)=>r.updatedAt-o.updatedAt),n.slice(0,e).map(o=>{let s=o.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]",c=o.messages.filter(l=>l.role==="assistant"),d=l=>{if(l.role!=="assistant")return;if(l.question)return l.question;let h=l.imprintSummary?.grounding;if(h?.question&&!l.imprintSummary?.resolvedAction)return h.question},p=o.messages.findLastIndex(l=>!!d(l)),x=o.messages.findLastIndex(l=>l.role==="human"),T=p>x?d(o.messages[p]):void 0,k=o.messages.at(-1)?.role,P=Array.from(new Set(o.messages.slice(0,Math.max(0,x)).filter(l=>l.role==="assistant"&&!!l.jobId).map(l=>l.jobId))),v=c.some(l=>!!l.responseText||!!l.question||!!l.result||!!l.memoryReviewCard||!!l.memoryReceipt),f=c.some(l=>!!l.error);return{id:o.id,createdAt:o.createdAt,updatedAt:o.updatedAt,preview:s,messageCount:o.messages.length,hasReply:v,hasError:f,lastMessageRole:k,pendingQuestion:T,acknowledgedJobIds:P,elementIdentifiers:o.elementIdentifiers,lifecycle:Or(o)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let o=n.messages.at(-1);if(!o||o.role!=="human"||/^(imprint|memory)-/.test(o.jobId))continue;let r=pn(o.lifecycle);o.queued&&await this.updateMessage(n.id,o.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:o.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await kt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:o,...r})=>{let s={};if(o?.path)try{let c=await kt($e(ti(this.legacyFilePath),o.path),"utf8");ei("sha256").update(c).digest("hex")===o.sha256&&(s=JSON.parse(c))}catch{}return Ut({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=cd(e),n=dd(e);if(Object.keys(t).length===0)return n;let o=ad(t),r=ei("sha256").update(o).digest("hex"),s=$e("artifacts","thread-messages",`${r}.json`);await un(this.artifactsDir,{recursive:!0});try{await kt($e(ti(this.legacyFilePath),s),"utf8")}catch{await qt($e(ti(this.legacyFilePath),s),o)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(ti(n)===this.mediaDir)return n;try{let o=await kt(n),r=ei("sha256").update(o).digest("hex"),s=$e(this.mediaDir,`${r}${rd(n)||".bin"}`);await un(this.mediaDir,{recursive:!0});try{await kt(s)}catch{await qt(s,o)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,o])=>[n,await t(o)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,o])=>[n,await Promise.all(o.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,o])=>[n,await Promise.all(o.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await un(this.threadsDir,{recursive:!0});let t=this.index??{...mn,files:{}},n=t.files[e.id]??`${ei("sha256").update(e.id).digest("hex").slice(0,32)}.json`,o=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:o};await qt($e(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await qt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await un(this.threadsDir,{recursive:!0}),this.index=this.index??{...mn,files:{}},await qt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...mn,files:{}},n=t.files[e];n&&await od($e(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await un(this.threadsDir,{recursive:!0}),await qt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as ld,open as pd,readFile as ud,rename as md,unlink as fd}from"fs/promises";import{dirname as hd,join as gd}from"path";var Nr={schemaVersion:1,theme:"auto",updatedAt:null};function Jr(i){return i==="light"||i==="dark"||i==="auto"?i:null}async function yd(i,e){await ld(hd(i),{recursive:!0});let t=`${i}.${process.pid}.${Date.now()}.tmp`;try{let n=await pd(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
-
`,"utf8"),await n.sync()}finally{await n.close()}await
|
|
179
|
-
|
|
180
|
-
`)
|
|
181
|
-
|
|
171
|
+
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.`;function sn(o,e,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(u=>{let I=[u.selector];return u.reactComponent&&I.push(`(${u.reactComponent})`),I.join(" ")}).join(", "),s=i.instruction||"No text";n.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[i.id];if(c&&c.length>0)for(let u of c)n.push(` Attached image: use the Read tool to view ${u}`);let d=t?.[i.id];if(d?.length)for(let u of d)n.push(` Attached context (${u.name}, ${u.mimeType}): use the Read tool to inspect ${u.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let i of o.styleModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"";for(let s of i.changes)n.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let i of o.textModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=JSON.stringify(i.original),c=JSON.stringify(i.modified),d=i.textNodePath.length>0?` textNodePath=${i.textNodePath.join(".")}`:"";n.push(`- ${i.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let i of o.domModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=i.sourceElement?.reactComponent?` from ${i.sourceSelector} (${i.sourceElement.reactComponent})`:i.sourceSelector?` from ${i.sourceSelector}`:"",c=i.referenceSelector?` ${i.placement} ${i.referenceSelector}`:` at index ${i.targetIndex}`;n.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${c}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let i of o.spacingTokenChanges){n.push(`
|
|
172
|
+
### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let r of i.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[i.selector];i.reactComponent&&r.push(`(${i.reactComponent})`),i.context&&r.push(`in ${i.context}`),i.textContent&&r.push(`"${i.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
173
|
+
`)}function ur(o,e,t){let n=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!r&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let c of t.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${c.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),c.feedbackSummary&&n.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&n.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${c.question}"`);else{if(n.push(`### Round ${s} (assistant)`),c.responseText&&n.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let u=d.finalScope??d.inferredScope,I=u?` [${u.breadth} ${u.target}]`:"";n.push(`- ${d.annotationId}: ${d.status}${I} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&n.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&n.push(`Tools used: ${c.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let I=new Map;for(let k of s)if(typeof k=="object"&&k!==null&&"text"in k){let T=k,P=T.scope||"general";I.has(P)||I.set(P,[]),I.get(P).push(T.text)}for(let[k,T]of I){n.push(`**${k.charAt(0).toUpperCase()+k.slice(1)}**`);for(let P of T)n.push(`- ${P}`)}}else for(let I of s)typeof I=="string"&&n.push(`- ${I}`);let c=t.designModel.tokens;c&&typeof c=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(c,null,2)),n.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=t?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let u=d.pathname||new URL(e.url).pathname;c.has(u)||c.set(u,[]),c.get(u).push(d)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,u]of c){n.push(""),n.push(`## Page: ${d}`);let I=s[d];I&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${I}`):!I&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let k={...e,annotations:u,styleModifications:e.styleModifications},T=sn(k,t?.imagePaths,t?.attachmentFiles);T&&(n.push(""),n.push(T))}}else{let s=sn(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
|
|
174
|
+
`)}function mr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function fr(o,e,t,n){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),t!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${c.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),c.feedbackSummary&&i.push(`Annotations: ${c.feedbackSummary}`))):c.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${c.question}"`)):(i.push(`### Round ${s} (assistant)`),c.responseText&&i.push(`Response: ${c.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of n)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),i.push("<resolution>"),i.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),i.push("</resolution>"),i.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
|
|
175
|
+
`)}function Tc(o){if(typeof o!="object"||o===null)return!1;let e=o;return(e.breadth==="instance"||e.breadth==="pattern")&&(e.target==="element"||e.target==="component"||e.target==="token")}function kc(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!Tc(e[t]))return!1;return!0}function hr(o){let t=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let n=JSON.parse(t);return(Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.annotations)?n.annotations:[]).filter(kc)}catch{return[]}}function Rc(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let i=n;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}function gr(o,e){return e>0?Rc(o):[]}import{execFile as Pc}from"child_process";import{readdir as jc,readFile as Ac,stat as Mc}from"fs/promises";import{homedir as an}from"os";import{join as Ye}from"path";var Wn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:yr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:yr()}],cn=[{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"}],dn={id:"",label:"Default",source:"cli"},Ec=/^\s*-\s+"([^"]+)"/;function _c(o){let e=[],t=!1;for(let n of o.split(`
|
|
176
|
+
`)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let i=n.match(Ec);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Ho(r),source:"cli"})}return Gn([dn,...e])}function Cc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,i)=>{let r=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(n=>{let i=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!i)return[];let r=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():Ho(i),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.effort!="string"?[]:[{effort:u.effort,...typeof u.description=="string"?{description:u.description}:{}}]}):void 0,c=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.id!="string"?[]:[{id:u.id,label:typeof u.name=="string"?u.name:u.id,...typeof u.description=="string"?{description:u.description}:{}}]}):void 0;return[{id:i,label:r,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function yr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function $c(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Gn(e.map(t=>({id:t,label:Ho(t),source:"cli"})))}function Ho(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},t=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let r=n[1]==="sonnet"?"Sonn":Jc(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${r}${s}${n[4]?" Fast":""}`}let i=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return t}async function vr(o="copilot"){let e=await zn(o,["help","config"]),t=_c(e);return t.length>1?t:[dn]}async function Ir(o="codex"){let e=await zn(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||Ye(an(),".codex");return br(Ye(n,"models_cache.json"))}),t=Cc(e);return t.length>0?Gn([...t,...cn]):cn}async function wr(o="claude"){let e=Ye(an(),".claude"),t=[Ye(an(),".claude","stats-cache.json"),Ye(an(),".claude","settings.json"),Ye(an(),".claude.json"),Ye(e,"cache","changelog.md")],[n,i,r]=await Promise.all([zn(o,["--help"]).catch(()=>""),zn(o,["--version"]).catch(()=>""),Oc(e).catch(()=>[])]),s=Nc([...t,...r]),c=await Promise.all(s.map(u=>br(u).catch(()=>""))),d=$c([n,i,...c].join(`
|
|
177
|
+
`));return Gn([...Wn,...d])}function zn(o,e,t=5e3){return new Promise((n,i)=>{Pc(o,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){i(r);return}n(s)})})}async function br(o){return Ac(o,"utf-8")}async function Oc(o){let e=[Ye(o,"projects"),Ye(o,"telemetry")],t=[];for(let n of e)await xr(n,t,4);return t.sort((n,i)=>i.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function xr(o,e,t){if(t<0)return;let n;try{n=await jc(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async i=>{let r=Ye(o,i.name);if(i.isDirectory()){await xr(r,e,t-1);return}if(!(!i.isFile()||!Dc(i.name)))try{let s=await Mc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function Dc(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Gn(o){let e=new Set,t=[];for(let n of o)e.has(n.id)||(e.add(n.id),t.push(n));return t}function Nc(o){return[...new Set(o)]}function Jc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Hn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,i=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),i}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(n=>n.threadId===e&&(!t||t(n)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let i=this.bufferEvent(t,e);for(let r of this.listeners)r(i,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let i={...t,seq:n.nextSeq++};return n.events.push(i),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),i}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(c=>c.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,t,n){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[t]+=n}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:"Cancelled by user",cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let n of t)try{n.kill("SIGTERM")}catch{}await Promise.all(t.map(n=>new Promise(i=>{let r=!1,s=()=>{r||(r=!0,i())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as ot}from"crypto";import{createHash as Bc}from"crypto";import{mkdir as Lc,open as qc,readFile as Sr,readdir as Fc,rename as Uc,unlink as zc}from"fs/promises";import{dirname as Wc,join as Lt}from"path";function Ce(o){return structuredClone(o)}function Tr(o){return Bc("sha256").update(JSON.stringify(o)).digest("hex")}async function St(o,e){await Lc(Wc(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await qc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await Uc(t,o)}catch(i){throw await zc(t).catch(()=>{}),i}}function Gc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Hc(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=Ce(e):o.explanations.push(Ce(e))}function Vo(o,e){let t=Ce(o);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(i=>i.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(Ce(n.explanation))}else if(n.op==="replace_explanation")Hc(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(i=>i.id!==n.explanationId),t.relations=t.relations.filter(i=>i.fromId!==n.explanationId&&i.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(i=>i.id===n.concrete.id)||t.concrete.push(Ce(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(i=>i.id!==n.concreteId),t.relations=t.relations.filter(i=>i.fromId!==n.concreteId&&i.toId!==n.concreteId);else if(n.op==="add_evidence"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);i.evidence.some(r=>r.id===n.evidence.id)||(i.evidence.push(Ce(n.evidence)),i.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(i,Ce(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let i=n.relation,r=t.explanations.find(u=>u.id===i.fromId),s=t.explanations.find(u=>u.id===i.toId),c=t.concrete.some(u=>u.id===i.fromId),d=t.concrete.some(u=>u.id===i.toId);if(Wi(i.type)){if(!(i.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(t.relations.some(I=>I.type===i.type&&I.fromId===i.fromId&&I.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toId}`);if(i.type==="expresses"&&r&&s){if(Ct(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let I=new Map;for(let P of t.relations)P.type==="expresses"&&I.set(P.fromId,[...I.get(P.fromId)??[],P.toId]);let k=[i.toId],T=new Set;for(;k.length;){let P=k.pop();if(P===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);T.has(P)||(T.add(P),k.push(...I.get(P)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);t.relations.some(u=>u.id===i.id)||t.relations.push(Ce(i))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(i=>i.id!==n.relationId));return t}function Vc(o,e){let t=[],n=Ce(o);for(let i of e){if(i.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===i.explanationId);r&&t.unshift({op:"add_explanation",explanation:Ce(r)})}else if(i.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===i.concreteId);r&&t.unshift({op:"add_concrete",concrete:Ce(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=n.explanations.find(c=>c.id===r);s&&t.unshift({op:"replace_explanation",explanation:Ce(s)})}else if(i.op==="add_relation")t.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=n.relations.find(s=>s.id===i.relationId);r&&t.unshift({op:"add_relation",relation:Ce(r)})}n=Vo(n,[i])}return t}function kr(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Vn=class{constructor(e,t){this.projectRoot=e;this.projectId=t;this.writeChain=Promise.resolve();this.imprintDir=Lt(e,".popmelt","imprint"),this.manifestPath=Lt(this.imprintDir,"manifest.json"),this.graphPath=Lt(this.imprintDir,"graph.json"),this.journalDir=Lt(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Sr(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),n=(await Fc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=Gc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<n.length;c++){let d=JSON.parse(await Sr(Lt(this.journalDir,n[c]),"utf8")),{hash:u,...I}=d;if(d.sequence!==c+1||d.previousHash!==s||u!==Tr(I))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=Vo(i,d.mutations),i.updatedAt=d.committedAt,i.head={sequence:d.sequence,hash:d.hash},r.push(d),s=d.hash}return{graph:i,transactions:r,recoveredTransactions:Math.max(0,r.length-e.head.sequence)}}async load(){let e=await this.loadRaw();return{...e,graph:bt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let t=await this.loadRaw(),n=bt(t.graph),i=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let c=i.get(s.id);c&&c.type===s.type&&c.fromId===s.fromId&&c.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),c&&r.push({op:"add_relation",relation:c}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await St(this.graphPath,n),await St(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(k=>k.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=n.graph.head.sequence+1,r=Vc(n.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:Ce(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Tr(s)},d=Vo(n.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let u=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await St(Lt(this.journalDir,u),c);let I={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await St(this.graphPath,d),await St(this.manifestPath,I),t={graph:d,transaction:c}}),await this.writeChain,t}async undo(e,t,n,i){let r=await this.load(),s=r.transactions.find(u=>u.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(u=>u.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(kr));if(r.transactions.filter(u=>u.sequence>s.sequence).some(u=>u.mutations.some(I=>kr(I).some(k=>c.has(k)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:n,source:t,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await St(this.graphPath,e.graph),await St(this.manifestPath,{version:1,topologyVersion:2,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var Kc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Qc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]),Xc=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Qo(o){return!!(o&&Xc.test(o))}function Yc(o){return o.scope.kind==="project"||Qo(`${o.statement} ${o.rationale}`)}function Zc(o){let e=o?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function ed(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Kn(o){return new Set(ed(o).split(" ").filter(e=>e.length>2&&!Qc.has(e)))}function Qn(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Ko(o){return!o||!Array.isArray(o.values)||o.values.length===0?{kind:"project",values:["*"]}:{kind:o.kind,values:[...new Set(o.values.map(e=>e.trim()).filter(Boolean))]}}function ut(o,e,t){return{id:ot(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ye(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Rr(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Pr(o,e){if(!o||!e.trim())return{found:!1};let t=o;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let i=Number(n);if(!Number.isInteger(i)||i<0||i>=t.length)return{found:!1};t=t[i]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Xo(o,e={}){let t=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),i=t.at(-1)?.[1],r,s=[];if(i)r=i;else{let d=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let u=JSON.parse(d);if(!u||typeof u!="object"||Array.isArray(u)||!Object.prototype.hasOwnProperty.call(u,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let I=u;r=I.imprint,s=Array.isArray(I.annotations)?I.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("imprint assessment is invalid");if(c.decision==="none"){let p=String(c.reason);if(!Kc.has(p))throw new Error("imprint no-op reason is invalid");if(p==="task_specific_detail"&&s.some(f=>{if(!f||typeof f!="object"||Array.isArray(f))return!1;let m=f;return(m.finalScope??m.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let l=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[];if(l.length){let f=l,m=new Set(e.context?.explanations.map(b=>b.id)??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(b=>{let g=e.context?.explanations.find(B=>B.id===b);return m.has(b)&&g&&(g.state==="emerging"||g.state==="testing")&&!h.has(b)});if(j.length){let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0],B=ye(b?.question,300);return{draft:{decision:"apply",summary:{title:ye(c.summary?.title,120)||"Applied shared understanding",detail:ye(c.summary?.detail,500)||ye(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:j,grounding:{explanationId:g,question:B||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(p==="duplicate"){let f=ye(c.duplicateOfExplanationId,100),m=c.scopeComparison;if(!f)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(m!=="equivalent"&&m!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let h=e.context?.explanations.find(j=>j.id===f);if(!h)throw new Error("duplicate assessment must cite a surfaced explanation");if(Qo(e.requestText)&&!Yc(h))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:p,duplicateOfExplanationId:f,scopeComparison:m},visibleText:n}}return{draft:{decision:"none",reason:p},visibleText:n}}if(c.decision==="recognize"){let p=ye(c.explanationId,100);if(!p)throw new Error("recognition requires explanationId");let l=e.context?.explanations.find(h=>h.id===p);if(!l)throw new Error("recognition must cite a surfaced explanation");if(l.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let f=c.summary,m={title:ye(f?.title,120),detail:ye(f?.detail,500)};if(!m.title||!m.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:p,summary:m},visibleText:n}}if(c.decision==="apply"){let p=c.summary,l={title:ye(p?.title,120),detail:ye(p?.detail,500)};if(!l.title||!l.detail)throw new Error("application summary title and detail are required");let f=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(B=>typeof B=="string"&&!!B.trim()):[];if(!f.length)throw new Error("application requires appliedExplanationIds");let m=new Map(e.context?.explanations.map(B=>[B.id,B])??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(B=>{let E=m.get(B);return E&&(E.state==="emerging"||E.state==="testing")&&!h.has(B)});if(!j.length){if(f.every(E=>m.get(E)?.state==="grounded"||h.has(E)))return{draft:{decision:"none",reason:"application_only"},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0];return{draft:{decision:"apply",summary:l,appliedExplanationIds:j,grounding:{explanationId:g,question:ye(b?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(c.decision!==void 0&&c.decision!=="mutate")throw new Error("imprint decision is invalid");let d=c.summary,u=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(u)))throw new Error("summary.kind is invalid");let I={kind:u,title:ye(d?.title,120),detail:ye(d?.detail,500)};if(!I.title||!I.detail)throw new Error("summary title and detail are required");let k=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(p=>typeof p=="string"&&!!p.trim()):[],T=[];for(let p of Array.isArray(c.mutations)?c.mutations:[]){if(!p||typeof p!="object")continue;let l=p;if(l.op==="add"&&["intention","principle","pattern"].includes(String(l.kind))){let f=ye(l.statement),m=ye(l.rationale);if(!f||!m)continue;T.push({op:"add",clientId:ye(l.clientId,100)||void 0,kind:l.kind,statement:f,rationale:m,scope:Rr(l.scope),rootReason:ye(l.rootReason,300)||void 0})}else if(l.op==="revise"&&typeof l.explanationId=="string"){let f={op:"revise",explanationId:l.explanationId,statement:ye(l.statement)||void 0,rationale:ye(l.rationale)||void 0,scope:Rr(l.scope),reopenGrounding:l.reopenGrounding===!0};(f.statement||f.rationale||f.scope||f.reopenGrounding)&&T.push(f)}else if(l.op==="evidence"&&typeof l.explanationId=="string"&&["supports","challenges","excepts"].includes(String(l.stance))){let f=ye(l.summary);f&&T.push({op:"evidence",explanationId:l.explanationId,stance:l.stance,summary:f})}else if(l.op==="relation"&&typeof l.fromId=="string"&&typeof l.toId=="string"&&["expresses","excepts"].includes(String(l.type))){let f=ye(l.rationale);if(!f)continue;T.push({op:"relation",type:l.type,fromId:l.fromId,toId:l.toId,rationale:f})}else if(l.op==="supersede"&&typeof l.explanationId=="string"&&typeof l.replacementId=="string"){let f=ye(l.reason);f&&T.push({op:"supersede",explanationId:l.explanationId,replacementId:l.replacementId,reason:f})}else if(l.op==="bind_concrete"&&typeof l.explanationId=="string"){let f=ye(l.modelPath,300);f&&T.push({op:"bind_concrete",explanationId:l.explanationId,modelPath:f,rationale:ye(l.rationale)})}else l.op==="retire"&&typeof l.explanationId=="string"&&T.push({op:"retire",explanationId:l.explanationId,reason:ye(l.reason)})}let P=c.grounding,x=P&&typeof P.explanationId=="string"&&ye(P.question)?{explanationId:P.explanationId,question:ye(P.question,300)}:void 0;return{draft:{decision:"mutate",summary:I,appliedExplanationIds:k,mutations:T,grounding:x},visibleText:n}}catch(c){return{visibleText:n,error:c instanceof Error?c.message:String(c)}}}function Yo(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),i=new Set(o?.correctionExplanationIds??[]),r=Qo(e.requestText);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((s,c)=>[`${c+1}. [${s.state}; ${s.kind}] ${s.statement}`,` - Why: ${s.rationale}`,` - Scope: ${s.scope.kind} ${s.scope.values.join(", ")}`,` - Explanation: ${s.id}`,...n.has(s.id)?[" - Grounding: already pending; do not ask again"]:[],...i.has(s.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...s.concrete.map(d=>` - Concrete terminal: ${d.modelPath} = ${JSON.stringify(d.value)}`)].join(`
|
|
179
|
+
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(s=>`- ${s.fromId} --${s.type}--> ${s.toId}: ${s.rationale}`)]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...r?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.","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"}',"A no-op reason cannot suppress application evidence. When the completed action semantically matches the top retrieved ungrounded explanation, the bridge records that application regardless of the no-op label. Report decision apply directly so the summary and grounding question are intentional.","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 requires neither appliedExplanationIds nor a mutation. Never claim that a new explanation is grounded."].join(`
|
|
180
|
+
`)}var ln=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Vn(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=Kn(e.text??""),n=Kn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]),r=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!i.size&&!r.size)return;let{graph:s}=await this.store.load(),c=s.explanations.filter(p=>p.state!=="retired"&&(p.state!=="challenged"||r.has(p.id))).map(p=>{let l=Kn([p.statement,p.rationale].join(" ")),f=Kn(p.scope.values.join(" ")),m=Qn(l,t),h=Qn(f,t),j=Qn(f,n),b=Qn(l,n),g=m+h*.2+j*.25+b*.1+(p.state==="grounded"?.08:0)+(i.has(p.id)?1:0)+(r.has(p.id)?1:0),B=i.has(p.id)||r.has(p.id)||(t.size?m>=.12||h>=.5:j>=.2||b>=.2);return{item:p,score:g,relevant:B}}).filter(p=>p.relevant&&p.score>=.18).sort((p,l)=>l.score-p.score||l.item.updatedAt.localeCompare(p.item.updatedAt)),d=Math.max(1,e.maxExplanations??6);if(!c.length)return;let u=c.slice(0,d).map(({item:p})=>p),I=new Set(u.map(p=>p.id)),k=new Set(s.relations.flatMap(p=>I.has(p.fromId)?[p.toId]:I.has(p.toId)?[p.fromId]:[])),T=new Set(s.explanations.flatMap(p=>k.has(p.id)&&p.state!=="retired"&&p.state!=="challenged"?[p.id]:[])),P=s.explanations.filter(p=>T.has(p.id)&&!I.has(p.id)).sort((p,l)=>l.updatedAt.localeCompare(p.updatedAt)).slice(0,4),x=[...u,...P];for(let p of P)I.add(p.id);return{explanations:x.map(p=>{let l=new Set(s.relations.filter(f=>f.toId===p.id&&f.type==="expresses").map(f=>f.fromId));return{id:p.id,kind:p.kind,statement:p.statement,rationale:p.rationale,scope:p.scope,state:p.state,concrete:s.concrete.filter(f=>l.has(f.id)).map(f=>({id:f.id,modelPath:f.modelPath,value:f.value}))}}),truncated:c.length>u.length||P.length<T.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},...r.size?{correctionExplanationIds:[...r]}:{},relations:s.relations.filter(p=>I.has(p.fromId)&&I.has(p.toId)).map(p=>({id:p.id,type:p.type,fromId:p.fromId,toId:p.toId,rationale:p.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],i=t.applicationOccurred?n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...i])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(w=>[w.id,w])),u=new Map,I=new Map,k=[],T=new Set,P=new Set(t.pendingGroundingExplanationIds??[]),x=new Set(n.flatMap(w=>w.op==="revise"&&n.some(H=>H.op==="evidence"&&H.stance==="challenges"&&H.explanationId===w.explanationId)?[w.explanationId]:[])),p=new Set(n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[])),l=w=>d.has(w)||p.has(w),f=new Set;for(let w of n)w.op==="relation"&&w.fromId!==w.toId&&l(w.fromId)&&l(w.toId)?(f.add(w.fromId),f.add(w.toId)):w.op==="supersede"&&w.explanationId!==w.replacementId&&l(w.explanationId)&&l(w.replacementId)?(f.add(w.explanationId),f.add(w.replacementId)):w.op==="bind_concrete"&&l(w.explanationId)&&Pr(t.concreteModel,w.modelPath).found&&f.add(w.explanationId);let m=c.graph.explanations.length===0;for(let w of n){if(w.op!=="add")continue;let H=!!(w.clientId&&f.has(w.clientId)),L=!!w.rootReason?.trim()||m;if(!H&&!L)continue;m&&(m=!1);let O=ot();w.clientId&&u.set(w.clientId,O);let he=w.clientId?r.includes(w.clientId):!1,J={id:O,kind:w.kind,statement:w.statement,rationale:w.rationale,scope:Ko(w.scope),state:he?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[ut(t,"supports",e.summary.detail)]};d.set(O,J),T.add(O),k.push({op:"add_explanation",explanation:J})}let h=w=>u.get(w)??w;for(let w of n){if(w.op!=="revise")continue;let H=h(w.explanationId),L=d.get(H);if(L?.state!=="grounded")continue;let O=ot(),he={id:O,kind:L.kind,statement:w.statement??L.statement,rationale:w.rationale??L.rationale,scope:w.scope?Ko(w.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[ut(t,"supports",e.summary.detail)]};d.set(O,he),I.set(H,O),T.add(O),k.push({op:"add_explanation",explanation:he});let J=Ct(L,he);J!==0&&k.push({op:"add_relation",relation:{id:ot(),type:"expresses",fromId:J>0?H:O,toId:J>0?O:H,rationale:w.rationale??e.summary.detail,createdAt:s}})}let j=w=>{let H=h(w);return I.get(H)??H};for(let w of n){if(w.op==="add")continue;if(w.op==="bind_concrete"){let L=j(w.explanationId);if(!d.has(L))continue;let O=Pr(t.concreteModel,w.modelPath);if(!O.found)continue;let he=c.graph.concrete.find(J=>J.modelPath===w.modelPath&&JSON.stringify(J.value)===JSON.stringify(O.value));he||(he={id:ot(),modelPath:w.modelPath,value:structuredClone(O.value),createdAt:s,updatedAt:s},k.push({op:"add_concrete",concrete:he})),k.push({op:"add_relation",relation:{id:ot(),type:"expresses",fromId:he.id,toId:L,rationale:w.rationale,createdAt:s}}),T.add(L);continue}if(w.op==="relation"){let L=j(w.fromId),O=j(w.toId);if(!d.has(L)||!d.has(O)||L===O)continue;w.type==="expresses"&&Ct(d.get(L),d.get(O))<0&&([L,O]=[O,L]),k.push({op:"add_relation",relation:{id:ot(),type:w.type,fromId:L,toId:O,rationale:w.rationale,createdAt:s}}),T.add(L),T.add(O);continue}if(w.op==="supersede"){let L=j(w.explanationId),O=j(w.replacementId);if(!d.has(L)||!d.has(O)||L===O)continue;k.push({op:"add_evidence",explanationId:L,evidence:ut(t,"challenges",w.reason)}),k.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:O},updatedAt:s}),T.add(L),T.add(O);continue}let H=j(w.explanationId);if(d.has(H))if(T.add(H),w.op==="revise"){if(I.has(h(w.explanationId)))continue;let L=d.get(H);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let O={...w.statement?{statement:w.statement}:{},...w.rationale?{rationale:w.rationale}:{},...w.scope?{scope:Ko(w.scope)}:{},...w.reopenGrounding||x.has(w.explanationId)?{state:"testing"}:{}};k.push({op:"revise_explanation",explanationId:H,patch:O,updatedAt:s})}else if(w.op==="evidence"){if(w.stance==="challenges"&&x.has(w.explanationId))continue;k.push({op:"add_evidence",explanationId:H,evidence:ut(t,w.stance,w.summary)}),w.stance==="challenges"&&k.push({op:"revise_explanation",explanationId:H,patch:{state:"challenged"},updatedAt:s})}else w.op==="retire"&&(k.push({op:"add_evidence",explanationId:H,evidence:ut(t,"challenges",w.reason||"Retired after contradictory collaboration evidence.")}),k.push({op:"revise_explanation",explanationId:H,patch:{state:"retired"},updatedAt:s}))}for(let w of r){let H=j(w),L=d.get(H);!L||L.state==="grounded"||L.state==="retired"||P.has(H)&&!T.has(H)||(T.has(H)||(T.add(H),k.push({op:"add_evidence",explanationId:H,evidence:{...ut(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&k.push({op:"revise_explanation",explanationId:H,patch:{state:"testing"},updatedAt:s}))}let b=new Set(c.graph.relations.map(w=>`${w.type}:${w.fromId}:${w.toId}`)),g=k.filter(w=>{if(w.op!=="add_relation")return!0;let H=`${w.relation.type}:${w.relation.fromId}:${w.relation.toId}`;return b.has(H)?!1:(b.add(H),!0)});if(!g.length)return;let B=ot(),E=await this.store.commit({transactionId:B,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:g}),R=new Map(E.graph.explanations.map(w=>[w.id,w])),N=[...T].flatMap(w=>{let H=R.get(w);if(!H)return[];let L=!c.graph.explanations.some(he=>he.id===w),O=H.state==="challenged"||H.state==="retired";return[{explanationId:w,action:L?"added":O?"challenged":"revised",statement:H.statement,state:H.state}]}),V=r.map(j).find(w=>R.get(w)?.state==="testing"&&!P.has(w)),K=e.grounding?j(e.grounding.explanationId):V,G=K?R.get(K):void 0,Q=G?.state==="testing"&&!P.has(G.id)?{explanationId:G.id,question:e.grounding?.question||Zc(G),state:"testing"}:void 0;return{transactionId:B,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:N,...Q?{grounding:Q}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(u=>u.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="yes"?(c.push({op:"add_evidence",explanationId:n,evidence:{...ut(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${r.statement}`):e.action==="this_time"&&(c.push({op:"add_evidence",explanationId:n,evidence:{...ut(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:ot(),committedAt:t,source:s,summary:d,mutations:c}),"applied"}};function jr(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Xn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Zo(o){if(!o)return null;try{let e=new URL(o);return["localhost","127.0.0.1","::1"].includes(e.hostname)?e.origin:null}catch{return null}}function Ar(o){let e=Zo(Xn(o.origin));if(e)return e;let t=Zo(Xn(o.referer));if(t)return t;let n=Xn(o["x-forwarded-host"]);if(!n)return null;let i=Xn(o["x-forwarded-proto"])==="https"?"https":"http";return Zo(`${i}://${n}`)}function Mr(o,e,t=5){let n=(d,u)=>(u.completedAt??u.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(n).slice(0,t),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,u)=>u.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,u)=>(d[u.status]=(d[u.status]??0)+1,d),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as eo}from"crypto";import{mkdir as un,readFile as Tt,unlink as sd,writeFile as Ft}from"fs/promises";import{dirname as to,extname as ad,join as $e}from"path";var td={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 nd(o){let e=typeof o=="string"?o:(()=>{try{return JSON.stringify(o)}catch{return String(o??"")}})();return/\b(?:http\s*)?503\b|server at capacity|\bat capacity\b|resource[_\s-]?exhausted|temporarily unavailable/i.test(e)?"capacity":/\b(?:http\s*)?429\b|rate[_\s-]?limit|too many requests/i.test(e)?"rate_limited":/timed?\s*out|timeout/i.test(e)?"timeout":/auth(?:entication|orization)? required|oauth|not authenticated|sign[ -]?in required|unauthorized|\b401\b/i.test(e)?"authentication":/transport channel closed|connection (?:closed|lost|reset)|socket hang up|network error|disconnected/i.test(e)?"connection":"failed"}function Er(o,e){let t=e??nd(o);return{kind:t,...td[t]}}function qt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ei(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:n,outcomes:t}}import{createHash as od,randomUUID as id}from"crypto";var _r=o=>`${o}-${id()}`;function ti(o,...e){return`${o}-${od("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function ni(o){return{schemaVersion:1,submissionIds:[_r("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function pn(o,e=[],t){return{...o,outcomeId:o.outcomeId??_r("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function rd(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function Yn(o,e){return e?[`${o||"/"}:${e}`]:[]}function Cr(o){let e=rd(o.url);return[...new Set([...o.annotations.flatMap(t=>Yn(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>Yn(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>Yn(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>Yn(t.pathname??e,t.durableSelector??t.selector))])]}function $r(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(t=>`annotation:${t.id}`),...o.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function Zn(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=ti("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[ti("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:ti("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function oi(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=Zn(o.id,t)||e;return e}function Or(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(i=>i.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:o.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var cd={version:1,threads:{}},Dr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],mn={version:2,updatedAt:0,files:{}};function dd(o){return JSON.stringify(o,null,2)}function ld(o){return Object.fromEntries(Dr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function pd(o){let e={...o};for(let t of Dr)delete e[t];return e}function Ut(o){let e=o;if(o.error){let t=Er(o.error,o.errorKind);(o.error!==t.message||o.errorKind!==t.kind||o.responseText!==void 0)&&(e={...o,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=qt(e.result,!1),n=qt(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var no=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=$e(e,".popmelt");this.legacyFilePath=$e(t,"threads.json"),this.threadsDir=$e(t,"threads"),this.indexPath=$e(this.threadsDir,"index.json"),this.artifactsDir=$e(t,"artifacts","thread-messages"),this.mediaDir=$e(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Tt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[i,r]of Object.entries(e.files)){let s=await this.readThread($e(this.threadsDir,r));s&&(t[i]=s)}this.cache={version:1,threads:t};let n=!1;for(let i of Object.values(t))n=oi(i)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Tt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(Ut)}]))},this.index={...mn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))oi(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...cd,threads:{}},this.index={...mn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let t=await this.load(),n=new Set(e);for(let i of Object.values(t.threads))if(i.elementIdentifiers.some(s=>n.has(s)))return i;return null}async createThread(e,t){let n=await this.load(),i={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,t){let i=(await this.load()).threads[e];i&&(Zn(e,t),i.messages.push(Ut(t)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,t){let i=(await this.load()).threads[e];if(!i)return;Zn(e,t);let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Ut(t)):i.messages.push(Ut(t)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===t);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,n),c.error){let d=Ut(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of t)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((i,r)=>r.updatedAt-i.updatedAt),n.slice(0,e).map(i=>{let s=i.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]",c=i.messages.filter(l=>l.role==="assistant"),d=l=>{if(l.role!=="assistant")return;if(l.question)return l.question;let f=l.imprintSummary?.grounding;if(f?.question&&!l.imprintSummary?.resolvedAction)return f.question},u=i.messages.findLastIndex(l=>!!d(l)),I=i.messages.findLastIndex(l=>l.role==="human"),k=u>I?d(i.messages[u]):void 0,T=i.messages.at(-1)?.role,P=Array.from(new Set(i.messages.slice(0,Math.max(0,I)).filter(l=>l.role==="assistant"&&!!l.jobId).map(l=>l.jobId))),x=c.some(l=>!!l.responseText||!!l.question||!!l.result||!!l.memoryReviewCard||!!l.memoryReceipt),p=c.some(l=>!!l.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:x,hasError:p,lastMessageRole:T,pendingQuestion:k,acknowledgedJobIds:P,elementIdentifiers:i.elementIdentifiers,lifecycle:Or(i)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let i=n.messages.at(-1);if(!i||i.role!=="human"||/^(imprint|memory)-/.test(i.jobId))continue;let r=pn(i.lifecycle);i.queued&&await this.updateMessage(n.id,i.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:i.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await Tt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await Tt($e(to(this.legacyFilePath),i.path),"utf8");eo("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Ut({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=ld(e),n=pd(e);if(Object.keys(t).length===0)return n;let i=dd(t),r=eo("sha256").update(i).digest("hex"),s=$e("artifacts","thread-messages",`${r}.json`);await un(this.artifactsDir,{recursive:!0});try{await Tt($e(to(this.legacyFilePath),s),"utf8")}catch{await Ft($e(to(this.legacyFilePath),s),i)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(to(n)===this.mediaDir)return n;try{let i=await Tt(n),r=eo("sha256").update(i).digest("hex"),s=$e(this.mediaDir,`${r}${ad(n)||".bin"}`);await un(this.mediaDir,{recursive:!0});try{await Tt(s)}catch{await Ft(s,i)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,i])=>[n,await t(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,i])=>[n,await Promise.all(i.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,i])=>[n,await Promise.all(i.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await un(this.threadsDir,{recursive:!0});let t=this.index??{...mn,files:{}},n=t.files[e.id]??`${eo("sha256").update(e.id).digest("hex").slice(0,32)}.json`,i=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),r={...e,version:2,messages:i};await Ft($e(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await Ft(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await un(this.threadsDir,{recursive:!0}),this.index=this.index??{...mn,files:{}},await Ft(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...mn,files:{}},n=t.files[e];n&&await sd($e(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await un(this.threadsDir,{recursive:!0}),await Ft(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as ud,open as md,readFile as fd,rename as hd,unlink as gd}from"fs/promises";import{dirname as yd,join as vd}from"path";var Nr={schemaVersion:1,theme:"auto",updatedAt:null};function Jr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Id(o,e){await ud(yd(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await md(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
181
|
+
`,"utf8"),await n.sync()}finally{await n.close()}await hd(t,o)}catch(n){throw await gd(t).catch(()=>{}),n}}var oo=class{constructor(e){this.path=vd(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await fd(this.path,"utf8")),t=Jr(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Nr}}}catch{return{exists:!1,preferences:{...Nr}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Id(this.path,t),t}};function Br(o){return Jr(o)!==null}function Lr(o){return bd(o).slice(0,12)}var wd=[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 bd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):xd(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let T=7;T>=0;T--)e.push(t/Math.pow(2,T*8)&255);let n=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,u=528734635,I=1541459225,k=new Array(64);for(let T=0;T<e.length;T+=64){for(let b=0;b<16;b++){let g=T+b*4;k[b]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let b=16;b<64;b++){let g=Ze(k[b-15],7)^Ze(k[b-15],18)^k[b-15]>>>3,B=Ze(k[b-2],17)^Ze(k[b-2],19)^k[b-2]>>>10;k[b]=k[b-16]+g+k[b-7]+B>>>0}let P=n,x=i,p=r,l=s,f=c,m=d,h=u,j=I;for(let b=0;b<64;b++){let g=Ze(f,6)^Ze(f,11)^Ze(f,25),B=f&m^~f&h,E=j+g+B+wd[b]+k[b]>>>0,R=Ze(P,2)^Ze(P,13)^Ze(P,22),N=P&x^P&p^x&p,V=R+N>>>0;j=h,h=m,m=f,f=l+E>>>0,l=p,p=x,x=P,P=E+V>>>0}n=n+P>>>0,i=i+x>>>0,r=r+p>>>0,s=s+l>>>0,c=c+f>>>0,d=d+m>>>0,u=u+h>>>0,I=I+j>>>0}return[n,i,r,s,c,d,u,I].map(T=>T.toString(16).padStart(8,"0")).join("")}function Ze(o,e){return o>>>e|o<<32-e}function xd(o){let e=[];for(let t=0;t<o.length;t++){let n=o.charCodeAt(t);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}function Sd(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function qr(o){let e=o.annotations.flatMap(i=>{let r=Sd(i);return r?[{instruction:r,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
|
|
182
|
+
|
|
183
|
+
`);let n=new Map;for(let i of e){let r=i.pathname||"(unknown)",s=n.get(r)??[];s.push(i.instruction),n.set(r,s)}return[...n.entries()].map(([i,r])=>`\`${i}\`
|
|
184
|
+
${r.map(s=>`- ${s}`).join(`
|
|
185
|
+
`)}`).join(`
|
|
186
|
+
`)}var Fr={name:"@popmelt.com/core",version:"0.8.15",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","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 fn=Fr.version;var Nd=1111,Jd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Bd=1800*1e3,Ld=3600*1e3,Wr=45e3,qd=5e3,Fd=1e4,Ud=2*1024*1024;function Gr(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
|
|
187
|
+
`)}function hn(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Hr(o){let e=o.findLastIndex(i=>i.role==="assistant");if(e<0)return[];let t=o[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=o.slice(0,e).findLast(i=>i.role==="assistant"&&i.imprintSummary?.resolvedAction==="no"&&!!i.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function zd(o,e){if(e.size===1)return[...o].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function Xr(o){if(!o)return!1;try{let e=new URL(o);return e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}catch{return!1}}function Wd(o,e,t){let n=[...t];for(let i of o)if(i.type==="tool_use"){let r=i.tool||"",s=i.file??void 0,c=i.content??void 0,d=s?s.split("/").pop()??s:void 0,u;switch(r){case"Read":u=d?`Reading ${d}`:"Reading file";break;case"Edit":u=d?`Editing ${d}`:"Editing file";break;case"Write":u=d?`Writing ${d}`:"Writing file";break;case"Bash":u=c?c.split(`
|
|
188
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":u="Searching files";break;case"Grep":u="Searching code";break;case"WebFetch":u="Fetching page";break;case"WebSearch":u="Searching web";break;default:u=r?`Using ${r}`:"tool";break}let I=s??c??void 0,k=s?Qr(s)?s:Od(e,s):void 0,T=n[n.length-1];T&&T.kind==="tool_group"&&T.tool===r?T.items.push({label:u,detail:I,...k?{filePath:k}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:u,detail:I,...k?{filePath:k}:{}}]})}return n}function Gd(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
|
|
189
|
+
`)}function Hd(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Vr(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),t=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),i=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;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}`}),r=[...e,...n,...t,...i].map(s=>Hd(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Vd(o,e){let t=o.headers.origin;Xr(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}async function Oe(o){let e=[],t=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(t+=r.length,t>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let n=JSON.parse(Buffer.concat(e).toString("utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object");return n}async function Kd(o,e){let t=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>e)throw new Error("Request body too large");t.push(r)}return Buffer.concat(t)}function Qd(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function Xd(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,i,r]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function so(o,e){try{o.res.write(`event: ${e.type}
|
|
182
190
|
data: ${JSON.stringify(e)}
|
|
183
191
|
|
|
184
|
-
`)}catch{}}function zt(
|
|
192
|
+
`)}catch{}}function zt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Yd(o){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}function Zd(o,e){return new Promise((t,n)=>{let i=s=>{o.removeListener("listening",r),n(s)},r=()=>{o.removeListener("error",i),t()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function Yr(o={}){let e=new Date().toISOString(),t=o.port??Nd,n=o.projectRoot??process.cwd(),i=await jd(n).catch(()=>n),r=Lr(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??De(_d(),"popmelt-bridge"),d=o.maxTurns??40,u=o.maxBudgetUsd??1,I=[...o.allowedTools??Jd],k=o.claudePath??"claude",T=o.copilotPath??"copilot",P=o.provider??"claude",x=o.timeoutMs,p=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,l=o.restartMode??"embedded",f=t,m={},h={claude:k,codex:"codex",copilot:T};for(let[a,y]of Object.entries(h))try{let M=y.includes("/")?y:kd("which",[y],{encoding:"utf-8"}).trim();m[a]={available:!0,path:M}}catch{m[a]={available:!1,path:null}}function j(a,y){return new Promise(M=>{let v=Ur(y,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,S=$=>{A||(A=!0,M($))},C=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout(C),S(!1)}),v.on("close",$=>{clearTimeout(C),S($===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await wr(m.claude.path).catch(()=>Wn):Wn)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await Ir(m.codex.path).catch(()=>cn):cn)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await vr(m.copilot.path).catch(()=>[dn]):[dn])})()]);let[b,g,B]=await Promise.all([Ro(i),Po(i),jo(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=b),m.codex&&(m.codex.mcp=g),m.copilot&&(m.copilot.mcp=B),b.found&&b.name&&I.push(`mcp__${b.name}__*`),await Rd(c,{recursive:!0}),Kr(c).catch(()=>{});let E=new Hn(1),R=new An,N=new En(Wr),V=null,K=0,G=!1,Q=()=>{K+=1,G=!1,V&&clearTimeout(V),V=null},w=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},H=()=>{if(l!=="detached"||N.size>0||G)return;G=!0;let a=++K,y=Date.now()+Fd,M=()=>{if(a!==K)return;if(N.size>0){Q();return}if(!(E.isRunning||E.depth>0||R.isRunning||R.depth>0)||Date.now()>=y){G=!1,V=setTimeout(w,50),V.unref?.();return}V=setTimeout(M,250),V.unref?.()};M()},L=new Set,O=new no(i),he=await O.recoverInterruptedTurns();he>0&&console.warn(`[Popmelt] Recovered ${he} interrupted thread turn(s) from durable history.`);let J=new kn(i);J.sweep();let D=new Fn(i),Y=new ln(i,r);try{let a=await Y.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let ce=new oo(i),ke=new bn(i),se=new jn(i,{claudePath:k,provider:P,timeoutMs:x,loadProjectableDecisions:a=>D.getProjectableDecisions(a),onEvent:a=>{for(let y of L)so(y,a)}});D.beginAutomaticInitialization({writerVersion:fn}).then(async a=>{a.state==="ready"?(await D.migrateImprintSnapshot(),await D.syncImprintGraph(),await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),P!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await ft({provider:P,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${f}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let Ue=20,Ge=300*1e3,Pe=[];function rt(){let a=Date.now()-Ge;for(;Pe.length>0&&(Pe[0].completedAt<a||Pe.length>Ue);)Pe.shift()}let He=new Map,st=null,Wt;E.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&so(v,a)}),R.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&so(v,a)}),R.setProcessor(async a=>{let y=a.provider??P;try{let M=await se.run({provider:y,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),A=M.runId?v.runs.find(C=>C.id===M.runId):void 0;if(M.success&&M.proposalId){let C=await se.findModelProposal(M.proposalId),$=await se.loadModel(),q=C?Ri(C,$):null;if(C&&q){let W=C.decisionIds.map(U=>({decisionId:U,status:"projected"}));await D.applyModelProjection({runId:C.runId??C.id,presentationJobId:C.presentationJobId,decisionIds:C.decisionIds,changes:q.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:W}),await se.applySelectedModelProposal(C.id,q.map(U=>({path:U.path,value:U.value})),q.map(U=>({group:U.path[0]==="rules"||U.path[0]==="components"||U.path[0]==="tokens"?U.path[0]:"model",label:U.label??U.id,detail:U.rationale,path:U.path,value:U.value})),"automatic")}}let S=Gd(M,A);if(a.threadId&&(await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:y})),M.success)a.status="done",a.result=S,R.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),rt();else{if(a.status="error",a.error=M.error??"Projection failed",a.threadId){let C=`Model projection failed.
|
|
185
193
|
|
|
186
|
-
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),
|
|
194
|
+
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),rt()}}catch(M){if(a.status==="cancelled")return;if(a.status="error",a.error=M instanceof Error?M.message:String(M),a.threadId){let v=`Model projection failed.
|
|
187
195
|
|
|
188
|
-
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:
|
|
196
|
+
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),rt()}}),E.setProcessor(async a=>{let y=a,M=y._replyPrompt,v=y._replyText,A=y._replyImagePaths,S=a.provider??P,C=!!(a.surfacedProposalIds?.length&&M),$=!C&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&v!==void 0&&await O.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let oe=await O.getThread(a.threadId);if(oe){for(let ue=oe.messages.length-1;ue>=0;ue--)if(oe.messages[ue].sessionId){q=oe.messages[ue].sessionId;break}}}C&&(q=void 0);let W;if(q&&M){if(W=v??M,A&&A.length>0){W+=`
|
|
189
197
|
|
|
190
|
-
The developer attached reference images with their reply:`;for(let
|
|
191
|
-
Attached image: use the Read tool to view the image at: ${
|
|
198
|
+
The developer attached reference images with their reply:`;for(let oe of A)W+=`
|
|
199
|
+
Attached image: use the Read tool to view the image at: ${oe}`}a.kind==="synthesize"?W+=`
|
|
192
200
|
|
|
193
|
-
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:
|
|
201
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:W+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(q)W=sn(a.feedback,a.imagePaths,a.attachmentFiles)+`
|
|
194
202
|
|
|
195
203
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
196
204
|
|
|
197
205
|
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
198
206
|
|
|
199
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let
|
|
207
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let oe=!M&&a.threadId?await O.getThreadHistory(a.threadId):void 0,ue=M?null:await se.loadModel();W=M??ur(a.screenshotPath,a.feedback,{threadHistory:oe&&oe.length>0?oe:void 0,provider:S,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:ue??void 0,screenshotPaths:a.screenshotPaths})}W+=rr(a.memoryReview),$&&(W+=Yo(a.imprintContext,{requestText:v??Bt(a.feedback)})),W+=`
|
|
200
208
|
|
|
201
|
-
${pr}`;let q=Vd(a.color,`[\u22B9 ${h}:${a.id}]`),le=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${q} Reviewing ${le} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let U=new Un(a.id),ue=(ie,me)=>{if(ie.type==="delta"&&"text"in ie){let Ee=U.push(ie.text);Ee.visibleText&&(E.accumulateText(me,"response",Ee.visibleText),E.broadcast({...ie,text:Ee.visibleText},me,a.sourceId));for(let Xe of Ee.orientations)E.broadcast({type:"orientation",jobId:me,orientation:Xe},me,a.sourceId);return}else ie.type==="thinking"&&"text"in ie&&E.accumulateText(me,"thinking",ie.text);E.broadcast(ie,me,a.sourceId)},{process:de,result:ne}=S==="codex"?wn(a.id,{prompt:z,projectRoot:o,screenshotPath:a.screenshotPath,resumeSessionId:F,model:a.model,sandboxMode:C?"read-only":void 0,configOverrides:yn(a.agentSettings),onEvent:ue}):S==="copilot"?Io(a.id,{prompt:z,projectRoot:o,resumeSessionId:F,model:a.model,timeoutMs:v,copilotPath:u.copilot?.path??k,onEvent:ue}):vn(a.id,{prompt:z,projectRoot:o,maxTurns:d,maxBudgetUsd:p,allowedTools:C?["Read"]:x,claudePath:T,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:v,onEvent:ue});E.setActiveProcess(a.id,de);let X=await ne,Se=[...(X.fileEdits??[]).map(ie=>ie.file_path),...(X.editEvents??[]).flatMap(ie=>ie.filePath?[ie.filePath]:[])],be=Wi(X.text,a.id),Ae=U.finalize(X.text),he=be.visibleText,ee=hr(he),ge=$?Qi(he,{context:a.imprintContext,requestText:I??Bt(a.feedback),applicationOccurred:Se.length>0||ee.some(ie=>ie.status==="resolved")}):{visibleText:he,draft:void 0,error:void 0},Be=ge.visibleText,Te=$?ge.error?{state:ge.error.includes("missing")?"missing":"invalid",reason:ge.error}:ge.draft?.decision==="none"?{state:"none",reason:ge.draft.reason}:ge.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let ie of Ae.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:ie},a.id,a.sourceId);if(a.result=Be,X.success){console.log(`${q} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${q} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(re=>`${re.tool} ${re.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${q} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(re=>`${re.operation} ${re.filePath}`).join(", ")}`),a.status="done";let ie=mr(he),me=ee;if(me.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);me.every(gt=>re.has(gt.annotationId))||(me=me.map((gt,yt)=>({...gt,annotationId:a.annotationIds[yt%a.annotationIds.length]})))}let Ee=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(re=>`${re.tool} ${re.file_path.split("/").pop()}`):X.toolsUsed,Xe=E.getBufferedEvents(a.id),Ue=qd(Xe?.events??[],o,be.segments),Le,Y=ar(he),pe=sr(he);if(pe)if(!(a.memoryReview?.packets.some(ce=>ce.proposalId===pe.proposalId)||a.surfacedProposalIds?.includes(pe.proposalId)))Le={status:"rejected",action:pe.action,proposalId:pe.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Le=await D.commitConversationalReview(pe)}catch(ce){Le={status:"rejected",action:pe.action,proposalId:pe.proposalId,message:ce instanceof Error?ce.message:String(ce)}}let Me=gr(he,Se.length),W,ye,Ie=a.imprintContext?.pendingGroundingExplanationIds??[];ge.draft?.decision==="none"&&Z.recordNoop(ge.draft.reason);let Fe=ge.draft?.decision==="recognize"?ge.draft:void 0;if(Fe&&!pe&&!Y){let re=a.imprintContext?.explanations.find(ce=>ce.id===Fe.explanationId&&ce.state==="grounded");re?ye={explanationId:re.id,title:Fe.summary.title,detail:Fe.summary.detail,statement:re.statement}:Te={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let pi=ge.draft?.decision==="mutate"||ge.draft?.decision==="apply"?ge.draft:void 0;if(a.threadId&&pi&&!pe&&!Y)try{W=await Z.capture(pi,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:Ie,applicationOccurred:Se.length>0||me.some(re=>re.status==="resolved")}),W?(Te={state:"mutated"},await D.recordImprintEvidence({summary:W,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${q} Canonical Imprint evidence linkage failed:`,re))):Te={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Te={state:"invalid",reason:re instanceof Error?re.message:String(re)},console.warn(`${q} Continuous imprint update failed; the thread result remains available:`,re instanceof Error?re.message:String(re))}else pi&&(Te={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ge.error&&console.warn(`${q} Ignored invalid imprint block: ${ge.error}`),(Te.state==="missing"||Te.state==="invalid")&&Z.recordAssessmentFailure(Te.state);let ui=W?.transactionId;if(a.threadId&&W&&!W.grounding){let re=await O.getThread(a.threadId),ce=new Set(W.changes.map(yt=>yt.explanationId)),gt=re?Fd(re.messages,ce):void 0;if(gt?.imprintSummary){let yt=gt.imprintSummary;await O.updateAssistantMessage(a.threadId,gt.jobId,{imprintSummary:{...yt,detail:W.detail,changes:W.changes,additionalObservationCount:(yt.additionalObservationCount??0)+1,coalescedTransactionIds:[...yt.coalescedTransactionIds??[],W.transactionId]}}),W=void 0}}let mi=Zi({question:ie,resolutions:me,changedFiles:Se,decisionRequired:!!Y,imprintTransactionId:ui,groundingRequired:!!W?.grounding}),us=Ue?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],Pt=a.lifecycle?pn(a.lifecycle,ui?[ui]:[],Te):void 0;if(a.threadId){let re=C?Y?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Be;await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:re,resolutions:!C&&me.length>0?me:void 0,question:C?void 0:ie??void 0,sessionId:X.sessionId,toolsUsed:C?void 0:Ee,editEvents:!C&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!C&&Ue&&Ue.length>0?Ue:void 0,turn:{phase:"complete",orientation:us,result:mi},result:mi,memoryReviewCard:Y??void 0,memoryReceipt:Le,imprintSummary:W,imprintRecognition:ye,modelDetails:Me.length>0?Me:void 0,model:a.model,provider:S,...Pt?{lifecycle:Pt}:{}})}if(a.threadId&&!pe&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let re=a.feedback.annotations.flatMap(ce=>ce.linkedSelector?[ce.pathname?`${ce.pathname}:${ce.linkedSelector}`:ce.linkedSelector]:[]);try{await D.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:I??(Bt(a.feedback)||"[request unavailable]"),responseSummary:ie??Be,outcome:ie?"question_asked":me.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:re,filePaths:[...(X.fileEdits??[]).map(ce=>ce.file_path),...(X.editEvents??[]).flatMap(ce=>ce.filePath?[ce.filePath]:[])].map(ce=>Vr(ce)?Ed(o,ce):ce),resolutions:me.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:Pt?.submissionIds,outcomeId:Pt?.outcomeId,imprintEvidenceIds:Pt?.imprintEvidenceIds,imprintAssessment:Pt?.imprintAssessment})}catch(ce){console.warn(`${q} Canonical memory capture failed; iteration remains available in legacy history:`,ce instanceof Error?ce.message:String(ce))}}Le?.status==="committed"&&Le.decisionId&&S!=="copilot"&&await ft({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Le.decisionId}`}),ie&&(console.log(`${q} \u{1F4AC} Question detected: "${ie.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),E.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:ie,annotationIds:a.annotationIds},a.id,a.sourceId)),Me.length>0&&(console.log(`${q} Applied model gap(s): ${Me.map(re=>`${re.category}/${re.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:Me,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:me.length>0?me:void 0,responseText:Be,threadId:a.threadId,annotationIds:a.annotationIds,result:mi},a.id,a.sourceId),je.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${q} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:S,...a.lifecycle?{lifecycle:pn(a.lifecycle)}:{}}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:S,model:a.model,recoverable:X.recoverableError,code:X.errorCode},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});at()});let Tt=jd(async(a,y)=>{if(Wd(a,y),a.method==="OPTIONS"){y.writeHead(204),y.end();return}let M=a.url||"/",I=M.split("?")[0],A=new URL(M,`http://127.0.0.1:${h}`),S=A.pathname,C=Hd(a,A);if(C&&C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:ri(o)});return}if(a.headers.origin){if(!Kr(a.headers.origin)){_(y,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:ri(o)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let $=A.searchParams.get("annotationId")?.trim()??"",F=A.searchParams.get("name")?.trim()??"",z=A.searchParams.get("kind"),q=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(y,400,{error:"A valid annotationId is required."});return}if(z!=="svg"&&z!=="text"||z==="svg"&&q!=="image/svg+xml"||z==="text"&&q!=="text/plain"){_(y,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let le=await Gd(a,Ld);if(le.length===0){_(y,400,{error:"Attachment is empty."});return}let U=await J.stage({annotationId:$,name:F,mimeType:q,kind:z,data:le});_(y,201,{attachment:{id:U.id,name:U.name,mimeType:U.mimeType,size:U.size,kind:U.kind}})}else if(a.method==="POST"&&S==="/draft-attachments/claim"){let $=await Oe(a),F=Array.isArray($.ids)?$.ids.filter(z=>typeof z=="string").slice(0,100):[];await J.claim(F),_(y,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await J.release([S.slice(19)]),_(y,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await dt(a,y);else if(a.method==="POST"&&S==="/capture/native"){if(!f){_(y,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await Oe(a),F=typeof $.pageUrl=="string"?$.pageUrl:"",z=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!F||!z){_(y,400,{error:"pageUrl and clip are required."});return}let q=await Jo(f,{pageUrl:F,clip:{x:Number(z.x),y:Number(z.y),width:Number(z.width),height:Number(z.height)},scale:typeof $.scale=="number"?$.scale:1});y.writeHead(200,{"Content-Type":"image/webp","Content-Length":q.length,"Cache-Control":"no-store"}),y.end(q)}else if(a.method==="GET"&&S==="/events")tt(a,y);else if(a.method==="GET"&&S==="/status")await lt(a,y,C);else if(a.method==="GET"&&S==="/ui-preferences")await mt(y);else if(a.method==="PATCH"&&S==="/ui-preferences")await ci(a,y);else if(a.method==="PATCH"&&S==="/config")await pt(a,y);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Oe(a),F=typeof $.leaseId=="string"?$.leaseId.trim():"",z=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!F||F.length>128){_(y,400,{error:"A valid leaseId is required."});return}Q();let q=N.acquire(F,z);_(y,201,{ok:!0,lease:q,ttlMs:zr})}catch{_(y,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(S.slice(8))}catch{_(y,400,{error:"Invalid lease id."});return}if(!$){_(y,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let F=N.heartbeat($);if(!F){_(y,404,{error:"Lease not found."});return}_(y,200,{ok:!0,lease:F})}else{let F=N.release($);_(y,F.found?200:404,{ok:F.found}),F.becameEmpty&&H()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0}),setTimeout(w,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of L)try{$.res.end()}catch{}Tt.close(()=>{qr(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(y,200,{providers:u});else if(S.startsWith("/imprint/"))await xe(a,y,S);else if(S.startsWith("/memory/"))await ai(a,y,S);else if(a.method==="POST"&&S==="/mcp/install")await li(a,y);else if(a.method==="POST"&&S==="/reply")await _e(a,y);else if(a.method==="POST"&&S==="/cancel")di(a,y);else if(a.method==="POST"&&S==="/materialize")_(y,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(y,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let $=await se.loadRuns();_(y,200,$)}else if(a.method==="GET"&&S==="/projection/proposals"){let $=await se.loadModelProposals();_(y,200,$)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let $=S.slice(22,-15);await Je($,a,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let $=S.slice(22,-6);await Ne($,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let $=S.slice(22,-8);await ut($,a,y)}else if(S.startsWith("/model/proposals/"))_(y,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await gn(a,y);else if(a.method==="DELETE"&&S==="/model/component")await ns(a,y);else if(a.method==="PATCH"&&S==="/model/token")await is(a,y);else if(a.method==="DELETE"&&S==="/model/token")await os(a,y);else if(a.method==="POST"&&S==="/model/consolidate")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let $=await se.loadModel();_(y,200,{model:$})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let $=S.slice(6,S.length-7),F=parseInt(A.searchParams.get("afterSeq")??"-1",10),z=E.getBufferedEvents($,isNaN(F)?-1:F);z?_(y,200,z):_(y,404,{error:"Unknown job"})}else if(a.method==="GET"&&I.startsWith("/files/"))await cs(I.slice(7),y);else if(a.method==="GET"&&S==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),F=await O.listRecent($);_(y,200,F)}else if(a.method==="GET"&&S.startsWith("/decision/")){let $=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(y,400,{error:"Invalid decision id"});else{let F=await O.getThread($),z=[...F?.messages??[]].reverse().find(q=>q.annotationSnapshot);if(F&&z?.annotationSnapshot){let q=[...F.messages].reverse().find(le=>le.resolutions?.length);_(y,200,{decision:{id:F.id,createdAt:z.timestamp,url:z.annotationSnapshot.url,viewport:z.annotationSnapshot.viewport,color:z.annotationSnapshot.color,annotations:z.annotationSnapshot.annotations,resolutions:q?.resolutions??[]},authority:"thread_snapshot"})}else{let q=await Re.loadDecision($);q?_(y,200,{decision:q,authority:"legacy_archive"}):_(y,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let $=S.slice(8);await ds($,y)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let $=S.slice(8);await ls($,y)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?rs(a,y):a.method==="GET"&&S==="/canvas/manifest"?await ss(y):a.method==="GET"&&S==="/canvas/app.mjs"?await as(y):_(y,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(y,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function ai(a,y,M){try{if(a.method==="GET"&&M==="/memory/status"){_(y,200,await D.status());return}if(a.method==="GET"&&M==="/memory/diagnostics"){_(y,200,await D.diagnostics());return}if(a.method==="GET"&&M==="/memory/model-view"){_(y,200,await D.getModelView());return}if(a.method==="GET"&&M==="/memory/imprint-view"){let I=await O.load(),A=[...new Set(Object.values(I.threads).flatMap(S=>hn(S.messages)))];_(y,200,await D.getImprintView(A,new Set(Object.keys(I.threads))));return}if(a.method==="POST"&&M==="/memory/constraints"){let I=await Oe(a),A=typeof I.reactComponent=="string"?I.reactComponent.trim():"",S=await D.getModelView(),C=A?S.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(y,200,{modelEntries:C});return}if(a.method==="POST"&&M==="/memory/conversation-action"){let I=await Oe(a),A=typeof I.threadId=="string"?I.threadId:"",S=typeof I.proposalId=="string"?I.proposalId:"",C=String(I.action);if(!A||!S||!["accept","edit_and_accept","reject","defer"].includes(C)){_(y,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await O.getThread(A),F=$?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!$||!F){_(y,409,{error:"This decision review card is not available in the thread."});return}let z=await se.findModelProposalsByThread(A),q=(await Promise.all(z.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(Se=>D.findPendingProposalForLegacyDecision(Se)))).some(Se=>Se?.proposalId===S)})))).find(X=>X.matches)?.proposal,le={proposalId:S,action:C,kind:F.kind,claim:C==="edit_and_accept"&&typeof I.claim=="string"?I.claim.trim():void 0,reason:C==="defer"?void 0:`The owner explicitly chose ${C.replaceAll("_"," ")} from the decision review card.`,taskContext:C==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:C==="defer"?["different_action","owner_request"]:void 0};if(le.action==="edit_and_accept"&&!le.claim){_(y,400,{error:"Edited decision wording is required."});return}let U=await D.commitConversationalReview(le),ue=`memory-${st().slice(0,8)}`,de=C==="accept"?"> Accepted decision":C==="edit_and_accept"?"> Edited and accepted decision":C==="reject"?"> Rejected decision":"> Deferred decision";await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:ue,replyToQuestion:de}),await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:ue,responseText:"",memoryReceipt:U,provider:zt(typeof I.provider=="string"?I.provider:void 0),model:typeof I.model=="string"?I.model:void 0}),U.status==="committed"&&q&&await se.dismissModelProposal(q.id);let ne=zt(typeof I.provider=="string"?I.provider:void 0);U.status==="committed"&&U.decisionId&&ne!=="copilot"&&await ft({provider:ne,model:typeof I.model=="string"?I.model:void 0,agentSettings:jt(I),threadId:A,reason:`Project accepted decision ${U.decisionId}`}),_(y,U.status==="committed"?200:409,{receipt:U});return}if(a.method==="POST"&&M==="/memory/analyze"){let I=await Oe(a),A=await D.analyzeLegacy({projectKey:typeof I.projectKey=="string"?I.projectKey:void 0}),S=Object.fromEntries([...new Set(A.issues.map(C=>C.code))].map(C=>[C,A.issues.filter($=>$.code===C).length]));_(y,200,{...A,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&M==="/memory/review"){let I=await Oe(a),A=await D.review(Fi(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/context"){let I=await Oe(a),A=await D.contextualize(Fi(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/initialize"){let I=await Oe(a),A=await D.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:fn});_(y,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&M==="/memory/plan"){let I=await Oe(a),A=await D.planReview(Li(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(y,A.result.ok?200:422,A);return}if(a.method==="POST"&&M==="/memory/commit"){let I=await Oe(a),A=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},S=await D.commitReview(Li(I.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(y,200,{status:await D.status(),journal:S.report});return}if(a.method==="POST"&&M==="/memory/recover"){let I=await Oe(a),A=await D.recover(I.confirm===!0);_(y,200,{status:await D.status(),journal:A.report});return}_(y,404,{error:"Memory endpoint not found."})}catch(I){let A=I instanceof Error?I.message:String(I),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),C=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(S||C){_(y,S?409:400,{error:A});return}throw I}}async function xe(a,y,M){if(a.method==="GET"&&M==="/imprint/status"){let[I,A]=await Promise.all([Z.store.load(),O.load()]),S=[...new Set(Object.values(A.threads).flatMap(C=>hn(C.messages)))].filter(C=>I.graph.explanations.some($=>$.id===C&&$.state==="testing"));_(y,200,{state:"ready",head:I.graph.head,updatedAt:I.graph.updatedAt,explanationCount:I.graph.explanations.filter(C=>C.state!=="retired").length,concreteCount:I.graph.concrete.length,relationCount:I.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:I.recoveredTransactions,admission:Z.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&M==="/imprint/action"){let I=await Oe(a),A=typeof I.threadId=="string"?I.threadId:"",S=typeof I.transactionId=="string"?I.transactionId:"",C=String(I.action);if(!A||!S||!["yes","this_time","no"].includes(C)){_(y,400,{error:"A valid thread, imprint update, and action are required."});return}let F=await O.getThread(A),z=[...F?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),q=z?.imprintSummary;if(!F||!z||!q){_(y,409,{error:"This imprint summary is not available in the thread."});return}if(q.resolvedAction){_(y,409,{error:"This imprint summary has already been resolved."});return}let le=`imprint-${st().slice(0,8)}`;await Z.applyGroundingAction({summary:q,action:C,threadId:A,jobId:le}),await D.recordImprintEvidence({summary:q,action:C,threadId:A,jobId:le}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let U=Ft(z.result,!!z.question),ue=z.turn?{...z.turn,result:Ft(z.turn.result,!!z.question)}:void 0;await O.updateAssistantMessage(A,z.jobId,{imprintSummary:{...q,resolvedAction:C},...U?{result:U}:{},...ue?{turn:ue}:{}});let de={yes:"> Yes",this_time:"> This time",no:"> No"};if(await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:le,replyToQuestion:de[C]}),C==="no"){let ne="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",X=Zi({question:ne});await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:le,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ne,turn:{phase:"complete",orientation:[],result:X},result:X})}_(y,200,{ok:!0,action:C});return}_(y,404,{error:"Imprint endpoint not found."})}async function dt(a,y){let{screenshot:M,feedback:I,color:A,provider:S,model:C,reasoningEffort:$,serviceTier:F,sourceId:z,pastedImages:q,pageScreenshots:le}=await qi(a),U;try{U=JSON.parse(I)}catch{_(y,400,{error:"Invalid feedback JSON"});return}let ue=U.annotations.flatMap(Y=>(Y.attachments??[]).map(pe=>({id:pe.id,annotationId:Y.id}))),de;try{de=ue.length>0?await J.promote(ue):void 0}catch(Y){_(y,409,{error:Y instanceof Error?Y.message:"Draft attachment unavailable."});return}let ne=st().slice(0,8),X={};if(le.length>0)for(let Y of le){let pe=encodeURIComponent(Y.pathname),Me=De(c,`screenshot-${ne}-${pe}.webp`);await oi(Me,Y.data),X[Y.pathname]=Me}let Se=De(c,`screenshot-${ne}.webp`);await oi(Se,M);let be={};if(q.length>0)for(let Y of q){let pe=De(c,`pasted-${ne}-${Y.annotationId}-${Y.index}.webp`);await oi(pe,Y.data),be[Y.annotationId]||(be[Y.annotationId]=[]),be[Y.annotationId].push(pe)}let Ae=Cr(U),he;if(Ae.length>0){let Y=await O.findContinuationThread(Ae);Y?(he=Y.id,await O.addElementIdentifiers(he,Ae)):he=(await O.createThread(`thread-${st()}`,Ae)).id}else he=(await O.createThread(`thread-${st()}`,[])).id;let ee=U.annotations.map(Y=>Y.id),ge=Object.keys(X).length>0,Be=await or(D,U,Ae,Y=>console.warn(`[\u22B9 ${h}:${ne}] Contextual memory unavailable; continuing without it:`,Y instanceof Error?Y.message:String(Y))),Te=await Z.contextualize({text:Bt(U),subjectHints:[...Ae,...U.annotations.flatMap(Y=>[Y.pathname,Y.elements?.[0]?.reactComponent].filter(pe=>!!pe))],pendingGroundingExplanationIds:hn((await O.getThread(he))?.messages??[])}).catch(Y=>{console.warn(`[\u22B9 ${h}:${ne}] Imprint context unavailable; continuing without it:`,Y instanceof Error?Y.message:String(Y))}),ie=to({jobId:ne,threadId:he,artifactIds:$r(U,ne)}),me={id:ne,status:"queued",screenshotPath:Se,feedback:U,createdAt:Date.now(),color:A,threadId:he,annotationIds:ee,provider:zt(S),model:C||void 0,agentSettings:jt({reasoningEffort:$,serviceTier:F}),...Object.keys(be).length>0?{imagePaths:be}:{},...de&&Object.keys(de).length>0?{attachmentFiles:de}:{},sourceId:z||void 0,...ge?{screenshotPaths:X}:{},...Be?{memoryReview:Be}:{},...Te?{imprintContext:Te}:{},lifecycle:ie},Ee=new Set(U.annotations.map(Y=>Y.pathname).filter(Boolean)),Xe;if(Ee.size>1){let Y=new Map;for(let pe of U.annotations){let Me=pe.pathname||"(unknown)";Y.has(Me)||Y.set(Me,[]),Y.get(Me).push(pe.instruction||Gr({...U,annotations:[pe]}))}Xe=[...Y.entries()].map(([pe,Me])=>`\`${pe}\`
|
|
202
|
-
${
|
|
209
|
+
${pr}`;let U=Xd(a.color,`[\u22B9 ${f}:${a.id}]`),pe=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${U} Reviewing ${pe} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let z=new Un(a.id),me=(oe,ue)=>{if(oe.type==="delta"&&"text"in oe){let Me=z.push(oe.text);Me.visibleText&&(E.accumulateText(ue,"response",Me.visibleText),E.broadcast({...oe,text:Me.visibleText},ue,a.sourceId));for(let pt of Me.orientations)E.broadcast({type:"orientation",jobId:ue,orientation:pt},ue,a.sourceId);return}else oe.type==="thinking"&&"text"in oe&&E.accumulateText(ue,"thinking",oe.text);E.broadcast(oe,ue,a.sourceId)},{process:le,result:ne}=S==="codex"?wn(a.id,{prompt:W,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:C?"read-only":void 0,configOverrides:yn(a.agentSettings),onEvent:me}):S==="copilot"?Ii(a.id,{prompt:W,projectRoot:i,resumeSessionId:q,model:a.model,timeoutMs:x,copilotPath:m.copilot?.path??T,onEvent:me}):vn(a.id,{prompt:W,projectRoot:i,maxTurns:d,maxBudgetUsd:u,allowedTools:C?["Read"]:I,claudePath:k,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:x,onEvent:me});E.setActiveProcess(a.id,le);let X=await ne,xe=[...(X.fileEdits??[]).map(oe=>oe.file_path),...(X.editEvents??[]).flatMap(oe=>oe.filePath?[oe.filePath]:[])],we=Go(X.text,a.id),je=z.finalize(X.text),ge=we.visibleText,Z=hr(ge),fe=$?Xo(ge,{context:a.imprintContext,requestText:v??Bt(a.feedback),applicationOccurred:xe.length>0||Z.some(oe=>oe.status==="resolved")}):{visibleText:ge,draft:void 0,error:void 0},Be=fe.visibleText,Ae=$?fe.error?{state:fe.error.includes("missing")?"missing":"invalid",reason:fe.error}:fe.draft?.decision==="none"?{state:"none",reason:fe.draft.reason}:fe.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let oe of je.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:oe},a.id,a.sourceId);if(a.result=Be,X.success){console.log(`${U} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${U} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(re=>`${re.tool} ${re.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${U} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(re=>`${re.operation} ${re.filePath}`).join(", ")}`),a.status="done";let oe=mr(ge),ue=Z;if(ue.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);ue.every(gt=>re.has(gt.annotationId))||(ue=ue.map((gt,yt)=>({...gt,annotationId:a.annotationIds[yt%a.annotationIds.length]})))}let Me=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(re=>`${re.tool} ${re.file_path.split("/").pop()}`):X.toolsUsed,pt=E.getBufferedEvents(a.id),_e=Wd(pt?.events??[],i,we.segments),Le,qe=ar(ge),Se=sr(ge);if(Se)if(!(a.memoryReview?.packets.some(de=>de.proposalId===Se.proposalId)||a.surfacedProposalIds?.includes(Se.proposalId)))Le={status:"rejected",action:Se.action,proposalId:Se.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Le=await D.commitConversationalReview(Se)}catch(de){Le={status:"rejected",action:Se.action,proposalId:Se.proposalId,message:de instanceof Error?de.message:String(de)}}let ee=gr(ge,xe.length),F,ae,ve=a.imprintContext?.pendingGroundingExplanationIds??[];fe.draft?.decision==="none"&&Y.recordNoop(fe.draft.reason);let Fe=fe.draft?.decision==="recognize"?fe.draft:void 0;if(Fe&&!Se&&!qe){let re=a.imprintContext?.explanations.find(de=>de.id===Fe.explanationId&&de.state==="grounded");re?ae={explanationId:re.id,title:Fe.summary.title,detail:Fe.summary.detail,statement:re.statement}:Ae={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let uo=fe.draft?.decision==="mutate"||fe.draft?.decision==="apply"?fe.draft:void 0;if(a.threadId&&uo&&!Se&&!qe)try{F=await Y.capture(uo,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:ve,applicationOccurred:xe.length>0||ue.some(re=>re.status==="resolved")}),F?(Ae={state:"mutated"},await D.recordImprintEvidence({summary:F,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${U} Canonical Imprint evidence linkage failed:`,re))):Ae={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Ae={state:"invalid",reason:re instanceof Error?re.message:String(re)},console.warn(`${U} Continuous imprint update failed; the thread result remains available:`,re instanceof Error?re.message:String(re))}else uo&&(Ae={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});fe.error&&console.warn(`${U} Ignored invalid imprint block: ${fe.error}`),(Ae.state==="missing"||Ae.state==="invalid")&&Y.recordAssessmentFailure(Ae.state);let mo=F?.transactionId;if(a.threadId&&F&&!F.grounding){let re=await O.getThread(a.threadId),de=new Set(F.changes.map(yt=>yt.explanationId)),gt=re?zd(re.messages,de):void 0;if(gt?.imprintSummary){let yt=gt.imprintSummary;await O.updateAssistantMessage(a.threadId,gt.jobId,{imprintSummary:{...yt,detail:F.detail,changes:F.changes,additionalObservationCount:(yt.additionalObservationCount??0)+1,coalescedTransactionIds:[...yt.coalescedTransactionIds??[],F.transactionId]}}),F=void 0}}let fo=ei({question:oe,resolutions:ue,changedFiles:xe,decisionRequired:!!qe,imprintTransactionId:mo,groundingRequired:!!F?.grounding}),fs=_e?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],Pt=a.lifecycle?pn(a.lifecycle,mo?[mo]:[],Ae):void 0;if(a.threadId){let re=C?qe?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Be;await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:re,resolutions:!C&&ue.length>0?ue:void 0,question:C?void 0:oe??void 0,sessionId:X.sessionId,toolsUsed:C?void 0:Me,editEvents:!C&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!C&&_e&&_e.length>0?_e:void 0,turn:{phase:"complete",orientation:fs,result:fo},result:fo,memoryReviewCard:qe??void 0,memoryReceipt:Le,imprintSummary:F,imprintRecognition:ae,modelDetails:ee.length>0?ee:void 0,model:a.model,provider:S,...Pt?{lifecycle:Pt}:{}})}if(a.threadId&&!Se&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let re=a.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await D.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(Bt(a.feedback)||"[request unavailable]"),responseSummary:oe??Be,outcome:oe?"question_asked":ue.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:re,filePaths:[...(X.fileEdits??[]).map(de=>de.file_path),...(X.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>Qr(de)?$d(i,de):de),resolutions:ue.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(de=>de.id),submissionIds:Pt?.submissionIds,outcomeId:Pt?.outcomeId,imprintEvidenceIds:Pt?.imprintEvidenceIds,imprintAssessment:Pt?.imprintAssessment})}catch(de){console.warn(`${U} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}Le?.status==="committed"&&Le.decisionId&&S!=="copilot"&&await ft({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Le.decisionId}`}),oe&&(console.log(`${U} \u{1F4AC} Question detected: "${oe.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),E.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:oe,annotationIds:a.annotationIds},a.id,a.sourceId)),ee.length>0&&(console.log(`${U} Applied model gap(s): ${ee.map(re=>`${re.category}/${re.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:ee,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ue.length>0?ue:void 0,responseText:Be,threadId:a.threadId,annotationIds:a.annotationIds,result:fo},a.id,a.sourceId),Pe.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${U} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:S,...a.lifecycle?{lifecycle:pn(a.lifecycle)}:{}}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:S,model:a.model,recoverable:X.recoverableError,code:X.errorCode},a.id,a.sourceId),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});rt()});let kt=Ed(async(a,y)=>{if(Vd(a,y),a.method==="OPTIONS"){y.writeHead(204),y.end();return}let M=a.url||"/",v=M.split("?")[0],A=new URL(M,`http://127.0.0.1:${f}`),S=A.pathname,C=Qd(a,A);if(C&&C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:ro(i)});return}if(a.headers.origin){if(!Xr(a.headers.origin)){_(y,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(C!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:ro(i)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let $=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",W=A.searchParams.get("kind"),U=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!$||$.length>128||!/^[a-z0-9_-]+$/i.test($)){_(y,400,{error:"A valid annotationId is required."});return}if(W!=="svg"&&W!=="text"||W==="svg"&&U!=="image/svg+xml"||W==="text"&&U!=="text/plain"){_(y,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let pe=await Kd(a,Ud);if(pe.length===0){_(y,400,{error:"Attachment is empty."});return}let z=await J.stage({annotationId:$,name:q,mimeType:U,kind:W,data:pe});_(y,201,{attachment:{id:z.id,name:z.name,mimeType:z.mimeType,size:z.size,kind:z.kind}})}else if(a.method==="POST"&&S==="/draft-attachments/claim"){let $=await Oe(a),q=Array.isArray($.ids)?$.ids.filter(W=>typeof W=="string").slice(0,100):[];await J.claim(q),_(y,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await J.release([S.slice(19)]),_(y,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await at(a,y);else if(a.method==="POST"&&S==="/capture/native"){if(!p){_(y,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let $=await Oe(a),q=typeof $.pageUrl=="string"?$.pageUrl:"",W=$.clip&&typeof $.clip=="object"&&!Array.isArray($.clip)?$.clip:null;if(!q||!W){_(y,400,{error:"pageUrl and clip are required."});return}let U=await Ji(p,{pageUrl:q,clip:{x:Number(W.x),y:Number(W.y),width:Number(W.width),height:Number(W.height)},scale:typeof $.scale=="number"?$.scale:1});y.writeHead(200,{"Content-Type":"image/webp","Content-Length":U.length,"Cache-Control":"no-store"}),y.end(U)}else if(a.method==="GET"&&S==="/events")et(a,y);else if(a.method==="GET"&&S==="/status")await ct(a,y,C);else if(a.method==="GET"&&S==="/ui-preferences")await mt(y);else if(a.method==="PATCH"&&S==="/ui-preferences")await co(a,y);else if(a.method==="PATCH"&&S==="/config")await dt(a,y);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}try{let $=await Oe(a),q=typeof $.leaseId=="string"?$.leaseId.trim():"",W=typeof $.ownerPid=="number"&&Number.isInteger($.ownerPid)&&$.ownerPid>0?$.ownerPid:void 0;if(!q||q.length>128){_(y,400,{error:"A valid leaseId is required."});return}Q();let U=N.acquire(q,W);_(y,201,{ok:!0,lease:U,ttlMs:Wr})}catch{_(y,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(S.slice(8))}catch{_(y,400,{error:"Invalid lease id."});return}if(!$){_(y,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=N.heartbeat($);if(!q){_(y,404,{error:"Lease not found."});return}_(y,200,{ok:!0,lease:q})}else{let q=N.release($);_(y,q.found?200:404,{ok:q.found}),q.becameEmpty&&H()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0}),setTimeout(w,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of L)try{$.res.end()}catch{}kt.close(()=>{Ur(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(y,200,{providers:m});else if(S.startsWith("/imprint/"))await be(a,y,S);else if(S.startsWith("/memory/"))await ao(a,y,S);else if(a.method==="POST"&&S==="/mcp/install")await po(a,y);else if(a.method==="POST"&&S==="/reply")await Ee(a,y);else if(a.method==="POST"&&S==="/cancel")lo(a,y);else if(a.method==="POST"&&S==="/materialize")_(y,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(y,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let $=await se.loadRuns();_(y,200,$)}else if(a.method==="GET"&&S==="/projection/proposals"){let $=await se.loadModelProposals();_(y,200,$)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let $=S.slice(22,-15);await Je($,a,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let $=S.slice(22,-6);await Ne($,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let $=S.slice(22,-8);await lt($,a,y)}else if(S.startsWith("/model/proposals/"))_(y,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await gn(a,y);else if(a.method==="DELETE"&&S==="/model/component")await is(a,y);else if(a.method==="PATCH"&&S==="/model/token")await rs(a,y);else if(a.method==="DELETE"&&S==="/model/token")await ss(a,y);else if(a.method==="POST"&&S==="/model/consolidate")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let $=await se.loadModel();_(y,200,{model:$})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let $=S.slice(6,S.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),W=E.getBufferedEvents($,isNaN(q)?-1:q);W?_(y,200,W):_(y,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await ls(v.slice(7),y);else if(a.method==="GET"&&S==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await O.listRecent($);_(y,200,q)}else if(a.method==="GET"&&S.startsWith("/decision/")){let $=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(y,400,{error:"Invalid decision id"});else{let q=await O.getThread($),W=[...q?.messages??[]].reverse().find(U=>U.annotationSnapshot);if(q&&W?.annotationSnapshot){let U=[...q.messages].reverse().find(pe=>pe.resolutions?.length);_(y,200,{decision:{id:q.id,createdAt:W.timestamp,url:W.annotationSnapshot.url,viewport:W.annotationSnapshot.viewport,color:W.annotationSnapshot.color,annotations:W.annotationSnapshot.annotations,resolutions:U?.resolutions??[]},authority:"thread_snapshot"})}else{let U=await ke.loadDecision($);U?_(y,200,{decision:U,authority:"legacy_archive"}):_(y,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let $=S.slice(8);await ps($,y)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let $=S.slice(8);await us($,y)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?as(a,y):a.method==="GET"&&S==="/canvas/manifest"?await cs(y):a.method==="GET"&&S==="/canvas/app.mjs"?await ds(y):_(y,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(y,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function ao(a,y,M){try{if(a.method==="GET"&&M==="/memory/status"){_(y,200,await D.status());return}if(a.method==="GET"&&M==="/memory/diagnostics"){_(y,200,await D.diagnostics());return}if(a.method==="GET"&&M==="/memory/model-view"){_(y,200,await D.getModelView());return}if(a.method==="GET"&&M==="/memory/imprint-view"){let v=await O.load(),A=[...new Set(Object.values(v.threads).flatMap(S=>hn(S.messages)))];_(y,200,await D.getImprintView(A,new Set(Object.keys(v.threads))));return}if(a.method==="POST"&&M==="/memory/constraints"){let v=await Oe(a),A=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=await D.getModelView(),C=A?S.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(y,200,{modelEntries:C});return}if(a.method==="POST"&&M==="/memory/conversation-action"){let v=await Oe(a),A=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",C=String(v.action);if(!A||!S||!["accept","edit_and_accept","reject","defer"].includes(C)){_(y,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await O.getThread(A),q=$?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!$||!q){_(y,409,{error:"This decision review card is not available in the thread."});return}let W=await se.findModelProposalsByThread(A),U=(await Promise.all(W.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(xe=>D.findPendingProposalForLegacyDecision(xe)))).some(xe=>xe?.proposalId===S)})))).find(X=>X.matches)?.proposal,pe={proposalId:S,action:C,kind:q.kind,claim:C==="edit_and_accept"&&typeof v.claim=="string"?v.claim.trim():void 0,reason:C==="defer"?void 0:`The owner explicitly chose ${C.replaceAll("_"," ")} from the decision review card.`,taskContext:C==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:C==="defer"?["different_action","owner_request"]:void 0};if(pe.action==="edit_and_accept"&&!pe.claim){_(y,400,{error:"Edited decision wording is required."});return}let z=await D.commitConversationalReview(pe),me=`memory-${it().slice(0,8)}`,le=C==="accept"?"> Accepted decision":C==="edit_and_accept"?"> Edited and accepted decision":C==="reject"?"> Rejected decision":"> Deferred decision";await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:me,replyToQuestion:le}),await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:me,responseText:"",memoryReceipt:z,provider:zt(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),z.status==="committed"&&U&&await se.dismissModelProposal(U.id);let ne=zt(typeof v.provider=="string"?v.provider:void 0);z.status==="committed"&&z.decisionId&&ne!=="copilot"&&await ft({provider:ne,model:typeof v.model=="string"?v.model:void 0,agentSettings:jt(v),threadId:A,reason:`Project accepted decision ${z.decisionId}`}),_(y,z.status==="committed"?200:409,{receipt:z});return}if(a.method==="POST"&&M==="/memory/analyze"){let v=await Oe(a),A=await D.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(A.issues.map(C=>C.code))].map(C=>[C,A.issues.filter($=>$.code===C).length]));_(y,200,{...A,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&M==="/memory/review"){let v=await Oe(a),A=await D.review(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/context"){let v=await Oe(a),A=await D.contextualize(Fo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/initialize"){let v=await Oe(a),A=await D.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:fn});_(y,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&M==="/memory/plan"){let v=await Oe(a),A=await D.planReview(qo(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,A.result.ok?200:422,A);return}if(a.method==="POST"&&M==="/memory/commit"){let v=await Oe(a),A=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await D.commitReview(qo(v.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(y,200,{status:await D.status(),journal:S.report});return}if(a.method==="POST"&&M==="/memory/recover"){let v=await Oe(a),A=await D.recover(v.confirm===!0);_(y,200,{status:await D.status(),journal:A.report});return}_(y,404,{error:"Memory endpoint not found."})}catch(v){let A=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),C=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(S||C){_(y,S?409:400,{error:A});return}throw v}}async function be(a,y,M){if(a.method==="GET"&&M==="/imprint/status"){let[v,A]=await Promise.all([Y.store.load(),O.load()]),S=[...new Set(Object.values(A.threads).flatMap(C=>hn(C.messages)))].filter(C=>v.graph.explanations.some($=>$.id===C&&$.state==="testing"));_(y,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter(C=>C.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:v.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&M==="/imprint/action"){let v=await Oe(a),A=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",C=String(v.action);if(!A||!S||!["yes","this_time","no"].includes(C)){_(y,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await O.getThread(A),W=[...q?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),U=W?.imprintSummary;if(!q||!W||!U){_(y,409,{error:"This imprint summary is not available in the thread."});return}if(U.resolvedAction){_(y,409,{error:"This imprint summary has already been resolved."});return}let pe=`imprint-${it().slice(0,8)}`;await Y.applyGroundingAction({summary:U,action:C,threadId:A,jobId:pe}),C!=="no"&&await D.recordImprintEvidence({summary:U,action:C,threadId:A,jobId:pe}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let z=qt(W.result,!!W.question),me=W.turn?{...W.turn,result:qt(W.turn.result,!!W.question)}:void 0;await O.updateAssistantMessage(A,W.jobId,{imprintSummary:{...U,resolvedAction:C},...z?{result:z}:{},...me?{turn:me}:{}});let le={yes:"> Yes",this_time:"> This time",no:"> No"};if(await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:pe,replyToQuestion:le[C]}),C==="no"){let ne="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",X=ei({question:ne});await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:pe,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ne,turn:{phase:"complete",orientation:[],result:X},result:X})}_(y,200,{ok:!0,action:C});return}_(y,404,{error:"Imprint endpoint not found."})}async function at(a,y){let{screenshot:M,feedback:v,color:A,provider:S,model:C,reasoningEffort:$,serviceTier:q,sourceId:W,pastedImages:U,pageScreenshots:pe}=await Uo(a),z;try{z=JSON.parse(v)}catch{_(y,400,{error:"Invalid feedback JSON"});return}let me=z.annotations.flatMap(ee=>(ee.attachments??[]).map(F=>({id:F.id,annotationId:ee.id}))),le;try{le=me.length>0?await J.promote(me):void 0}catch(ee){_(y,409,{error:ee instanceof Error?ee.message:"Draft attachment unavailable."});return}let ne=it().slice(0,8),X={};if(pe.length>0)for(let ee of pe){let F=encodeURIComponent(ee.pathname),ae=De(c,`screenshot-${ne}-${F}.webp`);await io(ae,ee.data),X[ee.pathname]=ae}let xe=De(c,`screenshot-${ne}.webp`);await io(xe,M);let we={};if(U.length>0)for(let ee of U){let F=De(c,`pasted-${ne}-${ee.annotationId}-${ee.index}.webp`);await io(F,ee.data),we[ee.annotationId]||(we[ee.annotationId]=[]),we[ee.annotationId].push(F)}let je=Cr(z),ge;if(je.length>0){let ee=await O.findContinuationThread(je);ee?(ge=ee.id,await O.addElementIdentifiers(ge,je)):ge=(await O.createThread(`thread-${it()}`,je)).id}else ge=(await O.createThread(`thread-${it()}`,[])).id;let Z=z.annotations.map(ee=>ee.id),fe=Object.keys(X).length>0,Be=await ir(D,z,je,ee=>console.warn(`[\u22B9 ${f}:${ne}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),Ae=(await O.getThread(ge))?.messages??[],oe=await Y.contextualize({text:Bt(z),subjectHints:[...je,...z.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(F=>!!F))],pendingGroundingExplanationIds:hn(Ae),correctionExplanationIds:Hr(Ae)}).catch(ee=>{console.warn(`[\u22B9 ${f}:${ne}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),ue=ni({jobId:ne,threadId:ge,artifactIds:$r(z,ne)}),Me={id:ne,status:"queued",screenshotPath:xe,feedback:z,createdAt:Date.now(),color:A,threadId:ge,annotationIds:Z,provider:zt(S),model:C||void 0,agentSettings:jt({reasoningEffort:$,serviceTier:q}),...Object.keys(we).length>0?{imagePaths:we}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},sourceId:W||void 0,...fe?{screenshotPaths:X}:{},...Be?{memoryReview:Be}:{},...oe?{imprintContext:oe}:{},lifecycle:ue},pt=new Set(z.annotations.map(ee=>ee.pathname).filter(Boolean)),_e;if(pt.size>1){let ee=new Map;for(let F of z.annotations){let ae=F.pathname||"(unknown)";ee.has(ae)||ee.set(ae,[]),ee.get(ae).push(F.instruction||Vr({...z,annotations:[F]}))}_e=[...ee.entries()].map(([F,ae])=>`\`${F}\`
|
|
210
|
+
${ae.map(ve=>`- ${ve}`).join(`
|
|
203
211
|
`)}`).join(`
|
|
204
|
-
`)}else
|
|
205
|
-
`):
|
|
206
|
-
`)),
|
|
212
|
+
`)}else _e=Vr(z);let Le=sn(z,Object.keys(we).length>0?we:void 0,le),qe=qr(z);await O.appendMessage(ge,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:xe,...fe?{screenshotPaths:X}:{},...Object.keys(we).length>0?{imagePaths:we}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},annotationIds:Z,annotationSnapshot:{url:z.url,viewport:z.viewport,annotations:z.annotations,color:A||void 0},feedbackSummary:_e,...qe?{requestText:qe}:{},feedbackContext:Le||void 0,...Be?{memoryReview:Be}:{},...oe?{imprintContext:oe}:{},lifecycle:ue});let Se=E.enqueue(Me);_(y,200,{jobId:ne,position:Se,threadId:ge})}async function Ee(a,y){let M=a.headers["content-type"]||"",v,A,S,C,$,q,W,U,pe=[];if(M.includes("multipart/form-data")){let F=await Uo(a),ae=F.feedback?JSON.parse(F.feedback):{};v=ae.threadId,A=ae.reply,S=ae.color,C=ae.provider,$=ae.model,q=jt(ae),W=ae.sourceId||F.sourceId,U=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let ve of F.pastedImages)pe.push(ve.data)}else{let F=[];for await(let Fe of a)F.push(typeof Fe=="string"?Buffer.from(Fe):Fe);let ae=Buffer.concat(F).toString("utf-8"),ve;try{ve=JSON.parse(ae)}catch{_(y,400,{error:"Invalid JSON"});return}v=ve.threadId,A=ve.reply,S=ve.color,C=ve.provider,$=ve.model,q=jt(ve),W=ve.sourceId,U=ve.memoryReviewProposalId}if(!v||!A){_(y,400,{error:"Missing threadId or reply"});return}let z=await O.getThread(v);if(!z){_(y,404,{error:"Thread not found"});return}let me;if(U){let F=await se.findModelProposalsByThread(v);if(me=(await Promise.all(F.flatMap(ve=>ve.authorityStatus==="accepted"?[]:ve.decisionIds.map(async Fe=>({modelProposalId:ve.id,underlying:await D.findPendingProposalForLegacyDecision(Fe)}))))).filter(ve=>!!ve.underlying).find(ve=>ve.underlying.proposalId===U),!me){_(y,409,{error:"The requested memory decision is not pending in this thread."});return}}let le="";{let F=await O.getThreadHistory(v);for(let ae=F.length-1;ae>=0;ae--)if(F[ae].screenshotPath){le=F[ae].screenshotPath;break}}let ne=await ht(v);if(!le&&!ne){_(y,400,{error:"No screenshot available"});return}let X=E.hasActiveThread(v),xe=X?E.getQueuedThreadJob(v,F=>F._replyText!==void 0||F._replyPrompt!==void 0):null,we=xe?.id??it().slice(0,8),je=ni({jobId:we,threadId:v}),ge=[],Z=`${we}-${Date.now()}`;for(let F=0;F<pe.length;F++){let ae=De(c,`reply-${Z}-${F}.webp`);await io(ae,pe[F]),ge.push(ae)}await O.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:we,replyToQuestion:A,screenshotPath:le,...X?{queued:!0}:{},...ge.length>0?{replyImagePaths:ge}:{},lifecycle:{...je,artifactIds:ge.map((F,ae)=>`reply-image:${we}:${ae}`)}});let fe=await O.getThreadHistory(v),Be=[...fe].reverse().find(F=>F.memoryReview)?.memoryReview,Ae=await Y.contextualize({text:A,subjectHints:z.elementIdentifiers,pendingGroundingExplanationIds:hn(fe),correctionExplanationIds:Hr(fe)}).catch(F=>{console.warn(`[\u22B9 ${f}:${we}] Imprint context unavailable for reply; continuing without it:`,F instanceof Error?F.message:String(F))}),oe=new Set(fe.flatMap(F=>F.memoryReceipt?.status==="committed"?[F.memoryReceipt.proposalId]:[])),ue=[...fe].reverse().find(F=>F.memoryReviewCard&&!oe.has(F.memoryReviewCard.proposalId))?.memoryReviewCard,Me=[];for(let F of fe)if(F.annotationIds)for(let ae of F.annotationIds)Me.includes(ae)||Me.push(ae);let pt=zt(C),_e=me,Le=_e?[_e.underlying.proposalId]:ue?[ue.proposalId]:[],qe=fr(le,fe,pt,ge.length>0?ge:void 0);if(_e?qe+=["","## Decision review card",`Privately review proposal ${_e.underlying.proposalId}: ${_e.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(`
|
|
213
|
+
`):ue&&(qe+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ue)}`,"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(`
|
|
214
|
+
`)),xe){let F=xe,ve=[...F._replyTexts??(F._replyText?[F._replyText]:[]),A],Fe=[...F._replyImagePaths??[],...ge];F._replyTexts=ve,F._replyText=Gr(ve),F._replyImagePaths=Fe.length>0?Fe:void 0,F._replyPrompt=qe,F.annotationIds=Me.length>0?Me:F.annotationIds,F.agentSettings=q??F.agentSettings,F.memoryReview=Be??F.memoryReview,F.imprintContext=Ae??F.imprintContext,F.surfacedProposalIds=[...new Set([...F.surfacedProposalIds??[],...Le])],F.lifecycle={...F.lifecycle??je,submissionIds:[...new Set([...F.lifecycle?.submissionIds??[],...je.submissionIds])],artifactIds:[...new Set([...F.lifecycle?.artifactIds??[],...je.artifactIds])]},_(y,200,{jobId:we,position:1,threadId:v,bundled:!0});return}let Se={id:we,status:"queued",screenshotPath:le,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:v,annotationIds:Me.length>0?Me:void 0,provider:pt,model:$||void 0,agentSettings:q,sourceId:W||void 0,...Be?{memoryReview:Be}:{},...Ae?{imprintContext:Ae}:{},...Le.length?{surfacedProposalIds:Le}:{},lifecycle:je};ne&&(Se.kind=ne),Se._replyPrompt=qe,Se._replyTexts=[A],Se._replyText=Gr([A]),ge.length>0&&(Se._replyImagePaths=ge);let ee=X?E.enqueueNext(Se):E.enqueue(Se);_(y,200,{jobId:we,position:ee,threadId:v})}function et(a,y){y.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),y.write(`event: connected
|
|
207
215
|
data: {"status":"connected"}
|
|
208
216
|
|
|
209
|
-
`);let I=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,A={id:st().slice(0,8),res:y,sourceId:I};L.add(A),a.on("close",()=>{L.delete(A)})}async function lt(a,y,M){s??=Ar(a.headers),at();let I=[...E.allActive,...R.allActive.map(ee=>({id:ee.id,status:ee.status,threadId:ee.threadId,annotationIds:ee.annotationIds??[],color:"#000000",kind:"project_model",standalone:ee.standalone}))],[A,S,C,$,F]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),D.status(),Z.store.load(),O.load()]),z=[],q=ee=>ee.reason instanceof Error?ee.reason.message:String(ee.reason);A.status==="rejected"&&z.push({subsystem:"projection",message:q(A)}),S.status==="rejected"&&z.push({subsystem:"projection",message:q(S)}),C.status==="rejected"?z.push({subsystem:"memory",message:q(C)}):C.value.state==="degraded"&&z.push({subsystem:"memory",message:C.value.error??"Product memory is degraded."}),$.status==="rejected"&&z.push({subsystem:"imprint",message:q($)}),F.status==="rejected"&&z.push({subsystem:"threads",message:q(F)});let le=A.status==="fulfilled"?A.value.runs:[],U=S.status==="fulfilled"?S.value.proposals:[],ue=Mr(le,U),de=ue.actionableProposals.map(ee=>({id:ee.id,status:ee.status,title:ee.title,summary:ee.summary,decisionIds:ee.decisionIds,threadId:ee.threadId,runId:ee.runId,presentationJobId:ee.presentationJobId,authorityStatus:ee.authorityStatus,underlyingProposalId:ee.underlyingProposalId,createdAt:ee.createdAt,updatedAt:ee.updatedAt,appliedAt:ee.appliedAt,dismissedAt:ee.dismissedAt,error:ee.error})),ne=C.status==="fulfilled"?C.value:{initialized:!1,state:"degraded",error:q(C)},X=F.status==="fulfilled"?[...new Set(Object.values(F.value.threads).flatMap(ee=>hn(ee.messages)))]:[],Se=$.status==="fulfilled"?X.filter(ee=>$.value.graph.explanations.some(ge=>ge.id===ee&&ge.state==="testing")):[],be=$.status==="fulfilled"?{state:"ready",head:$.value.graph.head,updatedAt:$.value.graph.updatedAt,explanationCount:$.value.graph.explanations.filter(ee=>ee.state!=="retired").length,concreteCount:$.value.graph.concrete.length,relationCount:$.value.graph.relations.length,pendingGroundingCount:Se.length,recoveredTransactions:$.value.recoveredTransactions,admission:Z.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:q($),pendingGroundingCount:Se.length,admission:Z.diagnostics(),admissionWindowStartedAt:e},Ae=z.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",he=new Date().toISOString();_(y,200,{ok:!0,schemaVersion:3,generatedAt:he,serverStartedAt:e,health:{state:Ae,issues:z},version:fn,restartMode:l,projectId:r,projectName:ri(o),projectRoot:o,requestProjectId:M,projectIdVerified:M===r,devOrigin:s,capture:{native:{configured:!!f,endpoint:f?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.map(ee=>({id:ee.id,status:ee.status,threadId:ee.threadId,annotationIds:ee.annotationIds,color:ee.color,kind:ee.kind,standalone:"standalone"in ee?ee.standalone:void 0})),queueDepth:E.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:N.isActivated,count:N.size,nextExpiryAt:N.nextExpiryAt,shutdownPending:G},projection:{state:A.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:ue.recentRuns,recentAppliedRuns:ue.recentAppliedRuns,actionableProposalCounts:ue.actionableProposalCounts,actionableProposals:de},memory:ne,imprint:be,recentJobsRetentionMs:Ge,recentJobs:je})}async function pt(a,y){let M=await new Promise(I=>{let A="";a.on("data",S=>{A+=S.toString()}),a.on("end",()=>I(A))});try{let I=JSON.parse(M);typeof I.devOrigin=="string"&&(s=I.devOrigin||null),_(y,200,{ok:!0,devOrigin:s})}catch{_(y,400,{error:"Invalid JSON"})}}async function mt(a){let y=await ae.load();_(a,200,{ok:!0,...y})}async function ci(a,y){let M=await Oe(a);if(!Br(M.theme)){_(y,400,{error:"theme must be light, dark, or auto"});return}let I=await ae.setTheme(M.theme);_(y,200,{ok:!0,exists:!0,preferences:I})}async function di(a,y){let I=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("jobId"),A=I?E.allActive.filter(q=>q.id===I):E.allActive,S=I?R.allActive.filter(q=>q.id===I):R.allActive,C=[...A.map(q=>q.threadId),...S.map(q=>q.threadId)].filter(Boolean),$=I?E.cancelJob(I):E.cancelActive(),F=I?R.cancelJob(I):R.cancelActive(),z=!!($||F);for(let q of C)await O.appendMessage(q,{role:"assistant",timestamp:Date.now(),jobId:I||F?.id||"",cancelled:!0});_(y,200,{cancelled:z})}async function ft(a){let y=st().slice(0,8),M=a.threadId,I=!M;M||(M=(await O.createThread(`thread-${st()}`,[])).id,He.set(M,"project_model")),I&&await O.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:a.reason}),await O.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:y,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:y,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:M,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:I},S=R.enqueue(A);return{jobId:y,position:S,threadId:M}}async function Ne(a,y){let M=decodeURIComponent(a),I=await se.findModelProposal(M);if(!I){_(y,404,{error:"Model proposal not found"});return}_(y,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:I})}async function Je(a,y,M){let I=decodeURIComponent(a),A=[];for await(let U of y)A.push(typeof U=="string"?Buffer.from(U):U);let S;try{S=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(M,400,{error:"Invalid JSON"});return}let C=(S.changes??[]).flatMap(U=>{if(!Array.isArray(U.path)||U.path.length===0)return[];let ue=U.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(ue.length!==U.path.length)return[];let de=Array.isArray(U.decisionIds)?U.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:ue,value:U.value,remove:U.remove===!0,decisionIds:de}]});if(C.length===0){_(M,400,{error:"No selected model changes"});return}let $=(S.changeSummaries??[]).flatMap(U=>{if(!U||typeof U!="object")return[];let ue=Array.isArray(U.path)?U.path.filter(de=>typeof de=="string"||typeof de=="number"):void 0;return Array.isArray(U.path)&&ue?.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:ue,value:U.value,currentValue:U.currentValue}]}),F=await se.findModelProposal(I);if(!F){_(M,404,{error:"Model proposal not found"});return}if(F.authorityStatus!=="accepted"){_(M,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(F.status!=="pending"){_(M,409,{error:`Model proposal is already ${F.status}.`});return}let z=F.decisionIds.map(U=>{let ue=F.changes?.filter(X=>X.decisionIds.includes(U)).length??0,de=C.filter(X=>X.decisionIds?.includes(U)).length,ne=de===0?"unprojected":ue>de?"partially_projected":"projected";return{decisionId:U,status:ne}}),q=await D.applyModelProjection({runId:F.runId??F.id,presentationJobId:F.presentationJobId,decisionIds:F.decisionIds,changes:C.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:z}),le=await se.applySelectedModelProposal(I,C,$);if(!le){_(M,404,{error:"Model proposal not found"});return}if(le.threadId){let U=zt(S.provider),ue=typeof S.model=="string"&&S.model?S.model:void 0;await O.appendMessage(le.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${le.id}`,responseText:"",provider:U,model:ue})}_(M,200,{proposal:le,projection:q})}async function ut(a,y,M){let I=decodeURIComponent(a),{provider:A,model:S}=await Rt(y),C=await se.dismissModelProposal(I);if(!C){_(M,404,{error:"Model proposal not found"});return}C.threadId&&await O.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${C.id}`,responseText:"",provider:A,model:S}),_(M,200,{proposal:C})}async function Rt(a){try{let y=[];for await(let I of a)y.push(typeof I=="string"?Buffer.from(I):I);if(y.length===0)return{};let M=JSON.parse(Buffer.concat(y).toString());return{provider:zt(typeof M.provider=="string"?M.provider:void 0),model:typeof M.model=="string"&&M.model?M.model:void 0,agentSettings:jt(M)}}catch{return{}}}async function ht(a){let y=He.get(a);if(y)return y;let A=(await O.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return He.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return He.set(a,"project_model"),"project_model"}async function li(a,y){let M=[];for await(let F of a)M.push(typeof F=="string"?Buffer.from(F):F);let I;if(M.length>0)try{I=JSON.parse(Buffer.concat(M).toString("utf-8")).serverUrl}catch{}let A=[];u.claude?.available&&u.claude.mcp&&!u.claude.mcp.found&&A.push(await Oo(I)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&A.push(await Do(I)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&A.push(await No(I,u.copilot.path??k));let[S,C,$]=await Promise.all([Ti(o),Ri(o),Pi(o,u.copilot?.path??k)]);u.claude&&(u.claude.mcp=S),u.codex&&(u.codex.mcp=C),u.copilot&&(u.copilot.mcp=$),_(y,200,{results:A,capabilities:{providers:u}})}async function gn(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${I.name}`,value:{description:""},claim:`${I.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{added:!0,alreadyExists:!1,...A})}async function ns(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${I.name}`,value:null,claim:`${I.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}async function is(a,y){let M=[];for await(let C of a)M.push(typeof C=="string"?Buffer.from(C):C);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){_(y,400,{error:"Missing or invalid path/value"});return}let A=I.value;try{let C=JSON.parse(I.value);C&&typeof C=="object"&&(A=C)}catch{}let S=await D.recordDirectModelMutation({key:`tokens.${I.path}`,value:A,claim:`${I.path} uses ${I.value} in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{updated:!0,...S})}async function os(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){_(y,400,{error:"Missing or invalid path"});return}let A=await D.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}function rs(a,y){let M=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let S=new URL(typeof A=="string"?A:A[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(M=S.origin)}catch{}}let I=so(h,M);y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(I)}async function ss(a){let y=Date.now();if(ct&&y<ct.expires){_(a,200,ct.data);return}try{let{scanForComponents:M}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:I}=await import("./render-generator-HWFLZYC3.mjs"),A=await M(o);ct={data:A,expires:y+5e3},I(A,o,Wt).then(S=>{Wt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,A)}catch(M){console.error("[Bridge] Scanner error:",M),_(a,500,{error:"Failed to scan components"})}}async function as(a){let y=[De(o,"node_modules","@popmelt.com","core","dist","canvas.mjs"),De(o,"packages","popmelt","dist","canvas.mjs")];try{let M=Cd(import.meta.url);y.unshift(De(Md(M),"canvas.mjs"))}catch{}for(let M of y)try{let I=await Ur(M,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(I);return}catch{}console.error("[Bridge] Canvas bundle not found in:",y),_(a,404,{error:"Canvas bundle not found"})}async function cs(a,y){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(y,400,{error:"Invalid filename"});return}try{let M=[De(c,a),De(o,".popmelt","artifacts","thread-media",a),De(o,".popmelt","artifacts","eval-screenshots",a),De(o,".popmelt","evals","screenshots",a),De(o,".popmelt","screenshots",a)],I;for(let C of M)try{I=await Ur(C);break}catch{}if(!I)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),S=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";y.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),y.end(I)}catch{_(y,404,{error:"File not found"})}}function Gt(a){return`/files/${ri(a)}`}async function ds(a,y){let M=await O.getThread(a);if(!M){_(y,404,{error:"Thread not found"});return}let I=M.messages.filter(F=>F.role==="assistant"&&F.responseText?.includes("Model suggestion ready")),A=await(I.length>0?se.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(A.map(async(F,z)=>{if(F.authorityStatus==="accepted")return F;let q=(await Promise.all(F.decisionIds.map(le=>D.findPendingProposalForLegacyDecision(le)))).find(Boolean);return{...F,authorityStatus:"legacy_untrusted",presentationJobId:F.presentationJobId??I[z]?.jobId??I.at(-1)?.jobId,underlyingProposalId:q?.proposalId,underlyingClaim:q?.claim}})),C=[...S].sort((F,z)=>z.updatedAt-F.updatedAt)[0]??null,$=M.messages.map(({screenshotPath:F,screenshotPaths:z,imagePaths:q,attachmentFiles:le,replyImagePaths:U,...ue})=>({...ue,...F?{screenshotUrl:Gt(F)}:{},...z?{screenshotUrls:Object.fromEntries(Object.entries(z).map(([de,ne])=>[de,Gt(ne)]))}:{},...q?{imageUrls:Object.fromEntries(Object.entries(q).map(([de,ne])=>[de,ne.map(Gt)]))}:{},...le?{attachments:Object.fromEntries(Object.entries(le).map(([de,ne])=>[de,ne.map(({path:X,...Se})=>({...Se,url:Gt(X)}))]))}:{},...U?{replyImageUrls:U.map(Gt)}:{}}));_(y,200,{id:M.id,createdAt:M.createdAt,messages:$,modelProposal:C,modelProposals:S})}async function ls(a,y){let M=decodeURIComponent(a);if(!await O.deleteThread(M)){_(y,404,{deleted:!1,error:"Thread not found"});return}_(y,200,{deleted:!0})}let io=9,oo=!1;for(let a=t;a<t+io;a++)try{await Qd(Tt,a),h=a,oo=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(y){if(y.code==="EADDRINUSE"){let M=await Kd(a);if(jr(M,{projectId:r,version:fn,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw y}if(!oo)throw new Error(`[Bridge] All ports ${t}\u2013${t+io-1} in use`);for(let[a,y]of Object.entries(u))!y.available||!y.path||j(a,y.path).then(M=>{if(M)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),y.available=!1,y.path=null;for(let I of L)si(I,{type:"capabilities_changed",data:{}})}});let ps=setInterval(()=>{Hr(c).catch(()=>{}),J.sweep().catch(()=>{})},Dd),ro=setInterval(()=>{N.expireStale().becameEmpty&&H()},Jd);return ro.unref?.(),{port:h,projectId:r,close:async()=>{clearInterval(ps),clearInterval(ro),Q(),N.clear(),await J.cleanupPartials(),await E.destroyAsync(),R.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{Tt.close(()=>a())})}}}async function Hr(i){try{let e=await kd(i),t=Date.now();for(let n of e){let o=De(i,n);try{let r=await Rd(o);t-r.mtimeMs>Nd&&await Pd(o)}catch{}}}catch{}}var el=parseInt(process.env.POPMELT_PORT||"1111",10),Yr=process.env.POPMELT_PROJECT_ROOT||process.cwd(),tl=process.env.POPMELT_DEV_ORIGIN||void 0,nl=process.env.POPMELT_COPILOT_PATH||void 0,il=process.env.POPMELT_CDP_URL||void 0,Zr=Xr(Yr,".popmelt"),es=Xr(Zr,"bridge.lock");async function ol(i){await Xd(Zr,{recursive:!0}),await Zd(es,JSON.stringify({pid:process.pid,port:i,startedAt:Date.now()})+`
|
|
210
|
-
`)}async function
|
|
217
|
+
`);let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("sourceId")||void 0,A={id:it().slice(0,8),res:y,sourceId:v};L.add(A),a.on("close",()=>{L.delete(A)})}async function ct(a,y,M){s??=Ar(a.headers),rt();let v=[...E.allActive,...R.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,S,C,$,q]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),D.status(),Y.store.load(),O.load()]),W=[],U=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&W.push({subsystem:"projection",message:U(A)}),S.status==="rejected"&&W.push({subsystem:"projection",message:U(S)}),C.status==="rejected"?W.push({subsystem:"memory",message:U(C)}):C.value.state==="degraded"&&W.push({subsystem:"memory",message:C.value.error??"Product memory is degraded."}),$.status==="rejected"&&W.push({subsystem:"imprint",message:U($)}),q.status==="rejected"&&W.push({subsystem:"threads",message:U(q)});let pe=A.status==="fulfilled"?A.value.runs:[],z=S.status==="fulfilled"?S.value.proposals:[],me=Mr(pe,z),le=me.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})),ne=C.status==="fulfilled"?C.value:{initialized:!1,state:"degraded",error:U(C)},X=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>hn(Z.messages)))]:[],xe=$.status==="fulfilled"?X.filter(Z=>$.value.graph.explanations.some(fe=>fe.id===Z&&fe.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:xe.length,recoveredTransactions:$.value.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:U($),pendingGroundingCount:xe.length,admission:Y.diagnostics(),admissionWindowStartedAt:e},je=W.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",ge=new Date().toISOString();_(y,200,{ok:!0,schemaVersion:3,generatedAt:ge,serverStartedAt:e,health:{state:je,issues:W},version:fn,restartMode:l,projectId:r,projectName:ro(i),projectRoot:i,requestProjectId:M,projectIdVerified:M===r,devOrigin:s,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.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:E.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:N.isActivated,count:N.size,nextExpiryAt:N.nextExpiryAt,shutdownPending:G},projection:{state:A.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:me.recentRuns,recentAppliedRuns:me.recentAppliedRuns,actionableProposalCounts:me.actionableProposalCounts,actionableProposals:le},memory:ne,imprint:we,recentJobsRetentionMs:Ge,recentJobs:Pe})}async function dt(a,y){let M=await new Promise(v=>{let A="";a.on("data",S=>{A+=S.toString()}),a.on("end",()=>v(A))});try{let v=JSON.parse(M);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(y,200,{ok:!0,devOrigin:s})}catch{_(y,400,{error:"Invalid JSON"})}}async function mt(a){let y=await ce.load();_(a,200,{ok:!0,...y})}async function co(a,y){let M=await Oe(a);if(!Br(M.theme)){_(y,400,{error:"theme must be light, dark, or auto"});return}let v=await ce.setTheme(M.theme);_(y,200,{ok:!0,exists:!0,preferences:v})}async function lo(a,y){let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("jobId"),A=v?E.allActive.filter(U=>U.id===v):E.allActive,S=v?R.allActive.filter(U=>U.id===v):R.allActive,C=[...A.map(U=>U.threadId),...S.map(U=>U.threadId)].filter(Boolean),$=v?E.cancelJob(v):E.cancelActive(),q=v?R.cancelJob(v):R.cancelActive(),W=!!($||q);for(let U of C)await O.appendMessage(U,{role:"assistant",timestamp:Date.now(),jobId:v||q?.id||"",cancelled:!0});_(y,200,{cancelled:W})}async function ft(a){let y=it().slice(0,8),M=a.threadId,v=!M;M||(M=(await O.createThread(`thread-${it()}`,[])).id,He.set(M,"project_model")),v&&await O.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:a.reason}),await O.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:y,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:y,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:M,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=R.enqueue(A);return{jobId:y,position:S,threadId:M}}async function Ne(a,y){let M=decodeURIComponent(a),v=await se.findModelProposal(M);if(!v){_(y,404,{error:"Model proposal not found"});return}_(y,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function Je(a,y,M){let v=decodeURIComponent(a),A=[];for await(let z of y)A.push(typeof z=="string"?Buffer.from(z):z);let S;try{S=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(M,400,{error:"Invalid JSON"});return}let C=(S.changes??[]).flatMap(z=>{if(!Array.isArray(z.path)||z.path.length===0)return[];let me=z.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(me.length!==z.path.length)return[];let le=Array.isArray(z.decisionIds)?z.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:me,value:z.value,remove:z.remove===!0,decisionIds:le}]});if(C.length===0){_(M,400,{error:"No selected model changes"});return}let $=(S.changeSummaries??[]).flatMap(z=>{if(!z||typeof z!="object")return[];let me=Array.isArray(z.path)?z.path.filter(le=>typeof le=="string"||typeof le=="number"):void 0;return Array.isArray(z.path)&&me?.length!==z.path.length?[]:[{group:typeof z.group=="string"?z.group:void 0,label:typeof z.label=="string"?z.label:void 0,detail:typeof z.detail=="string"?z.detail:void 0,path:me,value:z.value,currentValue:z.currentValue}]}),q=await se.findModelProposal(v);if(!q){_(M,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(M,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(M,409,{error:`Model proposal is already ${q.status}.`});return}let W=q.decisionIds.map(z=>{let me=q.changes?.filter(X=>X.decisionIds.includes(z)).length??0,le=C.filter(X=>X.decisionIds?.includes(z)).length,ne=le===0?"unprojected":me>le?"partially_projected":"projected";return{decisionId:z,status:ne}}),U=await D.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:C.map(z=>({path:z.path,value:z.value,decisionIds:z.decisionIds})),coverage:W}),pe=await se.applySelectedModelProposal(v,C,$);if(!pe){_(M,404,{error:"Model proposal not found"});return}if(pe.threadId){let z=zt(S.provider),me=typeof S.model=="string"&&S.model?S.model:void 0;await O.appendMessage(pe.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${pe.id}`,responseText:"",provider:z,model:me})}_(M,200,{proposal:pe,projection:U})}async function lt(a,y,M){let v=decodeURIComponent(a),{provider:A,model:S}=await Rt(y),C=await se.dismissModelProposal(v);if(!C){_(M,404,{error:"Model proposal not found"});return}C.threadId&&await O.appendMessage(C.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${C.id}`,responseText:"",provider:A,model:S}),_(M,200,{proposal:C})}async function Rt(a){try{let y=[];for await(let v of a)y.push(typeof v=="string"?Buffer.from(v):v);if(y.length===0)return{};let M=JSON.parse(Buffer.concat(y).toString());return{provider:zt(typeof M.provider=="string"?M.provider:void 0),model:typeof M.model=="string"&&M.model?M.model:void 0,agentSettings:jt(M)}}catch{return{}}}async function ht(a){let y=He.get(a);if(y)return y;let A=(await O.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return He.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return He.set(a,"project_model"),"project_model"}async function po(a,y){let M=[];for await(let q of a)M.push(typeof q=="string"?Buffer.from(q):q);let v;if(M.length>0)try{v=JSON.parse(Buffer.concat(M).toString("utf-8")).serverUrl}catch{}let A=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&A.push(await Oi(v)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&A.push(await Di(v)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&A.push(await Ni(v,m.copilot.path??T));let[S,C,$]=await Promise.all([Ro(i),Po(i),jo(i,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=C),m.copilot&&(m.copilot.mcp=$),_(y,200,{results:A,capabilities:{providers:m}})}async function gn(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{added:!0,alreadyExists:!1,...A})}async function is(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}async function rs(a,y){let M=[];for await(let C of a)M.push(typeof C=="string"?Buffer.from(C):C);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(y,400,{error:"Missing or invalid path/value"});return}let A=v.value;try{let C=JSON.parse(v.value);C&&typeof C=="object"&&(A=C)}catch{}let S=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:A,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{updated:!0,...S})}async function ss(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(y,400,{error:"Missing or invalid path"});return}let A=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}function as(a,y){let M=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let S=new URL(typeof A=="string"?A:A[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(M=S.origin)}catch{}}let v=ai(f,M);y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(v)}async function cs(a){let y=Date.now();if(st&&y<st.expires){_(a,200,st.data);return}try{let{scanForComponents:M}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:v}=await import("./render-generator-HWFLZYC3.mjs"),A=await M(i);st={data:A,expires:y+5e3},v(A,i,Wt).then(S=>{Wt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,A)}catch(M){console.error("[Bridge] Scanner error:",M),_(a,500,{error:"Failed to scan components"})}}async function ds(a){let y=[De(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),De(i,"packages","popmelt","dist","canvas.mjs")];try{let M=Dd(import.meta.url);y.unshift(De(Cd(M),"canvas.mjs"))}catch{}for(let M of y)try{let v=await zr(M,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",y),_(a,404,{error:"Canvas bundle not found"})}async function ls(a,y){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(y,400,{error:"Invalid filename"});return}try{let M=[De(c,a),De(i,".popmelt","artifacts","thread-media",a),De(i,".popmelt","artifacts","eval-screenshots",a),De(i,".popmelt","evals","screenshots",a),De(i,".popmelt","screenshots",a)],v;for(let C of M)try{v=await zr(C);break}catch{}if(!v)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),S=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";y.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),y.end(v)}catch{_(y,404,{error:"File not found"})}}function Gt(a){return`/files/${ro(a)}`}async function ps(a,y){let M=await O.getThread(a);if(!M){_(y,404,{error:"Thread not found"});return}let v=M.messages.filter(q=>q.role==="assistant"&&q.responseText?.includes("Model suggestion ready")),A=await(v.length>0?se.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(A.map(async(q,W)=>{if(q.authorityStatus==="accepted")return q;let U=(await Promise.all(q.decisionIds.map(pe=>D.findPendingProposalForLegacyDecision(pe)))).find(Boolean);return{...q,authorityStatus:"legacy_untrusted",presentationJobId:q.presentationJobId??v[W]?.jobId??v.at(-1)?.jobId,underlyingProposalId:U?.proposalId,underlyingClaim:U?.claim}})),C=[...S].sort((q,W)=>W.updatedAt-q.updatedAt)[0]??null,$=M.messages.map(({screenshotPath:q,screenshotPaths:W,imagePaths:U,attachmentFiles:pe,replyImagePaths:z,...me})=>({...me,...q?{screenshotUrl:Gt(q)}:{},...W?{screenshotUrls:Object.fromEntries(Object.entries(W).map(([le,ne])=>[le,Gt(ne)]))}:{},...U?{imageUrls:Object.fromEntries(Object.entries(U).map(([le,ne])=>[le,ne.map(Gt)]))}:{},...pe?{attachments:Object.fromEntries(Object.entries(pe).map(([le,ne])=>[le,ne.map(({path:X,...xe})=>({...xe,url:Gt(X)}))]))}:{},...z?{replyImageUrls:z.map(Gt)}:{}}));_(y,200,{id:M.id,createdAt:M.createdAt,messages:$,modelProposal:C,modelProposals:S})}async function us(a,y){let M=decodeURIComponent(a);if(!await O.deleteThread(M)){_(y,404,{deleted:!1,error:"Thread not found"});return}_(y,200,{deleted:!0})}let ii=9,ri=!1;for(let a=t;a<t+ii;a++)try{await Zd(kt,a),f=a,ri=!0,console.log(`[\u22B9 is watching :${f}]`);break}catch(y){if(y.code==="EADDRINUSE"){let M=await Yd(a);if(jr(M,{projectId:r,version:fn,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw y}if(!ri)throw new Error(`[Bridge] All ports ${t}\u2013${t+ii-1} in use`);for(let[a,y]of Object.entries(m))!y.available||!y.path||j(a,y.path).then(M=>{if(M)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),y.available=!1,y.path=null;for(let v of L)so(v,{type:"capabilities_changed",data:{}})}});let ms=setInterval(()=>{Kr(c).catch(()=>{}),J.sweep().catch(()=>{})},Bd),si=setInterval(()=>{N.expireStale().becameEmpty&&H()},qd);return si.unref?.(),{port:f,projectId:r,close:async()=>{clearInterval(ms),clearInterval(si),Q(),N.clear(),await J.cleanupPartials(),await E.destroyAsync(),R.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{kt.close(()=>a())})}}}async function Kr(o){try{let e=await Pd(o),t=Date.now();for(let n of e){let i=De(o,n);try{let r=await Ad(i);t-r.mtimeMs>Ld&&await Md(i)}catch{}}}catch{}}var ol=parseInt(process.env.POPMELT_PORT||"1111",10),es=process.env.POPMELT_PROJECT_ROOT||process.cwd(),il=process.env.POPMELT_DEV_ORIGIN||void 0,rl=process.env.POPMELT_COPILOT_PATH||void 0,sl=process.env.POPMELT_CDP_URL||void 0,ts=Zr(es,".popmelt"),ns=Zr(ts,"bridge.lock");async function al(o){await el(ts,{recursive:!0}),await nl(ns,JSON.stringify({pid:process.pid,port:o,startedAt:Date.now()})+`
|
|
218
|
+
`)}async function os(){try{await tl(ns)}catch{}}async function cl(){let o=await Yr({port:ol,projectRoot:es,devOrigin:il,copilotPath:rl,nativeCaptureUrl:sl,restartMode:"detached"});await al(o.port),await new Promise(e=>{let t=!1,n=async()=>{t||(t=!0,await o.close(),await os(),e(),process.exit(0))};process.on("SIGTERM",n),process.on("SIGINT",n)})}cl().catch(o=>{console.error("[popmelt bridge-entry] Fatal:",o),os().finally(()=>process.exit(1))});
|