@popmelt.com/core 0.8.13 → 0.8.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +77 -67
- package/dist/canvas.mjs +1 -1
- package/dist/chunk-U35GCRMU.mjs +1 -0
- package/dist/cli.mjs +77 -67
- package/dist/index.mjs +68 -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-next.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-LYQ2TJFR.mjs +221 -0
- package/dist/server.d.mts +55 -10
- package/dist/server.mjs +74 -64
- package/package.json +1 -1
- package/dist/chunk-X3ENE5RX.mjs +0 -1
- package/dist/server-UH23TSES.mjs +0 -211
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as
|
|
2
|
+
import{spawn as Xd}from"child_process";import{readFile as Yd,unlink as Zd}from"fs/promises";import{join as el}from"path";import{execFileSync as xd,spawn as Wr}from"child_process";import{randomUUID as rt}from"crypto";import{mkdir as Sd,readFile as Hr,readdir as kd,realpath as Td,stat as Rd,unlink as Pd,writeFile as ao}from"fs/promises";import{createServer as jd}from"http";import{tmpdir as Ad}from"os";import{basename as co,dirname as Md,isAbsolute as Zr,join as Ne,relative as Ed,resolve as _d}from"path";import{fileURLToPath as $d}from"url";function li(o,e){return`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -19,26 +19,31 @@ import{spawn as pd}from"child_process";import{readFile as ud,unlink as md}from"f
|
|
|
19
19
|
}}
|
|
20
20
|
</script>
|
|
21
21
|
<script type="module">
|
|
22
|
-
|
|
22
|
+
const isProxied = location.pathname === '/popmelt' || location.pathname.startsWith('/popmelt/');
|
|
23
|
+
const bridgeOrigin = isProxied ? location.origin + '/popmelt' : location.origin;
|
|
24
|
+
const canvasModule = isProxied ? bridgeOrigin + '/app.mjs' : location.origin + '/canvas/app.mjs';
|
|
25
|
+
const { mountCanvas } = await import(canvasModule);
|
|
23
26
|
mountCanvas(document.getElementById('root'), {
|
|
24
|
-
devOrigin:
|
|
25
|
-
bridgeOrigin
|
|
27
|
+
devOrigin: isProxied ? location.origin : ${JSON.stringify(e)},
|
|
28
|
+
bridgeOrigin,
|
|
26
29
|
});
|
|
27
30
|
</script>
|
|
28
31
|
</body>
|
|
29
|
-
</html>`}var
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
`)
|
|
34
|
-
`)[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 ss(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 io(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 as,readFile as cs}from"fs/promises";import{join as so}from"path";var hn=class{constructor(e){let n=so(e,".popmelt");this.decisionsDir=so(n,"decisions")}async listDecisionIds(){try{return(await as(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 cs(so(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 ds,randomUUID as ls}from"crypto";import{mkdir as ao,readFile as tr,readdir as nr,rename as gn,stat as or,unlink as yn,writeFile as vn}from"fs/promises";import{extname as ps,join as Ve}from"path";var us=10080*60*1e3,ms=600*1e3,fs=3600*1e3;function hs(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function gs(o,e){return[...o.trim()].map(t=>t==="/"||t==="\\"||t.charCodeAt(0)<32?"-":t).join("").slice(0,120)||e}var wn=class{constructor(e){this.draftsDir=Ve(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ve(e,".popmelt","artifacts","thread-media")}async stage(e){let n=ls(),t=hs(e.mimeType),r=`${n}${t}`,i=Date.now(),s={id:n,annotationId:e.annotationId,name:gs(e.name,`pasted-context${t}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:i,lastSeenAt:i,contentFile:r};await ao(this.draftsDir,{recursive:!0});let c=Ve(this.draftsDir,r),d=Ve(this.draftsDir,`${n}.json`),p=`${c}.part`,x=`${d}.part`;return await vn(p,e.data),await gn(p,c),await vn(x,JSON.stringify(s,null,2)),await gn(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=Ve(this.draftsDir,r.contentFile),s=await tr(i),c=ds("sha256").update(s).digest("hex"),d=Ve(this.mediaDir,`${c}${ps(r.contentFile)||".bin"}`);await ao(this.mediaDir,{recursive:!0});try{await or(d)}catch{let p=`${d}.part`;await vn(p,s),await gn(p,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 nr(this.draftsDir)}catch{return}await Promise.all(n.map(async t=>{let r=Ve(this.draftsDir,t);if(t.endsWith(".part")){let c=await or(r).catch(()=>null);c&&e-c.mtimeMs>fs&&await yn(r).catch(()=>{});return}if(!t.endsWith(".json"))return;let i=await this.readManifest(t.slice(0,-5));!i||!(i.releasedAt?e-i.releasedAt>ms:e-i.lastSeenAt>us)||await Promise.all([yn(r).catch(()=>{}),yn(Ve(this.draftsDir,i.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await nr(this.draftsDir)}catch{return}await Promise.all(e.filter(n=>n.endsWith(".part")).map(n=>yn(Ve(this.draftsDir,n)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await tr(Ve(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await ao(this.draftsDir,{recursive:!0});let n=Ve(this.draftsDir,`${e.id}.json`),t=`${n}.part`;await vn(t,JSON.stringify(e,null,2)),await gn(t,n)}};import{randomUUID as rr}from"crypto";import{mkdir as co,readFile as lo,writeFile as In}from"fs/promises";import{dirname as po,join as St}from"path";var Ke="[ProjectionWorker]",ys={version:1,runs:[]},vs={version:1,updatedAt:0,proposals:[]},ws=12;function Is(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 ir(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(r=>typeof r=="string"):[]})}return e.length>30&&console.warn(`${Ke} Rule count ${e.length} exceeds cap of 30`),e}function bs(o,e,n){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:n.length,estimatedTokens:Math.ceil(n.length/4)}}function xs(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 l=h.sources;if(Array.isArray(l))for(let v of l)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:[],p=i.filter(h=>{if(!h||typeof h!="object")return!1;let l=h.id,v=typeof l=="string"?d.find(w=>w&&typeof w=="object"&&w.id===l):void 0;return JSON.stringify(v)!==JSON.stringify(h)}).length,x=n?.tokens&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)?n.tokens:{},j=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(j[h])).length;return{ruleCount:p,tokenSectionCount:T,componentCount:b,coveredDecisionIds:[...r],uncoveredDecisionIds:e.filter(h=>!r.has(h))}}function Ss(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function Ps(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 bn(o,e,n){let t=o;for(let i=0;i<e.length-1;i++)t=Ps(t,e[i],e[i+1]);let r=e[e.length-1];t[String(r)]=Ss(n)}function sr(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 ks(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 Rs(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 ar(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let n of o.changes){let t=ks(e,n.path);if(!(n.path.length===1&&n.path[0]==="rules"?Rs(t.exists?t.value:void 0,n.value):!t.exists))return null}return o.changes}var xn=class{constructor(e,n={}){this.projectRoot=e;this.options=n;this.running=!1;let t=St(e,".popmelt");this.runsPath=St(t,"projection-runs.json"),this.legacyRunsPath=St(t,"materialization-runs.json"),this.proposalsPath=St(t,"projection-queue.json"),this.legacyProposalsPath=St(t,"model-proposals.json"),this.modelPath=St(t,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await lo(this.modelPath,"utf-8"),n=JSON.parse(e);return Array.isArray(n.rules)&&(n.rules=Is(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?sr(n,r):bn(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(ws),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(`${Ke} Processing ${i.length} pattern-scoped decision(s): ${i.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:i});let s=await this.loadModel(),c=As(r,s),d=bs(r,t.totalCandidateDecisionCount,c);n=rr().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:i,startedAt:Date.now(),promptStats:d};await this.persistRun(p);let x=!0,j,T,b;try{let h=`projection-${Date.now()}`,{provider:l,result:v}=this.spawnModelAgent(h,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});p={...p,provider:l},await this.persistRun(p);let w=await v;if(!w.success)x=!1,j=w.error,console.error(`${Ke} ${l} spawn error:`,j);else{let m=Ms(w.text,i);if(m){let u=structuredClone(s??{tokens:{},components:{},rules:[]});for(let y of m)bn(u,y.path,y.value);Array.isArray(u.rules)&&(u.rules=ir(u.rules));let P=xs(u,i,s);if(m){let y=[...new Set(m.flatMap(L=>L.decisionIds))];P.coveredDecisionIds=y,P.uncoveredDecisionIds=i.filter(L=>!y.includes(L))}T=P;let E=await this.createModelProposal({decisionIds:i,proposedModel:u,runId:n,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:l,model:e.model??this.options.model,outputStats:T,changes:m});b=E.id,console.log(`${Ke} Created model proposal ${E.id} for ${i.length} decision(s)`)}else x=!1,j="No valid bounded <model-changes> block found in response",console.error(`${Ke} ${j}`)}}catch(h){x=!1,j=h instanceof Error?h.message:String(h),console.error(`${Ke} Error:`,j)}return await this.persistRun({...p,status:x?"proposed":"failed",completedAt:Date.now(),error:j,outputStats:T,proposalId:b}),this.options.onEvent?.({type:"projection_done",decisionIds:i,success:x,error:j}),{processedIds:i,success:x,error:j,runId:n,proposalId:b}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=ir(e.rules)),await In(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 co(po(this.runsPath),{recursive:!0}),await In(this.runsPath,JSON.stringify(n,null,2)),n):{...ys,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??{...vs,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??[])bn(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?sr(s,d.path):bn(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:rr().slice(0,8),status:"pending",title:Ts(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"}.`:js(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 co(po(this.proposalsPath),{recursive:!0});let n={...e,proposals:e.proposals.map(({proposedModel:t,...r})=>r)};await In(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(r=>r.id===e.id);t>=0?n.runs[t]=e:n.runs.push(e),await co(po(this.runsPath),{recursive:!0}),await In(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 lo(e,"utf8"));return n?.version===1&&Array.isArray(n.runs)?n:null}catch{return null}}async readProposalStore(e){try{let n=JSON.parse(await lo(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",...fn(e,{prompt:n,projectRoot:this.projectRoot,model:t.model??this.options.model,configOverrides:pn(t.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(i==="copilot"&&console.warn(`${Ke} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...un(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 Ts(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 js(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 Ms(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(j=>typeof j=="string"||typeof j=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let p=d.path[0];if(p!=="tokens"&&p!=="components"&&p!=="rules")return[];if(p==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let x=Array.isArray(d.decisionIds)?d.decisionIds.filter(j=>typeof j=="string"&&r.has(j)):[];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 As(o,e){let n=o.map(i=>`### Accepted decision ${i.id} (${i.createdAt})
|
|
35
|
-
|
|
36
|
-
Claim: ${i.claim}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
`)
|
|
32
|
+
</html>`}var us=new Set(["minimal","low","medium","high","xhigh","max","ultra"]),ms=new Set(["default","flex","fast","priority"]);function Mt(o){let e=typeof o.reasoningEffort=="string"&&us.has(o.reasoningEffort)?o.reasoningEffort:void 0,t=typeof o.serviceTier=="string"&&ms.has(o.serviceTier)?o.serviceTier:void 0;return e||t?{reasoningEffort:e,serviceTier:t}:void 0}function wn(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 fs}from"child_process";import{createInterface as hs}from"readline";function Qt(o,e){let t=e.trim();if(!t)return"";let n=o.length>0?`
|
|
33
|
+
|
|
34
|
+
${t}`:t;return o.push(n),n}var gs=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"]),pi=1e5;function ys(o){let e=o.input?.file_path||o.input?.path;if(!e)return;let t=e.includes(".")?`.${e.split(".").pop().toLowerCase()}`:"";if(!gs.has(t))return;let n;if(o.name==="Write"&&typeof o.input?.content=="string"?n=o.input.content:o.name==="Edit"&&typeof o.input?.new_string=="string"&&(n=o.input.new_string),!!n)return n.length>pi?n.slice(0,pi)+`
|
|
35
|
+
\u2026[truncated]`:n}function bn(o,e){let{prompt:t,projectRoot:n,maxTurns:i=40,maxBudgetUsd:r=1,allowedTools:s=["Read","Edit","Write","Glob","Grep","Bash"],claudePath:c="claude",resumeSessionId:d,model:u,reasoningEffort:I,timeoutMs:T=3e5,onEvent:k}=e,P=[];d?P.push("--resume",d,"-p",t):P.push("-p",t),P.push("--output-format","stream-json","--verbose","--max-turns",String(i),"--max-budget-usd",String(r)),u&&P.push("--model",u),I&&P.push("--effort",I);for(let l of s)P.push("--allowedTools",l);let x=fs(c,P,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),p=new Promise(l=>{let f,m=[],h=[],j=[],b=!1,g="",B,E,R=!1,N=setTimeout(()=>{R=!0,x.kill("SIGTERM"),setTimeout(()=>{try{x.kill("SIGKILL")}catch{}},5e3)},T),V=hs({input:x.stdout}),K=new Set;V.on("line",Q=>{if(Q.trim())try{let w=JSON.parse(Q);w.session_id&&!f&&(f=w.session_id);let H=w.type??(w.event?.type?`event.${w.event.type}`:"unknown");if(K.add(H),w.type==="result"&&w.result&&m.length===0){let L=typeof w.result=="string"?w.result:"";if(L){let O=Qt(m,L);O&&k?.({type:"delta",jobId:o,text:O},o)}}if(w.type==="assistant"&&Array.isArray(w.message?.content)){typeof w.error=="string"&&(B=w.error);for(let L of w.message.content){if(L.type==="text"&&L.text){let O=Qt(m,L.text);O&&k?.({type:"delta",jobId:o,text:O},o)}if(L.type==="tool_use"&&L.name){let O=L.input?.file_path||L.input?.path||void 0,he=ys(L);if(k?.({type:"tool_use",jobId:o,tool:L.name,...O?{file:O}:{},...he?{content:he}:{}},o),L.name==="Edit"&&L.input?.file_path){let J={tool:"Edit",file_path:L.input.file_path,old_string:L.input.old_string,new_string:L.input.new_string,replace_all:L.input.replace_all};h.push(J),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Edit",operation:"modify",filePath:J.file_path,oldString:typeof J.old_string=="string"?J.old_string:void 0,newString:typeof J.new_string=="string"?J.new_string:void 0,replaceAll:typeof J.replace_all=="boolean"?J.replace_all:void 0})}else L.name==="Write"&&L.input?.file_path&&(h.push({tool:"Write",file_path:L.input.file_path,content:L.input.content}),j.push({sequence:j.length,occurredAt:Date.now(),provider:"claude",source:"claude_tool_use",tool:"Write",operation:"create",filePath:L.input.file_path,content:typeof L.input.content=="string"?L.input.content:void 0}))}L.type==="thinking"&&L.thinking&&k?.({type:"thinking",jobId:o,text:L.thinking},o)}}w.type==="result"&&w.is_error===!0&&(b=!0,typeof w.error=="string"&&(B=w.error),typeof w.result=="string"&&(E=w.result)),w.type==="user"&&w.tool_use_result?.file?.filePath&&k?.({type:"tool_use",jobId:o,tool:"Read",file:w.tool_use_result.file.filePath},o)}catch{}});let W=[];x.stderr?.on("data",Q=>{W.push(Q.toString())}),x.on("close",Q=>{if(clearTimeout(N),V.close(),m.length===0&&K.size>0&&console.warn(`[Claude:${o}] No text captured. Event types seen: ${[...K].join(", ")}`),R)b=!0,g=`Timed out after ${Math.round(T/6e4)} minutes`;else if(Q!==0&&Q!==null){b=!0;let H=W.join("").trim(),L=m.join("").trim(),O=m.length===0&&K.size>0?` (no text captured, event types: ${[...K].join(", ")})`:"";g=H||E||L||`Claude process exited with code ${Q}${O}`}b&&!g&&E&&(g=E);let w=vs(g,B);l({sessionId:f,text:m.join(""),success:!b,error:b?w.message:void 0,errorCode:b?w.code:void 0,recoverableError:b?w.recoverable:void 0,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})}),x.on("error",Q=>{clearTimeout(N),b=!0,g=Q.message,l({sessionId:f,text:m.join(""),success:!1,error:g,errorCode:"claude_spawn_error",recoverableError:!1,fileEdits:h.length>0?h:void 0,editEvents:j.length>0?j:void 0})})});return{process:x,result:p}}function vs(o,e){let t=o.trim()||"Claude CLI failed",n=`${e??""} ${t}`.toLowerCase();return n.includes("authentication_failed")||n.includes("not logged in")||n.includes("please run /login")||n.includes("api key")?{message:t,code:"claude_auth_required",recoverable:!0}:n.includes("model")&&(n.includes("not found")||n.includes("unknown")||n.includes("unavailable"))?{message:t,code:"claude_model_unavailable",recoverable:!0}:{message:t,code:e||"claude_error",recoverable:!1}}import{spawn as Is,spawnSync as yi}from"child_process";import{readFileSync as ws,statSync as bs}from"fs";import{basename as xs,extname as Ss,isAbsolute as ks,relative as vi,resolve as Ts}from"path";import{createInterface as Rs}from"readline";function ui(o){let e=o.match(/^\/bin\/(?:ba)?sh\s+-\w+\s+"(.*)"$/s);return e?e[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):o}var mi=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"]),vo=2e5,Ps=1e5,Ii=2e5;function wi(o){let e=xs(o).toLowerCase(),t=Ss(o).toLowerCase();return mi.has(t)||mi.has(e)}function Xt(o,e){let t=ks(e)?e:Ts(o,e),n=vi(o,t);return n===""||n.startsWith("..")?null:t}function xn(o,e){if(!wi(e))return;let t=Xt(o,e);if(t)try{let n=bs(t);return n.isFile()?n.size>vo?{exists:!0,truncated:!0}:{exists:!0,content:ws(t,"utf8")}:{exists:!1}}catch{return{exists:!1}}}function js(o,e){for(let t of e){let n=o[t];if(typeof n=="string")return n}}function As(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 fi(o){return js(o,["patch","diff","unifiedDiff","unified_diff"])}function Io(o,e){return o.length<=e?{text:o}:{text:o.slice(0,e),truncated:!0}}function hi(o,e){let t=yi("git",e,{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:Ii+65536});return t.status!==0?null:t.stdout??""}function Ms(o){let e=new Set;for(let t of o.split(`
|
|
36
|
+
`)){if(t.length<4)continue;let n=t.slice(3).trim();if(!n)continue;n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1));let i=n.split(" -> ");for(let r of i)r&&e.add(r)}return[...e]}function gi(o){let e=hi(o,["status","--porcelain=v1","-uall"]);if(e===null)return;let t=hi(o,["diff","--no-ext-diff","HEAD","--"])??"",n=Io(t,Ii);return{status:e,changedFiles:Ms(e),...n.text?{diff:n.text}:{},...n.truncated?{diffTruncated:!0}:{}}}function Es(o,e){return!o||!e?!1:o.status!==e.status||(o.diff??"")!==(e.diff??"")}function _s(o,e){if(!wi(e))return;let t=Xt(o,e);if(!t)return;let n=vi(o,t);if(n===""||n.startsWith(".."))return;let i=yi("git",["show",`HEAD:${n}`],{cwd:o,encoding:"utf8",timeout:5e3,maxBuffer:vo+65536});if(i.status!==0)return{exists:!1};let r=i.stdout??"",s=Io(r,vo);return{exists:!0,content:s.text,...s.truncated?{truncated:!0}:{}}}function $s(o,e,t){return e.map(n=>{let i=t.has(n)?t.get(n):_s(o,n),r=xn(o,n);return{filePath:n,...i?{before:i}:{},...r?{after:r}:{}}})}function Sn(o,e){let{prompt:t,projectRoot:n,screenshotPath:i,resumeSessionId:r,model:s,onEvent:c,sandboxMode:d="workspace-write",configOverrides:u=[]}=e,I=[];if(r){I.push("exec","resume","--skip-git-repo-check","--json","-c",`sandbox_mode="${d}"`);for(let P of u)I.push("-c",P);s&&I.push("-m",s),I.push(r),I.push(t),i&&I.push("--image",i)}else{I.push("exec","--skip-git-repo-check","--json","--sandbox",d);for(let P of u)I.push("-c",P);s&&I.push("-m",s),I.push(t),i&&I.push("--image",i)}let T=Is("codex",I,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,CLAUDECODE:void 0}}),k=new Promise(P=>{let x,p=[],l=[],f=[],m=new Map,h=new Map,j=!1,b="",g=Rs({input:T.stdout}),B=new Set;g.on("line",R=>{if(R.trim())try{let N=JSON.parse(R),V=N.type??"unknown";if(B.add(V),V==="thread.started"&&N.thread_id&&!x&&(x=N.thread_id),(V==="item.agentMessage.delta"||V==="item/agentMessage/delta")&&N.delta?.text&&(p.push(N.delta.text),c?.({type:"delta",jobId:o,text:N.delta.text},o)),(V==="item.reasoning.delta"||V==="item/reasoning/delta")&&N.delta?.text&&c?.({type:"thinking",jobId:o,text:N.delta.text},o),(V==="item.started"||V==="item/started")&&N.item){let K=N.item.type;if(K==="command_execution"){let W=N.item.command,Q=W?ui(W):void 0,w=gi(n),H=new Map;for(let O of w?.changedFiles??[])H.set(O,xn(n,O));typeof N.item.id=="string"&&h.set(N.item.id,{...W?{rawCommand:W}:{},...Q?{command:Q}:{},...w?{beforeWorktree:w}:{},beforeSnapshots:H});let L=Q?`Bash: ${Q.split(`
|
|
37
|
+
`)[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&&!m.has(W)&&m.set(W,xn(n,W)),l.push(W?`Edit ${W.split("/").pop()}`:"Edit");let Q=W?Xt(n,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(n,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(p,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 w=Xt(n,W)??W;c?.({type:"tool_use",jobId:o,tool:Q,file:w},o);let H=K,L=typeof H.kind=="string"?H.kind:void 0,O=As(L),he=m.get(W),J=xn(n,W);f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_file_change",tool:"FileChange",operation:O,filePath:W,...he?{before:he}:{},...J?{after:J}:{},...fi(H)?{patch:fi(H)}:{},...L?{rawKind:L}:{}}),m.set(W,J)}}else if(N.item.type==="command_execution"){let K=typeof N.item.id=="string"?N.item.id:void 0,W=K?h.get(K):void 0,Q=typeof N.item.command=="string"?N.item.command:W?.rawCommand,w=Q?ui(Q):W?.command,H=gi(n);if(Es(W?.beforeWorktree,H)){let L=[...new Set([...W?.beforeWorktree?.changedFiles??[],...H?.changedFiles??[]])],O=typeof N.item.aggregated_output=="string"?Io(N.item.aggregated_output,Ps):void 0,he=typeof N.item.exit_code=="number"?N.item.exit_code:N.item.exit_code===null?null:void 0,J=typeof N.item.status=="string"?N.item.status:void 0;f.push({sequence:f.length,occurredAt:Date.now(),provider:"codex",source:"codex_command_execution",tool:"Bash",operation:"command",...Q?{rawCommand:Q}:{},...w?{command:w}:{},...he!==void 0?{exitCode:he}:{},...J?{status:J}:{},...O?{output:O.text}:{},...O?.truncated?{outputTruncated:!0}:{},...W?.beforeWorktree?{beforeWorktree:W.beforeWorktree}:{},...H?{afterWorktree:H}:{},...L.length>0?{touchedFiles:$s(n,L,W?.beforeSnapshots??new Map)}:{}})}K&&h.delete(K)}}V==="turn.failed"&&(j=!0,b=N.error?.message||N.message||"Turn failed")}catch{}});let E=[];T.stderr?.on("data",R=>{E.push(R.toString())}),T.on("close",R=>{g.close(),p.length===0&&B.size>0&&console.warn(`[Codex:${o}] No text captured. Event types seen: ${[...B].join(", ")}`),R!==0&&R!==null&&(j=!0,b=E.join("")||`Codex process exited with code ${R}`),P({sessionId:x,text:p.join(""),success:!j,error:j?b:void 0,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})}),T.on("error",R=>{j=!0,b=R.message,P({sessionId:x,text:p.join(""),success:!1,error:b,editEvents:f.length>0?f:void 0,toolsUsed:l.length>0?l:void 0})})});return{process:T,result:k}}import{spawn as Cs}from"child_process";import{createInterface as Os}from"readline";function bi(o,e){let t=o.trim()||"Copilot CLI failed",n=t.toLowerCase();return n.includes("no authentication information")||n.includes("not authenticated")||n.includes("/login")?{code:"copilot_auth_required",recoverable:!0,message:"Copilot is not authenticated. Run `copilot login`, set `COPILOT_GITHUB_TOKEN`, or refresh `gh auth login`."}:n.includes("model")&&(n.includes("not available")||n.includes("not found")||n.includes("disabled")||n.includes("policy"))?{code:"copilot_model_unavailable",recoverable:!0,message:e?`Copilot rejected ${e}. Choose another model or ask your administrator to enable it.`:t}:n.includes("mcp")&&(n.includes("blocked")||n.includes("allowlist"))?{code:"copilot_mcp_blocked",recoverable:!0,message:"Copilot blocked the Popmelt MCP server. Ask your administrator to add it to the enterprise allowlist."}:n.includes("permission")||n.includes("denied")||n.includes("not allowed")?{code:"copilot_permission_denied",recoverable:!0,message:t}:{code:"copilot_error",recoverable:!1,message:t}}function xi(o,e){let{prompt:t,projectRoot:n,resumeSessionId:i,model:r,timeoutMs:s=3e5,onEvent:c,copilotPath:d="copilot"}=e,u=["--no-color","--no-auto-update","--output-format","json","--stream","on","--available-tools=read,write,shell","--allow-all-tools","--deny-tool=shell(git push)","--deny-tool=shell(rm)","--deny-tool=shell(sudo)","--no-ask-user"];i&&u.push(`--resume=${i}`),r&&u.push("--model",r),u.push("-p",t);let I=Cs(d,u,{cwd:n,stdio:["ignore","pipe","pipe"],env:{...process.env,ANTHROPIC_API_KEY:void 0,CLAUDECODE:void 0}}),T=new Promise(k=>{let P,x=[],p=[],l=!1,f="",m=!1,h=setTimeout(()=>{m=!0,I.kill("SIGTERM"),setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},5e3)},s),j=Os({input:I.stdout}),b=new Set,g=[];j.on("line",E=>{if(E.trim())try{let R=JSON.parse(E),N=Zt(R);b.add(N),g.length<5&&Ns(N)&&g.push(E.slice(0,800));let V=Yt(R,["sessionId","session_id","id"],["session","conversation","thread"]);V&&!P&&(P=V);let K=Ds(R,x.length===0);K&&(x.push(K),c?.({type:"delta",jobId:o,text:K},o));let W=Js(R);W&&c?.({type:"thinking",jobId:o,text:W},o);let Q=Bs(R);Q&&(p.push(Q.label),c?.({type:"tool_use",jobId:o,tool:Q.tool,...Q.file?{file:Q.file}:{},...Q.content?{content:Q.content}:{}},o));let w=Ls(R);w&&(l=!0,f=w)}catch{}});let B=[];I.stderr?.on("data",E=>{B.push(E.toString())}),I.on("close",E=>{clearTimeout(h),j.close(),x.length===0&&b.size>0&&(console.warn(`[Copilot:${o}] No text captured. Event types seen: ${[...b].join(", ")}`),g.length>0&&console.warn(`[Copilot:${o}] Sample text-bearing candidates: ${g.join(`
|
|
38
|
+
`)}`)),m?(l=!0,f=`Timed out after ${Math.round(s/6e4)} minutes`):E!==0&&E!==null&&(l=!0,f=B.join("").trim()||f||`Copilot process exited with code ${E}`);let R=l?bi(f,r):null;k({sessionId:P,text:x.join(""),success:!l,error:R?.message,errorCode:R?.code,recoverableError:R?.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})}),I.on("error",E=>{clearTimeout(h);let R=bi(E.message,r);k({sessionId:P,text:x.join(""),success:!1,error:R.message,errorCode:R.code,recoverableError:R.recoverable,provider:"copilot",toolsUsed:p.length>0?p:void 0})})});return{process:I,result:T}}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 Ds(o,e=!1){let t=Zt(o).toLowerCase(),n=o.update,i=n?.content;if(n?.sessionUpdate==="agent_message_chunk"&&i?.type==="text"&&typeof i.text=="string")return i.text;if(t==="assistant.message_delta"||t.includes("agent_message.delta"))return Ge(o.delta)??Ge(o.content)??Ge(o.message);if(t==="assistant.message"&&e)return Ge(o.message)??Ge(o.content)??Ge(o);if(t==="result"&&e)return Ge(o.result)??Ge(o.output)??Ge(o.message)??Ge(o);let r=o.content;if(r?.type==="text"&&typeof r.text=="string")return r.text;if(typeof o.text=="string"&&wo(o))return o.text;if(typeof o.message=="string"&&wo(o))return o.message;if(typeof o.delta=="string"&&wo(o))return o.delta}function Ge(o){if(typeof o=="string")return o;if(!o)return;if(Array.isArray(o)){let t=o.map(Ge).filter(n=>!!n);return t.length>0?t.join(""):void 0}if(typeof o!="object")return;let e=o;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;for(let t of["delta","content","message","messages","parts","items","output","result","data","value","body","markdown","text_delta","textDelta"]){let n=Ge(e[t]);if(n)return n}}function Ns(o){let e=o.toLowerCase();return e.includes("assistant.message")||e==="result"}function Js(o){if(typeof o.thinking=="string")return o.thinking;if(typeof o.reasoning=="string")return o.reasoning;let e=o.update;if(e?.sessionUpdate==="reasoning_chunk"){let t=e.content;if(typeof t?.text=="string")return t.text}}function Bs(o){let e=Yt(o,["tool","toolName","tool_name","name"]),t=Yt(o,["command","cmd"]),n=Yt(o,["file","path","filename","filePath"]),i=Zt(o);if(t||i.includes("shell"))return{tool:"Bash",label:t?`Bash: ${t.split(`
|
|
39
|
+
`)[0].slice(0,80)}`:"Bash",...t?{content:t}:{}};if(e)return{tool:e,label:n?`${e} ${n.split("/").pop()}`:e,...n?{file:n}:{}};if(n&&(i.includes("file")||i.includes("write")||i.includes("edit"))){let r=i.includes("write")?"Write":i.includes("read")?"Read":"Edit";return{tool:r,label:`${r} ${n.split("/").pop()}`,file:n}}}function Ls(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,t=[]){for(let n of e){let i=o[n];if(typeof i=="string")return i}for(let[n,i]of Object.entries(o)){if(!i||typeof i!="object"||t.length>0&&!t.some(s=>n.toLowerCase().includes(s)))continue;let r=Yt(i,e);if(r)return r}}function wo(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 qs,readFile as Fs}from"fs/promises";import{join as bo}from"path";var kn=class{constructor(e){let t=bo(e,".popmelt");this.decisionsDir=bo(t,"decisions")}async listDecisionIds(){try{return(await qs(this.decisionsDir)).filter(t=>t.startsWith("d-")&&t.endsWith(".json")).map(t=>t.slice(2,-5))}catch{return[]}}async loadDecision(e){try{let t=await Fs(bo(this.decisionsDir,`d-${e}.json`),"utf-8");return JSON.parse(t)}catch{return null}}async loadDecisions(e){return(await Promise.all(e.map(n=>this.loadDecision(n)))).filter(n=>n!==null)}};import{createHash as Us,randomUUID as zs}from"crypto";import{mkdir as xo,readFile as Si,readdir as ki,rename as Tn,stat as Ti,unlink as Rn,writeFile as Pn}from"fs/promises";import{extname as Gs,join as Ke}from"path";var Ws=10080*60*1e3,Hs=600*1e3,Vs=3600*1e3;function Ks(o){return o==="image/svg+xml"?".svg":o==="text/plain"?".txt":".bin"}function Qs(o,e){return[...o.trim()].map(n=>n==="/"||n==="\\"||n.charCodeAt(0)<32?"-":n).join("").slice(0,120)||e}var jn=class{constructor(e){this.draftsDir=Ke(e,".popmelt","artifacts","draft-attachments"),this.mediaDir=Ke(e,".popmelt","artifacts","thread-media")}async stage(e){let t=zs(),n=Ks(e.mimeType),i=`${t}${n}`,r=Date.now(),s={id:t,annotationId:e.annotationId,name:Qs(e.name,`pasted-context${n}`),mimeType:e.mimeType,size:e.data.byteLength,kind:e.kind,createdAt:r,lastSeenAt:r,contentFile:i};await xo(this.draftsDir,{recursive:!0});let c=Ke(this.draftsDir,i),d=Ke(this.draftsDir,`${t}.json`),u=`${c}.part`,I=`${d}.part`;return await Pn(u,e.data),await Tn(u,c),await Pn(I,JSON.stringify(s,null,2)),await Tn(I,d),s}async claim(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(delete n.releasedAt,n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async release(e){await Promise.all(e.map(async t=>{let n=await this.readManifest(t);n&&(n.releasedAt=Date.now(),n.lastSeenAt=Date.now(),await this.writeManifest(n))}))}async promote(e){let t={};for(let n of e){let i=await this.readManifest(n.id);if(!i)throw new Error(`Draft attachment ${n.id} is unavailable or expired.`);if(i.annotationId!==n.annotationId)throw new Error(`Draft attachment ${n.id} does not belong to annotation ${n.annotationId}.`);let r=Ke(this.draftsDir,i.contentFile),s=await Si(r),c=Us("sha256").update(s).digest("hex"),d=Ke(this.mediaDir,`${c}${Gs(i.contentFile)||".bin"}`);await xo(this.mediaDir,{recursive:!0});try{await Ti(d)}catch{let u=`${d}.part`;await Pn(u,s),await Tn(u,d)}(t[n.annotationId]??=[]).push({id:i.id,name:i.name,mimeType:i.mimeType,size:i.size,kind:i.kind,path:d}),i.releasedAt=Date.now(),i.lastSeenAt=Date.now(),await this.writeManifest(i)}return t}async sweep(e=Date.now()){let t;try{t=await ki(this.draftsDir)}catch{return}await Promise.all(t.map(async n=>{let i=Ke(this.draftsDir,n);if(n.endsWith(".part")){let c=await Ti(i).catch(()=>null);c&&e-c.mtimeMs>Vs&&await Rn(i).catch(()=>{});return}if(!n.endsWith(".json"))return;let r=await this.readManifest(n.slice(0,-5));!r||!(r.releasedAt?e-r.releasedAt>Hs:e-r.lastSeenAt>Ws)||await Promise.all([Rn(i).catch(()=>{}),Rn(Ke(this.draftsDir,r.contentFile)).catch(()=>{})])}))}async cleanupPartials(){let e;try{e=await ki(this.draftsDir)}catch{return}await Promise.all(e.filter(t=>t.endsWith(".part")).map(t=>Rn(Ke(this.draftsDir,t)).catch(()=>{})))}async readManifest(e){if(!/^[a-f0-9-]{36}$/i.test(e))return null;try{return JSON.parse(await Si(Ke(this.draftsDir,`${e}.json`),"utf8"))}catch{return null}}async writeManifest(e){await xo(this.draftsDir,{recursive:!0});let t=Ke(this.draftsDir,`${e.id}.json`),n=`${t}.part`;await Pn(n,JSON.stringify(e,null,2)),await Tn(n,t)}};import{randomUUID as Ri}from"crypto";import{mkdir as So,readFile as ko,writeFile as An}from"fs/promises";import{dirname as To,join as Et}from"path";var Qe="[ProjectionWorker]",Xs={version:1,runs:[]},Ys={version:1,updatedAt:0,proposals:[]},Zs=12;function ea(o){return Array.isArray(o)?o.map((e,t)=>typeof e=="string"?{id:Math.random().toString(16).slice(2,10),scope:"general",text:e,sources:[]}:e&&typeof e=="object"&&typeof e.text=="string"?e:{id:Math.random().toString(16).slice(2,10),scope:"general",text:String(e),sources:[]}):[]}function Pi(o){let e=[];for(let t of o){if(!t||typeof t!="object")continue;let n=t;if(typeof n.id!="string"||typeof n.text!="string"){console.warn(`${Qe} Dropping rule missing id or text:`,JSON.stringify(t).slice(0,120));continue}e.push({id:n.id,scope:typeof n.scope=="string"?n.scope:"general",text:n.text,sources:Array.isArray(n.sources)?n.sources.filter(i=>typeof i=="string"):[]})}return e.length>30&&console.warn(`${Qe} Rule count ${e.length} exceeds cap of 30`),e}function ta(o,e,t){return{decisionCount:o.length,totalCandidateDecisionCount:e,promptChars:t.length,estimatedTokens:Math.ceil(t.length/4)}}function na(o,e,t){let n=new Set(e),i=new Set,r=Array.isArray(o.rules)?o.rules:[];for(let x of r){if(!x||typeof x!="object")continue;let p=x.sources;if(Array.isArray(p))for(let l of p)typeof l=="string"&&n.has(l)&&i.add(l)}let s=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?o.tokens:{},c=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?o.components:{},d=Array.isArray(t?.rules)?t.rules:[],u=r.filter(x=>{if(!x||typeof x!="object")return!1;let p=x.id,l=typeof p=="string"?d.find(f=>f&&typeof f=="object"&&f.id===p):void 0;return JSON.stringify(l)!==JSON.stringify(x)}).length,I=t?.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},T=t?.components&&typeof t.components=="object"&&!Array.isArray(t.components)?t.components:{},k=Object.keys(s).filter(x=>JSON.stringify(s[x])!==JSON.stringify(I[x])).length,P=Object.keys(c).filter(x=>JSON.stringify(c[x])!==JSON.stringify(T[x])).length;return{ruleCount:u,tokenSectionCount:k,componentCount:P,coveredDecisionIds:[...i],uncoveredDecisionIds:e.filter(x=>!i.has(x))}}function oa(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ia(o,e,t){let n=o[e];if(n&&typeof n=="object")return n;let i=typeof t=="number"?[]:{};return o[String(e)]=i,i}function Mn(o,e,t){let n=o;for(let r=0;r<e.length-1;r++)n=ia(n,e[r],e[r+1]);let i=e[e.length-1];n[String(i)]=oa(t)}function ji(o,e){let t=o;for(let i=0;i<e.length-1;i++){let r=t[String(e[i])];if(!r||typeof r!="object")return;t=r}let n=e[e.length-1];Array.isArray(t)&&typeof n=="number"?t.splice(n,1):delete t[String(n)]}function ra(o,e){if(!o)return{exists:!1};let t=o;for(let n of e){if(!t||typeof t!="object"||!(String(n)in t))return{exists:!1};t=t[String(n)]}return{exists:!0,value:t}}function sa(o,e){return Array.isArray(e)?o===void 0?e.length>0:!Array.isArray(o)||e.length<=o.length?!1:o.every((t,n)=>JSON.stringify(t)===JSON.stringify(e[n])):!1}function Ai(o,e){if(o.authorityStatus!=="accepted"||!o.changes?.length)return null;for(let t of o.changes){let n=ra(e,t.path);if(!(t.path.length===1&&t.path[0]==="rules"?sa(n.exists?n.value:void 0,t.value):!n.exists))return null}return o.changes}var En=class{constructor(e,t={}){this.projectRoot=e;this.options=t;this.running=!1;let n=Et(e,".popmelt");this.runsPath=Et(n,"projection-runs.json"),this.legacyRunsPath=Et(n,"materialization-runs.json"),this.proposalsPath=Et(n,"projection-queue.json"),this.legacyProposalsPath=Et(n,"model-proposals.json"),this.modelPath=Et(n,"model-v2.json")}get isRunning(){return this.running}async loadModel(){try{let e=await ko(this.modelPath,"utf-8"),t=JSON.parse(e);return Array.isArray(t.rules)&&(t.rules=ea(t.rules)),t}catch{return null}}async applyCanonicalEntries(e){let t={tokens:{},components:{},rules:[]};for(let n of e){let i=n.key.split(".");n.value===null?ji(t,i):Mn(t,i,n.value)}await this.writeModel(t)}async getUnprojectedPatternDecisions(){return(await this.selectUnprojectedPatternDecisions()).decisions}async selectUnprojectedPatternDecisions(){if(!this.options.loadProjectableDecisions)return{decisions:[],totalCandidateDecisionCount:0};let e=await this.options.loadProjectableDecisions(Zs),t=new Set((await this.loadModelProposals()).proposals.flatMap(i=>i.status==="pending"&&i.authorityStatus==="accepted"?i.decisionIds:[]));return{decisions:e.filter(i=>!t.has(i.id)),totalCandidateDecisionCount:e.length}}async run(e={}){if(this.running)return{processedIds:[],success:!0,error:"Already running"};this.running=!0;let t;try{let n=await this.selectUnprojectedPatternDecisions(),i=n.decisions;if(i.length===0)return{processedIds:[],success:!0};let r=i.map(x=>x.id);console.log(`${Qe} Processing ${r.length} pattern-scoped decision(s): ${r.join(", ")}`),this.options.onEvent?.({type:"projection_started",decisionIds:r});let s=await this.loadModel(),c=la(i,s),d=ta(i,n.totalCandidateDecisionCount,c);t=Ri().slice(0,8);let u={id:t,status:"running",provider:e.provider??this.options.provider??"claude",model:e.model??this.options.model,threadId:e.threadId,presentationJobId:e.presentationJobId,decisionIds:r,startedAt:Date.now(),promptStats:d};await this.persistRun(u);let I=!0,T,k,P;try{let x=`projection-${Date.now()}`,{provider:p,result:l}=this.spawnModelAgent(x,c,e,{maxTurns:this.options.maxTurns??5,maxBudgetUsd:this.options.maxBudgetUsd??.5,allowedTools:["Read"]});u={...u,provider:p},await this.persistRun(u);let f=await l;if(!f.success)I=!1,T=f.error,console.error(`${Qe} ${p} spawn error:`,T);else{let m=da(f.text,r);if(m){let h=structuredClone(s??{tokens:{},components:{},rules:[]});for(let g of m)Mn(h,g.path,g.value);Array.isArray(h.rules)&&(h.rules=Pi(h.rules));let j=na(h,r,s);if(m){let g=[...new Set(m.flatMap(B=>B.decisionIds))];j.coveredDecisionIds=g,j.uncoveredDecisionIds=r.filter(B=>!g.includes(B))}k=j;let b=await this.createModelProposal({decisionIds:r,proposedModel:h,runId:t,threadId:e.threadId,presentationJobId:e.presentationJobId,provider:p,model:e.model??this.options.model,outputStats:k,changes:m});P=b.id,console.log(`${Qe} Created model proposal ${b.id} for ${r.length} decision(s)`)}else I=!1,T="No valid bounded <model-changes> block found in response",console.error(`${Qe} ${T}`)}}catch(x){I=!1,T=x instanceof Error?x.message:String(x),console.error(`${Qe} Error:`,T)}return await this.persistRun({...u,status:I?"proposed":"failed",completedAt:Date.now(),error:T,outputStats:k,proposalId:P}),this.options.onEvent?.({type:"projection_done",decisionIds:r,success:I,error:T}),{processedIds:r,success:I,error:T,runId:t,proposalId:P}}finally{this.running=!1}}async writeModel(e){Array.isArray(e.rules)&&(e.rules=Pi(e.rules)),await An(this.modelPath,JSON.stringify(e,null,2)),console.log(`${Qe} Model written \u2192 ${this.modelPath}`)}async loadRuns(){let e=await this.readRunStore(this.runsPath);if(e)return e;let t=await this.readRunStore(this.legacyRunsPath);return t?(await So(To(this.runsPath),{recursive:!0}),await An(this.runsPath,JSON.stringify(t,null,2)),t):{...Xs,runs:[]}}async loadModelProposals(){let e=await this.readProposalStore(this.proposalsPath);if(!e){let i=await this.readProposalStore(this.legacyProposalsPath);i&&(e={version:1,updatedAt:Date.now(),proposals:i.proposals.filter(r=>r.authorityStatus==="accepted"&&Array.isArray(r.changes)&&r.changes.length>0)},await this.persistModelProposals(e))}let t=e??{...Ys,proposals:[]},n=await this.loadModel()??{tokens:{},components:{},rules:[]};return{...t,proposals:t.proposals.map(i=>{if(i.proposedModel)return i;let r=structuredClone(n);for(let s of i.changes??[])Mn(r,s.path,s.value);return{...i,proposedModel:r}})}}async findModelProposal(e){return(await this.loadModelProposals()).proposals.find(n=>n.id===e)??null}async findModelProposalByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>i.updatedAt-n.updatedAt)[0]??null}async findModelProposalsByThread(e){return(await this.loadModelProposals()).proposals.filter(n=>n.threadId===e).sort((n,i)=>n.createdAt-i.createdAt||n.updatedAt-i.updatedAt)}async applySelectedModelProposal(e,t,n,i="confirmed"){let r=await this.findModelProposal(e);if(!r)return null;if(r.status==="dismissed")return r;let s=await this.loadModel()??{};for(let d of t)!Array.isArray(d.path)||d.path.length===0||(d.remove?ji(s,d.path):Mn(s,d.path,d.value));return await this.writeModel(s),await this.updateModelProposal(e,{status:"applied",appliedAt:Date.now(),applicationMode:i,error:void 0,selectedChanges:n})}async dismissModelProposal(e){return await this.findModelProposal(e)?await this.updateModelProposal(e,{status:"dismissed",dismissedAt:Date.now()}):null}async createModelProposal(e){let t={id:Ri().slice(0,8),status:"pending",title:aa(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"}.`:ca(e.proposedModel,e.decisionIds),decisionIds:e.decisionIds,threadId:e.threadId,runId:e.runId,presentationJobId:e.presentationJobId,authorityStatus:"accepted",provider:e.provider,model:e.model,proposedModel:e.proposedModel,changes:e.changes,createdAt:Date.now(),updatedAt:Date.now()},n=await this.loadModelProposals();return n.proposals=[t,...n.proposals.filter(i=>i.id!==t.id)].slice(0,100),n.updatedAt=Date.now(),await this.persistModelProposals(n),t}async updateModelProposal(e,t){let n=await this.loadModelProposals(),i=null;return n.proposals=n.proposals.map(r=>r.id!==e?r:(i={...r,...t,updatedAt:Date.now()},i)),i?(n.updatedAt=Date.now(),await this.persistModelProposals(n),i):null}async persistModelProposals(e){try{await So(To(this.proposalsPath),{recursive:!0});let t={...e,proposals:e.proposals.map(({proposedModel:n,...i})=>i)};await An(this.proposalsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} Failed to write model proposals:`,t)}}async persistRun(e){try{let t=await this.loadRuns(),n=t.runs.findIndex(i=>i.id===e.id);n>=0?t.runs[n]=e:t.runs.push(e),await So(To(this.runsPath),{recursive:!0}),await An(this.runsPath,JSON.stringify(t,null,2))}catch(t){console.error(`${Qe} Failed to write projection run:`,t)}}async readRunStore(e){try{let t=JSON.parse(await ko(e,"utf8"));return t?.version===1&&Array.isArray(t.runs)?t:null}catch{return null}}async readProposalStore(e){try{let t=JSON.parse(await ko(e,"utf8"));return t?.version===1&&Array.isArray(t.proposals)?t:null}catch{return null}}spawnModelAgent(e,t,n,i){let r=n.provider??this.options.provider??"claude",s=this.options.onEvent?(c,d)=>this.options.onEvent?.(c):void 0;return r==="codex"?{provider:"codex",...Sn(e,{prompt:t,projectRoot:this.projectRoot,model:n.model??this.options.model,configOverrides:wn(n.agentSettings),timeoutMs:this.options.timeoutMs,sandboxMode:"read-only",onEvent:s})}:(r==="copilot"&&console.warn(`${Qe} Copilot projection is not available yet; falling back to Claude.`),{provider:"claude",...bn(e,{prompt:t,projectRoot:this.projectRoot,maxTurns:i.maxTurns,maxBudgetUsd:i.maxBudgetUsd,allowedTools:i.allowedTools,claudePath:this.options.claudePath??"claude",model:r==="claude"?n.model??this.options.model:void 0,reasoningEffort:n.agentSettings?.reasoningEffort,timeoutMs:this.options.timeoutMs,onEvent:s})})}};function aa(o){let t=(Array.isArray(o.rules)?o.rules:[]).find(i=>i&&typeof i=="object"&&typeof i.text=="string");if(typeof t?.text=="string"&&t.text.trim())return t.text.trim().replace(/\.$/,"").slice(0,72);let n=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components):[];return n.length>0?`Model update for ${n[0]}`:"Model update"}function ca(o,e){let t=Array.isArray(o.rules)?o.rules.length:0,n=o.tokens&&typeof o.tokens=="object"&&!Array.isArray(o.tokens)?Object.keys(o.tokens).length:0,i=o.components&&typeof o.components=="object"&&!Array.isArray(o.components)?Object.keys(o.components).length:0;return`Proposes ${t} rule${t===1?"":"s"}, ${i} component entr${i===1?"y":"ies"}, and ${n} token section${n===1?"":"s"} from ${e.length} decision${e.length===1?"":"s"}.`}function da(o,e){let t=o.match(/<model-changes>\s*([\s\S]*?)\s*<\/model-changes>/);if(!t?.[1])return null;try{let n=JSON.parse(t[1]);if(!Array.isArray(n)||n.length===0||n.length>40)return null;let i=new Set(e),r=n.flatMap((s,c)=>{if(!s||typeof s!="object"||Array.isArray(s))return[];let d=s;if(!Array.isArray(d.path)||d.path.length===0||!d.path.every(T=>typeof T=="string"||typeof T=="number")||typeof d.rationale!="string"||!d.rationale.trim())return[];let u=d.path[0];if(u!=="tokens"&&u!=="components"&&u!=="rules")return[];if(u==="rules"&&(d.path.length!==1||!Array.isArray(d.value)))return[];if(!Object.prototype.hasOwnProperty.call(d,"value")||d.value===void 0)return[];let I=Array.isArray(d.decisionIds)?d.decisionIds.filter(T=>typeof T=="string"&&i.has(T)):[];return I.length===0?[]:[{id:typeof d.id=="string"&&d.id?d.id:`change-${c+1}`,path:d.path,value:d.value,decisionIds:I,rationale:d.rationale,label:typeof d.label=="string"?d.label:void 0}]});return r.length===n.length?r:null}catch{return null}}function la(o,e){let t=o.map(r=>`### Accepted decision ${r.id} (${r.createdAt})
|
|
40
|
+
Kind: ${r.kind}
|
|
41
|
+
Claim: ${r.claim}
|
|
42
|
+
${r.rationale?`Rationale: ${r.rationale}`:""}
|
|
43
|
+
Subjects: ${r.subjects.map(s=>`${s.role}:${s.subjectId}`).join(", ")}
|
|
44
|
+
Authority: ${r.authority.level}/${r.authority.mode}`).join(`
|
|
45
|
+
|
|
46
|
+
`),n=o.map(r=>r.id);return`You are extracting a local design model from accumulated design decisions.
|
|
42
47
|
|
|
43
48
|
## Instructions
|
|
44
49
|
1. Review the current model (if any) and the new decisions below.
|
|
@@ -55,7 +60,7 @@ ${JSON.stringify(e,null,2)}
|
|
|
55
60
|
Use this only to understand the existing state and avoid proposing unchanged values.`:"No model exists yet. Propose only the entries directly supported by the accepted decisions below."}
|
|
56
61
|
|
|
57
62
|
## Accepted Decisions to Project
|
|
58
|
-
${
|
|
63
|
+
${t}
|
|
59
64
|
|
|
60
65
|
## Output Format
|
|
61
66
|
Each change is a JSON object with:
|
|
@@ -63,7 +68,7 @@ Each change is a JSON object with:
|
|
|
63
68
|
- \`path\`: JSON path in the derived model; the first segment must be \`tokens\`, \`components\`, or \`rules\`
|
|
64
69
|
- \`label\`: short human-readable label
|
|
65
70
|
- \`value\`: complete JSON value to set at that path
|
|
66
|
-
- \`decisionIds\`: one or more IDs from ${JSON.stringify(
|
|
71
|
+
- \`decisionIds\`: one or more IDs from ${JSON.stringify(n)} that directly support the change
|
|
67
72
|
- \`rationale\`: concise explanation of the projection from decision to model entry
|
|
68
73
|
|
|
69
74
|
For tokens and components, choose the narrowest durable path. For rules, emit a single change at path \`["rules"]\` whose value is the complete next rules array. Preserve unchanged rule IDs and order, and keep the array at 30 rules maximum.
|
|
@@ -78,7 +83,7 @@ Fields:
|
|
|
78
83
|
- \`id\`: 8-character hex string. Preserve IDs for unchanged rules. Generate new IDs for new or merged rules.
|
|
79
84
|
- \`scope\`: One of: typography, color, spacing, border, component, layout, copy, ssr, accessibility, structure
|
|
80
85
|
- \`text\`: A clear, enforceable design rule
|
|
81
|
-
- \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(
|
|
86
|
+
- \`sources\`: Array of decision IDs that informed this rule. For new rules from these decisions, use: ${JSON.stringify(n)}
|
|
82
87
|
|
|
83
88
|
### Rule guidelines
|
|
84
89
|
- **Hard cap: 30 rules maximum.** Merge rules covering the same concern into one.
|
|
@@ -93,7 +98,7 @@ Example:
|
|
|
93
98
|
"path": ["tokens", "colors", "primary"],
|
|
94
99
|
"label": "Primary color",
|
|
95
100
|
"value": "#3b82f6",
|
|
96
|
-
"decisionIds": [${JSON.stringify(
|
|
101
|
+
"decisionIds": [${JSON.stringify(n[0]??"")}],
|
|
97
102
|
"rationale": "The accepted decision establishes this as the shared primary action color."
|
|
98
103
|
}
|
|
99
104
|
]
|
|
@@ -110,15 +115,15 @@ Example:
|
|
|
110
115
|
{ "value": "8px", "property": "gap", "bindings": ["gap-2"] }
|
|
111
116
|
- property: "gap", "padding", or "margin" \u2014 which CSS property this token controls
|
|
112
117
|
- bindings: Tailwind class names (without responsive prefixes) that use this token
|
|
113
|
-
Include property and bindings when the decision context has class-level evidence.`}var
|
|
114
|
-
`),
|
|
115
|
-
`)}),
|
|
116
|
-
`)}),
|
|
117
|
-
`)}),
|
|
118
|
-
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function
|
|
118
|
+
Include property and bindings when the decision context has class-level evidence.`}var _n=class{constructor(){this.queue=[];this.activeJob=null;this.listeners=new Set;this.processor=null}setProcessor(e){this.processor=e}get active(){return this.activeJob}get allActive(){return this.activeJob?[this.activeJob]:[]}get depth(){return this.queue.length}get isRunning(){return this.activeJob!==null}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+(this.activeJob?1:0)}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){for(let i of this.listeners)i(e,t,n)}cancelJob(e){let t=this.queue.findIndex(i=>i.id===e);if(t>=0){let[i]=this.queue.splice(t,1);return i?(i.status="cancelled",i.error="Cancelled by user",this.broadcast({type:"error",jobId:i.id,threadId:i.threadId,message:i.error,cancelled:!0,provider:i.provider,model:i.model},i.id,i.sourceId),i):null}let n=this.activeJob;return!n||n.id!==e?null:(n.status="cancelled",n.error="Cancelled by user",this.activeJob=null,this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:n.error,cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.queue.length===0&&this.broadcast({type:"queue_drained"},n.id),this.processNext(),n)}cancelActive(){return this.activeJob?this.cancelJob(this.activeJob.id):null}destroy(){this.queue=[],this.activeJob&&(this.activeJob.status="cancelled",this.activeJob.error="Bridge shutting down",this.activeJob=null),this.listeners.clear()}processNext(){if(this.activeJob||this.queue.length===0||!this.processor)return;let e=this.queue.shift();this.activeJob=e,e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:"#000000",kind:"project_model",global:e.standalone===!0},e.id,e.sourceId),this.processor(e).catch(t=>{e.status!=="cancelled"&&(e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId))}).finally(()=>{this.activeJob?.id===e.id&&(this.activeJob=null),!this.activeJob&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id),this.processNext()})}};import{execFile as pa}from"child_process";import{readFile as _i}from"fs/promises";import{homedir as Po}from"os";import{join as Ye}from"path";var jo=/popmelt/i;function It(){return{found:!1,name:null,scope:null,disabled:!1}}function _t(o,e,t=!1){return{found:!0,name:o,scope:e,disabled:t}}function en(o){for(let e of Object.keys(o))if(jo.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 Ao(o){let e=Po(),t=await $n(Ye(e,".claude.json"));if(t&&typeof t=="object"){let i=t;if(i.mcpServers&&typeof i.mcpServers=="object"){let r=en(i.mcpServers);if(r)return _t(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 u=Array.isArray(c.disabledMcpjsonServers)&&c.disabledMcpjsonServers.some(I=>jo.test(I));return _t(d,"project",u)}}}}}let n=await $n(Ye(o,".mcp.json"));if(n&&typeof n=="object"){let i=n;if(i.mcpServers&&typeof i.mcpServers=="object"){let s=en(i.mcpServers);if(s){let c=await Mi(o,s);return _t(s,"mcp.json",c)}}let r=en(i);if(r&&r!=="mcpServers"){let s=await Mi(o,r);return _t(r,"mcp.json",s)}}return It()}async function Mi(o,e){let t=Ye(o,".claude","settings.local.json"),n=await $n(t);if(n&&typeof n=="object"){let i=n;if(Array.isArray(i.disabledMcpjsonServers))return i.disabledMcpjsonServers.some(r=>r===e)}return!1}var ua=/^\[mcp_servers\.([^\]]+)\]/;function ma(o){let e=o.split(`
|
|
119
|
+
`),t=[],n=null;for(let i of e){let r=i.match(ua);r?(n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
120
|
+
`)}),n={name:r[1],bodyLines:[]}):i.startsWith("[")?n&&(t.push({name:n.name,body:n.bodyLines.join(`
|
|
121
|
+
`)}),n=null):n&&n.bodyLines.push(i)}return n&&t.push({name:n.name,body:n.bodyLines.join(`
|
|
122
|
+
`)}),t}function fa(o){return/enabled\s*=\s*false/i.test(o)}async function Mo(o){let e=process.env.CODEX_HOME||Ye(Po(),".codex"),t=await Ei(Ye(e,"config.toml"),"user");if(t.found)return t;let n=await Ei(Ye(o,".codex","config.toml"),"project");return n.found?n:It()}async function Eo(o,e="copilot"){let t=await ha(e);if(t.found)return t;let n=process.env.COPILOT_HOME||Ye(Po(),".copilot"),i=await Ro(Ye(n,"mcp-config.json"),"user");if(i.found)return i;let r=await Ro(Ye(o,".mcp.json"),"mcp.json");if(r.found)return r;let s=await Ro(Ye(o,".github","mcp.json"),"mcp.json");return s.found?s:It()}async function ha(o){try{let e=await new Promise((t,n)=>{pa(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return $i(JSON.parse(e),"user")}catch{return It()}}async function Ro(o,e){let t=await $n(o);return $i(t,e)}function $i(o,e){if(!o||typeof o!="object")return It();let t=o,n=t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:t.servers&&typeof t.servers=="object"?t.servers:t,i=en(n);return i?_t(i,e):It()}async function Ei(o,e){try{let t=await _i(o,"utf-8"),n=ma(t);for(let i of n)if(jo.test(i.name)){let r=fa(i.body);return _t(i.name,e,r)}}catch{}return It()}import{execFile as Ci}from"child_process";import{mkdir as ga,readFile as Oi,writeFile as Di}from"fs/promises";import{homedir as Ni}from"os";import{dirname as ya,join as _o}from"path";var $o="https://mcp.popmelt.com/mcp";async function Ji(o=$o){let e=_o(Ni(),".claude.json"),t;try{let i=await Oi(e,"utf-8");t=JSON.parse(i)}catch{t={}}(!t.mcpServers||typeof t.mcpServers!="object")&&(t.mcpServers={});let n=t.mcpServers;for(let i of Object.keys(n))if(/popmelt/i.test(i))return{installed:!1,provider:"claude",scope:null,reason:"already_configured"};return n.popmelt={type:"http",url:o},await Di(e,JSON.stringify(t,null,2)+`
|
|
123
|
+
`,"utf-8"),{installed:!0,provider:"claude",scope:"user"}}async function Bi(o=$o){let e=process.env.CODEX_HOME||_o(Ni(),".codex"),t=_o(e,"config.toml"),n;try{n=await Oi(t,"utf-8")}catch{n=""}if(/\[mcp_servers\.[^\]]*popmelt[^\]]*\]/i.test(n))return{installed:!1,provider:"codex",scope:null,reason:"already_configured"};await ga(ya(t),{recursive:!0});let i=`
|
|
119
124
|
[mcp_servers.popmelt]
|
|
120
125
|
url = "${o}"
|
|
121
|
-
`;return await
|
|
126
|
+
`;return await Di(t,n+i,"utf-8"),{installed:!0,provider:"codex",scope:"user"}}async function Li(o=$o,e="copilot"){let t=await va(e);if(Ia(t))return{installed:!1,provider:"copilot",scope:null,reason:"already_configured"};try{return await new Promise((n,i)=>{Ci(e,["mcp","add","--transport","http","--json","popmelt",o],{encoding:"utf-8",timeout:1e4},r=>{if(r){i(r);return}n()})}),{installed:!0,provider:"copilot",scope:"user"}}catch(n){return{installed:!1,provider:"copilot",scope:null,reason:n instanceof Error?n.message:"install_failed"}}}async function va(o){try{let e=await new Promise((t,n)=>{Ci(o,["mcp","list","--json"],{encoding:"utf-8",timeout:5e3},(i,r)=>{if(i){n(i);return}t(r)})});return JSON.parse(e)}catch{return null}}function Ia(o){if(!o||typeof o!="object")return!1;let e=o,t=e.mcpServers&&typeof e.mcpServers=="object"?e.mcpServers:e;return Object.keys(t).some(n=>/popmelt/i.test(n))}var 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 t of this.leases.values())(e===null||t.expiresAt<e)&&(e=t.expiresAt);return e}acquire(e,t,n=Date.now()){let i=this.leases.get(e),r={id:e,ownerPid:t,createdAt:i?.createdAt??n,expiresAt:n+this.ttlMs};return this.activated=!0,this.leases.set(e,r),r}heartbeat(e,t=Date.now()){let n=this.leases.get(e);return n?(n.expiresAt=t+this.ttlMs,n):null}release(e){let t=this.leases.delete(e);return{found:t,becameEmpty:t&&this.activated&&this.leases.size===0}}expireStale(e=Date.now()){let t=[];for(let[n,i]of this.leases)i.expiresAt>e||(this.leases.delete(n),t.push(n));return{expiredIds:t,becameEmpty:t.length>0&&this.activated&&this.leases.size===0}}list(){return Array.from(this.leases.values()).map(e=>({...e}))}clear(){this.leases.clear()}};var wa=String.raw`
|
|
122
127
|
(() => {
|
|
123
128
|
const hidden = [];
|
|
124
129
|
const visit = (root) => {
|
|
@@ -139,7 +144,7 @@ url = "${o}"
|
|
|
139
144
|
visit(document);
|
|
140
145
|
window.__popmeltNativeCaptureHidden = hidden;
|
|
141
146
|
})()
|
|
142
|
-
`,
|
|
147
|
+
`,ba=String.raw`
|
|
143
148
|
(() => {
|
|
144
149
|
for (const [element, value, priority] of window.__popmeltNativeCaptureHidden || []) {
|
|
145
150
|
if (value) element.style.setProperty('visibility', value, priority);
|
|
@@ -147,63 +152,68 @@ url = "${o}"
|
|
|
147
152
|
}
|
|
148
153
|
delete window.__popmeltNativeCaptureHidden;
|
|
149
154
|
})()
|
|
150
|
-
`;function Rn(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function Us(o,e){let n=Rn(e);if(!n)return null;let t=new URL(n),r=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&Rn(s.url)),i=r.find(s=>Rn(s.url)===n);return i||(r.find(s=>{let c=new URL(Rn(s.url));return c.origin===t.origin&&c.pathname===t.pathname})??null)}function qs(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 zs(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 Gs(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 Ws(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}),p=>{p&&(clearTimeout(d),n.delete(c),s(p))})})}async function wr(o,e){let n=qs(e.clip),t=await zs(o),r=Us(t,e.pageUrl);if(!r?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let i=await Gs(r.webSocketDebuggerUrl),s=Ws(i),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:Ls,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:Fs,returnByValue:!0}).catch(()=>{}),i.close()}}import{mkdir as Cr,readFile as Kt,writeFile as $r}from"fs/promises";import{join as jt}from"path";var Hs=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Io(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Tn(o){return new Set(Io(o).split(" ").filter(e=>e.length>2&&!Hs.has(e)))}function Ir(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 Vs(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 Ks(o,e){let n=new Map,t=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Io).filter(Boolean),i=Tn([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 Vs(s)){let p=Io(d.value);for(let T of r){let b=p===T?95:p.includes(T)||T.includes(p)?75:0;b>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:b>=90?"exact":"strong",matchedBy:d.by,score:b})}let j=["/","#","[","]","="].some(T=>d.value.includes(T))?0:Math.round(Ir(Tn(p),i)*55);j>=30&&j>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:j>=45?"strong":"weak",matchedBy:"query_text",score:j})}c&&n.set(s.id,c)}return n}function Qs(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 Xs(o){return Math.ceil(JSON.stringify(o).length/4)}function Wt(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=Ks(n,e),d=[...c.values()].sort((v,w)=>w.score-v.score),p=Tn([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(Ir(Tn(v.claim),p)*35),P=m+u;return P>=50?[{proposal:v,proposalMatches:w,score:P}]:[]}).sort((v,w)=>w.score-v.score||v.proposal.id.localeCompare(w.proposal.id)),j=Math.max(1,e.maxPackets??3),T=Math.max(200,e.maxEstimatedTokens??1200),b=[],h=0;for(let v of x){if(b.length>=j)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(P=>P.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:v.proposalMatches.map(({score:P,...E})=>E)},proposal:{id:v.proposal.id,claim:v.proposal.claim,state:v.proposal.state,proposedKind:v.proposal.proposedKind,subjectIds:v.proposal.subjects.map(P=>P.subjectId),origin:v.proposal.origin.mode},authority:"unaccepted",presentation:v.score>=100&&["constraint","rule"].includes(v.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Qs(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:Xs(m)};if(h+u.estimatedTokens>T)break;b.push(u),h+=u.estimatedTokens}let l=Math.max(0,x.length-b.length);return{packets:b,subjectMatches:d.map(({score:v,...w})=>w),completeness:{status:l>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:l,maxEstimatedTokens:T,estimatedTokens:h},uncertainty:c.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}var Ys=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function bo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function jn(o){return new Set(bo(o).split(" ").filter(e=>e.length>2&&!Ys.has(e)))}function br(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,e){let n=new Set(e.subjectIds??[]),t=(e.subjectHints??[]).map(bo).filter(Boolean),r=jn([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(p=>({value:p,by:"alias"})),...s.locators.map(p=>({value:p.value,by:"locator"}))];for(let p of d){let x=bo(p.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:p.by,score:h})}let T=["/","#","[","]","="].some(b=>p.value.includes(b))?0:Math.round(br(jn(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 ea(o){return Math.ceil(JSON.stringify(o).length/4)}function kt(o,e){return o.relationshipType===e&&o.from.entityType==="decision"&&o.to.entityType==="decision"}function ta(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 na(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 xr(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"),p=o.records.filter(y=>y.recordType==="verification_attempt"),x=o.records.filter(y=>y.recordType==="freshness_signal"&&y.state==="open"),j=o.records.filter(y=>y.recordType==="evidence"),T=o.records.filter(y=>y.recordType==="model_entry"),b=Zs(r,e),h=new Map(b.map(y=>[y.subjectId,y.score])),l=jn([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(br(jn(y.claim),l)*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(!kt(y,"excepts")&&!kt(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),P=(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=>kt(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=>kt(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}]})),z=new Set(B.flatMap(A=>A.decisionIds)),W=j.filter(A=>A.sourceRefs.some(q=>q.kind==="record"&&C.has(q.id))||o.relationships.some(q=>q.relationshipType==="supports"&&q.from.entityType==="evidence"&&q.from.entityId===A.id&&q.to.entityType==="decision"&&C.has(q.to.entityId))),Y=Math.max(0,v.length-y.length),me=o.relationships.some(A=>kt(A,"contradicts")&&u(A)&&(!C.has(A.from.entityId)||!C.has(A.to.entityId))),H=L||Y>0||me,G=[];b.length===0&&(e.subjectHints?.length??0)>0?G.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):y.length===0&&G.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),B.length&&G.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:B.flatMap(A=>A.expansionRefs)}),W.some(A=>A.availability!=="available")&&G.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:W.map(A=>({kind:"record",id:A.id}))}),H&&G.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let Ie={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,...q})=>q),modelEntries:T.filter(A=>A.decisionIds.some(q=>C.has(q))).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(q=>q.subjectId),authority:A.authority,effectiveState:z.has(A.id)?"conflicted":M.has(A.id)?"excepted":"active",freshness:f.filter(q=>q.target.entityId===A.id).map(q=>q.signalType),expansionRef:{kind:"record",id:A.id}})),conflicts:B,uncertainties:G,implementation:y.map(A=>ta(A.id,d)),verification:y.map(A=>na(A.id,p,f)),evidence:W.map(A=>({evidenceId:A.id,summary:A.summary,availability:A.availability,sourceRefs:A.sourceRefs})),completeness:{status:H?"truncated":"complete",omittedDecisionCount:Y,omittedEvidenceCount:0,conflictsComplete:!me}};return Ie.budget.estimatedTokens=ea(Ie),Ie},E=P(m);for(;E.budget.estimatedTokens>n&&m.length>0;){let y=m.pop(),L=o.relationships.filter(C=>kt(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=P(m,!0)}return E}var oa=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Rt(o){return oa.test(o)}function ra(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 xo(o,e,n,t){o.push({path:e,code:n,message:t,severity:"warning"})}function Re(o,e,n){Rt(n)||Z(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Qe(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 ia={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"])},sa=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function aa(o,e,n){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.entity.entityId`,e.entity.entityId),Qe(o,`${n}.createdAt`,e.createdAt),ft(o,`${n}.authority`,e.authority);let t=ia[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(sa.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&&Qe(o,`${n}.transitionContext.revisitAfter`,s.revisitAfter)}}function ca(o,e,n,t){Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Qe(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"&&xo(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."),Qe(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."),Qe(o,`${n}.concreteBindings[${i}].createdAt`,r.createdAt),Qe(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"&&(Qe(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&&xo(o,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&xo(o,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function da(o,e,n){if(Re(o,`${n}.id`,e.id),Re(o,`${n}.projectId`,e.projectId),Re(o,`${n}.participantId`,e.participantId),Re(o,`${n}.from.entityId`,e.from.entityId),Re(o,`${n}.to.entityId`,e.to.entityId),Qe(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=[];Re(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=(l,v)=>{let w=n.get(l);w?Z(e,v,"duplicate_id",`ID is already used at ${w}.`):n.set(l,v)};o.records.forEach((l,v)=>{let w=`records[${v}]`;t(l.id,w),ca(e,l,w,o.manifest.projectId)}),o.events.forEach((l,v)=>{let w=`events[${v}]`;t(l.id,w),aa(e,l,w),l.projectId!==o.manifest.projectId&&Z(e,`${w}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((l,v)=>{let w=`relationships[${v}]`;t(l.id,w),da(e,l,w),l.projectId!==o.manifest.projectId&&Z(e,`${w}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((l,v)=>{t(l.id,`artifacts[${v}]`),Re(e,`artifacts[${v}].id`,l.id)}),o.tombstones.forEach((l,v)=>{let w=`tombstones[${v}]`;t(l.id,w),Re(e,`${w}.id`,l.id),Re(e,`${w}.objectId`,l.objectId),Re(e,`${w}.deletedById`,l.deletedById),Qe(e,`${w}.deletedAt`,l.deletedAt),ft(e,`${w}.authority`,l.authority,!0)});let r=new Set(o.records.map(l=>`${l.recordType}:${l.id}`)),i=new Set(o.tombstones.map(l=>`${l.objectType}:${l.objectId}`)),s=(l,v)=>{let w=`${l.entityType}:${l.entityId}`;!r.has(w)&&!i.has(w)&&Z(e,v,"dangling_entity_reference",`No record or tombstone exists for ${w}.`)};o.events.forEach((l,v)=>s(l.entity,`events[${v}].entity`)),o.relationships.forEach((l,v)=>{s(l.from,`relationships[${v}].from`),s(l.to,`relationships[${v}].to`)});let c=new Set(o.artifacts.map(l=>l.id)),d=(l,v)=>{c.has(l)||Z(e,v,"dangling_artifact_reference","No artifact manifest entry exists.")},p=(l,v,w)=>{!r.has(`${l}:${v}`)&&!i.has(`${l}:${v}`)&&Z(e,w,"dangling_entity_reference",`No ${l} record or tombstone exists.`)};o.records.forEach((l,v)=>{let w=`records[${v}]`;switch(l.recordType){case"authority_grant":p("participant",l.granteeId,`${w}.granteeId`),p("participant",l.grantedById,`${w}.grantedById`),l.subjectIds.forEach((m,u)=>p("subject",m,`${w}.subjectIds[${u}]`));break;case"observation":l.captureContext.subjectIds.forEach((m,u)=>p("subject",m,`${w}.captureContext.subjectIds[${u}]`)),l.captureContext.artifactIds.forEach((m,u)=>d(m,`${w}.captureContext.artifactIds[${u}]`));break;case"proposal":case"decision":l.subjects.forEach((m,u)=>p("subject",m.subjectId,`${w}.subjects[${u}].subjectId`));break;case"thread":l.messageArtifactIds.forEach((m,u)=>d(m,`${w}.messageArtifactIds[${u}]`)),l.resultRefs.forEach((m,u)=>s(m,`${w}.resultRefs[${u}]`));break;case"iteration":l.threadIds.forEach((m,u)=>p("thread",m,`${w}.threadIds[${u}]`)),l.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"evidence":l.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"advisory_explanation":l.subjectIds.forEach((m,u)=>p("subject",m,`${w}.subjectIds[${u}]`)),l.evidenceIds.forEach((m,u)=>p("evidence",m,`${w}.evidenceIds[${u}]`)),l.supersededById&&p("advisory_explanation",l.supersededById,`${w}.supersededById`);break;case"implementation_attempt":l.iterationIds.forEach((m,u)=>p("iteration",m,`${w}.iterationIds[${u}]`)),l.coverageClaims.forEach((m,u)=>p("decision",m.decisionId,`${w}.coverageClaims[${u}].decisionId`)),l.artifactIds.forEach((m,u)=>d(m,`${w}.artifactIds[${u}]`));break;case"eval_spec":l.replacesSpecId&&p("eval_spec",l.replacesSpecId,`${w}.replacesSpecId`),l.decisionIds.forEach((m,u)=>p("decision",m,`${w}.decisionIds[${u}]`)),l.subjectIds.forEach((m,u)=>p("subject",m,`${w}.subjectIds[${u}]`)),(l.dependencies??[]).forEach((m,u)=>{m.kind==="subject"&&m.subjectId&&p("subject",m.subjectId,`${w}.dependencies[${u}].subjectId`)}),(l.scenarios??[]).forEach((m,u)=>{m.subjectIds?.forEach((P,E)=>p("subject",P,`${w}.scenarios[${u}].subjectIds[${E}]`))}),l.targets.forEach((m,u)=>p(m.entityType,m.entityId,`${w}.targets[${u}]`));break;case"verification_attempt":l.evalSpecId&&p("eval_spec",l.evalSpecId,`${w}.evalSpecId`),l.targets.forEach((m,u)=>p(m.entityType,m.entityId,`${w}.targets[${u}]`)),l.evidenceIds.forEach((m,u)=>p("evidence",m,`${w}.evidenceIds[${u}]`));break;case"model_entry":l.subjectIds.forEach((m,u)=>p("subject",m,`${w}.subjectIds[${u}]`)),l.decisionIds.forEach((m,u)=>p("decision",m,`${w}.decisionIds[${u}]`));break;case"model_projection":ft(e,`${w}.authority`,l.authority,!0),p("participant",l.appliedById,`${w}.appliedById`),l.decisionIds.forEach((m,u)=>p("decision",m,`${w}.decisionIds[${u}]`)),l.entryIds.forEach((m,u)=>p("model_entry",m,`${w}.entryIds[${u}]`)),l.coverage.forEach((m,u)=>p("decision",m.decisionId,`${w}.coverage[${u}].decisionId`));break;case"freshness_signal":s(l.target,`${w}.target`),l.evidenceIds.forEach((m,u)=>p("evidence",m,`${w}.evidenceIds[${u}]`));break;default:break}});let x=new Map(o.events.map(l=>[l.id,l])),j=new Map(o.records.map(l=>[`${l.recordType}:${l.id}`,l])),T=new Map;o.events.forEach((l,v)=>{let w=`${l.entity.entityType}:${l.entity.entityId}:${l.fromState??"null"}`,m=T.get(w)??new Set;m.add(l.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(l=>l.recordType==="authority_grant"?[[l.id,l]]:[])),h=(l,v,w,m,u)=>{if(l.level!=="delegate"||!l.grantId)return;let P=b.get(l.grantId);if(!P){Z(e,u,"invalid_authority_grant","Delegated authority references a missing grant.");return}(P.granteeId!==v||P.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(P.startsAt)||P.endsAt&&E>Date.parse(P.endsAt)||P.revokedAt&&E>=Date.parse(P.revokedAt))&&Z(e,u,"inactive_authority_grant","The delegated authority grant was not active at this time."),P.subjectIds.length&&m.length&&!m.every(y=>P.subjectIds.includes(y))&&Z(e,u,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let l of o.records)l.recordType==="decision"&&h(l.authority,l.acceptedById,l.createdAt,l.subjects.map(v=>v.subjectId),`records:${l.id}.authority`);o.events.forEach((l,v)=>{let w=j.get(`${l.entity.entityType}:${l.entity.entityId}`),m=w&&"subjects"in w?w.subjects.map(u=>u.subjectId):[];h(l.authority,l.participantId,l.createdAt,m,`events[${v}].authority`)}),o.relationships.forEach((l,v)=>{if(!l.authority)return;let w=[l.from,l.to].flatMap(m=>{let u=j.get(`${m.entityType}:${m.entityId}`);return u&&"subjects"in u?u.subjects.map(P=>P.subjectId):[]});h(l.authority,l.participantId,l.createdAt,w,`relationships[${v}].authority`)});for(let l of o.records){if(l.recordType!=="decision")continue;let v=x.get(l.acceptanceEventId);(!v||v.entity.entityType!=="proposal"||v.entity.entityId!==l.proposalId||v.toState!=="accepted")&&Z(e,`records:${l.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),v&&v.participantId!==l.acceptedById&&Z(e,`records:${l.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),j.has(`proposal:${l.proposalId}`)||Z(e,`records:${l.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),l.state==="superseded"&&(o.relationships.some(m=>m.relationshipType==="supersedes"&&m.to.entityType==="decision"&&m.to.entityId===l.id)||Z(e,`records:${l.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),l.state==="revoked"&&(o.events.some(m=>m.entity.entityType==="decision"&&m.entity.entityId===l.id&&m.toState==="revoked"&&!!m.reason?.trim())||Z(e,`records:${l.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let l of o.records){if(l.recordType!=="proposal"||l.state!=="accepted")continue;o.records.some(w=>w.recordType==="decision"&&w.proposalId===l.id)||Z(e,`records:${l.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return ra(e)}function Ht(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 Sr(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 la(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 Mn(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."}),Rt(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let i of la(e))Rt(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={...Ht(o,t,e,e.eventId),entity:{entityType:"proposal",entityId:t.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Sr(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={...Ht(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={...Ht(o,i,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Sr(o,i,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: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:[p]},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={...Ht(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={...Ht(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 pa}from"crypto";import{readFile as ua,readdir as ma,realpath as fa}from"fs/promises";import{join as Vt,relative as ha}from"path";var ga=["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 Tt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function ze(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Pr(...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=pa("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 So(o,e){try{return JSON.parse(await ua(o,"utf8"))}catch(n){return e.push({severity:"warning",code:"source_unavailable",source:o,message:n instanceof Error?n.message:String(n)}),null}}function ya(o){let e=Tt(o);if(!e)return 0;let n=0,t=r=>{let i=Tt(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 va(o){let e={};for(let n of o)e[n.recordType]=(e[n.recordType]??0)+1;return e}async function gt(o){let e=[],n=await fa(o.projectRoot).catch(()=>o.projectRoot),t=Vt(n,".popmelt"),r=await So(Vt(t,"threads.json"),e),i=await So(Vt(t,"model.json"),e),s=Tt(r),c=Tt(s?.threads)??{},d=Object.entries(c).map(([q,re])=>({key:q,value:Tt(re)})).filter(q=>!!q.value),p=Vt(t,"decisions"),x=await ma(p).catch(()=>[]),j=[];for(let q of x.filter(re=>re.endsWith(".json")).sort()){let re=Tt(await So(Vt(p,q),e));re&&j.push({file:q,value:re})}let T=d.flatMap(({value:q})=>[q.createdAt,q.updatedAt]).filter(q=>typeof q=="number"&&Number.isFinite(q)),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 l=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=ze(Math.max(b,...T)),P=[],E=[],y=new Map,L=new Map,C=new Map(j.map(q=>[q.value.id??q.file.replace(/^d-|\.json$/g,""),q.value])),f=new Map,M=(q,re,ae,te,De)=>{let Oe=y.get(ae);if(Oe)return Oe;let Pe=oe(h,"artifact",q,te);return E.push({id:Pe,kind:re,mediaType:De,location:ae,availability:"available"}),y.set(ae,Pe),Pe};for(let{file:q,value:re}of j){let ae=re.id??q.replace(/^d-|\.json$/g,""),te=re.createdAt??b,De=[M(`${ae}:envelope`,"other",`.popmelt/decisions/${q}`,te,"application/json")];re.screenshotPath&&De.push(M(`${ae}:screenshot`,"screenshot",`.popmelt/${re.screenshotPath.replace(/^\.popmelt\//,"")}`,te,re.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[Oe,Pe]of(re.pastedImagePaths??[]).entries())De.push(M(`${ae}:image:${Oe}`,"image",Pe,te));f.set(ae,De)}let O=(q,re,ae)=>({id:q,schemaVersion:1,projectId:l,createdAt:u,participantId:re,sourceRefs:ae}),B=(q,re)=>{P.push(re);let ae=L.get(q)??[];ae.push(re.id),L.set(q,ae)},z=[{...O(v,v,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...O(w,w,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];P.push(...z),P.push({...O(m,v,[]),recordType:"subject",subjectType:"project",label:ha(process.cwd(),n)||n,aliases:[],locators:[{id:oe(h,"locator",n,b),kind:"project_root",value:n,status:"current",validFrom:ze(b),sourceRefs:[]}]});let W=new Map,Y=(q,re)=>{let ae=W.get(q);if(ae)return ae;let te=oe(h,"subject",q,re),De={...O(te,v,[{kind:"external",id:q}]),createdAt:ze(re),recordType:"subject",subjectType:"element",label:q,aliases:[],locators:[{id:oe(h,"locator",q,re),kind:"dom_selector",value:q,status:"current",validFrom:ze(re),sourceRefs:[{kind:"external",id:q}]}]};return P.push(De),W.set(q,te),te};for(let{key:q,value:re}of d){let ae=re.id??q,te=re.createdAt??b,De=oe(h,"thread",ae,te),Oe={kind:"thread",id:ae},Pe=[],Ge=[],ct=Array.isArray(re.messages)?re.messages:[],We,wt,It=0;ct.forEach((we,rt)=>{let Me=we.timestamp??te,tt=oe(h,"artifact",`${ae}:message:${rt}`,Me);if(Pe.push(tt),E.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ae}/messages/${rt}`,availability:"available"}),y.set(`.popmelt/threads.json#/threads/${ae}/messages/${rt}`,tt),we.screenshotPath&&M(`${ae}:message:${rt}:screenshot`,"screenshot",we.screenshotPath,Me),we.role==="human"){We=we;let Ne=we.feedbackSummary??we.replyToQuestion;if(Ne?.trim()){let Je=oe(h,"observation",`${ae}:${rt}`,Me),at=re.elementIdentifiers??[],bt={...O(Je,v,[Oe,{kind:"message",id:tt}]),createdAt:ze(Me),recordType:"observation",state:"open",statement:Ne,captureContext:{subjectIds:at.map(lt=>Y(lt,te)),artifactIds:[tt]},resolvedByIds:[]};B(ae,bt),wt=Je,Ge.push({entityType:"observation",entityId:Je})}return}if(we.role!=="assistant")return;let it=we.jobId??`${ae}:${rt}`,st=oe(h,"iteration",it,Me),dt=C.get(it),to=we.cancelled?"cancelled":we.error?"failed":we.question?"question_asked":(we.resolutions?.length??0)>0?"completed":"no_change",Bt={...O(st,w,[Oe,{kind:"message",id:tt},...(f.get(it)??[]).map(Ne=>({kind:"artifact",id:Ne}))]),createdAt:ze(Me),recordType:"iteration",threadIds:[De],startedAt:ze(We?.timestamp,Me),completedAt:ze(Me),requestSummary:Pr(We?.feedbackSummary,We?.replyToQuestion)??"[legacy request unavailable]",responseSummary:we.question??we.error??we.responseText?.slice(0,1e3),outcome:to,execution:{provider:we.provider??dt?.provider,model:we.model??dt?.model,sessionId:we.sessionId??dt?.sessionId},artifactIds:[tt,...f.get(it)??[]]};B(ae,Bt),Ge.push({entityType:"iteration",entityId:st});let Lt=we.resolutions??dt?.resolutions??[];for(let[Ne,Je]of Lt.entries()){if(Je.status!=="resolved"||!Je.summary?.trim())continue;let at=re.elementIdentifiers??[],bt=(at.length?at:[n]).map(ln=>({subjectId:ln===n?m:Y(ln,te),role:"governed"})),lt=oe(h,"proposal",`${it}:${Je.annotationId??"resolution"}:${Ne}`,Me),no={...O(lt,w,[Oe,{kind:"iteration",id:st}]),createdAt:ze(Me),recordType:"proposal",state:"pending",claim:Je.summary,subjects:bt,subjectSemantics:bt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Pr(We?.feedbackSummary,We?.replyToQuestion,Je.summary),iterationId:st,inferredById:w}};B(ae,no),Ge.push({entityType:"proposal",entityId:lt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ae,message:`Proposal ${lt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(Lt.some(Ne=>Ne.status==="resolved")||dt?.gitDiff){let Ne=oe(h,"implementation",it,Me),Je={...O(Ne,w,[Oe,{kind:"iteration",id:st}]),createdAt:ze(Me),recordType:"implementation_attempt",state:"completed",iterationIds:[st],coverageClaims:[],summary:Lt.map(at=>at.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};B(ae,Je),Ge.push({entityType:"implementation_attempt",entityId:Ne}),It+=1}wt&&(wt=void 0)});let dn=ct.at(-1),eo={...O(De,v,[Oe]),createdAt:ze(te),recordType:"thread",state:dn?.question?"open":"resolved",messageArtifactIds:Pe,outcome:dn?.question?"question_unresolved":It?"implementation_only":"no_outcome",resultRefs:Ge};P.push(eo),L.set(ae,[De,...L.get(ae)??[]])}let me=ya(i);me&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${me} model values were not promoted because their accepted decision provenance is unresolved.`});let H={manifest:{formatVersion:1,projectId:l,createdAt:ze(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:P,events:[],relationships:[],artifacts:E,tombstones:[]},G=ht(H),A=(o.proofCaseIds??ga).map(q=>({legacyId:q,threadFound:d.some(({key:re,value:ae})=>(ae.id??re)===q),decisionEnvelopeFound:C.has(q),recordIds:L.get(q)??[]}));return{bundle:H,report:{projectRoot:n,source:{threads:d.length,messages:d.reduce((q,re)=>q+(re.value.messages?.length??0),0),decisionEnvelopes:j.length,modelEntries:me,artifactsReferenced:E.length},imported:va(P),unresolvedAcceptance:e.filter(q=>q.code==="acceptance_unresolved").length,deferredModelEntries:me,proofCases:A,issues:e,schemaIssues:G.issues}}}import{createHash as wa}from"crypto";import{mkdir as kr,open as Po,readFile as ko,readdir as Ia,rename as ba,unlink as Ro}from"fs/promises";import{join as nt}from"path";var xa={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function En(o){return wa("sha256").update(JSON.stringify(o)).digest("hex")}function Rr(o){return En(o)}function Tr(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 Sa(o,e,n){return Tr(structuredClone(o),e,n)}async function yt(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await Po(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
151
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await ba(n,o)}catch(r){throw await Ro(n).catch(()=>{}),r}}async function An(o){return JSON.parse(await ko(o,"utf8"))}var _n=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=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 ko(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 ko(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=En(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 yt(this.checkpointPath,r),await yt(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 yt(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=En(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 yt(nt(this.memoryDir,t),r),e.manifest.checkpoint={file:t,sequence:r.sequence,hash:n},await yt(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(!Rt(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:Rr(i)},c=Sa(t.bundle,e,n.committedAt),d=ht(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let p=`${String(r).padStart(12,"0")}-${n.transactionId}.json`;return await yt(nt(this.journalDir,p),s),t.manifest.head={sequence:r,hash:s.hash},t.manifest.updatedAt=n.committedAt,await yt(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({...xa,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},n)}async loadInternal(){let e=await An(this.manifestPath),n=await An(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!==En(n.bundle)||n.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let t=await Ia(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,p=n.journalHash??null,x=new Set;for(let T of s){let b=await An(nt(this.journalDir,T)),{hash:h,...l}=b;if(h!==Rr(l))throw new Error(`Journal hash mismatch: ${T}`);if(b.sequence!==d+1)throw new Error(`Journal sequence gap at ${T}`);if(b.previousHash!==p)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}`);Tr(c,b.mutation,b.committedAt),d=b.sequence,p=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!==p)throw new Error("Journal manifest head hash mismatch.");let j=ht(c);if(!j.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(j.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:p}}}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 Po(this.lockPath,"wx")}catch(t){if(t.code!=="EEXIST")throw t;let r=await An(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 Ro(this.lockPath),n=await Po(this.lockPath,"wx")}try{return await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await n.close(),await Ro(this.lockPath).catch(()=>{})}}};import{randomBytes as Pa}from"crypto";function ve(o=Date.now()){let n=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),t=Pa(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 ka=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function jr(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=ka(),p=d.records,x=o.records.find(u=>u.recordType==="thread"&&u.sourceRefs.some(P=>P.kind==="thread"&&P.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:[]},p.push(x));let j=[];for(let u of[...new Set(e.subjectHints.filter(Boolean))]){let P=o.records.find(E=>E.recordType==="subject"&&E.locators.some(y=>y.value===u&&y.status==="current"));P||(P={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}]}]},p.push(P)),j.push(P)}for(let u of[...new Set((e.filePaths??[]).filter(Boolean))]){let P=o.records.find(E=>E.recordType==="subject"&&E.locators.some(y=>y.kind==="source_file"&&y.value===u&&y.status==="current"));P||(P={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}]}]},p.push(P)),j.push(P)}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(P=>P.claim.trim()).join(" "),captureContext:{subjectIds:j.map(P=>P.id),artifactIds:[]},resolvedByIds:[]};p.push(u)}let h=oe(r,"live-iteration",i,e.completedAt),l={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:[]};p.push(l);let v=[],w=e.resolutions.filter(u=>u.status==="resolved"&&u.summary.trim()),m=j.length>0?j: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,P]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:P.claim.trim(),rationale:P.rationale?.trim()||void 0,proposedKind:P.proposedKind,subjects:y,subjectSemantics:y.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:P.sourceText?.trim()||e.requestSummary,iterationId:h,inferredById:t.id}};p.push(L),v.push(E)}if(w.length>0){let u=new Set(e.governingDecisionIds??[]),P=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:P.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:[]};p.push(E)}return{mutation:d,iterationId:h,proposalIds:v,observationId:b}}import{createHash as Ra}from"crypto";import{mkdir as Ta,open as ja,readFile as Ma,rename as Aa,unlink as Ea}from"fs/promises";import{join as Mr}from"path";function Ar(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Er(o){return Ra("sha256").update(JSON.stringify(o)).digest("hex")}async function _a(o,e){let n=`${o}.${process.pid}.${Date.now()}.tmp`,t=await ja(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
152
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await Aa(n,o)}catch(r){throw await Ea(n).catch(()=>{}),r}}function Ca(o,e,n=new Date().toISOString()){let t={},r={},i={},s=(d,p,x)=>{let j=d[p]??=[];j.includes(x)||j.push(x)};for(let d of o.records)if(d.recordType==="subject"){let p=d;for(let x of[p.label,...p.aliases,...p.locators.filter(j=>j.status==="current").map(j=>j.value)]){let j=Ar(x);j&&s(t,j,p.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let p of d.subjects)s(r,p.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let p of d.subjects)s(i,p.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:n,subjectIdsByValue:t,decisionIdsBySubject:r,proposalIdsBySubject:i};return{...c,checksum:Er(c)}}function _r(o,e){let n=[...new Set(e.flatMap(t=>o.subjectIdsByValue[Ar(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 Cn=class{constructor(e){this.indexDir=Mr(e,".popmelt","memory","indexes"),this.indexPath=Mr(this.indexDir,"retrieval-v1.json")}async ensure(e,n){try{let r=JSON.parse(await Ma(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===Er(s))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let t=Ca(e,n);return await Ta(this.indexDir,{recursive:!0}),await _a(this.indexPath,t),t}};var Qt="popmelt:imprint",Dr="popmelt:imprint-evidence",Mt="popmelt:imprint-relation";function $n(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===Qt)?.id}function To(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 Dn(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 _n(e),this.indexStore=new Cn(e),this.manifestPath=jt(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 gt({...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 gt({...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=jt(this.projectRoot,".popmelt","memory","migrations"),n=jt(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(jt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!t?.explanations)return await Cr(e,{recursive:!0}),await $r(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 p=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(u=>u.id)),j=new Set(r.bundle.relationships.flatMap(u=>u.sourceRefs.flatMap(P=>P.kind==="external"&&P.uri===Mt?[P.id]:[]))),T=new Map,b=r.bundle.records.filter(u=>u.recordType==="advisory_explanation");for(let u of t.explanations){let P=b.find(E=>$n(E)===u.id);T.set(u.id,P?.id??oe(p,"imprint-explanation",u.id,Date.parse(u.createdAt)))}let h=[],l=[],v=[],w=0;for(let u of t.explanations){let P=T.get(u.id),E=b.find(f=>f.id===P),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(p,"imprint-evidence-record",f.id,Date.parse(f.createdAt));y.push(M),!x.has(M)&&(h.push({id:M,schemaVersion:1,projectId:p,createdAt:f.createdAt,participantId:c.id,sourceRefs:To([{kind:"external",id:f.id,uri:Dr},{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(p,"imprint-evidence-link",`${u.id}:${f.id}`,Date.parse(f.createdAt)),schemaVersion:1,projectId:p,createdAt:f.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:f.id,uri:Dr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:P},to:{entityType:"evidence",entityId:M},reason:"This advisory explanation was derived from collaboration evidence."}),w+=1)}let C={id:P,schemaVersion:1,projectId:p,createdAt:E?.createdAt??u.createdAt,participantId:E?.participantId??c.id,sourceRefs:To([...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:Dn(t,u.id),supersededById:u.supersededBy?T.get(u.supersededBy):void 0,updatedAt:u.updatedAt};E?l.push(C):h.push(C)}for(let u of t.relations){let P=T.get(u.fromId),E=T.get(u.toId);!P||!E||j.has(u.id)||v.push({id:oe(p,"imprint-relation",u.id,Date.parse(u.createdAt)),schemaVersion:1,projectId:p,createdAt:u.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:u.id,uri:Mt}],recordType:"relationship",relationshipType:u.type,from:{entityType:"advisory_explanation",entityId:P},to:{entityType:"advisory_explanation",entityId:E},reason:u.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(h.length||l.length||v.length)try{let u=await this.store.commit({records:h,recordReplacements:l,events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:oe(p,"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 Cr(e,{recursive:!0}),await $r(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:Wt(t.bundle,r)}}async contextualize(e,n={}){let t=await this.loadSource(n),r=await this.withIndexedCandidates(t,e);return{source:t.source,actionPacket:xr(t.bundle,r),reviewSelection:Wt(t.bundle,r)}}async planReview(e,n={}){let t=await this.loadSource(n);return{source:t.source,result:Mn(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 gt({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=Mn(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:ve(i),decisionId:ve(i),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:ve(i),replacementProposalId:ve(i),acceptanceEventId:ve(i),decisionId:ve(i),relationshipId:ve(i),claim:e.claim,kind:e.kind,subjects:t.subjects,subjectSemantics:t.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:ve(i),reason:e.reason}:{...c,action:"defer",eventId:ve(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"]}},p=Mn(n.bundle,d);if(!p.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:p.errors.map(T=>T.message).join(" ")};let x=await this.store.commitReviewPlan(p.plan,{transactionId:ve(i),committedAt:s});await this.refreshIndex(x);let j=p.plan.resultRefs.find(T=>T.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:j,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=jr(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(jt(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(),p=Date.parse(d),x=t.bundle.manifest.projectId,j=[],T=[],b=[],h=t.bundle.records.filter(m=>m.recordType==="advisory_explanation"),l=new Map(h.flatMap(m=>{let u=$n(m);return u?[[u,m.id]]:[]}));for(let m of e.summary.changes)if(!l.has(m.explanationId)){let u=n?.explanations.find(P=>P.id===m.explanationId);l.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},P=l.get(m.explanationId),E=h.find(f=>f.id===P),y=n?.explanations.find(f=>f.id===m.explanationId),L={id:oe(x,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,p),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:[]};j.push(L);let C={id:P,schemaVersion:1,projectId:x,createdAt:E?.createdAt??y?.createdAt??d,participantId:E?.participantId??s.id,sourceRefs:To([...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?Dn(n,m.explanationId):E?.concreteBindings??[],supersededById:y?.supersededBy?l.get(y.supersededBy):E?.supersededById,updatedAt:y?.updatedAt??d};E?T.push(C):j.push(C),b.push({id:oe(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,p),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===Mt?[u.id]:[])));for(let m of n?.relations??[]){let u=l.get(m.fromId),P=l.get(m.toId);!u||!P||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:Mt}],recordType:"relationship",relationshipType:m.type,from:{entityType:"advisory_explanation",entityId:u},to:{entityType:"advisory_explanation",entityId:P},reason:m.rationale||"The Imprint graph connected these explanations."})}let w=oe(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let m=await this.store.commit({records:j,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(jt(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"),p=new Map(d.flatMap(y=>{let L=$n(y);return L?[[L,y]]:[]})),x=new Map([...[...p].map(([y,L])=>[y,L.id]),...e.explanations.filter(y=>!p.has(y.id)).map(y=>[y.id,oe(c,"imprint-explanation",y.id,Date.parse(y.createdAt))])]),j=[],T=[],b=new Set(e.explanations.map(y=>y.id));for(let y of e.explanations){let L=p.get(y.id);if(!L){j.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:Dn(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:Dn(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 p)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]:[])),l=new Map(n.bundle.relationships.flatMap(y=>{if(h.has(y.id))return[];let L=y.sourceRefs.find(C=>C.kind==="external"&&C.uri===Mt)?.id;return L?[[L,y]]:[]})),v=new Set(l.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:Mt}],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?[...l].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(!j.length&&!T.length&&!w.length&&!u.length)return{status:"no_change",relationships:0,explanations:0,headSequence:n.report.headSequence};let P=e.updatedAt,E=oe(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(P));try{let y=await this.store.commit({records:j,recordReplacements:T,events:[],relationships:w,artifacts:[],tombstones:u,projectionUpdates:[]},{transactionId:E,committedAt:P});return await this.refreshIndex(y),{status:"synced",relationships:w.length+u.length,explanations:j.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(l=>l.recordType==="advisory_explanation"),i=new Map(r.map(l=>[l.id,l])),s=new Map(r.flatMap(l=>{let v=$n(l);return v?[[v,l.id]]:[]})),c=new Set(e.map(l=>s.get(l)??l)),d=new Map(t.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),p=new Map(t.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),x=new Set(t.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),j=new Set(["operationalizes","refines","supports","contradicts","excepts","instantiates","supersedes"]),T={testing:0,emerging:1,grounded:2,challenged:3,retired:4},b=r.map(l=>{let v=l.evidenceIds.flatMap(u=>{let P=p.get(u);if(!P)return[];let E=P.sourceRefs.find(f=>f.kind==="thread")?.id,y=P.sourceRefs.find(f=>f.kind==="message")?.id,L=P.kind==="judgment"||P.kind==="user_feedback"||P.kind==="project_state"?P.kind:"other",C=d.get(P.participantId)??"unknown";return[{id:P.id,kind:L,summary:P.summary,createdAt:P.createdAt,participantKind:C,threadId:E,jobId:y}]}).sort((u,P)=>P.createdAt.localeCompare(u.createdAt)),w=t.bundle.relationships.flatMap(u=>{if(x.has(u.id))return[];if(!j.has(u.relationshipType))return[];let P=u.from.entityType==="advisory_explanation"&&u.from.entityId===l.id&&u.to.entityType==="advisory_explanation",E=u.to.entityType==="advisory_explanation"&&u.to.entityId===l.id&&u.from.entityType==="advisory_explanation";if(!P&&!E)return[];let y=P?u.to.entityId:u.from.entityId,L=i.get(y);return L?[{id:u.id,type:u.relationshipType,direction:P?"outgoing":"incoming",explanationId:L.id,statement:L.statement,rationale:u.reason}]:[]}),m=[...new Set([...l.sourceRefs.flatMap(u=>u.kind==="thread"?[u.id]:[]),...v.flatMap(u=>u.threadId?[u.threadId]:[])])];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:v.length,recentEvidence:v.slice(0,4),concrete:l.concreteBindings.map(u=>({...structuredClone(u)})),relations:w,sourceThreadIds:m,needsGrounding:l.state==="testing"&&c.has(l.id)}}).sort((l,v)=>Number(v.needsGrounding)-Number(l.needsGrounding)||T[l.state]-T[v.state]||v.updatedAt.localeCompare(l.updatedAt)),h={total:b.filter(l=>l.state!=="retired").length,emerging:b.filter(l=>l.state==="emerging").length,testing:b.filter(l=>l.state==="testing").length,grounded:b.filter(l=>l.state==="grounded").length,challenged:b.filter(l=>l.state==="challenged").length,retired:b.filter(l=>l.state==="retired").length,needsGrounding:b.filter(l=>l.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,p)=>d.createdAt.localeCompare(p.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(p=>p.targets.some(x=>x.entityType==="decision"&&x.entityId===c.id)).sort((p,x)=>x.createdAt.localeCompare(p.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:r.some(p=>p.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=ve(i),d=ve(i),p=ve(i),x=ve(i),j=ve(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"}]},l=[{subjectId:r.id,role:"governed"}],v={...h,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:l,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:p,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:t.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:l,noChange:!1,effectiveAt:s},u={...h,id:x,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[p],value:e.value},P={...h,id:j,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${i}`,appliedById:t.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[p],entryIds:[x],coverage:[{decisionId:p,status:"projected"}]},E={...h,id:ve(i),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:p},reason:"The model change is projected from the owner-confirmed decision."},y=b.map(f=>({...h,id:ve(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:ve(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,P],events:[w,...y],relationships:[E,...L],artifacts:[],tombstones:[],projectionUpdates:b.map(f=>({entityType:"decision",entityId:f.id,fromState:"active",state:"superseded"}))},{transactionId:ve(i),committedAt:s});return await this.refreshIndex(C),{decisionId:p,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=ve(s),p=e.changes.map(h=>{let l=h.decisionIds?.filter(m=>e.decisionIds.includes(m)),v=l?.length?l:e.decisionIds,w=[...new Set(r.filter(m=>v.includes(m.id)).flatMap(m=>m.subjects.map(u=>u.subjectId)))];return{id:ve(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(p.flatMap(h=>h.decisionIds)),j={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:p.map(h=>h.id),coverage:e.decisionIds.map(h=>e.coverage?.find(l=>l.decisionId===h)??{decisionId:h,status:x.has(h)?"projected":"unprojected"})},T=p.flatMap(h=>h.decisionIds.map(l=>({id:ve(s),schemaVersion:1,projectId:n.bundle.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"record",id:j.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h.id},to:{entityType:"decision",entityId:l},reason:"The owner applied this model entry as a projection of accepted product truth."}))),b=await this.store.commit({records:[...p,j],events:[],relationships:T,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ve(s),committedAt:c});return await this.refreshIndex(b),{projectionId:d,entryIds:p.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 gt({...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 Et(o){if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Expected a JSON object.");return o}function Se(o,e){if(typeof o!="string"||!o.trim())throw new Error(`${e} must be a non-empty string.`);return o}function At(o,e,n){let t=Se(o,e);if(!n.includes(t))throw new Error(`${e} is invalid.`);return t}function jo(o){let e=Et(o),n=Et(e.authority),t=n.level,r=n.mode,i=At(t,"authority.level",["owner","delegate","contributor"]),s=At(r,"authority.mode",["local_trusted","hosted"]),c={proposalId:Se(e.proposalId,"proposalId"),participantId:Se(e.participantId,"participantId"),occurredAt:Se(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:Se(e.eventId,"eventId"),decisionId:Se(e.decisionId,"decisionId"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),reason:Se(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:Se(e.eventId,"eventId"),reason:Se(e.reason,"reason")};case"defer":{let d=Et(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:Se(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=>Se(p,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(p=>At(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:Se(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Se(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Se(e.acceptanceEventId,"acceptanceEventId"),decisionId:Se(e.decisionId,"decisionId"),relationshipId:Se(e.relationshipId,"relationshipId"),claim:Se(e.claim,"claim"),kind:At(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let p=Et(d);return{subjectId:Se(p.subjectId,"subjectId"),role:At(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:Se(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function Mo(o){let e=Et(o),n=(i,s)=>{if(i!==void 0){if(!Array.isArray(i))throw new Error(`${s} must be an array.`);return i.map(c=>Se(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:Et(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 Nn(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
153
|
-
`)}async function
|
|
154
|
-
`)}function
|
|
155
|
+
`;function On(o){try{let e=new URL(o);return e.hash="",e.href}catch{return null}}function xa(o,e){let t=On(e);if(!t)return null;let n=new URL(t),i=o.filter(s=>s.type==="page"&&!!s.webSocketDebuggerUrl&&On(s.url)),r=i.find(s=>On(s.url)===t);return r||(i.find(s=>{let c=new URL(On(s.url));return c.origin===n.origin&&c.pathname===n.pathname})??null)}function Sa(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,t=setTimeout(()=>e.abort(),1e3);try{let n=new URL("/json/list",o).href,i=await fetch(n,{signal:e.signal});if(!i.ok)throw new Error(`CDP discovery returned ${i.status}`);let r=await i.json();return Array.isArray(r)?r:[]}finally{clearTimeout(t)}}async function Ta(o){let{WebSocket:e}=await import("ws");return new Promise((t,n)=>{let i=new e(o,{handshakeTimeout:1e3}),r=()=>{i.off("error",s),t(i)},s=c=>{i.off("open",r),n(c)};i.once("open",r),i.once("error",s)})}function Ra(o){let e=1,t=new Map;return o.on("message",n=>{let i;try{i=JSON.parse(String(n))}catch{return}if(!i.id)return;let r=t.get(i.id);r&&(t.delete(i.id),clearTimeout(r.timeout),i.error?r.reject(new Error(i.error.message||`CDP error ${i.error.code??""}`.trim())):r.resolve(i.result??{}))}),o.on("close",()=>{for(let[n,i]of t)clearTimeout(i.timeout),i.reject(new Error("CDP connection closed")),t.delete(n)}),(n,i={})=>new Promise((r,s)=>{let c=e++,d=setTimeout(()=>{t.delete(c),s(new Error(`CDP ${n} timed out`))},4e3);t.set(c,{resolve:r,reject:s,timeout:d}),o.send(JSON.stringify({id:c,method:n,params:i}),u=>{u&&(clearTimeout(d),t.delete(c),s(u))})})}async function qi(o,e){let t=Sa(e.clip),n=await ka(o),i=xa(n,e.pageUrl);if(!i?.webSocketDebuggerUrl)throw new Error("The active development page is not available through CDP");let r=await Ta(i.webSocketDebuggerUrl),s=Ra(r),c=!1;try{await s("Page.enable"),await s("Runtime.evaluate",{expression:wa,returnByValue:!0}),c=!0;let d=await s("Page.captureScreenshot",{format:"webp",quality:80,fromSurface:!0,captureBeyondViewport:!0,clip:{...t,scale:Math.max(.25,Math.min(4,e.scale??1))}}),u=typeof d.data=="string"?d.data:"";if(!u)throw new Error("CDP returned an empty screenshot");return Buffer.from(u,"base64")}finally{c&&await s("Runtime.evaluate",{expression:ba,returnByValue:!0}).catch(()=>{}),r.close()}}import{mkdir as ir,readFile as rn,writeFile as rr}from"fs/promises";import{join as Nt}from"path";var Pa=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Co(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Dn(o){return new Set(Co(o).split(" ").filter(e=>e.length>2&&!Pa.has(e)))}function Fi(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function ja(o){return[{value:o.label,by:"label"},...o.aliases.map(e=>({value:e,by:"alias"})),...o.locators.map(e=>({value:e.value,by:"locator"}))]}function Aa(o,e){let t=new Map,n=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(Co).filter(Boolean),r=Dn([e.action,e.text].filter(Boolean).join(" "));for(let s of o){if(n.has(s.id)){t.set(s.id,{subjectId:s.id,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let d of ja(s)){let u=Co(d.value);for(let k of i){let P=u===k?95:u.includes(k)||k.includes(u)?75:0;P>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:P>=90?"exact":"strong",matchedBy:d.by,score:P})}let T=["/","#","[","]","="].some(k=>d.value.includes(k))?0:Math.round(Fi(Dn(u),r)*55);T>=30&&T>(c?.score??0)&&(c={subjectId:s.id,label:s.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}c&&t.set(s.id,c)}return t}function Ma(o,e){let t=new Set(o.sourceRefs.filter(s=>s.kind==="iteration").map(s=>s.id)),n=new Set(o.sourceRefs.filter(s=>s.kind==="thread").map(s=>s.id)),i=e.filter(s=>s.iterationIds.some(c=>t.has(c))||s.sourceRefs.some(c=>c.kind==="thread"&&n.has(c.id)));if(!i.length)return{state:"none_found",attemptIds:[]};let r=new Set(i.map(s=>s.state));return{state:r.size>1?"mixed":r.has("completed")?"completed":"attempted",attemptIds:i.map(s=>s.id)}}function Ea(o){return Math.ceil(JSON.stringify(o).length/4)}function tn(o,e){let t=o.records.filter(l=>l.recordType==="subject"),n=e.generatedAt??new Date().toISOString(),i=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,r=o.records.filter(l=>{if(l.recordType!=="proposal"||i&&!i.has(l.id))return!1;if(l.state==="pending")return!0;if(l.state!=="deferred")return!1;let f=[...o.events].reverse().find(m=>m.entity.entityType==="proposal"&&m.entity.entityId===l.id&&m.toState==="deferred"&&m.transitionContext?.kind==="proposal_deferral")?.transitionContext;return f?f.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||f.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||f.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||f.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||f.resurfaceWhen.includes("after_date")&&!!(f.revisitAfter&&Date.parse(n)>=Date.parse(f.revisitAfter)):!1}),s=o.records.filter(l=>l.recordType==="implementation_attempt"),c=Aa(t,e),d=[...c.values()].sort((l,f)=>f.score-l.score),u=Dn([e.action,e.text].filter(Boolean).join(" ")),I=r.flatMap(l=>{let f=l.subjects.map(b=>c.get(b.subjectId)).filter(b=>!!b),m=Math.max(0,...f.map(b=>b.score)),h=Math.round(Fi(Dn(l.claim),u)*35),j=m+h;return j>=50?[{proposal:l,proposalMatches:f,score:j}]:[]}).sort((l,f)=>f.score-l.score||l.proposal.id.localeCompare(f.proposal.id)),T=Math.max(1,e.maxPackets??3),k=Math.max(200,e.maxEstimatedTokens??1200),P=[],x=0;for(let l of I){if(P.length>=T)break;let f=l.proposal.sourceRefs.slice(0,4),m={contractVersion:1,packetId:`review:${l.proposal.id}`,projectId:o.manifest.projectId,generatedAt:n,trigger:{action:e.action,reason:l.proposalMatches.length?`Historical proposal intersects ${l.proposalMatches.map(j=>j.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:l.proposalMatches.map(({score:j,...b})=>b)},proposal:{id:l.proposal.id,claim:l.proposal.claim,state:l.proposal.state,proposedKind:l.proposal.proposedKind,subjectIds:l.proposal.subjects.map(j=>j.subjectId),origin:l.proposal.origin.mode},authority:"unaccepted",presentation:l.score>=100&&["constraint","rule"].includes(l.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ma(l.proposal,s),evidence:{sourceCount:l.proposal.sourceRefs.length,sourceRefs:f},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:l.proposal.id},...f]},h={...m,estimatedTokens:Ea(m)};if(x+h.estimatedTokens>k)break;P.push(h),x+=h.estimatedTokens}let p=Math.max(0,I.length-P.length);return{packets:P,subjectMatches:d.map(({score:l,...f})=>f),completeness:{status:p>0?"truncated":"complete",consideredProposalCount:I.length,omittedPacketCount:p,maxEstimatedTokens:k,estimatedTokens:x},uncertainty:c.size===0?"subject_unresolved":I.length===0?"no_relevant_pending_proposal":void 0}}var _a=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Oo(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Nn(o){return new Set(Oo(o).split(" ").filter(e=>e.length>2&&!_a.has(e)))}function Ui(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function $a(o,e){let t=new Set(e.subjectIds??[]),n=(e.subjectHints??[]).map(Oo).filter(Boolean),i=Nn([e.action,e.text].filter(Boolean).join(" ")),r=[];for(let s of o){if(t.has(s.id)){r.push({subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,d=[{value:s.label,by:"semantic"},...s.aliases.map(u=>({value:u,by:"alias"})),...s.locators.map(u=>({value:u.value,by:"locator"}))];for(let u of d){let I=Oo(u.value);for(let P of n){let x=I===P?95:I.includes(P)||P.includes(I)?75:0;x>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:x>=90?"exact":"strong",matchedBy:u.by,score:x})}let k=["/","#","[","]","="].some(P=>u.value.includes(P))?0:Math.round(Ui(Nn(I),i)*55);k>=30&&k>(c?.score??0)&&(c={subjectId:s.id,subjectType:s.subjectType,label:s.label,confidence:k>=45?"strong":"weak",matchedBy:"semantic",score:k})}c&&r.push(c)}return r.sort((s,c)=>c.score-s.score||s.subjectId.localeCompare(c.subjectId))}function Ca(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 Oa(o,e){let t=e.filter(r=>r.coverageClaims.some(s=>s.decisionId===o));if(!t.length)return{decisionId:o,state:"unimplemented",attemptIds:[]};let n=t.filter(r=>r.state==="completed"),i=n.some(r=>r.coverageClaims.some(s=>s.decisionId===o&&s.coverage==="full"));return{decisionId:o,state:i?"implemented":n.length?"partial":"unknown",attemptIds:t.map(r=>r.id)}}function Da(o,e,t){let n=e.filter(c=>c.targets.some(d=>d.entityType==="decision"&&d.entityId===o)).sort((c,d)=>d.createdAt.localeCompare(c.createdAt)),i=t.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===o),r=n[0],s=i?"stale":r?r.state==="passed"?"passing":r.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(r.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:o},state:s,attemptIds:n.map(c=>c.id)}}function zi(o,e){let t=Math.max(300,e.maxEstimatedTokens??1200),n=Math.max(1,e.maxDecisions??6),i=o.records.filter(g=>g.recordType==="subject"),r=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,s=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"),c=r?s.filter(g=>r.has(g.id)):s,d=o.records.filter(g=>g.recordType==="implementation_attempt"),u=o.records.filter(g=>g.recordType==="verification_attempt"),I=o.records.filter(g=>g.recordType==="freshness_signal"&&g.state==="open"),T=o.records.filter(g=>g.recordType==="evidence"),k=o.records.filter(g=>g.recordType==="model_entry"),P=$a(i,e),x=new Map(P.map(g=>[g.subjectId,g.score])),p=Nn([e.action,e.text].filter(Boolean).join(" ")),l=c.flatMap(g=>{let B=Math.max(0,...g.subjects.map(N=>x.get(N.subjectId)??0)),E=Math.round(Ui(Nn(g.claim),p)*35),R=B+E;return R>=50?[{decision:g,score:R}]:[]}).sort((g,B)=>B.score-g.score||g.decision.id.localeCompare(B.decision.id)),f=new Map;for(let g of l.slice(0,n))f.set(g.decision.id,g.decision);for(let g of o.relationships){if(!$t(g,"excepts")&&!$t(g,"contradicts"))continue;let B=s.find(R=>R.id===g.from.entityId),E=s.find(R=>R.id===g.to.entityId);!B||!E||!f.has(B.id)&&!f.has(E.id)||(f.size<n&&f.set(B.id,B),f.size<n&&f.set(E.id,E))}let m=[...f.values()],h=g=>g.from.entityType==="decision"&&g.to.entityType==="decision"&&f.has(g.from.entityId)&&f.has(g.to.entityId),j=(g,B=!1)=>{let E=new Set(g.map(J=>J.id)),R=I.filter(J=>J.target.entityType==="decision"&&E.has(J.target.entityId)),N=new Set(o.relationships.filter(J=>$t(J,"excepts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).flatMap(J=>[J.from.entityId,J.to.entityId])),K=o.relationships.filter(J=>$t(J,"contradicts")&&E.has(J.from.entityId)&&E.has(J.to.entityId)).map(J=>({id:J.id,decisionIds:[J.from.entityId,J.to.entityId],unresolvedQuestion:J.reason,expansionRefs:[{kind:"record",id:J.id}]})),W=new Set(K.flatMap(J=>J.decisionIds)),Q=T.filter(J=>J.sourceRefs.some(D=>D.kind==="record"&&E.has(D.id))||o.relationships.some(D=>D.relationshipType==="supports"&&D.from.entityType==="evidence"&&D.from.entityId===J.id&&D.to.entityType==="decision"&&E.has(D.to.entityId))),w=Math.max(0,l.length-g.length),H=o.relationships.some(J=>$t(J,"contradicts")&&h(J)&&(!E.has(J.from.entityId)||!E.has(J.to.entityId))),L=B||w>0||H,O=[];P.length===0&&(e.subjectHints?.length??0)>0?O.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):g.length===0&&O.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),K.length&&O.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:K.flatMap(J=>J.expansionRefs)}),Q.some(J=>J.availability!=="available")&&O.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:Q.map(J=>({kind:"record",id:J.id}))}),L&&O.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:o.manifest.projectId}]});let he={contractVersion:1,projectId:o.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:P.map(({score:J,...D})=>D),modelEntries:k.filter(J=>J.decisionIds.some(D=>E.has(D))).map(J=>({id:J.id,key:J.key,value:J.value,decisionIds:J.decisionIds})),decisions:g.map(J=>({id:J.id,kind:J.kind,claim:J.claim,subjectIds:J.subjects.map(D=>D.subjectId),authority:J.authority,effectiveState:W.has(J.id)?"conflicted":N.has(J.id)?"excepted":"active",freshness:R.filter(D=>D.target.entityId===J.id).map(D=>D.signalType),expansionRef:{kind:"record",id:J.id}})),conflicts:K,uncertainties:O,implementation:g.map(J=>Oa(J.id,d)),verification:g.map(J=>Da(J.id,u,R)),evidence:Q.map(J=>({evidenceId:J.id,summary:J.summary,availability:J.availability,sourceRefs:J.sourceRefs})),completeness:{status:L?"truncated":"complete",omittedDecisionCount:w,omittedEvidenceCount:0,conflictsComplete:!H}};return he.budget.estimatedTokens=Ca(he),he},b=j(m);for(;b.budget.estimatedTokens>t&&m.length>0;){let g=m.pop(),B=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]);m=m.filter(E=>!B.includes(E.id)),b=j(m,!0)}return b}var Na=/^[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 Na.test(o)}function Ja(o){return{valid:!o.some(e=>e.severity==="error"),issues:o}}function te(o,e,t,n){o.push({path:e,code:t,message:n,severity:"error"})}function Do(o,e,t,n){o.push({path:e,code:t,message:n,severity:"warning"})}function Pe(o,e,t){Ct(t)||te(o,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function Xe(o,e,t){(!t||Number.isNaN(Date.parse(t)))&&te(o,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function wt(o,e,t,n=!1){n&&t.level==="contributor"&&te(o,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&te(o,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var Ba={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->emerging","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},La=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function qa(o,e,t){Pe(o,`${t}.id`,e.id),Pe(o,`${t}.projectId`,e.projectId),Pe(o,`${t}.participantId`,e.participantId),Pe(o,`${t}.entity.entityId`,e.entity.entityId),Xe(o,`${t}.createdAt`,e.createdAt),wt(o,`${t}.authority`,e.authority);let n=Ba[e.entity.entityType],i=`${e.fromState??"null"}->${e.toState}`;n&&!n.has(i)&&te(o,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${i}.`);let r=`${e.entity.entityType}:${e.toState}`;if(La.has(r)&&(wt(o,`${t}.authority`,e.authority,!0),e.reason?.trim()||te(o,`${t}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let s=e.transitionContext;(s?.kind!=="proposal_deferral"||s.resurfaceWhen.length===0)&&te(o,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),s?.resurfaceWhen.includes("after_date")&&!s.revisitAfter&&te(o,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),s?.revisitAfter&&Xe(o,`${t}.transitionContext.revisitAfter`,s.revisitAfter)}}function Fa(o,e,t,n){Pe(o,`${t}.id`,e.id),Pe(o,`${t}.projectId`,e.projectId),Pe(o,`${t}.participantId`,e.participantId),Xe(o,`${t}.createdAt`,e.createdAt),e.projectId!==n&&te(o,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&te(o,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&te(o,`${t}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&te(o,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(wt(o,`${t}.authority`,e.authority,!0),e.claim.trim()||te(o,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Do(o,`${t}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&te(o,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),Xe(o,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&te(o,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(i=>!i.trim())&&te(o,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((i,r)=>{(!i.id.trim()||!i.modelPath.trim())&&te(o,`${t}.concreteBindings[${r}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),Xe(o,`${t}.concreteBindings[${r}].createdAt`,i.createdAt),Xe(o,`${t}.concreteBindings[${r}].updatedAt`,i.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&te(o,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(Xe(o,`${t}.appliedAt`,e.appliedAt),wt(o,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&te(o,`${t}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&te(o,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(i=>!i.trim()))&&te(o,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Do(o,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Do(o,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function Ua(o,e,t){if(Pe(o,`${t}.id`,e.id),Pe(o,`${t}.projectId`,e.projectId),Pe(o,`${t}.participantId`,e.participantId),Pe(o,`${t}.from.entityId`,e.from.entityId),Pe(o,`${t}.to.entityId`,e.to.entityId),Xe(o,`${t}.createdAt`,e.createdAt),e.reason.trim()||te(o,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let i=e.from.entityType==="decision"&&e.to.entityType==="decision",r=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!i&&!r&&te(o,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),i&&!e.authority?te(o,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):i&&e.authority&&wt(o,`${t}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&te(o,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&te(o,t,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&te(o,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&te(o,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function bt(o){let e=[];Pe(e,"manifest.projectId",o.manifest.projectId),Xe(e,"manifest.createdAt",o.manifest.createdAt),Xe(e,"manifest.updatedAt",o.manifest.updatedAt);let t=new Map,n=(p,l)=>{let f=t.get(p);f?te(e,l,"duplicate_id",`ID is already used at ${f}.`):t.set(p,l)};o.records.forEach((p,l)=>{let f=`records[${l}]`;n(p.id,f),Fa(e,p,f,o.manifest.projectId)}),o.events.forEach((p,l)=>{let f=`events[${l}]`;n(p.id,f),qa(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Event belongs to another project.")}),o.relationships.forEach((p,l)=>{let f=`relationships[${l}]`;n(p.id,f),Ua(e,p,f),p.projectId!==o.manifest.projectId&&te(e,`${f}.projectId`,"project_mismatch","Relationship belongs to another project.")}),o.artifacts.forEach((p,l)=>{n(p.id,`artifacts[${l}]`),Pe(e,`artifacts[${l}].id`,p.id)}),o.tombstones.forEach((p,l)=>{let f=`tombstones[${l}]`;n(p.id,f),Pe(e,`${f}.id`,p.id),Pe(e,`${f}.objectId`,p.objectId),Pe(e,`${f}.deletedById`,p.deletedById),Xe(e,`${f}.deletedAt`,p.deletedAt),wt(e,`${f}.authority`,p.authority,!0)});let i=new Set(o.records.map(p=>`${p.recordType}:${p.id}`)),r=new Set(o.tombstones.map(p=>`${p.objectType}:${p.objectId}`)),s=(p,l)=>{let f=`${p.entityType}:${p.entityId}`;!i.has(f)&&!r.has(f)&&te(e,l,"dangling_entity_reference",`No record or tombstone exists for ${f}.`)};o.events.forEach((p,l)=>s(p.entity,`events[${l}].entity`)),o.relationships.forEach((p,l)=>{s(p.from,`relationships[${l}].from`),s(p.to,`relationships[${l}].to`)});let c=new Set(o.artifacts.map(p=>p.id)),d=(p,l)=>{c.has(p)||te(e,l,"dangling_artifact_reference","No artifact manifest entry exists.")},u=(p,l,f)=>{!i.has(`${p}:${l}`)&&!r.has(`${p}:${l}`)&&te(e,f,"dangling_entity_reference",`No ${p} record or tombstone exists.`)};o.records.forEach((p,l)=>{let f=`records[${l}]`;switch(p.recordType){case"authority_grant":u("participant",p.granteeId,`${f}.granteeId`),u("participant",p.grantedById,`${f}.grantedById`),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`));break;case"observation":p.captureContext.subjectIds.forEach((m,h)=>u("subject",m,`${f}.captureContext.subjectIds[${h}]`)),p.captureContext.artifactIds.forEach((m,h)=>d(m,`${f}.captureContext.artifactIds[${h}]`));break;case"proposal":case"decision":p.subjects.forEach((m,h)=>u("subject",m.subjectId,`${f}.subjects[${h}].subjectId`));break;case"thread":p.messageArtifactIds.forEach((m,h)=>d(m,`${f}.messageArtifactIds[${h}]`)),p.resultRefs.forEach((m,h)=>s(m,`${f}.resultRefs[${h}]`));break;case"iteration":p.threadIds.forEach((m,h)=>u("thread",m,`${f}.threadIds[${h}]`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"evidence":p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"advisory_explanation":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`)),p.supersededById&&u("advisory_explanation",p.supersededById,`${f}.supersededById`);break;case"implementation_attempt":p.iterationIds.forEach((m,h)=>u("iteration",m,`${f}.iterationIds[${h}]`)),p.coverageClaims.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverageClaims[${h}].decisionId`)),p.artifactIds.forEach((m,h)=>d(m,`${f}.artifactIds[${h}]`));break;case"eval_spec":p.replacesSpecId&&u("eval_spec",p.replacesSpecId,`${f}.replacesSpecId`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),(p.dependencies??[]).forEach((m,h)=>{m.kind==="subject"&&m.subjectId&&u("subject",m.subjectId,`${f}.dependencies[${h}].subjectId`)}),(p.scenarios??[]).forEach((m,h)=>{m.subjectIds?.forEach((j,b)=>u("subject",j,`${f}.scenarios[${h}].subjectIds[${b}]`))}),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`));break;case"verification_attempt":p.evalSpecId&&u("eval_spec",p.evalSpecId,`${f}.evalSpecId`),p.targets.forEach((m,h)=>u(m.entityType,m.entityId,`${f}.targets[${h}]`)),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;case"model_entry":p.subjectIds.forEach((m,h)=>u("subject",m,`${f}.subjectIds[${h}]`)),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`));break;case"model_projection":wt(e,`${f}.authority`,p.authority,!0),u("participant",p.appliedById,`${f}.appliedById`),p.decisionIds.forEach((m,h)=>u("decision",m,`${f}.decisionIds[${h}]`)),p.entryIds.forEach((m,h)=>u("model_entry",m,`${f}.entryIds[${h}]`)),p.coverage.forEach((m,h)=>u("decision",m.decisionId,`${f}.coverage[${h}].decisionId`));break;case"freshness_signal":s(p.target,`${f}.target`),p.evidenceIds.forEach((m,h)=>u("evidence",m,`${f}.evidenceIds[${h}]`));break;default:break}});let I=new Map(o.events.map(p=>[p.id,p])),T=new Map(o.records.map(p=>[`${p.recordType}:${p.id}`,p])),k=new Map;o.events.forEach((p,l)=>{let f=`${p.entity.entityType}:${p.entity.entityId}:${p.fromState??"null"}`,m=k.get(f)??new Set;m.add(p.toState),k.set(f,m),m.size>1&&te(e,`events[${l}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let P=new Map(o.records.flatMap(p=>p.recordType==="authority_grant"?[[p.id,p]]:[])),x=(p,l,f,m,h)=>{if(p.level!=="delegate"||!p.grantId)return;let j=P.get(p.grantId);if(!j){te(e,h,"invalid_authority_grant","Delegated authority references a missing grant.");return}(j.granteeId!==l||j.level!=="delegate")&&te(e,h,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let b=Date.parse(f);(b<Date.parse(j.startsAt)||j.endsAt&&b>Date.parse(j.endsAt)||j.revokedAt&&b>=Date.parse(j.revokedAt))&&te(e,h,"inactive_authority_grant","The delegated authority grant was not active at this time."),j.subjectIds.length&&m.length&&!m.every(g=>j.subjectIds.includes(g))&&te(e,h,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let p of o.records)p.recordType==="decision"&&x(p.authority,p.acceptedById,p.createdAt,p.subjects.map(l=>l.subjectId),`records:${p.id}.authority`);o.events.forEach((p,l)=>{let f=T.get(`${p.entity.entityType}:${p.entity.entityId}`),m=f&&"subjects"in f?f.subjects.map(h=>h.subjectId):[];x(p.authority,p.participantId,p.createdAt,m,`events[${l}].authority`)}),o.relationships.forEach((p,l)=>{if(!p.authority)return;let f=[p.from,p.to].flatMap(m=>{let h=T.get(`${m.entityType}:${m.entityId}`);return h&&"subjects"in h?h.subjects.map(j=>j.subjectId):[]});x(p.authority,p.participantId,p.createdAt,f,`relationships[${l}].authority`)});for(let p of o.records){if(p.recordType!=="decision")continue;let l=I.get(p.acceptanceEventId);(!l||l.entity.entityType!=="proposal"||l.entity.entityId!==p.proposalId||l.toState!=="accepted")&&te(e,`records:${p.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),l&&l.participantId!==p.acceptedById&&te(e,`records:${p.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${p.proposalId}`)||te(e,`records:${p.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),p.state==="superseded"&&(o.relationships.some(m=>m.relationshipType==="supersedes"&&m.to.entityType==="decision"&&m.to.entityId===p.id)||te(e,`records:${p.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),p.state==="revoked"&&(o.events.some(m=>m.entity.entityType==="decision"&&m.entity.entityId===p.id&&m.toState==="revoked"&&!!m.reason?.trim())||te(e,`records:${p.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let p of o.records){if(p.recordType!=="proposal"||p.state!=="accepted")continue;o.records.some(f=>f.recordType==="decision"&&f.proposalId===p.id)||te(e,`records:${p.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Ja(e)}function nn(o,e,t,n){return{id:n,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function Gi(o,e,t,n,i){return{id:i,schemaVersion:1,projectId:o.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:n,acceptedById:t.participantId,authority:t.authority,state:"active",kind:t.kind,claim:e.claim,rationale:t.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function za(o){switch(o.action){case"accept":return[o.eventId,o.decisionId];case"edit_and_accept":return[o.withdrawalEventId,o.replacementProposalId,o.acceptanceEventId,o.decisionId,o.relationshipId];case"reject":case"defer":return[o.eventId]}}function Jn(o,e){let t=[],n=o.records.find(r=>r.recordType==="proposal"&&r.id===e.proposalId);n?n.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${n.state}, not pending.`}):t.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&t.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&t.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),Ct(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let r of za(e))Ct(r)||t.push({code:"invalid_generated_id",message:`${r} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!n)return{ok:!1,errors:t};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let r={...nn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},s=Gi(o,n,e,r.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[s],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:s.id}]}}}if(e.action==="edit_and_accept"){if(!e.claim.trim()||!e.reason.trim())return{ok:!1,errors:[{code:"claim_and_reason_required",message:"Edited acceptance requires claim and reason."}]};if(e.subjects.length>1&&!e.subjectSemantics?.trim())return{ok:!1,errors:[{code:"subject_semantics_required",message:"Multi-subject edits require semantics."}]};let r={id:e.replacementProposalId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id},...e.sourceRefs??[]],recordType:"proposal",state:"accepted",claim:e.claim,rationale:e.rationale,proposedKind:e.kind,subjects:e.subjects,subjectSemantics:e.subjectSemantics,origin:{mode:"declared"}},s={...nn(o,n,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...nn(o,r,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:r.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=Gi(o,r,e,c.id,e.decisionId),u={id:e.relationshipId,schemaVersion:1,projectId:o.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:n.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:r.id},to:{entityType:"proposal",entityId:n.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[r,d],events:[s,c],relationships:[u]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:r.id},{entityType:"decision",entityId:d.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let r={...nn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}let i={...nn(o,n,e,e.eventId),entity:{entityType:"proposal",entityId:n.id},eventType:"proposal.deferred",fromState:"pending",toState:"deferred",reason:e.reason,transitionContext:{kind:"proposal_deferral",...e.context}};return{ok:!0,plan:{action:e.action,proposalId:n.id,append:{records:[],events:[i],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:n.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:n.id}]}}}var Wi={project:0,route:1,component:2,selector:2,file:3},Hi={intention:0,principle:1,pattern:2};function Ot(o,e){let t=Wi[o.scope.kind]-Wi[e.scope.kind];return t!==0?t:Hi[o.kind]-Hi[e.kind]}function Vi(o){return o==="expresses"||o==="excepts"}function Ga(o,e){if(e.type==="expresses"||e.type==="excepts")return structuredClone(e);if(e.type==="operationalizes")return{...structuredClone(e),type:"expresses"};if(e.type==="instantiates")return{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId};if(e.type==="refines"){let t=o.explanations.find(r=>r.id===e.fromId),n=o.explanations.find(r=>r.id===e.toId);if(!t||!n)return;let i=Ot(t,n);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),t=new Set;return e.relations=o.relations.flatMap(n=>{let i=Ga(o,n);if(!i)return[];let r=`${i.type}:${i.fromId}:${i.toId}`;return t.has(r)?[]:(t.add(r),[i])}),e}import{createHash as Wa}from"crypto";import{readFile as Ha,readdir as Va,realpath as Ka}from"fs/promises";import{join as on,relative as Qa}from"path";var Xa=["f5258a13","31ffc15e","3eae3a70","c185e614","33930045","55e04c59","f3bb881b","f8a55928","eac95a7d","e402bdc2","2854624b","cf28ad45","6a494fab","987e901b","ad7293aa","dd1d5d77","14c429d6","48494ad3","d6bbe932","e8b94260","f56fa283","7f1f6cb3","f239f4ac","bd671e61","dbe032ec","c0808b95"];function Dt(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)?o:null}function We(o,e=0){return new Date(Number.isFinite(o)?o:e).toISOString()}function Ki(...o){return o.find(e=>!!e?.trim())?.trim()}function ie(o,e,t,n){let r=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),s=Wa("sha256").update(`${o}\0${e}\0${t}`).digest("hex"),c=(Number.parseInt(s[3],16)&3|8).toString(16);return`${r.slice(0,8)}-${r.slice(8)}-7${s.slice(0,3)}-${c}${s.slice(4,7)}-${s.slice(7,19)}`}async function No(o,e){try{return JSON.parse(await Ha(o,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:o,message:t instanceof Error?t.message:String(t)}),null}}function Ya(o){let e=Dt(o);if(!e)return 0;let t=0,n=i=>{let r=Dt(i);if(!r){t+=1;return}for(let s of Object.values(r))n(s)};for(let i of Object.values(e))n(i);return t}function Za(o){let e={};for(let t of o)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function St(o){let e=[],t=await Ka(o.projectRoot).catch(()=>o.projectRoot),n=on(t,".popmelt"),i=await No(on(n,"threads.json"),e),r=await No(on(n,"model.json"),e),s=Dt(i),c=Dt(s?.threads)??{},d=Object.entries(c).map(([D,Y])=>({key:D,value:Dt(Y)})).filter(D=>!!D.value),u=on(n,"decisions"),I=await Va(u).catch(()=>[]),T=[];for(let D of I.filter(Y=>Y.endsWith(".json")).sort()){let Y=Dt(await No(on(u,D),e));Y&&T.push({file:D,value:Y})}let k=d.flatMap(({value:D})=>[D.createdAt,D.updatedAt]).filter(D=>typeof D=="number"&&Number.isFinite(D)),P=k.length?Math.min(...k):0,x=o.projectKey??t;o.projectKey||e.push({severity:"info",code:"path_derived_project_identity",message:"Canonical project identity is stable for this path; pass projectKey to preserve it across moves."});let p=ie(x,"project",x,P),l=ie(x,"participant","legacy-owner",P),f=ie(x,"participant","legacy-agent",P),m=ie(x,"subject","project",P),h=We(Math.max(P,...k)),j=[],b=[],g=new Map,B=new Map,E=new Map(T.map(D=>[D.value.id??D.file.replace(/^d-|\.json$/g,""),D.value])),R=new Map,N=(D,Y,ce,Re,se)=>{let ze=g.get(ce);if(ze)return ze;let He=ie(x,"artifact",D,Re);return b.push({id:He,kind:Y,mediaType:se,location:ce,availability:"available"}),g.set(ce,He),He};for(let{file:D,value:Y}of T){let ce=Y.id??D.replace(/^d-|\.json$/g,""),Re=Y.createdAt??P,se=[N(`${ce}:envelope`,"other",`.popmelt/decisions/${D}`,Re,"application/json")];Y.screenshotPath&&se.push(N(`${ce}:screenshot`,"screenshot",`.popmelt/${Y.screenshotPath.replace(/^\.popmelt\//,"")}`,Re,Y.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[ze,He]of(Y.pastedImagePaths??[]).entries())se.push(N(`${ce}:image:${ze}`,"image",He,Re));R.set(ce,se)}let V=(D,Y,ce)=>({id:D,schemaVersion:1,projectId:p,createdAt:h,participantId:Y,sourceRefs:ce}),K=(D,Y)=>{j.push(Y);let ce=B.get(D)??[];ce.push(Y.id),B.set(D,ce)},W=[{...V(l,l,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...V(f,f,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];j.push(...W),j.push({...V(m,l,[]),recordType:"subject",subjectType:"project",label:Qa(process.cwd(),t)||t,aliases:[],locators:[{id:ie(x,"locator",t,P),kind:"project_root",value:t,status:"current",validFrom:We(P),sourceRefs:[]}]});let Q=new Map,w=(D,Y)=>{let ce=Q.get(D);if(ce)return ce;let Re=ie(x,"subject",D,Y),se={...V(Re,l,[{kind:"external",id:D}]),createdAt:We(Y),recordType:"subject",subjectType:"element",label:D,aliases:[],locators:[{id:ie(x,"locator",D,Y),kind:"dom_selector",value:D,status:"current",validFrom:We(Y),sourceRefs:[{kind:"external",id:D}]}]};return j.push(se),Q.set(D,Re),Re};for(let{key:D,value:Y}of d){let ce=Y.id??D,Re=Y.createdAt??P,se=ie(x,"thread",ce,Re),ze={kind:"thread",id:ce},He=[],je=[],st=Array.isArray(Y.messages)?Y.messages:[],Ve,at,Vt=0;st.forEach((xe,ct)=>{let _e=xe.timestamp??Re,tt=ie(x,"artifact",`${ce}:message:${ct}`,_e);if(He.push(tt),b.push({id:tt,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${ce}/messages/${ct}`,availability:"available"}),g.set(`.popmelt/threads.json#/threads/${ce}/messages/${ct}`,tt),xe.screenshotPath&&N(`${ce}:message:${ct}:screenshot`,"screenshot",xe.screenshotPath,_e),xe.role==="human"){Ve=xe;let Je=xe.feedbackSummary??xe.replyToQuestion;if(Je?.trim()){let Be=ie(x,"observation",`${ce}:${ct}`,_e),pt=Y.elementIdentifiers??[],jt={...V(Be,l,[ze,{kind:"message",id:tt}]),createdAt:We(_e),recordType:"observation",state:"open",statement:Je,captureContext:{subjectIds:pt.map(gt=>w(gt,Re)),artifactIds:[tt]},resolvedByIds:[]};K(ce,jt),at=Be,je.push({entityType:"observation",entityId:Be})}return}if(xe.role!=="assistant")return;let dt=xe.jobId??`${ce}:${ct}`,lt=ie(x,"iteration",dt,_e),ft=E.get(dt),uo=xe.cancelled?"cancelled":xe.error?"failed":xe.question?"question_asked":(xe.resolutions?.length??0)>0?"completed":"no_change",mo={...V(lt,f,[ze,{kind:"message",id:tt},...(R.get(dt)??[]).map(Je=>({kind:"artifact",id:Je}))]),createdAt:We(_e),recordType:"iteration",threadIds:[se],startedAt:We(Ve?.timestamp,_e),completedAt:We(_e),requestSummary:Ki(Ve?.feedbackSummary,Ve?.replyToQuestion)??"[legacy request unavailable]",responseSummary:xe.question??xe.error??xe.responseText?.slice(0,1e3),outcome:uo,execution:{provider:xe.provider??ft?.provider,model:xe.model??ft?.model,sessionId:xe.sessionId??ft?.sessionId},artifactIds:[tt,...R.get(dt)??[]]};K(ce,mo),je.push({entityType:"iteration",entityId:lt});let ht=xe.resolutions??ft?.resolutions??[];for(let[Je,Be]of ht.entries()){if(Be.status!=="resolved"||!Be.summary?.trim())continue;let pt=Y.elementIdentifiers??[],jt=(pt.length?pt:[t]).map(In=>({subjectId:In===t?m:w(In,Re),role:"governed"})),gt=ie(x,"proposal",`${dt}:${Be.annotationId??"resolution"}:${Je}`,_e),fo={...V(gt,f,[ze,{kind:"iteration",id:lt}]),createdAt:We(_e),recordType:"proposal",state:"pending",claim:Be.summary,subjects:jt,subjectSemantics:jt.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:Ki(Ve?.feedbackSummary,Ve?.replyToQuestion,Be.summary),iterationId:lt,inferredById:f}};K(ce,fo),je.push({entityType:"proposal",entityId:gt}),e.push({severity:"warning",code:"acceptance_unresolved",source:ce,message:`Proposal ${gt} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(ht.some(Je=>Je.status==="resolved")||ft?.gitDiff){let Je=ie(x,"implementation",dt,_e),Be={...V(Je,f,[ze,{kind:"iteration",id:lt}]),createdAt:We(_e),recordType:"implementation_attempt",state:"completed",iterationIds:[lt],coverageClaims:[],summary:ht.map(pt=>pt.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};K(ce,Be),je.push({entityType:"implementation_attempt",entityId:Je}),Vt+=1}at&&(at=void 0)});let Pt=st.at(-1),po={...V(se,l,[ze]),createdAt:We(Re),recordType:"thread",state:Pt?.question?"open":"resolved",messageArtifactIds:He,outcome:Pt?.question?"question_unresolved":Vt?"implementation_only":"no_outcome",resultRefs:je};j.push(po),B.set(ce,[se,...B.get(ce)??[]])}let H=Ya(r);H&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${H} model values were not promoted because their accepted decision provenance is unresolved.`});let L={manifest:{formatVersion:1,projectId:p,createdAt:We(P),updatedAt:h,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:o.writerVersion??"0.8.4-dev"}},records:j,events:[],relationships:[],artifacts:b,tombstones:[]},O=bt(L),J=(o.proofCaseIds??Xa).map(D=>({legacyId:D,threadFound:d.some(({key:Y,value:ce})=>(ce.id??Y)===D),decisionEnvelopeFound:E.has(D),recordIds:B.get(D)??[]}));return{bundle:L,report:{projectRoot:t,source:{threads:d.length,messages:d.reduce((D,Y)=>D+(Y.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:H,artifactsReferenced:b.length},imported:Za(j),unresolvedAcceptance:e.filter(D=>D.code==="acceptance_unresolved").length,deferredModelEntries:H,proofCases:J,issues:e,schemaIssues:O.issues}}}import{createHash as ec}from"crypto";import{mkdir as Qi,open as Jo,readFile as Bo,readdir as tc,rename as nc,unlink as Lo}from"fs/promises";import{join as nt}from"path";var oc={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Ln(o){return ec("sha256").update(JSON.stringify(o)).digest("hex")}function Xi(o){return Ln(o)}function Yi(o,e,t){[...e.records,...e.recordReplacements??[]].some(n=>n.recordType==="advisory_explanation")&&!o.manifest.features.includes("advisory_explanations")&&o.manifest.features.push("advisory_explanations");for(let n of e.recordReplacements??[]){if(n.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${n.recordType}.`);let i=o.records.findIndex(s=>s.recordType===n.recordType&&s.id===n.id);if(i<0)throw new Error(`Record replacement target not found: ${n.recordType} ${n.id}`);let r=o.records[i];if(r.projectId!==n.projectId||r.createdAt!==n.createdAt||r.participantId!==n.participantId)throw new Error(`Record replacement changed immutable identity for ${n.id}.`);o.records[i]=structuredClone(n)}for(let n of e.projectionUpdates){let i=o.records.find(r=>r.recordType===n.entityType&&r.id===n.entityId);if(!i||i.recordType!=="proposal"&&i.recordType!=="decision")throw new Error(`Projection target not found: ${n.entityType} ${n.entityId}`);if(i.state!==n.fromState)throw new Error(`Projection state conflict for ${n.entityType} ${n.entityId}: expected ${n.fromState}, found ${i.state}`);i.state=n.state}return o.records.push(...e.records),o.events.push(...e.events),o.relationships.push(...e.relationships),o.artifacts.push(...e.artifacts),o.tombstones.push(...e.tombstones),o.manifest.updatedAt=t,o}function ic(o,e,t){return Yi(structuredClone(o),e,t)}async function kt(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Jo(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
156
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await nc(t,o)}catch(i){throw await Lo(t).catch(()=>{}),i}}async function Bn(o){return JSON.parse(await Bo(o,"utf8"))}var qn=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=nt(e,".popmelt","memory"),this.journalDir=nt(this.memoryDir,"journal"),this.manifestPath=nt(this.memoryDir,"manifest.json"),this.checkpointPath=nt(this.memoryDir,"checkpoint.json"),this.lockPath=nt(this.memoryDir,"writer.lock")}async initialize(e){let t=bt(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Qi(this.journalDir,{recursive:!0});try{throw await Bo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(n){if(n instanceof Error&&n.message==="Memory journal is already initialized."||n.code!=="ENOENT")throw n}await this.withWriterLock(async()=>{try{throw await Bo(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(s){if(s instanceof Error&&s.message==="Memory journal is already initialized."||s.code!=="ENOENT")throw s}let n=Ln(e),i={storageVersion:1,sequence:0,hash:n,journalHash:null,bundle:e},r={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:n},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await kt(this.checkpointPath,i),await kt(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 kt(this.manifestPath,e.manifest)),{bundle:e.bundle,report:e.report}}))}async rotateCheckpoint(){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{let e=await this.loadInternal();if(e.report.headSequence===e.report.checkpointSequence)return{bundle:e.bundle,report:e.report};let t=Ln(e.bundle),n=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,i={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await kt(nt(this.memoryDir,n),i),e.manifest.checkpoint={file:n,sequence:i.sequence,hash:t},await kt(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:i.sequence,appliedTransactions:0}}}))}async maintain(e=250){let t=await this.load();return t.report.headSequence-t.report.checkpointSequence>=e?this.rotateCheckpoint():t}async commit(e,t){return this.enqueueWrite(async()=>this.withWriterLock(async()=>{if(!Ct(t.transactionId))throw new Error("Transaction ID must be UUIDv7.");if(Number.isNaN(Date.parse(t.committedAt)))throw new Error("committedAt must be ISO-8601.");let n=await this.loadInternal();if(n.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let i=n.report.headSequence+1,r={storageVersion:1,sequence:i,transactionId:t.transactionId,projectId:n.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:n.report.headHash,mutation:e},s={...r,hash:Xi(r)},c=ic(n.bundle,e,t.committedAt),d=bt(c);if(!d.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(d.issues)}`);let u=`${String(i).padStart(12,"0")}-${t.transactionId}.json`;return await kt(nt(this.journalDir,u),s),n.manifest.head={sequence:i,hash:s.hash},n.manifest.updatedAt=t.committedAt,await kt(this.manifestPath,n.manifest),{bundle:c,report:{checkpointSequence:n.report.checkpointSequence,appliedTransactions:n.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:n.report.ignoredTemporaryFiles,headSequence:i,headHash:s.hash}}}))}async commitReviewPlan(e,t){return this.commit({...oc,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await Bn(this.manifestPath),t=await Bn(nt(this.memoryDir,e.checkpoint.file));if(e.storageVersion!==1||t.storageVersion!==1)throw new Error("Unsupported memory journal storage version.");if(e.projectId!==t.bundle.manifest.projectId)throw new Error("Checkpoint project does not match journal manifest.");if(t.hash!==Ln(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let n=await tc(this.journalDir),i=n.filter(k=>k.endsWith(".tmp")),s=n.filter(k=>/^\d{12}-[0-9a-f-]+\.json$/i.test(k)).sort().filter(k=>Number(k.slice(0,12))>t.sequence),c=structuredClone(t.bundle),d=t.sequence,u=t.journalHash??null,I=new Set;for(let k of s){let P=await Bn(nt(this.journalDir,k)),{hash:x,...p}=P;if(x!==Xi(p))throw new Error(`Journal hash mismatch: ${k}`);if(P.sequence!==d+1)throw new Error(`Journal sequence gap at ${k}`);if(P.previousHash!==u)throw new Error(`Journal chain mismatch at ${k}`);if(P.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${k}`);if(I.has(P.transactionId))throw new Error(`Duplicate transaction ID: ${P.transactionId}`);Yi(c,P.mutation,P.committedAt),d=P.sequence,u=P.hash,I.add(P.transactionId)}if(e.head.sequence>d)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===d&&e.head.hash!==u)throw new Error("Journal manifest head hash mismatch.");let T=bt(c);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:c,manifest:e,transactionIds:I,report:{checkpointSequence:t.sequence,appliedTransactions:s.length,recoveredTransactions:Math.max(0,d-e.head.sequence),ignoredTemporaryFiles:i.length,headSequence:d,headHash:u}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Qi(this.memoryDir,{recursive:!0});let t;try{t=await Jo(this.lockPath,"wx")}catch(n){if(n.code!=="EEXIST")throw n;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 Lo(this.lockPath),t=await Jo(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Lo(this.lockPath).catch(()=>{})}}};import{randomBytes as rc}from"crypto";function we(o=Date.now()){let t=Math.max(0,Math.min(Math.floor(o),0xffffffffffff)).toString(16).padStart(12,"0"),n=rc(10).toString("hex"),i=(Number.parseInt(n[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${n.slice(0,3)}-${i}${n.slice(4,7)}-${n.slice(7,19)}`}var sc=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function Zi(o,e){let t=o.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),n=o.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active");if(!t||!n)throw new Error("Canonical memory requires active human and AI participants before job capture.");let i=o.manifest.projectId,r=`${e.threadId}:${e.jobId}`,s=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),d=sc(),u=d.records,I=o.records.find(h=>h.recordType==="thread"&&h.sourceRefs.some(j=>j.kind==="thread"&&j.id===e.threadId));I||(I={id:ie(i,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"thread",state:e.outcome==="question_asked"?"open":"resolved",messageArtifactIds:[],outcome:e.outcome==="question_asked"?"question_unresolved":e.resolutions.some(h=>h.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},u.push(I));let T=[];for(let h of[...new Set(e.subjectHints.filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"element",label:h,aliases:[],locators:[{id:ie(i,"live-locator",h,e.createdAt),kind:"dom_selector",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),T.push(j)}for(let h of[...new Set((e.filePaths??[]).filter(Boolean))]){let j=o.records.find(b=>b.recordType==="subject"&&b.locators.some(g=>g.kind==="source_file"&&g.value===h&&g.status==="current"));j||(j={id:ie(i,"live-file-subject",h,e.createdAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"external",id:h}],recordType:"subject",subjectType:"file",label:h,aliases:[],locators:[{id:ie(i,"live-file-locator",h,e.createdAt),kind:"source_file",value:h,status:"current",validFrom:s,sourceRefs:[{kind:"external",id:h}]}]},u.push(j)),T.push(j)}let k=(e.semanticCandidates??[]).filter(h=>h.claim.trim()),P;if(k.length>0){P=ie(i,"live-observation",r,e.createdAt);let h={id:P,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:k.map(j=>j.claim.trim()).join(" "),captureContext:{subjectIds:T.map(j=>j.id),artifactIds:[]},resolvedByIds:[]};u.push(h)}let x=ie(i,"live-iteration",r,e.completedAt),p={id:x,schemaVersion:1,projectId:o.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(h=>({kind:"external",id:h,uri:"popmelt:imprint-evidence"})),...P?[{kind:"record",id:P}]:[]],recordType:"iteration",threadIds:[I.id],startedAt:s,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};u.push(p);let l=[],f=e.resolutions.filter(h=>h.status==="resolved"&&h.summary.trim()),m=T.length>0?T:o.records.filter(h=>h.recordType==="subject"&&h.subjectType==="project").slice(0,1);if(k.length>0&&m.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[h,j]of k.entries()){let b=ie(i,"live-proposal",`${r}:${h}`,e.completedAt),g=m.map(E=>({subjectId:E.id,role:"governed"})),B={id:b,schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:x},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:j.claim.trim(),rationale:j.rationale?.trim()||void 0,proposedKind:j.proposedKind,subjects:g,subjectSemantics:g.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:j.sourceText?.trim()||e.requestSummary,iterationId:x,inferredById:n.id}};u.push(B),l.push(b)}if(f.length>0){let h=new Set(e.governingDecisionIds??[]),j=o.records.filter(g=>g.recordType==="decision"&&g.state==="active"&&h.has(g.id)),b={id:ie(i,"live-implementation",r,e.completedAt),schemaVersion:1,projectId:o.manifest.projectId,createdAt:c,participantId:n.id,sourceRefs:[{kind:"iteration",id:x}],recordType:"implementation_attempt",state:"completed",iterationIds:[x],coverageClaims:j.map(g=>({decisionId:g.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${f.map(B=>B.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:x}]})),summary:f.map(g=>g.summary).join(" "),artifactIds:[]};u.push(b)}return{mutation:d,iterationId:x,proposalIds:l,observationId:P}}import{createHash as ac}from"crypto";import{mkdir as cc,open as dc,readFile as lc,rename as pc,unlink as uc}from"fs/promises";import{join as er}from"path";function tr(o){return o.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function nr(o){return ac("sha256").update(JSON.stringify(o)).digest("hex")}async function mc(o,e){let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await dc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
157
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await pc(t,o)}catch(i){throw await uc(t).catch(()=>{}),i}}function fc(o,e,t=new Date().toISOString()){let n={},i={},r={},s=(d,u,I)=>{let T=d[u]??=[];T.includes(I)||T.push(I)};for(let d of o.records)if(d.recordType==="subject"){let u=d;for(let I of[u.label,...u.aliases,...u.locators.filter(T=>T.status==="current").map(T=>T.value)]){let T=tr(I);T&&s(n,T,u.id)}}else if(d.recordType==="decision"&&d.state==="active")for(let u of d.subjects)s(i,u.subjectId,d.id);else if(d.recordType==="proposal"&&["pending","deferred"].includes(d.state))for(let u of d.subjects)s(r,u.subjectId,d.id);let c={version:1,projectId:o.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:n,decisionIdsBySubject:i,proposalIdsBySubject:r};return{...c,checksum:nr(c)}}function or(o,e){let t=[...new Set(e.flatMap(n=>o.subjectIdsByValue[tr(n)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(n=>o.decisionIdsBySubject[n]??[]))],proposalIds:[...new Set(t.flatMap(n=>o.proposalIdsBySubject[n]??[]))]}}var Fn=class{constructor(e){this.indexDir=er(e,".popmelt","memory","indexes"),this.indexPath=er(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let i=JSON.parse(await lc(this.indexPath,"utf8")),{checksum:r,...s}=i;if(i.version===1&&i.projectId===e.manifest.projectId&&i.journalHead.sequence===t.sequence&&i.journalHead.hash===t.hash&&r===nr(s))return i}catch(i){if(i.code!=="ENOENT"&&!(i instanceof SyntaxError))throw i}let n=fc(e,t);return await cc(this.indexDir,{recursive:!0}),await mc(this.indexPath,n),n}};var sn="popmelt:imprint",sr="popmelt:imprint-evidence",Jt="popmelt:imprint-relation";function Un(o){return o.sourceRefs.find(e=>e.kind==="external"&&e.uri===sn)?.id}function qo(o){let e=new Set;return o.filter(t=>{let n=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(n)?!1:(e.add(n),!0)})}function zn(o,e){if(!o)return[];let t=new Set(o.relations.flatMap(n=>n.type==="expresses"&&n.toId===e?[n.fromId]:[]));return o.concrete.filter(n=>t.has(n.id)).map(n=>({id:n.id,modelPath:n.modelPath,value:structuredClone(n.value),createdAt:n.createdAt,updatedAt:n.updatedAt}))}function Fo(o){if(o==="expresses")return"operationalizes";if(o==="excepts")return"excepts"}var Gn=class{constructor(e){this.projectRoot=e;this.store=new qn(e),this.indexStore=new Fn(e),this.manifestPath=Nt(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 n=await St({...e,projectRoot:this.projectRoot});if(n.report.schemaIssues.some(i=>i.severity==="error"))throw new Error("Legacy analysis produced schema errors; automatic initialization refused.");this.runtimeState={state:"initializing",phase:"writing_checkpoint"};try{await this.store.initialize(n.bundle)}catch(i){if(!(i instanceof Error)||!i.message.includes("already initialized"))throw i}return await this.refreshIndex(await this.store.load()),this.runtimeState={state:"ready"},await this.status()}catch(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await St({...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=Nt(this.projectRoot,".popmelt","memory","migrations"),t=Nt(e,"imprint-advisories-v2.json");try{let h=JSON.parse(await rn(t,"utf8"));return{migrated:!1,explanations:h.explanations??0,evidence:h.evidence??0}}catch{}let n;try{n=xt(JSON.parse(await rn(Nt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!n?.explanations)return await ir(e,{recursive:!0}),await rr(t,JSON.stringify({version:2,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let i=await this.store.load(),r=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active"),c=i.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="ai"&&h.status==="active")??r,d=i.bundle.records.find(h=>h.recordType==="subject"&&h.subjectType==="project");if(!c||!d)return{migrated:!1,explanations:0,evidence:0};let u=i.bundle.manifest.projectId,I=new Set(i.bundle.records.map(h=>h.id)),T=new Set(i.bundle.relationships.flatMap(h=>h.sourceRefs.flatMap(j=>j.kind==="external"&&j.uri===Jt?[j.id]:[]))),k=new Map,P=i.bundle.records.filter(h=>h.recordType==="advisory_explanation");for(let h of n.explanations){let j=P.find(b=>Un(b)===h.id);k.set(h.id,j?.id??ie(u,"imprint-explanation",h.id,Date.parse(h.createdAt)))}let x=[],p=[],l=[],f=0;for(let h of n.explanations){let j=k.get(h.id),b=P.find(R=>R.id===j),g=[],B=h.evidence.length?h.evidence:[{id:`fallback:${h.id}`,kind:"observation",stance:"supports",summary:h.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:h.createdAt}];for(let R of B){let N=ie(u,"imprint-evidence-record",R.id,Date.parse(R.createdAt));g.push(N),!I.has(N)&&(x.push({id:N,schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:qo([{kind:"external",id:R.id,uri:sr},{kind:"external",id:h.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(u,"imprint-evidence-link",`${h.id}:${R.id}`,Date.parse(R.createdAt)),schemaVersion:1,projectId:u,createdAt:R.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:R.id,uri:sr}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"evidence",entityId:N},reason:"This advisory explanation was derived from collaboration evidence."}),f+=1)}let E={id:j,schemaVersion:1,projectId:u,createdAt:b?.createdAt??h.createdAt,participantId:b?.participantId??c.id,sourceRefs:qo([...b?.sourceRefs??[],{kind:"external",id:h.id,uri:sn}]),recordType:"advisory_explanation",kind:h.kind,state:h.state,statement:h.statement,rationale:h.rationale,scope:structuredClone(h.scope),subjectIds:[d.id],evidenceIds:[...new Set([...b?.evidenceIds??[],...g])],concreteBindings:zn(n,h.id),supersededById:h.supersededBy?k.get(h.supersededBy):void 0,updatedAt:h.updatedAt};b?p.push(E):x.push(E)}for(let h of n.relations){let j=Fo(h.type);if(!j)continue;let b=k.get(h.fromId),g=k.get(h.toId);!b||!g||T.has(h.id)||l.push({id:ie(u,"imprint-relation",h.id,Date.parse(h.createdAt)),schemaVersion:1,projectId:u,createdAt:h.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:h.id,uri:Jt}],recordType:"relationship",relationshipType:j,from:{entityType:"advisory_explanation",entityId:b},to:{entityType:"advisory_explanation",entityId:g},reason:h.rationale||"The Imprint graph connected these explanations."})}let m=new Date().toISOString();if(x.length||p.length||l.length)try{let h=await this.store.commit({records:x,recordReplacements:p,events:[],relationships:l,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:ie(u,"imprint-advisories-v2",n.projectId,Date.parse(n.updatedAt)),committedAt:m});await this.refreshIndex(h)}catch(h){if(!(h instanceof Error)||!h.message.includes("Transaction already exists"))throw h}return await ir(e,{recursive:!0}),await rr(t,JSON.stringify({version:2,migratedAt:m,explanations:n.explanations.length,evidence:f,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:n.explanations.length,evidence:f}}async review(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,selection:tn(n.bundle,i)}}async contextualize(e,t={}){let n=await this.loadSource(t),i=await this.withIndexedCandidates(n,e);return{source:n.source,actionPacket:zi(n.bundle,i),reviewSelection:tn(n.bundle,i)}}async planReview(e,t={}){let n=await this.loadSource(t);return{source:n.source,result:Jn(n.bundle,e)}}async initializeFromLegacy(e){if(!e.confirmed)throw new Error("Explicit confirmation is required to initialize memory storage.");if((await this.status()).initialized)throw new Error("Memory storage is already initialized.");let t=await St({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(n=>n.severity==="error"))throw new Error("Legacy analysis produced schema errors; initialization refused.");return await this.store.initialize(t.bundle),await this.refreshIndex(await this.store.load()),{status:await this.status(),report:t.report}}async commitReview(e,t){if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let n=await this.store.load(),i=Jn(n.bundle,e);if(!i.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(i.errors)}`);let r=await this.store.commitReviewPlan(i.plan,t);return await this.refreshIndex(r),r}async commitConversationalReview(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",action:e.action,proposalId:e.proposalId,message:"Canonical memory is not ready; the review was not committed."};let t=await this.store.load(),n=t.bundle.records.find(k=>k.recordType==="proposal"&&k.id===e.proposalId),i=t.bundle.records.find(k=>k.recordType==="participant"&&k.kind==="human"&&k.status==="active");if(!n||n.state!=="pending"||!i)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:n?n.state!=="pending"?`The proposal is already ${n.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let r=Date.now(),s=new Date(r).toISOString(),c={proposalId:n.id,participantId:i.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:s},d=e.action==="accept"?{...c,action:"accept",eventId:we(r),decisionId:we(r),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:we(r),replacementProposalId:we(r),acceptanceEventId:we(r),decisionId:we(r),relationshipId:we(r),claim:e.claim,kind:e.kind,subjects:n.subjects,subjectSemantics:n.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:we(r),reason:e.reason}:{...c,action:"defer",eventId:we(r),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:n.subjects.map(k=>k.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},u=Jn(t.bundle,d);if(!u.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:u.errors.map(k=>k.message).join(" ")};let I=await this.store.commitReviewPlan(u.plan,{transactionId:we(r),committedAt:s});await this.refreshIndex(I);let T=u.plan.resultRefs.find(k=>k.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:T,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:I.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),n=Zi(t.bundle,e),i=ie(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let r=await this.store.commit(n.mutation,{transactionId:i,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(r),{status:"captured",iterationId:n.iterationId,proposalIds:n.proposalIds,headSequence:r.report.headSequence}}catch(r){if(r instanceof Error&&r.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:n.iterationId,proposalIds:n.proposalIds};throw r}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=xt(JSON.parse(await rn(Nt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let n=await this.store.load(),i=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="human"&&m.status==="active"),r=n.bundle.records.find(m=>m.recordType==="participant"&&m.kind==="ai"&&m.status==="active"),s=e.action?i:r??i,c=n.bundle.records.find(m=>m.recordType==="subject"&&m.subjectType==="project");if(!s||!c)return;let d=e.occurredAt??new Date().toISOString(),u=Date.parse(d),I=n.bundle.manifest.projectId,T=[],k=[],P=[],x=n.bundle.records.filter(m=>m.recordType==="advisory_explanation"),p=new Map(x.flatMap(m=>{let h=Un(m);return h?[[h,m.id]]:[]}));for(let m of e.summary.changes)if(!p.has(m.explanationId)){let h=t?.explanations.find(j=>j.id===m.explanationId);p.set(m.explanationId,ie(I,"imprint-explanation",m.explanationId,Date.parse(h?.createdAt??d)))}for(let m of e.summary.changes){let h={kind:"external",id:m.explanationId,uri:sn},j=p.get(m.explanationId),b=x.find(R=>R.id===j),g=t?.explanations.find(R=>R.id===m.explanationId),B={id:ie(I,"imprint-live-evidence",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"evidence",kind:e.action?"user_feedback":"judgment",summary:e.action?`${e.action}: ${e.summary.detail}`:`${e.summary.kind}: ${e.summary.detail}`,availability:"available",artifactIds:[]};T.push(B);let E={id:j,schemaVersion:1,projectId:I,createdAt:b?.createdAt??g?.createdAt??d,participantId:b?.participantId??s.id,sourceRefs:qo([...b?.sourceRefs??[],h,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:g?.kind??b?.kind??"pattern",state:g?.state??m.state,statement:g?.statement??m.statement,rationale:g?.rationale??b?.rationale??e.summary.detail,scope:structuredClone(g?.scope??b?.scope??{kind:"project",values:[]}),subjectIds:b?.subjectIds??[c.id],evidenceIds:[...new Set([...b?.evidenceIds??[],B.id])],concreteBindings:g?zn(t,m.explanationId):b?.concreteBindings??[],supersededById:g?.supersededBy?p.get(g.supersededBy):b?.supersededById,updatedAt:g?.updatedAt??d};b?k.push(E):T.push(E),P.push({id:ie(I,"imprint-live-evidence-link",`${e.summary.transactionId}:${m.explanationId}:${e.action??"automatic"}`,u),schemaVersion:1,projectId:I,createdAt:d,participantId:s.id,sourceRefs:[h],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:E.id},to:{entityType:"evidence",entityId:B.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let l=new Set(n.bundle.relationships.flatMap(m=>m.sourceRefs.flatMap(h=>h.kind==="external"&&h.uri===Jt?[h.id]:[])));for(let m of t?.relations??[]){let h=Fo(m.type);if(!h)continue;let j=p.get(m.fromId),b=p.get(m.toId);!j||!b||l.has(m.id)||P.push({id:ie(I,"imprint-relation",m.id,Date.parse(m.createdAt)),schemaVersion:1,projectId:I,createdAt:m.createdAt,participantId:s.id,sourceRefs:[{kind:"external",id:m.id,uri:Jt}],recordType:"relationship",relationshipType:h,from:{entityType:"advisory_explanation",entityId:j},to:{entityType:"advisory_explanation",entityId:b},reason:m.rationale||"The Imprint graph connected these explanations."})}let f=ie(n.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,u);try{let m=await this.store.commit({records:T,recordReplacements:k,events:[],relationships:P,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:f,committedAt:d});await this.refreshIndex(m)}catch(m){if(!(m instanceof Error)||!m.message.includes("Transaction already exists"))throw m}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=xt(JSON.parse(await rn(Nt(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),n=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="human"&&g.status==="active"),r=t.bundle.records.find(g=>g.recordType==="participant"&&g.kind==="ai"&&g.status==="active")??n;if(!r)return{status:"not_ready",relationships:0,explanations:0};let s=t.bundle.records.find(g=>g.recordType==="subject"&&g.subjectType==="project");if(!s)return{status:"not_ready",relationships:0,explanations:0};let c=t.bundle.manifest.projectId,d=t.bundle.records.filter(g=>g.recordType==="advisory_explanation"),u=new Map(d.flatMap(g=>{let B=Un(g);return B?[[B,g]]:[]})),I=new Map([...[...u].map(([g,B])=>[g,B.id]),...e.explanations.filter(g=>!u.has(g.id)).map(g=>[g.id,ie(c,"imprint-explanation",g.id,Date.parse(g.createdAt))])]),T=[],k=[],P=new Set(e.explanations.map(g=>g.id));for(let g of e.explanations){let B=u.get(g.id);if(!B){T.push({id:I.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:zn(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt});continue}let E={...structuredClone(B),kind:g.kind,state:g.state,statement:g.statement,rationale:g.rationale,scope:structuredClone(g.scope),concreteBindings:zn(e,g.id),supersededById:g.supersededBy?I.get(g.supersededBy):void 0,updatedAt:g.updatedAt},R=N=>JSON.stringify({kind:N.kind,state:N.state,statement:N.statement,rationale:N.rationale,scope:N.scope,concreteBindings:N.concreteBindings,supersededById:N.supersededById,updatedAt:N.updatedAt});R(B)!==R(E)&&k.push(E)}for(let[g,B]of u)P.has(g)||B.state==="retired"||k.push({...structuredClone(B),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let x=new Set(t.bundle.tombstones.flatMap(g=>g.objectType==="relationship"?[g.objectId]:[])),p=new Map(t.bundle.relationships.flatMap(g=>{if(x.has(g.id))return[];let B=g.sourceRefs.find(E=>E.kind==="external"&&E.uri===Jt)?.id;return B?[[B,g]]:[]})),l=[],f=new Set;for(let g of e.relations){let B=Fo(g.type);if(!B)continue;let E=I.get(g.fromId),R=I.get(g.toId);if(!E||!R)continue;let N=p.get(g.id);N&&N.relationshipType===B&&N.from.entityType==="advisory_explanation"&&N.from.entityId===E&&N.to.entityType==="advisory_explanation"&&N.to.entityId===R||(N&&f.add(g.id),l.push({id:ie(c,"imprint-relation",`${g.id}:${B}:${E}:${R}`,Date.parse(g.createdAt)),schemaVersion:1,projectId:c,createdAt:g.createdAt,participantId:r.id,sourceRefs:[{kind:"external",id:g.id,uri:Jt}],recordType:"relationship",relationshipType:B,from:{entityType:"advisory_explanation",entityId:E},to:{entityType:"advisory_explanation",entityId:R},reason:g.rationale||"The Imprint graph connected these explanations."}))}let m=new Set(e.relations.map(g=>g.id)),h=n?[...p].filter(([g])=>!m.has(g)||f.has(g)).map(([,g])=>({id:ie(c,"imprint-relationship-tombstone",g.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:c,objectId:g.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!T.length&&!k.length&&!l.length&&!h.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let j=e.updatedAt,b=ie(c,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(j));try{let g=await this.store.commit({records:T,recordReplacements:k,events:[],relationships:l,artifacts:[],tombstones:h,projectionUpdates:[]},{transactionId:b,committedAt:j});return await this.refreshIndex(g),{status:"synced",relationships:l.length+h.length,explanations:T.length+k.length,headSequence:g.report.headSequence}}catch(g){if(!(g instanceof Error)||!g.message.includes("Transaction already exists"))throw g;return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence}}}async recover(e){if(!e)throw new Error("Explicit confirmation is required to recover the journal head.");if(!(await this.status()).initialized)throw new Error("Memory storage is not initialized.");let t=await this.store.recover();return await this.refreshIndex(t),t}async diagnostics(){let e=await this.status();if(!e.initialized)return{status:e};let t=await this.store.load();await this.refreshIndex(t);let n={};for(let i of t.bundle.records)n[i.recordType]=(n[i.recordType]??0)+1;return{status:e,journal:t.report,records:n,openFreshnessSignals:t.bundle.records.filter(i=>i.recordType==="freshness_signal"&&i.state==="open").length,unavailableEvidence:t.bundle.records.filter(i=>i.recordType==="evidence"&&i.availability!=="available").length}}async getProjectableDecisions(e=12){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),n=new Set(t.records.flatMap(s=>s.recordType==="model_projection"&&s.state==="applied"?s.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),i=new Set(t.relationships.flatMap(s=>s.relationshipType==="contradicts"&&s.from.entityType==="decision"&&s.to.entityType==="decision"?[s.from.entityId,s.to.entityId]:[])),r=new Set(t.records.flatMap(s=>s.recordType==="freshness_signal"&&s.state==="open"&&s.target.entityType==="decision"?[s.target.entityId]:[]));return t.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&!n.has(s.id)&&!i.has(s.id)&&!r.has(s.id)).sort((s,c)=>c.createdAt.localeCompare(s.createdAt)).slice(0,Math.max(1,e))}async getCanonicalModelEntries(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(i=>i.recordType==="decision"&&i.state==="active"?[i.id]:[])),n=new Map;for(let i of e.records.filter(r=>r.recordType==="model_entry").sort((r,s)=>r.createdAt.localeCompare(s.createdAt)))i.decisionIds.some(r=>t.has(r))&&n.set(i.key,i);return[...n.values()]}async getImprintView(e=[],t){let n=()=>({head:{sequence:0,updatedAt:new Date(0).toISOString()},counts:{total:0,emerging:0,testing:0,grounded:0,challenged:0,retired:0,needsGrounding:0},explanations:[]});if(!(await this.status()).initialized)return n();let i=await this.store.load(),r=i.bundle.records.filter(l=>l.recordType==="advisory_explanation"),s=new Map(r.map(l=>[l.id,l])),c=new Map(r.flatMap(l=>{let f=Un(l);return f?[[f,l.id]]:[]})),d=new Set(e.map(l=>c.get(l)??l)),u=new Map(i.bundle.records.flatMap(l=>l.recordType==="participant"?[[l.id,l.kind]]:[])),I=new Map(i.bundle.records.flatMap(l=>l.recordType==="evidence"?[[l.id,l]]:[])),T=new Set(i.bundle.tombstones.flatMap(l=>l.objectType==="relationship"?[l.objectId]:[])),k=new Set(["operationalizes","excepts"]),P={testing:0,emerging:1,grounded:2,challenged:3,retired:4},x=r.map(l=>{let f=l.evidenceIds.flatMap(b=>{let g=I.get(b);if(!g)return[];let B=g.sourceRefs.find(V=>V.kind==="thread")?.id,E=g.sourceRefs.find(V=>V.kind==="message")?.id,R=g.kind==="judgment"||g.kind==="user_feedback"||g.kind==="project_state"?g.kind:"other",N=u.get(g.participantId)??"unknown";return[{id:g.id,kind:R,summary:g.summary,createdAt:g.createdAt,participantKind:N,threadId:B,jobId:E}]}).sort((b,g)=>g.createdAt.localeCompare(b.createdAt)),m=i.bundle.relationships.flatMap(b=>{if(T.has(b.id))return[];if(!k.has(b.relationshipType))return[];let g=b.from.entityType==="advisory_explanation"&&b.from.entityId===l.id&&b.to.entityType==="advisory_explanation",B=b.to.entityType==="advisory_explanation"&&b.to.entityId===l.id&&b.from.entityType==="advisory_explanation";if(!g&&!B)return[];let E=g?b.to.entityId:b.from.entityId,R=s.get(E);return R?[{id:b.id,type:b.relationshipType==="operationalizes"?"expresses":"excepts",direction:g?"outgoing":"incoming",explanationId:R.id,statement:R.statement,rationale:b.reason}]:[]}),h=[...(l.supersededById?[l.supersededById]:[]).flatMap(b=>{let g=s.get(b);return g?[{id:`supersedes:${l.id}:${g.id}`,type:"supersedes",direction:"incoming",explanationId:g.id,statement:g.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...r.flatMap(b=>b.supersededById===l.id?[{id:`supersedes:${b.id}:${l.id}`,type:"supersedes",direction:"outgoing",explanationId:b.id,statement:b.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],j=[...new Set([...l.sourceRefs.flatMap(b=>b.kind==="thread"?[b.id]:[]),...f.flatMap(b=>b.threadId?[b.threadId]:[])])].filter(b=>!t||t.has(b));return{id:l.id,kind:l.kind,state:l.state,statement:l.statement,rationale:l.rationale,scope:structuredClone(l.scope),createdAt:l.createdAt,updatedAt:l.updatedAt,evidenceCount:f.length,recentEvidence:f.slice(0,4),concrete:l.concreteBindings.map(b=>({...structuredClone(b)})),relations:[...m,...h],sourceThreadIds:j,needsGrounding:l.state==="testing"&&d.has(l.id)}}).sort((l,f)=>Number(f.needsGrounding)-Number(l.needsGrounding)||P[l.state]-P[f.state]||f.updatedAt.localeCompare(l.updatedAt)),p={total:x.filter(l=>l.state!=="retired").length,emerging:x.filter(l=>l.state==="emerging").length,testing:x.filter(l=>l.state==="testing").length,grounded:x.filter(l=>l.state==="grounded").length,challenged:x.filter(l=>l.state==="challenged").length,retired:x.filter(l=>l.state==="retired").length,needsGrounding:x.filter(l=>l.needsGrounding).length};return{head:{sequence:i.report.headSequence,updatedAt:i.bundle.manifest.updatedAt},counts:p,explanations:x}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(c=>c.recordType==="decision"&&c.state==="active"?[c.id]:[])),n=new Map;for(let c of e.records.filter(d=>d.recordType==="model_entry").sort((d,u)=>d.createdAt.localeCompare(u.createdAt)))c.decisionIds.some(d=>t.has(d))&&n.set(c.key,c);let i=[...n.values()],r=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let d=r.filter(u=>u.targets.some(I=>I.entityType==="decision"&&I.entityId===c.id)).sort((u,I)=>I.createdAt.localeCompare(u.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:i.some(u=>u.decisionIds.includes(c.id)),verification:d?d.state:"unverified"}}),entries:i.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async recordDirectModelMutation(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");let t=await this.store.load(),n=t.bundle.records.find(R=>R.recordType==="participant"&&R.kind==="human"&&R.status==="active"),i=t.bundle.records.find(R=>R.recordType==="subject"&&R.subjectType==="project");if(!n||!i)throw new Error("Canonical owner or project subject is unavailable.");let r=Date.now(),s=new Date(r).toISOString(),c=we(r),d=we(r),u=we(r),I=we(r),T=we(r),k=new Set(t.bundle.records.flatMap(R=>R.recordType==="model_entry"&&R.key===e.key?R.decisionIds:[])),P=t.bundle.records.filter(R=>R.recordType==="decision"&&R.state==="active"&&k.has(R.id)),x={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:s,participantId:n.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},p=[{subjectId:i.id,role:"governed"}],l={...x,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:p,origin:{mode:"declared",sourceText:e.claim,reviewedById:n.id}},f={...x,id:d,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:c},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},m={...x,id:u,recordType:"decision",proposalId:c,acceptanceEventId:d,acceptedById:n.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:p,noChange:!1,effectiveAt:s},h={...x,id:I,recordType:"model_entry",key:e.key,subjectIds:[i.id],decisionIds:[u],value:e.value},j={...x,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${r}`,appliedById:n.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:s,decisionIds:[u],entryIds:[I],coverage:[{decisionId:u,status:"projected"}]},b={...x,id:we(r),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:I},to:{entityType:"decision",entityId:u},reason:"The model change is projected from the owner-confirmed decision."},g=P.map(R=>({...x,id:we(r),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:R.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),B=P.map(R=>({...x,id:we(r),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:m.id},to:{entityType:"decision",entityId:R.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),E=await this.store.commit({records:[l,m,h,j],events:[f,...g],relationships:[b,...B],artifacts:[],tombstones:[],projectionUpdates:P.map(R=>({entityType:"decision",entityId:R.id,fromState:"active",state:"superseded"}))},{transactionId:we(r),committedAt:s});return await this.refreshIndex(E),{decisionId:u,entryId:I}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),n=t.records.find(i=>i.recordType==="proposal"&&i.state==="pending"&&i.sourceRefs.some(r=>r.id===e));return n?{proposalId:n.id,claim:n.claim}:null}async applyModelProjection(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)throw new Error("Canonical memory is not ready.");if(e.changes.length===0)throw new Error("A model projection requires selected changes.");let t=await this.store.load(),n=t.bundle.records.find(x=>x.recordType==="model_projection"&&x.state==="applied"&&x.runId===e.runId);if(n)return{projectionId:n.id,entryIds:n.entryIds,headSequence:t.report.headSequence};let i=t.bundle.records.filter(x=>x.recordType==="decision"&&e.decisionIds.includes(x.id)&&x.state==="active");if(i.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let r=t.bundle.records.find(x=>x.recordType==="participant"&&x.kind==="human"&&x.status==="active");if(!r)throw new Error("No active local owner participant is available.");let s=Date.now(),c=new Date(s).toISOString(),d=we(s),u=e.changes.map(x=>{let p=x.decisionIds?.filter(m=>e.decisionIds.includes(m)),l=p?.length?p:e.decisionIds,f=[...new Set(i.filter(m=>l.includes(m.id)).flatMap(m=>m.subjects.map(h=>h.subjectId)))];return{id:we(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:l.map(m=>({kind:"record",id:m})),recordType:"model_entry",key:x.path.map(String).join("."),subjectIds:f,decisionIds:l,value:x.value}}),I=new Set(u.flatMap(x=>x.decisionIds)),T={id:d,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:e.decisionIds.map(x=>({kind:"record",id:x})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:r.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:u.map(x=>x.id),coverage:e.decisionIds.map(x=>e.coverage?.find(p=>p.decisionId===x)??{decisionId:x,status:I.has(x)?"projected":"unprojected"})},k=u.flatMap(x=>x.decisionIds.map(p=>({id:we(s),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:r.id,sourceRefs:[{kind:"record",id:T.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x.id},to:{entityType:"decision",entityId:p},reason:"The owner applied this model entry as a projection of accepted product truth."}))),P=await this.store.commit({records:[...u,T],events:[],relationships:k,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:we(s),committedAt:c});return await this.refreshIndex(P),{projectionId:d,entryIds:u.map(x=>x.id),headSequence:P.report.headSequence}}async loadSource(e){if((await this.status()).initialized){let t=await this.store.load();return{source:"journal",bundle:t.bundle,journal:t.report}}return{source:"legacy_preview",bundle:(await St({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let n=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),i=or(n,t.subjectHints??[]);return i?{...t,subjectIds:[...new Set([...t.subjectIds??[],...i.subjectIds])],candidateDecisionIds:i.decisionIds,candidateProposalIds:i.proposalIds}:t}async refreshIndex(e){await this.indexStore.ensure(e.bundle,{sequence:e.report.headSequence,hash:e.report.headHash}),e.report.headSequence-e.report.checkpointSequence>=250&&await this.store.rotateCheckpoint()}};function Lt(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,t){let n=Te(o,e);if(!t.includes(n))throw new Error(`${e} is invalid.`);return n}function Uo(o){let e=Lt(o),t=Lt(e.authority),n=t.level,i=t.mode,r=Bt(n,"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 t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:Te(e.eventId,"eventId"),decisionId:Te(e.decisionId,"decisionId"),kind: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=Lt(e.context);if(!Array.isArray(d.subjectIds)||!Array.isArray(d.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:Te(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof d.taskContext=="string"?d.taskContext:void 0,subjectIds:d.subjectIds.map(u=>Te(u,"subjectId")),resurfaceWhen:d.resurfaceWhen.map(u=>Bt(u,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof d.revisitAfter=="string"?d.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...c,action:"edit_and_accept",withdrawalEventId:Te(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:Te(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:Te(e.acceptanceEventId,"acceptanceEventId"),decisionId:Te(e.decisionId,"decisionId"),relationshipId:Te(e.relationshipId,"relationshipId"),claim:Te(e.claim,"claim"),kind:Bt(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(d=>{let u=Lt(d);return{subjectId:Te(u.subjectId,"subjectId"),role:Bt(u.role,"role",["governed","consumer","provider","context"])}}),subjectSemantics:typeof e.subjectSemantics=="string"?e.subjectSemantics:void 0,rationale:typeof e.rationale=="string"?e.rationale:void 0,reason:Te(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function zo(o){let e=Lt(o),t=(r,s)=>{if(r!==void 0){if(!Array.isArray(r))throw new Error(`${s} must be an array.`);return r.map(c=>Te(c,s))}},n=(r,s)=>{if(r!==void 0){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new Error(`${s} must be a positive number.`);return r}},i=e.resurface===void 0?void 0:Lt(e.resurface);if(e.generatedAt!==void 0&&(typeof e.generatedAt!="string"||Number.isNaN(Date.parse(e.generatedAt))))throw new Error("generatedAt must be an ISO-8601 timestamp.");return{action:typeof e.action=="string"?e.action:void 0,text:typeof e.text=="string"?e.text:void 0,subjectIds:t(e.subjectIds,"subjectIds"),subjectHints:t(e.subjectHints,"subjectHints"),maxPackets:n(e.maxPackets,"maxPackets"),maxEstimatedTokens:n(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:i?{differentAction:i.differentAction===!0,newEvidence:i.newEvidence===!0,newConflict:i.newConflict===!0,ownerRequested:i.ownerRequested===!0}:void 0}}function qt(o){return o.annotations.map(e=>e.instruction?.trim()).filter(e=>!!e).join(`
|
|
158
|
+
`)}async function ar(o,e,t,n){let i=qt(e);if(!(!i&&t.length===0))try{let r=await o.contextualize({action:i||void 0,subjectHints:t,maxPackets:2,maxEstimatedTokens:700});if(r.actionPacket.decisions.length===0&&r.reviewSelection.packets.length===0)return;let s=new Map(r.actionPacket.implementation.map(d=>[d.decisionId,d.state])),c=new Map(r.actionPacket.verification.map(d=>[d.target.entityId,d.state]));return{source:r.source,...r.actionPacket.decisions.length>0?{acceptedTruth:{decisions:r.actionPacket.decisions.map(d=>({...d,implementation:s.get(d.id)??"unknown",verification:c.get(d.id)??"unverified"})),conflicts:r.actionPacket.conflicts,truncated:r.actionPacket.completeness.status==="truncated"}}:{},packets:r.reviewSelection.packets.map(d=>({packetId:d.packetId,proposalId:d.proposal.id,claim:d.proposal.claim,proposedKind:d.proposal.proposedKind,authority:d.authority,presentation:d.presentation,subjectLabels:d.trigger.subjectMatches.map(u=>u.label),evidenceCount:d.evidence.sourceCount,expansionRefs:d.expansionRefs})),truncated:r.reviewSelection.completeness.status==="truncated",estimatedTokens:r.actionPacket.budget.estimatedTokens+r.reviewSelection.completeness.estimatedTokens}}catch(r){n?.(r);return}}function cr(o){if(!o?.packets.length&&!o?.acceptedTruth?.decisions.length)return"";let e=o.packets.some(n=>n.presentation==="surface_before_action");return["","## Contextual product memory","",...o.acceptedTruth?.decisions.length?["### Accepted product truth","","These decisions are authoritative within their stated scope. Preserve them unless the task explicitly revises them. Do not silently resolve conflicts or ignore freshness warnings.",...o.acceptedTruth.decisions.flatMap((n,i)=>["",`${i+1}. [${n.kind}; ${n.effectiveState}] ${n.claim}`,` - Implementation: ${n.implementation}`,` - Verification: ${n.verification}`,...n.freshness.length?[` - Freshness warnings: ${n.freshness.join(", ")}`]:[],` - Decision: ${n.id}`]),...o.acceptedTruth.conflicts.length?["","Applicable accepted decisions contain an unresolved conflict. Ask the developer before choosing a side:",...o.acceptedTruth.conflicts.map(n=>`- ${n.unresolvedQuestion}`)]:[],...o.acceptedTruth.truncated?["","The accepted-truth packet is truncated; expand memory before making a broad or irreversible change."]:[],""]:[],...o.packets.length?["### Historical candidates","","The following records are unaccepted historical candidates, not project truth. Do not silently enforce or restate them as accepted decisions.",...o.packets.flatMap((n,i)=>["",`${i+1}. ${n.claim}`," - Authority: unaccepted candidate",` - Proposed kind: ${n.proposedKind??"unspecified"}`,` - Presentation: ${n.presentation}`,` - Packet: ${n.packetId}`,` - Evidence references available: ${n.evidenceCount}`]),"",e?"At least one candidate is marked surface_before_action. Before changing files, ask the developer a concise <question> that identifies the candidate and asks whether it should govern this task.":"These candidates are advisory. Continue the task, and mention a candidate conversationally only if it materially affects the implementation or deserves owner confirmation.","","If\u2014and only if\u2014the developer explicitly resolves one of these exact candidates in this conversation, emit one machine-readable block in addition to your normal response:",'<memory-review>{"proposalId":"<exact packet proposal id>","action":"accept|edit_and_accept|reject|defer","kind":"principle|preference|rule|constraint","claim":"<required only when edited>","reason":"<why this reflects the developer reply>","taskContext":"<current task for deferral>","resurfaceWhen":["different_action","owner_request"]}</memory-review>',"Never infer acceptance from implementation, praise, silence, or an ambiguous reply. Do not emit this block when the developer has not explicitly resolved the candidate."]:[]].join(`
|
|
159
|
+
`)}function dr(o){let e=o.match(/<memory-review>\s*([\s\S]*?)\s*<\/memory-review>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]);if(typeof t.proposalId!="string"||!["accept","edit_and_accept","reject","defer"].includes(String(t.action)))return null;let n=t.action,i=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:void 0;if((n==="accept"||n==="edit_and_accept")&&!i||n==="edit_and_accept"&&typeof t.claim!="string"||n!=="defer"&&(typeof t.reason!="string"||!t.reason.trim()))return null;let r=new Set(["different_action","new_evidence","new_conflict","owner_request"]),s=Array.isArray(t.resurfaceWhen)?t.resurfaceWhen.filter(c=>typeof c=="string"&&r.has(c)):void 0;return{proposalId:t.proposalId,action:n,kind:i,claim:typeof t.claim=="string"?t.claim:void 0,reason:typeof t.reason=="string"?t.reason:void 0,taskContext:typeof t.taskContext=="string"?t.taskContext:void 0,resurfaceWhen:s}}catch{return null}}function lr(o){let e=o.match(/<memory-review-card>\s*([\s\S]*?)\s*<\/memory-review-card>/);if(!e?.[1])return null;try{let t=JSON.parse(e[1]),n=["principle","preference","rule","constraint"].includes(String(t.kind))?t.kind:null;return!n||typeof t.proposalId!="string"||!t.proposalId||typeof t.title!="string"||!t.title.trim()||typeof t.claim!="string"||!t.claim.trim()||typeof t.rationale!="string"||!t.rationale.trim()?null:{proposalId:t.proposalId,kind:n,title:t.title.trim(),claim:t.claim.trim(),rationale:t.rationale.trim(),scope:typeof t.scope=="string"&&t.scope.trim()?t.scope.trim():void 0}}catch{return null}}async function Go(o){let t=(o.headers["content-type"]||"").match(/boundary=(?:"([^"]+)"|([^\s;]+))/);if(!t)throw new Error("Missing multipart boundary");let n=t[1]||t[2],i=await hc(o),r=Buffer.from(`--${n}`),s=Buffer.from(`--${n}--`),c,d,u,I,T,k,P,x,p,l,f,m,h,j,b=[],g=[],B=0,E=[];for(;B<i.length;){let R=i.indexOf(r,B);if(R===-1)break;let N=R+r.length;if(i.slice(R,R+s.length).equals(s))break;let V=N;i[V]===13&&i[V+1]===10&&(V+=2);let K=i.indexOf(`\r
|
|
155
160
|
\r
|
|
156
|
-
`,
|
|
161
|
+
`,V);if(K===-1)break;let W=i.slice(V,K).toString("utf-8"),Q=K+4,w=i.indexOf(r,Q),H=w!==-1?w-2:i.length;E.push({headers:W,body:i.slice(Q,H)}),B=w!==-1?w:i.length}for(let R of E){let N=R.headers.match(/name="([^"]+)"/);if(!N)continue;let V=N[1];if(V==="screenshot")c=R.body;else if(V==="feedback")d=R.body.toString("utf-8");else if(V==="color")u=R.body.toString("utf-8");else if(V==="provider")I=R.body.toString("utf-8");else if(V==="model")T=R.body.toString("utf-8");else if(V==="reasoningEffort")k=R.body.toString("utf-8");else if(V==="serviceTier")P=R.body.toString("utf-8");else if(V==="goal")x=R.body.toString("utf-8");else if(V==="pageUrl")p=R.body.toString("utf-8");else if(V==="viewport")l=R.body.toString("utf-8");else if(V==="planId")f=R.body.toString("utf-8");else if(V==="manifest")m=R.body.toString("utf-8");else if(V==="tasks")h=R.body.toString("utf-8");else if(V==="sourceId")j=R.body.toString("utf-8");else if(V.startsWith("screenshot-")){let K=V.slice(11);try{let 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)&&b.push({annotationId:Q,index:W,data:R.body})}}if(!c)throw new Error("Missing screenshot field");return d||(d=""),{screenshot:c,feedback:d,color:u,provider:I,model:T,reasoningEffort:k,serviceTier:P,goal:x,pageUrl:p,viewport:l,planId:f,manifest:m,tasks:h,sourceId:j,pastedImages:b,pageScreenshots:g}}function hc(o){return new Promise((e,t)=>{let n=[];o.on("data",i=>n.push(i)),o.on("end",()=>e(Buffer.concat(n))),o.on("error",t)})}import{randomUUID as gc}from"crypto";var an="<orientation>",ot="</orientation>";function Wo(o,e){let t=e;for(;t<o.length&&/\s/.test(o[t]);)t++;if(t>=o.length)return{status:"incomplete",start:t};if(o[t]!=="{")return{status:"invalid",start:t};let n=0,i=!1,r=!1;for(let s=t;s<o.length;s++){let c=o[s];if(i){r?r=!1:c==="\\"?r=!0:c==='"'&&(i=!1);continue}if(c==='"')i=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0)return{status:"complete",start:t,end:s+1};if(n<0)return{status:"invalid",start:t}}}return{status:"incomplete",start:t}}function pr(o,e){if(!e)return;let t=o[o.length-1];t?.kind==="text"?t.text+=e:o.push({kind:"text",text:e})}function ur(o){let e=[],t=0;for(;t<o.length;){let n=o.indexOf(an,t);if(n<0){pr(e,o.slice(t));break}pr(e,o.slice(t,n));let i=n+an.length,r=Wo(o,i);if(r.status!=="complete"){let c=o.indexOf(ot,i);if(c>=0){t=c+ot.length;continue}t=i;continue}e.push({kind:"orientation",json:o.slice(r.start,r.end)}),t=r.end;let s=t;for(;s<o.length&&/\s/.test(o[s]);)s++;o.startsWith(ot,s)&&(t=s+ot.length)}return e}var yc=new Set(["focus_set","focus_shifted","evidence_updated","hypothesis_changed","assumption_abandoned","uncertainty_identified","next_observation_selected"]),vc=new Set(["strengthened","weakened","mixed","unknown"]);function cn(o,e=180){if(typeof o!="string")return;let t=o.replace(/\s+/g," ").trim();if(t)return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ic(o){return!o||typeof o!="object"||Array.isArray(o)?null:o}function mr(o,e,t,n=Date.now()){let i=Ic(o);if(!i)return null;let r=typeof i.transition=="string"&&yc.has(i.transition)?i.transition:null,s=cn(i.focus);if(!r||!s)return null;let c=typeof i.evidencePosture=="string"&&vc.has(i.evidencePosture)?i.evidencePosture:void 0;return{id:gc(),jobId:e,sequence:t,timestamp:n,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 Ho(o){return JSON.stringify({transition:o.transition,snapshot:o.snapshot})}function Vo(o,e,t=0){let n=[],i=[],r=new Set,s=t;for(let d of ur(o)){if(d.kind==="text"){d.text&&i.push(d);continue}try{let u=mr(JSON.parse(d.json),e,s);if(!u)continue;let I=Ho(u);if(r.has(I))continue;r.add(I),n.push(u),i.push({kind:"orientation",orientation:u}),s++}catch{}}return{visibleText:i.map(d=>d.kind==="text"?d.text:`
|
|
157
162
|
|
|
158
|
-
`).
|
|
163
|
+
`).join("").replace(/\n{3,}/g,`
|
|
164
|
+
|
|
165
|
+
`).trim(),orientations:n,segments:i}}function wc(o){let e="<orientation>",t=Math.min(o.length,e.length-1);for(let n=t;n>0;n--)if(e.startsWith(o.slice(-n)))return n;return 0}var Wn=class{constructor(e){this.jobId=e;this.buffer="";this.sequence=0;this.signatures=new Set;this.optionalClosePending=!1}push(e){this.buffer+=e;let t="",n=[];for(;this.buffer;){if(this.optionalClosePending){let d=0;for(;d<this.buffer.length&&/\s/.test(this.buffer[d]);)d++;let u=this.buffer.slice(d);if(ot.startsWith(u)&&u.length<ot.length||(u.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=wc(this.buffer);t+=d>0?this.buffer.slice(0,-d):this.buffer,this.buffer=d>0?this.buffer.slice(-d):"";break}t+=this.buffer.slice(0,i);let r=i+an.length,s=Wo(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=mr(JSON.parse(c),this.jobId,this.sequence);if(!d)continue;let u=Ho(d);if(this.signatures.has(u))continue;this.signatures.add(u),n.push(d),this.sequence++}catch{}}return{visibleText:t,orientations:n}}finalize(e){let t=Vo(e,this.jobId,this.sequence),n=t.orientations.filter(i=>{let r=Ho(i);return this.signatures.has(r)?!1:(this.signatures.add(r),this.sequence++,!0)});return this.buffer="",this.optionalClosePending=!1,{visibleText:t.visibleText,orientations:n}}},fr=`## Public orientation updates
|
|
159
166
|
During meaningful transitions in the work, emit a brief public coordination update using this exact form:
|
|
160
167
|
<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>
|
|
161
168
|
|
|
162
169
|
Allowed transitions: focus_set, focus_shifted, evidence_updated, hypothesis_changed, assumption_abandoned, uncertainty_identified, next_observation_selected.
|
|
163
170
|
Optional fields: seeking, workingHypothesis, evidencePosture (strengthened, weakened, mixed, unknown), update, nextObservation.
|
|
164
171
|
|
|
165
|
-
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
|
|
166
|
-
### ${
|
|
167
|
-
`)}function
|
|
168
|
-
`)}function
|
|
169
|
-
`)}function
|
|
170
|
-
`)){if(/^\s*`model`:/.test(
|
|
171
|
-
`));return
|
|
172
|
-
`,"utf8"),await t.sync()}finally{await t.close()}try{await ac(n,o)}catch(r){throw await cc(n).catch(()=>{}),r}}function lc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function pc(o,e){let n=o.explanations.findIndex(t=>t.id===e.id);n>=0?o.explanations[n]=Ee(e):o.explanations.push(Ee(e))}function Co(o,e){let n=Ee(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(Ee(t.explanation))}else if(t.op==="replace_explanation")pc(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(Ee(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(Ee(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,Ee(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(Ee(t.relation))}else t.op==="remove_relation"&&(n.relations=n.relations.filter(r=>r.id!==t.relationId));return n}function uc(o,e){let n=[],t=Ee(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:Ee(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:Ee(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:Ee(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:Ee(i)})}t=Co(t,[r])}return n}function ti(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 qn=class{constructor(e,n){this.projectRoot=e;this.projectId=n;this.writeChain=Promise.resolve();this.imprintDir=_t(e,".popmelt","imprint"),this.manifestPath=_t(this.imprintDir,"manifest.json"),this.graphPath=_t(this.imprintDir,"graph.json"),this.journalDir=_t(this.imprintDir,"journal")}async readManifest(){try{let e=JSON.parse(await Zr(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 sc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),r=lc(this.projectId,e.createdAt),i=[],s=null;for(let c=0;c<t.length;c++){let d=JSON.parse(await Zr(_t(this.journalDir,t[c]),"utf8")),{hash:p,...x}=d;if(d.sequence!==c+1||d.previousHash!==s||p!==ei(x))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);r=Co(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(j=>j.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let r=t.graph.head.sequence+1,i=uc(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:Ee(e.mutations),inverseMutations:i,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:ei(s)},d=Co(t.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:r,hash:c.hash};let p=`${String(r).padStart(12,"0")}-${e.transactionId}.json`;await nn(_t(this.journalDir,p),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(p=>p.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(i.transactions.some(p=>p.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(ti));if(i.transactions.filter(p=>p.sequence>s.sequence).some(p=>p.mutations.some(x=>ti(x).some(j=>c.has(j)))))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 mc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),fc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function hc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function zn(o){return new Set(hc(o).split(" ").filter(e=>e.length>2&&!fc.has(e)))}function Gn(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 $o(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 ot(o,e,n){return{id:Xe(),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 je(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function ni(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 oi(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 Do(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(!mc.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:je(i?.title,120),detail:je(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()):[],p=[];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=je(b.statement),l=je(b.rationale);if(!h||!l)continue;p.push({op:"add",clientId:je(b.clientId,100)||void 0,kind:b.kind,statement:h,rationale:l,scope:ni(b.scope),rootReason:je(b.rootReason,300)||void 0})}else if(b.op==="revise"&&typeof b.explanationId=="string"){let h={op:"revise",explanationId:b.explanationId,statement:je(b.statement)||void 0,rationale:je(b.rationale)||void 0,scope:ni(b.scope),reopenGrounding:b.reopenGrounding===!0};(h.statement||h.rationale||h.scope||h.reopenGrounding)&&p.push(h)}else if(b.op==="evidence"&&typeof b.explanationId=="string"&&["supports","challenges","excepts"].includes(String(b.stance))){let h=je(b.summary);h&&p.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=je(b.rationale);if(!h)continue;p.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=je(b.reason);h&&p.push({op:"supersede",explanationId:b.explanationId,replacementId:b.replacementId,reason:h})}else if(b.op==="bind_concrete"&&typeof b.explanationId=="string"){let h=je(b.modelPath,300);h&&p.push({op:"bind_concrete",explanationId:b.explanationId,modelPath:h,rationale:je(b.rationale)})}else b.op==="retire"&&typeof b.explanationId=="string"&&p.push({op:"retire",explanationId:b.explanationId,reason:je(b.reason)})}let x=r.grounding,j=x&&typeof x.explanationId=="string"&&je(x.question)?{explanationId:x.explanationId,question:je(x.question,300)}:void 0;return{draft:{decision:"mutate",summary:c,appliedExplanationIds:d,mutations:p,grounding:j},visibleText:n}}catch(r){return{visibleText:n,error:r instanceof Error?r.message:String(r)}}}function Oo(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(`
|
|
173
|
-
`)),...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(`
|
|
174
|
-
`)}var on=class{constructor(e,n){this.noopCounts=new Map;this.store=new qn(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=zn(e.text??""),t=zn((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 l=zn([h.statement,h.rationale].join(" ")),v=zn(h.scope.values.join(" ")),w=Gn(l,n),m=Gn(v,n),u=Gn(v,t),P=Gn(l,t),E=w+m*.2+u*.25+P*.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||P>=.2);return{item:h,score:E,relevant:y}}).filter(h=>h.relevant&&h.score>=.18).sort((h,l)=>l.score-h.score||l.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),p=new Set(d.map(h=>h.id)),x=new Set(i.relations.flatMap(h=>p.has(h.fromId)?[h.toId]:p.has(h.toId)?[h.fromId]:[])),j=new Set(i.explanations.flatMap(h=>x.has(h.id)&&h.state!=="retired"&&h.state!=="challenged"?[h.id]:[])),T=i.explanations.filter(h=>j.has(h.id)&&!p.has(h.id)).sort((h,l)=>l.updatedAt.localeCompare(h.updatedAt)).slice(0,4),b=[...d,...T];for(let h of T)p.add(h.id);return{explanations:b.map(h=>{let l=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=>l.has(v.id)).map(v=>({id:v.id,modelPath:v.modelPath,value:v.value}))}}),truncated:s.length>d.length||T.length<j.size,...r.size?{pendingGroundingExplanationIds:[...r]}:{},relations:i.relations.filter(h=>p.has(h.fromId)&&p.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=[],p=new Set,x=new Set(n.pendingGroundingExplanationIds??[]),j=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)&&oi(n.concreteModel,f.modelPath).found&&h.add(f.explanationId);let l=r.graph.explanations.length===0;for(let f of e.mutations){if(f.op!=="add")continue;let M=!!(f.clientId&&h.has(f.clientId)),O=!!f.rootReason?.trim()||l;if(!M&&!O)continue;l&&(l=!1);let B=Xe();f.clientId&&s.set(f.clientId,B);let z=f.clientId?e.appliedExplanationIds.includes(f.clientId):!1,W={id:B,kind:f.kind,statement:f.statement,rationale:f.rationale,scope:$o(f.scope),state:z?"testing":"emerging",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};i.set(B,W),p.add(B),d.push({op:"add_explanation",explanation:W})}let v=f=>s.get(f)??f;for(let f of e.mutations){if(f.op!=="revise")continue;let M=v(f.explanationId),O=i.get(M);if(O?.state!=="grounded")continue;let B=Xe(),z={id:B,kind:O.kind,statement:f.statement??O.statement,rationale:f.rationale??O.rationale,scope:f.scope?$o(f.scope):O.scope,state:"testing",createdAt:t,updatedAt:t,evidence:[ot(n,"supports",e.summary.detail)]};i.set(B,z),c.set(M,B),p.add(B),d.push({op:"add_explanation",explanation:z}),d.push({op:"add_relation",relation:{id:Xe(),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 O=w(f.explanationId);if(!i.has(O))continue;let B=oi(n.concreteModel,f.modelPath);if(!B.found)continue;let z=r.graph.concrete.find(W=>W.modelPath===f.modelPath&&JSON.stringify(W.value)===JSON.stringify(B.value));z||(z={id:Xe(),modelPath:f.modelPath,value:structuredClone(B.value),createdAt:t,updatedAt:t},d.push({op:"add_concrete",concrete:z})),d.push({op:"add_relation",relation:{id:Xe(),type:"instantiates",fromId:O,toId:z.id,rationale:f.rationale,createdAt:t}}),p.add(O);continue}if(f.op==="relation"){let O=w(f.fromId),B=w(f.toId);if(!i.has(O)||!i.has(B)||O===B)continue;d.push({op:"add_relation",relation:{id:Xe(),type:f.type,fromId:O,toId:B,rationale:f.rationale,createdAt:t}}),p.add(O),p.add(B);continue}if(f.op==="supersede"){let O=w(f.explanationId),B=w(f.replacementId);if(!i.has(O)||!i.has(B)||O===B)continue;d.push({op:"add_evidence",explanationId:O,evidence:ot(n,"challenges",f.reason)}),d.push({op:"revise_explanation",explanationId:O,patch:{state:"challenged",supersededBy:B},updatedAt:t}),d.push({op:"add_relation",relation:{id:Xe(),type:"supersedes",fromId:B,toId:O,rationale:f.reason,createdAt:t}}),p.add(O),p.add(B);continue}let M=w(f.explanationId);if(i.has(M))if(p.add(M),f.op==="revise"){if(c.has(v(f.explanationId)))continue;let O=i.get(M);if(!O||O.state!=="emerging"&&O.state!=="testing")continue;let B={...f.statement?{statement:f.statement}:{},...f.rationale?{rationale:f.rationale}:{},...f.scope?{scope:$o(f.scope)}:{},...f.reopenGrounding||j.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"&&j.has(f.explanationId))continue;d.push({op:"add_evidence",explanationId:M,evidence:ot(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:ot(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),O=i.get(M);!O||O.state==="grounded"||O.state==="retired"||x.has(M)&&!p.has(M)||(p.has(M)||(p.add(M),d.push({op:"add_evidence",explanationId:M,evidence:{...ot(n,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),O.state==="emerging"&&d.push({op:"revise_explanation",explanationId:M,patch:{state:"testing"},updatedAt:t}))}if(!d.length)return;let m=Xe(),u=await this.store.commit({transactionId:m,committedAt:t,source:{kind:"automatic",threadId:n.threadId,jobId:n.jobId},summary:e.summary.title,mutations:d}),P=new Map(u.graph.explanations.map(f=>[f.id,f])),E=[...p].flatMap(f=>{let M=P.get(f);if(!M)return[];let O=!r.graph.explanations.some(z=>z.id===f),B=M.state==="challenged"||M.state==="retired";return[{explanationId:f,action:O?"added":B?"challenged":"revised",statement:M.statement,state:M.state}]}),y=e.grounding?w(e.grounding.explanationId):void 0,L=y?P.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 p=[...new Set([e.summary.transactionId,...e.summary.coalescedTransactionIds??[]])].reverse();for(let x of p)await this.store.undo(x,{kind:"undo",threadId:e.threadId,jobId:e.jobId},n,Xe());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(p=>p.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:{...ot(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:{...ot(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 p=(e.value??"").split(",").map(x=>x.trim()).filter(Boolean);if(!p.length)throw new Error("A narrower scope is required.");c.push({op:"revise_explanation",explanationId:t,patch:{scope:{kind:i.scope.kind,values:p},state:"testing"},updatedAt:n}),d=`Narrowed scope: ${i.statement}`}else if(e.action==="exception")c.push({op:"add_evidence",explanationId:t,evidence:{...ot(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 p=e.value?.trim();if(!p)throw new Error("Edited explanation wording is required.");c.push({op:"revise_explanation",explanationId:t,patch:{statement:p,state:"testing"},updatedAt:n}),d=`Edited: ${p}`}if(!c.length)throw new Error("Unsupported imprint action.");await this.store.commit({transactionId:Xe(),committedAt:n,source:s,summary:d,mutations:c})}};function ri(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 No(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 ii(o){let e=No(Wn(o.origin));if(e)return e;let n=No(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 No(`${r}://${t}`)}function si(o,e,n=5){let t=(d,p)=>(p.completedAt??p.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,p)=>p.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,p)=>(d[p.status]=(d[p.status]??0)+1,d),{});return{recentRuns:r,recentAppliedRuns:i,actionableProposalCounts:c,actionableProposals:s}}import{createHash as Hn}from"crypto";import{mkdir as rn,readFile as vt,unlink as vc,writeFile as $t}from"fs/promises";import{dirname as Vn,extname as wc,join as _e}from"path";var gc={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 yc(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 ai(o,e){let n=e??yc(o);return{kind:n,...gc[n]}}function Ct(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ci(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 Ic={version:1,threads:{}},di=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],sn={version:2,updatedAt:0,files:{}};function bc(o){return JSON.stringify(o,null,2)}function xc(o){return Object.fromEntries(di.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function Sc(o){let e={...o};for(let n of di)delete e[n];return e}function Dt(o){let e=o;if(o.error){let n=ai(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=Ct(e.result,!1),t=Ct(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 Kn=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 vt(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(_e(this.threadsDir,r));i&&(n[t]=i)}return this.cache={version:1,threads:n},this.cache}}catch{}try{let e=JSON.parse(await vt(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={...Ic,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},p=r.messages.findLastIndex(v=>!!d(v)),x=r.messages.findLastIndex(v=>v.role==="human"),j=p>x?d(r.messages[p]):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),l=c.some(v=>!!v.error);return{id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,preview:s,messageCount:r.messages.length,hasReply:h,hasError:l,lastMessageRole:T,pendingQuestion:j,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 vt(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 vt(_e(Vn(this.legacyFilePath),r.path),"utf8");Hn("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=xc(e),t=Sc(e);if(Object.keys(n).length===0)return t;let r=bc(n),i=Hn("sha256").update(r).digest("hex"),s=_e("artifacts","thread-messages",`${i}.json`);await rn(this.artifactsDir,{recursive:!0});try{await vt(_e(Vn(this.legacyFilePath),s),"utf8")}catch{await $t(_e(Vn(this.legacyFilePath),s),r)}return{...t,detailArtifact:{path:s,sha256:i}}}async persistMessageMedia(e){let n=async t=>{if(Vn(t)===this.mediaDir)return t;try{let r=await vt(t),i=Hn("sha256").update(r).digest("hex"),s=_e(this.mediaDir,`${i}${wc(t)||".bin"}`);await rn(this.mediaDir,{recursive:!0});try{await vt(s)}catch{await $t(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]??`${Hn("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 $t(_e(this.threadsDir,t),JSON.stringify(i,null,2)),n.files[e.id]=t,n.updatedAt=Date.now(),this.index=n,await $t(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 $t(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 vc(_e(this.threadsDir,t)).catch(()=>{}),delete n.files[e],n.updatedAt=Date.now(),this.index=n,await rn(this.threadsDir,{recursive:!0}),await $t(this.indexPath,JSON.stringify(n,null,2))}),await this.writeChain}};import{mkdir as Pc,open as kc,readFile as Rc,rename as Tc,unlink as jc}from"fs/promises";import{dirname as Mc,join as Ac}from"path";var li={schemaVersion:1,theme:"auto",updatedAt:null};function pi(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function Ec(o,e){await Pc(Mc(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.tmp`;try{let t=await kc(n,"w");try{await t.writeFile(`${JSON.stringify(e,null,2)}
|
|
175
|
-
`,"utf8"),await
|
|
176
|
-
|
|
177
|
-
`)
|
|
178
|
-
|
|
172
|
+
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,t){let n=[];if(o.annotations.length>0){n.push("## Annotations");for(let i of o.annotations){let r=i.elements.map(u=>{let I=[u.selector];return u.reactComponent&&I.push(`(${u.reactComponent})`),I.join(" ")}).join(", "),s=i.instruction||"No text";n.push(`- id=${i.id} [${i.type}] ${s} \u2192 Elements: ${r||"none"}`);let c=e?.[i.id];if(c&&c.length>0)for(let u of c)n.push(` Attached image: use the Read tool to view ${u}`);let d=t?.[i.id];if(d?.length)for(let u of d)n.push(` Attached context (${u.name}, ${u.mimeType}): use the Read tool to inspect ${u.path}`)}}if(o.styleModifications.length>0){n.push(""),n.push("## Style Changes (make permanent in source)"),n.push("The developer previewed these CSS changes via inline style overrides. Find the corresponding styles in the source files and update them so the changes persist:");for(let i of o.styleModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"";for(let s of i.changes)n.push(`- ${i.selector} ${r}: ${s.property} ${s.original} \u2192 ${s.modified}`)}}if(o.textModifications?.length){n.push(""),n.push("## Text Changes (make permanent in source)"),n.push("The developer directly edited rendered DOM text in the browser. Find the source copy and update it so the text change persists:");for(let i of o.textModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=JSON.stringify(i.original),c=JSON.stringify(i.modified),d=i.textNodePath.length>0?` textNodePath=${i.textNodePath.join(".")}`:"";n.push(`- ${i.selector} ${r}${d}: ${s} \u2192 ${c}`)}}if(o.domModifications?.length){n.push(""),n.push("## DOM Structure Changes (make permanent in source)"),n.push("The developer rearranged or copied rendered elements in the browser as a visual reference. Update the source structure so this layout/content relationship persists:");for(let i of o.domModifications){let r=i.element?.reactComponent?`(${i.element.reactComponent})`:"",s=i.sourceElement?.reactComponent?` from ${i.sourceSelector} (${i.sourceElement.reactComponent})`:i.sourceSelector?` from ${i.sourceSelector}`:"",c=i.referenceSelector?` ${i.placement} ${i.referenceSelector}`:` at index ${i.targetIndex}`;n.push(`- ${i.operation}: ${i.selector} ${r}${s} \u2192 ${i.targetParentSelector}${c}`)}}if(o.spacingTokenChanges?.length){n.push(""),n.push("## Spacing Token Changes"),n.push("The developer adjusted these spacing tokens. Apply each change to the source code:");for(let i of o.spacingTokenChanges){n.push(`
|
|
173
|
+
### ${i.tokenName}: ${i.originalPx}px \u2192 ${i.newPx}px`);for(let r of i.affectedElements){let s=r.reactComponent?` (${r.reactComponent})`:"";r.matchedClass&&r.suggestedClass?n.push(`- ${r.selector}${s}: \`${r.matchedClass}\` \u2192 \`${r.suggestedClass}\``):n.push(`- ${r.selector}${s}: ${r.property} ${i.originalPx}px \u2192 ${i.newPx}px`),n.push(` class="${r.className}"`)}}}if(o.inspectedElement){let i=o.inspectedElement;n.push(""),n.push("## Inspected Element"),n.push("The developer has this element selected in the inspector:");let r=[i.selector];i.reactComponent&&r.push(`(${i.reactComponent})`),i.context&&r.push(`in ${i.context}`),i.textContent&&r.push(`"${i.textContent.slice(0,80)}"`),n.push(`- ${r.join(" ")}`)}return n.join(`
|
|
174
|
+
`)}function hr(o,e,t){let n=[],r=new Set(e.annotations.map(s=>s.pathname).filter(Boolean)).size>1;if(n.push("You are reviewing a UI screenshot with developer annotations."),n.push(""),!r&&t?.provider!=="codex"&&(n.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`),n.push("")),n.push(`The developer annotated their running app at ${e.url} (${e.viewport.width}x${e.viewport.height}).`),t?.threadHistory&&t.threadHistory.length>0){n.push(""),n.push("## Previous Conversation");let s=0;for(let c of t.threadHistory)if(c.role==="human")s++,c.replyToQuestion?(n.push(`### Round ${s} (human) \u2014 reply`),n.push(`"${c.replyToQuestion}"`)):(n.push(`### Round ${s} (human)`),c.feedbackSummary&&n.push(`Annotations: ${c.feedbackSummary}`),c.annotationIds&&c.annotationIds.length>0&&n.push(`Annotation IDs: ${c.annotationIds.join(", ")}`));else if(c.question)n.push(`### Round ${s} (assistant) \u2014 question`),n.push(`"${c.question}"`);else{if(n.push(`### Round ${s} (assistant)`),c.responseText&&n.push(`Response: ${c.responseText}`),c.resolutions&&c.resolutions.length>0)for(let d of c.resolutions){let u=d.finalScope??d.inferredScope,I=u?` [${u.breadth} ${u.target}]`:"";n.push(`- ${d.annotationId}: ${d.status}${I} \u2014 ${d.summary}`),d.filesModified&&d.filesModified.length>0&&n.push(` Files: ${d.filesModified.join(", ")}`)}c.toolsUsed&&c.toolsUsed.length>0&&n.push(`Tools used: ${c.toolsUsed.join(", ")}`)}n.push(""),n.push("The current round is shown in full below.")}if(t?.designModel){n.push(""),n.push("## Established Design Policies"),n.push("This project has an active product model projected only from accepted canonical decisions. When making changes, follow these patterns unless the developer explicitly overrides them.");let s=t.designModel.rules;if(Array.isArray(s)&&s.length>0)if(n.push(""),n.push("Rules:"),s.length>0&&typeof s[0]=="object"&&s[0]!==null&&"scope"in s[0]){let I=new Map;for(let T of s)if(typeof T=="object"&&T!==null&&"text"in T){let k=T,P=k.scope||"general";I.has(P)||I.set(P,[]),I.get(P).push(k.text)}for(let[T,k]of I){n.push(`**${T.charAt(0).toUpperCase()+T.slice(1)}**`);for(let P of k)n.push(`- ${P}`)}}else for(let I of s)typeof I=="string"&&n.push(`- ${I}`);let c=t.designModel.tokens;c&&typeof c=="object"&&(n.push(""),n.push("Design tokens:"),n.push("```json"),n.push(JSON.stringify(c,null,2)),n.push("```"));let d=t.designModel.components;d&&typeof d=="object"&&(n.push(""),n.push("Component patterns:"),n.push("```json"),n.push(JSON.stringify(d,null,2)),n.push("```")),n.push(""),n.push("### Applied Model-Gap Details"),n.push("Only when you actually modify the project and implement a design decision that has no matching policy in the model above (e.g., styling a component type not yet in the model, choosing a color with no token, picking spacing with no rule), describe that applied gap:"),n.push("<novel>"),n.push('[{"category":"component","element":"button","decision":"Used 8px border-radius, 12px 24px padding","reason":"No button pattern in design model"}]'),n.push("</novel>"),n.push('- `category`: "token" (color, spacing, typography), "component" (UI component pattern), or "element" (specific element style)'),n.push("- `element`: What you are styling or creating"),n.push("- `decision`: What you actually implemented (specific values)"),n.push("- `reason`: Why this is novel (what is missing from the model)"),n.push("Do not emit <novel> for answer-only, explanatory, investigative, advisory, planning, or question turns. Never describe a recommendation or proposed future change as applied."),n.push("This is an execution receipt, not a memory proposal. Continuous imprinting separately decides whether the collaboration produced reusable learning.")}if(t?.designModel||(n.push(""),n.push("## Design Context"),n.push("This project uses Popmelt for product governance. Accepted canonical decisions may be projected into a rebuildable working model.")),r){let s=t?.screenshotPaths??{},c=new Map;for(let d of e.annotations){let u=d.pathname||new URL(e.url).pathname;c.has(u)||c.set(u,[]),c.get(u).push(d)}n.push(""),n.push("The developer annotated multiple pages. Each page section includes its own screenshot where available.");for(let[d,u]of c){n.push(""),n.push(`## Page: ${d}`);let I=s[d];I&&t?.provider!=="codex"?n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${I}`):!I&&t?.provider!=="codex"&&(Object.keys(s).length===0?(n.push(`IMPORTANT: Use the Read tool to view the screenshot at: ${o}`),n.push("(This screenshot shows the page the developer was on when submitting \u2014 not this page)")):n.push("(No screenshot available for this page \u2014 work from the annotation text and selectors)"));let T={...e,annotations:u,styleModifications:e.styleModifications},k=dn(T,t?.imagePaths,t?.attachmentFiles);k&&(n.push(""),n.push(k))}}else{let s=dn(e,t?.imagePaths,t?.attachmentFiles);s&&(n.push(""),n.push(s))}return n.push(""),n.push("Follow the developer's instructions. If they ask for changes, apply them to the source files \u2014 the dev server has HMR so changes appear immediately. If they ask a question or request analysis, respond in text without modifying code."),n.push(""),n.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n.push(""),n.push("## Resolution"),n.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),n.push("<resolution>"),n.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),n.push("</resolution>"),n.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),n.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),n.push(""),n.push("### Scope classification"),n.push("Each resolution MUST include scope fields:"),n.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),n.push("- `inferredScope`: What scope the change actually has, based on what you modified."),n.push("Scope has two dimensions:"),n.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),n.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),n.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),n.push("If you cannot confidently determine scope, set it to null."),n.push(""),n.push("## Questions"),n.push("If the annotation text is unclear, ambiguous, gibberish, or you are unsure what the developer wants, output a question:"),n.push('<question>What do you mean by "..."?</question>'),n.push("Do NOT guess what unclear instructions mean \u2014 ask instead."),n.push("You may output BOTH a <resolution> for clear annotations AND a <question> for unclear ones in the same response."),n.join(`
|
|
175
|
+
`)}function gr(o){return o.match(/<question>\s*([\s\S]*?)\s*<\/question>/)?.[1]??null}function yr(o,e,t,n){let i=[];i.push("You are continuing work on a UI based on the developer's reply to your question."),i.push(""),t!=="codex"&&i.push(`IMPORTANT: First, use the Read tool to view the screenshot at: ${o}`);let r=e.find(s=>s.role==="human"&&s.feedbackContext);if(r?.feedbackContext&&(i.push(""),i.push(r.feedbackContext)),e.length>0){i.push(""),i.push("## Conversation History");let s=0;for(let c of e)c.role==="human"?(s++,c.replyToQuestion?(i.push(`### Round ${s} (human) \u2014 reply`),i.push(`"${c.replyToQuestion}"`)):(i.push(`### Round ${s} (human)`),c.feedbackSummary&&i.push(`Annotations: ${c.feedbackSummary}`))):c.question?(i.push(`### Round ${s} (assistant) \u2014 question`),i.push(`"${c.question}"`)):(i.push(`### Round ${s} (assistant)`),c.responseText&&i.push(`Response: ${c.responseText}`))}if(i.push(""),i.push("The developer answered your question. Continue working based on their reply."),i.push("Follow their instructions \u2014 apply code changes only if requested. The dev server has HMR so changes appear immediately."),i.push(""),i.push("IMPORTANT: If any elements you modify have a `data-pm` attribute, preserve it in the source. This attribute tracks annotation positions."),n&&n.length>0){i.push(""),i.push("## Attached Images"),i.push("The developer attached reference images with their reply:");for(let s of n)i.push(`Attached image: use the Read tool to view the image at: ${s}`)}return i.push(""),i.push("## Resolution"),i.push("After completing all work, output one resolution envelope listing what you did for each annotation:"),i.push("<resolution>"),i.push('{"annotations":[{"annotationId":"<id>","status":"resolved","summary":"<what you did>","filesModified":["<file>"],"declaredScope":{"breadth":"...","target":"..."},"inferredScope":{"breadth":"...","target":"..."}}]}'),i.push("</resolution>"),i.push("Continuous imprinting may require an additional `imprint` field in this same envelope. Follow that contract when it appears below; do not emit a second resolution block."),i.push(`Use status "resolved" when the change is complete, or "needs_review" if you're unsure about the result.`),i.push(""),i.push("### Scope classification"),i.push("Each resolution MUST include scope fields:"),i.push("- `declaredScope`: What scope the user's instruction text implies. null if no signal."),i.push("- `inferredScope`: What scope the change actually has, based on what you modified."),i.push("Scope has two dimensions:"),i.push('- `breadth`: "instance" (just this occurrence) or "pattern" (all similar occurrences)'),i.push('- `target`: "element" (a specific DOM element), "component" (a React/UI component), or "token" (a design token \u2014 color, spacing, typography)'),i.push('Note: "instance" + "token" is invalid \u2014 tokens are inherently patterns.'),i.push("If you cannot confidently determine scope, set it to null."),i.push('If the developer\'s reply corrects a prior scope classification (e.g., "this should apply everywhere" or "only fix this one"), set `finalScope` on your resolution to reflect their correction and apply the change at the corrected scope.'),i.push(""),i.push("## Questions"),i.push("If you still need clarification, output:"),i.push("<question>Your question here</question>"),i.push("You may output BOTH a <resolution> and a <question> in the same response."),i.join(`
|
|
176
|
+
`)}function bc(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 xc(o){if(typeof o!="object"||o===null||typeof o.annotationId!="string"||o.status!=="resolved"&&o.status!=="needs_review"||typeof o.summary!="string")return!1;let e=o;for(let t of["declaredScope","inferredScope","finalScope"])if(e[t]!==void 0&&e[t]!==null&&!bc(e[t]))return!1;return!0}function vr(o){let t=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!t)return[];try{let n=JSON.parse(t);return(Array.isArray(n)?n:n&&typeof n=="object"&&Array.isArray(n.annotations)?n.annotations:[]).filter(xc)}catch{return[]}}function Sc(o){let e=o.match(/<novel>\s*([\s\S]*?)\s*<\/novel>/);if(!e?.[1])return[];try{let t=JSON.parse(e[1]);return Array.isArray(t)?t.filter(n=>{if(typeof n!="object"||n===null)return!1;let i=n;return(i.category==="token"||i.category==="component"||i.category==="element")&&typeof i.element=="string"&&typeof i.decision=="string"&&typeof i.reason=="string"}):[]}catch{return[]}}function Ir(o,e){return e>0?Sc(o):[]}import{execFile as kc}from"child_process";import{readdir as Tc,readFile as Rc,stat as Pc}from"fs/promises";import{homedir as ln}from"os";import{join as Ze}from"path";var Vn=[{id:"claude-opus-4-6",label:"Opus 4.6",source:"static",supportedReasoningLevels:wr()},{id:"claude-sonnet-4-6",label:"Sonn 4.6",source:"static",supportedReasoningLevels:wr()}],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"},jc=/^\s*-\s+"([^"]+)"/;function Ac(o){let e=[],t=!1;for(let n of o.split(`
|
|
177
|
+
`)){if(/^\s*`model`:/.test(n)){t=!0;continue}if(t&&/^\s*`[^`]+`:/.test(n))break;if(!t)continue;let i=n.match(jc);if(!i?.[1])continue;let r=i[1];e.push({id:r,label:Ko(r),source:"cli"})}return Kn([un,...e])}function Mc(o){let e=JSON.parse(o);return(Array.isArray(e.models)?e.models:[]).filter(n=>n.visibility===void 0||n.visibility==="list").sort((n,i)=>{let r=typeof n.priority=="number"?n.priority:Number.MAX_SAFE_INTEGER,s=typeof i.priority=="number"?i.priority:Number.MAX_SAFE_INTEGER;return r-s}).flatMap(n=>{let i=typeof n.slug=="string"?n.slug:typeof n.id=="string"?n.id:"";if(!i)return[];let r=typeof n.display_name=="string"&&n.display_name.trim()?n.display_name.trim():Ko(i),s=Array.isArray(n.supported_reasoning_levels)?n.supported_reasoning_levels.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.effort!="string"?[]:[{effort:u.effort,...typeof u.description=="string"?{description:u.description}:{}}]}):void 0,c=Array.isArray(n.service_tiers)?n.service_tiers.flatMap(d=>{if(!d||typeof d!="object")return[];let u=d;return typeof u.id!="string"?[]:[{id:u.id,label:typeof u.name=="string"?u.name:u.id,...typeof u.description=="string"?{description:u.description}:{}}]}):void 0;return[{id:i,label:r,source:"cli",...typeof n.default_reasoning_level=="string"?{defaultReasoningLevel:n.default_reasoning_level}:{},...s&&s.length>0?{supportedReasoningLevels:s}:{},...c&&c.length>0?{speedTiers:c}:{}}]})}function wr(){return["low","medium","high","xhigh","max"].map(o=>({effort:o}))}function Ec(o){let e=o.match(/\bclaude-[a-z0-9]+(?:[-.][a-z0-9]+)*\b/gi)??[];return Kn(e.map(t=>({id:t,label:Ko(t),source:"cli"})))}function Ko(o){if(!o)return"Default";let e={"gpt-5.5":"GPT 5.5","gpt-5.4":"GPT 5.4","gpt-5.4-mini":"Mini 5.4","gpt-5.3-codex":"Codex 5.3","gpt-5.3-codex-spark":"Spark 5.3","gpt-5.2-codex":"Codex 5.2","gpt-5.2":"GPT 5.2","gpt-5.1":"GPT 5.1","gpt-5-mini":"Mini 5","gpt-4.1":"GPT 4.1","claude-opus-4.7":"Opus 4.7","claude-opus-4.6":"Opus 4.6","claude-opus-4.6-fast":"Opus 4.6 Fast","claude-opus-4.5":"Opus 4.5","claude-sonnet-4.6":"Sonn 4.6","claude-sonnet-4.5":"Sonn 4.5","claude-sonnet-4":"Sonn 4","claude-haiku-4.5":"Haiku 4.5","claude-fable":"Fable"},t=o.replace(/-\d{8,}$/,"");if(e[o])return e[o];if(e[t])return e[t];let n=t.match(/^claude-(opus|sonnet|haiku|fable)(?:-(\d+)[-.](\d+))?(?:-(fast))?$/);if(n){let r=n[1]==="sonnet"?"Sonn":Oc(n[1]),s=n[2]&&n[3]?` ${n[2]}.${n[3]}`:"";return`${r}${s}${n[4]?" Fast":""}`}let i=t.match(/^gpt-(\d+)(?:[.-](\d+))?(?:-(mini|codex|spark))?$/);if(i){let r=i[2]?`${i[1]}.${i[2]}`:i[1];return i[3]==="mini"?`Mini ${r}`:i[3]==="codex"?`Codex ${r}`:i[3]==="spark"?`Spark ${r}`:`GPT ${r}`}return t}async function br(o="copilot"){let e=await Hn(o,["help","config"]),t=Ac(e);return t.length>1?t:[un]}async function xr(o="codex"){let e=await Hn(o,["debug","models"]).catch(async()=>{let n=process.env.CODEX_HOME||Ze(ln(),".codex");return kr(Ze(n,"models_cache.json"))}),t=Mc(e);return t.length>0?Kn([...t,...pn]):pn}async function Sr(o="claude"){let e=Ze(ln(),".claude"),t=[Ze(ln(),".claude","stats-cache.json"),Ze(ln(),".claude","settings.json"),Ze(ln(),".claude.json"),Ze(e,"cache","changelog.md")],[n,i,r]=await Promise.all([Hn(o,["--help"]).catch(()=>""),Hn(o,["--version"]).catch(()=>""),_c(e).catch(()=>[])]),s=Cc([...t,...r]),c=await Promise.all(s.map(u=>kr(u).catch(()=>""))),d=Ec([n,i,...c].join(`
|
|
178
|
+
`));return Kn([...Vn,...d])}function Hn(o,e,t=5e3){return new Promise((n,i)=>{kc(o,e,{encoding:"utf-8",timeout:t},(r,s)=>{if(r){i(r);return}n(s)})})}async function kr(o){return Rc(o,"utf-8")}async function _c(o){let e=[Ze(o,"projects"),Ze(o,"telemetry")],t=[];for(let n of e)await Tr(n,t,4);return t.sort((n,i)=>i.mtimeMs-n.mtimeMs).slice(0,80).map(n=>n.path)}async function Tr(o,e,t){if(t<0)return;let n;try{n=await Tc(o,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async i=>{let r=Ze(o,i.name);if(i.isDirectory()){await Tr(r,e,t-1);return}if(!(!i.isFile()||!$c(i.name)))try{let s=await Pc(r);if(s.size>2e6)return;e.push({path:r,mtimeMs:s.mtimeMs})}catch{}}))}function $c(o){return o.endsWith(".json")||o.endsWith(".jsonl")||o.endsWith(".md")||o.endsWith(".txt")}function Kn(o){let e=new Set,t=[];for(let n of o)e.has(n.id)||(e.add(n.id),t.push(n));return t}function Cc(o){return[...new Set(o)]}function Oc(o){return o.charAt(0).toUpperCase()+o.slice(1)}var Qn=class{constructor(e=5){this.queue=[];this.activeJobs=new Map;this.activeProcesses=new Map;this.listeners=new Set;this.processor=null;this.eventBuffers=new Map;this.accumulators=new Map;this.cleanupTimers=new Map;this.maxConcurrency=e}setProcessor(e){this.processor=e}get active(){let e=this.activeJobs.values().next();return e.done?null:e.value}get allActive(){return Array.from(this.activeJobs.values())}get activeCount(){return this.activeJobs.size}get depth(){return this.queue.length}get isRunning(){return this.activeJobs.size>0}setActiveProcess(e,t){t?this.activeProcesses.set(e,t):this.activeProcesses.delete(e)}enqueue(e){return this.queue.push(e),this.processNext(),this.queue.length+this.activeJobs.size}enqueueNext(e){let t=-1;if(e.threadId){for(let r=this.queue.length-1;r>=0;r--)if(this.queue[r]?.threadId===e.threadId){t=r;break}}let n=t>=0?t+1:0,i=this.activeJobs.size+n+1;return this.queue.splice(n,0,e),this.processNext(),i}hasActiveThread(e){return this.allActive.some(t=>t.threadId===e)}getQueuedThreadJob(e,t){return this.queue.find(n=>n.threadId===e&&(!t||t(n)))??null}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}broadcast(e,t,n){let i=this.bufferEvent(t,e);for(let r of this.listeners)r(i,t,n)}bufferEvent(e,t){let n=this.eventBuffers.get(e);n||(n={events:[],nextSeq:0},this.eventBuffers.set(e,n));let i={...t,seq:n.nextSeq++};return n.events.push(i),n.events.length>1e4&&n.events.splice(0,n.events.length-1e4),i}getBufferedEvents(e,t=-1){let n=this.eventBuffers.get(e),i=this.accumulators.get(e)??{response:"",thinking:""},r=this.activeJobs.has(e);if(!n)return null;let s=t<0?n.events:n.events.filter(c=>c.seq>t);return{jobId:e,events:s,currentSeq:n.nextSeq-1,accumulated:{...i},jobActive:r}}accumulateText(e,t,n){let i=this.accumulators.get(e);i||(i={response:"",thinking:""},this.accumulators.set(e,i)),i[t]+=n}getAccumulated(e){return this.accumulators.get(e)??null}scheduleBufferCleanup(e){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.eventBuffers.delete(e),this.accumulators.delete(e),this.cleanupTimers.delete(e)},6e4);this.cleanupTimers.set(e,n)}cancelJob(e){let t=this.activeProcesses.get(e),n=this.activeJobs.get(e);return!t||!n?!1:(t.kill("SIGTERM"),this.activeProcesses.delete(e),this.activeJobs.delete(e),n.status="error",n.error="Cancelled by user",this.broadcast({type:"error",jobId:n.id,threadId:n.threadId,message:"Cancelled by user",cancelled:!0,provider:n.provider,model:n.model},n.id,n.sourceId),this.processNext(),!0)}cancelActive(){if(this.activeJobs.size===0)return!1;let e=Array.from(this.activeJobs.keys());for(let t of e)this.cancelJob(t);return!0}destroy(){for(let e of this.activeProcesses.values())e.kill("SIGTERM");this.activeProcesses.clear(),this.activeJobs.clear(),this.queue=[],this.listeners.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear()}async destroyAsync(e=1e4){let t=Array.from(this.activeProcesses.values());if(this.queue=[],this.listeners.clear(),t.length===0){this.activeProcesses.clear(),this.activeJobs.clear();return}for(let n of t)try{n.kill("SIGTERM")}catch{}await Promise.all(t.map(n=>new Promise(i=>{let r=!1,s=()=>{r||(r=!0,i())};n.on("exit",s),n.on("error",s),setTimeout(()=>{if(!r){try{n.kill("SIGKILL")}catch{}setTimeout(s,500)}},e)}))),this.activeProcesses.clear(),this.activeJobs.clear(),this.eventBuffers.clear(),this.accumulators.clear();for(let n of this.cleanupTimers.values())clearTimeout(n);this.cleanupTimers.clear()}processNext(){for(;this.activeJobs.size<this.maxConcurrency&&this.queue.length>0&&this.processor;){let e=this.queue.shift();this.activeJobs.set(e.id,e),e.status="running",this.broadcast({type:"job_started",jobId:e.id,position:0,threadId:e.threadId,annotationIds:e.annotationIds,color:e.color,kind:e.kind,global:e.kind==="synthesize"||e.kind==="project_model"},e.id,e.sourceId),this.processor(e).catch(t=>{e.status="error",e.error=t instanceof Error?t.message:String(t),this.broadcast({type:"error",jobId:e.id,threadId:e.threadId,message:e.error,provider:e.provider,model:e.model},e.id,e.sourceId)}).finally(()=>{this.activeJobs.delete(e.id),this.activeProcesses.delete(e.id),this.scheduleBufferCleanup(e.id),this.processNext(),this.activeJobs.size===0&&this.queue.length===0&&this.broadcast({type:"queue_drained"},e.id)})}}};import{randomUUID as it}from"crypto";import{createHash as Dc}from"crypto";import{mkdir as Nc,open as Jc,readFile as Rr,readdir as Bc,rename as Lc,unlink as qc}from"fs/promises";import{dirname as Fc,join as Ft}from"path";function Ce(o){return structuredClone(o)}function Pr(o){return Dc("sha256").update(JSON.stringify(o)).digest("hex")}async function Tt(o,e){await Nc(Fc(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`,n=await Jc(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
179
|
+
`,"utf8"),await n.sync()}finally{await n.close()}try{await Lc(t,o)}catch(i){throw await qc(t).catch(()=>{}),i}}function Uc(o,e){return{version:1,projectId:o,createdAt:e,updatedAt:e,head:{sequence:0,hash:null},explanations:[],concrete:[],relations:[]}}function zc(o,e){let t=o.explanations.findIndex(n=>n.id===e.id);t>=0?o.explanations[t]=Ce(e):o.explanations.push(Ce(e))}function Qo(o,e){let t=Ce(o);for(let n of e)if(n.op==="add_explanation"){if(t.explanations.some(i=>i.id===n.explanation.id))throw new Error(`Imprint explanation already exists: ${n.explanation.id}`);t.explanations.push(Ce(n.explanation))}else if(n.op==="replace_explanation")zc(t,n.explanation);else if(n.op==="remove_explanation")t.explanations=t.explanations.filter(i=>i.id!==n.explanationId),t.relations=t.relations.filter(i=>i.fromId!==n.explanationId&&i.toId!==n.explanationId);else if(n.op==="add_concrete")t.concrete.some(i=>i.id===n.concrete.id)||t.concrete.push(Ce(n.concrete));else if(n.op==="remove_concrete")t.concrete=t.concrete.filter(i=>i.id!==n.concreteId),t.relations=t.relations.filter(i=>i.fromId!==n.concreteId&&i.toId!==n.concreteId);else if(n.op==="add_evidence"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);i.evidence.some(r=>r.id===n.evidence.id)||(i.evidence.push(Ce(n.evidence)),i.updatedAt=n.evidence.createdAt)}else if(n.op==="revise_explanation"){let i=t.explanations.find(r=>r.id===n.explanationId);if(!i)throw new Error(`Unknown imprint explanation: ${n.explanationId}`);Object.assign(i,Ce(n.patch),{updatedAt:n.updatedAt})}else if(n.op==="add_relation"){let i=n.relation,r=t.explanations.find(u=>u.id===i.fromId),s=t.explanations.find(u=>u.id===i.toId),c=t.concrete.some(u=>u.id===i.fromId),d=t.concrete.some(u=>u.id===i.toId);if(Vi(i.type)){if(!(i.type==="expresses"?!!((r||c)&&s):!!(r&&s)))throw new Error(`Imprint ${i.type} relation has invalid endpoints: ${i.id}`);if(t.relations.some(I=>I.type===i.type&&I.fromId===i.fromId&&I.toId===i.toId))throw new Error(`Duplicate imprint relation: ${i.type}:${i.fromId}:${i.toId}`);if(i.type==="expresses"&&r&&s){if(Ot(r,s)<0)throw new Error(`Imprint expresses relation must point from specific to abstract: ${i.id}`);let I=new Map;for(let P of t.relations)P.type==="expresses"&&I.set(P.fromId,[...I.get(P.fromId)??[],P.toId]);let T=[i.toId],k=new Set;for(;T.length;){let P=T.pop();if(P===i.fromId)throw new Error(`Imprint expresses relation would create a cycle: ${i.id}`);k.has(P)||(k.add(P),T.push(...I.get(P)??[]))}}}else if(!r||!s&&!d)throw new Error(`Imprint relation references an unknown explanation: ${i.id}`);t.relations.some(u=>u.id===i.id)||t.relations.push(Ce(i))}else n.op==="remove_relation"&&(t.relations=t.relations.filter(i=>i.id!==n.relationId));return t}function Gc(o,e){let t=[],n=Ce(o);for(let i of e){if(i.op==="add_explanation")t.unshift({op:"remove_explanation",explanationId:i.explanation.id});else if(i.op==="remove_explanation"){let r=n.explanations.find(s=>s.id===i.explanationId);r&&t.unshift({op:"add_explanation",explanation:Ce(r)})}else if(i.op==="add_concrete")t.unshift({op:"remove_concrete",concreteId:i.concrete.id});else if(i.op==="remove_concrete"){let r=n.concrete.find(s=>s.id===i.concreteId);r&&t.unshift({op:"add_concrete",concrete:Ce(r)})}else if(i.op==="replace_explanation"||i.op==="revise_explanation"||i.op==="add_evidence"){let r=i.op==="replace_explanation"?i.explanation.id:i.explanationId,s=n.explanations.find(c=>c.id===r);s&&t.unshift({op:"replace_explanation",explanation:Ce(s)})}else if(i.op==="add_relation")t.unshift({op:"remove_relation",relationId:i.relation.id});else if(i.op==="remove_relation"){let r=n.relations.find(s=>s.id===i.relationId);r&&t.unshift({op:"add_relation",relation:Ce(r)})}n=Qo(n,[i])}return t}function jr(o){return o.op==="add_explanation"||o.op==="replace_explanation"?[o.explanation.id]:o.op==="remove_explanation"||o.op==="add_evidence"||o.op==="revise_explanation"?[o.explanationId]:o.op==="add_relation"?[o.relation.fromId,o.relation.toId]:[]}var Xn=class{constructor(e,t){this.projectRoot=e;this.projectId=t;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 Rr(this.manifestPath,"utf8"));if(e.version!==1||e.projectId!==this.projectId)throw new Error("Imprint manifest does not match this project.");return e}catch(e){if(e.code!=="ENOENT")throw e;let t=new Date().toISOString();return{version:1,projectId:this.projectId,createdAt:t,updatedAt:t,head:{sequence:0,hash:null}}}}async loadRaw(){let e=await this.readManifest(),n=(await Bc(this.journalDir).catch(c=>{if(c.code==="ENOENT")return[];throw c})).filter(c=>/^\d{12}-.+\.json$/.test(c)).sort(),i=Uc(this.projectId,e.createdAt),r=[],s=null;for(let c=0;c<n.length;c++){let d=JSON.parse(await Rr(Ft(this.journalDir,n[c]),"utf8")),{hash:u,...I}=d;if(d.sequence!==c+1||d.previousHash!==s||u!==Pr(I))throw new Error(`Imprint journal hash mismatch at sequence ${d.sequence}.`);i=Qo(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 t=await this.loadRaw(),n=xt(t.graph),i=new Map(n.relations.map(s=>[s.id,s])),r=[];for(let s of t.graph.relations){let c=i.get(s.id);c&&c.type===s.type&&c.fromId===s.fromId&&c.toId===s.toId||(r.push({op:"remove_relation",relationId:s.id}),c&&r.push({op:"add_relation",relation:c}))}if(r.length){let s=new Date().toISOString();return await this.commit({transactionId:`topology-v2-${t.graph.head.sequence+1}`,committedAt:s,source:{kind:"migration",threadId:"imprint-topology",jobId:"imprint-topology-v2"},summary:"Simplify Imprint topology to expresses and excepts",mutations:r}),{migrated:!0,relationMutations:r.length}}return await Tt(this.graphPath,n),await Tt(this.manifestPath,{...e,topologyVersion:2}),{migrated:!0,relationMutations:0}}async commit(e){let t;return this.writeChain=this.writeChain.then(async()=>{let n=await this.load();if(n.transactions.some(T=>T.transactionId===e.transactionId))throw new Error(`Imprint transaction already exists: ${e.transactionId}`);let i=n.graph.head.sequence+1,r=Gc(n.graph,e.mutations),s={version:1,sequence:i,transactionId:e.transactionId,projectId:this.projectId,committedAt:e.committedAt,previousHash:n.graph.head.hash,source:e.source,summary:e.summary,mutations:Ce(e.mutations),inverseMutations:r,...e.undoesTransactionId?{undoesTransactionId:e.undoesTransactionId}:{}},c={...s,hash:Pr(s)},d=Qo(n.graph,c.mutations);d.updatedAt=e.committedAt,d.head={sequence:i,hash:c.hash};let u=`${String(i).padStart(12,"0")}-${e.transactionId}.json`;await Tt(Ft(this.journalDir,u),c);let I={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,I),t={graph:d,transaction:c}}),await this.writeChain,t}async undo(e,t,n,i){let r=await this.load(),s=r.transactions.find(u=>u.transactionId===e);if(!s)throw new Error("The imprint update is no longer available to undo.");if(r.transactions.some(u=>u.undoesTransactionId===e))throw new Error("This imprint update has already been undone.");let c=new Set(s.mutations.flatMap(jr));if(r.transactions.filter(u=>u.sequence>s.sequence).some(u=>u.mutations.some(I=>jr(I).some(T=>c.has(T)))))throw new Error("This imprint update has newer dependent changes and cannot be undone cleanly. Edit or challenge the current explanation instead.");return this.commit({transactionId:i,committedAt:n,source:t,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 Wc=new Set(["application_only","transient_state","concrete_without_model_path","duplicate","insufficient_evidence","task_specific_detail","no_shared_understanding_change"]),Hc=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]),Vc=/\b(all|any|every|everywhere|across|throughout|globally|project[- ]wide)\b/i;function Yo(o){return!!(o&&Vc.test(o))}function Kc(o){return o.scope.kind==="project"||Yo(`${o.statement} ${o.rationale}`)}function Qc(o){let e=o?.scope.values.filter(t=>t!=="*").join(", ");return e?`Does applying this understanding here match your intent for ${e}?`:"Does applying this understanding here match your intent?"}function Xc(o){return o.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Yn(o){return new Set(Xc(o).split(" ").filter(e=>e.length>2&&!Hc.has(e)))}function Zn(o,e){if(!o.size||!e.size)return 0;let t=0;for(let n of o)e.has(n)&&(t+=1);return t/Math.min(o.size,e.size)}function Xo(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 mt(o,e,t){return{id:it(),kind:e==="excepts"?"exception":e==="challenges"?"correction":"observation",stance:e,summary:t,threadId:o.threadId,jobId:o.jobId,createdAt:o.occurredAt??new Date().toISOString()}}function ye(o,e=800){return typeof o=="string"?o.trim().slice(0,e):""}function Ar(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o;if(!["project","route","component","selector","file"].includes(String(e.kind))||!Array.isArray(e.values))return;let t=e.values.filter(n=>typeof n=="string"&&!!n.trim());return t.length?{kind:e.kind,values:t}:void 0}function Mr(o,e){if(!o||!e.trim())return{found:!1};let t=o;for(let n of e.split(".").filter(Boolean))if(Array.isArray(t)){let i=Number(n);if(!Number.isInteger(i)||i<0||i>=t.length)return{found:!1};t=t[i]}else if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,n))t=t[n];else return{found:!1};return{found:!0,value:t}}function Zo(o,e={}){let t=[...o.matchAll(/<imprint>([\s\S]*?)<\/imprint>/g)],n=o.replace(/<imprint>[\s\S]*?<\/imprint>/g,"").replace(/<imprint>[\s\S]*$/g,"").trim(),i=t.at(-1)?.[1],r,s=[];if(i)r=i;else{let d=[...o.matchAll(/<resolution>\s*([\s\S]*?)\s*<\/resolution>/g)].at(-1)?.[1];if(!d)return{visibleText:n,error:"imprint assessment is missing"};try{let u=JSON.parse(d);if(!u||typeof u!="object"||Array.isArray(u)||!Object.prototype.hasOwnProperty.call(u,"imprint"))return{visibleText:n,error:"imprint assessment is missing"};let I=u;r=I.imprint,s=Array.isArray(I.annotations)?I.annotations:[]}catch{return{visibleText:n,error:"resolution envelope is invalid"}}}try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object"||Array.isArray(c))throw new Error("imprint assessment is invalid");if(c.decision==="none"){let p=String(c.reason);if(!Wc.has(p))throw new Error("imprint no-op reason is invalid");if(p==="task_specific_detail"&&s.some(f=>{if(!f||typeof f!="object"||Array.isArray(f))return!1;let m=f;return(m.finalScope??m.inferredScope)?.breadth==="pattern"}))throw new Error("pattern-scoped resolution cannot be classified as task_specific_detail");let l=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(f=>typeof f=="string"&&!!f.trim()):[];if(l.length){let f=l,m=new Set(e.context?.explanations.map(b=>b.id)??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(b=>{let g=e.context?.explanations.find(B=>B.id===b);return m.has(b)&&g&&(g.state==="emerging"||g.state==="testing")&&!h.has(b)});if(j.length){let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0],B=ye(b?.question,300);return{draft:{decision:"apply",summary:{title:ye(c.summary?.title,120)||"Applied shared understanding",detail:ye(c.summary?.detail,500)||ye(e.requestText||n,500)||"Applied an ungrounded explanation in a new context."},appliedExplanationIds:j,grounding:{explanationId:g,question:B||"Does applying this understanding here match your intent?"}},visibleText:n}}}if(p==="duplicate"){let f=ye(c.duplicateOfExplanationId,100),m=c.scopeComparison;if(!f)throw new Error("duplicate assessment requires duplicateOfExplanationId");if(m!=="equivalent"&&m!=="existing_broader")throw new Error("duplicate assessment requires an equivalent or existing_broader scopeComparison");let h=e.context?.explanations.find(j=>j.id===f);if(!h)throw new Error("duplicate assessment must cite a surfaced explanation");if(Yo(e.requestText)&&!Kc(h))throw new Error("duplicate explanation does not cover the requested broader scope");return{draft:{decision:"none",reason:p,duplicateOfExplanationId:f,scopeComparison:m},visibleText:n}}return{draft:{decision:"none",reason:p},visibleText:n}}if(c.decision==="recognize"){let p=ye(c.explanationId,100);if(!p)throw new Error("recognition requires explanationId");let l=e.context?.explanations.find(h=>h.id===p);if(!l)throw new Error("recognition must cite a surfaced explanation");if(l.state!=="grounded")throw new Error("recognition must cite a grounded explanation");let f=c.summary,m={title:ye(f?.title,120),detail:ye(f?.detail,500)};if(!m.title||!m.detail)throw new Error("recognition summary title and detail are required");return{draft:{decision:"recognize",explanationId:p,summary:m},visibleText:n}}if(c.decision==="apply"){let p=c.summary,l={title:ye(p?.title,120),detail:ye(p?.detail,500)};if(!l.title||!l.detail)throw new Error("application summary title and detail are required");let f=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(B=>typeof B=="string"&&!!B.trim()):[];if(!f.length)throw new Error("application requires appliedExplanationIds");let m=new Map(e.context?.explanations.map(B=>[B.id,B])??[]),h=new Set(e.context?.pendingGroundingExplanationIds??[]),j=f.filter(B=>{let E=m.get(B);return E&&(E.state==="emerging"||E.state==="testing")&&!h.has(B)});if(!j.length){if(f.every(E=>m.get(E)?.state==="grounded"||h.has(E)))return{draft:{decision:"none",reason:"application_only"},visibleText:n};throw new Error("application must cite a surfaced ungrounded explanation")}let b=c.grounding,g=typeof b?.explanationId=="string"&&j.includes(b.explanationId)?b.explanationId:j[0];return{draft:{decision:"apply",summary:l,appliedExplanationIds:j,grounding:{explanationId:g,question:ye(b?.question,300)||"Does applying this understanding here match your intent?"}},visibleText:n}}if(c.decision!==void 0&&c.decision!=="mutate")throw new Error("imprint decision is invalid");let d=c.summary,u=d?.kind;if(!["added","strengthened","refined","challenged","exception","consolidated"].includes(String(u)))throw new Error("summary.kind is invalid");let I={kind:u,title:ye(d?.title,120),detail:ye(d?.detail,500)};if(!I.title||!I.detail)throw new Error("summary title and detail are required");let T=Array.isArray(c.appliedExplanationIds)?c.appliedExplanationIds.filter(p=>typeof p=="string"&&!!p.trim()):[],k=[];for(let p of Array.isArray(c.mutations)?c.mutations:[]){if(!p||typeof p!="object")continue;let l=p;if(l.op==="add"&&["intention","principle","pattern"].includes(String(l.kind))){let f=ye(l.statement),m=ye(l.rationale);if(!f||!m)continue;k.push({op:"add",clientId:ye(l.clientId,100)||void 0,kind:l.kind,statement:f,rationale:m,scope:Ar(l.scope),rootReason:ye(l.rootReason,300)||void 0})}else if(l.op==="revise"&&typeof l.explanationId=="string"){let f={op:"revise",explanationId:l.explanationId,statement:ye(l.statement)||void 0,rationale:ye(l.rationale)||void 0,scope:Ar(l.scope),reopenGrounding:l.reopenGrounding===!0};(f.statement||f.rationale||f.scope||f.reopenGrounding)&&k.push(f)}else if(l.op==="evidence"&&typeof l.explanationId=="string"&&["supports","challenges","excepts"].includes(String(l.stance))){let f=ye(l.summary);f&&k.push({op:"evidence",explanationId:l.explanationId,stance:l.stance,summary:f})}else if(l.op==="relation"&&typeof l.fromId=="string"&&typeof l.toId=="string"&&["expresses","excepts"].includes(String(l.type))){let f=ye(l.rationale);if(!f)continue;k.push({op:"relation",type:l.type,fromId:l.fromId,toId:l.toId,rationale:f})}else if(l.op==="supersede"&&typeof l.explanationId=="string"&&typeof l.replacementId=="string"){let f=ye(l.reason);f&&k.push({op:"supersede",explanationId:l.explanationId,replacementId:l.replacementId,reason:f})}else if(l.op==="bind_concrete"&&typeof l.explanationId=="string"){let f=ye(l.modelPath,300);f&&k.push({op:"bind_concrete",explanationId:l.explanationId,modelPath:f,rationale:ye(l.rationale)})}else l.op==="retire"&&typeof l.explanationId=="string"&&k.push({op:"retire",explanationId:l.explanationId,reason:ye(l.reason)})}let P=c.grounding,x=P&&typeof P.explanationId=="string"&&ye(P.question)?{explanationId:P.explanationId,question:ye(P.question,300)}:void 0;return{draft:{decision:"mutate",summary:I,appliedExplanationIds:T,mutations:k,grounding:x},visibleText:n}}catch(c){return{visibleText:n,error:c instanceof Error?c.message:String(c)}}}function ei(o,e={}){let t=o?.explanations??[],n=new Set(o?.pendingGroundingExplanationIds??[]),i=new Set(o?.correctionExplanationIds??[]),r=Yo(e.requestText);return["","## Continuous imprinting","","An imprint is provisional shared understanding learned through human-AI collaboration. It is advisory, not authoritative product truth. Accepted product decisions above always win when they conflict.",...t.length?["","Relevant explanations from the project imprint:",...t.map((s,c)=>[`${c+1}. [${s.state}; ${s.kind}] ${s.statement}`,` - Why: ${s.rationale}`,` - Scope: ${s.scope.kind} ${s.scope.values.join(", ")}`,` - Explanation: ${s.id}`,...n.has(s.id)?[" - Grounding: already pending; do not ask again"]:[],...i.has(s.id)?[" - Correction: the developer selected No for this explanation and the current reply supplies the missing correction context"]:[],...s.concrete.map(d=>` - Concrete terminal: ${d.modelPath} = ${JSON.stringify(d.value)}`)].join(`
|
|
180
|
+
`)),...o?.truncated?["Additional imprint context exists outside this bounded packet."]:[]]:[],...o?.relations?.length?["","Known explanation topology:",...o.relations.map(s=>`- ${s.fromId} --${s.type}--> ${s.toId}: ${s.rationale}`)]:[],"","Work normally and preserve developer agency. A testing explanation may guide action as a hypothesis without asking permission first. An emerging explanation is observation-only: use it to recognize recurrence, not to choose behavior. If the developer independently repeats an emerging observation in a meaningfully different occurrence, that new application may promote it into testing and request grounding. Silence is not confirmation.","Assess learning proactively as part of completing every thread. Do not wait for the developer to ask whether there was a learning. Before choosing none, look one abstraction level above the exact edit and ask: would the reasoning behind this outcome change how a future agent handles a meaningfully different occurrence?","The developer's original annotation, ordinary instruction, scope language, and later corrections are already human-supplied evidence. They can support learning when they establish a reusable dependency, boundary, or rationale; a separate post-completion learning prompt is not required. Mere acceptance of completed work is still insufficient.","The default outcome is no imprint mutation. Completing work or making a successful design choice does not by itself constitute learning.","Application evidence is distinct from changing shared understanding. When an emerging or testing explanation materially influenced a completed action, report decision apply even when no explanation wording changed.","Applying grounded understanding does not mutate the graph. Usually report none. Use decision recognize only when visibly acknowledging the grounded explanation closes a correction loop or otherwise makes consequential reuse legible to the developer. Recognition must cite one exact surfaced grounded explanation ID; never infer or invent an ID.","Application and recognition are whole-statement operations. Cite an existing explanation only when the completed behavior is compatible with every material clause, its scope, and its exceptions. Sharing one useful clause is not a match. If the durable behavior is narrower, add one atomic explanation linked to the broader explanation when the admission tests pass; otherwise report none.","Mutate the imprint only when this collaboration changed reusable shared understanding: a future agent facing a meaningfully different task would behave differently because of what was learned here.","Relationship-first admission: before calling any completed change task-specific, compare its requested behavior and effective scope with every surfaced explanation that could plausibly govern the same subject or treatment. The developer does not need to name an Imprint concept or relation. Infer the relationship from the ordinary instruction, the annotated context, the implementation, and the surfaced explanations.","A narrower completed behavior that departs from an applicable broader explanation establishes an applicability boundary even when the developer did not say exception. Add one narrow testing explanation and link it to the broader rule with excepts. If the behaviors concern distinct concepts rather than the same rule, assess the reusable behavior as a sibling explanation instead. Do not manufacture an exception merely because implementations differ.","Scope and Imprint assessment must agree. If any resolved annotation has an effective inferred or final breadth of pattern, do not classify the Imprint decision as task_specific_detail. Either capture the reusable conceptual change, report application of existing understanding, cite a valid duplicate, or use another accurate no-op reason. The bridge rejects pattern-scoped task_specific_detail assessments.","","Before proposing a mutation, apply every admission test:","1. Reusable: it guides a future decision beyond reproducing this exact edit.","2. Novel: it is not already expressed by an explanation or its evidence.","3. Durable: it is an intention, rationale, relationship, or recurring pattern, not temporary implementation state.","4. Atomic: it expresses one claim at one abstraction level.","5. Scoped: its applicability can be named without silently generalizing.","6. Supported: the human supplied evidence, correction, or confirmation anywhere in the thread, including the original instruction, not merely acceptance of completed work or the model's own implementation choice.","If any test fails, return a decision of none.","","Usually not learning: exact copy substitutions, one-pixel adjustments, element reordering, implementation mechanics, keeping something hidden temporarily, applying an already-known pattern, or a stylistic choice made without human feedback. Distinguish mechanics from the reusable reasoning they may reveal: a CSS property alone is not learning, but a human-directed causal rule such as keeping optical adjustment out of layout geometry may be. This heuristic never overrides relationship-first admission: a small local change that narrows or contradicts an applicable surfaced explanation may establish an exception or correction. A task-specific edit otherwise becomes learning only if the human establishes a reusable dependency, applicability boundary, or rationale beyond that edit.","When a candidate overlaps an existing explanation, consolidate before adding. Same meaning plus a new observation means evidence only. A concrete application means bind_concrete, not a broader explanation. A scope correction means revise scope. A direct disagreement means add the replacement and supersede the contradicted explanation. A different abstraction level means a separate related explanation.","Duplicate means the same reusable claim is already represented at an equivalent or broader conceptual scope. Shared code, a centralized component, or implementation reuse does not establish conceptual duplication. A narrower component-, route-, selector-, or file-scoped explanation is not a duplicate of newly broadened applicability.","Words such as all, every, across, throughout, globally, and project-wide are explicit applicability signals. When the human broadens a grounded explanation, preserve the grounded narrower explanation and add a broader testing explanation. Link the narrower explanation to the broader one with expresses. Do not substitute another no-op reason for that scope change.",...r?["CURRENT SCOPE SIGNAL: The developer used explicit broadening language in this instruction. Do not classify it as duplicate unless the cited existing explanation already expresses universal or project-wide applicability."]:[],"Keep correction identity explicit. If feedback refines an emerging or testing explanation without rejecting its underlying claim, revise it and set reopenGrounding true; do not also add challenging evidence to that same explanation. If feedback rejects the claim as written, preserve that rejected wording, add a distinct replacement, and supersede the old explanation. Never revise an explanation and mark that same identity challenged in one update.","When an explanation is marked Correction in the supplied context, the developer selected No but the graph has not yet been changed. Interpret the current reply before mutating anything. Decide whether it corrects only the implementation result, the explanation scope, or the reasoning. Do not challenge the whole explanation for a narrow correction, and do not recognize a different explanation merely because one clause overlaps.","Topology assessment is mandatory for every add mutation. Imprint topology has exactly two relation types: expresses and excepts. expresses always points from the more specific, concrete, or lower-level explanation to the more abstract explanation it expresses. excepts points from the narrower exception to the rule whose applicability it limits. Support and challenge belong in evidence; correction belongs in supersede; neither is a topology relation. If an addition is genuinely a new root with no meaningful relative, include rootReason explaining why. Unmapped additions without rootReason are rejected.","Never append implementation facts to an intention merely because they occurred in the same component. Grounded explanations are append-only: add evidence for a compatible observation, but never revise or demote the grounded explanation. A material change in meaning, causal rationale, abstraction level, or applicability must be a new testing explanation linked with expresses or excepts. Multiple specific explanations may express the same parent, and one explanation may express multiple parents; never create an expresses cycle.","Grounded explanations may support new higher-level theory. Emerging explanations must not be the sole basis for another durable explanation. Concrete project facts should remain concrete; do not turn a one-off value into a universal principle.","Request grounding when an ungrounded explanation materially influenced the action, this application produced genuinely new evidence, and that explanation does not already have grounding pending. Ask at most one grounding question per thread. The bridge supplies a fallback question when the application is otherwise valid.","","At the end, emit exactly one machine-readable <resolution> envelope after the normal response. Its `annotations` array reports annotation outcomes, and its required `imprint` field completes the learning assessment. The envelope is hidden from the developer. Do not emit a separate <imprint> block.","For no learning, include:",'"imprint":{"decision":"none","reason":"application_only|transient_state|concrete_without_model_path|duplicate|insufficient_evidence|task_specific_detail|no_shared_understanding_change"}',"A no-op reason cannot suppress application evidence. When the completed action semantically matches the top retrieved ungrounded explanation, the bridge records that application regardless of the no-op label. Report decision apply directly so the summary and grounding question are intentional.","When and only when reason is duplicate, also include `duplicateOfExplanationId` naming one surfaced explanation and `scopeComparison` set to `equivalent` or `existing_broader`. The bridge rejects uncited duplicates and duplicates whose cited explanation cannot cover explicit broadening language.","For application evidence without a conceptual change, include:",'"imprint":{"decision":"apply","summary":{"title":"<short expandable-summary title>","detail":"<how the explanation influenced this completed action>"},"appliedExplanationIds":["<surfaced emerging or testing explanation id>"],"grounding":{"explanationId":"<one applied id>","question":"<brief post-application confirmation question>"}}',"For a consequential, non-mutating reuse of grounded understanding that should be visible, include:",'"imprint":{"decision":"recognize","explanationId":"<one exact surfaced grounded explanation id>","summary":{"title":"<short name for the recognized understanding>","detail":"<how it guided this outcome>"}}',"Or, only after every admission test passes for a conceptual change:",'"imprint":{"decision":"mutate","summary":{"kind":"added|strengthened|refined|challenged|exception|consolidated","title":"<short expandable-summary title>","detail":"<what changed in shared understanding>"},"appliedExplanationIds":["<only an ungrounded explanation materially tested here>"],"mutations":[{"op":"add","clientId":"new-1","kind":"intention|principle|pattern","statement":"<one durable atomic explanation>","rationale":"<why the evidence supports it>","scope":{"kind":"project|route|component|selector|file","values":["<scope>"]},"rootReason":"<only when this is genuinely unrelated to every surfaced or new explanation>"},{"op":"revise","explanationId":"<only an emerging or testing id>","statement":"<optional>","rationale":"<optional>","scope":{"kind":"component","values":["CardTile"]},"reopenGrounding":false},{"op":"evidence","explanationId":"<id>","stance":"supports|challenges|excepts","summary":"<thread evidence>"},{"op":"relation","type":"expresses|excepts","fromId":"<specific id or clientId>","toId":"<abstract rule id or clientId>","rationale":"<why>"},{"op":"supersede","explanationId":"<contradicted old id>","replacementId":"<new clientId or existing id>","reason":"<direct conflict>"},{"op":"bind_concrete","explanationId":"<id or clientId>","modelPath":"<exact existing model path>","rationale":"<how this fact expresses the explanation>"},{"op":"retire","explanationId":"<id>","reason":"<why>"}],"grounding":{"explanationId":"<one applied ungrounded id or clientId>","question":"<brief post-application confirmation question>"}}','The final shape is `<resolution>{"annotations":[...],"imprint":{...}}</resolution>`. The `imprint` field is required even when the decision is none; omission leaves the completed run explicitly unassessed.',"Include only mutation objects actually needed. A new explanation established through completed implementation must include its clientId in appliedExplanationIds; the bridge also derives this application from a completed change as a safeguard. Applying a grounded explanation requires neither appliedExplanationIds nor a mutation. Never claim that a new explanation is grounded."].join(`
|
|
181
|
+
`)}var mn=class{constructor(e,t){this.noopCounts=new Map;this.assessmentFailures=new Map;this.store=new Xn(e,t)}recordNoop(e){this.noopCounts.set(e,(this.noopCounts.get(e)??0)+1)}recordAssessmentFailure(e){this.assessmentFailures.set(e,(this.assessmentFailures.get(e)??0)+1)}diagnostics(){return{noopDecisions:Object.fromEntries(this.noopCounts),assessmentFailures:Object.fromEntries(this.assessmentFailures)}}async contextualize(e){let t=Yn(e.text??""),n=Yn((e.subjectHints??[]).join(" ")),i=new Set(e.pendingGroundingExplanationIds??[]),r=new Set(e.correctionExplanationIds??[]);if(!t.size&&!n.size&&!i.size&&!r.size)return;let{graph:s}=await this.store.load(),c=s.explanations.filter(p=>p.state!=="retired"&&(p.state!=="challenged"||r.has(p.id))).map(p=>{let l=Yn([p.statement,p.rationale].join(" ")),f=Yn(p.scope.values.join(" ")),m=Zn(l,t),h=Zn(f,t),j=Zn(f,n),b=Zn(l,n),g=m+h*.2+j*.25+b*.1+(p.state==="grounded"?.08:0)+(i.has(p.id)?1:0)+(r.has(p.id)?1:0),B=i.has(p.id)||r.has(p.id)||(t.size?m>=.12||h>=.5:j>=.2||b>=.2);return{item:p,score:g,relevant:B}}).filter(p=>p.relevant&&p.score>=.18).sort((p,l)=>l.score-p.score||l.item.updatedAt.localeCompare(p.item.updatedAt)),d=Math.max(1,e.maxExplanations??6);if(!c.length)return;let u=c.slice(0,d).map(({item:p})=>p),I=new Set(u.map(p=>p.id)),T=new Set(s.relations.flatMap(p=>I.has(p.fromId)?[p.toId]:I.has(p.toId)?[p.fromId]:[])),k=new Set(s.explanations.flatMap(p=>T.has(p.id)&&p.state!=="retired"&&p.state!=="challenged"?[p.id]:[])),P=s.explanations.filter(p=>k.has(p.id)&&!I.has(p.id)).sort((p,l)=>l.updatedAt.localeCompare(p.updatedAt)).slice(0,4),x=[...u,...P];for(let p of P)I.add(p.id);return{explanations:x.map(p=>{let l=new Set(s.relations.filter(f=>f.toId===p.id&&f.type==="expresses").map(f=>f.fromId));return{id:p.id,kind:p.kind,statement:p.statement,rationale:p.rationale,scope:p.scope,state:p.state,concrete:s.concrete.filter(f=>l.has(f.id)).map(f=>({id:f.id,modelPath:f.modelPath,value:f.value}))}}),truncated:c.length>u.length||P.length<k.size,...i.size?{pendingGroundingExplanationIds:[...i]}:{},...r.size?{correctionExplanationIds:[...r]}:{},relations:s.relations.filter(p=>I.has(p.fromId)&&I.has(p.toId)).map(p=>({id:p.id,type:p.type,fromId:p.fromId,toId:p.toId,rationale:p.rationale}))}}async capture(e,t){let n=e.decision==="mutate"?e.mutations:[],i=t.applicationOccurred?n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[]):[],r=[...new Set([...e.appliedExplanationIds,...i])];if(n.length===0&&r.length===0)return;let s=t.occurredAt??new Date().toISOString(),c=await this.store.load(),d=new Map(c.graph.explanations.map(w=>[w.id,w])),u=new Map,I=new Map,T=[],k=new Set,P=new Set(t.pendingGroundingExplanationIds??[]),x=new Set(n.flatMap(w=>w.op==="revise"&&n.some(H=>H.op==="evidence"&&H.stance==="challenges"&&H.explanationId===w.explanationId)?[w.explanationId]:[])),p=new Set(n.flatMap(w=>w.op==="add"&&w.clientId?[w.clientId]:[])),l=w=>d.has(w)||p.has(w),f=new Set;for(let w of n)w.op==="relation"&&w.fromId!==w.toId&&l(w.fromId)&&l(w.toId)?(f.add(w.fromId),f.add(w.toId)):w.op==="supersede"&&w.explanationId!==w.replacementId&&l(w.explanationId)&&l(w.replacementId)?(f.add(w.explanationId),f.add(w.replacementId)):w.op==="bind_concrete"&&l(w.explanationId)&&Mr(t.concreteModel,w.modelPath).found&&f.add(w.explanationId);let m=c.graph.explanations.length===0;for(let w of n){if(w.op!=="add")continue;let H=!!(w.clientId&&f.has(w.clientId)),L=!!w.rootReason?.trim()||m;if(!H&&!L)continue;m&&(m=!1);let O=it();w.clientId&&u.set(w.clientId,O);let he=w.clientId?r.includes(w.clientId):!1,J={id:O,kind:w.kind,statement:w.statement,rationale:w.rationale,scope:Xo(w.scope),state:he?"testing":"emerging",createdAt:s,updatedAt:s,evidence:[mt(t,"supports",e.summary.detail)]};d.set(O,J),k.add(O),T.push({op:"add_explanation",explanation:J})}let h=w=>u.get(w)??w;for(let w of n){if(w.op!=="revise")continue;let H=h(w.explanationId),L=d.get(H);if(L?.state!=="grounded")continue;let O=it(),he={id:O,kind:L.kind,statement:w.statement??L.statement,rationale:w.rationale??L.rationale,scope:w.scope?Xo(w.scope):L.scope,state:"testing",createdAt:s,updatedAt:s,evidence:[mt(t,"supports",e.summary.detail)]};d.set(O,he),I.set(H,O),k.add(O),T.push({op:"add_explanation",explanation:he});let J=Ot(L,he);J!==0&&T.push({op:"add_relation",relation:{id:it(),type:"expresses",fromId:J>0?H:O,toId:J>0?O:H,rationale:w.rationale??e.summary.detail,createdAt:s}})}let j=w=>{let H=h(w);return I.get(H)??H};for(let w of n){if(w.op==="add")continue;if(w.op==="bind_concrete"){let L=j(w.explanationId);if(!d.has(L))continue;let O=Mr(t.concreteModel,w.modelPath);if(!O.found)continue;let he=c.graph.concrete.find(J=>J.modelPath===w.modelPath&&JSON.stringify(J.value)===JSON.stringify(O.value));he||(he={id:it(),modelPath:w.modelPath,value:structuredClone(O.value),createdAt:s,updatedAt:s},T.push({op:"add_concrete",concrete:he})),T.push({op:"add_relation",relation:{id:it(),type:"expresses",fromId:he.id,toId:L,rationale:w.rationale,createdAt:s}}),k.add(L);continue}if(w.op==="relation"){let L=j(w.fromId),O=j(w.toId);if(!d.has(L)||!d.has(O)||L===O)continue;w.type==="expresses"&&Ot(d.get(L),d.get(O))<0&&([L,O]=[O,L]),T.push({op:"add_relation",relation:{id:it(),type:w.type,fromId:L,toId:O,rationale:w.rationale,createdAt:s}}),k.add(L),k.add(O);continue}if(w.op==="supersede"){let L=j(w.explanationId),O=j(w.replacementId);if(!d.has(L)||!d.has(O)||L===O)continue;T.push({op:"add_evidence",explanationId:L,evidence:mt(t,"challenges",w.reason)}),T.push({op:"revise_explanation",explanationId:L,patch:{state:"challenged",supersededBy:O},updatedAt:s}),k.add(L),k.add(O);continue}let H=j(w.explanationId);if(d.has(H))if(k.add(H),w.op==="revise"){if(I.has(h(w.explanationId)))continue;let L=d.get(H);if(!L||L.state!=="emerging"&&L.state!=="testing")continue;let O={...w.statement?{statement:w.statement}:{},...w.rationale?{rationale:w.rationale}:{},...w.scope?{scope:Xo(w.scope)}:{},...w.reopenGrounding||x.has(w.explanationId)?{state:"testing"}:{}};T.push({op:"revise_explanation",explanationId:H,patch:O,updatedAt:s})}else if(w.op==="evidence"){if(w.stance==="challenges"&&x.has(w.explanationId))continue;T.push({op:"add_evidence",explanationId:H,evidence:mt(t,w.stance,w.summary)}),w.stance==="challenges"&&T.push({op:"revise_explanation",explanationId:H,patch:{state:"challenged"},updatedAt:s})}else w.op==="retire"&&(T.push({op:"add_evidence",explanationId:H,evidence:mt(t,"challenges",w.reason||"Retired after contradictory collaboration evidence.")}),T.push({op:"revise_explanation",explanationId:H,patch:{state:"retired"},updatedAt:s}))}for(let w of r){let H=j(w),L=d.get(H);!L||L.state==="grounded"||L.state==="retired"||P.has(H)&&!k.has(H)||(k.has(H)||(k.add(H),T.push({op:"add_evidence",explanationId:H,evidence:{...mt(t,"supports",`Applied as an advisory hypothesis: ${e.summary.detail}`),kind:"application"}})),L.state==="emerging"&&T.push({op:"revise_explanation",explanationId:H,patch:{state:"testing"},updatedAt:s}))}let b=new Set(c.graph.relations.map(w=>`${w.type}:${w.fromId}:${w.toId}`)),g=T.filter(w=>{if(w.op!=="add_relation")return!0;let H=`${w.relation.type}:${w.relation.fromId}:${w.relation.toId}`;return b.has(H)?!1:(b.add(H),!0)});if(!g.length)return;let B=it(),E=await this.store.commit({transactionId:B,committedAt:s,source:{kind:"automatic",threadId:t.threadId,jobId:t.jobId},summary:e.summary.title,mutations:g}),R=new Map(E.graph.explanations.map(w=>[w.id,w])),N=[...k].flatMap(w=>{let H=R.get(w);if(!H)return[];let L=!c.graph.explanations.some(he=>he.id===w),O=H.state==="challenged"||H.state==="retired";return[{explanationId:w,action:L?"added":O?"challenged":"revised",statement:H.statement,state:H.state}]}),V=r.map(j).find(w=>R.get(w)?.state==="testing"&&!P.has(w)),K=e.grounding?j(e.grounding.explanationId):V,W=K?R.get(K):void 0,Q=W?.state==="testing"&&!P.has(W.id)?{explanationId:W.id,question:e.grounding?.question||Qc(W),state:"testing"}:void 0;return{transactionId:B,kind:e.decision==="apply"?"strengthened":e.summary.kind,title:e.summary.title,detail:e.summary.detail,changes:N,...Q?{grounding:Q}:{}}}async applyGroundingAction(e){let t=e.occurredAt??new Date().toISOString(),n=e.summary.grounding?.explanationId??e.summary.changes[0]?.explanationId;if(!n)throw new Error("This imprint summary has no explanation to update.");let r=(await this.store.load()).graph.explanations.find(u=>u.id===n);if(!r||r.state==="retired")throw new Error("This explanation is no longer active.");if(e.action==="no")return"pending_correction";let s={kind:"grounding",threadId:e.threadId,jobId:e.jobId},c=[],d="";if(e.action==="yes"?(c.push({op:"add_evidence",explanationId:n,evidence:{...mt(e,"supports","The developer confirmed that the applied reasoning matched their intent."),kind:"confirmation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"grounded"},updatedAt:t}),d=`Grounded: ${r.statement}`):e.action==="this_time"&&(c.push({op:"add_evidence",explanationId:n,evidence:{...mt(e,"supports","The developer accepted this result for the current occurrence without confirming it as reusable."),kind:"observation"}}),c.push({op:"revise_explanation",explanationId:n,patch:{state:"emerging"},updatedAt:t}),d=`Observed this time: ${r.statement}`),!c.length)throw new Error("Unsupported imprint action.");return await this.store.commit({transactionId:it(),committedAt:t,source:s,summary:d,mutations:c}),"applied"}};function Er(o,e){return o?.projectId===e.projectId&&o.version===e.version&&o.restartMode===e.restartMode}function eo(o){return(Array.isArray(o)?o[0]:o)?.split(",")[0]?.trim()||void 0}function ti(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 _r(o){let e=ti(eo(o.origin));if(e)return e;let t=ti(eo(o.referer));if(t)return t;let n=eo(o["x-forwarded-host"]);if(!n)return null;let i=eo(o["x-forwarded-proto"])==="https"?"https":"http";return ti(`${i}://${n}`)}function $r(o,e,t=5){let n=(d,u)=>(u.completedAt??u.startedAt)-(d.completedAt??d.startedAt),i=[...o].sort(n).slice(0,t),r=o.filter(d=>d.status==="applied"||d.status==="failed").sort(n).slice(0,t),s=e.filter(d=>d.status==="pending"&&d.authorityStatus==="accepted").sort((d,u)=>u.updatedAt-d.updatedAt).slice(0,10),c=s.reduce((d,u)=>(d[u.status]=(d[u.status]??0)+1,d),{});return{recentRuns:i,recentAppliedRuns:r,actionableProposalCounts:c,actionableProposals:s}}import{createHash as oo}from"crypto";import{mkdir as hn,readFile as Rt,unlink as od,writeFile as zt}from"fs/promises";import{dirname as io,extname as id,join as Oe}from"path";var Yc={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 Zc(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 Cr(o,e){let t=e??Zc(o);return{kind:t,...Yc[t]}}function Ut(o,e){return!o||e||o.attention!=="response_requested"?o:{...o,attention:"response_available"}}function ni(o){let e=Array.from(new Set((o.changedFiles??[]).filter(Boolean))),t=e.length>0?[{kind:"changes_applied",files:e}]:[{kind:"replied"}],n=o.decisionRequired?"decision_required":o.question||o.groundingRequired?"response_requested":o.reviewRequired||o.resolutions?.some(i=>i.status==="needs_review")?"review_required":"response_available";return o.imprintTransactionId&&t.push({kind:"imprint_updated",transactionId:o.imprintTransactionId}),{attention:n,outcomes:t}}import{createHash as ed,randomUUID as td}from"crypto";var Or=o=>`${o}-${td()}`;function oi(o,...e){return`${o}-${ed("sha256").update(e.join(":")).digest("hex").slice(0,24)}`}function ii(o){return{schemaVersion:1,submissionIds:[Or("submission")],jobId:o.jobId,threadId:o.threadId,artifactIds:[...new Set(o.artifactIds??[])]}}function fn(o,e=[],t){return{...o,outcomeId:o.outcomeId??Or("outcome"),imprintEvidenceIds:[...new Set([...o.imprintEvidenceIds??[],...e])],...t?{imprintAssessment:t}:{}}}function nd(o){try{return new URL(o).pathname||"/"}catch{return"/"}}function to(o,e){return e?[`${o||"/"}:${e}`]:[]}function Dr(o){let e=nd(o.url);return[...new Set([...o.annotations.flatMap(t=>to(t.pathname??e,t.linkedSelector)),...o.styleModifications.flatMap(t=>to(e,t.durableSelector??t.selector)),...(o.textModifications??[]).flatMap(t=>to(t.pathname??e,t.durableSelector??t.selector)),...(o.domModifications??[]).flatMap(t=>to(t.pathname??e,t.durableSelector??t.selector))])]}function Nr(o,e){return[...new Set([`screenshot:${e}`,...o.annotations.map(t=>`annotation:${t.id}`),...o.annotations.flatMap(t=>(t.attachments??[]).map(n=>`attachment:${n.id}`))])]}function no(o,e){if(e.lifecycle?.schemaVersion===1)return!1;let t=oi("submission",o,e.jobId,e.timestamp,e.role);return e.lifecycle={schemaVersion:1,submissionIds:[t],jobId:e.jobId,threadId:o,artifactIds:[...(e.annotationIds??[]).map(n=>`annotation:${n}`),...e.screenshotPath?[oi("artifact",o,e.jobId,"screenshot")]:[]],...e.role==="assistant"?{outcomeId:oi("outcome",o,e.jobId,e.timestamp),imprintEvidenceIds:e.imprintSummary?.transactionId?[e.imprintSummary.transactionId]:[]}:{}},!0}function ri(o){let e=o.lifecycleVersion!==1;o.lifecycleVersion=1;for(let t of o.messages)e=no(o.id,t)||e;return e}function Jr(o){let e=o.messages.at(-1),t=[...o.messages].reverse().find(i=>i.role==="assistant");if(!e||e.role==="human")return{jobId:e?.jobId,threadId:o.id,status:"in_flight",label:"Thinking",imprintEvidenceIds:[]};if(e.error||e.cancelled)return{jobId:e.jobId,threadId:o.id,status:"failed",label:"Failed",outcomeId:e.lifecycle?.outcomeId,imprintEvidenceIds:e.lifecycle?.imprintEvidenceIds??[]};let n=!!(e.question||e.imprintSummary?.grounding?.question&&!e.imprintSummary.resolvedAction);return{jobId:t?.jobId,threadId:o.id,status:n?"waiting_input":"resolved",label:n?"Question":"Replied",outcomeId:t?.lifecycle?.outcomeId,imprintEvidenceIds:t?.lifecycle?.imprintEvidenceIds??[]}}var rd={version:1,threads:{}},Br=["feedbackContext","annotationSnapshot","memoryReview","imprintContext","toolsUsed","editEvents","segments"],gn={version:2,updatedAt:0,files:{}};function sd(o){return JSON.stringify(o,null,2)}function ad(o){return Object.fromEntries(Br.flatMap(e=>o[e]===void 0?[]:[[e,o[e]]]))}function cd(o){let e={...o};for(let t of Br)delete e[t];return e}function Gt(o){let e=o;if(o.error){let t=Cr(o.error,o.errorKind);(o.error!==t.message||o.errorKind!==t.kind||o.responseText!==void 0)&&(e={...o,error:t.message,errorKind:t.kind},delete e.responseText)}if(e.imprintSummary?.resolvedAction&&!e.question){let t=Ut(e.result,!1),n=Ut(e.turn?.result,!1);(t!==e.result||n!==e.turn?.result)&&(e={...e,...t?{result:t}:{},...e.turn?{turn:{...e.turn,...n?{result:n}:{}}}:{}})}return e}var ro=class{constructor(e){this.cache=null;this.index=null;this.writeChain=Promise.resolve();let t=Oe(e,".popmelt");this.legacyFilePath=Oe(t,"threads.json"),this.threadsDir=Oe(t,"threads"),this.indexPath=Oe(this.threadsDir,"index.json"),this.artifactsDir=Oe(t,"artifacts","thread-messages"),this.mediaDir=Oe(t,"artifacts","thread-media")}async load(){if(this.cache)return this.cache;try{let e=JSON.parse(await Rt(this.indexPath,"utf-8"));if(e?.version===2&&e.files&&typeof e.files=="object"){this.index=e;let t={};for(let[i,r]of Object.entries(e.files)){let s=await this.readThread(Oe(this.threadsDir,r));s&&(t[i]=s)}this.cache={version:1,threads:t};let n=!1;for(let i of Object.values(t))n=ri(i)||n;return n&&await this.persistAll(),this.cache}}catch{}try{let e=JSON.parse(await Rt(this.legacyFilePath,"utf-8"));if(e?.version===1&&e.threads){this.cache={version:1,threads:Object.fromEntries(Object.entries(e.threads).map(([t,n])=>[t,{...n,messages:n.messages.map(Gt)}]))},this.index={...gn,files:{},migratedFromLegacyAt:Date.now()};for(let t of Object.values(this.cache.threads))ri(t);return await this.persistAll(),this.cache}}catch{}return this.cache={...rd,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 t=await this.load(),n=new Set(e);for(let i of Object.values(t.threads))if(i.elementIdentifiers.some(s=>n.has(s)))return i;return null}async createThread(e,t){let n=await this.load(),i={id:e,lifecycleVersion:1,createdAt:Date.now(),updatedAt:Date.now(),elementIdentifiers:t,messages:[]};return n.threads[e]=i,await this.persistThread(i),i}async appendMessage(e,t){let i=(await this.load()).threads[e];i&&(no(e,t),i.messages.push(Gt(t)),i.updatedAt=Date.now(),await this.persistThread(i))}async appendMessageBeforeQueuedReplies(e,t){let i=(await this.load()).threads[e];if(!i)return;no(e,t);let r=i.messages.findIndex(s=>s.role==="human"&&!!s.replyToQuestion&&s.queued);r>=0?i.messages.splice(r,0,Gt(t)):i.messages.push(Gt(t)),i.updatedAt=Date.now(),await this.persistThread(i)}async updateMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=r.messages.filter(c=>c.jobId===t);if(s.length===0)return!1;for(let c of s)if(Object.assign(c,n),c.error){let d=Gt(c);Object.assign(c,d),delete c.responseText}return r.updatedAt=Date.now(),await this.persistThread(r),!0}async updateAssistantMessage(e,t,n){let r=(await this.load()).threads[e];if(!r)return!1;let s=[...r.messages].reverse().find(c=>c.role==="assistant"&&c.jobId===t);return s?(Object.assign(s,n),r.updatedAt=Date.now(),await this.persistThread(r),!0):!1}async addElementIdentifiers(e,t){let i=(await this.load()).threads[e];if(!i)return;let r=new Set(i.elementIdentifiers);for(let s of t)r.has(s)||i.elementIdentifiers.push(s);i.updatedAt=Date.now(),await this.persistThread(i)}async deleteThread(e){let t=await this.load();return t.threads[e]?(delete t.threads[e],await this.deletePersistedThread(e),!0):!1}async listRecent(e=5){let t=await this.load(),n=Object.values(t.threads);return n.sort((i,r)=>r.updatedAt-i.updatedAt),n.slice(0,e).map(i=>{let s=i.messages.find(l=>l.role==="human")?.feedbackSummary||"[thread]",c=i.messages.filter(l=>l.role==="assistant"),d=l=>{if(l.role!=="assistant")return;if(l.question)return l.question;let f=l.imprintSummary?.grounding;if(f?.question&&!l.imprintSummary?.resolvedAction)return f.question},u=i.messages.findLastIndex(l=>!!d(l)),I=i.messages.findLastIndex(l=>l.role==="human"),T=u>I?d(i.messages[u]):void 0,k=i.messages.at(-1)?.role,P=Array.from(new Set(i.messages.slice(0,Math.max(0,I)).filter(l=>l.role==="assistant"&&!!l.jobId).map(l=>l.jobId))),x=c.some(l=>!!l.responseText||!!l.question||!!l.result||!!l.memoryReviewCard||!!l.memoryReceipt),p=c.some(l=>!!l.error);return{id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,preview:s,messageCount:i.messages.length,hasReply:x,hasError:p,lastMessageRole:k,pendingQuestion:T,acknowledgedJobIds:P,elementIdentifiers:i.elementIdentifiers,lifecycle:Jr(i)}})}async recoverInterruptedTurns(){let e=await this.load(),t=0;for(let n of Object.values(e.threads)){let i=n.messages.at(-1);if(!i||i.role!=="human"||/^(imprint|memory)-/.test(i.jobId))continue;let r=fn(i.lifecycle);i.queued&&await this.updateMessage(n.id,i.jobId,{queued:!1}),await this.appendMessage(n.id,{role:"assistant",timestamp:Date.now(),jobId:i.jobId,error:"This run was interrupted when the Popmelt bridge stopped. Send the thread again to continue.",lifecycle:r}),t+=1}return t}async getThreadHistory(e,t=6){let n=await this.getThread(e);return!n||n.messages.length===0?[]:n.messages.length<=t?n.messages:[n.messages[0],...n.messages.slice(-(t-1))]}async readThread(e){try{let t=JSON.parse(await Rt(e,"utf8"));if(t?.version!==2||!Array.isArray(t.messages))return null;let n=await Promise.all(t.messages.map(async({detailArtifact:i,...r})=>{let s={};if(i?.path)try{let c=await Rt(Oe(io(this.legacyFilePath),i.path),"utf8");oo("sha256").update(c).digest("hex")===i.sha256&&(s=JSON.parse(c))}catch{}return Gt({...r,...s})}));return{id:t.id,lifecycleVersion:t.lifecycleVersion,createdAt:t.createdAt,updatedAt:t.updatedAt,elementIdentifiers:t.elementIdentifiers,messages:n}}catch{return null}}async encodeMessage(e){await this.persistMessageMedia(e);let t=ad(e),n=cd(e);if(Object.keys(t).length===0)return n;let i=sd(t),r=oo("sha256").update(i).digest("hex"),s=Oe("artifacts","thread-messages",`${r}.json`);await hn(this.artifactsDir,{recursive:!0});try{await Rt(Oe(io(this.legacyFilePath),s),"utf8")}catch{await zt(Oe(io(this.legacyFilePath),s),i)}return{...n,detailArtifact:{path:s,sha256:r}}}async persistMessageMedia(e){let t=async n=>{if(io(n)===this.mediaDir)return n;try{let i=await Rt(n),r=oo("sha256").update(i).digest("hex"),s=Oe(this.mediaDir,`${r}${id(n)||".bin"}`);await hn(this.mediaDir,{recursive:!0});try{await Rt(s)}catch{await zt(s,i)}return s}catch{return n}};e.screenshotPath&&(e.screenshotPath=await t(e.screenshotPath)),e.screenshotPaths&&(e.screenshotPaths=Object.fromEntries(await Promise.all(Object.entries(e.screenshotPaths).map(async([n,i])=>[n,await t(i)])))),e.imagePaths&&(e.imagePaths=Object.fromEntries(await Promise.all(Object.entries(e.imagePaths).map(async([n,i])=>[n,await Promise.all(i.map(t))])))),e.attachmentFiles&&(e.attachmentFiles=Object.fromEntries(await Promise.all(Object.entries(e.attachmentFiles).map(async([n,i])=>[n,await Promise.all(i.map(async r=>({...r,path:await t(r.path)})))])))),e.replyImagePaths&&(e.replyImagePaths=await Promise.all(e.replyImagePaths.map(t)))}async persistThread(e){this.writeChain=this.writeChain.then(async()=>{try{await hn(this.threadsDir,{recursive:!0});let t=this.index??{...gn,files:{}},n=t.files[e.id]??`${oo("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 zt(Oe(this.threadsDir,n),JSON.stringify(r,null,2)),t.files[e.id]=n,t.updatedAt=Date.now(),this.index=t,await zt(this.indexPath,JSON.stringify(t,null,2))}catch(t){console.error("[ThreadStore] Failed to persist thread:",t)}}),await this.writeChain}async persistAll(){if(this.cache){for(let e of Object.values(this.cache.threads))await this.persistThread(e);Object.keys(this.cache.threads).length===0&&(await hn(this.threadsDir,{recursive:!0}),this.index=this.index??{...gn,files:{}},await zt(this.indexPath,JSON.stringify(this.index,null,2)))}}async deletePersistedThread(e){this.writeChain=this.writeChain.then(async()=>{let t=this.index??{...gn,files:{}},n=t.files[e];n&&await od(Oe(this.threadsDir,n)).catch(()=>{}),delete t.files[e],t.updatedAt=Date.now(),this.index=t,await hn(this.threadsDir,{recursive:!0}),await zt(this.indexPath,JSON.stringify(t,null,2))}),await this.writeChain}};import{mkdir as dd,open as ld,readFile as pd,rename as ud,unlink as md}from"fs/promises";import{dirname as fd,join as hd}from"path";var Lr={schemaVersion:1,theme:"auto",updatedAt:null};function qr(o){return o==="light"||o==="dark"||o==="auto"?o:null}async function gd(o,e){await dd(fd(o),{recursive:!0});let t=`${o}.${process.pid}.${Date.now()}.tmp`;try{let n=await ld(t,"w");try{await n.writeFile(`${JSON.stringify(e,null,2)}
|
|
182
|
+
`,"utf8"),await n.sync()}finally{await n.close()}await ud(t,o)}catch(n){throw await md(t).catch(()=>{}),n}}var so=class{constructor(e){this.path=hd(e,".popmelt","ui-preferences.json")}async load(){try{let e=JSON.parse(await pd(this.path,"utf8")),t=qr(e.theme);return t?{exists:!0,preferences:{schemaVersion:1,theme:t,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:null}}:{exists:!1,preferences:{...Lr}}}catch{return{exists:!1,preferences:{...Lr}}}}async setTheme(e){let t={schemaVersion:1,theme:e,updatedAt:new Date().toISOString()};return await gd(this.path,t),t}};function Fr(o){return qr(o)!==null}function Ur(o){return vd(o).slice(0,12)}var yd=[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 vd(o){let e=typeof TextEncoder<"u"?Array.from(new TextEncoder().encode(o)):Id(o),t=e.length*8;for(e.push(128);e.length%64!==56;)e.push(0);for(let k=7;k>=0;k--)e.push(t/Math.pow(2,k*8)&255);let n=1779033703,i=3144134277,r=1013904242,s=2773480762,c=1359893119,d=2600822924,u=528734635,I=1541459225,T=new Array(64);for(let k=0;k<e.length;k+=64){for(let b=0;b<16;b++){let g=k+b*4;T[b]=(e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])>>>0}for(let b=16;b<64;b++){let g=et(T[b-15],7)^et(T[b-15],18)^T[b-15]>>>3,B=et(T[b-2],17)^et(T[b-2],19)^T[b-2]>>>10;T[b]=T[b-16]+g+T[b-7]+B>>>0}let P=n,x=i,p=r,l=s,f=c,m=d,h=u,j=I;for(let b=0;b<64;b++){let g=et(f,6)^et(f,11)^et(f,25),B=f&m^~f&h,E=j+g+B+yd[b]+T[b]>>>0,R=et(P,2)^et(P,13)^et(P,22),N=P&x^P&p^x&p,V=R+N>>>0;j=h,h=m,m=f,f=l+E>>>0,l=p,p=x,x=P,P=E+V>>>0}n=n+P>>>0,i=i+x>>>0,r=r+p>>>0,s=s+l>>>0,c=c+f>>>0,d=d+m>>>0,u=u+h>>>0,I=I+j>>>0}return[n,i,r,s,c,d,u,I].map(k=>k.toString(16).padStart(8,"0")).join("")}function et(o,e){return o>>>e|o<<32-e}function Id(o){let e=[];for(let t=0;t<o.length;t++){let n=o.charCodeAt(t);n<128?e.push(n):n<2048?e.push(192|n>>6,128|n&63):e.push(224|n>>12,128|n>>6&63,128|n&63)}return e}function wd(o){let e=o.instruction?.trim();return e?o.attachments?.some(n=>n.name?.trim()===e)?null:e:null}function zr(o){let e=o.annotations.flatMap(i=>{let r=wd(i);return r?[{instruction:r,pathname:i.pathname}]:[]});if(e.length===0)return;if(new Set(e.map(i=>i.pathname).filter(Boolean)).size<=1)return e.map(i=>i.instruction).join(`
|
|
183
|
+
|
|
184
|
+
`);let n=new Map;for(let i of e){let r=i.pathname||"(unknown)",s=n.get(r)??[];s.push(i.instruction),n.set(r,s)}return[...n.entries()].map(([i,r])=>`\`${i}\`
|
|
185
|
+
${r.map(s=>`- ${s}`).join(`
|
|
186
|
+
`)}`).join(`
|
|
187
|
+
`)}var Gr={name:"@popmelt.com/core",version:"0.8.15",description:"The design collaboration layer for AI coding agents",license:"PolyForm-Shield-1.0.0",author:"Popmelt <reb@popmelt.com> (https://popmelt.com)",homepage:"https://github.com/popmelt/core",bugs:{url:"https://github.com/popmelt/core/issues"},repository:{type:"git",url:"git+https://github.com/popmelt/core.git"},keywords:["ai","annotations","collaboration","devtools","react","visual-feedback"],bin:{popmelt:"dist/cli.mjs"},sideEffects:!1,engines:{node:">=18.0.0"},scripts:{build:"tsup",clean:"git clean -xdf .turbo node_modules dist",format:'prettier --check "**/*.{ts,tsx}"',lint:"eslint .","pack:smoke":"node scripts/pack-smoke.mjs",prepublishOnly:"pnpm run verify",test:"vitest run","test:watch":"vitest",typecheck:"tsc --noEmit --incremental false",verify:"pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build && pnpm run pack:smoke"},exports:{".":{source:"./src/index.ts",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./provider":{source:"./src/components/PopmeltProvider.tsx",types:"./dist/index.d.mts",import:"./dist/index.mjs"},"./server":{source:"./src/server/index.ts",types:"./dist/server.d.mts",import:"./dist/server.mjs"},"./memory":{source:"./src/memory/index.ts",types:"./dist/memory.d.mts",import:"./dist/memory.mjs"},"./memory/legacy":{source:"./src/server/memory/index.ts",types:"./dist/memory-legacy.d.mts",import:"./dist/memory-legacy.mjs"},"./memory/store":{source:"./src/server/memory/journal-index.ts",types:"./dist/memory-store.d.mts",import:"./dist/memory-store.mjs"},"./canvas":{source:"./src/canvas/index.ts",import:"./dist/canvas.mjs"},"./next":{source:"./src/plugins/next.ts",import:"./dist/plugin-next.mjs",default:"./dist/plugin-next.mjs"},"./vite":{source:"./src/plugins/vite.ts",types:"./dist/plugin-vite.d.mts",import:"./dist/plugin-vite.mjs",default:"./dist/plugin-vite.mjs"},"./astro":{source:"./src/plugins/astro.ts",types:"./dist/plugin-astro.d.mts",import:"./dist/plugin-astro.mjs",default:"./dist/plugin-astro.mjs"}},files:["dist","LICENSE","README.md","THIRD_PARTY_NOTICES.md"],dependencies:{"modern-screenshot":"4.7.0",ws:"8.21.1"},peerDependencies:{"lucide-react":">=1.23.0",next:">=14.0.0",react:">=18.0.0","react-dom":">=18.0.0"},peerDependenciesMeta:{next:{optional:!0}},devDependencies:{"@kit/eslint-config":"workspace:^","@types/react":"19.1.0","@types/react-dom":"19.1.2","@types/ws":"8.18.1",eslint:"^9.24.0",geist:"1.7.2",jsdom:"26.1.0","lucide-react":"^1.23.0",next:"15.3.8",prettier:"^3.5.3",react:"19.1.0","react-dom":"19.1.0",tsup:"^8.5.1",typescript:"^5.8.3",vitest:"^3.2.4"}};var yn=Gr.version;var Cd=1111,Od=["Read","Edit","Write","Glob","Grep","Bash","WebFetch","WebSearch","Bash(curl:*)"],Dd=1800*1e3,Nd=3600*1e3,Vr=45e3,Jd=5e3,Bd=1e4,Ld=2*1024*1024;function Kr(o){return o.length<=1?o[0]??"":["The developer sent these queued steering messages while you were working:","",...o.map((e,t)=>`${t+1}. ${e}`)].join(`
|
|
188
|
+
`)}function vn(o){return[...new Set(o.flatMap(e=>{let t=e.imprintSummary;return e.role==="assistant"&&t?.grounding&&!t.resolvedAction?[t.grounding.explanationId]:[]}))]}function Qr(o){let e=o.findLastIndex(i=>i.role==="assistant");if(e<0)return[];let t=o[e];if(!t?.question||!t.jobId.startsWith("imprint-"))return[];let n=o.slice(0,e).findLast(i=>i.role==="assistant"&&i.imprintSummary?.resolvedAction==="no"&&!!i.imprintSummary.grounding);return n?.imprintSummary?.grounding?[n.imprintSummary.grounding.explanationId]:[]}function qd(o,e){if(e.size===1)return[...o].reverse().find(t=>{let n=t.imprintSummary;return t.role==="assistant"&&!!n?.grounding&&!n?.resolvedAction&&e.has(n.grounding.explanationId)})}function es(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 Fd(o,e,t){let n=[...t];for(let i of o)if(i.type==="tool_use"){let r=i.tool||"",s=i.file??void 0,c=i.content??void 0,d=s?s.split("/").pop()??s:void 0,u;switch(r){case"Read":u=d?`Reading ${d}`:"Reading file";break;case"Edit":u=d?`Editing ${d}`:"Editing file";break;case"Write":u=d?`Writing ${d}`:"Writing file";break;case"Bash":u=c?c.split(`
|
|
189
|
+
`)[0].trim().slice(0,60):"Running command";break;case"Glob":u="Searching files";break;case"Grep":u="Searching code";break;case"WebFetch":u="Fetching page";break;case"WebSearch":u="Searching web";break;default:u=r?`Using ${r}`:"tool";break}let I=s??c??void 0,T=s?Zr(s)?s:_d(e,s):void 0,k=n[n.length-1];k&&k.kind==="tool_group"&&k.tool===r?k.items.push({label:u,detail:I,...T?{filePath:T}:{}}):n.push({kind:"tool_group",tool:r,items:[{label:u,detail:I,...T?{filePath:T}:{}}]})}return n}function Ud(o,e){if(o.processedIds.length===0&&o.success)return"No accepted decisions were ready for model projection.";if(o.success&&o.proposalId)return"";let t=[];return o.success?t.push("Model suggestion ready."):t.push("Model projection failed."),o.proposalId&&t.push("Review the proposed model changes below."),e&&(e.outputStats?t.push(`${e.outputStats.ruleCount} rules, ${e.outputStats.tokenSectionCount} token sections, ${e.outputStats.componentCount} components proposed from ${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"}.`):t.push(`${e.decisionIds.length} decision${e.decisionIds.length===1?"":"s"} processed.`)),o.error&&(t.push(""),t.push(`Error: ${o.error}`),t.push("The selected decisions were not marked applied and remain visible in projection history.")),t.join(`
|
|
190
|
+
`)}function zd(o,e=96){let t=o.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}...`:t}function Xr(o){let e=o.styleModifications.flatMap(s=>{let c=s.element?.reactComponent||s.element?.tagName||s.selector;return s.changes.map(d=>`${c}: ${d.property} ${d.original||"unset"} -> ${d.modified||"unset"}`)}),t=(o.spacingTokenChanges??[]).map(s=>`${s.tokenName}: ${s.originalPx}px -> ${s.newPx}px`),n=(o.textModifications??[]).map(s=>`${s.element?.reactComponent||s.element?.tagName||s.selector}: text ${s.original||"empty"} -> ${s.modified||"empty"}`),i=o.annotations.map(s=>{let c=s.instruction?.trim();if(c)return c;if(s.imageCount&&s.imageCount>0)return`${s.imageCount} image${s.imageCount===1?"":"s"}`;let d=s.elements?.[0]?.reactComponent||s.elements?.[0]?.selector||s.linkedSelector||s.type;return`${s.type==="annotation"?"Annotation":`${s.type} annotation`} on ${d}`}),r=[...e,...n,...t,...i].map(s=>zd(s)).filter(Boolean);return r.length===0?"Annotation":r.length<=3?r.join("; "):`${r.slice(0,3).join("; ")}; +${r.length-3} more`}function Gd(o,e){let t=o.headers.origin;es(t)&&(e.setHeader("Access-Control-Allow-Origin",t),e.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, X-Popmelt-Project-Id"))}function _(o,e,t){o.writeHead(e,{"Content-Type":"application/json"}),o.end(JSON.stringify(t))}async function De(o){let e=[],t=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(t+=r.length,t>16384)throw new Error("Request body too large");e.push(r)}if(e.length===0)return{};let n=JSON.parse(Buffer.concat(e).toString("utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object");return n}async function Wd(o,e){let t=[],n=0;for await(let i of o){let r=typeof i=="string"?Buffer.from(i):i;if(n+=r.length,n>e)throw new Error("Request body too large");t.push(r)}return Buffer.concat(t)}function Hd(o,e){let t=o.headers["x-popmelt-project-id"];return(Array.isArray(t)?t[0]:t)||e.searchParams.get("projectId")||null}function Vd(o,e){if(!o)return e;let t=o.match(/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(!t)return e;let[,n,i,r]=t;return`\x1B[38;2;${parseInt(n,16)};${parseInt(i,16)};${parseInt(r,16)}m${e}\x1B[0m`}function lo(o,e){try{o.res.write(`event: ${e.type}
|
|
179
191
|
data: ${JSON.stringify(e)}
|
|
180
192
|
|
|
181
|
-
`)}catch{}}function
|
|
182
|
-
|
|
183
|
-
${a.error}`;await G.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:g})||await G.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),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),Ge()}}catch(R){if(a.status==="cancelled")return;if(a.status="error",a.error=R instanceof Error?R.message:String(R),a.threadId){let I=`Model projection failed.
|
|
193
|
+
`)}catch{}}function Wt(o){return o==="claude"||o==="codex"||o==="copilot"?o:void 0}async function Kd(o){try{let e=new AbortController,t=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${o}/status`,{signal:e.signal});return clearTimeout(t),n.ok?await n.json():null}catch{return null}}function Qd(o,e){return new Promise((t,n)=>{let i=s=>{o.removeListener("listening",r),n(s)},r=()=>{o.removeListener("error",i),t()};o.once("error",i),o.once("listening",r),o.listen(e,"127.0.0.1")})}async function si(o={}){let e=new Date().toISOString(),t=o.port??Cd,n=o.projectRoot??process.cwd(),i=await Td(n).catch(()=>n),r=Ur(i),s=o.devOrigin??(process.env.PORT?`http://localhost:${process.env.PORT}`:null),c=o.tempDir??Ne(Ad(),"popmelt-bridge"),d=o.maxTurns??40,u=o.maxBudgetUsd??1,I=[...o.allowedTools??Od],T=o.claudePath??"claude",k=o.copilotPath??"copilot",P=o.provider??"claude",x=o.timeoutMs,p=o.nativeCaptureUrl??process.env.POPMELT_CDP_URL??null,l=o.restartMode??"embedded",f=t,m={},h={claude:T,codex:"codex",copilot:k};for(let[a,y]of Object.entries(h))try{let M=y.includes("/")?y:xd("which",[y],{encoding:"utf-8"}).trim();m[a]={available:!0,path:M}}catch{m[a]={available:!1,path:null}}function j(a,y){return new Promise(M=>{let v=Wr(y,["--version"],{stdio:["ignore","ignore","ignore"]}),A=!1,S=C=>{A||(A=!0,M(C))},$=setTimeout(()=>{v.kill("SIGTERM"),S(!0)},5e3);v.on("error",()=>{clearTimeout($),S(!1)}),v.on("close",C=>{clearTimeout($),S(C===0)})})}await Promise.all([(async()=>{m.claude&&(m.claude.models=m.claude.available&&m.claude.path?await Sr(m.claude.path).catch(()=>Vn):Vn)})(),(async()=>{m.codex&&(m.codex.models=m.codex.available&&m.codex.path?await xr(m.codex.path).catch(()=>pn):pn)})(),(async()=>{m.copilot&&(m.copilot.models=m.copilot.available&&m.copilot.path?await br(m.copilot.path).catch(()=>[un]):[un])})()]);let[b,g,B]=await Promise.all([Ao(i),Mo(i),Eo(i,m.copilot?.path??k)]);m.claude&&(m.claude.mcp=b),m.codex&&(m.codex.mcp=g),m.copilot&&(m.copilot.mcp=B),b.found&&b.name&&I.push(`mcp__${b.name}__*`),await Sd(c,{recursive:!0}),Yr(c).catch(()=>{});let E=new Qn(1),R=new _n,N=new Cn(Vr),V=null,K=0,W=!1,Q=()=>{K+=1,W=!1,V&&clearTimeout(V),V=null},w=()=>{try{process.kill(process.pid,"SIGTERM")}catch{process.exit(0)}},H=()=>{if(l!=="detached"||N.size>0||W)return;W=!0;let a=++K,y=Date.now()+Bd,M=()=>{if(a!==K)return;if(N.size>0){Q();return}if(!(E.isRunning||E.depth>0||R.isRunning||R.depth>0)||Date.now()>=y){W=!1,V=setTimeout(w,50),V.unref?.();return}V=setTimeout(M,250),V.unref?.()};M()},L=new Set,O=new ro(i),he=await O.recoverInterruptedTurns();he>0&&console.warn(`[Popmelt] Recovered ${he} interrupted thread turn(s) from durable history.`);let J=new jn(i);J.sweep();let D=new Gn(i),Y=new mn(i,r);try{let a=await Y.store.migrateTopology();a.migrated&&console.log(`[Popmelt] Imprint topology migrated to v2 (${a.relationMutations} relation mutation(s)).`)}catch(a){console.warn(`[Popmelt] Imprint topology migration deferred: ${a instanceof Error?a.message:String(a)}`)}let ce=new so(i),Re=new kn(i),se=new En(i,{claudePath:T,provider:P,timeoutMs:x,loadProjectableDecisions:a=>D.getProjectableDecisions(a),onEvent:a=>{for(let y of L)lo(y,a)}});D.beginAutomaticInitialization({writerVersion:yn}).then(async a=>{a.state==="ready"?(await D.migrateImprintSnapshot(),await D.syncImprintGraph(),await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),P!=="copilot"&&(await se.getUnprojectedPatternDecisions()).length>0&&await ht({provider:P,reason:"Project accepted decisions that were waiting when the bridge restarted"})):a.state==="degraded"&&console.warn(`[\u22B9 ${f}] Product memory is degraded; legacy preview remains available: ${a.error}`)});let ze=20,He=300*1e3,je=[];function st(){let a=Date.now()-He;for(;je.length>0&&(je[0].completedAt<a||je.length>ze);)je.shift()}let Ve=new Map,at=null,Vt;E.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&lo(v,a)}),R.addListener((a,y,M)=>{for(let v of L)(!M||!v.sourceId||v.sourceId===M)&&lo(v,a)}),R.setProcessor(async a=>{let y=a.provider??P;try{let M=await se.run({provider:y,model:a.model,threadId:a.threadId,presentationJobId:a.id,agentSettings:a.agentSettings});if(a.status==="cancelled")return;let v=await se.loadRuns(),A=M.runId?v.runs.find($=>$.id===M.runId):void 0;if(M.success&&M.proposalId){let $=await se.findModelProposal(M.proposalId),C=await se.loadModel(),q=$?Ai($,C):null;if($&&q){let G=$.decisionIds.map(U=>({decisionId:U,status:"projected"}));await D.applyModelProjection({runId:$.runId??$.id,presentationJobId:$.presentationJobId,decisionIds:$.decisionIds,changes:q.map(U=>({path:U.path,value:U.value,decisionIds:U.decisionIds})),coverage:G}),await se.applySelectedModelProposal($.id,q.map(U=>({path:U.path,value:U.value})),q.map(U=>({group:U.path[0]==="rules"||U.path[0]==="components"||U.path[0]==="tokens"?U.path[0]:"model",label:U.label??U.id,detail:U.rationale,path:U.path,value:U.value})),"automatic")}}let S=Ud(M,A);if(a.threadId&&(await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:S,model:a.model,provider:y})),M.success)a.status="done",a.result=S,R.broadcast({type:"done",jobId:a.id,success:!0,responseText:S,threadId:a.threadId},a.id,a.sourceId),je.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st();else{if(a.status="error",a.error=M.error??"Projection failed",a.threadId){let $=`Model projection failed.
|
|
184
194
|
|
|
185
|
-
${a.error}`;await
|
|
195
|
+
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:$,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st()}}catch(M){if(a.status==="cancelled")return;if(a.status="error",a.error=M instanceof Error?M.message:String(M),a.threadId){let v=`Model projection failed.
|
|
186
196
|
|
|
187
|
-
|
|
188
|
-
Attached image: use the Read tool to view the image at: ${ee}`}a.kind==="synthesize"?U+=`
|
|
197
|
+
${a.error}`;await O.updateMessage(a.threadId,a.id,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})||await O.appendMessage(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:v,error:a.error,model:a.model,provider:y})}R.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:a.error,provider:y,model:a.model},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:a.error,threadId:a.threadId,annotationIds:a.annotationIds,color:"#000000",kind:"project_model"}),st()}}),E.setProcessor(async a=>{let y=a,M=y._replyPrompt,v=y._replyText,A=y._replyImagePaths,S=a.provider??P,$=!!(a.surfacedProposalIds?.length&&M),C=!$&&!["synthesize","project_model"].includes(a.kind??"");a.threadId&&v!==void 0&&await O.updateMessage(a.threadId,a.id,{queued:!1});let q;if(a.threadId){let oe=await O.getThread(a.threadId);if(oe){for(let ue=oe.messages.length-1;ue>=0;ue--)if(oe.messages[ue].sessionId){q=oe.messages[ue].sessionId;break}}}$&&(q=void 0);let G;if(q&&M){if(G=v??M,A&&A.length>0){G+=`
|
|
189
198
|
|
|
190
|
-
|
|
199
|
+
The developer attached reference images with their reply:`;for(let oe of A)G+=`
|
|
200
|
+
Attached image: use the Read tool to view the image at: ${oe}`}a.kind==="synthesize"?G+=`
|
|
191
201
|
|
|
192
|
-
|
|
202
|
+
Continue the project workflow from the previous instructions. If the developer approved the proposals, emit the final structured block requested earlier.`:G+="\n\nAfter completing work, output one <resolution> envelope with an `annotations` array containing declaredScope and inferredScope. If the developer corrected scope, set finalScope. If unclear, output a <question> block."}else if(q)G=dn(a.feedback,a.imagePaths,a.attachmentFiles)+`
|
|
193
203
|
|
|
194
204
|
Follow the developer's instructions. If they ask for changes, apply them to the source files.
|
|
195
205
|
|
|
196
|
-
After completing work, output
|
|
206
|
+
After completing work, output one <resolution> envelope with an \`annotations\` array containing declaredScope and inferredScope. If unclear, output a <question> block.`+(S!=="codex"?`
|
|
197
207
|
|
|
198
|
-
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let
|
|
208
|
+
IMPORTANT: First, use the Read tool to view the updated screenshot at: ${a.screenshotPath}`:"");else{let oe=!M&&a.threadId?await O.getThreadHistory(a.threadId):void 0,ue=M?null:await se.loadModel();G=M??hr(a.screenshotPath,a.feedback,{threadHistory:oe&&oe.length>0?oe:void 0,provider:S,imagePaths:a.imagePaths,attachmentFiles:a.attachmentFiles,designModel:ue??void 0,screenshotPaths:a.screenshotPaths})}G+=cr(a.memoryReview),C&&(G+=ei(a.imprintContext,{requestText:v??qt(a.feedback)})),G+=`
|
|
199
209
|
|
|
200
|
-
${Fr}`;let J=cd(a.color,`[\u22B9 ${w}:${a.id}]`),de=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 ${de} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${N?` (resuming: ${N.slice(0,8)})`:""}`);let F=new Jn(a.id),ue=(ee,le)=>{if(ee.type==="delta"&&"text"in ee){let Be=F.push(ee.text);Be.visibleText&&(C.accumulateText(le,"response",Be.visibleText),C.broadcast({...ee,text:Be.visibleText},le,a.sourceId));for(let He of Be.orientations)C.broadcast({type:"orientation",jobId:le,orientation:He},le,a.sourceId);return}else ee.type==="thinking"&&"text"in ee&&C.accumulateText(le,"thinking",ee.text);C.broadcast(ee,le,a.sourceId)},{process:ce,result:ne}=S==="codex"?fn(a.id,{prompt:U,projectRoot:r,screenshotPath:a.screenshotPath,resumeSessionId:N,model:a.model,sandboxMode:$?"read-only":void 0,configOverrides:pn(a.agentSettings),onEvent:ue}):S==="copilot"?er(a.id,{prompt:U,projectRoot:r,resumeSessionId:N,model:a.model,timeoutMs:h,copilotPath:m.copilot?.path??T,onEvent:ue}):un(a.id,{prompt:U,projectRoot:r,maxTurns:d,maxBudgetUsd:p,allowedTools:$?["Read"]:x,claudePath:j,resumeSessionId:N,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:h,onEvent:ue});C.setActiveProcess(a.id,ce);let X=await ne,ke=[...(X.fileEdits??[]).map(ee=>ee.file_path),...(X.editEvents??[]).flatMap(ee=>ee.filePath?[ee.filePath]:[])],be=F.finalize(X.text),ge=be.visibleText,xe=D?Do(ge):{visibleText:ge,draft:void 0,error:void 0},Q=xe.visibleText;for(let ee of be.orientations)C.broadcast({type:"orientation",jobId:a.id,orientation:ee},a.id,a.sourceId);if(a.result=Q,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(ie=>`${ie.tool} ${ie.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${J} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(ie=>`${ie.operation} ${ie.filePath}`).join(", ")}`),a.status="done";let ee=qr(ge),le=Gr(ge);if(le.length>0&&a.annotationIds&&a.annotationIds.length>0){let ie=new Set(a.annotationIds);le.every(pt=>ie.has(pt.annotationId))||(le=le.map((pt,ut)=>({...pt,annotationId:a.annotationIds[ut%a.annotationIds.length]})))}let Be=X.fileEdits&&X.fileEdits.length>0?X.fileEdits.map(ie=>`${ie.tool} ${ie.file_path.split("/").pop()}`):X.toolsUsed,He=C.getBufferedEvents(a.id),Le=He?nd(He.events,r):void 0,Ae,Fe=Br(ge),Te=Jr(ge);if(Te)if(!(a.memoryReview?.packets.some(pe=>pe.proposalId===Te.proposalId)||a.surfacedProposalIds?.includes(Te.proposalId)))Ae={status:"rejected",action:Te.action,proposalId:Te.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{Ae=await A.commitConversationalReview(Te)}catch(pe){Ae={status:"rejected",action:Te.action,proposalId:Te.proposalId,message:pe instanceof Error?pe.message:String(pe)}}let V=Wr(ge,ke.length),se,Ue=a.imprintContext?.pendingGroundingExplanationIds??[];if(xe.draft?.decision==="none"&&q.recordNoop(xe.draft.reason),a.threadId&&xe.draft?.decision==="mutate"&&!Te&&!Fe)try{se=await q.capture(xe.draft,{threadId:a.threadId,jobId:a.id,concreteModel:await te.loadModel(),pendingGroundingExplanationIds:Ue}),se&&await A.recordImprintEvidence({summary:se,threadId:a.threadId,jobId:a.id}).catch(ie=>console.warn(`${J} Canonical Imprint evidence linkage failed:`,ie))}catch(ie){console.warn(`${J} Continuous imprint update failed; the thread result remains available:`,ie instanceof Error?ie.message:String(ie))}else xe.error&&console.warn(`${J} Ignored invalid imprint block: ${xe.error}`);let K=se?.transactionId;if(a.threadId&&se&&!se.grounding){let ie=await G.getThread(a.threadId),pe=new Set(se.changes.map(ut=>ut.explanationId)),pt=ie?td(ie.messages,pe):void 0;if(pt?.imprintSummary){let ut=pt.imprintSummary;await G.updateAssistantMessage(a.threadId,pt.jobId,{imprintSummary:{...ut,detail:se.detail,changes:se.changes,additionalObservationCount:(ut.additionalObservationCount??0)+1,coalescedTransactionIds:[...ut.coalescedTransactionIds??[],se.transactionId]}}),se=void 0}}let fe=ci({question:ee,resolutions:le,changedFiles:ke,decisionRequired:!!Fe,imprintTransactionId:K,groundingRequired:!!se?.grounding}),ye=Le?.flatMap(ie=>ie.kind==="orientation"?[ie.orientation]:[])??[];if(a.threadId){let ie=$?Fe?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Q;await G.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:ie,resolutions:!$&&le.length>0?le:void 0,question:$?void 0:ee??void 0,sessionId:X.sessionId,toolsUsed:$?void 0:Be,editEvents:!$&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!$&&Le&&Le.length>0?Le:void 0,turn:{phase:"complete",orientation:ye,result:fe},result:fe,memoryReviewCard:Fe??void 0,memoryReceipt:Ae,imprintSummary:se,modelDetails:V.length>0?V:void 0,model:a.model,provider:S})}if(a.threadId&&!Te&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let ie=a.feedback.annotations.flatMap(pe=>pe.linkedSelector?[pe.pathname?`${pe.pathname}:${pe.linkedSelector}`:pe.linkedSelector]:[]);try{await A.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:I??(Nn(a.feedback)||"[request unavailable]"),responseSummary:ee??Q,outcome:ee?"question_asked":le.some(pe=>pe.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:ie,filePaths:[...(X.fileEdits??[]).map(pe=>pe.file_path),...(X.editEvents??[]).flatMap(pe=>pe.filePath?[pe.filePath]:[])].map(pe=>bi(pe)?Gc(r,pe):pe),resolutions:le.map(pe=>({status:pe.status,summary:pe.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(pe=>pe.id)})}catch(pe){console.warn(`${J} Canonical memory capture failed; iteration remains available in legacy history:`,pe instanceof Error?pe.message:String(pe))}}Ae?.status==="committed"&&Ae.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 ${Ae.decisionId}`}),ee&&(console.log(`${J} \u{1F4AC} Question detected: "${ee.slice(0,120)}" \u2192 broadcasting to ${H.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:ee,annotationIds:a.annotationIds},a.id,a.sourceId)),V.length>0&&(console.log(`${J} Applied model gap(s): ${V.map(ie=>`${ie.category}/${ie.element}`).join(", ")}`),C.broadcast({type:"novel_patterns",jobId:a.id,patterns:V,threadId:a.threadId},a.id,a.sourceId)),C.broadcast({type:"done",jobId:a.id,success:!0,resolutions:le.length>0?le:void 0,responseText:Q,threadId:a.threadId,annotationIds:a.annotationIds,result:fe},a.id,a.sourceId),Pe.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 G.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),Pe.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});Ge()});let It=Uc(async(a,g)=>{if(id(a,g),a.method==="OPTIONS"){g.writeHead(204),g.end();return}let R=a.url||"/",I=R.split("?")[0],k=new URL(R,`http://127.0.0.1:${w}`),S=k.pathname,$=ad(a,k);if($&&$!==i){_(g,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:i,requestProjectId:$,projectName:Yn(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:Yn(r)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let D=k.searchParams.get("annotationId")?.trim()??"",N=k.searchParams.get("name")?.trim()??"",U=k.searchParams.get("kind"),J=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!D||D.length>128||!/^[a-z0-9_-]+$/i.test(D)){_(g,400,{error:"A valid annotationId is required."});return}if(U!=="svg"&&U!=="text"||U==="svg"&&J!=="image/svg+xml"||U==="text"&&J!=="text/plain"){_(g,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let de=await sd(a,ed);if(de.length===0){_(g,400,{error:"Attachment is empty."});return}let F=await Ie.stage({annotationId:D,name:N,mimeType:J,kind:U,data:de});_(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 D=await Ce(a),N=Array.isArray(D.ids)?D.ids.filter(U=>typeof U=="string").slice(0,100):[];await Ie.claim(N),_(g,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await Ie.release([S.slice(19)]),_(g,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await we(a,g);else if(a.method==="POST"&&S==="/capture/native"){if(!l){_(g,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let D=await Ce(a),N=typeof D.pageUrl=="string"?D.pageUrl:"",U=D.clip&&typeof D.clip=="object"&&!Array.isArray(D.clip)?D.clip:null;if(!N||!U){_(g,400,{error:"pageUrl and clip are required."});return}let J=await wr(l,{pageUrl:N,clip:{x:Number(U.x),y:Number(U.y),width:Number(U.width),height:Number(U.height)},scale:typeof D.scale=="number"?D.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 tt(a,g,$);else if(a.method==="GET"&&S==="/ui-preferences")await st(g);else if(a.method==="PATCH"&&S==="/ui-preferences")await dt(a,g);else if(a.method==="PATCH"&&S==="/config")await it(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 D=await Ce(a),N=typeof D.leaseId=="string"?D.leaseId.trim():"",U=typeof D.ownerPid=="number"&&Number.isInteger(D.ownerPid)&&D.ownerPid>0?D.ownerPid:void 0;if(!N||N.length>128){_(g,400,{error:"A valid leaseId is required."});return}W();let J=M.acquire(N,U);_(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 D="";try{D=decodeURIComponent(S.slice(8))}catch{_(g,400,{error:"Invalid lease id."});return}if(!D){_(g,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let N=M.heartbeat(D);if(!N){_(g,404,{error:"Lease not found."});return}_(g,200,{ok:!0,lease:N})}else{let N=M.release(D);_(g,N.found?200:404,{ok:N.found}),N.becameEmpty&&me()}}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 D of H)try{D.res.end()}catch{}It.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 eo(a,g,S);else if(S.startsWith("/memory/"))await dn(a,g,S);else if(a.method==="POST"&&S==="/mcp/install")await lt(a,g);else if(a.method==="POST"&&S==="/reply")await rt(a,g);else if(a.method==="POST"&&S==="/cancel")to(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 D=await te.loadRuns();_(g,200,D)}else if(a.method==="GET"&&S==="/projection/proposals"){let D=await te.loadModelProposals();_(g,200,D)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let D=S.slice(22,-15);await Ne(D,a,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let D=S.slice(22,-6);await Lt(D,g)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let D=S.slice(22,-8);await Je(D,a,g)}else if(S.startsWith("/model/proposals/"))_(g,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await no(a,g);else if(a.method==="DELETE"&&S==="/model/component")await ln(a,g);else if(a.method==="PATCH"&&S==="/model/token")await Si(a,g);else if(a.method==="DELETE"&&S==="/model/token")await Pi(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 D=await te.loadModel();_(g,200,{model:D})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let D=S.slice(6,S.length-7),N=parseInt(k.searchParams.get("afterSeq")??"-1",10),U=C.getBufferedEvents(D,isNaN(N)?-1:N);U?_(g,200,U):_(g,404,{error:"Unknown job"})}else if(a.method==="GET"&&I.startsWith("/files/"))await ji(I.slice(7),g);else if(a.method==="GET"&&S==="/threads/recent"){let D=Math.min(Math.max(parseInt(k.searchParams.get("limit")??"5",10)||5,1),20),N=await G.listRecent(D);_(g,200,N)}else if(a.method==="GET"&&S.startsWith("/decision/")){let D=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(D))_(g,400,{error:"Invalid decision id"});else{let N=await G.getThread(D),U=[...N?.messages??[]].reverse().find(J=>J.annotationSnapshot);if(N&&U?.annotationSnapshot){let J=[...N.messages].reverse().find(de=>de.resolutions?.length);_(g,200,{decision:{id:N.id,createdAt:U.timestamp,url:U.annotationSnapshot.url,viewport:U.annotationSnapshot.viewport,color:U.annotationSnapshot.color,annotations:U.annotationSnapshot.annotations,resolutions:J?.resolutions??[]},authority:"thread_snapshot"})}else{let J=await ae.loadDecision(D);J?_(g,200,{decision:J,authority:"legacy_archive"}):_(g,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let D=S.slice(8);await Mi(D,g)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let D=S.slice(8);await Ai(D,g)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?ki(a,g):a.method==="GET"&&S==="/canvas/manifest"?await Ri(g):a.method==="GET"&&S==="/canvas/app.mjs"?await Ti(g):_(g,404,{error:"Not found"})}catch(D){console.error("[Bridge] Request error:",D),_(g,500,{error:D instanceof Error?D.message:"Internal error"})}});async function dn(a,g,R){try{if(a.method==="GET"&&R==="/memory/status"){_(g,200,await A.status());return}if(a.method==="GET"&&R==="/memory/diagnostics"){_(g,200,await A.diagnostics());return}if(a.method==="GET"&&R==="/memory/model-view"){_(g,200,await A.getModelView());return}if(a.method==="GET"&&R==="/memory/imprint-view"){let I=await G.load(),k=[...new Set(Object.values(I.threads).flatMap(S=>cn(S.messages)))];_(g,200,await A.getImprintView(k));return}if(a.method==="POST"&&R==="/memory/constraints"){let I=await Ce(a),k=typeof I.reactComponent=="string"?I.reactComponent.trim():"",S=await A.getModelView(),$=k?S.entries.filter(D=>D.key===`components.${k}`||D.key.startsWith(`components.${k}.`)):[];_(g,200,{modelEntries:$});return}if(a.method==="POST"&&R==="/memory/conversation-action"){let I=await Ce(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 D=await G.getThread(k),N=D?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!D||!N){_(g,409,{error:"This decision review card is not available in the thread."});return}let U=await te.findModelProposalsByThread(k),J=(await Promise.all(U.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(ke=>A.findPendingProposalForLegacyDecision(ke)))).some(ke=>ke?.proposalId===S)})))).find(X=>X.matches)?.proposal,de={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(de.action==="edit_and_accept"&&!de.claim){_(g,400,{error:"Edited decision wording is required."});return}let F=await A.commitConversationalReview(de),ue=`memory-${Ot().slice(0,8)}`,ce=$==="accept"?"> Accepted decision":$==="edit_and_accept"?"> Edited and accepted decision":$==="reject"?"> Rejected decision":"> Deferred decision";await G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:ue,replyToQuestion:ce}),await G.appendMessage(k,{role:"assistant",timestamp:Date.now(),jobId:ue,responseText:"",memoryReceipt:F,provider:Nt(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=Nt(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:xt(I),threadId:k,reason:`Project accepted decision ${F.decisionId}`}),_(g,F.status==="committed"?200:409,{receipt:F});return}if(a.method==="POST"&&R==="/memory/analyze"){let I=await Ce(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(D=>D.code===$).length]));_(g,200,{...k,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&R==="/memory/review"){let I=await Ce(a),k=await A.review(Mo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&R==="/memory/context"){let I=await Ce(a),k=await A.contextualize(Mo(I.query),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,200,k);return}if(a.method==="POST"&&R==="/memory/initialize"){let I=await Ce(a),k=await A.initializeFromLegacy({confirmed:I.confirm===!0,projectKey:typeof I.projectKey=="string"?I.projectKey:void 0,writerVersion:an});_(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"&&R==="/memory/plan"){let I=await Ce(a),k=await A.planReview(jo(I.command),{projectKey:typeof I.projectKey=="string"?I.projectKey:void 0});_(g,k.result.ok?200:422,k);return}if(a.method==="POST"&&R==="/memory/commit"){let I=await Ce(a),k=I.transaction&&typeof I.transaction=="object"&&!Array.isArray(I.transaction)?I.transaction:{},S=await A.commitReview(jo(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"&&R==="/memory/recover"){let I=await Ce(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 eo(a,g,R){if(a.method==="GET"&&R==="/imprint/status"){let[I,k]=await Promise.all([q.store.load(),G.load()]),S=[...new Set(Object.values(k.threads).flatMap($=>cn($.messages)))].filter($=>I.graph.explanations.some(D=>D.id===$&&D.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:q.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&R==="/imprint/action"){let I=await Ce(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 G.getThread(k),U=[...N?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),J=U?.imprintSummary;if(!N||!U||!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 de=`imprint-${Ot().slice(0,8)}`;await q.applyGroundingAction({summary:J,action:$,value:typeof I.value=="string"?I.value:void 0,threadId:k,jobId:de}),await A.recordImprintEvidence({summary:J,action:$,threadId:k,jobId:de}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let F=Ct(U.result,!!U.question),ue=U.turn?{...U.turn,result:Ct(U.turn.result,!!U.question)}:void 0;await G.updateAssistantMessage(k,U.jobId,{imprintSummary:{...J,resolvedAction:$},...F?{result:F}:{},...ue?{turn:ue}:{}});let ce={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 G.appendMessage(k,{role:"human",timestamp:Date.now(),jobId:de,replyToQuestion:ce[$]}),_(g,200,{ok:!0,action:$});return}_(g,404,{error:"Imprint endpoint not found."})}async function we(a,g){let{screenshot:R,feedback:I,color:k,provider:S,model:$,reasoningEffort:D,serviceTier:N,sourceId:U,pastedImages:J,pageScreenshots:de}=await Ao(a),F;try{F=JSON.parse(I)}catch{_(g,400,{error:"Invalid feedback JSON"});return}let ue=F.annotations.flatMap(V=>(V.attachments??[]).map(se=>({id:se.id,annotationId:V.id}))),ce;try{ce=ue.length>0?await Ie.promote(ue):void 0}catch(V){_(g,409,{error:V instanceof Error?V.message:"Draft attachment unavailable."});return}let ne=Ot().slice(0,8),X={};if(de.length>0)for(let V of de){let se=encodeURIComponent(V.pathname),Ue=$e(c,`screenshot-${ne}-${se}.webp`);await Xn(Ue,V.data),X[V.pathname]=Ue}let ke=$e(c,`screenshot-${ne}.webp`);await Xn(ke,R);let be={};if(J.length>0)for(let V of J){let se=$e(c,`pasted-${ne}-${V.annotationId}-${V.index}.webp`);await Xn(se,V.data),be[V.annotationId]||(be[V.annotationId]=[]),be[V.annotationId].push(se)}let ge=F.annotations.map(V=>V.linkedSelector?V.pathname?`${V.pathname}:${V.linkedSelector}`:V.linkedSelector:null).filter(V=>!!V),xe;if(ge.length>0){let V=await G.findContinuationThread(ge);V?(xe=V.id,await G.addElementIdentifiers(xe,ge)):xe=(await G.createThread(ne,ge)).id}else xe=(await G.createThread(ne,[])).id;let Q=F.annotations.map(V=>V.id),ee=Object.keys(X).length>0,le=await Or(A,F,ge,V=>console.warn(`[\u22B9 ${w}:${ne}] Contextual memory unavailable; continuing without it:`,V instanceof Error?V.message:String(V))),Be=await q.contextualize({text:Nn(F),subjectHints:[...ge,...F.annotations.flatMap(V=>[V.pathname,V.elements?.[0]?.reactComponent].filter(se=>!!se))],pendingGroundingExplanationIds:cn((await G.getThread(xe))?.messages??[])}).catch(V=>{console.warn(`[\u22B9 ${w}:${ne}] Imprint context unavailable; continuing without it:`,V instanceof Error?V.message:String(V))}),He={id:ne,status:"queued",screenshotPath:ke,feedback:F,createdAt:Date.now(),color:k,threadId:xe,annotationIds:Q,provider:Nt(S),model:$||void 0,agentSettings:xt({reasoningEffort:D,serviceTier:N}),...Object.keys(be).length>0?{imagePaths:be}:{},...ce&&Object.keys(ce).length>0?{attachmentFiles:ce}:{},sourceId:U||void 0,...ee?{screenshotPaths:X}:{},...le?{memoryReview:le}:{},...Be?{imprintContext:Be}:{}},Le=new Set(F.annotations.map(V=>V.pathname).filter(Boolean)),Ae;if(Le.size>1){let V=new Map;for(let se of F.annotations){let Ue=se.pathname||"(unknown)";V.has(Ue)||V.set(Ue,[]),V.get(Ue).push(se.instruction||wi({...F,annotations:[se]}))}Ae=[...V.entries()].map(([se,Ue])=>`\`${se}\`
|
|
201
|
-
${
|
|
210
|
+
${fr}`;let U=Vd(a.color,`[\u22B9 ${f}:${a.id}]`),pe=a.screenshotPaths&&Object.keys(a.screenshotPaths).length>0?`${Object.keys(a.screenshotPaths).length} pages [${Object.keys(a.screenshotPaths).join(", ")}]`:a.screenshotPath;console.log(`${U} Reviewing ${pe} (provider: ${S})${a.threadId?` (thread: ${a.threadId})`:""}${q?` (resuming: ${q.slice(0,8)})`:""}`);let z=new Wn(a.id),me=(oe,ue)=>{if(oe.type==="delta"&&"text"in oe){let Ee=z.push(oe.text);Ee.visibleText&&(E.accumulateText(ue,"response",Ee.visibleText),E.broadcast({...oe,text:Ee.visibleText},ue,a.sourceId));for(let ut of Ee.orientations)E.broadcast({type:"orientation",jobId:ue,orientation:ut},ue,a.sourceId);return}else oe.type==="thinking"&&"text"in oe&&E.accumulateText(ue,"thinking",oe.text);E.broadcast(oe,ue,a.sourceId)},{process:le,result:ne}=S==="codex"?Sn(a.id,{prompt:G,projectRoot:i,screenshotPath:a.screenshotPath,resumeSessionId:q,model:a.model,sandboxMode:$?"read-only":void 0,configOverrides:wn(a.agentSettings),onEvent:me}):S==="copilot"?xi(a.id,{prompt:G,projectRoot:i,resumeSessionId:q,model:a.model,timeoutMs:x,copilotPath:m.copilot?.path??k,onEvent:me}):bn(a.id,{prompt:G,projectRoot:i,maxTurns:d,maxBudgetUsd:u,allowedTools:$?["Read"]:I,claudePath:T,resumeSessionId:q,model:a.model,reasoningEffort:a.agentSettings?.reasoningEffort,timeoutMs:x,onEvent:me});E.setActiveProcess(a.id,le);let X=await ne,Se=[...(X.fileEdits??[]).map(oe=>oe.file_path),...(X.editEvents??[]).flatMap(oe=>oe.filePath?[oe.filePath]:[])],be=Vo(X.text,a.id),Ae=z.finalize(X.text),ge=be.visibleText,Z=vr(ge),fe=C?Zo(ge,{context:a.imprintContext,requestText:v??qt(a.feedback),applicationOccurred:Se.length>0||Z.some(oe=>oe.status==="resolved")}):{visibleText:ge,draft:void 0,error:void 0},Le=fe.visibleText,Me=C?fe.error?{state:fe.error.includes("missing")?"missing":"invalid",reason:fe.error}:fe.draft?.decision==="none"?{state:"none",reason:fe.draft.reason}:fe.draft?.decision==="recognize"?{state:"none",reason:"recognized existing grounded understanding"}:{state:"invalid",reason:"imprint mutation was not committed"}:{state:"not_applicable"};for(let oe of Ae.orientations)E.broadcast({type:"orientation",jobId:a.id,orientation:oe},a.id,a.sourceId);if(a.result=Le,X.success){console.log(`${U} Iteration complete`),X.fileEdits&&X.fileEdits.length>0&&console.log(`${U} Captured ${X.fileEdits.length} file edit(s): ${X.fileEdits.map(re=>`${re.tool} ${re.file_path}`).join(", ")}`),X.editEvents&&X.editEvents.length>0&&console.log(`${U} Captured ${X.editEvents.length} edit event(s): ${X.editEvents.map(re=>`${re.operation} ${re.filePath}`).join(", ")}`),a.status="done";let oe=gr(ge),ue=Z;if(ue.length>0&&a.annotationIds&&a.annotationIds.length>0){let re=new Set(a.annotationIds);ue.every(yt=>re.has(yt.annotationId))||(ue=ue.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,ut=E.getBufferedEvents(a.id),$e=Fd(ut?.events??[],i,be.segments),qe,Fe=lr(ge),ke=dr(ge);if(ke)if(!(a.memoryReview?.packets.some(de=>de.proposalId===ke.proposalId)||a.surfacedProposalIds?.includes(ke.proposalId)))qe={status:"rejected",action:ke.action,proposalId:ke.proposalId,message:"The agent attempted to resolve a proposal that was not surfaced in this conversation."};else try{qe=await D.commitConversationalReview(ke)}catch(de){qe={status:"rejected",action:ke.action,proposalId:ke.proposalId,message:de instanceof Error?de.message:String(de)}}let ee=Ir(ge,Se.length),F,ae,ve=a.imprintContext?.pendingGroundingExplanationIds??[];fe.draft?.decision==="none"&&Y.recordNoop(fe.draft.reason);let Ue=fe.draft?.decision==="recognize"?fe.draft:void 0;if(Ue&&!ke&&!Fe){let re=a.imprintContext?.explanations.find(de=>de.id===Ue.explanationId&&de.state==="grounded");re?ae={explanationId:re.id,title:Ue.summary.title,detail:Ue.summary.detail,statement:re.statement}:Me={state:"invalid",reason:"recognized explanation is no longer available as grounded context"}}let ho=fe.draft?.decision==="mutate"||fe.draft?.decision==="apply"?fe.draft:void 0;if(a.threadId&&ho&&!ke&&!Fe)try{F=await Y.capture(ho,{threadId:a.threadId,jobId:a.id,concreteModel:await se.loadModel(),pendingGroundingExplanationIds:ve,applicationOccurred:Se.length>0||ue.some(re=>re.status==="resolved")}),F?(Me={state:"mutated"},await D.recordImprintEvidence({summary:F,threadId:a.threadId,jobId:a.id}).catch(re=>console.warn(`${U} Canonical Imprint evidence linkage failed:`,re))):Me={state:"invalid",reason:"imprint mutation failed admission or produced no durable change"}}catch(re){Me={state:"invalid",reason:re instanceof Error?re.message:String(re)},console.warn(`${U} Continuous imprint update failed; the thread result remains available:`,re instanceof Error?re.message:String(re))}else ho&&(Me={state:"invalid",reason:"imprint update was suppressed by a conflicting structured workflow"});fe.error&&console.warn(`${U} Ignored invalid imprint block: ${fe.error}`),(Me.state==="missing"||Me.state==="invalid")&&Y.recordAssessmentFailure(Me.state);let go=F?.transactionId;if(a.threadId&&F&&!F.grounding){let re=await O.getThread(a.threadId),de=new Set(F.changes.map(vt=>vt.explanationId)),yt=re?qd(re.messages,de):void 0;if(yt?.imprintSummary){let vt=yt.imprintSummary;await O.updateAssistantMessage(a.threadId,yt.jobId,{imprintSummary:{...vt,detail:F.detail,changes:F.changes,additionalObservationCount:(vt.additionalObservationCount??0)+1,coalescedTransactionIds:[...vt.coalescedTransactionIds??[],F.transactionId]}}),F=void 0}}let yo=ni({question:oe,resolutions:ue,changedFiles:Se,decisionRequired:!!Fe,imprintTransactionId:go,groundingRequired:!!F?.grounding}),ps=$e?.flatMap(re=>re.kind==="orientation"?[re.orientation]:[])??[],At=a.lifecycle?fn(a.lifecycle,go?[go]:[],Me):void 0;if(a.threadId){let re=$?Fe?"":"Decision review could not be prepared as a structured card. Please try Review decision again.":Le;await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,responseText:re,resolutions:!$&&ue.length>0?ue:void 0,question:$?void 0:oe??void 0,sessionId:X.sessionId,toolsUsed:$?void 0:Ee,editEvents:!$&&X.editEvents&&X.editEvents.length>0?X.editEvents:void 0,segments:!$&&$e&&$e.length>0?$e:void 0,turn:{phase:"complete",orientation:ps,result:yo},result:yo,memoryReviewCard:Fe??void 0,memoryReceipt:qe,imprintSummary:F,imprintRecognition:ae,modelDetails:ee.length>0?ee:void 0,model:a.model,provider:S,...At?{lifecycle:At}:{}})}if(a.threadId&&!ke&&!a.surfacedProposalIds?.length&&a.kind!=="project_model"){let re=a.feedback.annotations.flatMap(de=>de.linkedSelector?[de.pathname?`${de.pathname}:${de.linkedSelector}`:de.linkedSelector]:[]);try{await D.captureCompletedJob({jobId:a.id,threadId:a.threadId,createdAt:a.createdAt,completedAt:Date.now(),requestSummary:v??(qt(a.feedback)||"[request unavailable]"),responseSummary:oe??Le,outcome:oe?"question_asked":ue.some(de=>de.status==="resolved")?"completed":"no_change",execution:{provider:S,model:a.model,sessionId:X.sessionId},subjectHints:re,filePaths:[...(X.fileEdits??[]).map(de=>de.file_path),...(X.editEvents??[]).flatMap(de=>de.filePath?[de.filePath]:[])].map(de=>Zr(de)?Ed(i,de):de),resolutions:ue.map(de=>({status:de.status,summary:de.summary})),governingDecisionIds:a.memoryReview?.acceptedTruth?.decisions.map(de=>de.id),submissionIds:At?.submissionIds,outcomeId:At?.outcomeId,imprintEvidenceIds:At?.imprintEvidenceIds,imprintAssessment:At?.imprintAssessment})}catch(de){console.warn(`${U} Canonical memory capture failed; iteration remains available in legacy history:`,de instanceof Error?de.message:String(de))}}qe?.status==="committed"&&qe.decisionId&&S!=="copilot"&&await ht({provider:S,model:a.model,agentSettings:a.agentSettings,threadId:a.threadId,annotationIds:a.annotationIds,sourceId:a.sourceId,reason:`Project accepted decision ${qe.decisionId}`}),oe&&(console.log(`${U} \u{1F4AC} Question detected: "${oe.slice(0,120)}" \u2192 broadcasting to ${L.size} SSE clients (threadId=${a.threadId??a.id}, annotationIds=${a.annotationIds?.join(",")??"none"})`),E.broadcast({type:"question",jobId:a.id,threadId:a.threadId??a.id,question:oe,annotationIds:a.annotationIds},a.id,a.sourceId)),ee.length>0&&(console.log(`${U} Applied model gap(s): ${ee.map(re=>`${re.category}/${re.element}`).join(", ")}`),E.broadcast({type:"novel_patterns",jobId:a.id,patterns:ee,threadId:a.threadId},a.id,a.sourceId)),E.broadcast({type:"done",jobId:a.id,success:!0,resolutions:ue.length>0?ue:void 0,responseText:Le,threadId:a.threadId,annotationIds:a.annotationIds,result:yo},a.id,a.sourceId),je.push({id:a.id,status:"done",completedAt:Date.now(),threadId:a.threadId,annotationIds:a.annotationIds})}else console.error(`${U} Error: ${X.error}`),a.status="error",a.error=X.error,a.threadId&&await O.appendMessageBeforeQueuedReplies(a.threadId,{role:"assistant",timestamp:Date.now(),jobId:a.id,error:X.error||"Unknown error",model:a.model,provider:S,...a.lifecycle?{lifecycle:fn(a.lifecycle)}:{}}),E.broadcast({type:"error",jobId:a.id,threadId:a.threadId,message:X.error||"Unknown error",provider:S,model:a.model,recoverable:X.recoverableError,code:X.errorCode},a.id,a.sourceId),je.push({id:a.id,status:"error",completedAt:Date.now(),error:X.error,threadId:a.threadId,annotationIds:a.annotationIds});st()});let Pt=jd(async(a,y)=>{if(Gd(a,y),a.method==="OPTIONS"){y.writeHead(204),y.end();return}let M=a.url||"/",v=M.split("?")[0],A=new URL(M,`http://127.0.0.1:${f}`),S=A.pathname,$=Hd(a,A);if($&&$!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:$,projectName:co(i)});return}if(a.headers.origin){if(!es(a.headers.origin)){_(y,403,{error:"Popmelt bridge only accepts browser requests from localhost origins."});return}if($!==r){_(y,409,{error:"Popmelt bridge/project mismatch",bridgeProjectId:r,requestProjectId:$,projectName:co(i)});return}}try{if(a.method==="POST"&&S==="/draft-attachments"){let C=A.searchParams.get("annotationId")?.trim()??"",q=A.searchParams.get("name")?.trim()??"",G=A.searchParams.get("kind"),U=String(a.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(!C||C.length>128||!/^[a-z0-9_-]+$/i.test(C)){_(y,400,{error:"A valid annotationId is required."});return}if(G!=="svg"&&G!=="text"||G==="svg"&&U!=="image/svg+xml"||G==="text"&&U!=="text/plain"){_(y,415,{error:"Only SVG and plain-text draft attachments are supported."});return}let pe=await Wd(a,Ld);if(pe.length===0){_(y,400,{error:"Attachment is empty."});return}let z=await J.stage({annotationId:C,name:q,mimeType:U,kind:G,data:pe});_(y,201,{attachment:{id:z.id,name:z.name,mimeType:z.mimeType,size:z.size,kind:z.kind}})}else if(a.method==="POST"&&S==="/draft-attachments/claim"){let C=await De(a),q=Array.isArray(C.ids)?C.ids.filter(G=>typeof G=="string").slice(0,100):[];await J.claim(q),_(y,200,{ok:!0})}else if(a.method==="DELETE"&&S.startsWith("/draft-attachments/"))await J.release([S.slice(19)]),_(y,200,{ok:!0});else if(a.method==="POST"&&S==="/send")await ct(a,y);else if(a.method==="POST"&&S==="/capture/native"){if(!p){_(y,501,{error:"Native capture is not configured. Set POPMELT_CDP_URL to a Chromium DevTools endpoint."});return}let C=await De(a),q=typeof C.pageUrl=="string"?C.pageUrl:"",G=C.clip&&typeof C.clip=="object"&&!Array.isArray(C.clip)?C.clip:null;if(!q||!G){_(y,400,{error:"pageUrl and clip are required."});return}let U=await qi(p,{pageUrl:q,clip:{x:Number(G.x),y:Number(G.y),width:Number(G.width),height:Number(G.height)},scale:typeof C.scale=="number"?C.scale:1});y.writeHead(200,{"Content-Type":"image/webp","Content-Length":U.length,"Cache-Control":"no-store"}),y.end(U)}else if(a.method==="GET"&&S==="/events")tt(a,y);else if(a.method==="GET"&&S==="/status")await dt(a,y,$);else if(a.method==="GET"&&S==="/ui-preferences")await ft(y);else if(a.method==="PATCH"&&S==="/ui-preferences")await uo(a,y);else if(a.method==="PATCH"&&S==="/config")await lt(a,y);else if(a.method==="POST"&&S==="/leases"){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}try{let C=await De(a),q=typeof C.leaseId=="string"?C.leaseId.trim():"",G=typeof C.ownerPid=="number"&&Number.isInteger(C.ownerPid)&&C.ownerPid>0?C.ownerPid:void 0;if(!q||q.length>128){_(y,400,{error:"A valid leaseId is required."});return}Q();let U=N.acquire(q,G);_(y,201,{ok:!0,lease:U,ttlMs:Vr})}catch{_(y,400,{error:"Invalid lease request."})}}else if(S.startsWith("/leases/")&&(a.method==="PATCH"||a.method==="DELETE")){if(l!=="detached"){_(y,409,{error:"Bridge leases are only available for detached bridges."});return}let C="";try{C=decodeURIComponent(S.slice(8))}catch{_(y,400,{error:"Invalid lease id."});return}if(!C){_(y,400,{error:"A lease id is required."});return}if(a.method==="PATCH"){let q=N.heartbeat(C);if(!q){_(y,404,{error:"Lease not found."});return}_(y,200,{ok:!0,lease:q})}else{let q=N.release(C);_(y,q.found?200:404,{ok:q.found}),q.becameEmpty&&H()}}else if(a.method==="POST"&&S==="/shutdown"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0}),setTimeout(w,100)}else if(a.method==="POST"&&S==="/restart"){if(l!=="detached"){_(y,409,{ok:!1,error:"This Popmelt bridge is embedded in the host dev server. Restart the dev server to reload bridge code.",restartMode:l});return}_(y,200,{ok:!0,restarting:!0}),setTimeout(()=>{for(let C of L)try{C.res.end()}catch{}Pt.close(()=>{Wr(process.execPath,process.argv.slice(1),{detached:!0,stdio:"ignore",cwd:process.cwd(),env:process.env}).unref(),setTimeout(()=>process.exit(0),200)})},100)}else if(a.method==="GET"&&S==="/capabilities")_(y,200,{providers:m});else if(S.startsWith("/imprint/"))await xe(a,y,S);else if(S.startsWith("/memory/"))await po(a,y,S);else if(a.method==="POST"&&S==="/mcp/install")await fo(a,y);else if(a.method==="POST"&&S==="/reply")await _e(a,y);else if(a.method==="POST"&&S==="/cancel")mo(a,y);else if(a.method==="POST"&&S==="/materialize")_(y,410,{error:"Standalone materialization was removed. Accepted decisions project automatically."});else if(a.method==="GET"&&S==="/materialization-runs")_(y,410,{error:"Use /projection-runs."});else if(a.method==="GET"&&S==="/projection-runs"){let C=await se.loadRuns();_(y,200,C)}else if(a.method==="GET"&&S==="/projection/proposals"){let C=await se.loadModelProposals();_(y,200,C)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply-selected")){let C=S.slice(22,-15);await Be(C,a,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/apply")){let C=S.slice(22,-6);await Je(C,y)}else if(a.method==="POST"&&S.startsWith("/projection/proposals/")&&S.endsWith("/dismiss")){let C=S.slice(22,-8);await pt(C,a,y)}else if(S.startsWith("/model/proposals/"))_(y,410,{error:"Use /projection/proposals."});else if(a.method==="POST"&&S==="/model/component")await In(a,y);else if(a.method==="DELETE"&&S==="/model/component")await ts(a,y);else if(a.method==="PATCH"&&S==="/model/token")await ns(a,y);else if(a.method==="DELETE"&&S==="/model/token")await os(a,y);else if(a.method==="POST"&&S==="/model/consolidate")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="POST"&&S==="/model/synthesize")_(y,410,{error:"Standalone model synthesis was removed. Models are projected from accepted decisions."});else if(a.method==="GET"&&S==="/model"){let C=await se.loadModel();_(y,200,{model:C})}else if(a.method==="GET"&&S.startsWith("/jobs/")&&S.endsWith("/events")){let C=S.slice(6,S.length-7),q=parseInt(A.searchParams.get("afterSeq")??"-1",10),G=E.getBufferedEvents(C,isNaN(q)?-1:q);G?_(y,200,G):_(y,404,{error:"Unknown job"})}else if(a.method==="GET"&&v.startsWith("/files/"))await as(v.slice(7),y);else if(a.method==="GET"&&S==="/threads/recent"){let C=Math.min(Math.max(parseInt(A.searchParams.get("limit")??"5",10)||5,1),20),q=await O.listRecent(C);_(y,200,q)}else if(a.method==="GET"&&S.startsWith("/decision/")){let C=S.slice(10);if(!/^[a-zA-Z0-9_-]+$/.test(C))_(y,400,{error:"Invalid decision id"});else{let q=await O.getThread(C),G=[...q?.messages??[]].reverse().find(U=>U.annotationSnapshot);if(q&&G?.annotationSnapshot){let U=[...q.messages].reverse().find(pe=>pe.resolutions?.length);_(y,200,{decision:{id:q.id,createdAt:G.timestamp,url:G.annotationSnapshot.url,viewport:G.annotationSnapshot.viewport,color:G.annotationSnapshot.color,annotations:G.annotationSnapshot.annotations,resolutions:U?.resolutions??[]},authority:"thread_snapshot"})}else{let U=await Re.loadDecision(C);U?_(y,200,{decision:U,authority:"legacy_archive"}):_(y,404,{error:"Decision not found"})}}}else if(a.method==="GET"&&S.startsWith("/thread/")){let C=S.slice(8);await cs(C,y)}else if(a.method==="DELETE"&&S.startsWith("/thread/")){let C=S.slice(8);await ds(C,y)}else a.method==="GET"&&(S==="/canvas"||S==="/canvas/")?is(a,y):a.method==="GET"&&S==="/canvas/manifest"?await rs(y):a.method==="GET"&&S==="/canvas/app.mjs"?await ss(y):_(y,404,{error:"Not found"})}catch(C){console.error("[Bridge] Request error:",C),_(y,500,{error:C instanceof Error?C.message:"Internal error"})}});async function po(a,y,M){try{if(a.method==="GET"&&M==="/memory/status"){_(y,200,await D.status());return}if(a.method==="GET"&&M==="/memory/diagnostics"){_(y,200,await D.diagnostics());return}if(a.method==="GET"&&M==="/memory/model-view"){_(y,200,await D.getModelView());return}if(a.method==="GET"&&M==="/memory/imprint-view"){let v=await O.load(),A=[...new Set(Object.values(v.threads).flatMap(S=>vn(S.messages)))];_(y,200,await D.getImprintView(A,new Set(Object.keys(v.threads))));return}if(a.method==="POST"&&M==="/memory/constraints"){let v=await De(a),A=typeof v.reactComponent=="string"?v.reactComponent.trim():"",S=await D.getModelView(),$=A?S.entries.filter(C=>C.key===`components.${A}`||C.key.startsWith(`components.${A}.`)):[];_(y,200,{modelEntries:$});return}if(a.method==="POST"&&M==="/memory/conversation-action"){let v=await De(a),A=typeof v.threadId=="string"?v.threadId:"",S=typeof v.proposalId=="string"?v.proposalId:"",$=String(v.action);if(!A||!S||!["accept","edit_and_accept","reject","defer"].includes($)){_(y,400,{error:"A valid thread, proposal, and review action are required."});return}let C=await O.getThread(A),q=C?.messages.find(X=>X.memoryReviewCard?.proposalId===S)?.memoryReviewCard;if(!C||!q){_(y,409,{error:"This decision review card is not available in the thread."});return}let G=await se.findModelProposalsByThread(A),U=(await Promise.all(G.map(async X=>({proposal:X,matches:(await Promise.all(X.decisionIds.map(Se=>D.findPendingProposalForLegacyDecision(Se)))).some(Se=>Se?.proposalId===S)})))).find(X=>X.matches)?.proposal,pe={proposalId:S,action:$,kind:q.kind,claim:$==="edit_and_accept"&&typeof v.claim=="string"?v.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(pe.action==="edit_and_accept"&&!pe.claim){_(y,400,{error:"Edited decision wording is required."});return}let z=await D.commitConversationalReview(pe),me=`memory-${rt().slice(0,8)}`,le=$==="accept"?"> Accepted decision":$==="edit_and_accept"?"> Edited and accepted decision":$==="reject"?"> Rejected decision":"> Deferred decision";await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:me,replyToQuestion:le}),await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:me,responseText:"",memoryReceipt:z,provider:Wt(typeof v.provider=="string"?v.provider:void 0),model:typeof v.model=="string"?v.model:void 0}),z.status==="committed"&&U&&await se.dismissModelProposal(U.id);let ne=Wt(typeof v.provider=="string"?v.provider:void 0);z.status==="committed"&&z.decisionId&&ne!=="copilot"&&await ht({provider:ne,model:typeof v.model=="string"?v.model:void 0,agentSettings:Mt(v),threadId:A,reason:`Project accepted decision ${z.decisionId}`}),_(y,z.status==="committed"?200:409,{receipt:z});return}if(a.method==="POST"&&M==="/memory/analyze"){let v=await De(a),A=await D.analyzeLegacy({projectKey:typeof v.projectKey=="string"?v.projectKey:void 0}),S=Object.fromEntries([...new Set(A.issues.map($=>$.code))].map($=>[$,A.issues.filter(C=>C.code===$).length]));_(y,200,{...A,issues:void 0,issueCounts:S});return}if(a.method==="POST"&&M==="/memory/review"){let v=await De(a),A=await D.review(zo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/context"){let v=await De(a),A=await D.contextualize(zo(v.query),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,200,A);return}if(a.method==="POST"&&M==="/memory/initialize"){let v=await De(a),A=await D.initializeFromLegacy({confirmed:v.confirm===!0,projectKey:typeof v.projectKey=="string"?v.projectKey:void 0,writerVersion:yn});_(y,201,{status:A.status,report:{source:A.report.source,imported:A.report.imported,unresolvedAcceptance:A.report.unresolvedAcceptance,deferredModelEntries:A.report.deferredModelEntries,proofCases:A.report.proofCases,schemaIssues:A.report.schemaIssues}});return}if(a.method==="POST"&&M==="/memory/plan"){let v=await De(a),A=await D.planReview(Uo(v.command),{projectKey:typeof v.projectKey=="string"?v.projectKey:void 0});_(y,A.result.ok?200:422,A);return}if(a.method==="POST"&&M==="/memory/commit"){let v=await De(a),A=v.transaction&&typeof v.transaction=="object"&&!Array.isArray(v.transaction)?v.transaction:{},S=await D.commitReview(Uo(v.command),{transactionId:typeof A.transactionId=="string"?A.transactionId:"",committedAt:typeof A.committedAt=="string"?A.committedAt:""});_(y,200,{status:await D.status(),journal:S.report});return}if(a.method==="POST"&&M==="/memory/recover"){let v=await De(a),A=await D.recover(v.confirm===!0);_(y,200,{status:await D.status(),journal:A.report});return}_(y,404,{error:"Memory endpoint not found."})}catch(v){let A=v instanceof Error?v.message:String(v),S=/already initialized|not initialized|state conflict|locked by another writer|not pending/i.test(A),$=/required|invalid|unsupported|expected|must be|confirmation/i.test(A);if(S||$){_(y,S?409:400,{error:A});return}throw v}}async function xe(a,y,M){if(a.method==="GET"&&M==="/imprint/status"){let[v,A]=await Promise.all([Y.store.load(),O.load()]),S=[...new Set(Object.values(A.threads).flatMap($=>vn($.messages)))].filter($=>v.graph.explanations.some(C=>C.id===$&&C.state==="testing"));_(y,200,{state:"ready",head:v.graph.head,updatedAt:v.graph.updatedAt,explanationCount:v.graph.explanations.filter($=>$.state!=="retired").length,concreteCount:v.graph.concrete.length,relationCount:v.graph.relations.length,pendingGroundingCount:S.length,recoveredTransactions:v.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e});return}if(a.method==="POST"&&M==="/imprint/action"){let v=await De(a),A=typeof v.threadId=="string"?v.threadId:"",S=typeof v.transactionId=="string"?v.transactionId:"",$=String(v.action);if(!A||!S||!["yes","this_time","no"].includes($)){_(y,400,{error:"A valid thread, imprint update, and action are required."});return}let q=await O.getThread(A),G=[...q?.messages??[]].reverse().find(ne=>ne.role==="assistant"&&ne.imprintSummary?.transactionId===S),U=G?.imprintSummary;if(!q||!G||!U){_(y,409,{error:"This imprint summary is not available in the thread."});return}if(U.resolvedAction){_(y,409,{error:"This imprint summary has already been resolved."});return}let pe=`imprint-${rt().slice(0,8)}`;await Y.applyGroundingAction({summary:U,action:$,threadId:A,jobId:pe}),$!=="no"&&await D.recordImprintEvidence({summary:U,action:$,threadId:A,jobId:pe}).catch(ne=>console.warn("[Imprint] Canonical grounding evidence linkage failed:",ne));let z=Ut(G.result,!!G.question),me=G.turn?{...G.turn,result:Ut(G.turn.result,!!G.question)}:void 0;await O.updateAssistantMessage(A,G.jobId,{imprintSummary:{...U,resolvedAction:$},...z?{result:z}:{},...me?{turn:me}:{}});let le={yes:"> Yes",this_time:"> This time",no:"> No"};if(await O.appendMessage(A,{role:"human",timestamp:Date.now(),jobId:pe,replyToQuestion:le[$]}),$==="no"){let ne="What should be different\u2014the result itself, where this understanding should apply, or the reasoning behind it?",X=ni({question:ne});await O.appendMessage(A,{role:"assistant",timestamp:Date.now(),jobId:pe,responseText:"I want to understand the mismatch before changing either the result or your Imprint.",question:ne,turn:{phase:"complete",orientation:[],result:X},result:X})}_(y,200,{ok:!0,action:$});return}_(y,404,{error:"Imprint endpoint not found."})}async function ct(a,y){let{screenshot:M,feedback:v,color:A,provider:S,model:$,reasoningEffort:C,serviceTier:q,sourceId:G,pastedImages:U,pageScreenshots:pe}=await Go(a),z;try{z=JSON.parse(v)}catch{_(y,400,{error:"Invalid feedback JSON"});return}let me=z.annotations.flatMap(ee=>(ee.attachments??[]).map(F=>({id:F.id,annotationId:ee.id}))),le;try{le=me.length>0?await J.promote(me):void 0}catch(ee){_(y,409,{error:ee instanceof Error?ee.message:"Draft attachment unavailable."});return}let ne=rt().slice(0,8),X={};if(pe.length>0)for(let ee of pe){let F=encodeURIComponent(ee.pathname),ae=Ne(c,`screenshot-${ne}-${F}.webp`);await ao(ae,ee.data),X[ee.pathname]=ae}let Se=Ne(c,`screenshot-${ne}.webp`);await ao(Se,M);let be={};if(U.length>0)for(let ee of U){let F=Ne(c,`pasted-${ne}-${ee.annotationId}-${ee.index}.webp`);await ao(F,ee.data),be[ee.annotationId]||(be[ee.annotationId]=[]),be[ee.annotationId].push(F)}let Ae=Dr(z),ge;if(Ae.length>0){let ee=await O.findContinuationThread(Ae);ee?(ge=ee.id,await O.addElementIdentifiers(ge,Ae)):ge=(await O.createThread(`thread-${rt()}`,Ae)).id}else ge=(await O.createThread(`thread-${rt()}`,[])).id;let Z=z.annotations.map(ee=>ee.id),fe=Object.keys(X).length>0,Le=await ar(D,z,Ae,ee=>console.warn(`[\u22B9 ${f}:${ne}] Contextual memory unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))),Me=(await O.getThread(ge))?.messages??[],oe=await Y.contextualize({text:qt(z),subjectHints:[...Ae,...z.annotations.flatMap(ee=>[ee.pathname,ee.elements?.[0]?.reactComponent].filter(F=>!!F))],pendingGroundingExplanationIds:vn(Me),correctionExplanationIds:Qr(Me)}).catch(ee=>{console.warn(`[\u22B9 ${f}:${ne}] Imprint context unavailable; continuing without it:`,ee instanceof Error?ee.message:String(ee))}),ue=ii({jobId:ne,threadId:ge,artifactIds:Nr(z,ne)}),Ee={id:ne,status:"queued",screenshotPath:Se,feedback:z,createdAt:Date.now(),color:A,threadId:ge,annotationIds:Z,provider:Wt(S),model:$||void 0,agentSettings:Mt({reasoningEffort:C,serviceTier:q}),...Object.keys(be).length>0?{imagePaths:be}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},sourceId:G||void 0,...fe?{screenshotPaths:X}:{},...Le?{memoryReview:Le}:{},...oe?{imprintContext:oe}:{},lifecycle:ue},ut=new Set(z.annotations.map(ee=>ee.pathname).filter(Boolean)),$e;if(ut.size>1){let ee=new Map;for(let F of z.annotations){let ae=F.pathname||"(unknown)";ee.has(ae)||ee.set(ae,[]),ee.get(ae).push(F.instruction||Xr({...z,annotations:[F]}))}$e=[...ee.entries()].map(([F,ae])=>`\`${F}\`
|
|
211
|
+
${ae.map(ve=>`- ${ve}`).join(`
|
|
202
212
|
`)}`).join(`
|
|
203
|
-
`)}else
|
|
204
|
-
`):
|
|
205
|
-
`)),
|
|
213
|
+
`)}else $e=Xr(z);let qe=dn(z,Object.keys(be).length>0?be:void 0,le),Fe=zr(z);await O.appendMessage(ge,{role:"human",timestamp:Date.now(),jobId:ne,screenshotPath:Se,...fe?{screenshotPaths:X}:{},...Object.keys(be).length>0?{imagePaths:be}:{},...le&&Object.keys(le).length>0?{attachmentFiles:le}:{},annotationIds:Z,annotationSnapshot:{url:z.url,viewport:z.viewport,annotations:z.annotations,color:A||void 0},feedbackSummary:$e,...Fe?{requestText:Fe}:{},feedbackContext:qe||void 0,...Le?{memoryReview:Le}:{},...oe?{imprintContext:oe}:{},lifecycle:ue});let ke=E.enqueue(Ee);_(y,200,{jobId:ne,position:ke,threadId:ge})}async function _e(a,y){let M=a.headers["content-type"]||"",v,A,S,$,C,q,G,U,pe=[];if(M.includes("multipart/form-data")){let F=await Go(a),ae=F.feedback?JSON.parse(F.feedback):{};v=ae.threadId,A=ae.reply,S=ae.color,$=ae.provider,C=ae.model,q=Mt(ae),G=ae.sourceId||F.sourceId,U=typeof ae.memoryReviewProposalId=="string"?ae.memoryReviewProposalId:void 0;for(let ve of F.pastedImages)pe.push(ve.data)}else{let F=[];for await(let Ue of a)F.push(typeof Ue=="string"?Buffer.from(Ue):Ue);let ae=Buffer.concat(F).toString("utf-8"),ve;try{ve=JSON.parse(ae)}catch{_(y,400,{error:"Invalid JSON"});return}v=ve.threadId,A=ve.reply,S=ve.color,$=ve.provider,C=ve.model,q=Mt(ve),G=ve.sourceId,U=ve.memoryReviewProposalId}if(!v||!A){_(y,400,{error:"Missing threadId or reply"});return}let z=await O.getThread(v);if(!z){_(y,404,{error:"Thread not found"});return}let me;if(U){let F=await se.findModelProposalsByThread(v);if(me=(await Promise.all(F.flatMap(ve=>ve.authorityStatus==="accepted"?[]:ve.decisionIds.map(async Ue=>({modelProposalId:ve.id,underlying:await D.findPendingProposalForLegacyDecision(Ue)}))))).filter(ve=>!!ve.underlying).find(ve=>ve.underlying.proposalId===U),!me){_(y,409,{error:"The requested memory decision is not pending in this thread."});return}}let le="";{let F=await O.getThreadHistory(v);for(let ae=F.length-1;ae>=0;ae--)if(F[ae].screenshotPath){le=F[ae].screenshotPath;break}}let ne=await gt(v);if(!le&&!ne){_(y,400,{error:"No screenshot available"});return}let X=E.hasActiveThread(v),Se=X?E.getQueuedThreadJob(v,F=>F._replyText!==void 0||F._replyPrompt!==void 0):null,be=Se?.id??rt().slice(0,8),Ae=ii({jobId:be,threadId:v}),ge=[],Z=`${be}-${Date.now()}`;for(let F=0;F<pe.length;F++){let ae=Ne(c,`reply-${Z}-${F}.webp`);await ao(ae,pe[F]),ge.push(ae)}await O.appendMessage(v,{role:"human",timestamp:Date.now(),jobId:be,replyToQuestion:A,screenshotPath:le,...X?{queued:!0}:{},...ge.length>0?{replyImagePaths:ge}:{},lifecycle:{...Ae,artifactIds:ge.map((F,ae)=>`reply-image:${be}:${ae}`)}});let fe=await O.getThreadHistory(v),Le=[...fe].reverse().find(F=>F.memoryReview)?.memoryReview,Me=await Y.contextualize({text:A,subjectHints:z.elementIdentifiers,pendingGroundingExplanationIds:vn(fe),correctionExplanationIds:Qr(fe)}).catch(F=>{console.warn(`[\u22B9 ${f}:${be}] Imprint context unavailable for reply; continuing without it:`,F instanceof Error?F.message:String(F))}),oe=new Set(fe.flatMap(F=>F.memoryReceipt?.status==="committed"?[F.memoryReceipt.proposalId]:[])),ue=[...fe].reverse().find(F=>F.memoryReviewCard&&!oe.has(F.memoryReviewCard.proposalId))?.memoryReviewCard,Ee=[];for(let F of fe)if(F.annotationIds)for(let ae of F.annotationIds)Ee.includes(ae)||Ee.push(ae);let ut=Wt($),$e=me,qe=$e?[$e.underlying.proposalId]:ue?[ue.proposalId]:[],Fe=yr(le,fe,ut,ge.length>0?ge:void 0);if($e?Fe+=["","## Decision review card",`Privately review proposal ${$e.underlying.proposalId}: ${$e.underlying.claim}`,"Classify it as a principle, preference, rule, or constraint and rewrite it as concise, durable product guidance.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Do not ask the developer to type an action. The interface will render action buttons.","Return only this machine-readable block:",'<memory-review-card>{"proposalId":"<exact proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<suggested durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"Do not emit a <memory-review> action; no decision has been made yet."].join(`
|
|
214
|
+
`):ue&&(Fe+=["","## Continue decision review","The developer is discussing an unresolved decision review card, not requesting implementation work.",`Current private card state: ${JSON.stringify(ue)}`,"Use the developer's latest reply to refine the classification, wording, scope, or rationale.","Do not edit files, run commands, or implement the proposed product change during this review.","Do not mention the proposal ID, UUIDs, machine tags, or implementation mechanics in user-facing prose.","Return only an updated block using the same proposalId:",'<memory-review-card>{"proposalId":"<same proposal id>","kind":"principle|preference|rule|constraint","title":"<short human title>","claim":"<refined durable wording>","rationale":"<short reason this classification fits>","scope":"<optional concise scope>"}</memory-review-card>',"The interface will render the updated card and its action buttons."].join(`
|
|
215
|
+
`)),Se){let F=Se,ve=[...F._replyTexts??(F._replyText?[F._replyText]:[]),A],Ue=[...F._replyImagePaths??[],...ge];F._replyTexts=ve,F._replyText=Kr(ve),F._replyImagePaths=Ue.length>0?Ue:void 0,F._replyPrompt=Fe,F.annotationIds=Ee.length>0?Ee:F.annotationIds,F.agentSettings=q??F.agentSettings,F.memoryReview=Le??F.memoryReview,F.imprintContext=Me??F.imprintContext,F.surfacedProposalIds=[...new Set([...F.surfacedProposalIds??[],...qe])],F.lifecycle={...F.lifecycle??Ae,submissionIds:[...new Set([...F.lifecycle?.submissionIds??[],...Ae.submissionIds])],artifactIds:[...new Set([...F.lifecycle?.artifactIds??[],...Ae.artifactIds])]},_(y,200,{jobId:be,position:1,threadId:v,bundled:!0});return}let ke={id:be,status:"queued",screenshotPath:le,feedback:{timestamp:new Date().toISOString(),url:"",viewport:{width:0,height:0},scrollPosition:{x:0,y:0},annotations:[],styleModifications:[]},createdAt:Date.now(),color:S,threadId:v,annotationIds:Ee.length>0?Ee:void 0,provider:ut,model:C||void 0,agentSettings:q,sourceId:G||void 0,...Le?{memoryReview:Le}:{},...Me?{imprintContext:Me}:{},...qe.length?{surfacedProposalIds:qe}:{},lifecycle:Ae};ne&&(ke.kind=ne),ke._replyPrompt=Fe,ke._replyTexts=[A],ke._replyText=Kr([A]),ge.length>0&&(ke._replyImagePaths=ge);let ee=X?E.enqueueNext(ke):E.enqueue(ke);_(y,200,{jobId:be,position:ee,threadId:v})}function tt(a,y){y.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),y.write(`event: connected
|
|
206
216
|
data: {"status":"connected"}
|
|
207
217
|
|
|
208
|
-
`);let I=new URL(a.url||"/",`http://127.0.0.1:${w}`).searchParams.get("sourceId")||void 0,k={id:Ot().slice(0,8),res:g,sourceId:I};H.add(k),a.on("close",()=>{H.delete(k)})}async function tt(a,g,R){s??=ii(a.headers),Ge();let I=[...C.allActive,...f.allActive.map(Q=>({id:Q.id,status:Q.status,threadId:Q.threadId,annotationIds:Q.annotationIds??[],color:"#000000",kind:"project_model",standalone:Q.standalone}))],[k,S,$,D,N]=await Promise.allSettled([te.loadRuns(),te.loadModelProposals(),A.status(),q.store.load(),G.load()]),U=[],J=Q=>Q.reason instanceof Error?Q.reason.message:String(Q.reason);k.status==="rejected"&&U.push({subsystem:"projection",message:J(k)}),S.status==="rejected"&&U.push({subsystem:"projection",message:J(S)}),$.status==="rejected"?U.push({subsystem:"memory",message:J($)}):$.value.state==="degraded"&&U.push({subsystem:"memory",message:$.value.error??"Product memory is degraded."}),D.status==="rejected"&&U.push({subsystem:"imprint",message:J(D)}),N.status==="rejected"&&U.push({subsystem:"threads",message:J(N)});let de=k.status==="fulfilled"?k.value.runs:[],F=S.status==="fulfilled"?S.value.proposals:[],ue=si(de,F),ce=ue.actionableProposals.map(Q=>({id:Q.id,status:Q.status,title:Q.title,summary:Q.summary,decisionIds:Q.decisionIds,threadId:Q.threadId,runId:Q.runId,presentationJobId:Q.presentationJobId,authorityStatus:Q.authorityStatus,underlyingProposalId:Q.underlyingProposalId,createdAt:Q.createdAt,updatedAt:Q.updatedAt,appliedAt:Q.appliedAt,dismissedAt:Q.dismissedAt,error:Q.error})),ne=$.status==="fulfilled"?$.value:{initialized:!1,state:"degraded",error:J($)},X=N.status==="fulfilled"?[...new Set(Object.values(N.value.threads).flatMap(Q=>cn(Q.messages)))]:[],ke=D.status==="fulfilled"?X.filter(Q=>D.value.graph.explanations.some(ee=>ee.id===Q&&ee.state==="testing")):[],be=D.status==="fulfilled"?{state:"ready",head:D.value.graph.head,updatedAt:D.value.graph.updatedAt,explanationCount:D.value.graph.explanations.filter(Q=>Q.state!=="retired").length,concreteCount:D.value.graph.concrete.length,relationCount:D.value.graph.relations.length,pendingGroundingCount:ke.length,recoveredTransactions:D.value.recoveredTransactions,admission:q.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:J(D),pendingGroundingCount:ke.length,admission:q.diagnostics(),admissionWindowStartedAt:e},ge=U.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",xe=new Date().toISOString();_(g,200,{ok:!0,schemaVersion:3,generatedAt:xe,serverStartedAt:e,health:{state:ge,issues:U},version:an,restartMode:v,projectId:i,projectName:Yn(r),projectRoot:r,requestProjectId:R,projectIdVerified:R===i,devOrigin:s,capture:{native:{configured:!!l,endpoint:l?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:I[0]?{id:I[0].id,status:I[0].status}:null,activeJobs:I.map(Q=>({id:Q.id,status:Q.status,threadId:Q.threadId,annotationIds:Q.annotationIds,color:Q.color,kind:Q.kind,standalone:"standalone"in Q?Q.standalone:void 0})),queueDepth:C.depth+f.depth,projectionQueueDepth:f.depth,leases:{active:M.isActivated,count:M.size,nextExpiryAt:M.nextExpiryAt,shutdownPending:z},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:ue.recentRuns,recentAppliedRuns:ue.recentAppliedRuns,actionableProposalCounts:ue.actionableProposalCounts,actionableProposals:ce},memory:ne,imprint:be,recentJobsRetentionMs:Oe,recentJobs:Pe})}async function it(a,g){let R=await new Promise(I=>{let k="";a.on("data",S=>{k+=S.toString()}),a.on("end",()=>I(k))});try{let I=JSON.parse(R);typeof I.devOrigin=="string"&&(s=I.devOrigin||null),_(g,200,{ok:!0,devOrigin:s})}catch{_(g,400,{error:"Invalid JSON"})}}async function st(a){let g=await re.load();_(a,200,{ok:!0,...g})}async function dt(a,g){let R=await Ce(a);if(!ui(R.theme)){_(g,400,{error:"theme must be light, dark, or auto"});return}let I=await re.setTheme(R.theme);_(g,200,{ok:!0,exists:!0,preferences:I})}async function to(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),D=I?C.cancelJob(I):C.cancelActive(),N=I?f.cancelJob(I):f.cancelActive(),U=!!(D||N);for(let J of $)await G.appendMessage(J,{role:"assistant",timestamp:Date.now(),jobId:I||N?.id||"",cancelled:!0});_(g,200,{cancelled:U})}async function Bt(a){let g=Ot().slice(0,8),R=a.threadId,I=!R;R||(R=(await G.createThread(g,[])).id,ct.set(R,"project_model")),I&&await G.appendMessage(R,{role:"human",timestamp:Date.now(),jobId:g,feedbackSummary:a.reason}),await G.appendMessage(R,{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:R,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:I},S=f.enqueue(k);return{jobId:g,position:S,threadId:R}}async function Lt(a,g){let R=decodeURIComponent(a),I=await te.findModelProposal(R);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 Ne(a,g,R){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{_(R,400,{error:"Invalid JSON"});return}let $=(S.changes??[]).flatMap(F=>{if(!Array.isArray(F.path)||F.path.length===0)return[];let ue=F.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(ue.length!==F.path.length)return[];let ce=Array.isArray(F.decisionIds)?F.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:ue,value:F.value,remove:F.remove===!0,decisionIds:ce}]});if($.length===0){_(R,400,{error:"No selected model changes"});return}let D=(S.changeSummaries??[]).flatMap(F=>{if(!F||typeof F!="object")return[];let ue=Array.isArray(F.path)?F.path.filter(ce=>typeof ce=="string"||typeof ce=="number"):void 0;return Array.isArray(F.path)&&ue?.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:ue,value:F.value,currentValue:F.currentValue}]}),N=await te.findModelProposal(I);if(!N){_(R,404,{error:"Model proposal not found"});return}if(N.authorityStatus!=="accepted"){_(R,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(N.status!=="pending"){_(R,409,{error:`Model proposal is already ${N.status}.`});return}let U=N.decisionIds.map(F=>{let ue=N.changes?.filter(X=>X.decisionIds.includes(F)).length??0,ce=$.filter(X=>X.decisionIds?.includes(F)).length,ne=ce===0?"unprojected":ue>ce?"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:U}),de=await te.applySelectedModelProposal(I,$,D);if(!de){_(R,404,{error:"Model proposal not found"});return}if(de.threadId){let F=Nt(S.provider),ue=typeof S.model=="string"&&S.model?S.model:void 0;await G.appendMessage(de.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${de.id}`,responseText:"",provider:F,model:ue})}_(R,200,{proposal:de,projection:J})}async function Je(a,g,R){let I=decodeURIComponent(a),{provider:k,model:S}=await at(g),$=await te.dismissModelProposal(I);if(!$){_(R,404,{error:"Model proposal not found"});return}$.threadId&&await G.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${$.id}`,responseText:"",provider:k,model:S}),_(R,200,{proposal:$})}async function at(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 R=JSON.parse(Buffer.concat(g).toString());return{provider:Nt(typeof R.provider=="string"?R.provider:void 0),model:typeof R.model=="string"&&R.model?R.model:void 0,agentSettings:xt(R)}}catch{return{}}}async function bt(a){let g=ct.get(a);if(g)return g;let k=(await G.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(k.startsWith("Synthesize rules"))return ct.set(a,"synthesize"),"synthesize";if(k.startsWith("Materialize model")||k.startsWith("Project model"))return ct.set(a,"project_model"),"project_model"}async function lt(a,g){let R=[];for await(let N of a)R.push(typeof N=="string"?Buffer.from(N):N);let I;if(R.length>0)try{I=JSON.parse(Buffer.concat(R).toString("utf-8")).serverUrl}catch{}let k=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&k.push(await gr(I)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&k.push(await yr(I)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&k.push(await vr(I,m.copilot.path??T));let[S,$,D]=await Promise.all([ho(r),go(r),yo(r,m.copilot?.path??T)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=$),m.copilot&&(m.copilot.mcp=D),_(g,200,{results:k,capabilities:{providers:m}})}async function no(a,g){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(R).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 ln(a,g){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(R).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 Si(a,g){let R=[];for await(let $ of a)R.push(typeof $=="string"?Buffer.from($):$);let I;try{I=JSON.parse(Buffer.concat(R).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 Pi(a,g){let R=[];for await(let S of a)R.push(typeof S=="string"?Buffer.from(S):S);let I;try{I=JSON.parse(Buffer.concat(R).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 ki(a,g){let R=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")&&(R=S.origin)}catch{}}let I=Uo(w,R);g.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),g.end(I)}async function Ri(a){let g=Date.now();if(We&&g<We.expires){_(a,200,We.data);return}try{let{scanForComponents:R}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:I}=await import("./render-generator-EANIDD2E.mjs"),k=await R(r);We={data:k,expires:g+5e3},I(k,r,wt).then(S=>{wt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,k)}catch(R){console.error("[Bridge] Scanner error:",R),_(a,500,{error:"Failed to scan components"})}}async function Ti(a){let g=[$e(r,"node_modules","@popmelt.com","core","dist","canvas.mjs"),$e(r,"packages","popmelt","dist","canvas.mjs")];try{let R=Hc(import.meta.url);g.unshift($e(zc(R),"canvas.mjs"))}catch{}for(let R of g)try{let I=await gi(R,"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 ji(a,g){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(g,400,{error:"Invalid filename"});return}try{let R=[$e(c,a),$e(r,".popmelt","artifacts","thread-media",a),$e(r,".popmelt","artifacts","eval-screenshots",a),$e(r,".popmelt","evals","screenshots",a),$e(r,".popmelt","screenshots",a)],I;for(let $ of R)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/${Yn(a)}`}async function Mi(a,g){let R=await G.getThread(a);if(!R){_(g,404,{error:"Thread not found"});return}let I=R.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,U)=>{if(N.authorityStatus==="accepted")return N;let J=(await Promise.all(N.decisionIds.map(de=>A.findPendingProposalForLegacyDecision(de)))).find(Boolean);return{...N,authorityStatus:"legacy_untrusted",presentationJobId:N.presentationJobId??I[U]?.jobId??I.at(-1)?.jobId,underlyingProposalId:J?.proposalId,underlyingClaim:J?.claim}})),$=[...S].sort((N,U)=>U.updatedAt-N.updatedAt)[0]??null,D=R.messages.map(({screenshotPath:N,screenshotPaths:U,imagePaths:J,attachmentFiles:de,replyImagePaths:F,...ue})=>({...ue,...N?{screenshotUrl:Ft(N)}:{},...U?{screenshotUrls:Object.fromEntries(Object.entries(U).map(([ce,ne])=>[ce,Ft(ne)]))}:{},...J?{imageUrls:Object.fromEntries(Object.entries(J).map(([ce,ne])=>[ce,ne.map(Ft)]))}:{},...de?{attachments:Object.fromEntries(Object.entries(de).map(([ce,ne])=>[ce,ne.map(({path:X,...ke})=>({...ke,url:Ft(X)}))]))}:{},...F?{replyImageUrls:F.map(Ft)}:{}}));_(g,200,{id:R.id,createdAt:R.createdAt,messages:D,modelProposal:$,modelProposals:S})}async function Ai(a,g){let R=decodeURIComponent(a);if(!await G.deleteThread(R)){_(g,404,{deleted:!1,error:"Thread not found"});return}_(g,200,{deleted:!0})}let Bo=9,Lo=!1;for(let a=n;a<n+Bo;a++)try{await ld(It,a),w=a,Lo=!0,console.log(`[\u22B9 is watching :${w}]`);break}catch(g){if(g.code==="EADDRINUSE"){let R=await dd(a);if(ri(R,{projectId:i,version:an,restartMode:v}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:i,close:async()=>{}};continue}throw g}if(!Lo)throw new Error(`[Bridge] All ports ${n}\u2013${n+Bo-1} in use`);for(let[a,g]of Object.entries(m))!g.available||!g.path||P(a,g.path).then(R=>{if(R)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 H)Zn(I,{type:"capabilities_changed",data:{}})}});let Ei=setInterval(()=>{Ii(c).catch(()=>{}),Ie.sweep().catch(()=>{})},Qc),Fo=setInterval(()=>{M.expireStale().becameEmpty&&me()},Yc);return Fo.unref?.(),{port:w,projectId:i,close:async()=>{clearInterval(Ei),clearInterval(Fo),W(),M.clear(),await Ie.cleanupPartials(),await C.destroyAsync(),f.destroy();for(let a of H)try{a.res.end()}catch{}return H.clear(),new Promise(a=>{It.close(()=>a())})}}}async function Ii(o){try{let e=await Jc(o),n=Date.now();for(let t of e){let r=$e(o,t);try{let i=await Lc(r);n-i.mtimeMs>Xc&&await Fc(r)}catch{}}}catch{}}var he="\x1B[35m[popmelt]\x1B[0m";async function hd(){let o=process.argv.slice(2);if(o[0]==="memory"){await yd(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${he} Usage: popmelt wrap -- <dev command>`),console.error(`${he} Example: popmelt wrap -- next dev`),console.error(`${he} Example: popmelt wrap -- astro dev`),process.exit(1));let n=o.slice(e+1);await Id(n);return}if(o[0]==="bridge"){await vd();return}if(o[0]==="stop"){await wd();return}console.log(`${he} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function Jt(o,e){let n=o.indexOf(e);return n>=0?o[n+1]:void 0}function gd(){console.log(`${he} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function yd(o){if(o[0]!=="import"&&o[0]!=="review"){gd(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=Jt(o,"--project")??process.cwd(),n=Jt(o,"--project-key"),t=await gt({projectRoot:e,projectKey:n});if(o[0]==="review"){let c=Jt(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=Wt(t.bundle,{subjectHints:[c],action:Jt(o,"--action"),maxPackets:Number(Jt(o,"--max-packets")??3),maxEstimatedTokens:Number(Jt(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${he} Contextual memory review (read-only)`),console.log(`${he} Subject: ${c}`),console.log(`${he} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${he} Uncertainty: ${d.uncertainty}`);for(let[p,x]of d.packets.entries())console.log(""),console.log(`${p+1}. ${x.proposal.claim}`),console.log(` Authority: ${x.authority}; presentation: ${x.presentation}; implementation: ${x.implementation.state}`),console.log(` Why now: ${x.trigger.reason}`),console.log(` Proposal: ${x.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(t.report,null,2));return}let r=t.report,i=r.proofCases.filter(c=>c.threadFound).length,s=r.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${he} Legacy memory analysis (read-only)`),console.log(`${he} Project: ${r.projectRoot}`),console.log(`${he} Source: ${r.source.threads} threads, ${r.source.messages} messages, ${r.source.decisionEnvelopes} decision envelopes`),console.log(`${he} Imported: ${Object.entries(r.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${he} Acceptance unresolved: ${r.unresolvedAcceptance}`),console.log(`${he} Model values deferred: ${r.deferredModelEntries}`),console.log(`${he} Proof coverage: ${i}/${r.proofCases.length} threads found`),console.log(`${he} Schema validation: ${s.length===0?"passed":`${s.length} errors`}`),r.issues.length){let c=new Map;for(let d of r.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${he} Review flags: ${[...c].map(([d,p])=>`${d}=${p}`).join(", ")}`)}}async function vd(){let o=await Jo({projectRoot:process.cwd()});console.log(`${he} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let n=async()=>{console.log(`
|
|
209
|
-
${
|
|
218
|
+
`);let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("sourceId")||void 0,A={id:rt().slice(0,8),res:y,sourceId:v};L.add(A),a.on("close",()=>{L.delete(A)})}async function dt(a,y,M){s??=_r(a.headers),st();let v=[...E.allActive,...R.allActive.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds??[],color:"#000000",kind:"project_model",standalone:Z.standalone}))],[A,S,$,C,q]=await Promise.allSettled([se.loadRuns(),se.loadModelProposals(),D.status(),Y.store.load(),O.load()]),G=[],U=Z=>Z.reason instanceof Error?Z.reason.message:String(Z.reason);A.status==="rejected"&&G.push({subsystem:"projection",message:U(A)}),S.status==="rejected"&&G.push({subsystem:"projection",message:U(S)}),$.status==="rejected"?G.push({subsystem:"memory",message:U($)}):$.value.state==="degraded"&&G.push({subsystem:"memory",message:$.value.error??"Product memory is degraded."}),C.status==="rejected"&&G.push({subsystem:"imprint",message:U(C)}),q.status==="rejected"&&G.push({subsystem:"threads",message:U(q)});let pe=A.status==="fulfilled"?A.value.runs:[],z=S.status==="fulfilled"?S.value.proposals:[],me=$r(pe,z),le=me.actionableProposals.map(Z=>({id:Z.id,status:Z.status,title:Z.title,summary:Z.summary,decisionIds:Z.decisionIds,threadId:Z.threadId,runId:Z.runId,presentationJobId:Z.presentationJobId,authorityStatus:Z.authorityStatus,underlyingProposalId:Z.underlyingProposalId,createdAt:Z.createdAt,updatedAt:Z.updatedAt,appliedAt:Z.appliedAt,dismissedAt:Z.dismissedAt,error:Z.error})),ne=$.status==="fulfilled"?$.value:{initialized:!1,state:"degraded",error:U($)},X=q.status==="fulfilled"?[...new Set(Object.values(q.value.threads).flatMap(Z=>vn(Z.messages)))]:[],Se=C.status==="fulfilled"?X.filter(Z=>C.value.graph.explanations.some(fe=>fe.id===Z&&fe.state==="testing")):[],be=C.status==="fulfilled"?{state:"ready",head:C.value.graph.head,updatedAt:C.value.graph.updatedAt,explanationCount:C.value.graph.explanations.filter(Z=>Z.state!=="retired").length,concreteCount:C.value.graph.concrete.length,relationCount:C.value.graph.relations.length,pendingGroundingCount:Se.length,recoveredTransactions:C.value.recoveredTransactions,admission:Y.diagnostics(),admissionWindowStartedAt:e}:{state:"degraded",error:U(C),pendingGroundingCount:Se.length,admission:Y.diagnostics(),admissionWindowStartedAt:e},Ae=G.length>0?"degraded":ne.state==="absent"||ne.state==="initializing"?"initializing":"healthy",ge=new Date().toISOString();_(y,200,{ok:!0,schemaVersion:3,generatedAt:ge,serverStartedAt:e,health:{state:Ae,issues:G},version:yn,restartMode:l,projectId:r,projectName:co(i),projectRoot:i,requestProjectId:M,projectIdVerified:M===r,devOrigin:s,capture:{native:{configured:!!p,endpoint:p?"chromium-cdp":null},fallback:"bounded-dom"},activeJob:v[0]?{id:v[0].id,status:v[0].status}:null,activeJobs:v.map(Z=>({id:Z.id,status:Z.status,threadId:Z.threadId,annotationIds:Z.annotationIds,color:Z.color,kind:Z.kind,standalone:"standalone"in Z?Z.standalone:void 0})),queueDepth:E.depth+R.depth,projectionQueueDepth:R.depth,leases:{active:N.isActivated,count:N.size,nextExpiryAt:N.nextExpiryAt,shutdownPending:W},projection:{state:A.status==="fulfilled"&&S.status==="fulfilled"?"ready":"degraded",activeJob:R.active?{id:R.active.id,status:R.active.status,threadId:R.active.threadId,annotationIds:R.active.annotationIds??[],provider:R.active.provider,model:R.active.model}:null,queueDepth:R.depth,recentRuns:me.recentRuns,recentAppliedRuns:me.recentAppliedRuns,actionableProposalCounts:me.actionableProposalCounts,actionableProposals:le},memory:ne,imprint:be,recentJobsRetentionMs:He,recentJobs:je})}async function lt(a,y){let M=await new Promise(v=>{let A="";a.on("data",S=>{A+=S.toString()}),a.on("end",()=>v(A))});try{let v=JSON.parse(M);typeof v.devOrigin=="string"&&(s=v.devOrigin||null),_(y,200,{ok:!0,devOrigin:s})}catch{_(y,400,{error:"Invalid JSON"})}}async function ft(a){let y=await ce.load();_(a,200,{ok:!0,...y})}async function uo(a,y){let M=await De(a);if(!Fr(M.theme)){_(y,400,{error:"theme must be light, dark, or auto"});return}let v=await ce.setTheme(M.theme);_(y,200,{ok:!0,exists:!0,preferences:v})}async function mo(a,y){let v=new URL(a.url||"/",`http://127.0.0.1:${f}`).searchParams.get("jobId"),A=v?E.allActive.filter(U=>U.id===v):E.allActive,S=v?R.allActive.filter(U=>U.id===v):R.allActive,$=[...A.map(U=>U.threadId),...S.map(U=>U.threadId)].filter(Boolean),C=v?E.cancelJob(v):E.cancelActive(),q=v?R.cancelJob(v):R.cancelActive(),G=!!(C||q);for(let U of $)await O.appendMessage(U,{role:"assistant",timestamp:Date.now(),jobId:v||q?.id||"",cancelled:!0});_(y,200,{cancelled:G})}async function ht(a){let y=rt().slice(0,8),M=a.threadId,v=!M;M||(M=(await O.createThread(`thread-${rt()}`,[])).id,Ve.set(M,"project_model")),v&&await O.appendMessage(M,{role:"human",timestamp:Date.now(),jobId:y,feedbackSummary:a.reason}),await O.appendMessage(M,{role:"assistant",timestamp:Date.now(),jobId:y,responseText:v?"Projecting model suggestions...":"Thinking through model suggestions from this decision...",model:a.model,provider:a.provider});let A={id:y,status:"queued",createdAt:Date.now(),provider:a.provider,model:a.model,agentSettings:a.agentSettings,threadId:M,annotationIds:a.annotationIds,sourceId:a.sourceId,standalone:v},S=R.enqueue(A);return{jobId:y,position:S,threadId:M}}async function Je(a,y){let M=decodeURIComponent(a),v=await se.findModelProposal(M);if(!v){_(y,404,{error:"Model proposal not found"});return}_(y,409,{error:"Whole-model replacement is disabled. Review and apply selected projection changes.",proposal:v})}async function Be(a,y,M){let v=decodeURIComponent(a),A=[];for await(let z of y)A.push(typeof z=="string"?Buffer.from(z):z);let S;try{S=JSON.parse(Buffer.concat(A).toString("utf-8"))}catch{_(M,400,{error:"Invalid JSON"});return}let $=(S.changes??[]).flatMap(z=>{if(!Array.isArray(z.path)||z.path.length===0)return[];let me=z.path.filter(ne=>typeof ne=="string"||typeof ne=="number");if(me.length!==z.path.length)return[];let le=Array.isArray(z.decisionIds)?z.decisionIds.filter(ne=>typeof ne=="string"):void 0;return[{path:me,value:z.value,remove:z.remove===!0,decisionIds:le}]});if($.length===0){_(M,400,{error:"No selected model changes"});return}let C=(S.changeSummaries??[]).flatMap(z=>{if(!z||typeof z!="object")return[];let me=Array.isArray(z.path)?z.path.filter(le=>typeof le=="string"||typeof le=="number"):void 0;return Array.isArray(z.path)&&me?.length!==z.path.length?[]:[{group:typeof z.group=="string"?z.group:void 0,label:typeof z.label=="string"?z.label:void 0,detail:typeof z.detail=="string"?z.detail:void 0,path:me,value:z.value,currentValue:z.currentValue}]}),q=await se.findModelProposal(v);if(!q){_(M,404,{error:"Model proposal not found"});return}if(q.authorityStatus!=="accepted"){_(M,409,{error:"The underlying product claim is not accepted canonical memory."});return}if(q.status!=="pending"){_(M,409,{error:`Model proposal is already ${q.status}.`});return}let G=q.decisionIds.map(z=>{let me=q.changes?.filter(X=>X.decisionIds.includes(z)).length??0,le=$.filter(X=>X.decisionIds?.includes(z)).length,ne=le===0?"unprojected":me>le?"partially_projected":"projected";return{decisionId:z,status:ne}}),U=await D.applyModelProjection({runId:q.runId??q.id,presentationJobId:q.presentationJobId,decisionIds:q.decisionIds,changes:$.map(z=>({path:z.path,value:z.value,decisionIds:z.decisionIds})),coverage:G}),pe=await se.applySelectedModelProposal(v,$,C);if(!pe){_(M,404,{error:"Model proposal not found"});return}if(pe.threadId){let z=Wt(S.provider),me=typeof S.model=="string"&&S.model?S.model:void 0;await O.appendMessage(pe.threadId,{role:"assistant",timestamp:Date.now(),jobId:`apply-${pe.id}`,responseText:"",provider:z,model:me})}_(M,200,{proposal:pe,projection:U})}async function pt(a,y,M){let v=decodeURIComponent(a),{provider:A,model:S}=await jt(y),$=await se.dismissModelProposal(v);if(!$){_(M,404,{error:"Model proposal not found"});return}$.threadId&&await O.appendMessage($.threadId,{role:"assistant",timestamp:Date.now(),jobId:`dismiss-${$.id}`,responseText:"",provider:A,model:S}),_(M,200,{proposal:$})}async function jt(a){try{let y=[];for await(let v of a)y.push(typeof v=="string"?Buffer.from(v):v);if(y.length===0)return{};let M=JSON.parse(Buffer.concat(y).toString());return{provider:Wt(typeof M.provider=="string"?M.provider:void 0),model:typeof M.model=="string"&&M.model?M.model:void 0,agentSettings:Mt(M)}}catch{return{}}}async function gt(a){let y=Ve.get(a);if(y)return y;let A=(await O.getThread(a))?.messages.find(S=>S.role==="human")?.feedbackSummary??"";if(A.startsWith("Synthesize rules"))return Ve.set(a,"synthesize"),"synthesize";if(A.startsWith("Materialize model")||A.startsWith("Project model"))return Ve.set(a,"project_model"),"project_model"}async function fo(a,y){let M=[];for await(let q of a)M.push(typeof q=="string"?Buffer.from(q):q);let v;if(M.length>0)try{v=JSON.parse(Buffer.concat(M).toString("utf-8")).serverUrl}catch{}let A=[];m.claude?.available&&m.claude.mcp&&!m.claude.mcp.found&&A.push(await Ji(v)),m.codex?.available&&m.codex.mcp&&!m.codex.mcp.found&&A.push(await Bi(v)),m.copilot?.available&&m.copilot.mcp&&!m.copilot.mcp.found&&A.push(await Li(v,m.copilot.path??k));let[S,$,C]=await Promise.all([Ao(i),Mo(i),Eo(i,m.copilot?.path??k)]);m.claude&&(m.claude.mcp=S),m.codex&&(m.codex.mcp=$),m.copilot&&(m.copilot.mcp=C),_(y,200,{results:A,capabilities:{providers:m}})}async function In(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:{description:""},claim:`${v.name} is an explicitly governed component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{added:!0,alreadyExists:!1,...A})}async function ts(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.name||typeof v.name!="string"){_(y,400,{error:"Missing or invalid name"});return}let A=await D.recordDirectModelMutation({key:`components.${v.name}`,value:null,claim:`${v.name} is not governed as a component in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}async function ns(a,y){let M=[];for await(let $ of a)M.push(typeof $=="string"?Buffer.from($):$);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"||typeof v.value!="string"){_(y,400,{error:"Missing or invalid path/value"});return}let A=v.value;try{let $=JSON.parse(v.value);$&&typeof $=="object"&&(A=$)}catch{}let S=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:A,claim:`${v.path} uses ${v.value} in the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{updated:!0,...S})}async function os(a,y){let M=[];for await(let S of a)M.push(typeof S=="string"?Buffer.from(S):S);let v;try{v=JSON.parse(Buffer.concat(M).toString("utf-8"))}catch{_(y,400,{error:"Invalid JSON"});return}if(!v.path||typeof v.path!="string"){_(y,400,{error:"Missing or invalid path"});return}let A=await D.recordDirectModelMutation({key:`tokens.${v.path}`,value:null,claim:`${v.path} is intentionally absent from the product model.`});await se.applyCanonicalEntries(await D.getCanonicalModelEntries()),_(y,200,{removed:!0,...A})}function is(a,y){let M=s??"http://localhost:3000";if(!s){let A=a.headers.referer||a.headers.origin;if(A)try{let S=new URL(typeof A=="string"?A:A[0]||"");(S.hostname==="localhost"||S.hostname==="127.0.0.1")&&(M=S.origin)}catch{}}let v=li(f,M);y.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),y.end(v)}async function rs(a){let y=Date.now();if(at&&y<at.expires){_(a,200,at.data);return}try{let{scanForComponents:M}=await import("./react-scanner-ZXYS5M3Y.mjs"),{generateRenderFiles:v}=await import("./render-generator-EANIDD2E.mjs"),A=await M(i);at={data:A,expires:y+5e3},v(A,i,Vt).then(S=>{Vt=S}).catch(S=>console.warn("[Bridge] Render generation failed:",S)),_(a,200,A)}catch(M){console.error("[Bridge] Scanner error:",M),_(a,500,{error:"Failed to scan components"})}}async function ss(a){let y=[Ne(i,"node_modules","@popmelt.com","core","dist","canvas.mjs"),Ne(i,"packages","popmelt","dist","canvas.mjs")];try{let M=$d(import.meta.url);y.unshift(Ne(Md(M),"canvas.mjs"))}catch{}for(let M of y)try{let v=await Hr(M,"utf-8");a.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Access-Control-Allow-Origin":"*"}),a.end(v);return}catch{}console.error("[Bridge] Canvas bundle not found in:",y),_(a,404,{error:"Canvas bundle not found"})}async function as(a,y){if(!a||a.includes("/")||a.includes("\\")||a.includes("..")){_(y,400,{error:"Invalid filename"});return}try{let M=[Ne(c,a),Ne(i,".popmelt","artifacts","thread-media",a),Ne(i,".popmelt","artifacts","eval-screenshots",a),Ne(i,".popmelt","evals","screenshots",a),Ne(i,".popmelt","screenshots",a)],v;for(let $ of M)try{v=await Hr($);break}catch{}if(!v)throw new Error("File not found");let A=a.split(".").pop()?.toLowerCase(),S=A==="png"?"image/png":A==="webp"?"image/webp":A==="jpg"||A==="jpeg"?"image/jpeg":A==="svg"?"image/svg+xml":A==="txt"?"text/plain; charset=utf-8":"application/octet-stream";y.writeHead(200,{"Content-Type":S,"Cache-Control":"public, max-age=3600"}),y.end(v)}catch{_(y,404,{error:"File not found"})}}function Kt(a){return`/files/${co(a)}`}async function cs(a,y){let M=await O.getThread(a);if(!M){_(y,404,{error:"Thread not found"});return}let v=M.messages.filter(q=>q.role==="assistant"&&q.responseText?.includes("Model suggestion ready")),A=await(v.length>0?se.findModelProposalsByThread(a):Promise.resolve([])),S=await Promise.all(A.map(async(q,G)=>{if(q.authorityStatus==="accepted")return q;let U=(await Promise.all(q.decisionIds.map(pe=>D.findPendingProposalForLegacyDecision(pe)))).find(Boolean);return{...q,authorityStatus:"legacy_untrusted",presentationJobId:q.presentationJobId??v[G]?.jobId??v.at(-1)?.jobId,underlyingProposalId:U?.proposalId,underlyingClaim:U?.claim}})),$=[...S].sort((q,G)=>G.updatedAt-q.updatedAt)[0]??null,C=M.messages.map(({screenshotPath:q,screenshotPaths:G,imagePaths:U,attachmentFiles:pe,replyImagePaths:z,...me})=>({...me,...q?{screenshotUrl:Kt(q)}:{},...G?{screenshotUrls:Object.fromEntries(Object.entries(G).map(([le,ne])=>[le,Kt(ne)]))}:{},...U?{imageUrls:Object.fromEntries(Object.entries(U).map(([le,ne])=>[le,ne.map(Kt)]))}:{},...pe?{attachments:Object.fromEntries(Object.entries(pe).map(([le,ne])=>[le,ne.map(({path:X,...Se})=>({...Se,url:Kt(X)}))]))}:{},...z?{replyImageUrls:z.map(Kt)}:{}}));_(y,200,{id:M.id,createdAt:M.createdAt,messages:C,modelProposal:$,modelProposals:S})}async function ds(a,y){let M=decodeURIComponent(a);if(!await O.deleteThread(M)){_(y,404,{deleted:!1,error:"Thread not found"});return}_(y,200,{deleted:!0})}let ai=9,ci=!1;for(let a=t;a<t+ai;a++)try{await Qd(Pt,a),f=a,ci=!0,console.log(`[\u22B9 is watching :${f}]`);break}catch(y){if(y.code==="EADDRINUSE"){let M=await Kd(a);if(Er(M,{projectId:r,version:yn,restartMode:l}))return console.log(`[\u22B9 already watching :${a}]`),{port:a,projectId:r,close:async()=>{}};continue}throw y}if(!ci)throw new Error(`[Bridge] All ports ${t}\u2013${t+ai-1} in use`);for(let[a,y]of Object.entries(m))!y.available||!y.path||j(a,y.path).then(M=>{if(M)console.log(`[Bridge] ${a} warmed up`);else{console.warn(`[Bridge] ${a} warm-up failed \u2014 marking unavailable`),y.available=!1,y.path=null;for(let v of L)lo(v,{type:"capabilities_changed",data:{}})}});let ls=setInterval(()=>{Yr(c).catch(()=>{}),J.sweep().catch(()=>{})},Dd),di=setInterval(()=>{N.expireStale().becameEmpty&&H()},Jd);return di.unref?.(),{port:f,projectId:r,close:async()=>{clearInterval(ls),clearInterval(di),Q(),N.clear(),await J.cleanupPartials(),await E.destroyAsync(),R.destroy();for(let a of L)try{a.res.end()}catch{}return L.clear(),new Promise(a=>{Pt.close(()=>a())})}}}async function Yr(o){try{let e=await kd(o),t=Date.now();for(let n of e){let i=Ne(o,n);try{let r=await Rd(i);t-r.mtimeMs>Nd&&await Pd(i)}catch{}}}catch{}}var Ie="\x1B[35m[popmelt]\x1B[0m";async function tl(){let o=process.argv.slice(2);if(o[0]==="memory"){await ol(o.slice(1));return}if(o[0]==="wrap"){let e=o.indexOf("--");(e===-1||e===o.length-1)&&(console.error(`${Ie} Usage: popmelt wrap -- <dev command>`),console.error(`${Ie} Example: popmelt wrap -- next dev`),console.error(`${Ie} Example: popmelt wrap -- astro dev`),process.exit(1));let t=o.slice(e+1);await sl(t);return}if(o[0]==="bridge"){await il();return}if(o[0]==="stop"){await rl();return}console.log(`${Ie} Popmelt \u2014 design collaboration for AI coding agents`),console.log(""),console.log(" popmelt wrap -- <command> Start bridge + dev server together"),console.log(" popmelt bridge Start the bridge server standalone"),console.log(" popmelt stop Stop a detached bridge"),console.log(" popmelt memory import Analyze legacy project memory"),console.log(""),console.log("Examples:"),console.log(" popmelt wrap -- next dev"),console.log(" popmelt wrap -- astro dev"),console.log(" popmelt wrap -- vite"),console.log(""),console.log("In package.json:"),console.log(' "scripts": { "dev": "popmelt wrap -- next dev" }')}function Ht(o,e){let t=o.indexOf(e);return t>=0?o[t+1]:void 0}function nl(){console.log(`${Ie} Memory commands`),console.log(""),console.log(" popmelt memory import [--project <path>] [--project-key <key>] [--json]"),console.log(" popmelt memory review --subject <hint> [--action <text>] [--project <path>] [--json]"),console.log(""),console.log("The import command is analysis-only. It does not modify legacy or canonical storage."),console.log("Future namespace: memory inspect, verify, export, and commit.")}async function ol(o){if(o[0]!=="import"&&o[0]!=="review"){nl(),o.length>0&&o[0]!=="help"&&o[0]!=="--help"&&(process.exitCode=1);return}if(o.includes("--write")||o.includes("--commit"))throw new Error("Legacy import is currently read-only; --write and --commit are not supported.");let e=Ht(o,"--project")??process.cwd(),t=Ht(o,"--project-key"),n=await St({projectRoot:e,projectKey:t});if(o[0]==="review"){let c=Ht(o,"--subject");if(!c)throw new Error("memory review requires --subject <hint>");let d=tn(n.bundle,{subjectHints:[c],action:Ht(o,"--action"),maxPackets:Number(Ht(o,"--max-packets")??3),maxEstimatedTokens:Number(Ht(o,"--max-tokens")??1200)});if(o.includes("--json")){console.log(JSON.stringify(d,null,2));return}console.log(`${Ie} Contextual memory review (read-only)`),console.log(`${Ie} Subject: ${c}`),console.log(`${Ie} Matches: ${d.subjectMatches.length}; packets: ${d.packets.length}; status: ${d.completeness.status}`),d.uncertainty&&console.log(`${Ie} Uncertainty: ${d.uncertainty}`);for(let[u,I]of d.packets.entries())console.log(""),console.log(`${u+1}. ${I.proposal.claim}`),console.log(` Authority: ${I.authority}; presentation: ${I.presentation}; implementation: ${I.implementation.state}`),console.log(` Why now: ${I.trigger.reason}`),console.log(` Proposal: ${I.proposal.id}`);return}if(o.includes("--json")){console.log(JSON.stringify(n.report,null,2));return}let i=n.report,r=i.proofCases.filter(c=>c.threadFound).length,s=i.schemaIssues.filter(c=>c.severity==="error");if(console.log(`${Ie} Legacy memory analysis (read-only)`),console.log(`${Ie} Project: ${i.projectRoot}`),console.log(`${Ie} Source: ${i.source.threads} threads, ${i.source.messages} messages, ${i.source.decisionEnvelopes} decision envelopes`),console.log(`${Ie} Imported: ${Object.entries(i.imported).map(([c,d])=>`${d} ${c}`).join(", ")}`),console.log(`${Ie} Acceptance unresolved: ${i.unresolvedAcceptance}`),console.log(`${Ie} Model values deferred: ${i.deferredModelEntries}`),console.log(`${Ie} Proof coverage: ${r}/${i.proofCases.length} threads found`),console.log(`${Ie} Schema validation: ${s.length===0?"passed":`${s.length} errors`}`),i.issues.length){let c=new Map;for(let d of i.issues)c.set(d.code,(c.get(d.code)??0)+1);console.log(`${Ie} Review flags: ${[...c].map(([d,u])=>`${d}=${u}`).join(", ")}`)}}async function il(){let o=await si({projectRoot:process.cwd()});console.log(`${Ie} Bridge running on http://localhost:${o.port}`),await new Promise(e=>{let t=async()=>{console.log(`
|
|
219
|
+
${Ie} Shutting down bridge...`),await o.close(),e()};process.on("SIGINT",t),process.on("SIGTERM",t)})}async function rl(){let o=el(process.cwd(),".popmelt","bridge.lock"),e;try{e=JSON.parse(await Yd(o,"utf8"))}catch{console.log(`${Ie} No bridge running (no .popmelt/bridge.lock found)`);return}try{process.kill(e.pid,"SIGTERM"),console.log(`${Ie} Sent SIGTERM to bridge (pid ${e.pid}, port ${e.port})`)}catch(t){if(t.code==="ESRCH")console.log(`${Ie} Bridge process ${e.pid} already dead`);else throw t}try{await Zd(o)}catch{}}async function sl(o){let e=await si({projectRoot:process.cwd()});console.log(`${Ie} Bridge running on http://localhost:${e.port}`);let[t,...n]=o;console.log(`${Ie} Starting: ${o.join(" ")}`);let i=Xd(t,n,{stdio:"inherit",shell:!0,env:{...process.env,POPMELT_BRIDGE_URL:`http://localhost:${e.port}`,POPMELT_BRIDGE_PORT:String(e.port),POPMELT_PROJECT_ID:e.projectId}}),r=s=>{i.kill(s)};process.on("SIGINT",()=>r("SIGINT")),process.on("SIGTERM",()=>r("SIGTERM")),i.on("exit",async(s,c)=>{await e.close(),c?process.kill(process.pid,c):process.exit(s??0)})}tl().catch(o=>{console.error(`${Ie} Fatal:`,o),process.exit(1)});
|