@popmelt.com/core 0.8.12 → 0.8.14
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 +69 -67
- package/dist/{chunk-TT6CN5YA.mjs → chunk-JJEESG5Y.mjs} +1 -1
- package/dist/cli.mjs +66 -64
- package/dist/index.mjs +45 -39
- package/dist/memory-legacy.d.mts +4 -0
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +17 -3
- package/dist/memory-store.mjs +3 -3
- package/dist/memory.d.mts +4 -0
- package/dist/memory.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-SESHQYMR.mjs +213 -0
- package/dist/server.d.mts +52 -9
- package/dist/server.mjs +63 -61
- package/package.json +1 -1
- package/dist/server-OGLISVYX.mjs +0 -211
package/dist/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as tl}from"child_process";import{closeSync as nl,openSync as ol}from"fs";import{appendFile as il,mkdir as rl,readFile as sl,realpath as al}from"fs/promises";import{dirname as cl,join as ci}from"path";import{fileURLToPath as dl}from"url";import{execFileSync as Td,spawn as Gr}from"child_process";import{randomUUID as at}from"crypto";import{mkdir as Pd,readFile as Wr,readdir as Rd,realpath as kd,stat as jd,unlink as Ad,writeFile as lo}from"fs/promises";import{createServer as Md}from"http";import{tmpdir as Ed}from"os";import{basename as po,dirname as _d,isAbsolute as Xr,join as De,relative as Cd,resolve as $d}from"path";import{fileURLToPath as Od}from"url";function ui(o,e){return`<!DOCTYPE html>
|
|
2
2
|
<html>
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -25,19 +25,21 @@ import{spawn as yd}from"child_process";import{closeSync as vd,openSync as wd}fro
|
|
|
25
25
|
});
|
|
26
26
|
</script>
|
|
27
27
|
</body>
|
|
28
|
-
</html>`}var
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
`)
|
|
33
|
-
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(r.includes("file")||r.includes("write")||r.includes("edit"))){let i=r.includes("write")?"Write":r.includes("read")?"Read":"Edit";return{tool:i,label:`${i} ${t.split("/").pop()}`,file:t}}}function ps(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"&&zt(o).toLowerCase().includes("error"))return o.message}function qt(o,e,n=[]){for(let t of e){let r=o[t];if(typeof r=="string")return r}for(let[t,r]of Object.entries(o)){if(!r||typeof r!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let i=qt(r,e);if(i)return i}}function co(o){let e=zt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as us,readFile as ms}from"fs/promises";import{join as lo}from"path";var fn=class{constructor(e){let n=lo(e,".popmelt");this.decisionsDir=lo(n,"decisions")}async listDecisionIds(){try{return(await us(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await ms(lo(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};import{createHash as fs,randomUUID as hs}from"crypto";import{mkdir as po,readFile as or,readdir as rr,rename as hn,stat as ir,unlink as gn,writeFile as yn}from"fs/promises";import{extname as gs,join as Ge}from"path";var ys=10080*60*1e3,vs=600*1e3,ws=3600*1e3;function Is(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function bs(o,e){return[...o.trim()].map(t=>t==="/"||t==="\\"||t.charCodeAt(0)<32?"-":t).join("").slice(0,120)||e}var vn=class{constructor(e){this.draftsDir=Ge(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ge(e,".popmelt","artifacts","thread-media")}async stage(e){let n=hs(),t=Is(e.mimeType),r=`${n}${t}`,i=Date.now(),s={id:n,annotationId:e.annotationId,name:bs(e.name,`pasted-context${t}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await po(this.draftsDir,{recursive:!0});let c=Ge(this.draftsDir,r),d=Ge(this.draftsDir,`${n}.json`),l=`${c}.part`,x=`${d}.part`;return await yn(l,e.data),await hn(l,c),await yn(x,JSON.stringify(s,null,2)),await hn(x,d),s}async claim(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(delete t.releasedAt,t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async release(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(t.releasedAt=Date.now(),t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async promote(e){let n={};for(let t of e){let r=await this.readManifest(t.id);if(!r)throw new Error(`Draft attachment ${t.id} is unavailable or expired.`);if(r.annotationId!==t.annotationId)throw new Error(`Draft attachment ${t.id} does not belong to annotation ${t.annotationId}.`);let i=Ge(this.draftsDir,r.contentFile),s=await or(i),c=fs("sha256").update(s).digest("hex"),d=Ge(this.mediaDir,`${c}${gs(r.contentFile)||".bin"}`);await po(this.mediaDir,{recursive:!0});try{await ir(d)}catch{let l=`${d}.part`;await yn(l,s),await hn(l,d)}(n[t.annotationId]??=[]).push({id:r.id,name:r.name,mimeType:r.mimeType,size:r.size,kind:r.kind,path:d}),r.releasedAt=Date.now(),r.lastSeenAt=Date.now(),await this.writeManifest(r)}return n}async sweep(e=Date.now()){let n;try{n=await rr(this.draftsDir)}catch{return}await Promise.all(n.map(async t=>{let r=Ge(this.draftsDir,t);if(t.endsWith(".part")){let c=await ir(r).catch(()=>null);c&&e-c.mtimeMs>ws&&await gn(r).catch(()=>{});return}if(!t.endsWith(".json"))return;let i=await this.readManifest(t.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>vs:e-i.lastSeenAt>ys)||await Promise.all([gn(r).catch(()=>{}),gn(Ge(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await rr(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>gn(Ge(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await or(Ge(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await po(this.draftsDir,{recursive:!0});let n=Ge(this.draftsDir,`${e.id}.json`),t=`${n}.part`;await yn(t,JSON.stringify(e,null,2)),await hn(t,n)}};import{randomUUID as sr}from"crypto";import{mkdir as uo,readFile as mo,writeFile as wn}from"fs/promises";import{dirname as fo,join as xt}from"path";var We="[ProjectionWorker]",xs={version:1,runs:[]},Ss={version:1,updatedAt:0,proposals:[]},Ps=12;function Ts(o){return Array.isArray(o)?o.map((e,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function ar(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${We} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.sources.filter(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${We} Rule count ${e.length} exceeds cap of 30`),e}function Rs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function ks(o,e,n){let t=new Set(e),r=new Set,i=Array.isArray(o.rules)?o.rules:[];for(let h of i){if(!h||typeof h!="object")continue;let p=h.sources;if(Array.isArray(p))for(let v of p)typeof v=="string"&&t.has(v)&&r.add(v)}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(n?.rules)?n.rules:[],l=i.filter(h=>{if(!h||typeof h!="object")return!1;let p=h.id,v=typeof p=="string"?d.find(w=>w&&typeof w=="object"&&w.id===p):void 0;return JSON.stringify(v)!==JSON.stringify(h)}).length,x=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},P=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(h=>JSON.stringify(s[h])!==JSON.stringify(x[h])).length,b=Object.keys(c).filter(h=>JSON.stringify(c[h])!==JSON.stringify(P[h])).length;return{ruleCount:l,tokenSectionCount:T,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(h=>!r.has(h))}}function js(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ms(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let r=typeof n=="number"?[]:{};return o[String(e)]=r,r}function In(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=Ms(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=js(n)}function cr(o,e){let n=o;for(let r=0;r<e.length-1;r++){let i=n[String(e[r])];if(!i||typeof i!="object")return;n=i}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function As(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function Es(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function dr(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=As(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Es(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var bn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=xt(e,".popmelt");this.runsPath=xt(t,"projection-runs.json"),this.legacyRunsPath=xt(t,"materialization-runs.json"),this.proposalsPath=xt(t,"projection-queue.json"),this.legacyProposalsPath=xt(t,"model-proposals.json"),this.modelPath=xt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await mo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Ts(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let r=t.key.split(".");t.value===null?cr(n,r):In(n,r,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Ps),n=new Set((await this.loadModelProposals()).proposals.flatMap(r=>r.status==="pending"&&r.authorityStatus==="accepted"?r.decisionIds:[]));return{decisions:e.filter(r=>!n.has(r.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),r=t.decisions;if(r.length===0)return{processedIds:[],success:!0};let i=r.map(h=>h.id);console.log(`${We} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=Os(r,s),d=Rs(r,t.totalCandidateDecisionCount,c);n=sr().slice(0,8);let l={id:n,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:i,startedAt:Date.now(),promptStats:d};await this.persistRun(l);let x=!0,P,T,b;try{let h=`projection-${Date.now()}`,{provider:p,result:v}=this.spawnModelAgent(h,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});l={...l,provider:p},await this.persistRun(l);let w=await v;if(!w.success)x=!1,P=w.error,console.error(`${We} ${p} spawn error:`,P);else{let m=$s(w.text,i);if(m){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let y of m)In(u,y.path,y.value);Array.isArray(u.rules)&&(u.rules=ar(u.rules));let R=ks(u,i,s);if(m){let y=[...new Set(m.flatMap(L=>L.decisionIds))];R.coveredDecisionIds=y,R.uncoveredDecisionIds=i.filter(L=>!y.includes(L))}T=R;let E=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:T,changes:m});b=E.id,console.log(`${We} Created model proposal ${E.id} for ${i.length} decision(s)`)}else x=!1,P="No valid bounded <model-changes> block found in response",console.error(`${We} ${P}`)}}catch(h){x=!1,P=h instanceof Error?h.message:String(h),console.error(`${We} Error:`,P)}return await this.persistRun({...l,status:x?"proposed":"failed",completedAt:Date.now(),error:P,outputStats:T,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:x,error:P}),{processedIds:i,success:x,error:P,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ar(e.rules)),await wn(this.modelPath,JSON.stringify(e,null,2)),console.log(`${We} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let n=await this.readRunStore(this.legacyRunsPath);return n?(await uo(fo(this.runsPath),{recursive:!0}),await wn(this.runsPath,JSON.stringify(n,null,2)),n):{...xs,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let r=await this.readProposalStore(this.legacyProposalsPath);r&&(e={version:1,updatedAt:Date.now(),proposals:r.proposals.filter(i=>i.authorityStatus==="accepted"&&Array.isArray(i.changes)&&i.changes.length>0)},await this.persistModelProposals(e))}let n=e??{...Ss,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(r=>{if(r.proposedModel)return r;let i=structuredClone(t);for(let s of r.changes??[])In(i,s.path,s.value);return{...r,proposedModel:i}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>r.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,r)=>t.createdAt-r.createdAt||t.updatedAt-r.updatedAt)}async applySelectedModelProposal(e,n,t,r="confirmed"){let i=await this.findModelProposal(e);if(!i)return null;if(i.status==="dismissed")return i;let s=await this.loadModel()??{};for(let d of n)!Array.isArray(d.path)||d.path.length===0||(d.remove?cr(s,d.path):In(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:r,error:void 0,selectedChanges:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:sr().slice(0,8),status:"pending",title:_s(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"}.`:Cs(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()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(r=>r.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),r=null;return t.proposals=t.proposals.map(i=>i.id!==e?i:(r={...i,...n,updatedAt:Date.now()},r)),r?(t.updatedAt=Date.now(),await this.persistModelProposals(t),r):null}async persistModelProposals(e){try{await uo(fo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await wn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await uo(fo(this.runsPath),{recursive:!0}),await wn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${We} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await mo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await mo(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,r){let i=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return i==="codex"?{provider:"codex",...mn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:ln(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${We} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...pn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:r.maxTurns,maxBudgetUsd:r.maxBudgetUsd,allowedTools:r.allowedTools,claudePath:this.options.claudePath??"claude",model:i==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function _s(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(r=>r&&typeof r=="object"&&typeof r.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function Cs(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,r=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${n} rule${n===1?"":"s"}, ${r} component entr${r===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function $s(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let r=new Set(e),i=t.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(P=>typeof P=="string"||typeof P=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let l=d.path[0];if(l!=="tokens"&&l!=="components"&&l!=="rules")return[];if(l==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(P=>typeof P=="string"&&r.has(P)):[];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 i.length===t.length?i:null}catch{return null}}function Os(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
34
|
-
|
|
35
|
-
Claim: ${i.claim}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`)
|
|
28
|
+
</html>`}var hs=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),gs=new Set(["default","flex","fast","priority"]);function At(o){let e=typeof o.reasoningEffort=="string"&&hs.has(o.reasoningEffort)?o.reasoningEffort:void 0,n=typeof o.serviceTier=="string"&&gs.has(o.serviceTier)?o.serviceTier:void 0;return e||n?{reasoningEffort:e,serviceTier:n}:void 0}function In(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 Qt(o,e){let n=e.trim();if(!n)return"";let t=o.length>0?`
|
|
29
|
+
|
|
30
|
+
${n}`:n;return o.push(t),t}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"]),mi=1e5;function ws(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let n=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!Is.has(n))return;let t;if(o.name==="Write"&&typeof o.input?.content=="string"?t=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(t=o.input.new_string),!!t)return t.length>mi?t.slice(0,mi)+`
|
|
31
|
+
\u2026[truncated]`:t}function wn(o,e){let{prompt:n,projectRoot:t,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:p,reasoningEffort:w,timeoutMs:x=3e5,onEvent:T}=e,k=[];d?k.push("--resume",d,"-p",n):k.push("-p",n),k.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),p&&k.push("--model",p),w&&k.push("--effort",w);for(let l of s)k.push("--allowedTools",l);let y=ys(c,k,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),f=new Promise(l=>{let h,u=[],m=[],j=[],S=!1,g="",J,E,R=!1,N=setTimeout(()=>{R=!0,y.kill("SIGTERM"),setTimeout(()=>{try{y.kill("SIGKILL")}catch{}},5e3)},x),V=vs({input:y.stdout}),K=new Set;V.on("line",Q=>{if(Q.trim())try{let b=JSON.parse(Q);b.session_id&&!h&&(h=b.session_id);let H=b.type??(b.event?.type?`event.${b.event.type}`:"unknown");if(K.add(H),b.type==="result"&&b.result&&u.length===0){let L=typeof b.result=="string"?b.result:"";if(L){let O=Qt(u,L);O&&T?.({type:"delta",jobId:o,text:O},o)}}if(b.type==="assistant"&&Array.isArray(b.message?.content)){typeof b.error=="string"&&(J=b.error);for(let L of b.message.content){if(L.type==="text"&&L.text){let O=Qt(u,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,fe=ws(L);if(T?.({type:"tool_use",jobId:o,tool:L.name,...O?{file:O}:{},...fe?{content:fe}:{}},o),L.name==="Edit"&&L.input?.file_path){let B={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};m.push(B),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:B.file_path,oldString:typeof B.old_string=="string"?B.old_string:void 0,newString:typeof B.new_string=="string"?B.new_string:void 0,replaceAll:typeof B.replace_all=="boolean"?B.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(m.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)}}b.type==="result"&&b.is_error===!0&&(S=!0,typeof b.error=="string"&&(J=b.error),typeof b.result=="string"&&(E=b.result)),b.type==="user"&&b.tool_use_result?.file?.filePath&&T?.({type:"tool_use",jobId:o,tool:"Read",file:b.tool_use_result.file.filePath},o)}catch{}});let W=[];y.stderr?.on("data",Q=>{W.push(Q.toString())}),y.on("close",Q=>{if(clearTimeout(N),V.close(),u.length===0&&K.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...K].join(", ")}`),R)S=!0,g=`Timed out after ${Math.round(x/6e4)} minutes`;else if(Q!==0&&Q!==null){S=!0;let H=W.join("").trim(),L=u.join("").trim(),O=u.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";g=H||E||L||`Claude process exited with code ${Q}${O}`}S&&!g&&E&&(g=E);let b=bs(g,J);l({sessionId:h,text:u.join(""),success:!S,error:S?b.message:void 0,errorCode:S?b.code:void 0,recoverableError:S?b.recoverable:void 0,fileEdits:m.length>0?m:void 0,editEvents:j.length>0?j:void 0})}),y.on("error",Q=>{clearTimeout(N),S=!0,g=Q.message,l({sessionId:h,text:u.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:m.length>0?m:void 0,editEvents:j.length>0?j:void 0})})});return{process:y,result:f}}function bs(o,e){let n=o.trim()||"Claude CLI failed",t=`${e??""} ${n}`.toLowerCase();return t.includes("authentication_failed")||t.includes("not logged in")||t.includes("please run /login")||t.includes("api key")?{message:n,code:"claude_auth_required",recoverable:!0}:t.includes("model")&&(t.includes("not found")||t.includes("unknown")||t.includes("unavailable"))?{message:n,code:"claude_model_unavailable",recoverable:!0}:{message:n,code:e||"claude_error",recoverable:!1}}import{spawn as xs,spawnSync as Ii}from"child_process";import{readFileSync as Ss,statSync as Ts}from"fs";import{basename as Ps,extname as Rs,isAbsolute as ks,relative as wi,resolve as js}from"path";import{createInterface as As}from"readline";function fi(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var hi=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"]),bo=2e5,Ms=1e5,bi=2e5;function xi(o){let e=Ps(o).toLowerCase(),n=Rs(o).toLowerCase();return hi.has(n)||hi.has(e)}function Xt(o,e){let n=ks(e)?e:js(o,e),t=wi(o,n);return t===""||t.startsWith("..")?null:n}function bn(o,e){if(!xi(e))return;let n=Xt(o,e);if(n)try{let t=Ts(n);return t.isFile()?t.size>bo?{exists:!0,truncated:!0}:{exists:!0,content:Ss(n,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function Es(o,e){for(let n of e){let t=o[n];if(typeof t=="string")return t}}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 gi(o){return Es(o,["patch","diff","unifiedDiff","unified_diff"])}function xo(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function yi(o,e){let n=Ii("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:bi+65536});return n.status!==0?null:n.stdout??""}function Cs(o){let e=new Set;for(let n of o.split(`
|
|
32
|
+
`)){if(n.length<4)continue;let t=n.slice(3).trim();if(!t)continue;t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1));let i=t.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function vi(o){let e=yi(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let n=yi(o,["diff","--no-ext-diff","HEAD","--"])??"",t=xo(n,bi);return{status:e,changedFiles:Cs(e),...t.text?{diff:t.text}:{},...t.truncated?{diffTruncated:!0}:{}}}function $s(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function Os(o,e){if(!xi(e))return;let n=Xt(o,e);if(!n)return;let t=wi(o,n);if(t===""||t.startsWith(".."))return;let i=Ii("git",["show",`HEAD:${t}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:bo+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=xo(r,bo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function Ds(o,e,n){return e.map(t=>{let i=n.has(t)?n.get(t):Os(o,t),r=bn(o,t);return{filePath:t,...i?{before:i}:{},...r?{after:r}:{}}})}function xn(o,e){let{prompt:n,projectRoot:t,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:p=[]}=e,w=[];if(r){w.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let k of p)w.push("-c",k);s&&w.push("-m",s),w.push(r),w.push(n),i&&w.push("--image",i)}else{w.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let k of p)w.push("-c",k);s&&w.push("-m",s),w.push(n),i&&w.push("--image",i)}let x=xs("codex",w,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),T=new Promise(k=>{let y,f=[],l=[],h=[],u=new Map,m=new Map,j=!1,S="",g=As({input:x.stdout}),J=new Set;g.on("line",R=>{if(R.trim())try{let N=JSON.parse(R),V=N.type??"unknown";if(J.add(V),V==="thread.started"&&N.thread_id&&!y&&(y=N.thread_id),(V==="item.agentMessage.delta"||V==="item/agentMessage/delta")&&N.delta?.text&&(f.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 W=N.item.command,Q=W?fi(W):void 0,b=vi(t),H=new Map;for(let O of b?.changedFiles??[])H.set(O,bn(t,O));typeof N.item.id=="string"&&m.set(N.item.id,{...W?{rawCommand:W}:{},...Q?{command:Q}:{},...b?{beforeWorktree:b}:{},beforeSnapshots:H});let L=Q?`Bash: ${Q.split(`
|
|
33
|
+
`)[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 W=N.item.filename||N.item.path;W&&!u.has(W)&&u.set(W,bn(t,W)),l.push(W?`Edit ${W.split("/").pop()}`:"Edit");let Q=W?Xt(t,W)??W:void 0;c?.({type:"tool_use",jobId:o,tool:"Edit",...Q?{file:Q}:{}},o)}else if(K==="file_read"){let W=N.item.filename||N.item.path;l.push(W?`Read ${W.split("/").pop()}`:"Read");let Q=W?Xt(t,W)??W: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 W=N.item.tool_name||N.item.name||"MCP";l.push(W),c?.({type:"tool_use",jobId:o,tool:W},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 W=Qt(f,K);W&&c?.({type:"delta",jobId:o,text:W},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 W=K.path||K.filename,Q=K.kind==="add"?"Write":"Edit";if(W){l.push(`${Q} ${W.split("/").pop()}`);let b=Xt(t,W)??W;c?.({type:"tool_use",jobId:o,tool:Q,file:b},o);let H=K,L=typeof H.kind=="string"?H.kind:void 0,O=_s(L),fe=u.get(W),B=bn(t,W);h.push({sequence:h.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:O,filePath:W,...fe?{before:fe}:{},...B?{after:B}:{},...gi(H)?{patch:gi(H)}:{},...L?{rawKind:L}:{}}),u.set(W,B)}}else if(N.item.type==="command_execution"){let K=typeof N.item.id=="string"?N.item.id:void 0,W=K?m.get(K):void 0,Q=typeof N.item.command=="string"?N.item.command:W?.rawCommand,b=Q?fi(Q):W?.command,H=vi(t);if($s(W?.beforeWorktree,H)){let L=[...new Set([...W?.beforeWorktree?.changedFiles??[],...H?.changedFiles??[]])],O=typeof N.item.aggregated_output=="string"?xo(N.item.aggregated_output,Ms):void 0,fe=typeof N.item.exit_code=="number"?N.item.exit_code:N.item.exit_code===null?null:void 0,B=typeof N.item.status=="string"?N.item.status:void 0;h.push({sequence:h.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Q?{rawCommand:Q}:{},...b?{command:b}:{},...fe!==void 0?{exitCode:fe}:{},...B?{status:B}:{},...O?{output:O.text}:{},...O?.truncated?{outputTruncated:!0}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...H?{afterWorktree:H}:{},...L.length>0?{touchedFiles:Ds(t,L,W?.beforeSnapshots??new Map)}:{}})}K&&m.delete(K)}}V==="turn.failed"&&(j=!0,S=N.error?.message||N.message||"Turn failed")}catch{}});let E=[];x.stderr?.on("data",R=>{E.push(R.toString())}),x.on("close",R=>{g.close(),f.length===0&&J.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...J].join(", ")}`),R!==0&&R!==null&&(j=!0,S=E.join("")||`Codex process exited with code ${R}`),k({sessionId:y,text:f.join(""),success:!j,error:j?S:void 0,editEvents:h.length>0?h:void 0,toolsUsed:l.length>0?l:void 0})}),x.on("error",R=>{j=!0,S=R.message,k({sessionId:y,text:f.join(""),success:!1,error:S,editEvents:h.length>0?h:void 0,toolsUsed:l.length>0?l:void 0})})});return{process:x,result:T}}import{spawn as Ns}from"child_process";import{createInterface as Bs}from"readline";function Si(o,e){let n=o.trim()||"Copilot CLI failed",t=n.toLowerCase();return t.includes("no authentication information")||t.includes("not authenticated")||t.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`."}:t.includes("model")&&(t.includes("not available")||t.includes("not found")||t.includes("disabled")||t.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:n}:t.includes("mcp")&&(t.includes("blocked")||t.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."}:t.includes("permission")||t.includes("denied")||t.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:n}:{code:"copilot_error",recoverable:!1,message:n}}function Ti(o,e){let{prompt:n,projectRoot:t,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,p=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];i&&p.push(`--resume=${i}`),r&&p.push("--model",r),p.push("-p",n);let w=Ns(d,p,{cwd:t,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),x=new Promise(T=>{let k,y=[],f=[],l=!1,h="",u=!1,m=setTimeout(()=>{u=!0,w.kill("SIGTERM"),setTimeout(()=>{try{w.kill("SIGKILL")}catch{}},5e3)},s),j=Bs({input:w.stdout}),S=new Set,g=[];j.on("line",E=>{if(E.trim())try{let R=JSON.parse(E),N=Zt(R);S.add(N),g.length<5&&Ls(N)&&g.push(E.slice(0,800));let V=Yt(R,["sessionId","session_id","id"],["session","conversation","thread"]);V&&!k&&(k=V);let K=Js(R,y.length===0);K&&(y.push(K),c?.({type:"delta",jobId:o,text:K},o));let W=Fs(R);W&&c?.({type:"thinking",jobId:o,text:W},o);let Q=qs(R);Q&&(f.push(Q.label),c?.({type:"tool_use",jobId:o,tool:Q.tool,...Q.file?{file:Q.file}:{},...Q.content?{content:Q.content}:{}},o));let b=Us(R);b&&(l=!0,h=b)}catch{}});let J=[];w.stderr?.on("data",E=>{J.push(E.toString())}),w.on("close",E=>{clearTimeout(m),j.close(),y.length===0&&S.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...S].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
|
|
34
|
+
`)}`)),u?(l=!0,h=`Timed out after ${Math.round(s/6e4)} minutes`):E!==0&&E!==null&&(l=!0,h=J.join("").trim()||h||`Copilot process exited with code ${E}`);let R=l?Si(h,r):null;T({sessionId:k,text:y.join(""),success:!l,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})}),w.on("error",E=>{clearTimeout(m);let R=Si(E.message,r);T({sessionId:k,text:y.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:f.length>0?f:void 0})})});return{process:w,result:x}}function Zt(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 Js(o,e=!1){let n=Zt(o).toLowerCase(),t=o.update,i=t?.content;if(t?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(n==="assistant.message_delta"||n.includes("agent_message.delta"))return ze(o.delta)??ze(o.content)??ze(o.message);if(n==="assistant.message"&&e)return ze(o.message)??ze(o.content)??ze(o);if(n==="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"&&So(o))return o.text;if(typeof o.message=="string"&&So(o))return o.message;if(typeof o.delta=="string"&&So(o))return o.delta}function ze(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let n=o.map(ze).filter(t=>!!t);return n.length>0?n.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 n of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let t=ze(e[n]);if(t)return t}}function Ls(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Fs(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 n=e.content;if(typeof n?.text=="string")return n.text}}function qs(o){let e=Yt(o,["tool","toolName","tool_name","name"]),n=Yt(o,["command","cmd"]),t=Yt(o,["file","path","filename","filePath"]),i=Zt(o);if(n||i.includes("shell"))return{tool:"Bash",label:n?`Bash: ${n.split(`
|
|
35
|
+
`)[0].slice(0,80)}`:"Bash",...n?{content:n}:{}};if(e)return{tool:e,label:t?`${e} ${t.split("/").pop()}`:e,...t?{file:t}:{}};if(t&&(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} ${t.split("/").pop()}`,file:t}}}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"&&Zt(o).toLowerCase().includes("error"))return o.message}function Yt(o,e,n=[]){for(let t of e){let i=o[t];if(typeof i=="string")return i}for(let[t,i]of Object.entries(o)){if(!i||typeof i!="object"||n.length>0&&!n.some(s=>t.toLowerCase().includes(s)))continue;let r=Yt(i,e);if(r)return r}}function So(o){let e=Zt(o).toLowerCase();return(typeof o.role=="string"?o.role.toLowerCase():"")==="assistant"||e.includes("assistant")||e.includes("agent_message")}import{readdir as zs,readFile as Gs}from"fs/promises";import{join as To}from"path";var Sn=class{constructor(e){let n=To(e,".popmelt");this.decisionsDir=To(n,"decisions")}async listDecisionIds(){try{return(await zs(this.decisionsDir)).filter(n=>n.startsWith("d-")&&n.endsWith(".json")).map(n=>n.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let n=await Gs(To(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(n)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(t=>this.loadDecision(t)))).filter(t=>t!==null)}};import{createHash as Ws,randomUUID as Hs}from"crypto";import{mkdir as Po,readFile as Pi,readdir as Ri,rename as Tn,stat as ki,unlink as Pn,writeFile as Rn}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(t=>t==="/"||t==="\\"||t.charCodeAt(0)<32?"-":t).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 n=Hs(),t=Ys(e.mimeType),i=`${n}${t}`,r=Date.now(),s={id:n,annotationId:e.annotationId,name:Zs(e.name,`pasted-context${t}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await Po(this.draftsDir,{recursive:!0});let c=Ve(this.draftsDir,i),d=Ve(this.draftsDir,`${n}.json`),p=`${c}.part`,w=`${d}.part`;return await Rn(p,e.data),await Tn(p,c),await Rn(w,JSON.stringify(s,null,2)),await Tn(w,d),s}async claim(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(delete t.releasedAt,t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async release(e){await Promise.all(e.map(async n=>{let t=await this.readManifest(n);t&&(t.releasedAt=Date.now(),t.lastSeenAt=Date.now(),await this.writeManifest(t))}))}async promote(e){let n={};for(let t of e){let i=await this.readManifest(t.id);if(!i)throw new Error(`Draft attachment ${t.id} is unavailable or expired.`);if(i.annotationId!==t.annotationId)throw new Error(`Draft attachment ${t.id} does not belong to annotation ${t.annotationId}.`);let r=Ve(this.draftsDir,i.contentFile),s=await Pi(r),c=Ws("sha256").update(s).digest("hex"),d=Ve(this.mediaDir,`${c}${Vs(i.contentFile)||".bin"}`);await Po(this.mediaDir,{recursive:!0});try{await ki(d)}catch{let p=`${d}.part`;await Rn(p,s),await Tn(p,d)}(n[t.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 n}async sweep(e=Date.now()){let n;try{n=await Ri(this.draftsDir)}catch{return}await Promise.all(n.map(async t=>{let i=Ve(this.draftsDir,t);if(t.endsWith(".part")){let c=await ki(i).catch(()=>null);c&&e-c.mtimeMs>Xs&&await Pn(i).catch(()=>{});return}if(!t.endsWith(".json"))return;let r=await this.readManifest(t.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Qs:e-r.lastSeenAt>Ks)||await Promise.all([Pn(i).catch(()=>{}),Pn(Ve(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await Ri(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>Pn(Ve(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Pi(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await Po(this.draftsDir,{recursive:!0});let n=Ve(this.draftsDir,`${e.id}.json`),t=`${n}.part`;await Rn(t,JSON.stringify(e,null,2)),await Tn(t,n)}};import{randomUUID as ji}from"crypto";import{mkdir as Ro,readFile as ko,writeFile as jn}from"fs/promises";import{dirname as jo,join as Mt}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,n)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Ai(o){let e=[];for(let n of o){if(!n||typeof n!="object")continue;let t=n;if(typeof t.id!="string"||typeof t.text!="string"){console.warn(`${Ke} Dropping rule missing id or text:`,JSON.stringify(n).slice(0,120));continue}e.push({id:t.id,scope:typeof t.scope=="string"?t.scope:"general",text:t.text,sources:Array.isArray(t.sources)?t.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,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function ra(o,e,n){let t=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let y of r){if(!y||typeof y!="object")continue;let f=y.sources;if(Array.isArray(f))for(let l of f)typeof l=="string"&&t.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(n?.rules)?n.rules:[],p=r.filter(y=>{if(!y||typeof y!="object")return!1;let f=y.id,l=typeof f=="string"?d.find(h=>h&&typeof h=="object"&&h.id===f):void 0;return JSON.stringify(l)!==JSON.stringify(y)}).length,w=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},x=n?.components&&typeof n.components=="object"&&!Array.isArray(n.components)?n.components:{},T=Object.keys(s).filter(y=>JSON.stringify(s[y])!==JSON.stringify(w[y])).length,k=Object.keys(c).filter(y=>JSON.stringify(c[y])!==JSON.stringify(x[y])).length;return{ruleCount:p,tokenSectionCount:T,componentCount:k,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(y=>!i.has(y))}}function sa(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function aa(o,e,n){let t=o[e];if(t&&typeof t=="object")return t;let i=typeof n=="number"?[]:{};return o[String(e)]=i,i}function An(o,e,n){let t=o;for(let r=0;r<e.length-1;r++)t=aa(t,e[r],e[r+1]);let i=e[e.length-1];t[String(i)]=sa(n)}function Mi(o,e){let n=o;for(let i=0;i<e.length-1;i++){let r=n[String(e[i])];if(!r||typeof r!="object")return;n=r}let t=e[e.length-1];Array.isArray(n)&&typeof t=="number"?n.splice(t,1):delete n[String(t)]}function ca(o,e){if(!o)return{exists:!1};let n=o;for(let t of e){if(!n||typeof n!="object"||!(String(t)in n))return{exists:!1};n=n[String(t)]}return{exists:!0,value:n}}function da(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((n,t)=>JSON.stringify(n)===JSON.stringify(e[t])):!1}function Ei(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=ca(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?da(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var Mn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=Mt(e,".popmelt");this.runsPath=Mt(t,"projection-runs.json"),this.legacyRunsPath=Mt(t,"materialization-runs.json"),this.proposalsPath=Mt(t,"projection-queue.json"),this.legacyProposalsPath=Mt(t,"model-proposals.json"),this.modelPath=Mt(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ko(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=oa(n.rules)),n}catch{return null}}async applyCanonicalEntries(e){let n={tokens:{},components:{},rules:[]};for(let t of e){let i=t.key.split(".");t.value===null?Mi(n,i):An(n,i,t.value)}await this.writeModel(n)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(na),n=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!n.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let n;try{let t=await this.selectUnprojectedPatternDecisions(),i=t.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(y=>y.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,t.totalCandidateDecisionCount,c);n=ji().slice(0,8);let p={id:n,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 w=!0,x,T,k;try{let y=`projection-${Date.now()}`,{provider:f,result:l}=this.spawnModelAgent(y,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)w=!1,x=h.error,console.error(`${Ke} ${f} spawn error:`,x);else{let u=ua(h.text,r);if(u){let m=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of u)An(m,g.path,g.value);Array.isArray(m.rules)&&(m.rules=Ai(m.rules));let j=ra(m,r,s);if(u){let g=[...new Set(u.flatMap(J=>J.decisionIds))];j.coveredDecisionIds=g,j.uncoveredDecisionIds=r.filter(J=>!g.includes(J))}T=j;let S=await this.createModelProposal({decisionIds:r,proposedModel:m,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:f,model:e.model??this.options.model,outputStats:T,changes:u});k=S.id,console.log(`${Ke} Created model proposal ${S.id} for ${r.length} decision(s)`)}else w=!1,x="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${x}`)}}catch(y){w=!1,x=y instanceof Error?y.message:String(y),console.error(`${Ke} Error:`,x)}return await this.persistRun({...p,status:w?"proposed":"failed",completedAt:Date.now(),error:x,outputStats:T,proposalId:k}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:w,error:x}),{processedIds:r,success:w,error:x,runId:n,proposalId:k}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Ai(e.rules)),await jn(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 n=await this.readRunStore(this.legacyRunsPath);return n?(await Ro(jo(this.runsPath),{recursive:!0}),await jn(this.runsPath,JSON.stringify(n,null,2)),n):{...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 n=e??{...ta,proposals:[]},t=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...n,proposals:n.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(t);for(let s of i.changes??[])An(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(t=>t.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>i.updatedAt-t.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(t=>t.threadId===e).sort((t,i)=>t.createdAt-i.createdAt||t.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,n,t,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 n)!Array.isArray(d.path)||d.path.length===0||(d.remove?Mi(s,d.path):An(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:t})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let n={id:ji().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()},t=await this.loadModelProposals();return t.proposals=[n,...t.proposals.filter(i=>i.id!==n.id)].slice(0,100),t.updatedAt=Date.now(),await this.persistModelProposals(t),n}async updateModelProposal(e,n){let t=await this.loadModelProposals(),i=null;return t.proposals=t.proposals.map(r=>r.id!==e?r:(i={...r,...n,updatedAt:Date.now()},i)),i?(t.updatedAt=Date.now(),await this.persistModelProposals(t),i):null}async persistModelProposals(e){try{await Ro(jo(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...i})=>i)};await jn(this.proposalsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ke} Failed to write model proposals:`,n)}}async persistRun(e){try{let n=await this.loadRuns(),t=n.runs.findIndex(i=>i.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await Ro(jo(this.runsPath),{recursive:!0}),await jn(this.runsPath,JSON.stringify(n,null,2))}catch(n){console.error(`${Ke} Failed to write projection run:`,n)}}async readRunStore(e){try{let n=JSON.parse(await ko(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await ko(e,"utf8"));return n?.version===1&&Array.isArray(n.proposals)?n:null}catch{return null}}spawnModelAgent(e,n,t,i){let r=t.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...xn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:In(t.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",...wn(e,{prompt:n,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?t.model??this.options.model:void 0,reasoningEffort:t.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function la(o){let n=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof n?.text=="string"&&n.text.trim())return n.text.trim().replace(/\.$/,"").slice(0,72);let t=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return t.length>0?`Model update for ${t[0]}`:"Model update"}function pa(o,e){let n=Array.isArray(o.rules)?o.rules.length:0,t=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 ${n} rule${n===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${t} token section${t===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function ua(o,e){let n=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!n?.[1])return null;try{let t=JSON.parse(n[1]);if(!Array.isArray(t)||t.length===0||t.length>40)return null;let i=new Set(e),r=t.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(x=>typeof x=="string"||typeof x=="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 w=Array.isArray(d.decisionIds)?d.decisionIds.filter(x=>typeof x=="string"&&i.has(x)):[];return w.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:w,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===t.length?r:null}catch{return null}}function ma(o,e){let n=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
36
|
+
Kind: ${r.kind}
|
|
37
|
+
Claim: ${r.claim}
|
|
38
|
+
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
39
|
+
Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
|
|
40
|
+
Authority: ${r.authority.level}/${r.authority.mode}`).join(`
|
|
41
|
+
|
|
42
|
+
`),t=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
|
|
41
43
|
|
|
42
44
|
## Instructions
|
|
43
45
|
1. Review the current model (if any) and the new decisions below.
|
|
@@ -109,15 +111,15 @@ Example:
|
|
|
109
111
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
110
112
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
111
113
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
112
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
113
|
-
`),n=[],t=null;for(let
|
|
114
|
-
`)}),t={name:
|
|
115
|
-
`)}),t=null):t&&t.bodyLines.push(
|
|
116
|
-
`)}),n}function
|
|
117
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
114
|
+
Include property and bindings when the decision context has class-level evidence.`}var En=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){for(let i of this.listeners)i(e,n,t)}cancelJob(e){let n=this.queue.findIndex(i=>i.id===e);if(n>=0){let[i]=this.queue.splice(n,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 t=this.activeJob;return!t||t.id!==e?null:(t.status="cancelled",t.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:t.error,cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},t.id),this.processNext(),t)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(n=>{e.status!=="cancelled"&&(e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as fa}from"child_process";import{readFile as $i}from"fs/promises";import{homedir as Mo}from"os";import{join as Ye}from"path";var Eo=/popmelt/i;function It(){return{found:!1,name:null,scope:null,disabled:!1}}function Et(o,e,n=!1){return{found:!0,name:o,scope:e,disabled:n}}function en(o){for(let e of Object.keys(o))if(Eo.test(e))return e;return null}async function _n(o){try{let e=await $i(o,"utf-8");return JSON.parse(e)}catch{return null}}async function _o(o){let e=Mo(),n=await _n(Ye(e,".claude.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=en(i.mcpServers);if(r)return Et(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=en(c.mcpServers);if(d){let p=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(w=>Eo.test(w));return Et(d,"project",p)}}}}}let t=await _n(Ye(o,".mcp.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=en(i.mcpServers);if(s){let c=await _i(o,s);return Et(s,"mcp.json",c)}}let r=en(i);if(r&&r!=="mcpServers"){let s=await _i(o,r);return Et(r,"mcp.json",s)}}return It()}async function _i(o,e){let n=Ye(o,".claude","settings.local.json"),t=await _n(n);if(t&&typeof t=="object"){let i=t;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(`
|
|
115
|
+
`),n=[],t=null;for(let i of e){let r=i.match(ha);r?(t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
116
|
+
`)}),t={name:r[1],bodyLines:[]}):i.startsWith("[")?t&&(n.push({name:t.name,body:t.bodyLines.join(`
|
|
117
|
+
`)}),t=null):t&&t.bodyLines.push(i)}return t&&n.push({name:t.name,body:t.bodyLines.join(`
|
|
118
|
+
`)}),n}function ya(o){return/enabled\s*=\s*false/i.test(o)}async function Co(o){let e=process.env.CODEX_HOME||Ye(Mo(),".codex"),n=await Ci(Ye(e,"config.toml"),"user");if(n.found)return n;let t=await Ci(Ye(o,".codex","config.toml"),"project");return t.found?t:It()}async function $o(o,e="copilot"){let n=await va(e);if(n.found)return n;let t=process.env.COPILOT_HOME||Ye(Mo(),".copilot"),i=await Ao(Ye(t,"mcp-config.json"),"user");if(i.found)return i;let r=await Ao(Ye(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Ao(Ye(o,".github","mcp.json"),"mcp.json");return s.found?s:It()}async function va(o){try{let e=await new Promise((n,t)=>{fa(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return Oi(JSON.parse(e),"user")}catch{return It()}}async function Ao(o,e){let n=await _n(o);return Oi(n,e)}function Oi(o,e){if(!o||typeof o!="object")return It();let n=o,t=n.mcpServers&&typeof n.mcpServers=="object"?n.mcpServers:n.servers&&typeof n.servers=="object"?n.servers:n,i=en(t);return i?Et(i,e):It()}async function Ci(o,e){try{let n=await $i(o,"utf-8"),t=ga(n);for(let i of t)if(Eo.test(i.name)){let r=ya(i.body);return Et(i.name,e,r)}}catch{}return It()}import{execFile as Di}from"child_process";import{mkdir as Ia,readFile as Ni,writeFile as Bi}from"fs/promises";import{homedir as Ji}from"os";import{dirname as wa,join as Oo}from"path";var Do="https://mcp.popmelt.com/mcp";async function Li(o=Do){let e=Oo(Ji(),".claude.json"),n;try{let i=await Ni(e,"utf-8");n=JSON.parse(i)}catch{n={}}(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={});let t=n.mcpServers;for(let i of Object.keys(t))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return t.popmelt={type:"http",url:o},await Bi(e,JSON.stringify(n,null,2)+`
|
|
119
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Fi(o=Do){let e=process.env.CODEX_HOME||Oo(Ji(),".codex"),n=Oo(e,"config.toml"),t;try{t=await Ni(n,"utf-8")}catch{t=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(t))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await Ia(wa(n),{recursive:!0});let i=`
|
|
118
120
|
[mcp_servers.popmelt]
|
|
119
121
|
url = "${o}"
|
|
120
|
-
`;return await
|
|
122
|
+
`;return await Bi(n,t+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function qi(o=Do,e="copilot"){let n=await ba(e);if(xa(n))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((t,i)=>{Di(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}t()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(t){return{installed:!1,provider:"copilot",scope:null,reason:t instanceof Error?t.message:"install_failed"}}}async function ba(o){try{let e=await new Promise((n,t)=>{Di(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){t(i);return}n(r)})});return JSON.parse(e)}catch{return null}}function xa(o){if(!o||typeof o!="object")return!1;let e=o,n=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(n).some(t=>/popmelt/i.test(t))}var Cn=class{constructor(e){this.ttlMs=e;this.leases=new Map;this.activated=!1;if(!Number.isFinite(e)||e<=0)throw new Error("Lease TTL must be positive")}get isActivated(){return this.activated}get size(){return this.leases.size}get nextExpiryAt(){let e=null;for(let n of this.leases.values())(e===null||n.expiresAt<e)&&(e=n.expiresAt);return e}acquire(e,n,t=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:n,createdAt:i?.createdAt??t,expiresAt:t+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,n=Date.now()){let t=this.leases.get(e);return t?(t.expiresAt=n+this.ttlMs,t):null}release(e){let n=this.leases.delete(e);return{found:n,becameEmpty:n&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let n=[];for(let[t,i]of this.leases)i.expiresAt>e||(this.leases.delete(t),n.push(t));return{expiredIds:n,becameEmpty:n.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};var Sa=String.raw`
|
|
121
123
|
(() => {
|
|
122
124
|
const hidden = [];
|
|
123
125
|
const visit = (root) => {
|
|
@@ -138,7 +140,7 @@ url = "${o}"
|
|
|
138
140
|
visit(document);
|
|
139
141
|
window.__popmeltNativeCaptureHidden = hidden;
|
|
140
142
|
})()
|
|
141
|
-
`,
|
|
143
|
+
`,Ta=String.raw`
|
|
142
144
|
(() => {
|
|
143
145
|
for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
|
|
144
146
|
if (value) element.style.setProperty('visibility', value, priority);
|
|
@@ -146,66 +148,66 @@ url = "${o}"
|
|
|
146
148
|
}
|
|
147
149
|
delete window.__popmeltNativeCaptureHidden;
|
|
148
150
|
})()
|
|
149
|
-
`;function Tn(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Ws(o,e){let n=Tn(e);if(!n)return null;let t=new URL(n),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Tn(s.url)),i=r.find(s=>Tn(s.url)===n);return i||(r.find(s=>{let c=new URL(Tn(s.url));return c.origin===t.origin&&c.pathname===t.pathname})??null)}function Vs(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 Ks(o){let e=new AbortController,n=setTimeout(()=>e.abort(),1e3);try{let t=new URL("/json/list",o).href,r=await fetch(t,{signal:e.signal});if(!r.ok)throw new Error(`CDP discovery returned ${r.status}`);let i=await r.json();return Array.isArray(i)?i:[]}finally{clearTimeout(n)}}async function Qs(o){let{WebSocket:e}=await import("ws");return new Promise((n,t)=>{let r=new e(o,{handshakeTimeout:1e3}),i=()=>{r.off("error",s),n(r)},s=c=>{r.off("open",i),t(c)};r.once("open",i),r.once("error",s)})}function Xs(o){let e=1,n=new Map;return o.on("message",t=>{let r;try{r=JSON.parse(String(t))}catch{return}if(!r.id)return;let i=n.get(r.id);i&&(n.delete(r.id),clearTimeout(i.timeout),r.error?i.reject(new Error(r.error.message||`CDP error ${r.error.code??""}`.trim())):i.resolve(r.result??{}))}),o.on("close",()=>{for(let[t,r]of n)clearTimeout(r.timeout),r.reject(new Error("CDP connection closed")),n.delete(t)}),(t,r={})=>new Promise((i,s)=>{let c=e++,d=setTimeout(()=>{n.delete(c),s(new Error(`CDP ${t} timed out`))},4e3);n.set(c,{resolve:i,reject:s,timeout:d}),o.send(JSON.stringify({id:c,method:t,params:r}),l=>{l&&(clearTimeout(d),n.delete(c),s(l))})})}async function br(o,e){let n=Vs(e.clip),t=await Ks(o),r=Ws(t,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Qs(r.webSocketDebuggerUrl),s=Xs(i),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Hs,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...n,scale:Math.max(.25,Math.min(4,e.scale??1))}}),l=typeof d.data=="string"?d.data:"";if(!l)throw new Error("CDP returned an empty screenshot");return Buffer.from(l,"base64")}finally{c&&await s("Runtime.evaluate",{expression:Gs,returnByValue:!0}).catch(()=>{}),i.close()}}import{mkdir as Or,readFile as Kt,writeFile as Dr}from"fs/promises";import{join as kt}from"path";var Ys=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function So(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Rn(o){return new Set(So(o).split(" ").filter(e=>e.length>2&&!Ys.has(e)))}function xr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Zs(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 ea(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(So).filter(Boolean),i=Rn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of Zs(s)){let l=So(d.value);for(let T of r){let b=l===T?95:l.includes(T)||T.includes(l)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let P=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(xr(Rn(l),i)*55);P>=30&&P>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:P>=45?"strong":"weak",matchedBy:"query_text",score:P})}c&&n.set(s.id,c)}return n}function ta(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),r=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.has(c.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let i=new Set(r.map(s=>s.state));return{state:i.size>1?"mixed":i.has("completed")?"completed":"attempted",attemptIds:r.map(s=>s.id)}}function na(o){return Math.ceil(JSON.stringify(o).length/4)}function Po(o,e){let n=o.records.filter(v=>v.recordType==="subject"),t=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,i=o.records.filter(v=>{if(v.recordType!=="proposal"||r&&!r.has(v.id))return!1;if(v.state==="pending")return!0;if(v.state!=="deferred")return!1;let w=[...o.events].reverse().find(m=>m.entity.entityType==="proposal"&&m.entity.entityId===v.id&&m.toState==="deferred"&&m.transitionContext?.kind==="proposal_deferral")?.transitionContext;return w?w.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||w.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||w.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||w.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||w.resurfaceWhen.includes("after_date")&&!!(w.revisitAfter&&Date.parse(t)>=Date.parse(w.revisitAfter)):!1}),s=o.records.filter(v=>v.recordType==="implementation_attempt"),c=ea(n,e),d=[...c.values()].sort((v,w)=>w.score-v.score),l=Rn([e.action,e.text].filter(Boolean).join(" ")),x=i.flatMap(v=>{let w=v.subjects.map(E=>c.get(E.subjectId)).filter(E=>!!E),m=Math.max(0,...w.map(E=>E.score)),u=Math.round(xr(Rn(v.claim),l)*35),R=m+u;return R>=50?[{proposal:v,proposalMatches:w,score:R}]:[]}).sort((v,w)=>w.score-v.score||v.proposal.id.localeCompare(w.proposal.id)),P=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),b=[],h=0;for(let v of x){if(b.length>=P)break;let w=v.proposal.sourceRefs.slice(0,4),m={contractVersion:1,packetId:`review:${v.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,trigger:{action:e.action,reason:v.proposalMatches.length?`Historical proposal intersects ${v.proposalMatches.map(R=>R.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:v.proposalMatches.map(({score:R,...E})=>E)},proposal:{id:v.proposal.id,claim:v.proposal.claim,state:v.proposal.state,proposedKind:v.proposal.proposedKind,subjectIds:v.proposal.subjects.map(R=>R.subjectId),origin:v.proposal.origin.mode},authority:"unaccepted",presentation:v.score>=100&&["constraint","rule"].includes(v.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ta(v.proposal,s),evidence:{sourceCount:v.proposal.sourceRefs.length,sourceRefs:w},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:v.proposal.id},...w]},u={...m,estimatedTokens:na(m)};if(h+u.estimatedTokens>T)break;b.push(u),h+=u.estimatedTokens}let p=Math.max(0,x.length-b.length);return{packets:b,subjectMatches:d.map(({score:v,...w})=>w),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:p,maxEstimatedTokens:T,estimatedTokens:h},uncertainty:c.size===0?"subject_unresolved":x.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 To(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function kn(o){return new Set(To(o).split(" ").filter(e=>e.length>2&&!oa.has(e)))}function Sr(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ra(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(To).filter(Boolean),r=kn([e.action,e.text].filter(Boolean).join(" ")),i=[];for(let s of o){if(n.has(s.id)){i.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(l=>({value:l,by:"alias"})),...s.locators.map(l=>({value:l.value,by:"locator"}))];for(let l of d){let x=To(l.value);for(let b of t){let h=x===b?95:x.includes(b)||b.includes(x)?75:0;h>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:h>=90?"exact":"strong",matchedBy:l.by,score:h})}let T=["/","#","[","]","="].some(b=>l.value.includes(b))?0:Math.round(Sr(kn(x),r)*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&&i.push(c)}return i.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function ia(o){return Math.ceil(JSON.stringify(o).length/4)}function Pt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function sa(o,e){let n=e.filter(i=>i.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(i=>i.state==="completed"),r=t.some(i=>i.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:r?"implemented":t.length?"partial":"unknown",attemptIds:n.map(i=>i.id)}}function aa(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),r=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),i=t[0],s=r?"stale":i?i.state==="passed"?"passing":i.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(i.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:t.map(c=>c.id)}}function Pr(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=Math.max(1,e.maxDecisions??6),r=o.records.filter(y=>y.recordType==="subject"),i=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(y=>y.recordType==="decision"&&y.state==="active"),c=i?s.filter(y=>i.has(y.id)):s,d=o.records.filter(y=>y.recordType==="implementation_attempt"),l=o.records.filter(y=>y.recordType==="verification_attempt"),x=o.records.filter(y=>y.recordType==="freshness_signal"&&y.state==="open"),P=o.records.filter(y=>y.recordType==="evidence"),T=o.records.filter(y=>y.recordType==="model_entry"),b=ra(r,e),h=new Map(b.map(y=>[y.subjectId,y.score])),p=kn([e.action,e.text].filter(Boolean).join(" ")),v=c.flatMap(y=>{let L=Math.max(0,...y.subjects.map(M=>h.get(M.subjectId)??0)),C=Math.round(Sr(kn(y.claim),p)*35),f=L+C;return f>=50?[{decision:y,score:f}]:[]}).sort((y,L)=>L.score-y.score||y.decision.id.localeCompare(L.decision.id)),w=new Map;for(let y of v.slice(0,t))w.set(y.decision.id,y.decision);for(let y of o.relationships){if(!Pt(y,"excepts")&&!Pt(y,"contradicts"))continue;let L=s.find(f=>f.id===y.from.entityId),C=s.find(f=>f.id===y.to.entityId);!L||!C||!w.has(L.id)&&!w.has(C.id)||(w.size<t&&w.set(L.id,L),w.size<t&&w.set(C.id,C))}let m=[...w.values()],u=y=>y.from.entityType==="decision"&&y.to.entityType==="decision"&&w.has(y.from.entityId)&&w.has(y.to.entityId),R=(y,L=!1)=>{let C=new Set(y.map(A=>A.id)),f=x.filter(A=>A.target.entityType==="decision"&&C.has(A.target.entityId)),M=new Set(o.relationships.filter(A=>Pt(A,"excepts")&&C.has(A.from.entityId)&&C.has(A.to.entityId)).flatMap(A=>[A.from.entityId,A.to.entityId])),B=o.relationships.filter(A=>Pt(A,"contradicts")&&C.has(A.from.entityId)&&C.has(A.to.entityId)).map(A=>({id:A.id,decisionIds:[A.from.entityId,A.to.entityId],unresolvedQuestion:A.reason,expansionRefs:[{kind:"record",id:A.id}]})),H=new Set(B.flatMap(A=>A.decisionIds)),V=P.filter(A=>A.sourceRefs.some(z=>z.kind==="record"&&C.has(z.id))||o.relationships.some(z=>z.relationshipType==="supports"&&z.from.entityType==="evidence"&&z.from.entityId===A.id&&z.to.entityType==="decision"&&C.has(z.to.entityId))),Y=Math.max(0,v.length-y.length),pe=o.relationships.some(A=>Pt(A,"contradicts")&&u(A)&&(!C.has(A.from.entityId)||!C.has(A.to.entityId))),Q=L||Y>0||pe,W=[];b.length===0&&(e.subjectHints?.length??0)>0?W.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):y.length===0&&W.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),B.length&&W.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:B.flatMap(A=>A.expansionRefs)}),V.some(A=>A.availability!=="available")&&W.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:V.map(A=>({kind:"record",id:A.id}))}),Q&&W.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let we={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:b.map(({score:A,...z})=>z),modelEntries:T.filter(A=>A.decisionIds.some(z=>C.has(z))).map(A=>({id:A.id,key:A.key,value:A.value,decisionIds:A.decisionIds})),decisions:y.map(A=>({id:A.id,kind:A.kind,claim:A.claim,subjectIds:A.subjects.map(z=>z.subjectId),authority:A.authority,effectiveState:H.has(A.id)?"conflicted":M.has(A.id)?"excepted":"active",freshness:f.filter(z=>z.target.entityId===A.id).map(z=>z.signalType),expansionRef:{kind:"record",id:A.id}})),conflicts:B,uncertainties:W,implementation:y.map(A=>sa(A.id,d)),verification:y.map(A=>aa(A.id,l,f)),evidence:V.map(A=>({evidenceId:A.id,summary:A.summary,availability:A.availability,sourceRefs:A.sourceRefs})),completeness:{status:Q?"truncated":"complete",omittedDecisionCount:Y,omittedEvidenceCount:0,conflictsComplete:!pe}};return we.budget.estimatedTokens=ia(we),we},E=R(m);for(;E.budget.estimatedTokens>n&&m.length>0;){let y=m.pop(),L=o.relationships.filter(C=>Pt(C,"contradicts")&&(C.from.entityId===y.id||C.to.entityId===y.id)).flatMap(C=>[C.from.entityId,C.to.entityId]);m=m.filter(C=>!L.includes(C.id)),E=R(m,!0)}return E}var ca=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Tt(o){return ca.test(o)}function da(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function Z(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function Ro(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Te(o,e,n){Tt(n)||Z(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Ve(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&Z(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function ft(o,e,n,t=!1){t&&n.level==="contributor"&&Z(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&Z(o,`${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->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"])},pa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ua(o,e,n){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.entity.entityId`,e.entity.entityId),Ve(o,`${n}.createdAt`,e.createdAt),ft(o,`${n}.authority`,e.authority);let t=la[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(r)&&Z(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let i=`${e.entity.entityType}:${e.toState}`;if(pa.has(i)&&(ft(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||Z(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&Z(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&Z(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Ve(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function ma(o,e,n,t){Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Ve(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&Z(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&Z(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&Z(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&Z(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(ft(o,`${n}.authority`,e.authority,!0),e.claim.trim()||Z(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Ro(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&Z(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Ve(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&Z(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&Z(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,i)=>{(!r.id.trim()||!r.modelPath.trim())&&Z(o,`${n}.concreteBindings[${i}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Ve(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),Ve(o,`${n}.concreteBindings[${i}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&Z(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Ve(o,`${n}.appliedAt`,e.appliedAt),ft(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&Z(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&Z(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&Z(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Ro(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Ro(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function fa(o,e,n){if(Te(o,`${n}.id`,e.id),Te(o,`${n}.projectId`,e.projectId),Te(o,`${n}.participantId`,e.participantId),Te(o,`${n}.from.entityId`,e.from.entityId),Te(o,`${n}.to.entityId`,e.to.entityId),Ve(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||Z(o,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let r=e.from.entityType==="decision"&&e.to.entityType==="decision",i=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!i&&Z(o,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?Z(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&ft(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&Z(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&Z(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&Z(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&Z(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function ht(o){let e=[];Te(e,"manifest.projectId",o.manifest.projectId),Ve(e,"manifest.createdAt",o.manifest.createdAt),Ve(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(p,v)=>{let w=n.get(p);w?Z(e,v,"duplicate_id",`ID is already used at ${w}.`):n.set(p,v)};o.records.forEach((p,v)=>{let w=`records[${v}]`;t(p.id,w),ma(e,p,w,o.manifest.projectId)}),o.events.forEach((p,v)=>{let w=`events[${v}]`;t(p.id,w),ua(e,p,w),p.projectId!==o.manifest.projectId&&Z(e,`${w}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,v)=>{let w=`relationships[${v}]`;t(p.id,w),fa(e,p,w),p.projectId!==o.manifest.projectId&&Z(e,`${w}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,v)=>{t(p.id,`artifacts[${v}]`),Te(e,`artifacts[${v}].id`,p.id)}),o.tombstones.forEach((p,v)=>{let w=`tombstones[${v}]`;t(p.id,w),Te(e,`${w}.id`,p.id),Te(e,`${w}.objectId`,p.objectId),Te(e,`${w}.deletedById`,p.deletedById),Ve(e,`${w}.deletedAt`,p.deletedAt),ft(e,`${w}.authority`,p.authority,!0)});let r=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),i=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,v)=>{let w=`${p.entityType}:${p.entityId}`;!r.has(w)&&!i.has(w)&&Z(e,v,"dangling_entity_reference",`No record or tombstone exists for ${w}.`)};o.events.forEach((p,v)=>s(p.entity,`events[${v}].entity`)),o.relationships.forEach((p,v)=>{s(p.from,`relationships[${v}].from`),s(p.to,`relationships[${v}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,v)=>{c.has(p)||Z(e,v,"dangling_artifact_reference","No artifact manifest entry exists.")},l=(p,v,w)=>{!r.has(`${p}:${v}`)&&!i.has(`${p}:${v}`)&&Z(e,w,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,v)=>{let w=`records[${v}]`;switch(p.recordType){case"authority_grant":l("participant",p.granteeId,`${w}.granteeId`),l("participant",p.grantedById,`${w}.grantedById`),p.subjectIds.forEach((m,u)=>l("subject",m,`${w}.subjectIds[${u}]`));break;case"observation":p.captureContext.subjectIds.forEach((m,u)=>l("subject",m,`${w}.captureContext.subjectIds[${u}]`)),p.captureContext.artifactIds.forEach((m,u)=>d(m,`${w}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":p.subjects.forEach((m,u)=>l("subject",m.subjectId,`${w}.subjects[${u}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((m,u)=>d(m,`${w}.messageArtifactIds[${u}]`)),p.resultRefs.forEach((m,u)=>s(m,`${w}.resultRefs[${u}]`));break;case"iteration":p.threadIds.forEach((m,u)=>l("thread",m,`${w}.threadIds[${u}]`)),p.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"evidence":p.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"advisory_explanation":p.subjectIds.forEach((m,u)=>l("subject",m,`${w}.subjectIds[${u}]`)),p.evidenceIds.forEach((m,u)=>l("evidence",m,`${w}.evidenceIds[${u}]`)),p.supersededById&&l("advisory_explanation",p.supersededById,`${w}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((m,u)=>l("iteration",m,`${w}.iterationIds[${u}]`)),p.coverageClaims.forEach((m,u)=>l("decision",m.decisionId,`${w}.coverageClaims[${u}].decisionId`)),p.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"eval_spec":p.replacesSpecId&&l("eval_spec",p.replacesSpecId,`${w}.replacesSpecId`),p.decisionIds.forEach((m,u)=>l("decision",m,`${w}.decisionIds[${u}]`)),p.subjectIds.forEach((m,u)=>l("subject",m,`${w}.subjectIds[${u}]`)),(p.dependencies??[]).forEach((m,u)=>{m.kind==="subject"&&m.subjectId&&l("subject",m.subjectId,`${w}.dependencies[${u}].subjectId`)}),(p.scenarios??[]).forEach((m,u)=>{m.subjectIds?.forEach((R,E)=>l("subject",R,`${w}.scenarios[${u}].subjectIds[${E}]`))}),p.targets.forEach((m,u)=>l(m.entityType,m.entityId,`${w}.targets[${u}]`));break;case"verification_attempt":p.evalSpecId&&l("eval_spec",p.evalSpecId,`${w}.evalSpecId`),p.targets.forEach((m,u)=>l(m.entityType,m.entityId,`${w}.targets[${u}]`)),p.evidenceIds.forEach((m,u)=>l("evidence",m,`${w}.evidenceIds[${u}]`));break;case"model_entry":p.subjectIds.forEach((m,u)=>l("subject",m,`${w}.subjectIds[${u}]`)),p.decisionIds.forEach((m,u)=>l("decision",m,`${w}.decisionIds[${u}]`));break;case"model_projection":ft(e,`${w}.authority`,p.authority,!0),l("participant",p.appliedById,`${w}.appliedById`),p.decisionIds.forEach((m,u)=>l("decision",m,`${w}.decisionIds[${u}]`)),p.entryIds.forEach((m,u)=>l("model_entry",m,`${w}.entryIds[${u}]`)),p.coverage.forEach((m,u)=>l("decision",m.decisionId,`${w}.coverage[${u}].decisionId`));break;case"freshness_signal":s(p.target,`${w}.target`),p.evidenceIds.forEach((m,u)=>l("evidence",m,`${w}.evidenceIds[${u}]`));break;default:break}});let x=new Map(o.events.map(p=>[p.id,p])),P=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),T=new Map;o.events.forEach((p,v)=>{let w=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,m=T.get(w)??new Set;m.add(p.toState),T.set(w,m),m.size>1&&Z(e,`events[${v}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),h=(p,v,w,m,u)=>{if(p.level!=="delegate"||!p.grantId)return;let R=b.get(p.grantId);if(!R){Z(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(R.granteeId!==v||R.level!=="delegate")&&Z(e,u,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let E=Date.parse(w);(E<Date.parse(R.startsAt)||R.endsAt&&E>Date.parse(R.endsAt)||R.revokedAt&&E>=Date.parse(R.revokedAt))&&Z(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),R.subjectIds.length&&m.length&&!m.every(y=>R.subjectIds.includes(y))&&Z(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&h(p.authority,p.acceptedById,p.createdAt,p.subjects.map(v=>v.subjectId),`records:${p.id}.authority`);o.events.forEach((p,v)=>{let w=P.get(`${p.entity.entityType}:${p.entity.entityId}`),m=w&&"subjects"in w?w.subjects.map(u=>u.subjectId):[];h(p.authority,p.participantId,p.createdAt,m,`events[${v}].authority`)}),o.relationships.forEach((p,v)=>{if(!p.authority)return;let w=[p.from,p.to].flatMap(m=>{let u=P.get(`${m.entityType}:${m.entityId}`);return u&&"subjects"in u?u.subjects.map(R=>R.subjectId):[]});h(p.authority,p.participantId,p.createdAt,w,`relationships[${v}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let v=x.get(p.acceptanceEventId);(!v||v.entity.entityType!=="proposal"||v.entity.entityId!==p.proposalId||v.toState!=="accepted")&&Z(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),v&&v.participantId!==p.acceptedById&&Z(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),P.has(`proposal:${p.proposalId}`)||Z(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)||Z(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())||Z(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(w=>w.recordType==="decision"&&w.proposalId===p.id)||Z(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return da(e)}function Gt(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Tr(o,e,n,t,r){return{id:r,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function 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 jn(o,e){let n=[],t=o.records.find(i=>i.recordType==="proposal"&&i.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Tt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of ha(e))Tt(i)||n.push({code:"invalid_generated_id",message:`${i} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let i={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Tr(o,t,e,i.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let i={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.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={...Gt(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...Gt(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Tr(o,i,e,c.id,e.decisionId),l={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:i.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[i,d],events:[s,c],relationships:[l]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:i.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let i={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let r={...Gt(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.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:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}import{createHash as ga}from"crypto";import{readFile as ya,readdir as va,realpath as wa}from"fs/promises";import{join as Wt,relative as Ia}from"path";var ba=["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 Rt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Le(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Rr(...o){return o.find(e=>!!e?.trim())?.trim()}function oe(o,e,n,t){let i=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=ga("sha256").update(`${o}\0${e}\0${n}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${i.slice(0,8)}-${i.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function ko(o,e){try{return JSON.parse(await ya(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function xa(o){let e=Rt(o);if(!e)return 0;let n=0,t=r=>{let i=Rt(r);if(!i){n+=1;return}for(let s of Object.values(i))t(s)};for(let r of Object.values(e))t(r);return n}function Sa(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function Vt(o){let e=[],n=await wa(o.projectRoot).catch(()=>o.projectRoot),t=Wt(n,".popmelt"),r=await ko(Wt(t,"threads.json"),e),i=await ko(Wt(t,"model.json"),e),s=Rt(r),c=Rt(s?.threads)??{},d=Object.entries(c).map(([z,re])=>({key:z,value:Rt(re)})).filter(z=>!!z.value),l=Wt(t,"decisions"),x=await va(l).catch(()=>[]),P=[];for(let z of x.filter(re=>re.endsWith(".json")).sort()){let re=Rt(await ko(Wt(l,z),e));re&&P.push({file:z,value:re})}let T=d.flatMap(({value:z})=>[z.createdAt,z.updatedAt]).filter(z=>typeof z=="number"&&Number.isFinite(z)),b=T.length?Math.min(...T):0,h=o.projectKey??n;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=oe(h,"project",h,b),v=oe(h,"participant","legacy-owner",b),w=oe(h,"participant","legacy-agent",b),m=oe(h,"subject","project",b),u=Le(Math.max(b,...T)),R=[],E=[],y=new Map,L=new Map,C=new Map(P.map(z=>[z.value.id??z.file.replace(/^d-|\.json$/g,""),z.value])),f=new Map,M=(z,re,ie,te,$e)=>{let Oe=y.get(ie);if(Oe)return Oe;let be=oe(h,"artifact",z,te);return E.push({id:be,kind:re,mediaType:$e,location:ie,availability:"available"}),y.set(ie,be),be};for(let{file:z,value:re}of P){let ie=re.id??z.replace(/^d-|\.json$/g,""),te=re.createdAt??b,$e=[M(`${ie}:envelope`,"other",`.popmelt/decisions/${z}`,te,"application/json")];re.screenshotPath&&$e.push(M(`${ie}:screenshot`,"screenshot",`.popmelt/${re.screenshotPath.replace(/^\.popmelt\//,"")}`,te,re.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Oe,be]of(re.pastedImagePaths??[]).entries())$e.push(M(`${ie}:image:${Oe}`,"image",be,te));f.set(ie,$e)}let D=(z,re,ie)=>({id:z,schemaVersion:1,projectId:p,createdAt:u,participantId:re,sourceRefs:ie}),B=(z,re)=>{R.push(re);let ie=L.get(z)??[];ie.push(re.id),L.set(z,ie)},H=[{...D(v,v,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...D(w,w,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];R.push(...H),R.push({...D(m,v,[]),recordType:"subject",subjectType:"project",label:Ia(process.cwd(),n)||n,aliases:[],locators:[{id:oe(h,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:Le(b),sourceRefs:[]}]});let V=new Map,Y=(z,re)=>{let ie=V.get(z);if(ie)return ie;let te=oe(h,"subject",z,re),$e={...D(te,v,[{kind:"external",id:z}]),createdAt:Le(re),recordType:"subject",subjectType:"element",label:z,aliases:[],locators:[{id:oe(h,"locator",z,re),kind:"dom_selector",value:z,status:"current",validFrom:Le(re),sourceRefs:[{kind:"external",id:z}]}]};return R.push($e),V.set(z,te),te};for(let{key:z,value:re}of d){let ie=re.id??z,te=re.createdAt??b,$e=oe(h,"thread",ie,te),Oe={kind:"thread",id:ie},be=[],Fe=[],at=Array.isArray(re.messages)?re.messages:[],Ue,vt,wt=0;at.forEach((ve,ot)=>{let Me=ve.timestamp??te,Ze=oe(h,"artifact",`${ie}:message:${ot}`,Me);if(be.push(Ze),E.push({id:Ze,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ie}/messages/${ot}`,availability:"available"}),y.set(`.popmelt/threads.json#/threads/${ie}/messages/${ot}`,Ze),ve.screenshotPath&&M(`${ie}:message:${ot}:screenshot`,"screenshot",ve.screenshotPath,Me),ve.role==="human"){Ue=ve;let De=ve.feedbackSummary??ve.replyToQuestion;if(De?.trim()){let Ne=oe(h,"observation",`${ie}:${ot}`,Me),st=re.elementIdentifiers??[],It={...D(Ne,v,[Oe,{kind:"message",id:Ze}]),createdAt:Le(Me),recordType:"observation",state:"open",statement:De,captureContext:{subjectIds:st.map(dt=>Y(dt,te)),artifactIds:[Ze]},resolvedByIds:[]};B(ie,It),vt=Ne,Fe.push({entityType:"observation",entityId:Ne})}return}if(ve.role!=="assistant")return;let rt=ve.jobId??`${ie}:${ot}`,it=oe(h,"iteration",rt,Me),ct=C.get(rt),ro=ve.cancelled?"cancelled":ve.error?"failed":ve.question?"question_asked":(ve.resolutions?.length??0)>0?"completed":"no_change",Bt={...D(it,w,[Oe,{kind:"message",id:Ze},...(f.get(rt)??[]).map(De=>({kind:"artifact",id:De}))]),createdAt:Le(Me),recordType:"iteration",threadIds:[$e],startedAt:Le(Ue?.timestamp,Me),completedAt:Le(Me),requestSummary:Rr(Ue?.feedbackSummary,Ue?.replyToQuestion)??"[legacy request unavailable]",responseSummary:ve.question??ve.error??ve.responseText?.slice(0,1e3),outcome:ro,execution:{provider:ve.provider??ct?.provider,model:ve.model??ct?.model,sessionId:ve.sessionId??ct?.sessionId},artifactIds:[Ze,...f.get(rt)??[]]};B(ie,Bt),Fe.push({entityType:"iteration",entityId:it});let Lt=ve.resolutions??ct?.resolutions??[];for(let[De,Ne]of Lt.entries()){if(Ne.status!=="resolved"||!Ne.summary?.trim())continue;let st=re.elementIdentifiers??[],It=(st.length?st:[n]).map(dn=>({subjectId:dn===n?m:Y(dn,te),role:"governed"})),dt=oe(h,"proposal",`${rt}:${Ne.annotationId??"resolution"}:${De}`,Me),io={...D(dt,w,[Oe,{kind:"iteration",id:it}]),createdAt:Le(Me),recordType:"proposal",state:"pending",claim:Ne.summary,subjects:It,subjectSemantics:It.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Rr(Ue?.feedbackSummary,Ue?.replyToQuestion,Ne.summary),iterationId:it,inferredById:w}};B(ie,io),Fe.push({entityType:"proposal",entityId:dt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ie,message:`Proposal ${dt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Lt.some(De=>De.status==="resolved")||ct?.gitDiff){let De=oe(h,"implementation",rt,Me),Ne={...D(De,w,[Oe,{kind:"iteration",id:it}]),createdAt:Le(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[it],coverageClaims:[],summary:Lt.map(st=>st.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};B(ie,Ne),Fe.push({entityType:"implementation_attempt",entityId:De}),wt+=1}vt&&(vt=void 0)});let cn=at.at(-1),oo={...D($e,v,[Oe]),createdAt:Le(te),recordType:"thread",state:cn?.question?"open":"resolved",messageArtifactIds:be,outcome:cn?.question?"question_unresolved":wt?"implementation_only":"no_outcome",resultRefs:Fe};R.push(oo),L.set(ie,[$e,...L.get(ie)??[]])}let pe=xa(i);pe&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${pe} model values were not promoted because their accepted decision provenance is unresolved.`});let Q={manifest:{formatVersion:1,projectId:p,createdAt:Le(b),updatedAt:u,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:R,events:[],relationships:[],artifacts:E,tombstones:[]},W=ht(Q),A=(o.proofCaseIds??ba).map(z=>({legacyId:z,threadFound:d.some(({key:re,value:ie})=>(ie.id??re)===z),decisionEnvelopeFound:C.has(z),recordIds:L.get(z)??[]}));return{bundle:Q,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((z,re)=>z+(re.value.messages?.length??0),0),decisionEnvelopes:P.length,modelEntries:pe,artifactsReferenced:E.length},imported:Sa(R),unresolvedAcceptance:e.filter(z=>z.code==="acceptance_unresolved").length,deferredModelEntries:pe,proofCases:A,issues:e,schemaIssues:W.issues}}}import{createHash as Pa}from"crypto";import{mkdir as kr,open as jo,readFile as Mo,readdir as Ta,rename as Ra,unlink as Ao}from"fs/promises";import{join as et}from"path";var ka={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function An(o){return Pa("sha256").update(JSON.stringify(o)).digest("hex")}function jr(o){return An(o)}function Mr(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let r=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(r<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let i=o.records[r];if(i.projectId!==t.projectId||i.createdAt!==t.createdAt||i.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[r]=structuredClone(t)}for(let t of e.projectionUpdates){let r=o.records.find(i=>i.recordType===t.entityType&&i.id===t.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(r.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${r.state}`);r.state=t.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=n,o}function ja(o,e,n){return Mr(structuredClone(o),e,n)}async function gt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await jo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
150
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Ra(n,o)}catch(r){throw await Ao(n).catch(()=>{}),r}}async function Mn(o){return JSON.parse(await Mo(o,"utf8"))}var En=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=et(e,".popmelt","memory"),this.journalDir=et(this.memoryDir,"journal"),this.manifestPath=et(this.memoryDir,"manifest.json"),this.checkpointPath=et(this.memoryDir,"checkpoint.json"),this.lockPath=et(this.memoryDir,"writer.lock")}async initialize(e){let n=ht(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await kr(this.journalDir,{recursive:!0});try{throw await Mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Mo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=An(e),r={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},i={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await gt(this.checkpointPath,r),await gt(this.manifestPath,i)})}async load(){let e=await this.loadInternal();return{bundle:e.bundle,report:e.report}}async recover(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();return e.report.recoveredTransactions>0&&(e.manifest.head={sequence:e.report.headSequence,hash:e.report.headHash},e.manifest.updatedAt=e.bundle.manifest.updatedAt,await gt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=An(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await gt(et(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await gt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Tt(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let r=t.report.headSequence+1,i={storageVersion:1,sequence:r,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...i,hash:jr(i)},c=ja(t.bundle,e,n.committedAt),d=ht(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let l=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await gt(et(this.journalDir,l),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await gt(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:r,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...ka,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Mn(this.manifestPath),n=await Mn(et(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==An(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Ta(this.journalDir),r=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,l=n.journalHash??null,x=new Set;for(let T of s){let b=await Mn(et(this.journalDir,T)),{hash:h,...p}=b;if(h!==jr(p))throw new Error(`Journal hash mismatch: ${T}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(b.previousHash!==l)throw new Error(`Journal chain mismatch at ${T}`);if(b.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(x.has(b.transactionId))throw new Error(`Duplicate transaction ID: ${b.transactionId}`);Mr(c,b.mutation,b.committedAt),d=b.sequence,l=b.hash,x.add(b.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==l)throw new Error("Journal manifest head hash mismatch.");let P=ht(c);if(!P.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(P.issues)}`);return{bundle:c,manifest:e,transactionIds:x,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:d,headHash:l}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await kr(this.memoryDir,{recursive:!0});let n;try{n=await jo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await Mn(this.lockPath).catch(()=>({})),i=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(s){i=s.code!=="ESRCH"}if(i)throw new Error("Memory journal is locked by another writer.");await Ao(this.lockPath),n=await jo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ao(this.lockPath).catch(()=>{})}}};import{randomBytes as Ma}from"crypto";function ye(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Ma(10).toString("hex"),r=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${r}${t.slice(4,7)}-${t.slice(7,19)}`}var Aa=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Ar(o,e){let n=o.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),t=o.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active");if(!n||!t)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=o.manifest.projectId,i=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=Aa(),l=d.records,x=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(R=>R.kind==="thread"&&R.id===e.threadId));x||(x={id:oe(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(u=>u.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},l.push(x));let P=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let R=o.records.find(E=>E.recordType==="subject"&&E.locators.some(y=>y.value===u&&y.status==="current"));R||(R={id:oe(r,"live-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:oe(r,"live-locator",u,e.createdAt),kind:"dom_selector",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(R)),P.push(R)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let R=o.records.find(E=>E.recordType==="subject"&&E.locators.some(y=>y.kind==="source_file"&&y.value===u&&y.status==="current"));R||(R={id:oe(r,"live-file-subject",u,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:u}],recordType:"subject",subjectType:"file",label:u,aliases:[],locators:[{id:oe(r,"live-file-locator",u,e.createdAt),kind:"source_file",value:u,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:u}]}]},l.push(R)),P.push(R)}let T=(e.semanticCandidates??[]).filter(u=>u.claim.trim()),b;if(T.length>0){b=oe(r,"live-observation",i,e.createdAt);let u={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(R=>R.claim.trim()).join(" "),captureContext:{subjectIds:P.map(R=>R.id),artifactIds:[]},resolvedByIds:[]};l.push(u)}let h=oe(r,"live-iteration",i,e.completedAt),p={id:h,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId},...b?[{kind:"record",id:b}]:[]],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:[]};l.push(p);let v=[],w=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),m=P.length>0?P:o.records.filter(u=>u.recordType==="subject"&&u.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[u,R]of T.entries()){let E=oe(r,"live-proposal",`${i}:${u}`,e.completedAt),y=m.map(C=>({subjectId:C.id,role:"governed"})),L={id:E,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:h},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:R.claim.trim(),rationale:R.rationale?.trim()||void 0,proposedKind:R.proposedKind,subjects:y,subjectSemantics:y.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:R.sourceText?.trim()||e.requestSummary,iterationId:h,inferredById:t.id}};l.push(L),v.push(E)}if(w.length>0){let u=new Set(e.governingDecisionIds??[]),R=o.records.filter(y=>y.recordType==="decision"&&y.state==="active"&&u.has(y.id)),E={id:oe(r,"live-implementation",i,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:h}],recordType:"implementation_attempt",state:"completed",iterationIds:[h],coverageClaims:R.map(y=>({decisionId:y.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${w.map(L=>L.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:h}]})),summary:w.map(y=>y.summary).join(" "),artifactIds:[]};l.push(E)}return{mutation:d,iterationId:h,proposalIds:v,observationId:b}}import{createHash as Ea}from"crypto";import{mkdir as _a,open as Ca,readFile as $a,rename as Oa,unlink as Da}from"fs/promises";import{join as Er}from"path";function _r(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Cr(o){return Ea("sha256").update(JSON.stringify(o)).digest("hex")}async function Na(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Ca(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
151
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Oa(n,o)}catch(r){throw await Da(n).catch(()=>{}),r}}function Ja(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,l,x)=>{let P=d[l]??=[];P.includes(x)||P.push(x)};for(let d of o.records)if(d.recordType==="subject"){let l=d;for(let x of[l.label,...l.aliases,...l.locators.filter(P=>P.status==="current").map(P=>P.value)]){let P=_r(x);P&&s(t,P,l.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let l of d.subjects)s(r,l.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let l of d.subjects)s(i,l.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:Cr(c)}}function $r(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[_r(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var _n=class{constructor(e){this.indexDir=Er(e,".popmelt","memory","indexes"),this.indexPath=Er(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await $a(this.indexPath,"utf8")),{checksum:i,...s}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===n.sequence&&r.journalHead.hash===n.hash&&i===Cr(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ja(e,n);return await _a(this.indexDir,{recursive:!0}),await Na(this.indexPath,t),t}};var Qt="popmelt:imprint",Nr="popmelt:imprint-evidence",jt="popmelt:imprint-relation";function Cn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Qt)?.id}function Eo(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function $n(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="instantiates"&&t.fromId===e?[t.toId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}var On=class{constructor(e){this.projectRoot=e;this.store=new En(e),this.indexStore=new _n(e),this.manifestPath=kt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await Kt(this.manifestPath,"utf8"));return{initialized:!0,state:"ready",projectId:e.projectId,headSequence:e.head.sequence,updatedAt:e.updatedAt}}catch(e){if(e.code==="ENOENT")return{initialized:!1,state:this.runtimeState?.state??"absent",phase:this.runtimeState?.phase,error:this.runtimeState?.error};throw e}}beginAutomaticInitialization(e={}){return this.initializationPromise?this.initializationPromise:(this.initializationPromise=(async()=>{this.runtimeState={state:"initializing",phase:"analyzing_legacy"};try{if((await this.status()).initialized){let r=await this.store.load();return r.report.recoveredTransactions>0&&(r=await this.store.recover()),await this.refreshIndex(r),await this.status()}let t=await Vt({...e,projectRoot:this.projectRoot});if(t.report.schemaIssues.some(r=>r.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(t.bundle)}catch(r){if(!(r instanceof Error)||!r.message.includes("already initialized"))throw r}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Vt({...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=kt(this.projectRoot,".popmelt","memory","migrations"),n=kt(e,"imprint-advisories-v2.json");try{let u=JSON.parse(await Kt(n,"utf8"));return{migrated:!1,explanations:u.explanations??0,evidence:u.evidence??0}}catch{}let t;try{t=JSON.parse(await Kt(kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Or(e,{recursive:!0}),await Dr(n,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let r=await this.store.load(),i=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),c=r.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active")??i,d=r.bundle.records.find(u=>u.recordType==="subject"&&u.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let l=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(u=>u.id)),P=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(R=>R.kind==="external"&&R.uri===jt?[R.id]:[]))),T=new Map,b=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let R=b.find(E=>Cn(E)===u.id);T.set(u.id,R?.id??oe(l,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let h=[],p=[],v=[],w=0;for(let u of t.explanations){let R=T.get(u.id),E=b.find(f=>f.id===R),y=[],L=u.evidence.length?u.evidence:[{id:`fallback:${u.id}`,kind:"observation",stance:"supports",summary:u.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:u.createdAt}];for(let f of L){let M=oe(l,"imprint-evidence-record",f.id,Date.parse(f.createdAt));y.push(M),!x.has(M)&&(h.push({id:M,schemaVersion:1,projectId:l,createdAt:f.createdAt,participantId:c.id,sourceRefs:Eo([{kind:"external",id:f.id,uri:Nr},{kind:"external",id:u.id,uri:Qt},{kind:"thread",id:f.threadId},{kind:"message",id:f.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(f.kind)?"user_feedback":"judgment",summary:f.summary,availability:"available",artifactIds:[]}),v.push({id:oe(l,"imprint-evidence-link",`${u.id}:${f.id}`,Date.parse(f.createdAt)),schemaVersion:1,projectId:l,createdAt:f.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:f.id,uri:Nr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:R},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),w+=1)}let C={id:R,schemaVersion:1,projectId:l,createdAt:E?.createdAt??u.createdAt,participantId:E?.participantId??c.id,sourceRefs:Eo([...E?.sourceRefs??[],{kind:"external",id:u.id,uri:Qt}]),recordType:"advisory_explanation",kind:u.kind,state:u.state,statement:u.statement,rationale:u.rationale,scope:structuredClone(u.scope),subjectIds:[d.id],evidenceIds:[...new Set([...E?.evidenceIds??[],...y])],concreteBindings:$n(t,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};E?p.push(C):h.push(C)}for(let u of t.relations){let R=T.get(u.fromId),E=T.get(u.toId);!R||!E||P.has(u.id)||v.push({id:oe(l,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:l,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:jt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:R},to:{entityType:"advisory_explanation",entityId:E},reason:u.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(h.length||p.length||v.length)try{let u=await this.store.commit({records:h,recordReplacements:p,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:oe(l,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:m});await this.refreshIndex(u)}catch(u){if(!(u instanceof Error)||!u.message.includes("Transaction already exists"))throw u}return await Or(e,{recursive:!0}),await Dr(n,JSON.stringify({version:2,migratedAt:m,explanations:t.explanations.length,evidence:w,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:w}}async review(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Po(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Pr(t.bundle,r),reviewSelection:Po(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:jn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await Vt({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),r=jn(t.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let i=await this.store.commitReviewPlan(r.plan,n);return await this.refreshIndex(i),i}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),r=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!r)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let i=Date.now(),s=new Date(i).toISOString(),c={proposalId:t.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:ye(i),decisionId:ye(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:ye(i),replacementProposalId:ye(i),acceptanceEventId:ye(i),decisionId:ye(i),relationshipId:ye(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:ye(i),reason:e.reason}:{...c,action:"defer",eventId:ye(i),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},l=jn(n.bundle,d);if(!l.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:l.errors.map(T=>T.message).join(" ")};let x=await this.store.commitReviewPlan(l.plan,{transactionId:ye(i),committedAt:s});await this.refreshIndex(x);let P=l.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:P,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 n=await this.store.load(),t=Ar(n.bundle,e),r=oe(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let i=await this.store.commit(t.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(i),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:i.report.headSequence}}catch(i){if(i instanceof Error&&i.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw i}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=JSON.parse(await Kt(kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}let t=await this.store.load(),r=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),i=t.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active"),s=e.action?r:i??r,c=t.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),l=Date.parse(d),x=t.bundle.manifest.projectId,P=[],T=[],b=[],h=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),p=new Map(h.flatMap(m=>{let u=Cn(m);return u?[[u,m.id]]:[]}));for(let m of e.summary.changes)if(!p.has(m.explanationId)){let u=n?.explanations.find(R=>R.id===m.explanationId);p.set(m.explanationId,oe(x,"imprint-explanation",m.explanationId,Date.parse(u?.createdAt??d)))}for(let m of e.summary.changes){let u={kind:"external",id:m.explanationId,uri:Qt},R=p.get(m.explanationId),E=h.find(f=>f.id===R),y=n?.explanations.find(f=>f.id===m.explanationId),L={id:oe(x,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};P.push(L);let C={id:R,schemaVersion:1,projectId:x,createdAt:E?.createdAt??y?.createdAt??d,participantId:E?.participantId??s.id,sourceRefs:Eo([...E?.sourceRefs??[],u,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:y?.kind??E?.kind??"pattern",state:y?.state??m.state,statement:y?.statement??m.statement,rationale:y?.rationale??E?.rationale??e.summary.detail,scope:structuredClone(y?.scope??E?.scope??{kind:"project",values:[]}),subjectIds:E?.subjectIds??[c.id],evidenceIds:[...new Set([...E?.evidenceIds??[],L.id])],concreteBindings:y?$n(n,m.explanationId):E?.concreteBindings??[],supersededById:y?.supersededBy?p.get(y.supersededBy):E?.supersededById,updatedAt:y?.updatedAt??d};E?T.push(C):P.push(C),b.push({id:oe(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,l),schemaVersion:1,projectId:x,createdAt:d,participantId:s.id,sourceRefs:[u],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:C.id},to:{entityType:"evidence",entityId:L.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let v=new Set(t.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(u=>u.kind==="external"&&u.uri===jt?[u.id]:[])));for(let m of n?.relations??[]){let u=p.get(m.fromId),R=p.get(m.toId);!u||!R||v.has(m.id)||b.push({id:oe(x,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:x,createdAt:m.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:m.id,uri:jt}],recordType:"relationship",relationshipType:m.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:R},reason:m.rationale||"The Imprint graph connected these explanations."})}let w=oe(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,l);try{let m=await this.store.commit({records:P,recordReplacements:T,events:[],relationships:b,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:w,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=JSON.parse(await Kt(kt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.status==="active"),i=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="ai"&&y.status==="active")??t;if(!i)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(y=>y.recordType==="subject"&&y.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(y=>y.recordType==="advisory_explanation"),l=new Map(d.flatMap(y=>{let L=Cn(y);return L?[[L,y]]:[]})),x=new Map([...[...l].map(([y,L])=>[y,L.id]),...e.explanations.filter(y=>!l.has(y.id)).map(y=>[y.id,oe(c,"imprint-explanation",y.id,Date.parse(y.createdAt))])]),P=[],T=[],b=new Set(e.explanations.map(y=>y.id));for(let y of e.explanations){let L=l.get(y.id);if(!L){P.push({id:x.get(y.id),schemaVersion:1,projectId:c,createdAt:y.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:y.id,uri:Qt}],recordType:"advisory_explanation",kind:y.kind,state:y.state,statement:y.statement,rationale:y.rationale,scope:structuredClone(y.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:$n(e,y.id),supersededById:y.supersededBy?x.get(y.supersededBy):void 0,updatedAt:y.updatedAt});continue}let C={...structuredClone(L),kind:y.kind,state:y.state,statement:y.statement,rationale:y.rationale,scope:structuredClone(y.scope),concreteBindings:$n(e,y.id),supersededById:y.supersededBy?x.get(y.supersededBy):void 0,updatedAt:y.updatedAt},f=M=>JSON.stringify({kind:M.kind,state:M.state,statement:M.statement,rationale:M.rationale,scope:M.scope,concreteBindings:M.concreteBindings,supersededById:M.supersededById,updatedAt:M.updatedAt});f(L)!==f(C)&&T.push(C)}for(let[y,L]of l)b.has(y)||L.state==="retired"||T.push({...structuredClone(L),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let h=new Set(n.bundle.tombstones.flatMap(y=>y.objectType==="relationship"?[y.objectId]:[])),p=new Map(n.bundle.relationships.flatMap(y=>{if(h.has(y.id))return[];let L=y.sourceRefs.find(C=>C.kind==="external"&&C.uri===jt)?.id;return L?[[L,y]]:[]})),v=new Set(p.keys()),w=[];for(let y of e.relations){let L=x.get(y.fromId),C=x.get(y.toId);!L||!C||v.has(y.id)||w.push({id:oe(c,"imprint-relation",y.id,Date.parse(y.createdAt)),schemaVersion:1,projectId:c,createdAt:y.createdAt,participantId:i.id,sourceRefs:[{kind:"external",id:y.id,uri:jt}],recordType:"relationship",relationshipType:y.type,from:{entityType:"advisory_explanation",entityId:L},to:{entityType:"advisory_explanation",entityId:C},reason:y.rationale||"The Imprint graph connected these explanations."})}let m=new Set(e.relations.map(y=>y.id)),u=t?[...p].filter(([y])=>!m.has(y)).map(([,y])=>({id:oe(c,"imprint-relationship-tombstone",y.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:y.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!P.length&&!T.length&&!w.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let R=e.updatedAt,E=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(R));try{let y=await this.store.commit({records:P,recordReplacements:T,events:[],relationships:w,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:E,committedAt:R});return await this.refreshIndex(y),{status:"synced",relationships:w.length+u.length,explanations:P.length+T.length,headSequence:y.report.headSequence}}catch(y){if(!(y instanceof Error)||!y.message.includes("Transaction already exists"))throw y;return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let r of n.bundle.records)t[r.recordType]=(t[r.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:n.bundle.records.filter(r=>r.recordType==="evidence"&&r.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),r=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),i=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.has(s.id)&&!r.has(s.id)&&!i.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(),n=new Set(e.records.flatMap(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),t=new Map;for(let r of e.records.filter(i=>i.recordType==="model_entry").sort((i,s)=>i.createdAt.localeCompare(s.createdAt)))r.decisionIds.some(i=>n.has(i))&&t.set(r.key,r);return[...t.values()]}async getImprintView(e=[]){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 t=await this.store.load(),r=t.bundle.records.filter(p=>p.recordType==="advisory_explanation"),i=new Map(r.map(p=>[p.id,p])),s=new Map(r.flatMap(p=>{let v=Cn(p);return v?[[v,p.id]]:[]})),c=new Set(e.map(p=>s.get(p)??p)),d=new Map(t.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),l=new Map(t.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),x=new Set(t.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),P=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),T={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=r.map(p=>{let v=p.evidenceIds.flatMap(u=>{let R=l.get(u);if(!R)return[];let E=R.sourceRefs.find(f=>f.kind==="thread")?.id,y=R.sourceRefs.find(f=>f.kind==="message")?.id,L=R.kind==="judgment"||R.kind==="user_feedback"||R.kind==="project_state"?R.kind:"other",C=d.get(R.participantId)??"unknown";return[{id:R.id,kind:L,summary:R.summary,createdAt:R.createdAt,participantKind:C,threadId:E,jobId:y}]}).sort((u,R)=>R.createdAt.localeCompare(u.createdAt)),w=t.bundle.relationships.flatMap(u=>{if(x.has(u.id))return[];if(!P.has(u.relationshipType))return[];let R=u.from.entityType==="advisory_explanation"&&u.from.entityId===p.id&&u.to.entityType==="advisory_explanation",E=u.to.entityType==="advisory_explanation"&&u.to.entityId===p.id&&u.from.entityType==="advisory_explanation";if(!R&&!E)return[];let y=R?u.to.entityId:u.from.entityId,L=i.get(y);return L?[{id:u.id,type:u.relationshipType,direction:R?"outgoing":"incoming",explanationId:L.id,statement:L.statement,rationale:u.reason}]:[]}),m=[...new Set([...p.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...v.flatMap(u=>u.threadId?[u.threadId]:[])])];return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:v.length,recentEvidence:v.slice(0,4),concrete:p.concreteBindings.map(u=>({...structuredClone(u)})),relations:w,sourceThreadIds:m,needsGrounding:p.state==="testing"&&c.has(p.id)}}).sort((p,v)=>Number(v.needsGrounding)-Number(p.needsGrounding)||T[p.state]-T[v.state]||v.updatedAt.localeCompare(p.updatedAt)),h={total:b.filter(p=>p.state!=="retired").length,emerging:b.filter(p=>p.state==="emerging").length,testing:b.filter(p=>p.state==="testing").length,grounded:b.filter(p=>p.state==="grounded").length,challenged:b.filter(p=>p.state==="challenged").length,retired:b.filter(p=>p.state==="retired").length,needsGrounding:b.filter(p=>p.needsGrounding).length};return{head:{sequence:t.report.headSequence,updatedAt:t.bundle.manifest.updatedAt},counts:h,explanations:b}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,l)=>d.createdAt.localeCompare(l.createdAt)))c.decisionIds.some(d=>n.has(d))&&t.set(c.key,c);let r=[...t.values()],i=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=i.filter(l=>l.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((l,x)=>x.createdAt.localeCompare(l.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(l=>l.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:r.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 n=await this.store.load(),t=n.bundle.records.find(f=>f.recordType==="participant"&&f.kind==="human"&&f.status==="active"),r=n.bundle.records.find(f=>f.recordType==="subject"&&f.subjectType==="project");if(!t||!r)throw new Error("Canonical owner or project subject is unavailable.");let i=Date.now(),s=new Date(i).toISOString(),c=ye(i),d=ye(i),l=ye(i),x=ye(i),P=ye(i),T=new Set(n.bundle.records.flatMap(f=>f.recordType==="model_entry"&&f.key===e.key?f.decisionIds:[])),b=n.bundle.records.filter(f=>f.recordType==="decision"&&f.state==="active"&&T.has(f.id)),h={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:r.id,role:"governed"}],v={...h,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},w={...h,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={...h,id:l,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},u={...h,id:x,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[l],value:e.value},R={...h,id:P,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[l],entryIds:[x],coverage:[{decisionId:l,status:"projected"}]},E={...h,id:ye(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:l},reason:"The model change is projected from the owner-confirmed decision."},y=b.map(f=>({...h,id:ye(i),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:f.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),L=b.map(f=>({...h,id:ye(i),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:m.id},to:{entityType:"decision",entityId:f.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),C=await this.store.commit({records:[v,m,u,R],events:[w,...y],relationships:[E,...L],artifacts:[],tombstones:[],projectionUpdates:b.map(f=>({entityType:"decision",entityId:f.id,fromState:"active",state:"superseded"}))},{transactionId:ye(i),committedAt:s});return await this.refreshIndex(C),{decisionId:l,entryId:x}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(i=>i.id===e));return t?{proposalId:t.id,claim:t.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 n=await this.store.load(),t=n.bundle.records.find(h=>h.recordType==="model_projection"&&h.state==="applied"&&h.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let r=n.bundle.records.filter(h=>h.recordType==="decision"&&e.decisionIds.includes(h.id)&&h.state==="active");if(r.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let i=n.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!i)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=ye(s),l=e.changes.map(h=>{let p=h.decisionIds?.filter(m=>e.decisionIds.includes(m)),v=p?.length?p:e.decisionIds,w=[...new Set(r.filter(m=>v.includes(m.id)).flatMap(m=>m.subjects.map(u=>u.subjectId)))];return{id:ye(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:v.map(m=>({kind:"record",id:m})),recordType:"model_entry",key:h.path.map(String).join("."),subjectIds:w,decisionIds:v,value:h.value}}),x=new Set(l.flatMap(h=>h.decisionIds)),P={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:e.decisionIds.map(h=>({kind:"record",id:h})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:l.map(h=>h.id),coverage:e.decisionIds.map(h=>e.coverage?.find(p=>p.decisionId===h)??{decisionId:h,status:x.has(h)?"projected":"unprojected"})},T=l.flatMap(h=>h.decisionIds.map(p=>({id:ye(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:P.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...l,P],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ye(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:l.map(h=>h.id),headSequence:b.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await Vt({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),r=$r(t,n.subjectHints??[]);return r?{...n,subjectIds:[...new Set([...n.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function At(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Ie(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function Mt(o,e,n){let t=Ie(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function _o(o){let e=At(o),n=At(e.authority),t=n.level,r=n.mode,i=Mt(t,"authority.level",["owner","delegate","contributor"]),s=Mt(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Ie(e.proposalId,"proposalId"),participantId:Ie(e.participantId,"participantId"),occurredAt:Ie(e.occurredAt,"occurredAt"),authority:{level:i,mode:s,grantId:typeof n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Ie(e.eventId,"eventId"),decisionId:Ie(e.decisionId,"decisionId"),kind:Mt(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Ie(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Ie(e.eventId,"eventId"),reason:Ie(e.reason,"reason")};case"defer":{let d=At(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:Ie(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(l=>Ie(l,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(l=>Mt(l,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Ie(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Ie(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Ie(e.acceptanceEventId,"acceptanceEventId"),decisionId:Ie(e.decisionId,"decisionId"),relationshipId:Ie(e.relationshipId,"relationshipId"),claim:Ie(e.claim,"claim"),kind:Mt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let l=At(d);return{subjectId:Ie(l.subjectId,"subjectId"),role:Mt(l.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Ie(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Co(o){let e=At(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>Ie(c,s))}},t=(i,s)=>{if(i!==void 0){if(typeof i!="number"||!Number.isFinite(i)||i<=0)throw new Error(`${s} must be a positive number.`);return i}},r=e.resurface===void 0?void 0:At(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}function Dn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
152
|
-
`)}async function
|
|
153
|
-
`)}function
|
|
151
|
+
`;function $n(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Pa(o,e){let n=$n(e);if(!n)return null;let t=new URL(n),i=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&$n(s.url)),r=i.find(s=>$n(s.url)===n);return r||(i.find(s=>{let c=new URL($n(s.url));return c.origin===t.origin&&c.pathname===t.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 ka(o){let e=new AbortController,n=setTimeout(()=>e.abort(),1e3);try{let t=new URL("/json/list",o).href,i=await fetch(t,{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(n)}}async function ja(o){let{WebSocket:e}=await import("ws");return new Promise((n,t)=>{let i=new e(o,{handshakeTimeout:1e3}),r=()=>{i.off("error",s),n(i)},s=c=>{i.off("open",r),t(c)};i.once("open",r),i.once("error",s)})}function Aa(o){let e=1,n=new Map;return o.on("message",t=>{let i;try{i=JSON.parse(String(t))}catch{return}if(!i.id)return;let r=n.get(i.id);r&&(n.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[t,i]of n)clearTimeout(i.timeout),i.reject(new Error("CDP connection closed")),n.delete(t)}),(t,i={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{n.delete(c),s(new Error(`CDP ${t} timed out`))},4e3);n.set(c,{resolve:r,reject:s,timeout:d}),o.send(JSON.stringify({id:c,method:t,params:i}),p=>{p&&(clearTimeout(d),n.delete(c),s(p))})})}async function Ui(o,e){let n=Ra(e.clip),t=await ka(o),i=Pa(t,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:{...n,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:Ta,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as sr,readFile as rn,writeFile as ar}from"fs/promises";import{join as Dt}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 No(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function On(o){return new Set(No(o).split(" ").filter(e=>e.length>2&&!Ma.has(e)))}function zi(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/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 n=new Map,t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(No).filter(Boolean),r=On([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(t.has(s.id)){n.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 p=No(d.value);for(let T of i){let k=p===T?95:p.includes(T)||T.includes(p)?75:0;k>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:k>=90?"exact":"strong",matchedBy:d.by,score:k})}let x=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(zi(On(p),r)*55);x>=30&&x>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:x>=45?"strong":"weak",matchedBy:"query_text",score:x})}c&&n.set(s.id,c)}return n}function Ca(o,e){let n=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),t=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>n.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&t.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 Bo(o,e){let n=o.records.filter(l=>l.recordType==="subject"),t=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 h=[...o.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(t)>=Date.parse(h.revisitAfter)):!1}),s=o.records.filter(l=>l.recordType==="implementation_attempt"),c=_a(n,e),d=[...c.values()].sort((l,h)=>h.score-l.score),p=On([e.action,e.text].filter(Boolean).join(" ")),w=r.flatMap(l=>{let h=l.subjects.map(S=>c.get(S.subjectId)).filter(S=>!!S),u=Math.max(0,...h.map(S=>S.score)),m=Math.round(zi(On(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)),x=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),k=[],y=0;for(let l of w){if(k.length>=x)break;let h=l.proposal.sourceRefs.slice(0,4),u={contractVersion:1,packetId:`review:${l.proposal.id}`,projectId:o.manifest.projectId,generatedAt:t,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,...S})=>S)},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: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(y+m.estimatedTokens>T)break;k.push(m),y+=m.estimatedTokens}let f=Math.max(0,w.length-k.length);return{packets:k,subjectMatches:d.map(({score:l,...h})=>h),completeness:{status:f>0?"truncated":"complete",consideredProposalCount:w.length,omittedPacketCount:f,maxEstimatedTokens:T,estimatedTokens:y},uncertainty:c.size===0?"subject_unresolved":w.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 Jo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dn(o){return new Set(Jo(o).split(" ").filter(e=>e.length>2&&!Oa.has(e)))}function Gi(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function Da(o,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(Jo).filter(Boolean),i=Dn([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(n.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 w=Jo(p.value);for(let k of t){let y=w===k?95:w.includes(k)||k.includes(w)?75:0;y>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:y>=90?"exact":"strong",matchedBy:p.by,score:y})}let T=["/","#","[","]","="].some(k=>p.value.includes(k))?0:Math.round(Gi(Dn(w),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 _t(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function Ba(o,e){let n=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!n.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let t=n.filter(r=>r.state==="completed"),i=t.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":t.length?"partial":"unknown",attemptIds:n.map(r=>r.id)}}function Ja(o,e,n){let t=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),i=n.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=t[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:t.map(c=>c.id)}}function Wi(o,e){let n=Math.max(300,e.maxEstimatedTokens??1200),t=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"),p=o.records.filter(g=>g.recordType==="verification_attempt"),w=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),x=o.records.filter(g=>g.recordType==="evidence"),T=o.records.filter(g=>g.recordType==="model_entry"),k=Da(i,e),y=new Map(k.map(g=>[g.subjectId,g.score])),f=Dn([e.action,e.text].filter(Boolean).join(" ")),l=c.flatMap(g=>{let J=Math.max(0,...g.subjects.map(N=>y.get(N.subjectId)??0)),E=Math.round(Gi(Dn(g.claim),f)*35),R=J+E;return R>=50?[{decision:g,score:R}]:[]}).sort((g,J)=>J.score-g.score||g.decision.id.localeCompare(J.decision.id)),h=new Map;for(let g of l.slice(0,t))h.set(g.decision.id,g.decision);for(let g of o.relationships){if(!_t(g,"excepts")&&!_t(g,"contradicts"))continue;let J=s.find(R=>R.id===g.from.entityId),E=s.find(R=>R.id===g.to.entityId);!J||!E||!h.has(J.id)&&!h.has(E.id)||(h.size<t&&h.set(J.id,J),h.size<t&&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,J=!1)=>{let E=new Set(g.map(B=>B.id)),R=w.filter(B=>B.target.entityType==="decision"&&E.has(B.target.entityId)),N=new Set(o.relationships.filter(B=>_t(B,"excepts")&&E.has(B.from.entityId)&&E.has(B.to.entityId)).flatMap(B=>[B.from.entityId,B.to.entityId])),K=o.relationships.filter(B=>_t(B,"contradicts")&&E.has(B.from.entityId)&&E.has(B.to.entityId)).map(B=>({id:B.id,decisionIds:[B.from.entityId,B.to.entityId],unresolvedQuestion:B.reason,expansionRefs:[{kind:"record",id:B.id}]})),W=new Set(K.flatMap(B=>B.decisionIds)),Q=x.filter(B=>B.sourceRefs.some(D=>D.kind==="record"&&E.has(D.id))||o.relationships.some(D=>D.relationshipType==="supports"&&D.from.entityType==="evidence"&&D.from.entityId===B.id&&D.to.entityType==="decision"&&E.has(D.to.entityId))),b=Math.max(0,l.length-g.length),H=o.relationships.some(B=>_t(B,"contradicts")&&m(B)&&(!E.has(B.from.entityId)||!E.has(B.to.entityId))),L=J||b>0||H,O=[];k.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(B=>B.expansionRefs)}),Q.some(B=>B.availability!=="available")&&O.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(B=>({kind:"record",id:B.id}))}),L&&O.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let fe={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:k.map(({score:B,...D})=>D),modelEntries:T.filter(B=>B.decisionIds.some(D=>E.has(D))).map(B=>({id:B.id,key:B.key,value:B.value,decisionIds:B.decisionIds})),decisions:g.map(B=>({id:B.id,kind:B.kind,claim:B.claim,subjectIds:B.subjects.map(D=>D.subjectId),authority:B.authority,effectiveState:W.has(B.id)?"conflicted":N.has(B.id)?"excepted":"active",freshness:R.filter(D=>D.target.entityId===B.id).map(D=>D.signalType),expansionRef:{kind:"record",id:B.id}})),conflicts:K,uncertainties:O,implementation:g.map(B=>Ba(B.id,d)),verification:g.map(B=>Ja(B.id,p,R)),evidence:Q.map(B=>({evidenceId:B.id,summary:B.summary,availability:B.availability,sourceRefs:B.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:b,omittedEvidenceCount:0,conflictsComplete:!H}};return fe.budget.estimatedTokens=Na(fe),fe},S=j(u);for(;S.budget.estimatedTokens>n&&u.length>0;){let g=u.pop(),J=o.relationships.filter(E=>_t(E,"contradicts")&&(E.from.entityId===g.id||E.to.entityId===g.id)).flatMap(E=>[E.from.entityId,E.to.entityId]);u=u.filter(E=>!J.includes(E.id)),S=j(u,!0)}return S}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 Ct(o){return La.test(o)}function Fa(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function te(o,e,n,t){o.push({path:e,code:n,message:t,severity:"error"})}function Lo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function ke(o,e,n){Ct(n)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(o,e,n){(!n||Number.isNaN(Date.parse(n)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,n,t=!1){t&&n.level==="contributor"&&te(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&te(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var qa={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->emerging","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},Ua=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function za(o,e,n){ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),ke(o,`${n}.entity.entityId`,e.entity.entityId),Qe(o,`${n}.createdAt`,e.createdAt),wt(o,`${n}.authority`,e.authority);let t=qa[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;t&&!t.has(i)&&te(o,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(Ua.has(r)&&(wt(o,`${n}.authority`,e.authority,!0),e.reason?.trim()||te(o,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&te(o,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(o,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Qe(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function Ga(o,e,n,t){ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),Qe(o,`${n}.createdAt`,e.createdAt),e.projectId!==t&&te(o,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(o,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(o,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&te(o,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${n}.authority`,e.authority,!0),e.claim.trim()||te(o,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Lo(o,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&te(o,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Qe(o,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(o,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&te(o,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&te(o,`${n}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Qe(o,`${n}.concreteBindings[${r}].createdAt`,i.createdAt),Qe(o,`${n}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Qe(o,`${n}.appliedAt`,e.appliedAt),wt(o,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&te(o,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&te(o,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&te(o,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Lo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Lo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Wa(o,e,n){if(ke(o,`${n}.id`,e.id),ke(o,`${n}.projectId`,e.projectId),ke(o,`${n}.participantId`,e.participantId),ke(o,`${n}.from.entityId`,e.from.entityId),ke(o,`${n}.to.entityId`,e.to.entityId),Qe(o,`${n}.createdAt`,e.createdAt),e.reason.trim()||te(o,`${n}.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,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?te(o,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&wt(o,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(o,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(o,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&te(o,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(o,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];ke(e,"manifest.projectId",o.manifest.projectId),Qe(e,"manifest.createdAt",o.manifest.createdAt),Qe(e,"manifest.updatedAt",o.manifest.updatedAt);let n=new Map,t=(f,l)=>{let h=n.get(f);h?te(e,l,"duplicate_id",`ID is already used at ${h}.`):n.set(f,l)};o.records.forEach((f,l)=>{let h=`records[${l}]`;t(f.id,h),Ga(e,f,h,o.manifest.projectId)}),o.events.forEach((f,l)=>{let h=`events[${l}]`;t(f.id,h),za(e,f,h),f.projectId!==o.manifest.projectId&&te(e,`${h}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((f,l)=>{let h=`relationships[${l}]`;t(f.id,h),Wa(e,f,h),f.projectId!==o.manifest.projectId&&te(e,`${h}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((f,l)=>{t(f.id,`artifacts[${l}]`),ke(e,`artifacts[${l}].id`,f.id)}),o.tombstones.forEach((f,l)=>{let h=`tombstones[${l}]`;t(f.id,h),ke(e,`${h}.id`,f.id),ke(e,`${h}.objectId`,f.objectId),ke(e,`${h}.deletedById`,f.deletedById),Qe(e,`${h}.deletedAt`,f.deletedAt),wt(e,`${h}.authority`,f.authority,!0)});let i=new Set(o.records.map(f=>`${f.recordType}:${f.id}`)),r=new Set(o.tombstones.map(f=>`${f.objectType}:${f.objectId}`)),s=(f,l)=>{let h=`${f.entityType}:${f.entityId}`;!i.has(h)&&!r.has(h)&&te(e,l,"dangling_entity_reference",`No record or tombstone exists for ${h}.`)};o.events.forEach((f,l)=>s(f.entity,`events[${l}].entity`)),o.relationships.forEach((f,l)=>{s(f.from,`relationships[${l}].from`),s(f.to,`relationships[${l}].to`)});let c=new Set(o.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)=>{!i.has(`${f}:${l}`)&&!r.has(`${f}:${l}`)&&te(e,h,"dangling_entity_reference",`No ${f} record or tombstone exists.`)};o.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,S)=>p("subject",j,`${h}.scenarios[${m}].subjectIds[${S}]`))}),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":wt(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 w=new Map(o.events.map(f=>[f.id,f])),x=new Map(o.records.map(f=>[`${f.recordType}:${f.id}`,f])),T=new Map;o.events.forEach((f,l)=>{let h=`${f.entity.entityType}:${f.entity.entityId}:${f.fromState??"null"}`,u=T.get(h)??new Set;u.add(f.toState),T.set(h,u),u.size>1&&te(e,`events[${l}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let k=new Map(o.records.flatMap(f=>f.recordType==="authority_grant"?[[f.id,f]]:[])),y=(f,l,h,u,m)=>{if(f.level!=="delegate"||!f.grantId)return;let j=k.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 S=Date.parse(h);(S<Date.parse(j.startsAt)||j.endsAt&&S>Date.parse(j.endsAt)||j.revokedAt&&S>=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 o.records)f.recordType==="decision"&&y(f.authority,f.acceptedById,f.createdAt,f.subjects.map(l=>l.subjectId),`records:${f.id}.authority`);o.events.forEach((f,l)=>{let h=x.get(`${f.entity.entityType}:${f.entity.entityId}`),u=h&&"subjects"in h?h.subjects.map(m=>m.subjectId):[];y(f.authority,f.participantId,f.createdAt,u,`events[${l}].authority`)}),o.relationships.forEach((f,l)=>{if(!f.authority)return;let h=[f.from,f.to].flatMap(u=>{let m=x.get(`${u.entityType}:${u.entityId}`);return m&&"subjects"in m?m.subjects.map(j=>j.subjectId):[]});y(f.authority,f.participantId,f.createdAt,h,`relationships[${l}].authority`)});for(let f of o.records){if(f.recordType!=="decision")continue;let l=w.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."),x.has(`proposal:${f.proposalId}`)||te(e,`records:${f.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),f.state==="superseded"&&(o.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"&&(o.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 o.records){if(f.recordType!=="proposal"||f.state!=="accepted")continue;o.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 Fa(e)}function tn(o,e,n,t){return{id:t,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function Hi(o,e,n,t,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:t,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function 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 Nn(o,e){let n=[],t=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);t?t.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${t.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Ct(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of Ha(e))Ct(r)||n.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!t)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...tn(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Hi(o,t,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.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:t.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={...tn(o,t,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...tn(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Hi(o,r,e,c.id,e.decisionId),p={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:t.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:t.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[r,d],events:[s,c],relationships:[p]},projectionUpdates:[{entityType:"proposal",entityId:t.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={...tn(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:t.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}let i={...tn(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.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:t.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:t.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:t.id}]}}}var Vi={project:0,route:1,component:2,selector:2,file:3},Ki={intention:0,principle:1,pattern:2};function $t(o,e){let n=Vi[o.scope.kind]-Vi[e.scope.kind];return n!==0?n:Ki[o.kind]-Ki[e.kind]}function Qi(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 n=o.explanations.find(r=>r.id===e.fromId),t=o.explanations.find(r=>r.id===e.toId);if(!n||!t)return;let i=$t(n,t);return i===0?void 0:i>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function xt(o){let e=structuredClone(o),n=new Set;return e.relations=o.relations.flatMap(t=>{let i=Va(o,t);if(!i)return[];let r=`${i.type}:${i.fromId}:${i.toId}`;return n.has(r)?[]:(n.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 nn,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 Ot(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function Ge(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Xi(...o){return o.find(e=>!!e?.trim())?.trim()}function ie(o,e,n,t){let r=Math.max(0,Math.min(Math.floor(t),0xffffffffffff)).toString(16).padStart(12,"0"),s=Ka("sha256").update(`${o}\0${e}\0${n}`).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 Fo(o,e){try{return JSON.parse(await Qa(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function tc(o){let e=Ot(o);if(!e)return 0;let n=0,t=i=>{let r=Ot(i);if(!r){n+=1;return}for(let s of Object.values(r))t(s)};for(let i of Object.values(e))t(i);return n}function nc(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function on(o){let e=[],n=await Ya(o.projectRoot).catch(()=>o.projectRoot),t=nn(n,".popmelt"),i=await Fo(nn(t,"threads.json"),e),r=await Fo(nn(t,"model.json"),e),s=Ot(i),c=Ot(s?.threads)??{},d=Object.entries(c).map(([D,Z])=>({key:D,value:Ot(Z)})).filter(D=>!!D.value),p=nn(t,"decisions"),w=await Xa(p).catch(()=>[]),x=[];for(let D of w.filter(Z=>Z.endsWith(".json")).sort()){let Z=Ot(await Fo(nn(p,D),e));Z&&x.push({file:D,value:Z})}let T=d.flatMap(({value:D})=>[D.createdAt,D.updatedAt]).filter(D=>typeof D=="number"&&Number.isFinite(D)),k=T.length?Math.min(...T):0,y=o.projectKey??n;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let f=ie(y,"project",y,k),l=ie(y,"participant","legacy-owner",k),h=ie(y,"participant","legacy-agent",k),u=ie(y,"subject","project",k),m=Ge(Math.max(k,...T)),j=[],S=[],g=new Map,J=new Map,E=new Map(x.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 We=ie(y,"artifact",D,Re);return S.push({id:We,kind:Z,mediaType:se,location:ae,availability:"available"}),g.set(ae,We),We};for(let{file:D,value:Z}of x){let ae=Z.id??D.replace(/^d-|\.json$/g,""),Re=Z.createdAt??k,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,We]of(Z.pastedImagePaths??[]).entries())se.push(N(`${ae}:image:${qe}`,"image",We,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=J.get(D)??[];ae.push(Z.id),J.set(D,ae)},W=[{...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(...W),j.push({...V(u,l,[]),recordType:"subject",subjectType:"project",label:Za(process.cwd(),n)||n,aliases:[],locators:[{id:ie(y,"locator",n,k),kind:"project_root",value:n,status:"current",validFrom:Ge(k),sourceRefs:[]}]});let Q=new Map,b=(D,Z)=>{let ae=Q.get(D);if(ae)return ae;let Re=ie(y,"subject",D,Z),se={...V(Re,l,[{kind:"external",id:D}]),createdAt:Ge(Z),recordType:"subject",subjectType:"element",label:D,aliases:[],locators:[{id:ie(y,"locator",D,Z),kind:"dom_selector",value:D,status:"current",validFrom:Ge(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??k,se=ie(y,"thread",ae,Re),qe={kind:"thread",id:ae},We=[],je=[],ct=Array.isArray(Z.messages)?Z.messages:[],He,dt,Vt=0;ct.forEach((xe,lt)=>{let _e=xe.timestamp??Re,tt=ie(y,"artifact",`${ae}:message:${lt}`,_e);if(We.push(tt),S.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ae}/messages/${lt}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${ae}/messages/${lt}`,tt),xe.screenshotPath&&N(`${ae}:message:${lt}:screenshot`,"screenshot",xe.screenshotPath,_e),xe.role==="human"){He=xe;let Ne=xe.feedbackSummary??xe.replyToQuestion;if(Ne?.trim()){let Be=ie(y,"observation",`${ae}:${lt}`,_e),mt=Z.elementIdentifiers??[],kt={...V(Be,l,[qe,{kind:"message",id:tt}]),createdAt:Ge(_e),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:mt.map(gt=>b(gt,Re)),artifactIds:[tt]},resolvedByIds:[]};K(ae,kt),dt=Be,je.push({entityType:"observation",entityId:Be})}return}if(xe.role!=="assistant")return;let pt=xe.jobId??`${ae}:${lt}`,ut=ie(y,"iteration",pt,_e),ft=E.get(pt),ho=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",go={...V(ut,h,[qe,{kind:"message",id:tt},...(R.get(pt)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:Ge(_e),recordType:"iteration",threadIds:[se],startedAt:Ge(He?.timestamp,_e),completedAt:Ge(_e),requestSummary:Xi(He?.feedbackSummary,He?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:ho,execution:{provider:xe.provider??ft?.provider,model:xe.model??ft?.model,sessionId:xe.sessionId??ft?.sessionId},artifactIds:[tt,...R.get(pt)??[]]};K(ae,go),je.push({entityType:"iteration",entityId:ut});let ht=xe.resolutions??ft?.resolutions??[];for(let[Ne,Be]of ht.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let mt=Z.elementIdentifiers??[],kt=(mt.length?mt:[n]).map(vn=>({subjectId:vn===n?u:b(vn,Re),role:"governed"})),gt=ie(y,"proposal",`${pt}:${Be.annotationId??"resolution"}:${Ne}`,_e),yo={...V(gt,h,[qe,{kind:"iteration",id:ut}]),createdAt:Ge(_e),recordType:"proposal",state:"pending",claim:Be.summary,subjects:kt,subjectSemantics:kt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Xi(He?.feedbackSummary,He?.replyToQuestion,Be.summary),iterationId:ut,inferredById:h}};K(ae,yo),je.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ae,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(ht.some(Ne=>Ne.status==="resolved")||ft?.gitDiff){let Ne=ie(y,"implementation",pt,_e),Be={...V(Ne,h,[qe,{kind:"iteration",id:ut}]),createdAt:Ge(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[ut],coverageClaims:[],summary:ht.map(mt=>mt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(ae,Be),je.push({entityType:"implementation_attempt",entityId:Ne}),Vt+=1}dt&&(dt=void 0)});let Rt=ct.at(-1),fo={...V(se,l,[qe]),createdAt:Ge(Re),recordType:"thread",state:Rt?.question?"open":"resolved",messageArtifactIds:We,outcome:Rt?.question?"question_unresolved":Vt?"implementation_only":"no_outcome",resultRefs:je};j.push(fo),J.set(ae,[se,...J.get(ae)??[]])}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:f,createdAt:Ge(k),updatedAt:m,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:S,tombstones:[]},O=bt(L),B=(o.proofCaseIds??ec).map(D=>({legacyId:D,threadFound:d.some(({key:Z,value:ae})=>(ae.id??Z)===D),decisionEnvelopeFound:E.has(D),recordIds:J.get(D)??[]}));return{bundle:L,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((D,Z)=>D+(Z.value.messages?.length??0),0),decisionEnvelopes:x.length,modelEntries:H,artifactsReferenced:S.length},imported:nc(j),unresolvedAcceptance:e.filter(D=>D.code==="acceptance_unresolved").length,deferredModelEntries:H,proofCases:B,issues:e,schemaIssues:O.issues}}}import{createHash as oc}from"crypto";import{mkdir as Yi,open as qo,readFile as Uo,readdir as ic,rename as rc,unlink as zo}from"fs/promises";import{join as nt}from"path";var sc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Jn(o){return oc("sha256").update(JSON.stringify(o)).digest("hex")}function Zi(o){return Jn(o)}function er(o,e,n){[...e.records,...e.recordReplacements??[]].some(t=>t.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let t of e.recordReplacements??[]){if(t.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${t.recordType}.`);let i=o.records.findIndex(s=>s.recordType===t.recordType&&s.id===t.id);if(i<0)throw new Error(`Record replacement target not found: ${t.recordType} ${t.id}`);let r=o.records[i];if(r.projectId!==t.projectId||r.createdAt!==t.createdAt||r.participantId!==t.participantId)throw new Error(`Record replacement changed immutable identity for ${t.id}.`);o.records[i]=structuredClone(t)}for(let t of e.projectionUpdates){let i=o.records.find(r=>r.recordType===t.entityType&&r.id===t.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${t.entityType} ${t.entityId}`);if(i.state!==t.fromState)throw new Error(`Projection state conflict for ${t.entityType} ${t.entityId}: expected ${t.fromState}, found ${i.state}`);i.state=t.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=n,o}function ac(o,e,n){return er(structuredClone(o),e,n)}async function St(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await qo(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
152
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await rc(n,o)}catch(i){throw await zo(n).catch(()=>{}),i}}async function Bn(o){return JSON.parse(await Uo(o,"utf8"))}var Ln=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 n=bt(e);if(!n.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(n.issues)}`);await Yi(this.journalDir,{recursive:!0});try{throw await Uo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(t){if(t instanceof Error&&t.message==="Memory journal is already initialized."||t.code!=="ENOENT")throw t}await this.withWriterLock(async()=>{try{throw await Uo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let t=Jn(e),i={storageVersion:1,sequence:0,hash:t,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:t},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await St(this.checkpointPath,i),await St(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 St(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let n=Jn(e.bundle),t=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:n,journalHash:e.report.headHash,bundle:e.bundle};return await St(nt(this.memoryDir,t),i),e.manifest.checkpoint={file:t,sequence:i.sequence,hash:n},await St(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let n=await this.load();return n.report.headSequence-n.report.checkpointSequence>=e?this.rotateCheckpoint():n}async commit(e,n){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Ct(n.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(n.committedAt)))throw new Error("committedAt must be ISO-8601.");let t=await this.loadInternal();if(t.transactionIds.has(n.transactionId))throw new Error(`Transaction already exists: ${n.transactionId}`);let i=t.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:n.transactionId,projectId:t.bundle.manifest.projectId,committedAt:n.committedAt,previousHash:t.report.headHash,mutation:e},s={...r,hash:Zi(r)},c=ac(t.bundle,e,n.committedAt),d=bt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let p=`${String(i).padStart(12,"0")}-${n.transactionId}.json`;return await St(nt(this.journalDir,p),s),t.manifest.head={sequence:i,hash:s.hash},t.manifest.updatedAt=n.committedAt,await St(this.manifestPath,t.manifest),{bundle:c,report:{checkpointSequence:t.report.checkpointSequence,appliedTransactions:t.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:t.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,n){return this.commit({...sc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await Bn(this.manifestPath),n=await Bn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||n.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==n.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(n.hash!==Jn(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await ic(this.journalDir),i=t.filter(T=>T.endsWith(".tmp")),s=t.filter(T=>/^\d{12}-[0-9a-f-]+\.json$/i.test(T)).sort().filter(T=>Number(T.slice(0,12))>n.sequence),c=structuredClone(n.bundle),d=n.sequence,p=n.journalHash??null,w=new Set;for(let T of s){let k=await Bn(nt(this.journalDir,T)),{hash:y,...f}=k;if(y!==Zi(f))throw new Error(`Journal hash mismatch: ${T}`);if(k.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(k.previousHash!==p)throw new Error(`Journal chain mismatch at ${T}`);if(k.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${T}`);if(w.has(k.transactionId))throw new Error(`Duplicate transaction ID: ${k.transactionId}`);er(c,k.mutation,k.committedAt),d=k.sequence,p=k.hash,w.add(k.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 x=bt(c);if(!x.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(x.issues)}`);return{bundle:c,manifest:e,transactionIds:w,report:{checkpointSequence:n.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:p}}}enqueueWrite(e){let n=this.writeChain.then(e,e);return this.writeChain=n.then(()=>{},()=>{}),n}async withWriterLock(e){await Yi(this.memoryDir,{recursive:!0});let n;try{n=await qo(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let i=await Bn(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 zo(this.lockPath),n=await qo(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await zo(this.lockPath).catch(()=>{})}}};import{randomBytes as cc}from"crypto";function we(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=cc(10).toString("hex"),i=(Number.parseInt(t[3],16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8)}-7${t.slice(0,3)}-${i}${t.slice(4,7)}-${t.slice(7,19)}`}var dc=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function tr(o,e){let n=o.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),t=o.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active");if(!n||!t)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(),p=d.records,w=o.records.find(m=>m.recordType==="thread"&&m.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));w||(w={id:ie(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(m=>m.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},p.push(w));let x=[];for(let m of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(S=>S.recordType==="subject"&&S.locators.some(g=>g.value===m&&g.status==="current"));j||(j={id:ie(i,"live-subject",m,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:m}],recordType:"subject",subjectType:"element",label:m,aliases:[],locators:[{id:ie(i,"live-locator",m,e.createdAt),kind:"dom_selector",value:m,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:m}]}]},p.push(j)),x.push(j)}for(let m of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=o.records.find(S=>S.recordType==="subject"&&S.locators.some(g=>g.kind==="source_file"&&g.value===m&&g.status==="current"));j||(j={id:ie(i,"live-file-subject",m,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:m}],recordType:"subject",subjectType:"file",label:m,aliases:[],locators:[{id:ie(i,"live-file-locator",m,e.createdAt),kind:"source_file",value:m,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:m}]}]},p.push(j)),x.push(j)}let T=(e.semanticCandidates??[]).filter(m=>m.claim.trim()),k;if(T.length>0){k=ie(i,"live-observation",r,e.createdAt);let m={id:k,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:T.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:x.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};p.push(m)}let y=ie(i,"live-iteration",r,e.completedAt),f={id:y,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.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"})),...k?[{kind:"record",id:k}]:[]],recordType:"iteration",threadIds:[w.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=x.length>0?x:o.records.filter(m=>m.recordType==="subject"&&m.subjectType==="project").slice(0,1);if(T.length>0&&u.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[m,j]of T.entries()){let S=ie(i,"live-proposal",`${r}:${m}`,e.completedAt),g=u.map(E=>({subjectId:E.id,role:"governed"})),J={id:S,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y},{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:y,inferredById:t.id}};p.push(J),l.push(S)}if(h.length>0){let m=new Set(e.governingDecisionIds??[]),j=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&m.has(g.id)),S={id:ie(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:t.id,sourceRefs:[{kind:"iteration",id:y}],recordType:"implementation_attempt",state:"completed",iterationIds:[y],coverageClaims:j.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${h.map(J=>J.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:y}]})),summary:h.map(g=>g.summary).join(" "),artifactIds:[]};p.push(S)}return{mutation:d,iterationId:y,proposalIds:l,observationId:k}}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 nr}from"path";function or(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function ir(o){return lc("sha256").update(JSON.stringify(o)).digest("hex")}async function gc(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await uc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
153
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await fc(n,o)}catch(i){throw await hc(n).catch(()=>{}),i}}function yc(o,e,n=new Date().toISOString()){let t={},i={},r={},s=(d,p,w)=>{let x=d[p]??=[];x.includes(w)||x.push(w)};for(let d of o.records)if(d.recordType==="subject"){let p=d;for(let w of[p.label,...p.aliases,...p.locators.filter(x=>x.status==="current").map(x=>x.value)]){let x=or(w);x&&s(t,x,p.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let p of d.subjects)s(i,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:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:ir(c)}}function rr(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[or(t)]??[]))];if(n.length)return{subjectIds:n,decisionIds:[...new Set(n.flatMap(t=>o.decisionIdsBySubject[t]??[]))],proposalIds:[...new Set(n.flatMap(t=>o.proposalIdsBySubject[t]??[]))]}}var Fn=class{constructor(e){this.indexDir=nr(e,".popmelt","memory","indexes"),this.indexPath=nr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){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===n.sequence&&i.journalHead.hash===n.hash&&r===ir(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let t=yc(e,n);return await pc(this.indexDir,{recursive:!0}),await gc(this.indexPath,t),t}};var sn="popmelt:imprint",cr="popmelt:imprint-evidence",Nt="popmelt:imprint-relation";function qn(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===sn)?.id}function Go(o){let e=new Set;return o.filter(n=>{let t=`${n.kind}:${n.id}:${n.uri??""}`;return e.has(t)?!1:(e.add(t),!0)})}function Un(o,e){if(!o)return[];let n=new Set(o.relations.flatMap(t=>t.type==="expresses"&&t.toId===e?[t.fromId]:[]));return o.concrete.filter(t=>n.has(t.id)).map(t=>({id:t.id,modelPath:t.modelPath,value:structuredClone(t.value),createdAt:t.createdAt,updatedAt:t.updatedAt}))}function Wo(o){if(o==="expresses")return"operationalizes";if(o==="excepts")return"excepts"}var zn=class{constructor(e){this.projectRoot=e;this.store=new Ln(e),this.indexStore=new Fn(e),this.manifestPath=Dt(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await rn(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 t=await on({...e,projectRoot:this.projectRoot});if(t.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(t.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(n){return this.runtimeState={state:"degraded",error:n instanceof Error?n.message:String(n)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await on({...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=Dt(this.projectRoot,".popmelt","memory","migrations"),n=Dt(e,"imprint-advisories-v2.json");try{let m=JSON.parse(await rn(n,"utf8"));return{migrated:!1,explanations:m.explanations??0,evidence:m.evidence??0}}catch{}let t;try{t=xt(JSON.parse(await rn(Dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!t?.explanations)return await sr(e,{recursive:!0}),await ar(n,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(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),c=i.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active")??r,d=i.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let p=i.bundle.manifest.projectId,w=new Set(i.bundle.records.map(m=>m.id)),x=new Set(i.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Nt?[j.id]:[]))),T=new Map,k=i.bundle.records.filter(m=>m.recordType==="advisory_explanation");for(let m of t.explanations){let j=k.find(S=>qn(S)===m.id);T.set(m.id,j?.id??ie(p,"imprint-explanation",m.id,Date.parse(m.createdAt)))}let y=[],f=[],l=[],h=0;for(let m of t.explanations){let j=T.get(m.id),S=k.find(R=>R.id===j),g=[],J=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 J){let N=ie(p,"imprint-evidence-record",R.id,Date.parse(R.createdAt));g.push(N),!w.has(N)&&(y.push({id:N,schemaVersion:1,projectId:p,createdAt:R.createdAt,participantId:c.id,sourceRefs:Go([{kind:"external",id:R.id,uri:cr},{kind:"external",id:m.id,uri:sn},{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(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:cr}],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:S?.createdAt??m.createdAt,participantId:S?.participantId??c.id,sourceRefs:Go([...S?.sourceRefs??[],{kind:"external",id:m.id,uri:sn}]),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([...S?.evidenceIds??[],...g])],concreteBindings:Un(t,m.id),supersededById:m.supersededBy?T.get(m.supersededBy):void 0,updatedAt:m.updatedAt};S?f.push(E):y.push(E)}for(let m of t.relations){let j=Wo(m.type);if(!j)continue;let S=T.get(m.fromId),g=T.get(m.toId);!S||!g||x.has(m.id)||l.push({id:ie(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:Nt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:S},to:{entityType:"advisory_explanation",entityId:g},reason:m.rationale||"The Imprint graph connected these explanations."})}let u=new Date().toISOString();if(y.length||f.length||l.length)try{let m=await this.store.commit({records:y,recordReplacements:f,events:[],relationships:l,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ie(p,"imprint-advisories-v2",t.projectId,Date.parse(t.updatedAt)),committedAt:u});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}return await sr(e,{recursive:!0}),await ar(n,JSON.stringify({version:2,migratedAt:u,explanations:t.explanations.length,evidence:h,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:t.explanations.length,evidence:h}}async review(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,selection:Bo(t.bundle,i)}}async contextualize(e,n={}){let t=await this.loadSource(n),i=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:Wi(t.bundle,i),reviewSelection:Bo(t.bundle,i)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Nn(t.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let n=await on({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(n.report.schemaIssues.some(t=>t.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(n.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:n.report}}async commitReview(e,n){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.load(),i=Nn(t.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,n);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 n=await this.store.load(),t=n.bundle.records.find(T=>T.recordType==="proposal"&&T.id===e.proposalId),i=n.bundle.records.find(T=>T.recordType==="participant"&&T.kind==="human"&&T.status==="active");if(!t||t.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:t?t.state!=="pending"?`The proposal is already ${t.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:t.id,participantId:i.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:t.subjects,subjectSemantics:t.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:t.subjects.map(T=>T.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},p=Nn(n.bundle,d);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(T=>T.message).join(" ")};let w=await this.store.commitReviewPlan(p.plan,{transactionId:we(r),committedAt:s});await this.refreshIndex(w);let x=p.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:x,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:w.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let n=await this.store.load(),t=tr(n.bundle,e),i=ie(n.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(t.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:t.iterationId,proposalIds:t.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:t.iterationId,proposalIds:t.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let n;try{n=xt(JSON.parse(await rn(Dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let t=await this.store.load(),i=t.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="human"&&u.status==="active"),r=t.bundle.records.find(u=>u.recordType==="participant"&&u.kind==="ai"&&u.status==="active"),s=e.action?i:r??i,c=t.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),w=t.bundle.manifest.projectId,x=[],T=[],k=[],y=t.bundle.records.filter(u=>u.recordType==="advisory_explanation"),f=new Map(y.flatMap(u=>{let m=qn(u);return m?[[m,u.id]]:[]}));for(let u of e.summary.changes)if(!f.has(u.explanationId)){let m=n?.explanations.find(j=>j.id===u.explanationId);f.set(u.explanationId,ie(w,"imprint-explanation",u.explanationId,Date.parse(m?.createdAt??d)))}for(let u of e.summary.changes){let m={kind:"external",id:u.explanationId,uri:sn},j=f.get(u.explanationId),S=y.find(R=>R.id===j),g=n?.explanations.find(R=>R.id===u.explanationId),J={id:ie(w,"imprint-live-evidence",`${e.summary.transactionId}:${u.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:w,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:[]};x.push(J);let E={id:j,schemaVersion:1,projectId:w,createdAt:S?.createdAt??g?.createdAt??d,participantId:S?.participantId??s.id,sourceRefs:Go([...S?.sourceRefs??[],m,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??S?.kind??"pattern",state:g?.state??u.state,statement:g?.statement??u.statement,rationale:g?.rationale??S?.rationale??e.summary.detail,scope:structuredClone(g?.scope??S?.scope??{kind:"project",values:[]}),subjectIds:S?.subjectIds??[c.id],evidenceIds:[...new Set([...S?.evidenceIds??[],J.id])],concreteBindings:g?Un(n,u.explanationId):S?.concreteBindings??[],supersededById:g?.supersededBy?f.get(g.supersededBy):S?.supersededById,updatedAt:g?.updatedAt??d};S?T.push(E):x.push(E),k.push({id:ie(w,"imprint-live-evidence-link",`${e.summary.transactionId}:${u.explanationId}:${e.action??"automatic"}`,p),schemaVersion:1,projectId:w,createdAt:d,participantId:s.id,sourceRefs:[m],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E.id},to:{entityType:"evidence",entityId:J.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let l=new Set(t.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(m=>m.kind==="external"&&m.uri===Nt?[m.id]:[])));for(let u of n?.relations??[]){let m=Wo(u.type);if(!m)continue;let j=f.get(u.fromId),S=f.get(u.toId);!j||!S||l.has(u.id)||k.push({id:ie(w,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:w,createdAt:u.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:u.id,uri:Nt}],recordType:"relationship",relationshipType:m,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:S},reason:u.rationale||"The Imprint graph connected these explanations."})}let h=ie(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let u=await this.store.commit({records:x,recordReplacements:T,events:[],relationships:k,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=xt(JSON.parse(await rn(Dt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let n=await this.store.load(),t=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),r=n.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??t;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=n.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=n.bundle.manifest.projectId,d=n.bundle.records.filter(g=>g.recordType==="advisory_explanation"),p=new Map(d.flatMap(g=>{let J=qn(g);return J?[[J,g]]:[]})),w=new Map([...[...p].map(([g,J])=>[g,J.id]),...e.explanations.filter(g=>!p.has(g.id)).map(g=>[g.id,ie(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),x=[],T=[],k=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let J=p.get(g.id);if(!J){x.push({id:w.get(g.id),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:sn}],recordType:"advisory_explanation",kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),subjectIds:[s.id],evidenceIds:[],concreteBindings:Un(e,g.id),supersededById:g.supersededBy?w.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let E={...structuredClone(J),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:Un(e,g.id),supersededById:g.supersededBy?w.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(J)!==R(E)&&T.push(E)}for(let[g,J]of p)k.has(g)||J.state==="retired"||T.push({...structuredClone(J),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let y=new Set(n.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),f=new Map(n.bundle.relationships.flatMap(g=>{if(y.has(g.id))return[];let J=g.sourceRefs.find(E=>E.kind==="external"&&E.uri===Nt)?.id;return J?[[J,g]]:[]})),l=[],h=new Set;for(let g of e.relations){let J=Wo(g.type);if(!J)continue;let E=w.get(g.fromId),R=w.get(g.toId);if(!E||!R)continue;let N=f.get(g.id);N&&N.relationshipType===J&&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:ie(c,"imprint-relation",`${g.id}:${J}:${E}:${R}`,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Nt}],recordType:"relationship",relationshipType:J,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=t?[...f].filter(([g])=>!u.has(g)||h.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:t.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!x.length&&!T.length&&!l.length&&!m.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let j=e.updatedAt,S=ie(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let g=await this.store.commit({records:x,recordReplacements:T,events:[],relationships:l,artifacts:[],tombstones:m,projectionUpdates:[]},{transactionId:S,committedAt:j});return await this.refreshIndex(g),{status:"synced",relationships:l.length+m.length,explanations:x.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:n.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.recover();return await this.refreshIndex(n),n}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let n=await this.store.load();await this.refreshIndex(n);let t={};for(let i of n.bundle.records)t[i.recordType]=(t[i.recordType]??0)+1;return{status:e,journal:n.report,records:t,openFreshnessSignals:n.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:n.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:n}=await this.store.load(),t=new Set(n.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(n.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(n.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!t.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(),n=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),t=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=>n.has(r))&&t.set(i.key,i);return[...t.values()]}async getImprintView(e=[],n){let t=()=>({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 t();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 h=qn(l);return h?[[h,l.id]]:[]})),d=new Set(e.map(l=>c.get(l)??l)),p=new Map(i.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),w=new Map(i.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),x=new Set(i.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),T=new Set(["operationalizes","excepts"]),k={testing:0,emerging:1,grounded:2,challenged:3,retired:4},y=r.map(l=>{let h=l.evidenceIds.flatMap(S=>{let g=w.get(S);if(!g)return[];let J=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:J,jobId:E}]}).sort((S,g)=>g.createdAt.localeCompare(S.createdAt)),u=i.bundle.relationships.flatMap(S=>{if(x.has(S.id))return[];if(!T.has(S.relationshipType))return[];let g=S.from.entityType==="advisory_explanation"&&S.from.entityId===l.id&&S.to.entityType==="advisory_explanation",J=S.to.entityType==="advisory_explanation"&&S.to.entityId===l.id&&S.from.entityType==="advisory_explanation";if(!g&&!J)return[];let E=g?S.to.entityId:S.from.entityId,R=s.get(E);return R?[{id:S.id,type:S.relationshipType==="operationalizes"?"expresses":"excepts",direction:g?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:S.reason}]:[]}),m=[...(l.supersededById?[l.supersededById]:[]).flatMap(S=>{let g=s.get(S);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(S=>S.supersededById===l.id?[{id:`supersedes:${S.id}:${l.id}`,type:"supersedes",direction:"outgoing",explanationId:S.id,statement:S.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...l.sourceRefs.flatMap(S=>S.kind==="thread"?[S.id]:[]),...h.flatMap(S=>S.threadId?[S.threadId]:[])])].filter(S=>!n||n.has(S));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(S=>({...structuredClone(S)})),relations:[...u,...m],sourceThreadIds:j,needsGrounding:l.state==="testing"&&d.has(l.id)}}).sort((l,h)=>Number(h.needsGrounding)-Number(l.needsGrounding)||k[l.state]-k[h.state]||h.updatedAt.localeCompare(l.updatedAt)),f={total:y.filter(l=>l.state!=="retired").length,emerging:y.filter(l=>l.state==="emerging").length,testing:y.filter(l=>l.state==="testing").length,grounded:y.filter(l=>l.state==="grounded").length,challenged:y.filter(l=>l.state==="challenged").length,retired:y.filter(l=>l.state==="retired").length,needsGrounding:y.filter(l=>l.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:f,explanations:y}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),n=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),t=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=>n.has(d))&&t.set(c.key,c);let i=[...t.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(w=>w.entityType==="decision"&&w.entityId===c.id)).sort((p,w)=>w.createdAt.localeCompare(p.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(p=>p.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 n=await this.store.load(),t=n.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=n.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!t||!i)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),w=we(r),x=we(r),T=new Set(n.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),k=n.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&T.has(R.id)),y={schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},f=[{subjectId:i.id,role:"governed"}],l={...y,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:f,origin:{mode:"declared",sourceText:e.claim,reviewedById:t.id}},h={...y,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={...y,id:p,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:f,noChange:!1,effectiveAt:s},m={...y,id:w,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[p],value:e.value},j={...y,id:x,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[p],entryIds:[w],coverage:[{decisionId:p,status:"projected"}]},S={...y,id:we(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:w},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},g=k.map(R=>({...y,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}.`})),J=k.map(R=>({...y,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:[S,...J],artifacts:[],tombstones:[],projectionUpdates:k.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:we(r),committedAt:s});return await this.refreshIndex(E),{decisionId:p,entryId:w}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:n}=await this.store.load(),t=n.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return t?{proposalId:t.id,claim:t.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 n=await this.store.load(),t=n.bundle.records.find(y=>y.recordType==="model_projection"&&y.state==="applied"&&y.runId===e.runId);if(t)return{projectionId:t.id,entryIds:t.entryIds,headSequence:n.report.headSequence};let i=n.bundle.records.filter(y=>y.recordType==="decision"&&e.decisionIds.includes(y.id)&&y.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=n.bundle.records.find(y=>y.recordType==="participant"&&y.kind==="human"&&y.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(y=>{let f=y.decisionIds?.filter(u=>e.decisionIds.includes(u)),l=f?.length?f:e.decisionIds,h=[...new Set(i.filter(u=>l.includes(u.id)).flatMap(u=>u.subjects.map(m=>m.subjectId)))];return{id:we(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:l.map(u=>({kind:"record",id:u})),recordType:"model_entry",key:y.path.map(String).join("."),subjectIds:h,decisionIds:l,value:y.value}}),w=new Set(p.flatMap(y=>y.decisionIds)),x={id:d,schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(y=>({kind:"record",id:y})),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(y=>y.id),coverage:e.decisionIds.map(y=>e.coverage?.find(f=>f.decisionId===y)??{decisionId:y,status:w.has(y)?"projected":"unprojected"})},T=p.flatMap(y=>y.decisionIds.map(f=>({id:we(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:x.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:y.id},to:{entityType:"decision",entityId:f},reason:"The owner applied this model entry as a projection of accepted product truth."}))),k=await this.store.commit({records:[...p,x],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:we(s),committedAt:c});return await this.refreshIndex(k),{projectionId:d,entryIds:p.map(y=>y.id),headSequence:k.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let n=await this.store.load();return{source:"journal",bundle:n.bundle,journal:n.report}}return{source:"legacy_preview",bundle:(await on({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,n){if(e.source!=="journal"||!e.journal)return n;let t=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=rr(t,n.subjectHints??[]);return i?{...n,subjectIds:[...new Set([...n.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:n}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function 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 Bt(o,e,n){let t=Te(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function Ho(o){let e=Jt(o),n=Jt(e.authority),t=n.level,i=n.mode,r=Bt(t,"authority.level",["owner","delegate","contributor"]),s=Bt(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 n.grantId=="string"?n.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind:Bt(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(p=>Te(p,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(p=>Bt(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: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:Bt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let p=Jt(d);return{subjectId:Te(p.subjectId,"subjectId"),role:Bt(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:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Vo(o){let e=Jt(o),n=(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))}},t=(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:n(e.subjectIds,"subjectIds"),subjectHints:n(e.subjectHints,"subjectHints"),maxPackets:t(e.maxPackets,"maxPackets"),maxEstimatedTokens:t(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 Lt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
154
|
+
`)}async function dr(o,e,n,t){let i=Lt(e);if(!(!i&&n.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:n,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(p=>p.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){t?.(r);return}}function lr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(t=>t.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((t,i)=>["",`${i+1}. [${t.kind}; ${t.effectiveState}] ${t.claim}`,` - Implementation: ${t.implementation}`,` - Verification: ${t.verification}`,...t.freshness.length?[` - Freshness warnings: ${t.freshness.join(", ")}`]:[],` - Decision: ${t.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(t=>`- ${t.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((t,i)=>["",`${i+1}. ${t.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${t.proposedKind??"unspecified"}`,` - Presentation: ${t.presentation}`,` - Packet: ${t.packetId}`,` - Evidence references available: ${t.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(`
|
|
155
|
+
`)}function pr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]);if(typeof n.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(n.action)))return null;let t=n.action,i=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:void 0;if((t==="accept"||t==="edit_and_accept")&&!i||t==="edit_and_accept"&&typeof n.claim!="string"||t!=="defer"&&(typeof n.reason!="string"||!n.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(n.resurfaceWhen)?n.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:n.proposalId,action:t,kind:i,claim:typeof n.claim=="string"?n.claim:void 0,reason:typeof n.reason=="string"?n.reason:void 0,taskContext:typeof n.taskContext=="string"?n.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function ur(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let n=JSON.parse(e[1]),t=["principle","preference","rule","constraint"].includes(String(n.kind))?n.kind:null;return!t||typeof n.proposalId!="string"||!n.proposalId||typeof n.title!="string"||!n.title.trim()||typeof n.claim!="string"||!n.claim.trim()||typeof n.rationale!="string"||!n.rationale.trim()?null:{proposalId:n.proposalId,kind:t,title:n.title.trim(),claim:n.claim.trim(),rationale:n.rationale.trim(),scope:typeof n.scope=="string"&&n.scope.trim()?n.scope.trim():void 0}}catch{return null}}async function Ko(o){let n=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!n)throw new Error("Missing multipart boundary");let t=n[1]||n[2],i=await vc(o),r=Buffer.from(`--${t}`),s=Buffer.from(`--${t}--`),c,d,p,w,x,T,k,y,f,l,h,u,m,j,S=[],g=[],J=0,E=[];for(;J<i.length;){let R=i.indexOf(r,J);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
|
|
154
156
|
\r
|
|
155
|
-
`,
|
|
157
|
+
`,V);if(K===-1)break;let W=i.slice(V,K).toString("utf-8"),Q=K+4,b=i.indexOf(r,Q),H=b!==-1?b-2:i.length;E.push({headers:W,body:i.slice(Q,H)}),J=b!==-1?b: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")p=R.body.toString("utf-8");else if(V==="provider")w=R.body.toString("utf-8");else if(V==="model")x=R.body.toString("utf-8");else if(V==="reasoningEffort")T=R.body.toString("utf-8");else if(V==="serviceTier")k=R.body.toString("utf-8");else if(V==="goal")y=R.body.toString("utf-8");else if(V==="pageUrl")f=R.body.toString("utf-8");else if(V==="viewport")l=R.body.toString("utf-8");else if(V==="planId")h=R.body.toString("utf-8");else if(V==="manifest")u=R.body.toString("utf-8");else if(V==="tasks")m=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 W=decodeURIComponent(K);g.push({pathname:W,data:R.body})}catch{}}else if(V.startsWith("image-")){let K=V.split("-"),W=parseInt(K[K.length-1],10),Q=K.slice(1,-1).join("-");Q&&!isNaN(W)&&S.push({annotationId:Q,index:W,data:R.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:p,provider:w,model:x,reasoningEffort:T,serviceTier:k,goal:y,pageUrl:f,viewport:l,planId:h,manifest:u,tasks:m,sourceId:j,pastedImages:S,pageScreenshots:g}}function vc(o){return new Promise((e,n)=>{let t=[];o.on("data",i=>t.push(i)),o.on("end",()=>e(Buffer.concat(t))),o.on("error",n)})}import{randomUUID as Ic}from"crypto";var an="<orientation>",ot="</orientation>";function Qo(o,e){let n=e;for(;n<o.length&&/\s/.test(o[n]);)n++;if(n>=o.length)return{status:"incomplete",start:n};if(o[n]!=="{")return{status:"invalid",start:n};let t=0,i=!1,r=!1;for(let s=n;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==="{")t++;else if(c==="}"){if(t--,t===0)return{status:"complete",start:n,end:s+1};if(t<0)return{status:"invalid",start:n}}}return{status:"incomplete",start:n}}function mr(o,e){if(!e)return;let n=o[o.length-1];n?.kind==="text"?n.text+=e:o.push({kind:"text",text:e})}function fr(o){let e=[],n=0;for(;n<o.length;){let t=o.indexOf(an,n);if(t<0){mr(e,o.slice(n));break}mr(e,o.slice(n,t));let i=t+an.length,r=Qo(o,i);if(r.status!=="complete"){let c=o.indexOf(ot,i);if(c>=0){n=c+ot.length;continue}n=i;continue}e.push({kind:"orientation",json:o.slice(r.start,r.end)}),n=r.end;let s=n;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(ot,s)&&(n=s+ot.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 cn(o,e=180){if(typeof o!="string")return;let n=o.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,e-1).trimEnd()}\u2026`}function xc(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function hr(o,e,n,t=Date.now()){let i=xc(o);if(!i)return null;let r=typeof i.transition=="string"&&wc.has(i.transition)?i.transition:null,s=cn(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:n,timestamp:t,transition:r,snapshot:{focus:s,seeking:cn(i.seeking),workingHypothesis:cn(i.workingHypothesis),evidencePosture:c,update:cn(i.update),nextObservation:cn(i.nextObservation)},contextPolicy:"exclude"}}function Xo(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Yo(o,e,n=0){let t=[],i=[],r=new Set,s=n;for(let d of fr(o)){if(d.kind==="text"){d.text&&i.push(d);continue}try{let p=hr(JSON.parse(d.json),e,s);if(!p)continue;let w=Xo(p);if(r.has(w))continue;r.add(w),t.push(p),i.push({kind:"orientation",orientation:p}),s++}catch{}}return{visibleText:i.map(d=>d.kind==="text"?d.text:`
|
|
156
158
|
|
|
157
|
-
`).
|
|
159
|
+
`).join("").replace(/\n{3,}/g,`
|
|
160
|
+
|
|
161
|
+
`).trim(),orientations:t,segments:i}}function Sc(o){let e="<orientation>",n=Math.min(o.length,e.length-1);for(let t=n;t>0;t--)if(e.startsWith(o.slice(-t)))return t;return 0}var Gn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let n="",t=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let p=this.buffer.slice(d);if(ot.startsWith(p)&&p.length<ot.length||(p.startsWith(ot)&&(this.buffer=this.buffer.slice(d+ot.length)),this.optionalClosePending=!1,!this.buffer))break}let i=this.buffer.indexOf(an);if(i<0){let d=Sc(this.buffer);n+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}n+=this.buffer.slice(0,i);let r=i+an.length,s=Qo(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=hr(JSON.parse(c),this.jobId,this.sequence);if(!d)continue;let p=Xo(d);if(this.signatures.has(p))continue;this.signatures.add(p),t.push(d),this.sequence++}catch{}}return{visibleText:n,orientations:t}}finalize(e){let n=Yo(e,this.jobId,this.sequence),t=n.orientations.filter(i=>{let r=Xo(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:n.visibleText,orientations:t}}},gr=`## Public orientation updates
|
|
158
162
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
159
163
|
<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>
|
|
160
164
|
|
|
161
165
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
162
166
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
163
167
|
|
|
164
|
-
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
|
|
165
|
-
### ${
|
|
166
|
-
`)}function
|
|
167
|
-
`)}function
|
|
168
|
-
`)}function
|
|
169
|
-
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let
|
|
170
|
-
`));return
|
|
171
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await pc(n,o)}catch(r){throw await uc(n).catch(()=>{}),r}}function fc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function hc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Ae(e):o.explanations.push(Ae(e))}function Un(o,e){let n=Ae(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(r=>r.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(Ae(t.explanation))}else if(t.op==="replace_explanation")hc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(r=>r.id!==t.explanationId),n.relations=n.relations.filter(r=>r.fromId!==t.explanationId&&r.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(r=>r.id===t.concrete.id)||n.concrete.push(Ae(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(r=>r.id!==t.concreteId),n.relations=n.relations.filter(r=>r.fromId!==t.concreteId&&r.toId!==t.concreteId);else if(t.op==="add_evidence"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);r.evidence.some(i=>i.id===t.evidence.id)||(r.evidence.push(Ae(t.evidence)),r.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let r=n.explanations.find(i=>i.id===t.explanationId);if(!r)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(r,Ae(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let r=n.explanations.some(s=>s.id===t.relation.fromId),i=n.explanations.some(s=>s.id===t.relation.toId)||n.concrete.some(s=>s.id===t.relation.toId);if(!r||!i)throw new Error(`Imprint relation references an unknown explanation: ${t.relation.id}`);n.relations.some(s=>s.id===t.relation.id)||n.relations.push(Ae(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function gc(o,e){let n=[],t=Ae(o);for(let r of e){if(r.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:r.explanation.id});else if(r.op==="remove_explanation"){let i=t.explanations.find(s=>s.id===r.explanationId);i&&n.unshift({op:"add_explanation",explanation:Ae(i)})}else if(r.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:r.concrete.id});else if(r.op==="remove_concrete"){let i=t.concrete.find(s=>s.id===r.concreteId);i&&n.unshift({op:"add_concrete",concrete:Ae(i)})}else if(r.op==="replace_explanation"||r.op==="revise_explanation"||r.op==="add_evidence"){let i=r.op==="replace_explanation"?r.explanation.id:r.explanationId,s=t.explanations.find(c=>c.id===i);s&&n.unshift({op:"replace_explanation",explanation:Ae(s)})}else if(r.op==="add_relation")n.unshift({op:"remove_relation",relationId:r.relation.id});else if(r.op==="remove_relation"){let i=t.relations.find(s=>s.id===r.relationId);i&&n.unshift({op:"add_relation",relation:Ae(i)})}t=Un(t,[r])}return n}function oi(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 _t=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Et(e,".popmelt","imprint"),this.manifestPath=Et(this.imprintDir,"manifest.json"),this.graphPath=Et(this.imprintDir,"graph.json"),this.journalDir=Et(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await ti(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async load(){let e=await this.readManifest(),t=(await lc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=fc(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await ti(Et(this.journalDir,t[c]),"utf8")),{hash:l,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||l!==ni(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Un(r,d.mutations),r.updatedAt=d.committedAt,r.head={sequence:d.sequence,hash:d.hash},i.push(d),s=d.hash}return{graph:r,transactions:i,recoveredTransactions:Math.max(0,i.length-e.head.sequence)}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(P=>P.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=gc(t.graph,e.mutations),s={version:1,sequence:r,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:Ae(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:ni(s)},d=Un(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let l=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await nn(Et(this.journalDir,l),c);let x={version:1,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await nn(this.graphPath,d),await nn(this.manifestPath,x),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,r){let i=await this.load(),s=i.transactions.find(l=>l.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(l=>l.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(oi));if(i.transactions.filter(l=>l.sequence>s.sequence).some(l=>l.mutations.some(x=>oi(x).some(P=>c.has(P)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:r,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await nn(this.graphPath,e.graph),await nn(this.manifestPath,{version:1,projectId:this.projectId,createdAt:e.graph.createdAt,updatedAt:e.graph.updatedAt,head:e.graph.head}),{...e,recoveredTransactions:0}}};var yc=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"]);function wc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function qn(o){return new Set(wc(o).split(" ").filter(e=>e.length>2&&!vc.has(e)))}function zn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function No(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 tt(o,e,n){return{id:Ke(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ke(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function ri(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 n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function ii(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let r=Number(t);if(!Number.isInteger(r)||r<0||r>=n.length)return{found:!1};n=n[r]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Hn(o){let e=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),t=e.at(-1)?.[1];if(!t)return{visibleText:n};try{let r=JSON.parse(t);if(r.decision==="none"){let T=String(r.reason);if(!yc.has(T))throw new Error("imprint no-op reason is invalid");return{draft:{decision:"none",reason:T},visibleText:n}}if(r.decision!==void 0&&r.decision!=="mutate")throw new Error("imprint decision is invalid");let i=r.summary,s=i?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(s)))throw new Error("summary.kind is invalid");let c={kind:s,title:ke(i?.title,120),detail:ke(i?.detail,500)};if(!c.title||!c.detail)throw new Error("summary title and detail are required");let d=Array.isArray(r.appliedExplanationIds)?r.appliedExplanationIds.filter(T=>typeof T=="string"&&!!T.trim()):[],l=[];for(let T of Array.isArray(r.mutations)?r.mutations:[]){if(!T||typeof T!="object")continue;let b=T;if(b.op==="add"&&["intention","principle","pattern"].includes(String(b.kind))){let h=ke(b.statement),p=ke(b.rationale);if(!h||!p)continue;l.push({op:"add",clientId:ke(b.clientId,100)||void 0,kind:b.kind,statement:h,rationale:p,scope:ri(b.scope),rootReason:ke(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let h={op:"revise",explanationId:b.explanationId,statement:ke(b.statement)||void 0,rationale:ke(b.rationale)||void 0,scope:ri(b.scope),reopenGrounding:b.reopenGrounding===!0};(h.statement||h.rationale||h.scope||h.reopenGrounding)&&l.push(h)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let h=ke(b.summary);h&&l.push({op:"evidence",explanationId:b.explanationId,stance:b.stance,summary:h})}else if(b.op==="relation"&&typeof b.fromId=="string"&&typeof b.toId=="string"&&["operationalizes","refines","supports","contradicts","excepts","instantiates"].includes(String(b.type))){let h=ke(b.rationale);if(!h)continue;l.push({op:"relation",type:b.type,fromId:b.fromId,toId:b.toId,rationale:h})}else if(b.op==="supersede"&&typeof b.explanationId=="string"&&typeof b.replacementId=="string"){let h=ke(b.reason);h&&l.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:h})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let h=ke(b.modelPath,300);h&&l.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:h,rationale:ke(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&l.push({op:"retire",explanationId:b.explanationId,reason:ke(b.reason)})}let x=r.grounding,P=x&&typeof x.explanationId=="string"&&ke(x.question)?{explanationId:x.explanationId,question:ke(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:l,grounding:P},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Gn(o){let e=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]);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.",...e.length?["","Relevant explanations from the project imprint:",...e.map((t,r)=>[`${r+1}. [${t.state}; ${t.kind}] ${t.statement}`,` - Why: ${t.rationale}`,` - Scope: ${t.scope.kind} ${t.scope.values.join(", ")}`,` - Explanation: ${t.id}`,...n.has(t.id)?[" - Grounding: already pending; do not ask again"]:[],...t.concrete.map(i=>` - Concrete terminal: ${i.modelPath} = ${JSON.stringify(i.value)}`)].join(`
|
|
172
|
-
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(t=>`- ${t.fromId} --${t.type}--> ${t.toId}: ${t.rationale}`)]:[],"","Work normally and preserve developer agency. You may use an emerging or testing explanation as a hypothesis without asking permission first. Silence is not confirmation.","The default outcome is no imprint mutation. Completing work, applying an existing explanation, or making a successful design choice does not by itself constitute learning.","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.","","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. A task-specific edit becomes learning only if the human establishes a reusable dependency 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.","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. Connect the new clientId with relation or supersede mutations whenever it overlaps, specializes, operationalizes, supports, contradicts, or excepts another surfaced or newly-added explanation. If it is genuinely a new root with no meaningful relative, include rootReason on the add mutation 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 to the grounded parent with a refines, operationalizes, or excepts relation.","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 only 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.","","At the end, append exactly one machine-readable decision block after the normal response. It is hidden from the developer:",'<imprint>{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}</imprint>',"Or, only after every admission test passes:",'<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":"operationalizes|refines|supports|contradicts|excepts|instantiates","fromId":"<id or clientId>","toId":"<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 operationalizes the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}</imprint>',"Include only mutation objects actually needed. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Omit grounding unless its three conditions pass. Never claim that a new explanation is grounded."].join(`
|
|
173
|
-
`)}var Ct=class{constructor(e,n){this.noopCounts=new Map;this.store=new _t(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts)}}async contextualize(e){let n=qn(e.text??""),t=qn((e.subjectHints??[]).join(" ")),r=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!r.size)return;let{graph:i}=await this.store.load(),s=i.explanations.filter(h=>h.state!=="retired"&&h.state!=="challenged").map(h=>{let p=qn([h.statement,h.rationale].join(" ")),v=qn(h.scope.values.join(" ")),w=zn(p,n),m=zn(v,n),u=zn(v,t),R=zn(p,t),E=w+m*.2+u*.25+R*.1+(h.state==="grounded"?.08:0)+(r.has(h.id)?1:0),y=r.has(h.id)||(n.size?w>=.12||m>=.5:u>=.2||R>=.2);return{item:h,score:E,relevant:y}}).filter(h=>h.relevant&&h.score>=.18).sort((h,p)=>p.score-h.score||p.item.updatedAt.localeCompare(h.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:h})=>h),l=new Set(d.map(h=>h.id)),x=new Set(i.relations.flatMap(h=>l.has(h.fromId)?[h.toId]:l.has(h.toId)?[h.fromId]:[])),P=new Set(i.explanations.flatMap(h=>x.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),T=i.explanations.filter(h=>P.has(h.id)&&!l.has(h.id)).sort((h,p)=>p.updatedAt.localeCompare(h.updatedAt)).slice(0,4),b=[...d,...T];for(let h of T)l.add(h.id);return{explanations:b.map(h=>{let p=new Set(i.relations.filter(v=>v.fromId===h.id&&v.type==="instantiates").map(v=>v.toId));return{id:h.id,kind:h.kind,statement:h.statement,rationale:h.rationale,scope:h.scope,state:h.state,concrete:i.concrete.filter(v=>p.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:s.length>d.length||T.length<P.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(h=>l.has(h.fromId)&&l.has(h.toId)&&h.type!=="instantiates").map(h=>({id:h.id,type:h.type,fromId:h.fromId,toId:h.toId,rationale:h.rationale}))}}async capture(e,n){if(e.mutations.length===0&&e.appliedExplanationIds.length===0)return;let t=n.occurredAt??new Date().toISOString(),r=await this.store.load(),i=new Map(r.graph.explanations.map(f=>[f.id,f])),s=new Map,c=new Map,d=[],l=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),P=new Set(e.mutations.flatMap(f=>f.op==="revise"&&e.mutations.some(M=>M.op==="evidence"&&M.stance==="challenges"&&M.explanationId===f.explanationId)?[f.explanationId]:[])),T=new Set(e.mutations.flatMap(f=>f.op==="add"&&f.clientId?[f.clientId]:[])),b=f=>i.has(f)||T.has(f),h=new Set;for(let f of e.mutations)f.op==="relation"&&f.fromId!==f.toId&&b(f.fromId)&&b(f.toId)?(h.add(f.fromId),h.add(f.toId)):f.op==="supersede"&&f.explanationId!==f.replacementId&&b(f.explanationId)&&b(f.replacementId)?(h.add(f.explanationId),h.add(f.replacementId)):f.op==="bind_concrete"&&b(f.explanationId)&&ii(n.concreteModel,f.modelPath).found&&h.add(f.explanationId);let p=r.graph.explanations.length===0;for(let f of e.mutations){if(f.op!=="add")continue;let M=!!(f.clientId&&h.has(f.clientId)),D=!!f.rootReason?.trim()||p;if(!M&&!D)continue;p&&(p=!1);let B=Ke();f.clientId&&s.set(f.clientId,B);let H=f.clientId?e.appliedExplanationIds.includes(f.clientId):!1,V={id:B,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:No(f.scope),state:H?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};i.set(B,V),l.add(B),d.push({op:"add_explanation",explanation:V})}let v=f=>s.get(f)??f;for(let f of e.mutations){if(f.op!=="revise")continue;let M=v(f.explanationId),D=i.get(M);if(D?.state!=="grounded")continue;let B=Ke(),H={id:B,kind:D.kind,statement:f.statement??D.statement,rationale:f.rationale??D.rationale,scope:f.scope?No(f.scope):D.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[tt(n,"supports",e.summary.detail)]};i.set(B,H),c.set(M,B),l.add(B),d.push({op:"add_explanation",explanation:H}),d.push({op:"add_relation",relation:{id:Ke(),type:"refines",fromId:B,toId:M,rationale:f.rationale??e.summary.detail,createdAt:t}})}let w=f=>{let M=v(f);return c.get(M)??M};for(let f of e.mutations){if(f.op==="add")continue;if(f.op==="bind_concrete"){let D=w(f.explanationId);if(!i.has(D))continue;let B=ii(n.concreteModel,f.modelPath);if(!B.found)continue;let H=r.graph.concrete.find(V=>V.modelPath===f.modelPath&&JSON.stringify(V.value)===JSON.stringify(B.value));H||(H={id:Ke(),modelPath:f.modelPath,value:structuredClone(B.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:H})),d.push({op:"add_relation",relation:{id:Ke(),type:"instantiates",fromId:D,toId:H.id,rationale:f.rationale,createdAt:t}}),l.add(D);continue}if(f.op==="relation"){let D=w(f.fromId),B=w(f.toId);if(!i.has(D)||!i.has(B)||D===B)continue;d.push({op:"add_relation",relation:{id:Ke(),type:f.type,fromId:D,toId:B,rationale:f.rationale,createdAt:t}}),l.add(D),l.add(B);continue}if(f.op==="supersede"){let D=w(f.explanationId),B=w(f.replacementId);if(!i.has(D)||!i.has(B)||D===B)continue;d.push({op:"add_evidence",explanationId:D,evidence:tt(n,"challenges",f.reason)}),d.push({op:"revise_explanation",explanationId:D,patch:{state:"challenged",supersededBy:B},updatedAt:t}),d.push({op:"add_relation",relation:{id:Ke(),type:"supersedes",fromId:B,toId:D,rationale:f.reason,createdAt:t}}),l.add(D),l.add(B);continue}let M=w(f.explanationId);if(i.has(M))if(l.add(M),f.op==="revise"){if(c.has(v(f.explanationId)))continue;let D=i.get(M);if(!D||D.state!=="emerging"&&D.state!=="testing")continue;let B={...f.statement?{statement:f.statement}:{},...f.rationale?{rationale:f.rationale}:{},...f.scope?{scope:No(f.scope)}:{},...f.reopenGrounding||P.has(f.explanationId)?{state:"testing"}:{}};d.push({op:"revise_explanation",explanationId:M,patch:B,updatedAt:t})}else if(f.op==="evidence"){if(f.stance==="challenges"&&P.has(f.explanationId))continue;d.push({op:"add_evidence",explanationId:M,evidence:tt(n,f.stance,f.summary)}),f.stance==="challenges"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"challenged"},updatedAt:t})}else f.op==="retire"&&(d.push({op:"add_evidence",explanationId:M,evidence:tt(n,"challenges",f.reason||"Retired after contradictory collaboration evidence.")}),d.push({op:"revise_explanation",explanationId:M,patch:{state:"retired"},updatedAt:t}))}for(let f of e.appliedExplanationIds){let M=w(f),D=i.get(M);!D||D.state==="grounded"||D.state==="retired"||x.has(M)&&!l.has(M)||(l.has(M)||(l.add(M),d.push({op:"add_evidence",explanationId:M,evidence:{...tt(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),D.state==="emerging"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let m=Ke(),u=await this.store.commit({transactionId:m,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),R=new Map(u.graph.explanations.map(f=>[f.id,f])),E=[...l].flatMap(f=>{let M=R.get(f);if(!M)return[];let D=!r.graph.explanations.some(H=>H.id===f),B=M.state==="challenged"||M.state==="retired";return[{explanationId:f,action:D?"added":B?"challenged":"revised",statement:M.statement,state:M.state}]}),y=e.grounding?w(e.grounding.explanationId):void 0,L=y?R.get(y):void 0,C=L?.state==="testing"&&!x.has(L.id)?{explanationId:L.id,question:e.grounding.question,state:"testing"}:void 0;return{transactionId:m,kind:e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:E,...C?{grounding:C}:{}}}async applyGroundingAction(e){let n=e.occurredAt??new Date().toISOString();if(e.action==="undo"||e.action==="dont_learn"){let l=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let x of l)await this.store.undo(x,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Ke());return}let t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let i=(await this.store.load()).graph.explanations.find(l=>l.id===t);if(!i||i.state==="retired")throw new Error("This explanation is no longer active.");let s={kind:e.action==="confirm"?"grounding":"correction",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="confirm")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${i.statement}`;else if(e.action==="reason_wrong")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"challenges",e.value?.trim()||"The result was right, but this explanation was not the reason."),kind:"correction"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${i.statement}`;else if(e.action==="narrow"){let l=(e.value??"").split(",").map(x=>x.trim()).filter(Boolean);if(!l.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:l},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...tt(e,"excepts",e.value?.trim()||"The developer marked this application as an exception."),kind:"exception"}}),d=`Exception recorded: ${i.statement}`;else if(e.action==="edit"){let l=e.value?.trim();if(!l)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:l,state:"testing"},updatedAt:n}),d=`Edited: ${l}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:Ke(),committedAt:n,source:s,summary:d,mutations:c})}};function on(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function Wn(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function Jo(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 si(o){let e=Jo(Wn(o.origin));if(e)return e;let n=Jo(Wn(o.referer));if(n)return n;let t=Wn(o["x-forwarded-host"]);if(!t)return null;let r=Wn(o["x-forwarded-proto"])==="https"?"https":"http";return Jo(`${r}://${t}`)}function ai(o,e,n=5){let t=(d,l)=>(l.completedAt??l.startedAt)-(d.completedAt??d.startedAt),r=[...o].sort(t).slice(0,n),i=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,l)=>(d[l.status]=(d[l.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Vn}from"crypto";import{mkdir as rn,readFile as yt,unlink as xc,writeFile as Ot}from"fs/promises";import{dirname as Kn,extname as Sc,join as Ee}from"path";var Ic={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 bc(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 ci(o,e){let n=e??bc(o);return{kind:n,...Ic[n]}}function $t(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function di(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(r=>r.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}var Pc={version:1,threads:{}},li=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],sn={version:2,updatedAt:0,files:{}};function Tc(o){return JSON.stringify(o,null,2)}function Rc(o){return Object.fromEntries(li.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function kc(o){let e={...o};for(let n of li)delete e[n];return e}function Dt(o){let e=o;if(o.error){let n=ci(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=$t(e.result,!1),t=$t(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var Qn=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=Ee(e,".popmelt");this.legacyFilePath=Ee(n,"threads.json"),this.threadsDir=Ee(n,"threads"),this.indexPath=Ee(this.threadsDir,"index.json"),this.artifactsDir=Ee(n,"artifacts","thread-messages"),this.mediaDir=Ee(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await yt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[t,r]of Object.entries(e.files)){let i=await this.readThread(Ee(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await yt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads)return this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Dt)}]))},this.index={...sn,files:{},migratedFromLegacyAt:Date.now()},await this.persistAll(),this.cache}catch{}return this.cache={...Pc,threads:{}},this.index={...sn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let r of Object.values(n.threads))if(r.elementIdentifiers.some(s=>t.has(s)))return r;return null}async createThread(e,n){let t=await this.load(),r={id:e,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=r,await this.persistThread(r),r}async appendMessage(e,n){let r=(await this.load()).threads[e];r&&(r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r))}async appendMessageBeforeQueuedReplies(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=r.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);i>=0?r.messages.splice(i,0,Dt(n)):r.messages.push(Dt(n)),r.updatedAt=Date.now(),await this.persistThread(r)}async updateMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=i.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Dt(c);Object.assign(c,d),delete c.responseText}return i.updatedAt=Date.now(),await this.persistThread(i),!0}async updateAssistantMessage(e,n,t){let i=(await this.load()).threads[e];if(!i)return!1;let s=[...i.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),i.updatedAt=Date.now(),await this.persistThread(i),!0):!1}async addElementIdentifiers(e,n){let r=(await this.load()).threads[e];if(!r)return;let i=new Set(r.elementIdentifiers);for(let s of n)i.has(s)||r.elementIdentifiers.push(s);r.updatedAt=Date.now(),await this.persistThread(r)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((r,i)=>i.updatedAt-r.updatedAt),t.slice(0,e).map(r=>{let s=r.messages.find(v=>v.role==="human")?.feedbackSummary||"[thread]",c=r.messages.filter(v=>v.role==="assistant"),d=v=>{if(v.role!=="assistant")return;if(v.question)return v.question;let w=v.imprintSummary?.grounding;if(w?.question&&!v.imprintSummary?.resolvedAction)return w.question},l=r.messages.findLastIndex(v=>!!d(v)),x=r.messages.findLastIndex(v=>v.role==="human"),P=l>x?d(r.messages[l]):void 0,T=r.messages.at(-1)?.role,b=Array.from(new Set(r.messages.slice(0,Math.max(0,x)).filter(v=>v.role==="assistant"&&!!v.jobId).map(v=>v.jobId))),h=c.some(v=>!!v.responseText||!!v.question||!!v.result||!!v.memoryReviewCard||!!v.memoryReceipt),p=c.some(v=>!!v.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:h,hasError:p,lastMessageRole:T,pendingQuestion:P,acknowledgedJobIds:b,elementIdentifiers:r.elementIdentifiers}})}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await yt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:r,...i})=>{let s={};if(r?.path)try{let c=await yt(Ee(Kn(this.legacyFilePath),r.path),"utf8");Vn("sha256").update(c).digest("hex")===r.sha256&&(s=JSON.parse(c))}catch{}return Dt({...i,...s})}));return{id:n.id,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=Rc(e),t=kc(e);if(Object.keys(n).length===0)return t;let r=Tc(n),i=Vn("sha256").update(r).digest("hex"),s=Ee("artifacts","thread-messages",`${i}.json`);await rn(this.artifactsDir,{recursive:!0});try{await yt(Ee(Kn(this.legacyFilePath),s),"utf8")}catch{await Ot(Ee(Kn(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Kn(t)===this.mediaDir)return t;try{let r=await yt(t),i=Vn("sha256").update(r).digest("hex"),s=Ee(this.mediaDir,`${i}${Sc(t)||".bin"}`);await rn(this.mediaDir,{recursive:!0});try{await yt(s)}catch{await Ot(s,r)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,r])=>[t,await n(r)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,r])=>[t,await Promise.all(r.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([t,r])=>[t,await Promise.all(r.map(async i=>({...i,path:await n(i.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await rn(this.threadsDir,{recursive:!0});let n=this.index??{...sn,files:{}},t=n.files[e.id]??`${Vn("sha256").update(e.id).digest("hex").slice(0,32)}.json`,r=await Promise.all(e.messages.map(s=>this.encodeMessage(s))),i={...e,version:2,messages:r};await Ot(Ee(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Ot(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await rn(this.threadsDir,{recursive:!0}),this.index=this.index??{...sn,files:{}},await Ot(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...sn,files:{}},t=n.files[e];t&&await xc(Ee(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await rn(this.threadsDir,{recursive:!0}),await Ot(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as jc,open as Mc,readFile as Ac,rename as Ec,unlink as _c}from"fs/promises";import{dirname as Cc,join as $c}from"path";var pi={schemaVersion:1,theme:"auto",updatedAt:null};function ui(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Oc(o,e){await jc(Cc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await Mc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
174
|
-
`,"utf8"),await t.sync()}finally{await t.close()}await
|
|
175
|
-
`)}function
|
|
176
|
-
`)[0].trim().slice(0,60):"Running command";break;case"Glob":
|
|
177
|
-
`)}function
|
|
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 dn(o,e,n){let t=[];if(o.annotations.length>0){t.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(p=>{let w=[p.selector];return p.reactComponent&&w.push(`(${p.reactComponent})`),w.join(" ")}).join(", "),s=i.instruction||"No text";t.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[i.id];if(c&&c.length>0)for(let p of c)t.push(` Attached image: use the Read tool to view ${p}`);let d=n?.[i.id];if(d?.length)for(let p of d)t.push(` Attached context (${p.name}, ${p.mimeType}): use the Read tool to inspect ${p.path}`)}}if(o.styleModifications.length>0){t.push(""),t.push("## Style Changes (make permanent in source)"),t.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)t.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){t.push(""),t.push("## Text Changes (make permanent in source)"),t.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(".")}`:"";t.push(`- ${i.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(o.domModifications?.length){t.push(""),t.push("## DOM Structure Changes (make permanent in source)"),t.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}`;t.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${c}`)}}if(o.spacingTokenChanges?.length){t.push(""),t.push("## Spacing Token Changes"),t.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let i of o.spacingTokenChanges){t.push(`
|
|
169
|
+
### ${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?t.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):t.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),t.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;t.push(""),t.push("## Inspected Element"),t.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)}"`),t.push(`- ${r.join(" ")}`)}return t.join(`
|
|
170
|
+
`)}function yr(o,e,n){let t=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(t.push("You are reviewing a UI screenshot with developer annotations."),t.push(""),!r&&n?.provider!=="codex"&&(t.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),t.push("")),t.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),n?.threadHistory&&n.threadHistory.length>0){t.push(""),t.push("## Previous Conversation");let s=0;for(let c of n.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(t.push(`### Round ${s} (human) \u2014 reply`),t.push(`"${c.replyToQuestion}"`)):(t.push(`### Round ${s} (human)`),c.feedbackSummary&&t.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&t.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)t.push(`### Round ${s} (assistant) \u2014 question`),t.push(`"${c.question}"`);else{if(t.push(`### Round ${s} (assistant)`),c.responseText&&t.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let p=d.finalScope??d.inferredScope,w=p?` [${p.breadth} ${p.target}]`:"";t.push(`- ${d.annotationId}: ${d.status}${w} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&t.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&t.push(`Tools used: ${c.toolsUsed.join(", ")}`)}t.push(""),t.push("The current round is shown in full below.")}if(n?.designModel){t.push(""),t.push("## Established Design Policies"),t.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=n.designModel.rules;if(Array.isArray(s)&&s.length>0)if(t.push(""),t.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let w=new Map;for(let x of s)if(typeof x=="object"&&x!==null&&"text"in x){let T=x,k=T.scope||"general";w.has(k)||w.set(k,[]),w.get(k).push(T.text)}for(let[x,T]of w){t.push(`**${x.charAt(0).toUpperCase()+x.slice(1)}**`);for(let k of T)t.push(`- ${k}`)}}else for(let w of s)typeof w=="string"&&t.push(`- ${w}`);let c=n.designModel.tokens;c&&typeof c=="object"&&(t.push(""),t.push("Design tokens:"),t.push("```json"),t.push(JSON.stringify(c,null,2)),t.push("```"));let d=n.designModel.components;d&&typeof d=="object"&&(t.push(""),t.push("Component patterns:"),t.push("```json"),t.push(JSON.stringify(d,null,2)),t.push("```")),t.push(""),t.push("### Applied Model-Gap Details"),t.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:"),t.push("<novel>"),t.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),t.push("</novel>"),t.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),t.push("- `element`: What you are styling or creating"),t.push("- `decision`: What you actually implemented (specific values)"),t.push("- `reason`: Why this is novel (what is missing from the model)"),t.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."),t.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(n?.designModel||(t.push(""),t.push("## Design Context"),t.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=n?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let p=d.pathname||new URL(e.url).pathname;c.has(p)||c.set(p,[]),c.get(p).push(d)}t.push(""),t.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,p]of c){t.push(""),t.push(`## Page: ${d}`);let w=s[d];w&&n?.provider!=="codex"?t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${w}`):!w&&n?.provider!=="codex"&&(Object.keys(s).length===0?(t.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),t.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):t.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let x={...e,annotations:p,styleModifications:e.styleModifications},T=dn(x,n?.imagePaths,n?.attachmentFiles);T&&(t.push(""),t.push(T))}}else{let s=dn(e,n?.imagePaths,n?.attachmentFiles);s&&(t.push(""),t.push(s))}return t.push(""),t.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."),t.push(""),t.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),t.push(""),t.push("## Resolution"),t.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),t.push("<resolution>"),t.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),t.push("</resolution>"),t.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."),t.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),t.push(""),t.push("### Scope classification"),t.push("Each resolution MUST include scope fields:"),t.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),t.push("- `inferredScope`: What scope the change actually has, based on what you modified."),t.push("Scope has two dimensions:"),t.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),t.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),t.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),t.push("If you cannot confidently determine scope, set it to null."),t.push(""),t.push("## Questions"),t.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),t.push('<question>What do you mean by "..."?</question>'),t.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),t.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),t.join(`
|
|
171
|
+
`)}function vr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function Ir(o,e,n,t){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),n!=="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."),t&&t.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of t)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(`
|
|
172
|
+
`)}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 Pc(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 n of["declaredScope","inferredScope","finalScope"])if(e[n]!==void 0&&e[n]!==null&&!Tc(e[n]))return!1;return!0}function wr(o){let n=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!n)return[];try{let t=JSON.parse(n);return(Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.annotations)?t.annotations:[]).filter(Pc)}catch{return[]}}function Rc(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let n=JSON.parse(e[1]);return Array.isArray(n)?n.filter(t=>{if(typeof t!="object"||t===null)return!1;let i=t;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 br(o,e){return e>0?Rc(o):[]}import{execFile as kc}from"child_process";import{readdir as jc,readFile as Ac,stat as Mc}from"fs/promises";import{homedir as ln}from"os";import{join as Ze}from"path";var Hn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:xr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:xr()}],pn=[{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"}],un={id:"",label:"Default",source:"cli"},Ec=/^\s*-\s+"([^"]+)"/;function _c(o){let e=[],n=!1;for(let t of o.split(`
|
|
173
|
+
`)){if(/^\s*`model`:/.test(t)){n=!0;continue}if(n&&/^\s*`[^`]+`:/.test(t))break;if(!n)continue;let i=t.match(Ec);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Zo(r),source:"cli"})}return Vn([un,...e])}function Cc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(t=>t.visibility===void 0||t.visibility==="list").sort((t,i)=>{let r=typeof t.priority=="number"?t.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(t=>{let i=typeof t.slug=="string"?t.slug:typeof t.id=="string"?t.id:"";if(!i)return[];let r=typeof t.display_name=="string"&&t.display_name.trim()?t.display_name.trim():Zo(i),s=Array.isArray(t.supported_reasoning_levels)?t.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let p=d;return typeof p.effort!="string"?[]:[{effort:p.effort,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0,c=Array.isArray(t.service_tiers)?t.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let p=d;return typeof p.id!="string"?[]:[{id:p.id,label:typeof p.name=="string"?p.name:p.id,...typeof p.description=="string"?{description:p.description}:{}}]}):void 0;return[{id:i,label:r,source:"cli",...typeof t.default_reasoning_level=="string"?{defaultReasoningLevel:t.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function xr(){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 Vn(e.map(n=>({id:n,label:Zo(n),source:"cli"})))}function Zo(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"},n=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[n])return e[n];let t=n.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(t){let r=t[1]==="sonnet"?"Sonn":Bc(t[1]),s=t[2]&&t[3]?` ${t[2]}.${t[3]}`:"";return`${r}${s}${t[4]?" Fast":""}`}let i=n.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 n}async function Sr(o="copilot"){let e=await Wn(o,["help","config"]),n=_c(e);return n.length>1?n:[un]}async function Tr(o="codex"){let e=await Wn(o,["debug","models"]).catch(async()=>{let t=process.env.CODEX_HOME||Ze(ln(),".codex");return Rr(Ze(t,"models_cache.json"))}),n=Cc(e);return n.length>0?Vn([...n,...pn]):pn}async function Pr(o="claude"){let e=Ze(ln(),".claude"),n=[Ze(ln(),".claude","stats-cache.json"),Ze(ln(),".claude","settings.json"),Ze(ln(),".claude.json"),Ze(e,"cache","changelog.md")],[t,i,r]=await Promise.all([Wn(o,["--help"]).catch(()=>""),Wn(o,["--version"]).catch(()=>""),Oc(e).catch(()=>[])]),s=Nc([...n,...r]),c=await Promise.all(s.map(p=>Rr(p).catch(()=>""))),d=$c([t,i,...c].join(`
|
|
174
|
+
`));return Vn([...Hn,...d])}function Wn(o,e,n=5e3){return new Promise((t,i)=>{kc(o,e,{encoding:"utf-8",timeout:n},(r,s)=>{if(r){i(r);return}t(s)})})}async function Rr(o){return Ac(o,"utf-8")}async function Oc(o){let e=[Ze(o,"projects"),Ze(o,"telemetry")],n=[];for(let t of e)await kr(t,n,4);return n.sort((t,i)=>i.mtimeMs-t.mtimeMs).slice(0,80).map(t=>t.path)}async function kr(o,e,n){if(n<0)return;let t;try{t=await jc(o,{withFileTypes:!0})}catch{return}await Promise.all(t.map(async i=>{let r=Ze(o,i.name);if(i.isDirectory()){await kr(r,e,n-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 Vn(o){let e=new Set,n=[];for(let t of o)e.has(t.id)||(e.add(t.id),n.push(t));return n}function Nc(o){return[...new Set(o)]}function Bc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Kn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,n){n?this.activeProcesses.set(e,n):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let n=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){n=r;break}}let t=n>=0?n+1:0,i=this.activeJobs.size+t+1;return this.queue.splice(t,0,e),this.processNext(),i}hasActiveThread(e){return this.allActive.some(n=>n.threadId===e)}getQueuedThreadJob(e,n){return this.queue.find(t=>t.threadId===e&&(!n||n(t)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,n,t){let i=this.bufferEvent(n,e);for(let r of this.listeners)r(i,n,t)}bufferEvent(e,n){let t=this.eventBuffers.get(e);t||(t={events:[],nextSeq:0},this.eventBuffers.set(e,t));let i={...n,seq:t.nextSeq++};return t.events.push(i),t.events.length>1e4&&t.events.splice(0,t.events.length-1e4),i}getBufferedEvents(e,n=-1){let t=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!t)return null;let s=n<0?t.events:t.events.filter(c=>c.seq>n);return{jobId:e,events:s,currentSeq:t.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,n,t){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[n]+=t}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let n=this.cleanupTimers.get(e);n&&clearTimeout(n);let t=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,t)}cancelJob(e){let n=this.activeProcesses.get(e),t=this.activeJobs.get(e);return!n||!t?!1:(n.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),t.status="error",t.error="Cancelled by user",this.broadcast({type:"error",jobId:t.id,threadId:t.threadId,message:"Cancelled by user",cancelled:!0,provider:t.provider,model:t.model},t.id,t.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let n of e)this.cancelJob(n);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let n=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),n.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let t of n)try{t.kill("SIGTERM")}catch{}await Promise.all(n.map(t=>new Promise(i=>{let r=!1,s=()=>{r||(r=!0,i())};t.on("exit",s),t.on("error",s),setTimeout(()=>{if(!r){try{t.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let t of this.cleanupTimers.values())clearTimeout(t);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(n=>{e.status="error",e.error=n instanceof Error?n.message:String(n),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as rt}from"crypto";import{createHash as Jc}from"crypto";import{mkdir as Lc,open as Fc,readFile as jr,readdir as qc,rename as Uc,unlink as zc}from"fs/promises";import{dirname as Gc,join as Ft}from"path";function Ce(o){return structuredClone(o)}function Ar(o){return Jc("sha256").update(JSON.stringify(o)).digest("hex")}async function Tt(o,e){await Lc(Gc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Fc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
175
|
+
`,"utf8"),await t.sync()}finally{await t.close()}try{await Uc(n,o)}catch(i){throw await zc(n).catch(()=>{}),i}}function Wc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function Hc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Ce(e):o.explanations.push(Ce(e))}function Qn(o,e){let n=Ce(o);for(let t of e)if(t.op==="add_explanation"){if(n.explanations.some(i=>i.id===t.explanation.id))throw new Error(`Imprint explanation already exists: ${t.explanation.id}`);n.explanations.push(Ce(t.explanation))}else if(t.op==="replace_explanation")Hc(n,t.explanation);else if(t.op==="remove_explanation")n.explanations=n.explanations.filter(i=>i.id!==t.explanationId),n.relations=n.relations.filter(i=>i.fromId!==t.explanationId&&i.toId!==t.explanationId);else if(t.op==="add_concrete")n.concrete.some(i=>i.id===t.concrete.id)||n.concrete.push(Ce(t.concrete));else if(t.op==="remove_concrete")n.concrete=n.concrete.filter(i=>i.id!==t.concreteId),n.relations=n.relations.filter(i=>i.fromId!==t.concreteId&&i.toId!==t.concreteId);else if(t.op==="add_evidence"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);i.evidence.some(r=>r.id===t.evidence.id)||(i.evidence.push(Ce(t.evidence)),i.updatedAt=t.evidence.createdAt)}else if(t.op==="revise_explanation"){let i=n.explanations.find(r=>r.id===t.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${t.explanationId}`);Object.assign(i,Ce(t.patch),{updatedAt:t.updatedAt})}else if(t.op==="add_relation"){let i=t.relation,r=n.explanations.find(p=>p.id===i.fromId),s=n.explanations.find(p=>p.id===i.toId),c=n.concrete.some(p=>p.id===i.fromId),d=n.concrete.some(p=>p.id===i.toId);if(Qi(i.type)){if(!(i.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(n.relations.some(w=>w.type===i.type&&w.fromId===i.fromId&&w.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toId}`);if(i.type==="expresses"&&r&&s){if($t(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let w=new Map;for(let k of n.relations)k.type==="expresses"&&w.set(k.fromId,[...w.get(k.fromId)??[],k.toId]);let x=[i.toId],T=new Set;for(;x.length;){let k=x.pop();if(k===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);T.has(k)||(T.add(k),x.push(...w.get(k)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);n.relations.some(p=>p.id===i.id)||n.relations.push(Ce(i))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(i=>i.id!==t.relationId));return n}function Vc(o,e){let n=[],t=Ce(o);for(let i of e){if(i.op==="add_explanation")n.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=t.explanations.find(s=>s.id===i.explanationId);r&&n.unshift({op:"add_explanation",explanation:Ce(r)})}else if(i.op==="add_concrete")n.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=t.concrete.find(s=>s.id===i.concreteId);r&&n.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=t.explanations.find(c=>c.id===r);s&&n.unshift({op:"replace_explanation",explanation:Ce(s)})}else if(i.op==="add_relation")n.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=t.relations.find(s=>s.id===i.relationId);r&&n.unshift({op:"add_relation",relation:Ce(r)})}t=Qn(t,[i])}return n}function Mr(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 qt=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=Ft(e,".popmelt","imprint"),this.manifestPath=Ft(this.imprintDir,"manifest.json"),this.graphPath=Ft(this.imprintDir,"graph.json"),this.journalDir=Ft(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await jr(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let n=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:n,updatedAt:n,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),t=(await qc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=Wc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await jr(Ft(this.journalDir,t[c]),"utf8")),{hash:p,...w}=d;if(d.sequence!==c+1||d.previousHash!==s||p!==Ar(w))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=Qn(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:xt(e.graph)}}async migrateTopology(){let e=await this.readManifest();if(e.topologyVersion===2)return{migrated:!1,relationMutations:0};let n=await this.loadRaw(),t=xt(n.graph),i=new Map(t.relations.map(s=>[s.id,s])),r=[];for(let s of n.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-${n.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await Tt(this.graphPath,t),await Tt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let n;return this.writeChain=this.writeChain.then(async()=>{let t=await this.load();if(t.transactions.some(x=>x.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=t.graph.head.sequence+1,r=Vc(t.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:t.graph.head.hash,source:e.source,summary:e.summary,mutations:Ce(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Ar(s)},d=Qn(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let p=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await Tt(Ft(this.journalDir,p),c);let w={version:1,topologyVersion:2,projectId:this.projectId,createdAt:d.createdAt,updatedAt:e.committedAt,head:d.head};await Tt(this.graphPath,d),await Tt(this.manifestPath,w),n={graph:d,transaction:c}}),await this.writeChain,n}async undo(e,n,t,i){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(Mr));if(r.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(w=>Mr(w).some(x=>c.has(x)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:t,source:n,summary:`Undo: ${s.summary}`,mutations:s.inverseMutations,undoesTransactionId:e})}async recover(){let e=await this.load();return await Tt(this.graphPath,e.graph),await Tt(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 ti(o){return!!(o&&Xc.test(o))}function Yc(o){return o.scope.kind==="project"||ti(`${o.statement} ${o.rationale}`)}function Zc(o){let e=o?.scope.values.filter(n=>n!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function ed(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Xn(o){return new Set(ed(o).split(" ").filter(e=>e.length>2&&!Qc.has(e)))}function Yn(o,e){if(!o.size||!e.size)return 0;let n=0;for(let t of o)e.has(t)&&(n+=1);return n/Math.min(o.size,e.size)}function ei(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 it(o,e,n){return{id:rt(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:n,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ve(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Er(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 n=e.values.filter(t=>typeof t=="string"&&!!t.trim());return n.length?{kind:e.kind,values:n}:void 0}function _r(o,e){if(!o||!e.trim())return{found:!1};let n=o;for(let t of e.split(".").filter(Boolean))if(Array.isArray(n)){let i=Number(t);if(!Number.isInteger(i)||i<0||i>=n.length)return{found:!1};n=n[i]}else if(n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,t))n=n[t];else return{found:!1};return{found:!0,value:n}}function Zn(o,e={}){let n=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],t=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),i=n.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:t,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:t,error:"imprint assessment is missing"};let w=p;r=w.imprint,s=Array.isArray(w.annotations)?w.annotations:[]}catch{return{visibleText:t,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(!Kc.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(S=>S.id)??[]),m=new Set(e.context?.pendingGroundingExplanationIds??[]),j=h.filter(S=>{let g=e.context?.explanations.find(J=>J.id===S);return u.has(S)&&g&&(g.state==="emerging"||g.state==="testing")&&!m.has(S)});if(j.length){let S=c.grounding,g=typeof S?.explanationId=="string"&&j.includes(S.explanationId)?S.explanationId:j[0],J=ve(S?.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||t,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:j,grounding:{explanationId:g,question:J||"Does applying this understanding here match your intent?"}},visibleText:t}}}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(ti(e.requestText)&&!Yc(m))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:f,duplicateOfExplanationId:h,scopeComparison:u},visibleText:t}}return{draft:{decision:"none",reason:f},visibleText:t}}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:t}}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(J=>typeof J=="string"&&!!J.trim()):[];if(!h.length)throw new Error("application requires appliedExplanationIds");let u=new Map(e.context?.explanations.map(J=>[J.id,J])??[]),m=new Set(e.context?.pendingGroundingExplanationIds??[]),j=h.filter(J=>{let E=u.get(J);return E&&(E.state==="emerging"||E.state==="testing")&&!m.has(J)});if(!j.length){if(h.every(E=>u.get(E)?.state==="grounded"||m.has(E)))return{draft:{decision:"none",reason:"application_only"},visibleText:t};throw new Error("application must cite a surfaced ungrounded explanation")}let S=c.grounding,g=typeof S?.explanationId=="string"&&j.includes(S.explanationId)?S.explanationId:j[0];return{draft:{decision:"apply",summary:l,appliedExplanationIds:j,grounding:{explanationId:g,question:ve(S?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:t}}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 w={kind:p,title:ve(d?.title,120),detail:ve(d?.detail,500)};if(!w.title||!w.detail)throw new Error("summary title and detail are required");let x=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[],T=[];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;T.push({op:"add",clientId:ve(l.clientId,100)||void 0,kind:l.kind,statement:h,rationale:u,scope:Er(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:Er(l.scope),reopenGrounding:l.reopenGrounding===!0};(h.statement||h.rationale||h.scope||h.reopenGrounding)&&T.push(h)}else if(l.op==="evidence"&&typeof l.explanationId=="string"&&["supports","challenges","excepts"].includes(String(l.stance))){let h=ve(l.summary);h&&T.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;T.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&&T.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&&T.push({op:"bind_concrete",explanationId:l.explanationId,modelPath:h,rationale:ve(l.rationale)})}else l.op==="retire"&&typeof l.explanationId=="string"&&T.push({op:"retire",explanationId:l.explanationId,reason:ve(l.reason)})}let k=c.grounding,y=k&&typeof k.explanationId=="string"&&ve(k.question)?{explanationId:k.explanationId,question:ve(k.question,300)}:void 0;return{draft:{decision:"mutate",summary:w,appliedExplanationIds:x,mutations:T,grounding:y},visibleText:t}}catch(c){return{visibleText:t,error:c instanceof Error?c.message:String(c)}}}function eo(o,e={}){let n=o?.explanations??[],t=new Set(o?.pendingGroundingExplanationIds??[]),i=ti(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.",...n.length?["","Relevant explanations from the project imprint:",...n.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}`,...t.has(r.id)?[" - Grounding: already pending; do not ask again"]:[],...r.concrete.map(c=>` - Concrete terminal: ${c.modelPath} = ${JSON.stringify(c.value)}`)].join(`
|
|
176
|
+
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.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.",...i?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","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 Ut=class{constructor(e,n){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new qt(e,n)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let n=Xn(e.text??""),t=Xn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]);if(!n.size&&!t.size&&!i.size)return;let{graph:r}=await this.store.load(),s=r.explanations.filter(y=>y.state!=="retired"&&y.state!=="challenged").map(y=>{let f=Xn([y.statement,y.rationale].join(" ")),l=Xn(y.scope.values.join(" ")),h=Yn(f,n),u=Yn(l,n),m=Yn(l,t),j=Yn(f,t),S=h+u*.2+m*.25+j*.1+(y.state==="grounded"?.08:0)+(i.has(y.id)?1:0),g=i.has(y.id)||(n.size?h>=.12||u>=.5:m>=.2||j>=.2);return{item:y,score:S,relevant:g}}).filter(y=>y.relevant&&y.score>=.18).sort((y,f)=>f.score-y.score||f.item.updatedAt.localeCompare(y.item.updatedAt)),c=Math.max(1,e.maxExplanations??6);if(!s.length)return;let d=s.slice(0,c).map(({item:y})=>y),p=new Set(d.map(y=>y.id)),w=new Set(r.relations.flatMap(y=>p.has(y.fromId)?[y.toId]:p.has(y.toId)?[y.fromId]:[])),x=new Set(r.explanations.flatMap(y=>w.has(y.id)&&y.state!=="retired"&&y.state!=="challenged"?[y.id]:[])),T=r.explanations.filter(y=>x.has(y.id)&&!p.has(y.id)).sort((y,f)=>f.updatedAt.localeCompare(y.updatedAt)).slice(0,4),k=[...d,...T];for(let y of T)p.add(y.id);return{explanations:k.map(y=>{let f=new Set(r.relations.filter(l=>l.toId===y.id&&l.type==="expresses").map(l=>l.fromId));return{id:y.id,kind:y.kind,statement:y.statement,rationale:y.rationale,scope:y.scope,state:y.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||T.length<x.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},relations:r.relations.filter(y=>p.has(y.fromId)&&p.has(y.toId)).map(y=>({id:y.id,type:y.type,fromId:y.fromId,toId:y.toId,rationale:y.rationale}))}}async capture(e,n){let t=e.decision==="mutate"?e.mutations:[],i=n.applicationOccurred?t.flatMap(b=>b.op==="add"&&b.clientId?[b.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...i])];if(t.length===0&&r.length===0)return;let s=n.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(b=>[b.id,b])),p=new Map,w=new Map,x=[],T=new Set,k=new Set(n.pendingGroundingExplanationIds??[]),y=new Set(t.flatMap(b=>b.op==="revise"&&t.some(H=>H.op==="evidence"&&H.stance==="challenges"&&H.explanationId===b.explanationId)?[b.explanationId]:[])),f=new Set(t.flatMap(b=>b.op==="add"&&b.clientId?[b.clientId]:[])),l=b=>d.has(b)||f.has(b),h=new Set;for(let b of t)b.op==="relation"&&b.fromId!==b.toId&&l(b.fromId)&&l(b.toId)?(h.add(b.fromId),h.add(b.toId)):b.op==="supersede"&&b.explanationId!==b.replacementId&&l(b.explanationId)&&l(b.replacementId)?(h.add(b.explanationId),h.add(b.replacementId)):b.op==="bind_concrete"&&l(b.explanationId)&&_r(n.concreteModel,b.modelPath).found&&h.add(b.explanationId);let u=c.graph.explanations.length===0;for(let b of t){if(b.op!=="add")continue;let H=!!(b.clientId&&h.has(b.clientId)),L=!!b.rootReason?.trim()||u;if(!H&&!L)continue;u&&(u=!1);let O=rt();b.clientId&&p.set(b.clientId,O);let fe=b.clientId?r.includes(b.clientId):!1,B={id:O,kind:b.kind,statement:b.statement,rationale:b.rationale,scope:ei(b.scope),state:fe?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[it(n,"supports",e.summary.detail)]};d.set(O,B),T.add(O),x.push({op:"add_explanation",explanation:B})}let m=b=>p.get(b)??b;for(let b of t){if(b.op!=="revise")continue;let H=m(b.explanationId),L=d.get(H);if(L?.state!=="grounded")continue;let O=rt(),fe={id:O,kind:L.kind,statement:b.statement??L.statement,rationale:b.rationale??L.rationale,scope:b.scope?ei(b.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[it(n,"supports",e.summary.detail)]};d.set(O,fe),w.set(H,O),T.add(O),x.push({op:"add_explanation",explanation:fe});let B=$t(L,fe);B!==0&&x.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:B>0?H:O,toId:B>0?O:H,rationale:b.rationale??e.summary.detail,createdAt:s}})}let j=b=>{let H=m(b);return w.get(H)??H};for(let b of t){if(b.op==="add")continue;if(b.op==="bind_concrete"){let L=j(b.explanationId);if(!d.has(L))continue;let O=_r(n.concreteModel,b.modelPath);if(!O.found)continue;let fe=c.graph.concrete.find(B=>B.modelPath===b.modelPath&&JSON.stringify(B.value)===JSON.stringify(O.value));fe||(fe={id:rt(),modelPath:b.modelPath,value:structuredClone(O.value),createdAt:s,updatedAt:s},x.push({op:"add_concrete",concrete:fe})),x.push({op:"add_relation",relation:{id:rt(),type:"expresses",fromId:fe.id,toId:L,rationale:b.rationale,createdAt:s}}),T.add(L);continue}if(b.op==="relation"){let L=j(b.fromId),O=j(b.toId);if(!d.has(L)||!d.has(O)||L===O)continue;b.type==="expresses"&&$t(d.get(L),d.get(O))<0&&([L,O]=[O,L]),x.push({op:"add_relation",relation:{id:rt(),type:b.type,fromId:L,toId:O,rationale:b.rationale,createdAt:s}}),T.add(L),T.add(O);continue}if(b.op==="supersede"){let L=j(b.explanationId),O=j(b.replacementId);if(!d.has(L)||!d.has(O)||L===O)continue;x.push({op:"add_evidence",explanationId:L,evidence:it(n,"challenges",b.reason)}),x.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:O},updatedAt:s}),T.add(L),T.add(O);continue}let H=j(b.explanationId);if(d.has(H))if(T.add(H),b.op==="revise"){if(w.has(m(b.explanationId)))continue;let L=d.get(H);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let O={...b.statement?{statement:b.statement}:{},...b.rationale?{rationale:b.rationale}:{},...b.scope?{scope:ei(b.scope)}:{},...b.reopenGrounding||y.has(b.explanationId)?{state:"testing"}:{}};x.push({op:"revise_explanation",explanationId:H,patch:O,updatedAt:s})}else if(b.op==="evidence"){if(b.stance==="challenges"&&y.has(b.explanationId))continue;x.push({op:"add_evidence",explanationId:H,evidence:it(n,b.stance,b.summary)}),b.stance==="challenges"&&x.push({op:"revise_explanation",explanationId:H,patch:{state:"challenged"},updatedAt:s})}else b.op==="retire"&&(x.push({op:"add_evidence",explanationId:H,evidence:it(n,"challenges",b.reason||"Retired after contradictory collaboration evidence.")}),x.push({op:"revise_explanation",explanationId:H,patch:{state:"retired"},updatedAt:s}))}for(let b of r){let H=j(b),L=d.get(H);!L||L.state==="grounded"||L.state==="retired"||k.has(H)&&!T.has(H)||(T.has(H)||(T.add(H),x.push({op:"add_evidence",explanationId:H,evidence:{...it(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&x.push({op:"revise_explanation",explanationId:H,patch:{state:"testing"},updatedAt:s}))}let S=new Set(c.graph.relations.map(b=>`${b.type}:${b.fromId}:${b.toId}`)),g=x.filter(b=>{if(b.op!=="add_relation")return!0;let H=`${b.relation.type}:${b.relation.fromId}:${b.relation.toId}`;return S.has(H)?!1:(S.add(H),!0)});if(!g.length)return;let J=rt(),E=await this.store.commit({transactionId:J,committedAt:s,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:g}),R=new Map(E.graph.explanations.map(b=>[b.id,b])),N=[...T].flatMap(b=>{let H=R.get(b);if(!H)return[];let L=!c.graph.explanations.some(fe=>fe.id===b),O=H.state==="challenged"||H.state==="retired";return[{explanationId:b,action:L?"added":O?"challenged":"revised",statement:H.statement,state:H.state}]}),V=r.map(j).find(b=>R.get(b)?.state==="testing"&&!k.has(b)),K=e.grounding?j(e.grounding.explanationId):V,W=K?R.get(K):void 0,Q=W?.state==="testing"&&!k.has(W.id)?{explanationId:W.id,question:e.grounding?.question||Zc(W),state:"testing"}:void 0;return{transactionId:J,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 n=e.occurredAt??new Date().toISOString(),t=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!t)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(p=>p.id===t);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:t,evidence:{...it(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"grounded"},updatedAt:n}),d=`Grounded: ${r.statement}`):e.action==="this_time"?(c.push({op:"add_evidence",explanationId:t,evidence:{...it(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"emerging"},updatedAt:n}),d=`Observed this time: ${r.statement}`):e.action==="no"&&(c.push({op:"add_evidence",explanationId:t,evidence:{...it(e,"challenges","The developer said this understanding did not capture their intent and requested follow-up."),kind:"rejection"}}),c.push({op:"revise_explanation",explanationId:t,patch:{state:"challenged"},updatedAt:n}),d=`Challenged: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:rt(),committedAt:n,source:s,summary:d,mutations:c})}};function mn(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function to(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function ni(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 Cr(o){let e=ni(to(o.origin));if(e)return e;let n=ni(to(o.referer));if(n)return n;let t=to(o["x-forwarded-host"]);if(!t)return null;let i=to(o["x-forwarded-proto"])==="https"?"https":"http";return ni(`${i}://${t}`)}function $r(o,e,n=5){let t=(d,p)=>(p.completedAt??p.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(t).slice(0,n),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(t).slice(0,n),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:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as io}from"crypto";import{mkdir as hn,readFile as Pt,unlink as sd,writeFile as Gt}from"fs/promises";import{dirname as ro,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 Or(o,e){let n=e??nd(o);return{kind:n,...td[n]}}function zt(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function oi(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),n=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],t=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&&n.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:t,outcomes:n}}import{createHash as od,randomUUID as id}from"crypto";var Dr=o=>`${o}-${id()}`;function ii(o,...e){return`${o}-${od("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function ri(o){return{schemaVersion:1,submissionIds:[Dr("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function fn(o,e=[],n){return{...o,outcomeId:o.outcomeId??Dr("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...n?{imprintAssessment:n}:{}}}function rd(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function no(o,e){return e?[`${o||"/"}:${e}`]:[]}function Nr(o){let e=rd(o.url);return[...new Set([...o.annotations.flatMap(n=>no(n.pathname??e,n.linkedSelector)),...o.styleModifications.flatMap(n=>no(e,n.durableSelector??n.selector)),...(o.textModifications??[]).flatMap(n=>no(n.pathname??e,n.durableSelector??n.selector)),...(o.domModifications??[]).flatMap(n=>no(n.pathname??e,n.durableSelector??n.selector))])]}function Br(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(n=>`annotation:${n.id}`),...o.annotations.flatMap(n=>(n.attachments??[]).map(t=>`attachment:${t.id}`))])]}function oo(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let n=ii("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[n],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(t=>`annotation:${t}`),...e.screenshotPath?[ii("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:ii("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function si(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let n of o.messages)e=oo(o.id,n)||e;return e}function Jr(o){let e=o.messages.at(-1),n=[...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 t=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:n?.jobId,threadId:o.id,status:t?"waiting_input":"resolved",label:t?"Question":"Replied",outcomeId:n?.lifecycle?.outcomeId,imprintEvidenceIds:n?.lifecycle?.imprintEvidenceIds??[]}}var cd={version:1,threads:{}},Lr=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],gn={version:2,updatedAt:0,files:{}};function dd(o){return JSON.stringify(o,null,2)}function ld(o){return Object.fromEntries(Lr.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function pd(o){let e={...o};for(let n of Lr)delete e[n];return e}function Wt(o){let e=o;if(o.error){let n=Or(o.error,o.errorKind);(o.error!==n.message||o.errorKind!==n.kind||o.responseText!==void 0)&&(e={...o,error:n.message,errorKind:n.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let n=zt(e.result,!1),t=zt(e.turn?.result,!1);(n!==e.result||t!==e.turn?.result)&&(e={...e,...n?{result:n}:{},...e.turn?{turn:{...e.turn,...t?{result:t}:{}}}:{}})}return e}var so=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let n=$e(e,".popmelt");this.legacyFilePath=$e(n,"threads.json"),this.threadsDir=$e(n,"threads"),this.indexPath=$e(this.threadsDir,"index.json"),this.artifactsDir=$e(n,"artifacts","thread-messages"),this.mediaDir=$e(n,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Pt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let n={};for(let[i,r]of Object.entries(e.files)){let s=await this.readThread($e(this.threadsDir,r));s&&(n[i]=s)}this.cache={version:1,threads:n};let t=!1;for(let i of Object.values(n))t=si(i)||t;return t&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Pt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([n,t])=>[n,{...t,messages:t.messages.map(Wt)}]))},this.index={...gn,files:{},migratedFromLegacyAt:Date.now()};for(let n of Object.values(this.cache.threads))si(n);return await this.persistAll(),this.cache}}catch{}return this.cache={...cd,threads:{}},this.index={...gn,files:{}},this.cache}async getThread(e){return(await this.load()).threads[e]??null}async findContinuationThread(e){if(e.length===0)return null;let n=await this.load(),t=new Set(e);for(let i of Object.values(n.threads))if(i.elementIdentifiers.some(s=>t.has(s)))return i;return null}async createThread(e,n){let t=await this.load(),i={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:n,messages:[]};return t.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,n){let i=(await this.load()).threads[e];i&&(oo(e,n),i.messages.push(Wt(n)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,n){let i=(await this.load()).threads[e];if(!i)return;oo(e,n);let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Wt(n)):i.messages.push(Wt(n)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===n);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,t),c.error){let d=Wt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,n,t){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===n);return s?(Object.assign(s,t),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,n){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of n)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let n=await this.load();return n.threads[e]?(delete n.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let n=await this.load(),t=Object.values(n.threads);return t.sort((i,r)=>r.updatedAt-i.updatedAt),t.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 h=l.imprintSummary?.grounding;if(h?.question&&!l.imprintSummary?.resolvedAction)return h.question},p=i.messages.findLastIndex(l=>!!d(l)),w=i.messages.findLastIndex(l=>l.role==="human"),x=p>w?d(i.messages[p]):void 0,T=i.messages.at(-1)?.role,k=Array.from(new Set(i.messages.slice(0,Math.max(0,w)).filter(l=>l.role==="assistant"&&!!l.jobId).map(l=>l.jobId))),y=c.some(l=>!!l.responseText||!!l.question||!!l.result||!!l.memoryReviewCard||!!l.memoryReceipt),f=c.some(l=>!!l.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:y,hasError:f,lastMessageRole:T,pendingQuestion:x,acknowledgedJobIds:k,elementIdentifiers:i.elementIdentifiers,lifecycle:Jr(i)}})}async recoverInterruptedTurns(){let e=await this.load(),n=0;for(let t of Object.values(e.threads)){let i=t.messages.at(-1);if(!i||i.role!=="human"||/^(imprint|memory)-/.test(i.jobId))continue;let r=fn(i.lifecycle);i.queued&&await this.updateMessage(t.id,i.jobId,{queued:!1}),await this.appendMessage(t.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}),n+=1}return n}async getThreadHistory(e,n=6){let t=await this.getThread(e);return!t||t.messages.length===0?[]:t.messages.length<=n?t.messages:[t.messages[0],...t.messages.slice(-(n-1))]}async readThread(e){try{let n=JSON.parse(await Pt(e,"utf8"));if(n?.version!==2||!Array.isArray(n.messages))return null;let t=await Promise.all(n.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await Pt($e(ro(this.legacyFilePath),i.path),"utf8");io("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Wt({...r,...s})}));return{id:n.id,lifecycleVersion:n.lifecycleVersion,createdAt:n.createdAt,updatedAt:n.updatedAt,elementIdentifiers:n.elementIdentifiers,messages:t}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let n=ld(e),t=pd(e);if(Object.keys(n).length===0)return t;let i=dd(n),r=io("sha256").update(i).digest("hex"),s=$e("artifacts","thread-messages",`${r}.json`);await hn(this.artifactsDir,{recursive:!0});try{await Pt($e(ro(this.legacyFilePath),s),"utf8")}catch{await Gt($e(ro(this.legacyFilePath),s),i)}return{...t,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let n=async t=>{if(ro(t)===this.mediaDir)return t;try{let i=await Pt(t),r=io("sha256").update(i).digest("hex"),s=$e(this.mediaDir,`${r}${ad(t)||".bin"}`);await hn(this.mediaDir,{recursive:!0});try{await Pt(s)}catch{await Gt(s,i)}return s}catch{return t}};e.screenshotPath&&(e.screenshotPath=await n(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([t,i])=>[t,await n(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([t,i])=>[t,await Promise.all(i.map(n))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([t,i])=>[t,await Promise.all(i.map(async r=>({...r,path:await n(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(n)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await hn(this.threadsDir,{recursive:!0});let n=this.index??{...gn,files:{}},t=n.files[e.id]??`${io("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 Gt($e(this.threadsDir,t),JSON.stringify(r,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await Gt(this.indexPath,JSON.stringify(n,null,2))}catch(n){console.error("[ThreadStore] Failed to persist thread:",n)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await hn(this.threadsDir,{recursive:!0}),this.index=this.index??{...gn,files:{}},await Gt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let n=this.index??{...gn,files:{}},t=n.files[e];t&&await sd($e(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await hn(this.threadsDir,{recursive:!0}),await Gt(this.indexPath,JSON.stringify(n,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 Fr={schemaVersion:1,theme:"auto",updatedAt:null};function qr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Id(o,e){await ud(yd(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await md(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
178
|
+
`,"utf8"),await t.sync()}finally{await t.close()}await hd(n,o)}catch(t){throw await gd(n).catch(()=>{}),t}}var ao=class{constructor(e){this.path=vd(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await fd(this.path,"utf8")),n=qr(e.theme);return n?{exists:!0,preferences:{schemaVersion:1,theme:n,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Fr}}}catch{return{exists:!1,preferences:{...Fr}}}}async setTheme(e){let n={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await Id(this.path,n),n}};function Ur(o){return qr(o)!==null}function co(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),n=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let T=7;T>=0;T--)e.push(n/Math.pow(2,T*8)&255);let t=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,p=528734635,w=1541459225,x=new Array(64);for(let T=0;T<e.length;T+=64){for(let S=0;S<16;S++){let g=T+S*4;x[S]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let S=16;S<64;S++){let g=et(x[S-15],7)^et(x[S-15],18)^x[S-15]>>>3,J=et(x[S-2],17)^et(x[S-2],19)^x[S-2]>>>10;x[S]=x[S-16]+g+x[S-7]+J>>>0}let k=t,y=i,f=r,l=s,h=c,u=d,m=p,j=w;for(let S=0;S<64;S++){let g=et(h,6)^et(h,11)^et(h,25),J=h&u^~h&m,E=j+g+J+wd[S]+x[S]>>>0,R=et(k,2)^et(k,13)^et(k,22),N=k&y^k&f^y&f,V=R+N>>>0;j=m,m=u,u=h,h=l+E>>>0,l=f,f=y,y=k,k=E+V>>>0}t=t+k>>>0,i=i+y>>>0,r=r+f>>>0,s=s+l>>>0,c=c+h>>>0,d=d+u>>>0,p=p+m>>>0,w=w+j>>>0}return[t,i,r,s,c,d,p,w].map(T=>T.toString(16).padStart(8,"0")).join("")}function et(o,e){return o>>>e|o<<32-e}function xd(o){let e=[];for(let n=0;n<o.length;n++){let t=o.charCodeAt(n);t<128?e.push(t):t<2048?e.push(192|t>>6,128|t&63):e.push(224|t>>12,128|t>>6&63,128|t&63)}return e}var zr={name:"@popmelt.com/core",version:"0.8.14",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 st=zr.version;var Dd=1111,Nd=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Bd=1800*1e3,Jd=3600*1e3,Hr=45e3,Ld=5e3,Fd=1e4,qd=2*1024*1024;function Vr(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,n)=>`${n+1}. ${e}`)].join(`
|
|
179
|
+
`)}function yn(o){return[...new Set(o.flatMap(e=>{let n=e.imprintSummary;return e.role==="assistant"&&n?.grounding&&!n.resolvedAction?[n.grounding.explanationId]:[]}))]}function Ud(o,e){if(e.size===1)return[...o].reverse().find(n=>{let t=n.imprintSummary;return n.role==="assistant"&&!!t?.grounding&&!t?.resolvedAction&&e.has(t.grounding.explanationId)})}function Yr(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 zd(o,e,n){let t=[...n];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,p;switch(r){case"Read":p=d?`Reading ${d}`:"Reading file";break;case"Edit":p=d?`Editing ${d}`:"Editing file";break;case"Write":p=d?`Writing ${d}`:"Writing file";break;case"Bash":p=c?c.split(`
|
|
180
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":p="Searching files";break;case"Grep":p="Searching code";break;case"WebFetch":p="Fetching page";break;case"WebSearch":p="Searching web";break;default:p=r?`Using ${r}`:"tool";break}let w=s??c??void 0,x=s?Xr(s)?s:$d(e,s):void 0,T=t[t.length-1];T&&T.kind==="tool_group"&&T.tool===r?T.items.push({label:p,detail:w,...x?{filePath:x}:{}}):t.push({kind:"tool_group",tool:r,items:[{label:p,detail:w,...x?{filePath:x}:{}}]})}return t}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 n=[];return o.success?n.push("Model suggestion ready."):n.push("Model projection failed."),o.proposalId&&n.push("Review the proposed model changes below."),e&&(e.outputStats?n.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):n.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(n.push(""),n.push(`Error: ${o.error}`),n.push("The selected decisions were not marked applied and remain visible in projection history.")),n.join(`
|
|
181
|
+
`)}function Wd(o,e=96){let n=o.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}...`:n}function Kr(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"}`)}),n=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),t=(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,...t,...n,...i].map(s=>Wd(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Hd(o,e){let n=o.headers.origin;Yr(n)&&(e.setHeader("Access-Control-Allow-Origin",n),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(o,e,n){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(n))}async function Oe(o){let e=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let t=JSON.parse(Buffer.concat(e).toString("utf8"));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Expected a JSON object");return t}async function Vd(o,e){let n=[],t=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(t+=r.length,t>e)throw new Error("Request body too large");n.push(r)}return Buffer.concat(n)}function Kd(o,e){let n=o.headers["x-popmelt-project-id"];return(Array.isArray(n)?n[0]:n)||e.searchParams.get("projectId")||null}function Qd(o,e){if(!o)return e;let n=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!n)return e;let[,t,i,r]=n;return`\x1B[38;2;${parseInt(t,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function uo(o,e){try{o.res.write(`event: ${e.type}
|
|
178
182
|
data: ${JSON.stringify(e)}
|
|
179
183
|
|
|
180
|
-
`)}catch{}}function
|
|
181
|
-
|
|
182
|
-
${a.error}`;await W.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:g})||await W.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:g})}f.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:g,model:a.model},a.id,a.sourceId),be.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Fe()}}catch(j){if(a.status==="cancelled")return;if(a.status="error",a.error=j instanceof Error?j.message:String(j),a.threadId){let I=`Model projection failed.
|
|
184
|
+
`)}catch{}}function Ht(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function mo(o){try{let e=new AbortController,n=setTimeout(()=>e.abort(),500),t=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(n),t.ok?await t.json():null}catch{return null}}function Xd(o,e){return new Promise((n,t)=>{let i=s=>{o.removeListener("listening",r),t(s)},r=()=>{o.removeListener("error",i),n()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function Zr(o={}){let e=new Date().toISOString(),n=o.port??Dd,t=o.projectRoot??process.cwd(),i=await kd(t).catch(()=>t),r=co(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??De(Ed(),"popmelt-bridge"),d=o.maxTurns??40,p=o.maxBudgetUsd??1,w=[...o.allowedTools??Nd],x=o.claudePath??"claude",T=o.copilotPath??"copilot",k=o.provider??"claude",y=o.timeoutMs,f=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,l=o.restartMode??"embedded",h=n,u={},m={claude:x,codex:"codex",copilot:T};for(let[a,v]of Object.entries(m))try{let M=v.includes("/")?v:Td("which",[v],{encoding:"utf-8"}).trim();u[a]={available:!0,path:M}}catch{u[a]={available:!1,path:null}}function j(a,v){return new Promise(M=>{let I=Gr(v,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,P=$=>{A||(A=!0,M($))},C=setTimeout(()=>{I.kill("SIGTERM"),P(!0)},5e3);I.on("error",()=>{clearTimeout(C),P(!1)}),I.on("close",$=>{clearTimeout(C),P($===0)})})}await Promise.all([(async()=>{u.claude&&(u.claude.models=u.claude.available&&u.claude.path?await Pr(u.claude.path).catch(()=>Hn):Hn)})(),(async()=>{u.codex&&(u.codex.models=u.codex.available&&u.codex.path?await Tr(u.codex.path).catch(()=>pn):pn)})(),(async()=>{u.copilot&&(u.copilot.models=u.copilot.available&&u.copilot.path?await Sr(u.copilot.path).catch(()=>[un]):[un])})()]);let[S,g,J]=await Promise.all([_o(i),Co(i),$o(i,u.copilot?.path??T)]);u.claude&&(u.claude.mcp=S),u.codex&&(u.codex.mcp=g),u.copilot&&(u.copilot.mcp=J),S.found&&S.name&&w.push(`mcp__${S.name}__*`),await Pd(c,{recursive:!0}),Qr(c).catch(()=>{});let E=new Kn(1),R=new En,N=new Cn(Hr),V=null,K=0,W=!1,Q=()=>{K+=1,W=!1,V&&clearTimeout(V),V=null},b=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},H=()=>{if(l!=="detached"||N.size>0||W)return;W=!0;let a=++K,v=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()>=v){W=!1,V=setTimeout(b,50),V.unref?.();return}V=setTimeout(M,250),V.unref?.()};M()},L=new Set,O=new so(i),fe=await O.recoverInterruptedTurns();fe>0&&console.warn(`[Popmelt] Recovered ${fe} interrupted thread turn(s) from durable history.`);let B=new kn(i);B.sweep();let D=new zn(i),Z=new Ut(i,r);try{let a=await Z.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 ae=new ao(i),Re=new Sn(i),se=new Mn(i,{claudePath:x,provider:k,timeoutMs:y,loadProjectableDecisions:a=>D.getProjectableDecisions(a),onEvent:a=>{for(let v of L)uo(v,a)}});D.beginAutomaticInitialization({writerVersion:st}).then(async a=>{a.state==="ready"?(await D.migrateImprintSnapshot(),await D.syncImprintGraph(),await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),k!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await ht({provider:k,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${h}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let qe=20,We=300*1e3,je=[];function ct(){let a=Date.now()-We;for(;je.length>0&&(je[0].completedAt<a||je.length>qe);)je.shift()}let He=new Map,dt=null,Vt;E.addListener((a,v,M)=>{for(let I of L)(!M||!I.sourceId||I.sourceId===M)&&uo(I,a)}),R.addListener((a,v,M)=>{for(let I of L)(!M||!I.sourceId||I.sourceId===M)&&uo(I,a)}),R.setProcessor(async a=>{let v=a.provider??k;try{let M=await se.run({provider:v,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let I=await se.loadRuns(),A=M.runId?I.runs.find(C=>C.id===M.runId):void 0;if(M.success&&M.proposalId){let C=await se.findModelProposal(M.proposalId),$=await se.loadModel(),F=C?Ei(C,$):null;if(C&&F){let z=C.decisionIds.map(q=>({decisionId:q,status:"projected"}));await D.applyModelProjection({runId:C.runId??C.id,presentationJobId:C.presentationJobId,decisionIds:C.decisionIds,changes:F.map(q=>({path:q.path,value:q.value,decisionIds:q.decisionIds})),coverage:z}),await se.applySelectedModelProposal(C.id,F.map(q=>({path:q.path,value:q.value})),F.map(q=>({group:q.path[0]==="rules"||q.path[0]==="components"||q.path[0]==="tokens"?q.path[0]:"model",label:q.label??q.id,detail:q.rationale,path:q.path,value:q.value})),"automatic")}}let P=Gd(M,A);if(a.threadId&&(await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:v})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:P,model:a.model,provider:v})),M.success)a.status="done",a.result=P,R.broadcast({type:"done",jobId:a.id,success:!0,responseText:P,threadId:a.threadId},a.id,a.sourceId),je.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),ct();else{if(a.status="error",a.error=M.error??"Projection failed",a.threadId){let C=`Model projection failed.
|
|
183
185
|
|
|
184
|
-
${a.error}`;await
|
|
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:v})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:C,error:a.error,model:a.model,provider:v})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),ct()}}catch(M){if(a.status==="cancelled")return;if(a.status="error",a.error=M instanceof Error?M.message:String(M),a.threadId){let I=`Model projection failed.
|
|
185
187
|
|
|
186
|
-
|
|
187
|
-
Attached image: use the Read tool to view the image at: ${U}`}a.kind==="synthesize"?q+=`
|
|
188
|
+
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,error:a.error,model:a.model,provider:v})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:I,error:a.error,model:a.model,provider:v})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:v,model:a.model},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),ct()}}),E.setProcessor(async a=>{let v=a,M=v._replyPrompt,I=v._replyText,A=v._replyImagePaths,P=a.provider??k,C=!!(a.surfacedProposalIds?.length&&M),$=!C&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&I!==void 0&&await O.updateMessage(a.threadId,a.id,{queued:!1});let F;if(a.threadId){let oe=await O.getThread(a.threadId);if(oe){for(let me=oe.messages.length-1;me>=0;me--)if(oe.messages[me].sessionId){F=oe.messages[me].sessionId;break}}}C&&(F=void 0);let z;if(F&&M){if(z=I??M,A&&A.length>0){z+=`
|
|
188
189
|
|
|
189
|
-
|
|
190
|
+
The developer attached reference images with their reply:`;for(let oe of A)z+=`
|
|
191
|
+
Attached image: use the Read tool to view the image at: ${oe}`}a.kind==="synthesize"?z+=`
|
|
190
192
|
|
|
191
|
-
|
|
193
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:z+="\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(F)z=dn(a.feedback,a.imagePaths,a.attachmentFiles)+`
|
|
192
194
|
|
|
193
195
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
194
196
|
|
|
195
|
-
After completing work, output
|
|
197
|
+
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(P!=="codex"?`
|
|
196
198
|
|
|
197
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let
|
|
199
|
+
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,me=M?null:await se.loadModel();z=M??yr(a.screenshotPath,a.feedback,{threadHistory:oe&&oe.length>0?oe:void 0,provider:P,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:me??void 0,screenshotPaths:a.screenshotPaths})}z+=lr(a.memoryReview),$&&(z+=eo(a.imprintContext,{requestText:I??Lt(a.feedback)})),z+=`
|
|
198
200
|
|
|
199
|
-
${qr}`;let J=ud(a.color,`[\u22B9 ${w}:${a.id}]`),ce=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${J} Reviewing ${ce} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${N?` (resuming: ${N.slice(0,8)})`:""}`);let F=new Nn(a.id),le=(U,ae)=>{if(U.type==="delta"&&"text"in U){let je=F.push(U.text);je.visibleText&&(C.accumulateText(ae,"response",je.visibleText),C.broadcast({...U,text:je.visibleText},ae,a.sourceId));for(let qe of je.orientations)C.broadcast({type:"orientation",jobId:ae,orientation:qe},ae,a.sourceId);return}else U.type==="thinking"&&"text"in U&&C.accumulateText(ae,"thinking",U.text);C.broadcast(U,ae,a.sourceId)},{process:se,result:ne}=S==="codex"?mn(a.id,{prompt:q,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:N,model:a.model,sandboxMode:$?"read-only":void 0,configOverrides:ln(a.agentSettings),onEvent:le}):S==="copilot"?nr(a.id,{prompt:q,projectRoot:r,resumeSessionId:N,model:a.model,timeoutMs:h,copilotPath:m.copilot?.path??T,onEvent:le}):pn(a.id,{prompt:q,projectRoot:r,maxTurns:d,maxBudgetUsd:l,allowedTools:$?["Read"]:x,claudePath:P,resumeSessionId:N,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:le});C.setActiveProcess(a.id,se);let X=await ne,xe=F.finalize(X.text),ue=xe.visibleText,he=O?Hn(ue):{visibleText:ue,draft:void 0,error:void 0},Pe=he.visibleText;for(let U of xe.orientations)C.broadcast({type:"orientation",jobId:a.id,orientation:U},a.id,a.sourceId);if(a.result=Pe,X.success){console.log(`${J} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${J} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(ee=>`${ee.tool} ${ee.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${J} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(ee=>`${ee.operation} ${ee.filePath}`).join(", ")}`),a.status="done";let U=Hr(ue),ae=Wr(ue);if(ae.length>0&&a.annotationIds&&a.annotationIds.length>0){let ee=new Set(a.annotationIds);ae.every(pt=>ee.has(pt.annotationId))||(ae=ae.map((pt,ut)=>({...pt,annotationId:a.annotationIds[ut%a.annotationIds.length]})))}let je=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(ee=>`${ee.tool} ${ee.file_path.split("/").pop()}`):X.toolsUsed,qe=C.getBufferedEvents(a.id),ze=qe?sd(qe.events,r):void 0,Re,He=Fr(ue),Se=Lr(ue);if(Se)if(!(a.memoryReview?.packets.some(de=>de.proposalId===Se.proposalId)||a.surfacedProposalIds?.includes(Se.proposalId)))Re={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{Re=await A.commitConversationalReview(Se)}catch(de){Re={status:"rejected",action:Se.action,proposalId:Se.proposalId,message:de instanceof Error?de.message:String(de)}}let lt=[...(X.fileEdits??[]).map(ee=>ee.file_path),...(X.editEvents??[]).flatMap(ee=>ee.filePath?[ee.filePath]:[])],G,ge=a.imprintContext?.pendingGroundingExplanationIds??[];if(he.draft?.decision==="none"&&z.recordNoop(he.draft.reason),a.threadId&&he.draft?.decision==="mutate"&&!Se&&!He)try{G=await z.capture(he.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await te.loadModel(),pendingGroundingExplanationIds:ge}),G&&await A.recordImprintEvidence({summary:G,threadId:a.threadId,jobId:a.id}).catch(ee=>console.warn(`${J} Canonical Imprint evidence linkage failed:`,ee))}catch(ee){console.warn(`${J} Continuous imprint update failed; the thread result remains available:`,ee instanceof Error?ee.message:String(ee))}else he.error&&console.warn(`${J} Ignored invalid imprint block: ${he.error}`);let Je=G?.transactionId;if(a.threadId&&G&&!G.grounding){let ee=await W.getThread(a.threadId),de=new Set(G.changes.map(ut=>ut.explanationId)),pt=ee?id(ee.messages,de):void 0;if(pt?.imprintSummary){let ut=pt.imprintSummary;await W.updateAssistantMessage(a.threadId,pt.jobId,{imprintSummary:{...ut,detail:G.detail,changes:G.changes,additionalObservationCount:(ut.additionalObservationCount??0)+1,coalescedTransactionIds:[...ut.coalescedTransactionIds??[],G.transactionId]}}),G=void 0}}let K=di({question:U,resolutions:ae,changedFiles:lt,decisionRequired:!!He,imprintTransactionId:Je,groundingRequired:!!G?.grounding}),me=ze?.flatMap(ee=>ee.kind==="orientation"?[ee.orientation]:[])??[];if(a.threadId){let ee=$?He?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Pe;await W.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:ee,resolutions:!$&&ae.length>0?ae:void 0,question:$?void 0:U??void 0,sessionId:X.sessionId,toolsUsed:$?void 0:je,editEvents:!$&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!$&&ze&&ze.length>0?ze:void 0,turn:{phase:"complete",orientation:me,result:K},result:K,memoryReviewCard:He??void 0,memoryReceipt:Re,imprintSummary:G,model:a.model,provider:S})}if(a.threadId&&!Se&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let ee=a.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await A.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:I??(Dn(a.feedback)||"[request unavailable]"),responseSummary:U??Pe,outcome:U?"question_asked":ae.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:ee,filePaths:[...(X.fileEdits??[]).map(de=>de.file_path),...(X.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>bi(de)?Kc(r,de):de),resolutions:ae.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(de=>de.id)})}catch(de){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}Re?.status==="committed"&&Re.decisionId&&S!=="copilot"&&await Bt({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Re.decisionId}`}),U&&(console.log(`${J} \u{1F4AC} Question detected: "${U.slice(0,120)}" \u2192 broadcasting to ${Q.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),C.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:U,annotationIds:a.annotationIds},a.id,a.sourceId));let fe=Vr(ue);fe.length>0&&(console.log(`${J} Novel pattern(s): ${fe.map(ee=>`${ee.category}/${ee.element}`).join(", ")}`),C.broadcast({type:"novel_patterns",jobId:a.id,patterns:fe,threadId:a.threadId},a.id,a.sourceId)),C.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ae.length>0?ae:void 0,responseText:Pe,threadId:a.threadId,annotationIds:a.annotationIds,result:K},a.id,a.sourceId),be.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${J} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await W.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:S}),C.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),be.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});Fe()});let wt=Gc(async(a,g)=>{if(dd(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let j=a.url||"/",I=j.split("?")[0],k=new URL(j,`http://127.0.0.1:${w}`),S=k.pathname,$=pd(a,k);if($&&$!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:$,projectName:eo(r)});return}if(a.headers.origin){if(!xi(a.headers.origin)){_(g,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if($!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:$,projectName:eo(r)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let O=k.searchParams.get("annotationId")?.trim()??"",N=k.searchParams.get("name")?.trim()??"",q=k.searchParams.get("kind"),J=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!O||O.length>128||!/^[a-z0-9_-]+$/i.test(O)){_(g,400,{error:"A valid annotationId is required."});return}if(q!=="svg"&&q!=="text"||q==="svg"&&J!=="image/svg+xml"||q==="text"&&J!=="text/plain"){_(g,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let ce=await ld(a,rd);if(ce.length===0){_(g,400,{error:"Attachment is empty."});return}let F=await we.stage({annotationId:O,name:N,mimeType:J,kind:q,data:ce});_(g,201,{attachment:{id:F.id,name:F.name,mimeType:F.mimeType,size:F.size,kind:F.kind}})}else if(a.method==="POST"&&S==="/draft-attachments/claim"){let O=await _e(a),N=Array.isArray(O.ids)?O.ids.filter(q=>typeof q=="string").slice(0,100):[];await we.claim(N),_(g,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await we.release([S.slice(19)]),_(g,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await ve(a,g);else if(a.method==="POST"&&S==="/capture/native"){if(!p){_(g,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let O=await _e(a),N=typeof O.pageUrl=="string"?O.pageUrl:"",q=O.clip&&typeof O.clip=="object"&&!Array.isArray(O.clip)?O.clip:null;if(!N||!q){_(g,400,{error:"pageUrl and clip are required."});return}let J=await br(p,{pageUrl:N,clip:{x:Number(q.x),y:Number(q.y),width:Number(q.width),height:Number(q.height)},scale:typeof O.scale=="number"?O.scale:1});g.writeHead(200,{"Content-Type":"image/webp","Content-Length":J.length,"Cache-Control":"no-store"}),g.end(J)}else if(a.method==="GET"&&S==="/events")Me(a,g);else if(a.method==="GET"&&S==="/status")await Ze(a,g,$);else if(a.method==="GET"&&S==="/ui-preferences")await it(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await ct(a,g);else if(a.method==="PATCH"&&S==="/config")await rt(a,g);else if(a.method==="POST"&&S==="/leases"){if(v!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}try{let O=await _e(a),N=typeof O.leaseId=="string"?O.leaseId.trim():"",q=typeof O.ownerPid=="number"&&Number.isInteger(O.ownerPid)&&O.ownerPid>0?O.ownerPid:void 0;if(!N||N.length>128){_(g,400,{error:"A valid leaseId is required."});return}V();let J=M.acquire(N,q);_(g,201,{ok:!0,lease:J,ttlMs:yi})}catch{_(g,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(v!=="detached"){_(g,409,{error:"Bridge leases are only available for detached bridges."});return}let O="";try{O=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!O){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let N=M.heartbeat(O);if(!N){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:N})}else{let N=M.release(O);_(g,N.found?200:404,{ok:N.found}),N.becameEmpty&&pe()}}else if(a.method==="POST"&&S==="/shutdown"){if(v!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:v});return}_(g,200,{ok:!0}),setTimeout(Y,100)}else if(a.method==="POST"&&S==="/restart"){if(v!=="detached"){_(g,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:v});return}_(g,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let O of Q)try{O.res.end()}catch{}wt.close(()=>{hi(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")_(g,200,{providers:m});else if(S.startsWith("/imprint/"))await oo(a,g,S);else if(S.startsWith("/memory/"))await cn(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await dt(a,g);else if(a.method==="POST"&&S==="/reply")await ot(a,g);else if(a.method==="POST"&&S==="/cancel")ro(a,g);else if(a.method==="POST"&&S==="/materialize")_(g,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(g,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let O=await te.loadRuns();_(g,200,O)}else if(a.method==="GET"&&S==="/projection/proposals"){let O=await te.loadModelProposals();_(g,200,O)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let O=S.slice(22,-15);await De(O,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let O=S.slice(22,-6);await Lt(O,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let O=S.slice(22,-8);await Ne(O,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await io(a,g);else if(a.method==="DELETE"&&S==="/model/component")await dn(a,g);else if(a.method==="PATCH"&&S==="/model/token")await ji(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Mi(a,g);else if(a.method==="POST"&&S==="/model/consolidate")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(g,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let O=await te.loadModel();_(g,200,{model:O})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let O=S.slice(6,S.length-7),N=parseInt(k.searchParams.get("afterSeq")??"-1",10),q=C.getBufferedEvents(O,isNaN(N)?-1:N);q?_(g,200,q):_(g,404,{error:"Unknown job"})}else if(a.method==="GET"&&I.startsWith("/files/"))await Ci(I.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let O=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),N=await W.listRecent(O);_(g,200,N)}else if(a.method==="GET"&&S.startsWith("/decision/")){let O=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(O))_(g,400,{error:"Invalid decision id"});else{let N=await W.getThread(O),q=[...N?.messages??[]].reverse().find(J=>J.annotationSnapshot);if(N&&q?.annotationSnapshot){let J=[...N.messages].reverse().find(ce=>ce.resolutions?.length);_(g,200,{decision:{id:N.id,createdAt:q.timestamp,url:q.annotationSnapshot.url,viewport:q.annotationSnapshot.viewport,color:q.annotationSnapshot.color,annotations:q.annotationSnapshot.annotations,resolutions:J?.resolutions??[]},authority:"thread_snapshot"})}else{let J=await ie.loadDecision(O);J?_(g,200,{decision:J,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let O=S.slice(8);await $i(O,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let O=S.slice(8);await Oi(O,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?Ai(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Ei(g):a.method==="GET"&&S==="/canvas/app.mjs"?await _i(g):_(g,404,{error:"Not found"})}catch(O){console.error("[Bridge] Request error:",O),_(g,500,{error:O instanceof Error?O.message:"Internal error"})}});async function cn(a,g,j){try{if(a.method==="GET"&&j==="/memory/status"){_(g,200,await A.status());return}if(a.method==="GET"&&j==="/memory/diagnostics"){_(g,200,await A.diagnostics());return}if(a.method==="GET"&&j==="/memory/model-view"){_(g,200,await A.getModelView());return}if(a.method==="GET"&&j==="/memory/imprint-view"){let I=await W.load(),k=[...new Set(Object.values(I.threads).flatMap(S=>an(S.messages)))];_(g,200,await A.getImprintView(k));return}if(a.method==="POST"&&j==="/memory/constraints"){let I=await _e(a),k=typeof I.reactComponent=="string"?I.reactComponent.trim():"",S=await A.getModelView(),$=k?S.entries.filter(O=>O.key===`components.${k}`||O.key.startsWith(`components.${k}.`)):[];_(g,200,{modelEntries:$});return}if(a.method==="POST"&&j==="/memory/conversation-action"){let I=await _e(a),k=typeof I.threadId=="string"?I.threadId:"",S=typeof I.proposalId=="string"?I.proposalId:"",$=String(I.action);if(!k||!S||!["accept","edit_and_accept","reject","defer"].includes($)){_(g,400,{error:"A valid thread, proposal, and review action are required."});return}let O=await W.getThread(k),N=O?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!O||!N){_(g,409,{error:"This decision review card is not available in the thread."});return}let q=await te.findModelProposalsByThread(k),J=(await Promise.all(q.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(xe=>A.findPendingProposalForLegacyDecision(xe)))).some(xe=>xe?.proposalId===S)})))).find(X=>X.matches)?.proposal,ce={proposalId:S,action:$,kind:N.kind,claim:$==="edit_and_accept"&&typeof I.claim=="string"?I.claim.trim():void 0,reason:$==="defer"?void 0:`The owner explicitly chose ${$.replaceAll("_"," ")} from the decision review card.`,taskContext:$==="defer"?"Deferred during in-thread decision review.":void 0,resurfaceWhen:$==="defer"?["different_action","owner_request"]:void 0};if(ce.action==="edit_and_accept"&&!ce.claim){_(g,400,{error:"Edited decision wording is required."});return}let F=await A.commitConversationalReview(ce),le=`memory-${Nt().slice(0,8)}`,se=$==="accept"?"> Accepted decision":$==="edit_and_accept"?"> Edited and accepted decision":$==="reject"?"> Rejected decision":"> Deferred decision";await W.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:le,replyToQuestion:se}),await W.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:le,responseText:"",memoryReceipt:F,provider:Jt(typeof I.provider=="string"?I.provider:void 0),model:typeof I.model=="string"?I.model:void 0}),F.status==="committed"&&J&&await te.dismissModelProposal(J.id);let ne=Jt(typeof I.provider=="string"?I.provider:void 0);F.status==="committed"&&F.decisionId&&ne!=="copilot"&&await Bt({provider:ne,model:typeof I.model=="string"?I.model:void 0,agentSettings:bt(I),threadId:k,reason:`Project accepted decision ${F.decisionId}`}),_(g,F.status==="committed"?200:409,{receipt:F});return}if(a.method==="POST"&&j==="/memory/analyze"){let I=await _e(a),k=await A.analyzeLegacy({projectKey:typeof I.projectKey=="string"?I.projectKey:void 0}),S=Object.fromEntries([...new Set(k.issues.map($=>$.code))].map($=>[$,k.issues.filter(O=>O.code===$).length]));_(g,200,{...k,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&j==="/memory/review"){let I=await _e(a),k=await A.review(Co(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&j==="/memory/context"){let I=await _e(a),k=await A.contextualize(Co(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&j==="/memory/initialize"){let I=await _e(a),k=await A.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:nt});_(g,201,{status:k.status,report:{source:k.report.source,imported:k.report.imported,unresolvedAcceptance:k.report.unresolvedAcceptance,deferredModelEntries:k.report.deferredModelEntries,proofCases:k.report.proofCases,schemaIssues:k.report.schemaIssues}});return}if(a.method==="POST"&&j==="/memory/plan"){let I=await _e(a),k=await A.planReview(_o(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,k.result.ok?200:422,k);return}if(a.method==="POST"&&j==="/memory/commit"){let I=await _e(a),k=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},S=await A.commitReview(_o(I.command),{transactionId:typeof k.transactionId=="string"?k.transactionId:"",committedAt:typeof k.committedAt=="string"?k.committedAt:""});_(g,200,{status:await A.status(),journal:S.report});return}if(a.method==="POST"&&j==="/memory/recover"){let I=await _e(a),k=await A.recover(I.confirm===!0);_(g,200,{status:await A.status(),journal:k.report});return}_(g,404,{error:"Memory endpoint not found."})}catch(I){let k=I instanceof Error?I.message:String(I),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(k),$=/required|invalid|unsupported|expected|must be|confirmation/i.test(k);if(S||$){_(g,S?409:400,{error:k});return}throw I}}async function oo(a,g,j){if(a.method==="GET"&&j==="/imprint/status"){let[I,k]=await Promise.all([z.store.load(),W.load()]),S=[...new Set(Object.values(k.threads).flatMap($=>an($.messages)))].filter($=>I.graph.explanations.some(O=>O.id===$&&O.state==="testing"));_(g,200,{state:"ready",head:I.graph.head,updatedAt:I.graph.updatedAt,explanationCount:I.graph.explanations.filter($=>$.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"&&j==="/imprint/action"){let I=await _e(a),k=typeof I.threadId=="string"?I.threadId:"",S=typeof I.transactionId=="string"?I.transactionId:"",$=String(I.action);if(!k||!S||!["confirm","reason_wrong","narrow","exception","edit","dont_learn","undo"].includes($)){_(g,400,{error:"A valid thread, imprint update, and action are required."});return}let N=await W.getThread(k),q=[...N?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),J=q?.imprintSummary;if(!N||!q||!J){_(g,409,{error:"This imprint summary is not available in the thread."});return}if(J.resolvedAction){_(g,409,{error:"This imprint summary has already been resolved."});return}let ce=`imprint-${Nt().slice(0,8)}`;await z.applyGroundingAction({summary:J,action:$,value:typeof I.value=="string"?I.value:void 0,threadId:k,jobId:ce}),await A.recordImprintEvidence({summary:J,action:$,threadId:k,jobId:ce}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let F=$t(q.result,!!q.question),le=q.turn?{...q.turn,result:$t(q.turn.result,!!q.question)}:void 0;await W.updateAssistantMessage(k,q.jobId,{imprintSummary:{...J,resolvedAction:$},...F?{result:F}:{},...le?{turn:le}:{}});let se={confirm:"> Confirmed imprint reasoning",reason_wrong:"> Result right, reasoning corrected",narrow:"> Narrowed imprint scope",exception:"> Marked an imprint exception",edit:"> Edited imprint wording",dont_learn:"> Removed this thread from the imprint",undo:"> Undid imprint update"};await W.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:ce,replyToQuestion:se[$]}),_(g,200,{ok:!0,action:$});return}_(g,404,{error:"Imprint endpoint not found."})}async function ve(a,g){let{screenshot:j,feedback:I,color:k,provider:S,model:$,reasoningEffort:O,serviceTier:N,sourceId:q,pastedImages:J,pageScreenshots:ce}=await $o(a),F;try{F=JSON.parse(I)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let le=F.annotations.flatMap(G=>(G.attachments??[]).map(ge=>({id:ge.id,annotationId:G.id}))),se;try{se=le.length>0?await we.promote(le):void 0}catch(G){_(g,409,{error:G instanceof Error?G.message:"Draft attachment unavailable."});return}let ne=Nt().slice(0,8),X={};if(ce.length>0)for(let G of ce){let ge=encodeURIComponent(G.pathname),Je=Ce(c,`screenshot-${ne}-${ge}.webp`);await Zn(Je,G.data),X[G.pathname]=Je}let xe=Ce(c,`screenshot-${ne}.webp`);await Zn(xe,j);let ue={};if(J.length>0)for(let G of J){let ge=Ce(c,`pasted-${ne}-${G.annotationId}-${G.index}.webp`);await Zn(ge,G.data),ue[G.annotationId]||(ue[G.annotationId]=[]),ue[G.annotationId].push(ge)}let he=F.annotations.map(G=>G.linkedSelector?G.pathname?`${G.pathname}:${G.linkedSelector}`:G.linkedSelector:null).filter(G=>!!G),Pe;if(he.length>0){let G=await W.findContinuationThread(he);G?(Pe=G.id,await W.addElementIdentifiers(Pe,he)):Pe=(await W.createThread(ne,he)).id}else Pe=(await W.createThread(ne,[])).id;let U=F.annotations.map(G=>G.id),ae=Object.keys(X).length>0,je=await Jr(A,F,he,G=>console.warn(`[\u22B9 ${w}:${ne}] Contextual memory unavailable; continuing without it:`,G instanceof Error?G.message:String(G))),qe=await z.contextualize({text:Dn(F),subjectHints:[...he,...F.annotations.flatMap(G=>[G.pathname,G.elements?.[0]?.reactComponent].filter(ge=>!!ge))],pendingGroundingExplanationIds:an((await W.getThread(Pe))?.messages??[])}).catch(G=>{console.warn(`[\u22B9 ${w}:${ne}] Imprint context unavailable; continuing without it:`,G instanceof Error?G.message:String(G))}),ze={id:ne,status:"queued",screenshotPath:xe,feedback:F,createdAt:Date.now(),color:k,threadId:Pe,annotationIds:U,provider:Jt(S),model:$||void 0,agentSettings:bt({reasoningEffort:O,serviceTier:N}),...Object.keys(ue).length>0?{imagePaths:ue}:{},...se&&Object.keys(se).length>0?{attachmentFiles:se}:{},sourceId:q||void 0,...ae?{screenshotPaths:X}:{},...je?{memoryReview:je}:{},...qe?{imprintContext:qe}:{}},Re=new Set(F.annotations.map(G=>G.pathname).filter(Boolean)),He;if(Re.size>1){let G=new Map;for(let ge of F.annotations){let Je=ge.pathname||"(unknown)";G.has(Je)||G.set(Je,[]),G.get(Je).push(ge.instruction||wi({...F,annotations:[ge]}))}He=[...G.entries()].map(([ge,Je])=>`\`${ge}\`
|
|
200
|
-
${
|
|
201
|
+
${gr}`;let q=Qd(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: ${P})${a.threadId?` (thread: ${a.threadId})`:""}${F?` (resuming: ${F.slice(0,8)})`:""}`);let U=new Gn(a.id),ue=(oe,me)=>{if(oe.type==="delta"&&"text"in oe){let Ee=U.push(oe.text);Ee.visibleText&&(E.accumulateText(me,"response",Ee.visibleText),E.broadcast({...oe,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 oe.type==="thinking"&&"text"in oe&&E.accumulateText(me,"thinking",oe.text);E.broadcast(oe,me,a.sourceId)},{process:de,result:ne}=P==="codex"?xn(a.id,{prompt:z,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:F,model:a.model,sandboxMode:C?"read-only":void 0,configOverrides:In(a.agentSettings),onEvent:ue}):P==="copilot"?Ti(a.id,{prompt:z,projectRoot:i,resumeSessionId:F,model:a.model,timeoutMs:y,copilotPath:u.copilot?.path??T,onEvent:ue}):wn(a.id,{prompt:z,projectRoot:i,maxTurns:d,maxBudgetUsd:p,allowedTools:C?["Read"]:w,claudePath:x,resumeSessionId:F,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:y,onEvent:ue});E.setActiveProcess(a.id,de);let X=await ne,Se=[...(X.fileEdits??[]).map(oe=>oe.file_path),...(X.editEvents??[]).flatMap(oe=>oe.filePath?[oe.filePath]:[])],be=Yo(X.text,a.id),Ae=U.finalize(X.text),he=be.visibleText,ee=wr(he),ge=$?Zn(he,{context:a.imprintContext,requestText:I??Lt(a.feedback),applicationOccurred:Se.length>0||ee.some(oe=>oe.status==="resolved")}):{visibleText:he,draft:void 0,error:void 0},Je=ge.visibleText,Pe=$?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 oe of Ae.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:oe},a.id,a.sourceId);if(a.result=Je,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 oe=vr(he),me=ee;if(me.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);me.every(yt=>re.has(yt.annotationId))||(me=me.map((yt,vt)=>({...yt,annotationId:a.annotationIds[vt%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=zd(Xe?.events??[],i,be.segments),Le,Y=ur(he),pe=pr(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=br(he,Se.length),G,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}:Pe={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let vo=ge.draft?.decision==="mutate"||ge.draft?.decision==="apply"?ge.draft:void 0;if(a.threadId&&vo&&!pe&&!Y)try{G=await Z.capture(vo,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:Ie,applicationOccurred:Se.length>0||me.some(re=>re.status==="resolved")}),G?(Pe={state:"mutated"},await D.recordImprintEvidence({summary:G,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${q} Canonical Imprint evidence linkage failed:`,re))):Pe={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Pe={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 vo&&(Pe={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});ge.error&&console.warn(`${q} Ignored invalid imprint block: ${ge.error}`),(Pe.state==="missing"||Pe.state==="invalid")&&Z.recordAssessmentFailure(Pe.state);let Io=G?.transactionId;if(a.threadId&&G&&!G.grounding){let re=await O.getThread(a.threadId),ce=new Set(G.changes.map(vt=>vt.explanationId)),yt=re?Ud(re.messages,ce):void 0;if(yt?.imprintSummary){let vt=yt.imprintSummary;await O.updateAssistantMessage(a.threadId,yt.jobId,{imprintSummary:{...vt,detail:G.detail,changes:G.changes,additionalObservationCount:(vt.additionalObservationCount??0)+1,coalescedTransactionIds:[...vt.coalescedTransactionIds??[],G.transactionId]}}),G=void 0}}let wo=oi({question:oe,resolutions:me,changedFiles:Se,decisionRequired:!!Y,imprintTransactionId:Io,groundingRequired:!!G?.grounding}),fs=Ue?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],jt=a.lifecycle?fn(a.lifecycle,Io?[Io]:[],Pe):void 0;if(a.threadId){let re=C?Y?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Je;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:oe??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:fs,result:wo},result:wo,memoryReviewCard:Y??void 0,memoryReceipt:Le,imprintSummary:G,imprintRecognition:ye,modelDetails:Me.length>0?Me:void 0,model:a.model,provider:P,...jt?{lifecycle:jt}:{}})}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??(Lt(a.feedback)||"[request unavailable]"),responseSummary:oe??Je,outcome:oe?"question_asked":me.some(ce=>ce.status==="resolved")?"completed":"no_change",execution:{provider:P,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=>Xr(ce)?Cd(i,ce):ce),resolutions:me.map(ce=>({status:ce.status,summary:ce.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(ce=>ce.id),submissionIds:jt?.submissionIds,outcomeId:jt?.outcomeId,imprintEvidenceIds:jt?.imprintEvidenceIds,imprintAssessment:jt?.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&&P!=="copilot"&&await ht({provider:P,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${Le.decisionId}`}),oe&&(console.log(`${q} \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)),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:Je,threadId:a.threadId,annotationIds:a.annotationIds,result:wo},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:P,...a.lifecycle?{lifecycle:fn(a.lifecycle)}:{}}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:P,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});ct()});let Rt=Md(async(a,v)=>{if(Hd(a,v),a.method==="OPTIONS"){v.writeHead(204),v.end();return}let M=a.url||"/",I=M.split("?")[0],A=new URL(M,`http://127.0.0.1:${h}`),P=A.pathname,C=Kd(a,A);if(C&&C!==r){_(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:po(i)});return}if(a.headers.origin){if(!Yr(a.headers.origin)){_(v,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if(C!==r){_(v,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:C,projectName:po(i)});return}}try{if(a.method==="POST"&&P==="/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($)){_(v,400,{error:"A valid annotationId is required."});return}if(z!=="svg"&&z!=="text"||z==="svg"&&q!=="image/svg+xml"||z==="text"&&q!=="text/plain"){_(v,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let le=await Vd(a,qd);if(le.length===0){_(v,400,{error:"Attachment is empty."});return}let U=await B.stage({annotationId:$,name:F,mimeType:q,kind:z,data:le});_(v,201,{attachment:{id:U.id,name:U.name,mimeType:U.mimeType,size:U.size,kind:U.kind}})}else if(a.method==="POST"&&P==="/draft-attachments/claim"){let $=await Oe(a),F=Array.isArray($.ids)?$.ids.filter(z=>typeof z=="string").slice(0,100):[];await B.claim(F),_(v,200,{ok:!0})}else if(a.method==="DELETE"&&P.startsWith("/draft-attachments/"))await B.release([P.slice(19)]),_(v,200,{ok:!0});else if(a.method==="POST"&&P==="/send")await lt(a,v);else if(a.method==="POST"&&P==="/capture/native"){if(!f){_(v,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){_(v,400,{error:"pageUrl and clip are required."});return}let q=await Ui(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});v.writeHead(200,{"Content-Type":"image/webp","Content-Length":q.length,"Cache-Control":"no-store"}),v.end(q)}else if(a.method==="GET"&&P==="/events")tt(a,v);else if(a.method==="GET"&&P==="/status")await pt(a,v,C);else if(a.method==="GET"&&P==="/ui-preferences")await ft(v);else if(a.method==="PATCH"&&P==="/ui-preferences")await ho(a,v);else if(a.method==="PATCH"&&P==="/config")await ut(a,v);else if(a.method==="POST"&&P==="/leases"){if(l!=="detached"){_(v,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){_(v,400,{error:"A valid leaseId is required."});return}Q();let q=N.acquire(F,z);_(v,201,{ok:!0,lease:q,ttlMs:Hr})}catch{_(v,400,{error:"Invalid lease request."})}}else if(P.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){_(v,409,{error:"Bridge leases are only available for detached bridges."});return}let $="";try{$=decodeURIComponent(P.slice(8))}catch{_(v,400,{error:"Invalid lease id."});return}if(!$){_(v,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let F=N.heartbeat($);if(!F){_(v,404,{error:"Lease not found."});return}_(v,200,{ok:!0,lease:F})}else{let F=N.release($);_(v,F.found?200:404,{ok:F.found}),F.becameEmpty&&H()}}else if(a.method==="POST"&&P==="/shutdown"){if(l!=="detached"){_(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(v,200,{ok:!0}),setTimeout(b,100)}else if(a.method==="POST"&&P==="/restart"){if(l!=="detached"){_(v,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(v,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let $ of L)try{$.res.end()}catch{}Rt.close(()=>{Gr(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&P==="/capabilities")_(v,200,{providers:u});else if(P.startsWith("/imprint/"))await xe(a,v,P);else if(P.startsWith("/memory/"))await fo(a,v,P);else if(a.method==="POST"&&P==="/mcp/install")await yo(a,v);else if(a.method==="POST"&&P==="/reply")await _e(a,v);else if(a.method==="POST"&&P==="/cancel")go(a,v);else if(a.method==="POST"&&P==="/materialize")_(v,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&P==="/materialization-runs")_(v,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&P==="/projection-runs"){let $=await se.loadRuns();_(v,200,$)}else if(a.method==="GET"&&P==="/projection/proposals"){let $=await se.loadModelProposals();_(v,200,$)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply-selected")){let $=P.slice(22,-15);await Be($,a,v)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/apply")){let $=P.slice(22,-6);await Ne($,v)}else if(a.method==="POST"&&P.startsWith("/projection/proposals/")&&P.endsWith("/dismiss")){let $=P.slice(22,-8);await mt($,a,v)}else if(P.startsWith("/model/proposals/"))_(v,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&P==="/model/component")await vn(a,v);else if(a.method==="DELETE"&&P==="/model/component")await is(a,v);else if(a.method==="PATCH"&&P==="/model/token")await rs(a,v);else if(a.method==="DELETE"&&P==="/model/token")await ss(a,v);else if(a.method==="POST"&&P==="/model/consolidate")_(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&P==="/model/synthesize")_(v,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&P==="/model"){let $=await se.loadModel();_(v,200,{model:$})}else if(a.method==="GET"&&P.startsWith("/jobs/")&&P.endsWith("/events")){let $=P.slice(6,P.length-7),F=parseInt(A.searchParams.get("afterSeq")??"-1",10),z=E.getBufferedEvents($,isNaN(F)?-1:F);z?_(v,200,z):_(v,404,{error:"Unknown job"})}else if(a.method==="GET"&&I.startsWith("/files/"))await ls(I.slice(7),v);else if(a.method==="GET"&&P==="/threads/recent"){let $=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),F=await O.listRecent($);_(v,200,F)}else if(a.method==="GET"&&P.startsWith("/decision/")){let $=P.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test($))_(v,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);_(v,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?_(v,200,{decision:q,authority:"legacy_archive"}):_(v,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&P.startsWith("/thread/")){let $=P.slice(8);await ps($,v)}else if(a.method==="DELETE"&&P.startsWith("/thread/")){let $=P.slice(8);await us($,v)}else a.method==="GET"&&(P==="/canvas"||P==="/canvas/")?as(a,v):a.method==="GET"&&P==="/canvas/manifest"?await cs(v):a.method==="GET"&&P==="/canvas/app.mjs"?await ds(v):_(v,404,{error:"Not found"})}catch($){console.error("[Bridge] Request error:",$),_(v,500,{error:$ instanceof Error?$.message:"Internal error"})}});async function fo(a,v,M){try{if(a.method==="GET"&&M==="/memory/status"){_(v,200,await D.status());return}if(a.method==="GET"&&M==="/memory/diagnostics"){_(v,200,await D.diagnostics());return}if(a.method==="GET"&&M==="/memory/model-view"){_(v,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(P=>yn(P.messages)))];_(v,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():"",P=await D.getModelView(),C=A?P.entries.filter($=>$.key===`components.${A}`||$.key.startsWith(`components.${A}.`)):[];_(v,200,{modelEntries:C});return}if(a.method==="POST"&&M==="/memory/conversation-action"){let I=await Oe(a),A=typeof I.threadId=="string"?I.threadId:"",P=typeof I.proposalId=="string"?I.proposalId:"",C=String(I.action);if(!A||!P||!["accept","edit_and_accept","reject","defer"].includes(C)){_(v,400,{error:"A valid thread, proposal, and review action are required."});return}let $=await O.getThread(A),F=$?.messages.find(X=>X.memoryReviewCard?.proposalId===P)?.memoryReviewCard;if(!$||!F){_(v,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===P)})))).find(X=>X.matches)?.proposal,le={proposalId:P,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){_(v,400,{error:"Edited decision wording is required."});return}let U=await D.commitConversationalReview(le),ue=`memory-${at().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:Ht(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=Ht(typeof I.provider=="string"?I.provider:void 0);U.status==="committed"&&U.decisionId&&ne!=="copilot"&&await ht({provider:ne,model:typeof I.model=="string"?I.model:void 0,agentSettings:At(I),threadId:A,reason:`Project accepted decision ${U.decisionId}`}),_(v,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}),P=Object.fromEntries([...new Set(A.issues.map(C=>C.code))].map(C=>[C,A.issues.filter($=>$.code===C).length]));_(v,200,{...A,issues:void 0,issueCounts:P});return}if(a.method==="POST"&&M==="/memory/review"){let I=await Oe(a),A=await D.review(Vo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(v,200,A);return}if(a.method==="POST"&&M==="/memory/context"){let I=await Oe(a),A=await D.contextualize(Vo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(v,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:st});_(v,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&M==="/memory/plan"){let I=await Oe(a),A=await D.planReview(Ho(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(v,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:{},P=await D.commitReview(Ho(I.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(v,200,{status:await D.status(),journal:P.report});return}if(a.method==="POST"&&M==="/memory/recover"){let I=await Oe(a),A=await D.recover(I.confirm===!0);_(v,200,{status:await D.status(),journal:A.report});return}_(v,404,{error:"Memory endpoint not found."})}catch(I){let A=I instanceof Error?I.message:String(I),P=/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(P||C){_(v,P?409:400,{error:A});return}throw I}}async function xe(a,v,M){if(a.method==="GET"&&M==="/imprint/status"){let[I,A]=await Promise.all([Z.store.load(),O.load()]),P=[...new Set(Object.values(A.threads).flatMap(C=>yn(C.messages)))].filter(C=>I.graph.explanations.some($=>$.id===C&&$.state==="testing"));_(v,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:P.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:"",P=typeof I.transactionId=="string"?I.transactionId:"",C=String(I.action);if(!A||!P||!["yes","this_time","no"].includes(C)){_(v,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===P),q=z?.imprintSummary;if(!F||!z||!q){_(v,409,{error:"This imprint summary is not available in the thread."});return}if(q.resolvedAction){_(v,409,{error:"This imprint summary has already been resolved."});return}let le=`imprint-${at().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=zt(z.result,!!z.question),ue=z.turn?{...z.turn,result:zt(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=oi({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})}_(v,200,{ok:!0,action:C});return}_(v,404,{error:"Imprint endpoint not found."})}async function lt(a,v){let{screenshot:M,feedback:I,color:A,provider:P,model:C,reasoningEffort:$,serviceTier:F,sourceId:z,pastedImages:q,pageScreenshots:le}=await Ko(a),U;try{U=JSON.parse(I)}catch{_(v,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 B.promote(ue):void 0}catch(Y){_(v,409,{error:Y instanceof Error?Y.message:"Draft attachment unavailable."});return}let ne=at().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 lo(Me,Y.data),X[Y.pathname]=Me}let Se=De(c,`screenshot-${ne}.webp`);await lo(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 lo(pe,Y.data),be[Y.annotationId]||(be[Y.annotationId]=[]),be[Y.annotationId].push(pe)}let Ae=Nr(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-${at()}`,Ae)).id}else he=(await O.createThread(`thread-${at()}`,[])).id;let ee=U.annotations.map(Y=>Y.id),ge=Object.keys(X).length>0,Je=await dr(D,U,Ae,Y=>console.warn(`[\u22B9 ${h}:${ne}] Contextual memory unavailable; continuing without it:`,Y instanceof Error?Y.message:String(Y))),Pe=await Z.contextualize({text:Lt(U),subjectHints:[...Ae,...U.annotations.flatMap(Y=>[Y.pathname,Y.elements?.[0]?.reactComponent].filter(pe=>!!pe))],pendingGroundingExplanationIds:yn((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))}),oe=ri({jobId:ne,threadId:he,artifactIds:Br(U,ne)}),me={id:ne,status:"queued",screenshotPath:Se,feedback:U,createdAt:Date.now(),color:A,threadId:he,annotationIds:ee,provider:Ht(P),model:C||void 0,agentSettings:At({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}:{},...Je?{memoryReview:Je}:{},...Pe?{imprintContext:Pe}:{},lifecycle:oe},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||Kr({...U,annotations:[pe]}))}Xe=[...Y.entries()].map(([pe,Me])=>`\`${pe}\`
|
|
202
|
+
${Me.map(G=>`- ${G}`).join(`
|
|
201
203
|
`)}`).join(`
|
|
202
|
-
`)}else
|
|
203
|
-
`):
|
|
204
|
-
`)),
|
|
204
|
+
`)}else Xe=Kr(U);let Ue=dn(U,Object.keys(be).length>0?be:void 0,de);await O.appendMessage(he,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:Se,...ge?{screenshotPaths:X}:{},...Object.keys(be).length>0?{imagePaths:be}:{},...de&&Object.keys(de).length>0?{attachmentFiles:de}:{},annotationIds:ee,annotationSnapshot:{url:U.url,viewport:U.viewport,annotations:U.annotations,color:A||void 0},feedbackSummary:Xe,feedbackContext:Ue||void 0,...Je?{memoryReview:Je}:{},...Pe?{imprintContext:Pe}:{},lifecycle:oe});let Le=E.enqueue(me);_(v,200,{jobId:ne,position:Le,threadId:he})}async function _e(a,v){let M=a.headers["content-type"]||"",I,A,P,C,$,F,z,q,le=[];if(M.includes("multipart/form-data")){let G=await Ko(a),ye=G.feedback?JSON.parse(G.feedback):{};I=ye.threadId,A=ye.reply,P=ye.color,C=ye.provider,$=ye.model,F=At(ye),z=ye.sourceId||G.sourceId,q=typeof ye.memoryReviewProposalId=="string"?ye.memoryReviewProposalId:void 0;for(let Ie of G.pastedImages)le.push(Ie.data)}else{let G=[];for await(let Fe of a)G.push(typeof Fe=="string"?Buffer.from(Fe):Fe);let ye=Buffer.concat(G).toString("utf-8"),Ie;try{Ie=JSON.parse(ye)}catch{_(v,400,{error:"Invalid JSON"});return}I=Ie.threadId,A=Ie.reply,P=Ie.color,C=Ie.provider,$=Ie.model,F=At(Ie),z=Ie.sourceId,q=Ie.memoryReviewProposalId}if(!I||!A){_(v,400,{error:"Missing threadId or reply"});return}let U=await O.getThread(I);if(!U){_(v,404,{error:"Thread not found"});return}let ue;if(q){let G=await se.findModelProposalsByThread(I);if(ue=(await Promise.all(G.flatMap(Ie=>Ie.authorityStatus==="accepted"?[]:Ie.decisionIds.map(async Fe=>({modelProposalId:Ie.id,underlying:await D.findPendingProposalForLegacyDecision(Fe)}))))).filter(Ie=>!!Ie.underlying).find(Ie=>Ie.underlying.proposalId===q),!ue){_(v,409,{error:"The requested memory decision is not pending in this thread."});return}}let de="";{let G=await O.getThreadHistory(I);for(let ye=G.length-1;ye>=0;ye--)if(G[ye].screenshotPath){de=G[ye].screenshotPath;break}}let ne=await gt(I);if(!de&&!ne){_(v,400,{error:"No screenshot available"});return}let X=E.hasActiveThread(I),Se=X?E.getQueuedThreadJob(I,G=>G._replyText!==void 0||G._replyPrompt!==void 0):null,be=Se?.id??at().slice(0,8),Ae=ri({jobId:be,threadId:I}),he=[],ee=`${be}-${Date.now()}`;for(let G=0;G<le.length;G++){let ye=De(c,`reply-${ee}-${G}.webp`);await lo(ye,le[G]),he.push(ye)}await O.appendMessage(I,{role:"human",timestamp:Date.now(),jobId:be,replyToQuestion:A,screenshotPath:de,...X?{queued:!0}:{},...he.length>0?{replyImagePaths:he}:{},lifecycle:{...Ae,artifactIds:he.map((G,ye)=>`reply-image:${be}:${ye}`)}});let ge=await O.getThreadHistory(I),Je=[...ge].reverse().find(G=>G.memoryReview)?.memoryReview,Pe=await Z.contextualize({text:A,subjectHints:U.elementIdentifiers,pendingGroundingExplanationIds:yn(ge)}).catch(G=>{console.warn(`[\u22B9 ${h}:${be}] Imprint context unavailable for reply; continuing without it:`,G instanceof Error?G.message:String(G))}),oe=new Set(ge.flatMap(G=>G.memoryReceipt?.status==="committed"?[G.memoryReceipt.proposalId]:[])),me=[...ge].reverse().find(G=>G.memoryReviewCard&&!oe.has(G.memoryReviewCard.proposalId))?.memoryReviewCard,Ee=[];for(let G of ge)if(G.annotationIds)for(let ye of G.annotationIds)Ee.includes(ye)||Ee.push(ye);let Xe=Ht(C),Ue=ue,Le=Ue?[Ue.underlying.proposalId]:me?[me.proposalId]:[],Y=Ir(de,ge,Xe,he.length>0?he:void 0);if(Ue?Y+=["","## Decision review card",`Privately review proposal ${Ue.underlying.proposalId}: ${Ue.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(`
|
|
205
|
+
`):me&&(Y+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(me)}`,"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(`
|
|
206
|
+
`)),Se){let G=Se,Ie=[...G._replyTexts??(G._replyText?[G._replyText]:[]),A],Fe=[...G._replyImagePaths??[],...he];G._replyTexts=Ie,G._replyText=Vr(Ie),G._replyImagePaths=Fe.length>0?Fe:void 0,G._replyPrompt=Y,G.annotationIds=Ee.length>0?Ee:G.annotationIds,G.agentSettings=F??G.agentSettings,G.memoryReview=Je??G.memoryReview,G.imprintContext=Pe??G.imprintContext,G.surfacedProposalIds=[...new Set([...G.surfacedProposalIds??[],...Le])],G.lifecycle={...G.lifecycle??Ae,submissionIds:[...new Set([...G.lifecycle?.submissionIds??[],...Ae.submissionIds])],artifactIds:[...new Set([...G.lifecycle?.artifactIds??[],...Ae.artifactIds])]},_(v,200,{jobId:be,position:1,threadId:I,bundled:!0});return}let pe={id:be,status:"queued",screenshotPath:de,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:P,threadId:I,annotationIds:Ee.length>0?Ee:void 0,provider:Xe,model:$||void 0,agentSettings:F,sourceId:z||void 0,...Je?{memoryReview:Je}:{},...Pe?{imprintContext:Pe}:{},...Le.length?{surfacedProposalIds:Le}:{},lifecycle:Ae};ne&&(pe.kind=ne),pe._replyPrompt=Y,pe._replyTexts=[A],pe._replyText=Vr([A]),he.length>0&&(pe._replyImagePaths=he);let Me=X?E.enqueueNext(pe):E.enqueue(pe);_(v,200,{jobId:be,position:Me,threadId:I})}function tt(a,v){v.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),v.write(`event: connected
|
|
205
207
|
data: {"status":"connected"}
|
|
206
208
|
|
|
207
|
-
`);let I=new URL(a.url||"/",`http://127.0.0.1:${w}`).searchParams.get("sourceId")||void 0,k={id:Nt().slice(0,8),res:g,sourceId:I};Q.add(k),a.on("close",()=>{Q.delete(k)})}async function Ze(a,g,j){s??=si(a.headers),Fe();let I=[...C.allActive,...f.allActive.map(U=>({id:U.id,status:U.status,threadId:U.threadId,annotationIds:U.annotationIds??[],color:"#000000",kind:"project_model",standalone:U.standalone}))],[k,S,$,O,N]=await Promise.allSettled([te.loadRuns(),te.loadModelProposals(),A.status(),z.store.load(),W.load()]),q=[],J=U=>U.reason instanceof Error?U.reason.message:String(U.reason);k.status==="rejected"&&q.push({subsystem:"projection",message:J(k)}),S.status==="rejected"&&q.push({subsystem:"projection",message:J(S)}),$.status==="rejected"?q.push({subsystem:"memory",message:J($)}):$.value.state==="degraded"&&q.push({subsystem:"memory",message:$.value.error??"Product memory is degraded."}),O.status==="rejected"&&q.push({subsystem:"imprint",message:J(O)}),N.status==="rejected"&&q.push({subsystem:"threads",message:J(N)});let ce=k.status==="fulfilled"?k.value.runs:[],F=S.status==="fulfilled"?S.value.proposals:[],le=ai(ce,F),se=le.actionableProposals.map(U=>({id:U.id,status:U.status,title:U.title,summary:U.summary,decisionIds:U.decisionIds,threadId:U.threadId,runId:U.runId,presentationJobId:U.presentationJobId,authorityStatus:U.authorityStatus,underlyingProposalId:U.underlyingProposalId,createdAt:U.createdAt,updatedAt:U.updatedAt,appliedAt:U.appliedAt,dismissedAt:U.dismissedAt,error:U.error})),ne=$.status==="fulfilled"?$.value:{initialized:!1,state:"degraded",error:J($)},X=N.status==="fulfilled"?[...new Set(Object.values(N.value.threads).flatMap(U=>an(U.messages)))]:[],xe=O.status==="fulfilled"?X.filter(U=>O.value.graph.explanations.some(ae=>ae.id===U&&ae.state==="testing")):[],ue=O.status==="fulfilled"?{state:"ready",head:O.value.graph.head,updatedAt:O.value.graph.updatedAt,explanationCount:O.value.graph.explanations.filter(U=>U.state!=="retired").length,concreteCount:O.value.graph.concrete.length,relationCount:O.value.graph.relations.length,pendingGroundingCount:xe.length,recoveredTransactions:O.value.recoveredTransactions,admission:z.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J(O),pendingGroundingCount:xe.length,admission:z.diagnostics(),admissionWindowStartedAt:e},he=q.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",Pe=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:Pe,serverStartedAt:e,health:{state:he,issues:q},version:nt,restartMode:v,projectId:i,projectName:eo(r),projectRoot:r,requestProjectId:j,projectIdVerified:j===i,devOrigin:s,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.map(U=>({id:U.id,status:U.status,threadId:U.threadId,annotationIds:U.annotationIds,color:U.color,kind:U.kind,standalone:"standalone"in U?U.standalone:void 0})),queueDepth:C.depth+f.depth,projectionQueueDepth:f.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:H},projection:{state:k.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:f.active?{id:f.active.id,status:f.active.status,threadId:f.active.threadId,annotationIds:f.active.annotationIds??[],provider:f.active.provider,model:f.active.model}:null,queueDepth:f.depth,recentRuns:le.recentRuns,recentAppliedRuns:le.recentAppliedRuns,actionableProposalCounts:le.actionableProposalCounts,actionableProposals:se},memory:ne,imprint:ue,recentJobsRetentionMs:Oe,recentJobs:be})}async function rt(a,g){let j=await new Promise(I=>{let k="";a.on("data",S=>{k+=S.toString()}),a.on("end",()=>I(k))});try{let I=JSON.parse(j);typeof I.devOrigin=="string"&&(s=I.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function it(a){let g=await re.load();_(a,200,{ok:!0,...g})}async function ct(a,g){let j=await _e(a);if(!mi(j.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let I=await re.setTheme(j.theme);_(g,200,{ok:!0,exists:!0,preferences:I})}async function ro(a,g){let I=new URL(a.url||"/",`http://127.0.0.1:${w}`).searchParams.get("jobId"),k=I?C.allActive.filter(J=>J.id===I):C.allActive,S=I?f.allActive.filter(J=>J.id===I):f.allActive,$=[...k.map(J=>J.threadId),...S.map(J=>J.threadId)].filter(Boolean),O=I?C.cancelJob(I):C.cancelActive(),N=I?f.cancelJob(I):f.cancelActive(),q=!!(O||N);for(let J of $)await W.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:I||N?.id||"",cancelled:!0});_(g,200,{cancelled:q})}async function Bt(a){let g=Nt().slice(0,8),j=a.threadId,I=!j;j||(j=(await W.createThread(g,[])).id,at.set(j,"project_model")),I&&await W.appendMessage(j,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await W.appendMessage(j,{role:"assistant",timestamp:Date.now(),jobId:g,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let k={id:g,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:j,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:I},S=f.enqueue(k);return{jobId:g,position:S,threadId:j}}async function Lt(a,g){let j=decodeURIComponent(a),I=await te.findModelProposal(j);if(!I){_(g,404,{error:"Model proposal not found"});return}_(g,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:I})}async function De(a,g,j){let I=decodeURIComponent(a),k=[];for await(let F of g)k.push(typeof F=="string"?Buffer.from(F):F);let S;try{S=JSON.parse(Buffer.concat(k).toString("utf-8"))}catch{_(j,400,{error:"Invalid JSON"});return}let $=(S.changes??[]).flatMap(F=>{if(!Array.isArray(F.path)||F.path.length===0)return[];let le=F.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(le.length!==F.path.length)return[];let se=Array.isArray(F.decisionIds)?F.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:le,value:F.value,remove:F.remove===!0,decisionIds:se}]});if($.length===0){_(j,400,{error:"No selected model changes"});return}let O=(S.changeSummaries??[]).flatMap(F=>{if(!F||typeof F!="object")return[];let le=Array.isArray(F.path)?F.path.filter(se=>typeof se=="string"||typeof se=="number"):void 0;return Array.isArray(F.path)&&le?.length!==F.path.length?[]:[{group:typeof F.group=="string"?F.group:void 0,label:typeof F.label=="string"?F.label:void 0,detail:typeof F.detail=="string"?F.detail:void 0,path:le,value:F.value,currentValue:F.currentValue}]}),N=await te.findModelProposal(I);if(!N){_(j,404,{error:"Model proposal not found"});return}if(N.authorityStatus!=="accepted"){_(j,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(N.status!=="pending"){_(j,409,{error:`Model proposal is already ${N.status}.`});return}let q=N.decisionIds.map(F=>{let le=N.changes?.filter(X=>X.decisionIds.includes(F)).length??0,se=$.filter(X=>X.decisionIds?.includes(F)).length,ne=se===0?"unprojected":le>se?"partially_projected":"projected";return{decisionId:F,status:ne}}),J=await A.applyModelProjection({runId:N.runId??N.id,presentationJobId:N.presentationJobId,decisionIds:N.decisionIds,changes:$.map(F=>({path:F.path,value:F.value,decisionIds:F.decisionIds})),coverage:q}),ce=await te.applySelectedModelProposal(I,$,O);if(!ce){_(j,404,{error:"Model proposal not found"});return}if(ce.threadId){let F=Jt(S.provider),le=typeof S.model=="string"&&S.model?S.model:void 0;await W.appendMessage(ce.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${ce.id}`,responseText:"",provider:F,model:le})}_(j,200,{proposal:ce,projection:J})}async function Ne(a,g,j){let I=decodeURIComponent(a),{provider:k,model:S}=await st(g),$=await te.dismissModelProposal(I);if(!$){_(j,404,{error:"Model proposal not found"});return}$.threadId&&await W.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${$.id}`,responseText:"",provider:k,model:S}),_(j,200,{proposal:$})}async function st(a){try{let g=[];for await(let I of a)g.push(typeof I=="string"?Buffer.from(I):I);if(g.length===0)return{};let j=JSON.parse(Buffer.concat(g).toString());return{provider:Jt(typeof j.provider=="string"?j.provider:void 0),model:typeof j.model=="string"&&j.model?j.model:void 0,agentSettings:bt(j)}}catch{return{}}}async function It(a){let g=at.get(a);if(g)return g;let k=(await W.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize rules"))return at.set(a,"synthesize"),"synthesize";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return at.set(a,"project_model"),"project_model"}async function dt(a,g){let j=[];for await(let N of a)j.push(typeof N=="string"?Buffer.from(N):N);let I;if(j.length>0)try{I=JSON.parse(Buffer.concat(j).toString("utf-8")).serverUrl}catch{}let k=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&k.push(await vr(I)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&k.push(await wr(I)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&k.push(await Ir(I,m.copilot.path??T));let[S,$,O]=await Promise.all([vo(r),wo(r),Io(r,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=$),m.copilot&&(m.copilot.mcp=O),_(g,200,{results:k,capabilities:{providers:m}})}async function io(a,g){let j=[];for await(let S of a)j.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let k=await A.recordDirectModelMutation({key:`components.${I.name}`,value:{description:""},claim:`${I.name} is an explicitly governed component in the product model.`});await te.applyCanonicalEntries(await A.getCanonicalModelEntries()),_(g,200,{added:!0,alreadyExists:!1,...k})}async function dn(a,g){let j=[];for await(let S of a)j.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(g,400,{error:"Missing or invalid name"});return}let k=await A.recordDirectModelMutation({key:`components.${I.name}`,value:null,claim:`${I.name} is not governed as a component in the product model.`});await te.applyCanonicalEntries(await A.getCanonicalModelEntries()),_(g,200,{removed:!0,...k})}async function ji(a,g){let j=[];for await(let $ of a)j.push(typeof $=="string"?Buffer.from($):$);let I;try{I=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){_(g,400,{error:"Missing or invalid path/value"});return}let k=I.value;try{let $=JSON.parse(I.value);$&&typeof $=="object"&&(k=$)}catch{}let S=await A.recordDirectModelMutation({key:`tokens.${I.path}`,value:k,claim:`${I.path} uses ${I.value} in the product model.`});await te.applyCanonicalEntries(await A.getCanonicalModelEntries()),_(g,200,{updated:!0,...S})}async function Mi(a,g){let j=[];for await(let S of a)j.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(j).toString("utf-8"))}catch{_(g,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){_(g,400,{error:"Missing or invalid path"});return}let k=await A.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await te.applyCanonicalEntries(await A.getCanonicalModelEntries()),_(g,200,{removed:!0,...k})}function Ai(a,g){let j=s??"http://localhost:3000";if(!s){let k=a.headers.referer||a.headers.origin;if(k)try{let S=new URL(typeof k=="string"?k:k[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(j=S.origin)}catch{}}let I=zo(w,j);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(I)}async function Ei(a){let g=Date.now();if(Ue&&g<Ue.expires){_(a,200,Ue.data);return}try{let{scanForComponents:j}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:I}=await import("./render-generator-HWFLZYC3.mjs"),k=await j(r);Ue={data:k,expires:g+5e3},I(k,r,vt).then(S=>{vt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,k)}catch(j){console.error("[Bridge] Scanner error:",j),_(a,500,{error:"Failed to scan components"})}}async function _i(a){let g=[Ce(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ce(r,"packages","popmelt","dist","canvas.mjs")];try{let j=Xc(import.meta.url);g.unshift(Ce(Vc(j),"canvas.mjs"))}catch{}for(let j of g)try{let I=await gi(j,"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:",g),_(a,404,{error:"Canvas bundle not found"})}async function Ci(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let j=[Ce(c,a),Ce(r,".popmelt","artifacts","thread-media",a),Ce(r,".popmelt","artifacts","eval-screenshots",a),Ce(r,".popmelt","evals","screenshots",a),Ce(r,".popmelt","screenshots",a)],I;for(let $ of j)try{I=await gi($);break}catch{}if(!I)throw new Error("File not found");let k=a.split(".").pop()?.toLowerCase(),S=k==="png"?"image/png":k==="webp"?"image/webp":k==="jpg"||k==="jpeg"?"image/jpeg":k==="svg"?"image/svg+xml":k==="txt"?"text/plain; charset=utf-8":"application/octet-stream";g.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),g.end(I)}catch{_(g,404,{error:"File not found"})}}function Ft(a){return`/files/${eo(a)}`}async function $i(a,g){let j=await W.getThread(a);if(!j){_(g,404,{error:"Thread not found"});return}let I=j.messages.filter(N=>N.role==="assistant"&&N.responseText?.includes("Model suggestion ready")),k=await(I.length>0?te.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(k.map(async(N,q)=>{if(N.authorityStatus==="accepted")return N;let J=(await Promise.all(N.decisionIds.map(ce=>A.findPendingProposalForLegacyDecision(ce)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??I[q]?.jobId??I.at(-1)?.jobId,underlyingProposalId:J?.proposalId,underlyingClaim:J?.claim}})),$=[...S].sort((N,q)=>q.updatedAt-N.updatedAt)[0]??null,O=j.messages.map(({screenshotPath:N,screenshotPaths:q,imagePaths:J,attachmentFiles:ce,replyImagePaths:F,...le})=>({...le,...N?{screenshotUrl:Ft(N)}:{},...q?{screenshotUrls:Object.fromEntries(Object.entries(q).map(([se,ne])=>[se,Ft(ne)]))}:{},...J?{imageUrls:Object.fromEntries(Object.entries(J).map(([se,ne])=>[se,ne.map(Ft)]))}:{},...ce?{attachments:Object.fromEntries(Object.entries(ce).map(([se,ne])=>[se,ne.map(({path:X,...xe})=>({...xe,url:Ft(X)}))]))}:{},...F?{replyImageUrls:F.map(Ft)}:{}}));_(g,200,{id:j.id,createdAt:j.createdAt,messages:O,modelProposal:$,modelProposals:S})}async function Oi(a,g){let j=decodeURIComponent(a);if(!await W.deleteThread(j)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Fo=9,Uo=!1;for(let a=n;a<n+Fo;a++)try{await md(wt,a),w=a,Uo=!0,console.log(`[\u22B9 is watching :${w}]`);break}catch(g){if(g.code==="EADDRINUSE"){let j=await no(a);if(on(j,{projectId:i,version:nt,restartMode:v}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw g}if(!Uo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Fo-1} in use`);for(let[a,g]of Object.entries(m))!g.available||!g.path||R(a,g.path).then(j=>{if(j)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),g.available=!1,g.path=null;for(let I of Q)to(I,{type:"capabilities_changed",data:{}})}});let Di=setInterval(()=>{Ii(c).catch(()=>{}),we.sweep().catch(()=>{})},ed),qo=setInterval(()=>{M.expireStale().becameEmpty&&pe()},nd);return qo.unref?.(),{port:w,projectId:i,close:async()=>{clearInterval(Di),clearInterval(qo),V(),M.clear(),await we.cleanupPartials(),await C.destroyAsync(),f.destroy();for(let a of Q)try{a.res.end()}catch{}return Q.clear(),new Promise(a=>{wt.close(()=>a())})}}}async function Ii(o){try{let e=await Uc(o),n=Date.now();for(let t of e){let r=Ce(o,t);try{let i=await zc(r);n-i.mtimeMs>td&&await Hc(r)}catch{}}}catch{}}import{randomUUID as fd}from"crypto";var hd=5e3,gd=250;function Bo(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function Pi(o,e=fetch){let n=`${process.pid}-${fd()}`,t=`http://127.0.0.1:${o.port}`,r=!1,i=!1,s=async()=>(await e(`${t}/leases`,{method:"POST",headers:Bo(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(x){return console.warn("[popmelt] failed to register bridge lease:",x instanceof Error?x.message:String(x)),null}let c=async()=>{if(!(r||i)){i=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:Bo(o)})).status===404&&!r&&await s()}catch{}finally{i=!1}}},d=setInterval(()=>{c()},hd);return d.unref?.(),{id:n,release:async()=>{if(!r){r=!0,clearInterval(d);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:Bo(o),keepalive:!0})}catch{}}}}}function Ti(o,e=process){let n=!1,t=new Map,r=()=>{if(!n){n=!0;for(let[i,s]of t)e.removeListener(i,s);t.clear()}};for(let i of["SIGINT","SIGTERM"]){let s=()=>{let c=e.listenerCount(i),d=o.release();if(c>0)return;let l=new Promise(x=>{setTimeout(x,gd)});Promise.race([d,l]).finally(()=>{r(),e.kill(e.pid,i)})};t.set(i,s),e.prependOnceListener(i,s)}return r}var Rd=1111,Ri=3e4,kd=8e3;async function jd(o){return Sd(o).catch(()=>o)}async function ki(o,e){let t=(await xd(e,"utf8").catch(()=>"")).slice(-kd).trim();return new Error(t?`${o}
|
|
209
|
+
`);let I=new URL(a.url||"/",`http://127.0.0.1:${h}`).searchParams.get("sourceId")||void 0,A={id:at().slice(0,8),res:v,sourceId:I};L.add(A),a.on("close",()=>{L.delete(A)})}async function pt(a,v,M){s??=Cr(a.headers),ct();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,P,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)}),P.status==="rejected"&&z.push({subsystem:"projection",message:q(P)}),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=P.status==="fulfilled"?P.value.proposals:[],ue=$r(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=>yn(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();_(v,200,{ok:!0,schemaVersion:3,generatedAt:he,serverStartedAt:e,health:{state:Ae,issues:z},version:st,restartMode:l,projectId:r,projectName:po(i),projectRoot:i,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:W},projection:{state:A.status==="fulfilled"&&P.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:We,recentJobs:je})}async function ut(a,v){let M=await new Promise(I=>{let A="";a.on("data",P=>{A+=P.toString()}),a.on("end",()=>I(A))});try{let I=JSON.parse(M);typeof I.devOrigin=="string"&&(s=I.devOrigin||null),_(v,200,{ok:!0,devOrigin:s})}catch{_(v,400,{error:"Invalid JSON"})}}async function ft(a){let v=await ae.load();_(a,200,{ok:!0,...v})}async function ho(a,v){let M=await Oe(a);if(!Ur(M.theme)){_(v,400,{error:"theme must be light, dark, or auto"});return}let I=await ae.setTheme(M.theme);_(v,200,{ok:!0,exists:!0,preferences:I})}async function go(a,v){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,P=I?R.allActive.filter(q=>q.id===I):R.allActive,C=[...A.map(q=>q.threadId),...P.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});_(v,200,{cancelled:z})}async function ht(a){let v=at().slice(0,8),M=a.threadId,I=!M;M||(M=(await O.createThread(`thread-${at()}`,[])).id,He.set(M,"project_model")),I&&await O.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:v,feedbackSummary:a.reason}),await O.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:v,responseText:I?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:v,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:M,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:I},P=R.enqueue(A);return{jobId:v,position:P,threadId:M}}async function Ne(a,v){let M=decodeURIComponent(a),I=await se.findModelProposal(M);if(!I){_(v,404,{error:"Model proposal not found"});return}_(v,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:I})}async function Be(a,v,M){let I=decodeURIComponent(a),A=[];for await(let U of v)A.push(typeof U=="string"?Buffer.from(U):U);let P;try{P=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(M,400,{error:"Invalid JSON"});return}let C=(P.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 $=(P.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=Ht(P.provider),ue=typeof P.model=="string"&&P.model?P.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 mt(a,v,M){let I=decodeURIComponent(a),{provider:A,model:P}=await kt(v),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:P}),_(M,200,{proposal:C})}async function kt(a){try{let v=[];for await(let I of a)v.push(typeof I=="string"?Buffer.from(I):I);if(v.length===0)return{};let M=JSON.parse(Buffer.concat(v).toString());return{provider:Ht(typeof M.provider=="string"?M.provider:void 0),model:typeof M.model=="string"&&M.model?M.model:void 0,agentSettings:At(M)}}catch{return{}}}async function gt(a){let v=He.get(a);if(v)return v;let A=(await O.getThread(a))?.messages.find(P=>P.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 yo(a,v){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 Li(I)),u.codex?.available&&u.codex.mcp&&!u.codex.mcp.found&&A.push(await Fi(I)),u.copilot?.available&&u.copilot.mcp&&!u.copilot.mcp.found&&A.push(await qi(I,u.copilot.path??T));let[P,C,$]=await Promise.all([_o(i),Co(i),$o(i,u.copilot?.path??T)]);u.claude&&(u.claude.mcp=P),u.codex&&(u.codex.mcp=C),u.copilot&&(u.copilot.mcp=$),_(v,200,{results:A,capabilities:{providers:u}})}async function vn(a,v){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(v,400,{error:"Missing or invalid name"});return}let A=await 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()),_(v,200,{added:!0,alreadyExists:!1,...A})}async function is(a,v){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(v,400,{error:"Invalid JSON"});return}if(!I.name||typeof I.name!="string"){_(v,400,{error:"Missing or invalid name"});return}let A=await 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()),_(v,200,{removed:!0,...A})}async function rs(a,v){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{_(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"||typeof I.value!="string"){_(v,400,{error:"Missing or invalid path/value"});return}let A=I.value;try{let C=JSON.parse(I.value);C&&typeof C=="object"&&(A=C)}catch{}let P=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()),_(v,200,{updated:!0,...P})}async function ss(a,v){let M=[];for await(let P of a)M.push(typeof P=="string"?Buffer.from(P):P);let I;try{I=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(v,400,{error:"Invalid JSON"});return}if(!I.path||typeof I.path!="string"){_(v,400,{error:"Missing or invalid path"});return}let A=await D.recordDirectModelMutation({key:`tokens.${I.path}`,value:null,claim:`${I.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(v,200,{removed:!0,...A})}function as(a,v){let M=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let P=new URL(typeof A=="string"?A:A[0]||"");(P.hostname==="localhost"||P.hostname==="127.0.0.1")&&(M=P.origin)}catch{}}let I=ui(h,M);v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(I)}async function cs(a){let v=Date.now();if(dt&&v<dt.expires){_(a,200,dt.data);return}try{let{scanForComponents:M}=await import("./react-scanner-P3VD53VT.mjs"),{generateRenderFiles:I}=await import("./render-generator-HWFLZYC3.mjs"),A=await M(i);dt={data:A,expires:v+5e3},I(A,i,Vt).then(P=>{Vt=P}).catch(P=>console.warn("[Bridge] Render generation failed:",P)),_(a,200,A)}catch(M){console.error("[Bridge] Scanner error:",M),_(a,500,{error:"Failed to scan components"})}}async function ds(a){let v=[De(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),De(i,"packages","popmelt","dist","canvas.mjs")];try{let M=Od(import.meta.url);v.unshift(De(_d(M),"canvas.mjs"))}catch{}for(let M of v)try{let I=await Wr(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:",v),_(a,404,{error:"Canvas bundle not found"})}async function ls(a,v){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(v,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)],I;for(let C of M)try{I=await Wr(C);break}catch{}if(!I)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),P=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";v.writeHead(200,{"Content-Type":P,"Cache-Control":"public, max-age=3600"}),v.end(I)}catch{_(v,404,{error:"File not found"})}}function Kt(a){return`/files/${po(a)}`}async function ps(a,v){let M=await O.getThread(a);if(!M){_(v,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([])),P=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=[...P].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:Kt(F)}:{},...z?{screenshotUrls:Object.fromEntries(Object.entries(z).map(([de,ne])=>[de,Kt(ne)]))}:{},...q?{imageUrls:Object.fromEntries(Object.entries(q).map(([de,ne])=>[de,ne.map(Kt)]))}:{},...le?{attachments:Object.fromEntries(Object.entries(le).map(([de,ne])=>[de,ne.map(({path:X,...Se})=>({...Se,url:Kt(X)}))]))}:{},...U?{replyImageUrls:U.map(Kt)}:{}}));_(v,200,{id:M.id,createdAt:M.createdAt,messages:$,modelProposal:C,modelProposals:P})}async function us(a,v){let M=decodeURIComponent(a);if(!await O.deleteThread(M)){_(v,404,{deleted:!1,error:"Thread not found"});return}_(v,200,{deleted:!0})}let di=9,li=!1;for(let a=n;a<n+di;a++)try{await Xd(Rt,a),h=a,li=!0,console.log(`[\u22B9 is watching :${h}]`);break}catch(v){if(v.code==="EADDRINUSE"){let M=await mo(a);if(mn(M,{projectId:r,version:st,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw v}if(!li)throw new Error(`[Bridge] All ports ${n}\u2013${n+di-1} in use`);for(let[a,v]of Object.entries(u))!v.available||!v.path||j(a,v.path).then(M=>{if(M)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),v.available=!1,v.path=null;for(let I of L)uo(I,{type:"capabilities_changed",data:{}})}});let ms=setInterval(()=>{Qr(c).catch(()=>{}),B.sweep().catch(()=>{})},Bd),pi=setInterval(()=>{N.expireStale().becameEmpty&&H()},Ld);return pi.unref?.(),{port:h,projectId:r,close:async()=>{clearInterval(ms),clearInterval(pi),Q(),N.clear(),await B.cleanupPartials(),await E.destroyAsync(),R.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{Rt.close(()=>a())})}}}async function Qr(o){try{let e=await Rd(o),n=Date.now();for(let t of e){let i=De(o,t);try{let r=await jd(i);n-r.mtimeMs>Jd&&await Ad(i)}catch{}}}catch{}}import{randomUUID as Yd}from"crypto";var Zd=5e3,el=250;function ai(o){return{"Content-Type":"application/json",...o.projectId?{"X-Popmelt-Project-Id":o.projectId}:{}}}async function es(o,e=fetch){let n=`${process.pid}-${Yd()}`,t=`http://127.0.0.1:${o.port}`,i=!1,r=!1,s=async()=>(await e(`${t}/leases`,{method:"POST",headers:ai(o),body:JSON.stringify({leaseId:n,ownerPid:process.pid})})).ok;try{if(!await s())return null}catch(w){return console.warn("[popmelt] failed to register bridge lease:",w instanceof Error?w.message:String(w)),null}let c=async()=>{if(!(i||r)){r=!0;try{(await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"PATCH",headers:ai(o)})).status===404&&!i&&await s()}catch{}finally{r=!1}}},d=setInterval(()=>{c()},Zd);return d.unref?.(),{id:n,release:async()=>{if(!i){i=!0,clearInterval(d);try{await e(`${t}/leases/${encodeURIComponent(n)}`,{method:"DELETE",headers:ai(o),keepalive:!0})}catch{}}}}}function ts(o,e=process){let n=!1,t=new Map,i=()=>{if(!n){n=!0;for(let[r,s]of t)e.removeListener(r,s);t.clear()}};for(let r of["SIGINT","SIGTERM"]){let s=()=>{let c=e.listenerCount(r),d=o.release();if(c>0)return;let p=new Promise(w=>{setTimeout(w,el)});Promise.race([d,p]).finally(()=>{i(),e.kill(e.pid,r)})};t.set(r,s),e.prependOnceListener(r,s)}return i}var ll=1111,ns=3e4,pl=8e3;async function ul(o){return al(o).catch(()=>o)}async function os(o,e){let t=(await sl(e,"utf8").catch(()=>"")).slice(-pl).trim();return new Error(t?`${o}
|
|
208
210
|
Bridge log (${e}):
|
|
209
|
-
${t}`:o)}async function
|
|
211
|
+
${t}`:o)}async function Pm(o){if(process.env.NODE_ENV==="production"&&!o?.force)throw new Error("[Bridge] Refusing to start in production. Pass { force: true } to override.");if(o?.detached){let n=await ml(o);if(o.manageLease===!1)return n;let t=await es({port:n.port,projectId:n.projectId});if(!t)return console.warn("[popmelt] detached bridge started without a process lease"),n;let i=ts(t);return{...n,close:async()=>{i(),await t.release()}}}let e=await Zr(o);return process.env.POPMELT_BRIDGE_PORT=String(e.port),process.env.POPMELT_PROJECT_ID=e.projectId,e}async function ml(o){let e=o.port??ll,n=await ul(o.projectRoot??process.cwd()),t=co(n);for(let x=e;x<e+10;x++){let T=await mo(x);if(T&&T.projectId===t){if(T.version&&T.version!==st){if(T.restartMode==="detached"){try{await fetch(`http://127.0.0.1:${x}/shutdown`,{method:"POST"})}catch{}await new Promise(y=>setTimeout(y,500));break}continue}if(!mn(T,{projectId:t,version:st,restartMode:"detached"}))continue;let k=o.devOrigin;if(k&&T.devOrigin!==k)try{await fetch(`http://127.0.0.1:${x}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({devOrigin:k})})}catch{}return process.env.POPMELT_BRIDGE_PORT=String(x),process.env.POPMELT_PROJECT_ID=t,{port:x,projectId:t,close:async()=>{}}}}let i=ci(cl(dl(import.meta.url)),"bridge-entry.mjs"),r=ci(n,".popmelt"),s=ci(r,"bridge.log");await rl(r,{recursive:!0}),await il(s,`
|
|
210
212
|
[${new Date().toISOString()}] Starting detached bridge
|
|
211
|
-
`);let c=
|
|
213
|
+
`);let c=ol(s,"a"),d;try{d=tl(process.execPath,[i],{detached:!0,stdio:["ignore","ignore",c],env:{...process.env,POPMELT_PORT:String(e),POPMELT_PROJECT_ROOT:n,POPMELT_DEV_ORIGIN:o.devOrigin??"",POPMELT_COPILOT_PATH:o.copilotPath??""}})}finally{nl(c)}let p=null;d.once("error",x=>{p=`spawn error: ${x.message}`}),d.once("exit",(x,T)=>{p=`child exited before becoming healthy (${T?`signal ${T}`:`code ${x??"unknown"}`})`}),d.unref();let w=Date.now()+ns;for(;Date.now()<w;){if(await new Promise(x=>setTimeout(x,100)),p)throw await os(`[Bridge] Detached bridge ${p}`,s);for(let x=e;x<e+10;x++){let T=await mo(x);if(mn(T,{projectId:t,version:st,restartMode:"detached"}))return process.env.POPMELT_BRIDGE_PORT=String(x),process.env.POPMELT_PROJECT_ID=t,{port:x,projectId:t,close:async()=>{}}}}throw d.kill("SIGTERM"),await os(`[Bridge] Detached bridge failed to start within ${ns/1e3}s (port ${e})`,s)}export{Ut as ImprintService,qt as ImprintStore,eo as formatImprintPrompt,Zn as parseImprintDraft,Pm as startPopmelt};
|