@popmelt.com/core 0.8.4 → 0.8.6
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/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/bridge-entry.mjs +116 -299
- package/dist/{chunk-RBFQCZQP.mjs → chunk-EYFN72RC.mjs} +1 -1
- package/dist/chunk-NOHXTT24.mjs +1 -0
- package/dist/cli.mjs +116 -299
- package/dist/index.d.mts +7 -4
- package/dist/index.mjs +112 -40
- package/dist/memory-legacy.d.mts +446 -0
- package/dist/memory-legacy.mjs +1 -0
- package/dist/memory-store.d.mts +1048 -0
- package/dist/memory-store.mjs +3 -0
- package/dist/memory.d.mts +662 -0
- package/dist/memory.mjs +1 -0
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-KCVEM3PH.mjs +242 -0
- package/dist/server.d.mts +268 -1
- package/dist/server.mjs +119 -298
- package/package.json +19 -2
- package/dist/chunk-3TS7MVTZ.mjs +0 -1
- package/dist/server-7UMGXB6S.mjs +0 -421
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createHash as gt}from"crypto";import{mkdir as Ge,open as De,readFile as Oe,readdir as wt,rename as bt,unlink as Je}from"fs/promises";import{join as F}from"path";var ut=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ae(r){return ut.test(r)}function mt(r){return{valid:!r.some(e=>e.severity==="error"),issues:r}}function T(r,e,t,i){r.push({path:e,code:t,message:i,severity:"error"})}function Ce(r,e,t,i){r.push({path:e,code:t,message:i,severity:"warning"})}function C(r,e,t){ae(t)||T(r,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function U(r,e,t){(!t||Number.isNaN(Date.parse(t)))&&T(r,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function X(r,e,t,i=!1){i&&t.level==="contributor"&&T(r,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&T(r,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ft={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"]),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"])},yt=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function ht(r,e,t){C(r,`${t}.id`,e.id),C(r,`${t}.projectId`,e.projectId),C(r,`${t}.participantId`,e.participantId),C(r,`${t}.entity.entityId`,e.entity.entityId),U(r,`${t}.createdAt`,e.createdAt),X(r,`${t}.authority`,e.authority);let i=ft[e.entity.entityType],s=`${e.fromState??"null"}->${e.toState}`;i&&!i.has(s)&&T(r,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${s}.`);let o=`${e.entity.entityType}:${e.toState}`;if(yt.has(o)&&(X(r,`${t}.authority`,e.authority,!0),e.reason?.trim()||T(r,`${t}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let n=e.transitionContext;(n?.kind!=="proposal_deferral"||n.resurfaceWhen.length===0)&&T(r,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),n?.resurfaceWhen.includes("after_date")&&!n.revisitAfter&&T(r,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),n?.revisitAfter&&U(r,`${t}.transitionContext.revisitAfter`,n.revisitAfter)}}function It(r,e,t,i){C(r,`${t}.id`,e.id),C(r,`${t}.projectId`,e.projectId),C(r,`${t}.participantId`,e.participantId),U(r,`${t}.createdAt`,e.createdAt),e.projectId!==i&&T(r,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&T(r,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&T(r,`${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)&&T(r,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(X(r,`${t}.authority`,e.authority,!0),e.claim.trim()||T(r,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Ce(r,`${t}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&T(r,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(U(r,`${t}.appliedAt`,e.appliedAt),X(r,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&T(r,`${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())&&T(r,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(s=>!s.trim()))&&T(r,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Ce(r,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Ce(r,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function vt(r,e,t){C(r,`${t}.id`,e.id),C(r,`${t}.projectId`,e.projectId),C(r,`${t}.participantId`,e.participantId),C(r,`${t}.from.entityId`,e.from.entityId),C(r,`${t}.to.entityId`,e.to.entityId),U(r,`${t}.createdAt`,e.createdAt),e.reason.trim()||T(r,`${t}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&T(r,t,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?X(r,`${t}.authority`,e.authority,!0):T(r,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&T(r,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))&&T(r,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&T(r,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Y(r){let e=[];C(e,"manifest.projectId",r.manifest.projectId),U(e,"manifest.createdAt",r.manifest.createdAt),U(e,"manifest.updatedAt",r.manifest.updatedAt);let t=new Map,i=(a,y)=>{let m=t.get(a);m?T(e,y,"duplicate_id",`ID is already used at ${m}.`):t.set(a,y)};r.records.forEach((a,y)=>{let m=`records[${y}]`;i(a.id,m),It(e,a,m,r.manifest.projectId)}),r.events.forEach((a,y)=>{let m=`events[${y}]`;i(a.id,m),ht(e,a,m),a.projectId!==r.manifest.projectId&&T(e,`${m}.projectId`,"project_mismatch","Event belongs to another project.")}),r.relationships.forEach((a,y)=>{let m=`relationships[${y}]`;i(a.id,m),vt(e,a,m),a.projectId!==r.manifest.projectId&&T(e,`${m}.projectId`,"project_mismatch","Relationship belongs to another project.")}),r.artifacts.forEach((a,y)=>{i(a.id,`artifacts[${y}]`),C(e,`artifacts[${y}].id`,a.id)}),r.tombstones.forEach((a,y)=>{let m=`tombstones[${y}]`;i(a.id,m),C(e,`${m}.id`,a.id),C(e,`${m}.objectId`,a.objectId),C(e,`${m}.deletedById`,a.deletedById),U(e,`${m}.deletedAt`,a.deletedAt),X(e,`${m}.authority`,a.authority,!0)});let s=new Set(r.records.map(a=>`${a.recordType}:${a.id}`)),o=new Set(r.tombstones.map(a=>`${a.objectType}:${a.objectId}`)),n=(a,y)=>{let m=`${a.entityType}:${a.entityId}`;!s.has(m)&&!o.has(m)&&T(e,y,"dangling_entity_reference",`No record or tombstone exists for ${m}.`)};r.events.forEach((a,y)=>n(a.entity,`events[${y}].entity`)),r.relationships.forEach((a,y)=>{n(a.from,`relationships[${y}].from`),n(a.to,`relationships[${y}].to`)});let c=new Set(r.artifacts.map(a=>a.id)),p=(a,y)=>{c.has(a)||T(e,y,"dangling_artifact_reference","No artifact manifest entry exists.")},d=(a,y,m)=>{!s.has(`${a}:${y}`)&&!o.has(`${a}:${y}`)&&T(e,m,"dangling_entity_reference",`No ${a} record or tombstone exists.`)};r.records.forEach((a,y)=>{let m=`records[${y}]`;switch(a.recordType){case"authority_grant":d("participant",a.granteeId,`${m}.granteeId`),d("participant",a.grantedById,`${m}.grantedById`),a.subjectIds.forEach((f,l)=>d("subject",f,`${m}.subjectIds[${l}]`));break;case"observation":a.captureContext.subjectIds.forEach((f,l)=>d("subject",f,`${m}.captureContext.subjectIds[${l}]`)),a.captureContext.artifactIds.forEach((f,l)=>p(f,`${m}.captureContext.artifactIds[${l}]`));break;case"proposal":case"decision":a.subjects.forEach((f,l)=>d("subject",f.subjectId,`${m}.subjects[${l}].subjectId`));break;case"thread":a.messageArtifactIds.forEach((f,l)=>p(f,`${m}.messageArtifactIds[${l}]`)),a.resultRefs.forEach((f,l)=>n(f,`${m}.resultRefs[${l}]`));break;case"iteration":a.threadIds.forEach((f,l)=>d("thread",f,`${m}.threadIds[${l}]`)),a.artifactIds.forEach((f,l)=>p(f,`${m}.artifactIds[${l}]`));break;case"evidence":a.artifactIds.forEach((f,l)=>p(f,`${m}.artifactIds[${l}]`));break;case"implementation_attempt":a.iterationIds.forEach((f,l)=>d("iteration",f,`${m}.iterationIds[${l}]`)),a.coverageClaims.forEach((f,l)=>d("decision",f.decisionId,`${m}.coverageClaims[${l}].decisionId`)),a.artifactIds.forEach((f,l)=>p(f,`${m}.artifactIds[${l}]`));break;case"eval_spec":a.replacesSpecId&&d("eval_spec",a.replacesSpecId,`${m}.replacesSpecId`),a.decisionIds.forEach((f,l)=>d("decision",f,`${m}.decisionIds[${l}]`)),a.subjectIds.forEach((f,l)=>d("subject",f,`${m}.subjectIds[${l}]`)),(a.dependencies??[]).forEach((f,l)=>{f.kind==="subject"&&f.subjectId&&d("subject",f.subjectId,`${m}.dependencies[${l}].subjectId`)}),(a.scenarios??[]).forEach((f,l)=>{f.subjectIds?.forEach((b,x)=>d("subject",b,`${m}.scenarios[${l}].subjectIds[${x}]`))}),a.targets.forEach((f,l)=>d(f.entityType,f.entityId,`${m}.targets[${l}]`));break;case"verification_attempt":a.evalSpecId&&d("eval_spec",a.evalSpecId,`${m}.evalSpecId`),a.targets.forEach((f,l)=>d(f.entityType,f.entityId,`${m}.targets[${l}]`)),a.evidenceIds.forEach((f,l)=>d("evidence",f,`${m}.evidenceIds[${l}]`));break;case"model_entry":a.subjectIds.forEach((f,l)=>d("subject",f,`${m}.subjectIds[${l}]`)),a.decisionIds.forEach((f,l)=>d("decision",f,`${m}.decisionIds[${l}]`));break;case"model_projection":X(e,`${m}.authority`,a.authority,!0),d("participant",a.appliedById,`${m}.appliedById`),a.decisionIds.forEach((f,l)=>d("decision",f,`${m}.decisionIds[${l}]`)),a.entryIds.forEach((f,l)=>d("model_entry",f,`${m}.entryIds[${l}]`)),a.coverage.forEach((f,l)=>d("decision",f.decisionId,`${m}.coverage[${l}].decisionId`));break;case"freshness_signal":n(a.target,`${m}.target`),a.evidenceIds.forEach((f,l)=>d("evidence",f,`${m}.evidenceIds[${l}]`));break;default:break}});let g=new Map(r.events.map(a=>[a.id,a])),R=new Map(r.records.map(a=>[`${a.recordType}:${a.id}`,a])),I=new Map;r.events.forEach((a,y)=>{let m=`${a.entity.entityType}:${a.entity.entityId}:${a.fromState??"null"}`,f=I.get(m)??new Set;f.add(a.toState),I.set(m,f),f.size>1&&T(e,`events[${y}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let w=new Map(r.records.flatMap(a=>a.recordType==="authority_grant"?[[a.id,a]]:[])),h=(a,y,m,f,l)=>{if(a.level!=="delegate"||!a.grantId)return;let b=w.get(a.grantId);if(!b){T(e,l,"invalid_authority_grant","Delegated authority references a missing grant.");return}(b.granteeId!==y||b.level!=="delegate")&&T(e,l,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let x=Date.parse(m);(x<Date.parse(b.startsAt)||b.endsAt&&x>Date.parse(b.endsAt)||b.revokedAt&&x>=Date.parse(b.revokedAt))&&T(e,l,"inactive_authority_grant","The delegated authority grant was not active at this time."),b.subjectIds.length&&f.length&&!f.every(_=>b.subjectIds.includes(_))&&T(e,l,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let a of r.records)a.recordType==="decision"&&h(a.authority,a.acceptedById,a.createdAt,a.subjects.map(y=>y.subjectId),`records:${a.id}.authority`);r.events.forEach((a,y)=>{let m=R.get(`${a.entity.entityType}:${a.entity.entityId}`),f=m&&"subjects"in m?m.subjects.map(l=>l.subjectId):[];h(a.authority,a.participantId,a.createdAt,f,`events[${y}].authority`)}),r.relationships.forEach((a,y)=>{if(!a.authority)return;let m=[a.from,a.to].flatMap(f=>{let l=R.get(`${f.entityType}:${f.entityId}`);return l&&"subjects"in l?l.subjects.map(b=>b.subjectId):[]});h(a.authority,a.participantId,a.createdAt,m,`relationships[${y}].authority`)});for(let a of r.records){if(a.recordType!=="decision")continue;let y=g.get(a.acceptanceEventId);(!y||y.entity.entityType!=="proposal"||y.entity.entityId!==a.proposalId||y.toState!=="accepted")&&T(e,`records:${a.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),y&&y.participantId!==a.acceptedById&&T(e,`records:${a.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),R.has(`proposal:${a.proposalId}`)||T(e,`records:${a.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),a.state==="superseded"&&(r.relationships.some(f=>f.relationshipType==="supersedes"&&f.to.entityType==="decision"&&f.to.entityId===a.id)||T(e,`records:${a.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),a.state==="revoked"&&(r.events.some(f=>f.entity.entityType==="decision"&&f.entity.entityId===a.id&&f.toState==="revoked"&&!!f.reason?.trim())||T(e,`records:${a.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let a of r.records){if(a.recordType!=="proposal"||a.state!=="accepted")continue;r.records.some(m=>m.recordType==="decision"&&m.proposalId===a.id)||T(e,`records:${a.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return mt(e)}var jt={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function xe(r){return gt("sha256").update(JSON.stringify(r)).digest("hex")}function Be(r){return xe(r)}function Xe(r,e,t){for(let i of e.projectionUpdates){let s=r.records.find(o=>o.recordType===i.entityType&&o.id===i.entityId);if(!s||s.recordType!=="proposal"&&s.recordType!=="decision")throw new Error(`Projection target not found: ${i.entityType} ${i.entityId}`);if(s.state!==i.fromState)throw new Error(`Projection state conflict for ${i.entityType} ${i.entityId}: expected ${i.fromState}, found ${s.state}`);s.state=i.state}return r.records.push(...e.records),r.events.push(...e.events),r.relationships.push(...e.relationships),r.artifacts.push(...e.artifacts),r.tombstones.push(...e.tombstones),r.manifest.updatedAt=t,r}function Rt(r,e,t){return Xe(structuredClone(r),e,t)}async function Z(r,e){let t=`${r}.${process.pid}.${Date.now()}.tmp`,i=await De(t,"w");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,"utf8"),await i.sync()}finally{await i.close()}try{await bt(t,r)}catch(s){throw await Je(t).catch(()=>{}),s}}async function ke(r){return JSON.parse(await Oe(r,"utf8"))}var ge=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=F(e,".popmelt","memory"),this.journalDir=F(this.memoryDir,"journal"),this.manifestPath=F(this.memoryDir,"manifest.json"),this.checkpointPath=F(this.memoryDir,"checkpoint.json"),this.lockPath=F(this.memoryDir,"writer.lock")}async initialize(e){let t=Y(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await Ge(this.journalDir,{recursive:!0});try{throw await Oe(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(i){if(i instanceof Error&&i.message==="Memory journal is already initialized."||i.code!=="ENOENT")throw i}await this.withWriterLock(async()=>{try{throw await Oe(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}let i=xe(e),s={storageVersion:1,sequence:0,hash:i,journalHash:null,bundle:e},o={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:i},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await Z(this.checkpointPath,s),await Z(this.manifestPath,o)})}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 Z(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=xe(e.bundle),i=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,s={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await Z(F(this.memoryDir,i),s),e.manifest.checkpoint={file:i,sequence:s.sequence,hash:t},await Z(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:s.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(!ae(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 i=await this.loadInternal();if(i.transactionIds.has(t.transactionId))throw new Error(`Transaction already exists: ${t.transactionId}`);let s=i.report.headSequence+1,o={storageVersion:1,sequence:s,transactionId:t.transactionId,projectId:i.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:i.report.headHash,mutation:e},n={...o,hash:Be(o)},c=Rt(i.bundle,e,t.committedAt),p=Y(c);if(!p.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(p.issues)}`);let d=`${String(s).padStart(12,"0")}-${t.transactionId}.json`;return await Z(F(this.journalDir,d),n),i.manifest.head={sequence:s,hash:n.hash},i.manifest.updatedAt=t.committedAt,await Z(this.manifestPath,i.manifest),{bundle:c,report:{checkpointSequence:i.report.checkpointSequence,appliedTransactions:i.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:i.report.ignoredTemporaryFiles,headSequence:s,headHash:n.hash}}}))}async commitReviewPlan(e,t){return this.commit({...jt,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await ke(this.manifestPath),t=await ke(F(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!==xe(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let i=await wt(this.journalDir),s=i.filter(I=>I.endsWith(".tmp")),n=i.filter(I=>/^\d{12}-[0-9a-f-]+\.json$/i.test(I)).sort().filter(I=>Number(I.slice(0,12))>t.sequence),c=structuredClone(t.bundle),p=t.sequence,d=t.journalHash??null,g=new Set;for(let I of n){let w=await ke(F(this.journalDir,I)),{hash:h,...a}=w;if(h!==Be(a))throw new Error(`Journal hash mismatch: ${I}`);if(w.sequence!==p+1)throw new Error(`Journal sequence gap at ${I}`);if(w.previousHash!==d)throw new Error(`Journal chain mismatch at ${I}`);if(w.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${I}`);if(g.has(w.transactionId))throw new Error(`Duplicate transaction ID: ${w.transactionId}`);Xe(c,w.mutation,w.committedAt),p=w.sequence,d=w.hash,g.add(w.transactionId)}if(e.head.sequence>p)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===p&&e.head.hash!==d)throw new Error("Journal manifest head hash mismatch.");let R=Y(c);if(!R.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(R.issues)}`);return{bundle:c,manifest:e,transactionIds:g,report:{checkpointSequence:t.sequence,appliedTransactions:n.length,recoveredTransactions:Math.max(0,p-e.head.sequence),ignoredTemporaryFiles:s.length,headSequence:p,headHash:d}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await Ge(this.memoryDir,{recursive:!0});let t;try{t=await De(this.lockPath,"wx")}catch(i){if(i.code!=="EEXIST")throw i;let s=await ke(this.lockPath).catch(()=>({})),o=!0;if(typeof s.pid=="number")try{process.kill(s.pid,0)}catch(n){o=n.code!=="ESRCH"}if(o)throw new Error("Memory journal is locked by another writer.");await Je(this.lockPath),t=await De(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Je(this.lockPath).catch(()=>{})}}};import{mkdir as Ne,readFile as pe,writeFile as Fe}from"fs/promises";import{join as K}from"path";var St=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function ze(r){return r.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Me(r){return new Set(ze(r).split(" ").filter(e=>e.length>2&&!St.has(e)))}function Ye(r,e){if(!r.size||!e.size)return 0;let t=0;for(let i of r)e.has(i)&&(t+=1);return t/Math.min(r.size,e.size)}function Tt(r){return[{value:r.label,by:"label"},...r.aliases.map(e=>({value:e,by:"alias"})),...r.locators.map(e=>({value:e.value,by:"locator"}))]}function kt(r,e){let t=new Map,i=new Set(e.subjectIds??[]),s=(e.subjectHints??[]).map(ze).filter(Boolean),o=Me([e.action,e.text].filter(Boolean).join(" "));for(let n of r){if(i.has(n.id)){t.set(n.id,{subjectId:n.id,label:n.label,confidence:"exact",matchedBy:"id",score:100});continue}let c;for(let p of Tt(n)){let d=ze(p.value);for(let I of s){let w=d===I?95:d.includes(I)||I.includes(d)?75:0;w>(c?.score??0)&&(c={subjectId:n.id,label:n.label,confidence:w>=90?"exact":"strong",matchedBy:p.by,score:w})}let R=["/","#","[","]","="].some(I=>p.value.includes(I))?0:Math.round(Ye(Me(d),o)*55);R>=30&&R>(c?.score??0)&&(c={subjectId:n.id,label:n.label,confidence:R>=45?"strong":"weak",matchedBy:"query_text",score:R})}c&&t.set(n.id,c)}return t}function xt(r,e){let t=new Set(r.sourceRefs.filter(n=>n.kind==="iteration").map(n=>n.id)),i=new Set(r.sourceRefs.filter(n=>n.kind==="thread").map(n=>n.id)),s=e.filter(n=>n.iterationIds.some(c=>t.has(c))||n.sourceRefs.some(c=>c.kind==="thread"&&i.has(c.id)));if(!s.length)return{state:"none_found",attemptIds:[]};let o=new Set(s.map(n=>n.state));return{state:o.size>1?"mixed":o.has("completed")?"completed":"attempted",attemptIds:s.map(n=>n.id)}}function Mt(r){return Math.ceil(JSON.stringify(r).length/4)}function qe(r,e){let t=r.records.filter(y=>y.recordType==="subject"),i=e.generatedAt??new Date().toISOString(),s=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,o=r.records.filter(y=>{if(y.recordType!=="proposal"||s&&!s.has(y.id))return!1;if(y.state==="pending")return!0;if(y.state!=="deferred")return!1;let m=[...r.events].reverse().find(f=>f.entity.entityType==="proposal"&&f.entity.entityId===y.id&&f.toState==="deferred"&&f.transitionContext?.kind==="proposal_deferral")?.transitionContext;return m?m.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||m.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||m.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||m.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||m.resurfaceWhen.includes("after_date")&&!!(m.revisitAfter&&Date.parse(i)>=Date.parse(m.revisitAfter)):!1}),n=r.records.filter(y=>y.recordType==="implementation_attempt"),c=kt(t,e),p=[...c.values()].sort((y,m)=>m.score-y.score),d=Me([e.action,e.text].filter(Boolean).join(" ")),g=o.flatMap(y=>{let m=y.subjects.map(x=>c.get(x.subjectId)).filter(x=>!!x),f=Math.max(0,...m.map(x=>x.score)),l=Math.round(Ye(Me(y.claim),d)*35),b=f+l;return b>=50?[{proposal:y,proposalMatches:m,score:b}]:[]}).sort((y,m)=>m.score-y.score||y.proposal.id.localeCompare(m.proposal.id)),R=Math.max(1,e.maxPackets??3),I=Math.max(200,e.maxEstimatedTokens??1200),w=[],h=0;for(let y of g){if(w.length>=R)break;let m=y.proposal.sourceRefs.slice(0,4),f={contractVersion:1,packetId:`review:${y.proposal.id}`,projectId:r.manifest.projectId,generatedAt:i,trigger:{action:e.action,reason:y.proposalMatches.length?`Historical proposal intersects ${y.proposalMatches.map(b=>b.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:y.proposalMatches.map(({score:b,...x})=>x)},proposal:{id:y.proposal.id,claim:y.proposal.claim,state:y.proposal.state,proposedKind:y.proposal.proposedKind,subjectIds:y.proposal.subjects.map(b=>b.subjectId),origin:y.proposal.origin.mode},authority:"unaccepted",presentation:y.score>=100&&["constraint","rule"].includes(y.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:xt(y.proposal,n),evidence:{sourceCount:y.proposal.sourceRefs.length,sourceRefs:m},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:y.proposal.id},...m]},l={...f,estimatedTokens:Mt(f)};if(h+l.estimatedTokens>I)break;w.push(l),h+=l.estimatedTokens}let a=Math.max(0,g.length-w.length);return{packets:w,subjectMatches:p.map(({score:y,...m})=>m),completeness:{status:a>0?"truncated":"complete",consideredProposalCount:g.length,omittedPacketCount:a,maxEstimatedTokens:I,estimatedTokens:h},uncertainty:c.size===0?"subject_unresolved":g.length===0?"no_relevant_pending_proposal":void 0}}var _t=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Le(r){return r.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function _e(r){return new Set(Le(r).split(" ").filter(e=>e.length>2&&!_t.has(e)))}function Ze(r,e){if(!r.size||!e.size)return 0;let t=0;for(let i of r)e.has(i)&&(t+=1);return t/Math.min(r.size,e.size)}function At(r,e){let t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(Le).filter(Boolean),s=_e([e.action,e.text].filter(Boolean).join(" ")),o=[];for(let n of r){if(t.has(n.id)){o.push({subjectId:n.id,subjectType:n.subjectType,label:n.label,confidence:"exact",matchedBy:"id",score:100});continue}let c,p=[{value:n.label,by:"semantic"},...n.aliases.map(d=>({value:d,by:"alias"})),...n.locators.map(d=>({value:d.value,by:"locator"}))];for(let d of p){let g=Le(d.value);for(let w of i){let h=g===w?95:g.includes(w)||w.includes(g)?75:0;h>(c?.score??0)&&(c={subjectId:n.id,subjectType:n.subjectType,label:n.label,confidence:h>=90?"exact":"strong",matchedBy:d.by,score:h})}let I=["/","#","[","]","="].some(w=>d.value.includes(w))?0:Math.round(Ze(_e(g),s)*55);I>=30&&I>(c?.score??0)&&(c={subjectId:n.id,subjectType:n.subjectType,label:n.label,confidence:I>=45?"strong":"weak",matchedBy:"semantic",score:I})}c&&o.push(c)}return o.sort((n,c)=>c.score-n.score||n.subjectId.localeCompare(c.subjectId))}function Pt(r){return Math.ceil(JSON.stringify(r).length/4)}function ce(r,e){return r.relationshipType===e&&r.from.entityType==="decision"&&r.to.entityType==="decision"}function Et(r,e){let t=e.filter(o=>o.coverageClaims.some(n=>n.decisionId===r));if(!t.length)return{decisionId:r,state:"unimplemented",attemptIds:[]};let i=t.filter(o=>o.state==="completed"),s=i.some(o=>o.coverageClaims.some(n=>n.decisionId===r&&n.coverage==="full"));return{decisionId:r,state:s?"implemented":i.length?"partial":"unknown",attemptIds:t.map(o=>o.id)}}function $t(r,e,t){let i=e.filter(c=>c.targets.some(p=>p.entityType==="decision"&&p.entityId===r)).sort((c,p)=>p.createdAt.localeCompare(c.createdAt)),s=t.some(c=>c.signalType==="verification_expired"&&c.target.entityType==="decision"&&c.target.entityId===r),o=i[0],n=s?"stale":o?o.state==="passed"?"passing":o.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(o.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:r},state:n,attemptIds:i.map(c=>c.id)}}function et(r,e){let t=Math.max(300,e.maxEstimatedTokens??1200),i=Math.max(1,e.maxDecisions??6),s=r.records.filter(v=>v.recordType==="subject"),o=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,n=r.records.filter(v=>v.recordType==="decision"&&v.state==="active"),c=o?n.filter(v=>o.has(v.id)):n,p=r.records.filter(v=>v.recordType==="implementation_attempt"),d=r.records.filter(v=>v.recordType==="verification_attempt"),g=r.records.filter(v=>v.recordType==="freshness_signal"&&v.state==="open"),R=r.records.filter(v=>v.recordType==="evidence"),I=r.records.filter(v=>v.recordType==="model_entry"),w=[...r.records].reverse().filter(v=>v.recordType==="eval_spec").filter((v,P,S)=>S.findIndex(D=>D.legacyId===v.legacyId)===P),h=At(s,e),a=new Map(h.map(v=>[v.subjectId,v.score])),y=_e([e.action,e.text].filter(Boolean).join(" ")),m=c.flatMap(v=>{let P=Math.max(0,...v.subjects.map(J=>a.get(J.subjectId)??0)),S=Math.round(Ze(_e(v.claim),y)*35),D=P+S;return D>=50?[{decision:v,score:D}]:[]}).sort((v,P)=>P.score-v.score||v.decision.id.localeCompare(P.decision.id)),f=new Map;for(let v of m.slice(0,i))f.set(v.decision.id,v.decision);for(let v of r.relationships){if(!ce(v,"excepts")&&!ce(v,"contradicts"))continue;let P=n.find(D=>D.id===v.from.entityId),S=n.find(D=>D.id===v.to.entityId);!P||!S||!f.has(P.id)&&!f.has(S.id)||(f.size<i&&f.set(P.id,P),f.size<i&&f.set(S.id,S))}let l=[...f.values()],b=v=>v.from.entityType==="decision"&&v.to.entityType==="decision"&&f.has(v.from.entityId)&&f.has(v.to.entityId),x=(v,P=!1)=>{let S=new Set(v.map(u=>u.id)),D=g.filter(u=>u.target.entityType==="decision"&&S.has(u.target.entityId)),J=new Set(r.relationships.filter(u=>ce(u,"excepts")&&S.has(u.from.entityId)&&S.has(u.to.entityId)).flatMap(u=>[u.from.entityId,u.to.entityId])),ee=r.relationships.filter(u=>ce(u,"contradicts")&&S.has(u.from.entityId)&&S.has(u.to.entityId)).map(u=>({id:u.id,decisionIds:[u.from.entityId,u.to.entityId],unresolvedQuestion:u.reason,expansionRefs:[{kind:"record",id:u.id}]})),Re=new Set(ee.flatMap(u=>u.decisionIds)),te=R.filter(u=>u.sourceRefs.some(j=>j.kind==="record"&&S.has(j.id))||r.relationships.some(j=>j.relationshipType==="supports"&&j.from.entityType==="evidence"&&j.from.entityId===u.id&&j.to.entityType==="decision"&&S.has(j.to.entityId))),W=Math.max(0,m.length-v.length),fe=r.relationships.some(u=>ce(u,"contradicts")&&b(u)&&(!S.has(u.from.entityId)||!S.has(u.to.entityId))),Se=P||W>0||fe,Q=[];h.length===0&&(e.subjectHints?.length??0)>0?Q.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):v.length===0&&Q.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),ee.length&&Q.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:ee.flatMap(u=>u.expansionRefs)}),te.some(u=>u.availability!=="available")&&Q.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:te.map(u=>({kind:"record",id:u.id}))}),Se&&Q.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:r.manifest.projectId}]});let ye={contractVersion:1,projectId:r.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:h.map(({score:u,...j})=>j),modelEntries:I.filter(u=>u.decisionIds.some(j=>S.has(j))).map(u=>({id:u.id,key:u.key,value:u.value,decisionIds:u.decisionIds})),evalSpecs:w.filter(u=>u.decisionIds.some(j=>S.has(j))).map(u=>({id:u.id,legacyId:u.legacyId,state:u.state,title:u.title,assertionCount:u.assertions.length,decisionIds:u.decisionIds,expansionRef:{kind:"record",id:u.id}})),decisions:v.map(u=>({id:u.id,kind:u.kind,claim:u.claim,subjectIds:u.subjects.map(j=>j.subjectId),authority:u.authority,effectiveState:Re.has(u.id)?"conflicted":J.has(u.id)?"excepted":"active",freshness:D.filter(j=>j.target.entityId===u.id).map(j=>j.signalType),expansionRef:{kind:"record",id:u.id}})),conflicts:ee,uncertainties:Q,implementation:v.map(u=>Et(u.id,p)),verification:v.map(u=>$t(u.id,d,D)),evidence:te.map(u=>({evidenceId:u.id,summary:u.summary,availability:u.availability,sourceRefs:u.sourceRefs})),completeness:{status:Se?"truncated":"complete",omittedDecisionCount:W,omittedEvidenceCount:0,conflictsComplete:!fe}};return ye.budget.estimatedTokens=Pt(ye),ye},_=x(l);for(;_.budget.estimatedTokens>t&&l.length>0;){let v=l.pop(),P=r.relationships.filter(S=>ce(S,"contradicts")&&(S.from.entityId===v.id||S.to.entityId===v.id)).flatMap(S=>[S.from.entityId,S.to.entityId]);l=l.filter(S=>!P.includes(S.id)),_=x(l,!0)}return _}function we(r,e,t,i){return{id:i,schemaVersion:1,projectId:r.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function tt(r,e,t,i,s){return{id:s,schemaVersion:1,projectId:r.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:i,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 Ct(r){switch(r.action){case"accept":return[r.eventId,r.decisionId];case"edit_and_accept":return[r.withdrawalEventId,r.replacementProposalId,r.acceptanceEventId,r.decisionId,r.relationshipId];case"reject":case"defer":return[r.eventId]}}function Ae(r,e){let t=[],i=r.records.find(o=>o.recordType==="proposal"&&o.id===e.proposalId);i?i.state!=="pending"&&t.push({code:"proposal_not_pending",message:`Proposal is ${i.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."}),ae(e.participantId)||t.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let o of Ct(e))ae(o)||t.push({code:"invalid_generated_id",message:`${o} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&t.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),t.length||!i)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 o={...we(r,i,e,e.eventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},n=tt(r,i,e,o.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:i.id,append:{records:[n],events:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:n.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 o={id:e.replacementProposalId,schemaVersion:1,projectId:r.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:i.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"}},n={...we(r,i,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},c={...we(r,o,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:o.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},p=tt(r,o,e,c.id,e.decisionId),d={id:e.relationshipId,schemaVersion:1,projectId:r.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:i.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:o.id},to:{entityType:"proposal",entityId:i.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:i.id,append:{records:[o,p],events:[n,c],relationships:[d]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:o.id},{entityType:"decision",entityId:p.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let o={...we(r,i,e,e.eventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:i.id,append:{records:[],events:[o],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:i.id}]}}}let s={...we(r,i,e,e.eventId),entity:{entityType:"proposal",entityId:i.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:i.id,append:{records:[],events:[s],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:i.id}]}}}import{createHash as Dt}from"crypto";import{readFile as Ot,readdir as Jt,realpath as Bt}from"fs/promises";import{join as be,relative as zt}from"path";var qt=["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 de(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function z(r,e=0){return new Date(Number.isFinite(r)?r:e).toISOString()}function it(...r){return r.find(e=>!!e?.trim())?.trim()}function A(r,e,t,i){let o=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),n=Dt("sha256").update(`${r}\0${e}\0${t}`).digest("hex"),c=(Number.parseInt(n[3],16)&3|8).toString(16);return`${o.slice(0,8)}-${o.slice(8)}-7${n.slice(0,3)}-${c}${n.slice(4,7)}-${n.slice(7,19)}`}async function Ve(r,e){try{return JSON.parse(await Ot(r,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:r,message:t instanceof Error?t.message:String(t)}),null}}function Lt(r){let e=de(r);if(!e)return 0;let t=0,i=s=>{let o=de(s);if(!o){t+=1;return}for(let n of Object.values(o))i(n)};for(let s of Object.values(e))i(s);return t}function Vt(r){let e={};for(let t of r)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function je(r){let e=[],t=await Bt(r.projectRoot).catch(()=>r.projectRoot),i=be(t,".popmelt"),s=await Ve(be(i,"threads.json"),e),o=await Ve(be(i,"model.json"),e),n=de(s),c=de(n?.threads)??{},p=Object.entries(c).map(([u,j])=>({key:u,value:de(j)})).filter(u=>!!u.value),d=be(i,"decisions"),g=await Jt(d).catch(()=>[]),R=[];for(let u of g.filter(j=>j.endsWith(".json")).sort()){let j=de(await Ve(be(d,u),e));j&&R.push({file:u,value:j})}let I=p.flatMap(({value:u})=>[u.createdAt,u.updatedAt]).filter(u=>typeof u=="number"&&Number.isFinite(u)),w=I.length?Math.min(...I):0,h=r.projectKey??t;r.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 a=A(h,"project",h,w),y=A(h,"participant","legacy-owner",w),m=A(h,"participant","legacy-agent",w),f=A(h,"subject","project",w),l=z(Math.max(w,...I)),b=[],x=[],_=new Map,v=new Map,P=new Map(R.map(u=>[u.value.id??u.file.replace(/^d-|\.json$/g,""),u.value])),S=new Map,D=(u,j,M,O,q)=>{let N=_.get(M);if(N)return N;let H=A(h,"artifact",u,O);return x.push({id:H,kind:j,mediaType:q,location:M,availability:"available"}),_.set(M,H),H};for(let{file:u,value:j}of R){let M=j.id??u.replace(/^d-|\.json$/g,""),O=j.createdAt??w,q=[D(`${M}:envelope`,"other",`.popmelt/decisions/${u}`,O,"application/json")];j.screenshotPath&&q.push(D(`${M}:screenshot`,"screenshot",`.popmelt/${j.screenshotPath.replace(/^\.popmelt\//,"")}`,O,j.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[N,H]of(j.pastedImagePaths??[]).entries())q.push(D(`${M}:image:${N}`,"image",H,O));S.set(M,q)}let J=(u,j,M)=>({id:u,schemaVersion:1,projectId:a,createdAt:l,participantId:j,sourceRefs:M}),me=(u,j)=>{b.push(j);let M=v.get(u)??[];M.push(j.id),v.set(u,M)},ee=[{...J(y,y,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...J(m,m,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];b.push(...ee),b.push({...J(f,y,[]),recordType:"subject",subjectType:"project",label:zt(process.cwd(),t)||t,aliases:[],locators:[{id:A(h,"locator",t,w),kind:"project_root",value:t,status:"current",validFrom:z(w),sourceRefs:[]}]});let Re=new Map,te=(u,j)=>{let M=Re.get(u);if(M)return M;let O=A(h,"subject",u,j),q={...J(O,y,[{kind:"external",id:u}]),createdAt:z(j),recordType:"subject",subjectType:"element",label:u,aliases:[],locators:[{id:A(h,"locator",u,j),kind:"dom_selector",value:u,status:"current",validFrom:z(j),sourceRefs:[{kind:"external",id:u}]}]};return b.push(q),Re.set(u,O),O};for(let{key:u,value:j}of p){let M=j.id??u,O=j.createdAt??w,q=A(h,"thread",M,O),N={kind:"thread",id:M},H=[],he=[],Ue=Array.isArray(j.messages)?j.messages:[],ie,Ee,Ke=0;Ue.forEach((E,re)=>{let B=E.timestamp??O,G=A(h,"artifact",`${M}:message:${re}`,B);if(H.push(G),x.push({id:G,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${M}/messages/${re}`,availability:"available"}),_.set(`.popmelt/threads.json#/threads/${M}/messages/${re}`,G),E.screenshotPath&&D(`${M}:message:${re}:screenshot`,"screenshot",E.screenshotPath,B),E.role==="human"){ie=E;let L=E.feedbackSummary??E.replyToQuestion;if(L?.trim()){let V=A(h,"observation",`${M}:${re}`,B),se=j.elementIdentifiers??[],Te={...J(V,y,[N,{kind:"message",id:G}]),createdAt:z(B),recordType:"observation",state:"open",statement:L,captureContext:{subjectIds:se.map(ve=>te(ve,O)),artifactIds:[G]},resolvedByIds:[]};me(M,Te),Ee=V,he.push({entityType:"observation",entityId:V})}return}if(E.role!=="assistant")return;let ne=E.jobId??`${M}:${re}`,oe=A(h,"iteration",ne,B),Ie=P.get(ne),dt=E.cancelled?"cancelled":E.error?"failed":E.question?"question_asked":(E.resolutions?.length??0)>0?"completed":"no_change",pt={...J(oe,m,[N,{kind:"message",id:G},...(S.get(ne)??[]).map(L=>({kind:"artifact",id:L}))]),createdAt:z(B),recordType:"iteration",threadIds:[q],startedAt:z(ie?.timestamp,B),completedAt:z(B),requestSummary:it(ie?.feedbackSummary,ie?.replyToQuestion)??"[legacy request unavailable]",responseSummary:E.question??E.error??E.responseText?.slice(0,1e3),outcome:dt,execution:{provider:E.provider??Ie?.provider,model:E.model??Ie?.model,sessionId:E.sessionId??Ie?.sessionId},artifactIds:[G,...S.get(ne)??[]]};me(M,pt),he.push({entityType:"iteration",entityId:oe});let $e=E.resolutions??Ie?.resolutions??[];for(let[L,V]of $e.entries()){if(V.status!=="resolved"||!V.summary?.trim())continue;let se=j.elementIdentifiers??[],Te=(se.length?se:[t]).map(Qe=>({subjectId:Qe===t?f:te(Qe,O),role:"governed"})),ve=A(h,"proposal",`${ne}:${V.annotationId??"resolution"}:${L}`,B),lt={...J(ve,m,[N,{kind:"iteration",id:oe}]),createdAt:z(B),recordType:"proposal",state:"pending",claim:V.summary,subjects:Te,subjectSemantics:Te.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:it(ie?.feedbackSummary,ie?.replyToQuestion,V.summary),iterationId:oe,inferredById:m}};me(M,lt),he.push({entityType:"proposal",entityId:ve}),e.push({severity:"warning",code:"acceptance_unresolved",source:M,message:`Proposal ${ve} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if($e.some(L=>L.status==="resolved")||Ie?.gitDiff){let L=A(h,"implementation",ne,B),V={...J(L,m,[N,{kind:"iteration",id:oe}]),createdAt:z(B),recordType:"implementation_attempt",state:"completed",iterationIds:[oe],coverageClaims:[],summary:$e.map(se=>se.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};me(M,V),he.push({entityType:"implementation_attempt",entityId:L}),Ke+=1}Ee&&(Ee=void 0)});let We=Ue.at(-1),ct={...J(q,y,[N]),createdAt:z(O),recordType:"thread",state:We?.question?"open":"resolved",messageArtifactIds:H,outcome:We?.question?"question_unresolved":Ke?"implementation_only":"no_outcome",resultRefs:he};b.push(ct),v.set(M,[q,...v.get(M)??[]])}let W=Lt(o);W&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${W} model values were not promoted because their accepted decision provenance is unresolved.`});let fe={manifest:{formatVersion:1,projectId:a,createdAt:z(w),updatedAt:l,features:["authority","subjects","implementations","eval_specs","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:r.writerVersion??"0.8.4-dev"}},records:b,events:[],relationships:[],artifacts:x,tombstones:[]},Se=Y(fe),ye=(r.proofCaseIds??qt).map(u=>({legacyId:u,threadFound:p.some(({key:j,value:M})=>(M.id??j)===u),decisionEnvelopeFound:P.has(u),recordIds:v.get(u)??[]}));return{bundle:fe,report:{projectRoot:t,source:{threads:p.length,messages:p.reduce((u,j)=>u+(j.value.messages?.length??0),0),decisionEnvelopes:R.length,modelEntries:W,artifactsReferenced:x.length},imported:Vt(b),unresolvedAcceptance:e.filter(u=>u.code==="acceptance_unresolved").length,deferredModelEntries:W,proofCases:ye,issues:e,schemaIssues:Se.issues}}}import{randomBytes as Nt}from"crypto";function k(r=Date.now()){let t=Math.max(0,Math.min(Math.floor(r),0xffffffffffff)).toString(16).padStart(12,"0"),i=Nt(10).toString("hex"),s=(Number.parseInt(i[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${i.slice(0,3)}-${s}${i.slice(4,7)}-${i.slice(7,19)}`}var Ft=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function rt(r,e){let t=r.records.find(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),i=r.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.status==="active");if(!t||!i)throw new Error("Canonical memory requires active human and AI participants before job capture.");let s=r.manifest.projectId,o=`${e.threadId}:${e.jobId}`,n=new Date(e.createdAt).toISOString(),c=new Date(e.completedAt).toISOString(),p=Ft(),d=p.records,g=r.records.find(l=>l.recordType==="thread"&&l.sourceRefs.some(b=>b.kind==="thread"&&b.id===e.threadId));g||(g={id:A(s,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:r.manifest.projectId,createdAt:n,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(l=>l.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},d.push(g));let R=[];for(let l of[...new Set(e.subjectHints.filter(Boolean))]){let b=r.records.find(x=>x.recordType==="subject"&&x.locators.some(_=>_.value===l&&_.status==="current"));b||(b={id:A(s,"live-subject",l,e.createdAt),schemaVersion:1,projectId:r.manifest.projectId,createdAt:n,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"element",label:l,aliases:[],locators:[{id:A(s,"live-locator",l,e.createdAt),kind:"dom_selector",value:l,status:"current",validFrom:n,sourceRefs:[{kind:"external",id:l}]}]},d.push(b)),R.push(b)}for(let l of[...new Set((e.filePaths??[]).filter(Boolean))]){let b=r.records.find(x=>x.recordType==="subject"&&x.locators.some(_=>_.kind==="source_file"&&_.value===l&&_.status==="current"));b||(b={id:A(s,"live-file-subject",l,e.createdAt),schemaVersion:1,projectId:r.manifest.projectId,createdAt:n,participantId:t.id,sourceRefs:[{kind:"external",id:l}],recordType:"subject",subjectType:"file",label:l,aliases:[],locators:[{id:A(s,"live-file-locator",l,e.createdAt),kind:"source_file",value:l,status:"current",validFrom:n,sourceRefs:[{kind:"external",id:l}]}]},d.push(b)),R.push(b)}let I=(e.semanticCandidates??[]).filter(l=>l.claim.trim()),w;if(I.length>0){w=A(s,"live-observation",o,e.createdAt);let l={id:w,schemaVersion:1,projectId:r.manifest.projectId,createdAt:n,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:I.map(b=>b.claim.trim()).join(" "),captureContext:{subjectIds:R.map(b=>b.id),artifactIds:[]},resolvedByIds:[]};d.push(l)}let h=A(s,"live-iteration",o,e.completedAt),a={id:h,schemaVersion:1,projectId:r.manifest.projectId,createdAt:n,participantId:i.id,sourceRefs:[{kind:"thread",id:e.threadId},...w?[{kind:"record",id:w}]:[]],recordType:"iteration",threadIds:[g.id],startedAt:n,completedAt:c,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[]};d.push(a);let y=[],m=e.resolutions.filter(l=>l.status==="resolved"&&l.summary.trim()),f=R.length>0?R:r.records.filter(l=>l.recordType==="subject"&&l.subjectType==="project").slice(0,1);if(I.length>0&&f.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[l,b]of I.entries()){let x=A(s,"live-proposal",`${o}:${l}`,e.completedAt),_=f.map(P=>({subjectId:P.id,role:"governed"})),v={id:x,schemaVersion:1,projectId:r.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"iteration",id:h},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:b.claim.trim(),rationale:b.rationale?.trim()||void 0,proposedKind:b.proposedKind,subjects:_,subjectSemantics:_.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:b.sourceText?.trim()||e.requestSummary,iterationId:h,inferredById:i.id}};d.push(v),y.push(x)}if(m.length>0){let l=new Set(e.governingDecisionIds??[]),b=r.records.filter(_=>_.recordType==="decision"&&_.state==="active"&&l.has(_.id)),x={id:A(s,"live-implementation",o,e.completedAt),schemaVersion:1,projectId:r.manifest.projectId,createdAt:c,participantId:i.id,sourceRefs:[{kind:"iteration",id:h}],recordType:"implementation_attempt",state:"completed",iterationIds:[h],coverageClaims:b.map(_=>({decisionId:_.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${m.map(v=>v.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:h}]})),summary:m.map(_=>_.summary).join(" "),artifactIds:[]};d.push(x)}return{mutation:p,iterationId:h,proposalIds:y,observationId:w}}import{createHash as Ht}from"crypto";import{mkdir as Ut,open as Kt,readFile as Wt,rename as Qt,unlink as Gt}from"fs/promises";import{join as nt}from"path";function ot(r){return r.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function st(r){return Ht("sha256").update(JSON.stringify(r)).digest("hex")}async function Xt(r,e){let t=`${r}.${process.pid}.${Date.now()}.tmp`,i=await Kt(t,"w");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3
|
+
`,"utf8"),await i.sync()}finally{await i.close()}try{await Qt(t,r)}catch(s){throw await Gt(t).catch(()=>{}),s}}function Yt(r,e,t=new Date().toISOString()){let i={},s={},o={},n=(p,d,g)=>{let R=p[d]??=[];R.includes(g)||R.push(g)};for(let p of r.records)if(p.recordType==="subject"){let d=p;for(let g of[d.label,...d.aliases,...d.locators.filter(R=>R.status==="current").map(R=>R.value)]){let R=ot(g);R&&n(i,R,d.id)}}else if(p.recordType==="decision"&&p.state==="active")for(let d of p.subjects)n(s,d.subjectId,p.id);else if(p.recordType==="proposal"&&["pending","deferred"].includes(p.state))for(let d of p.subjects)n(o,d.subjectId,p.id);let c={version:1,projectId:r.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:i,decisionIdsBySubject:s,proposalIdsBySubject:o};return{...c,checksum:st(c)}}function at(r,e){let t=[...new Set(e.flatMap(i=>r.subjectIdsByValue[ot(i)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(i=>r.decisionIdsBySubject[i]??[]))],proposalIds:[...new Set(t.flatMap(i=>r.proposalIdsBySubject[i]??[]))]}}var Pe=class{constructor(e){this.indexDir=nt(e,".popmelt","memory","indexes"),this.indexPath=nt(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let s=JSON.parse(await Wt(this.indexPath,"utf8")),{checksum:o,...n}=s;if(s.version===1&&s.projectId===e.manifest.projectId&&s.journalHead.sequence===t.sequence&&s.journalHead.hash===t.hash&&o===st(n))return s}catch(s){if(s.code!=="ENOENT"&&!(s instanceof SyntaxError))throw s}let i=Yt(e,t);return await Ut(this.indexDir,{recursive:!0}),await Xt(this.indexPath,i),i}};var He=class{constructor(e){this.projectRoot=e;this.store=new ge(e),this.indexStore=new Pe(e),this.manifestPath=K(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await pe(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 s=await this.store.load();return s.report.recoveredTransactions>0&&(s=await this.store.recover()),await this.refreshIndex(s),await this.status()}let i=await je({...e,projectRoot:this.projectRoot});if(i.report.schemaIssues.some(s=>s.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(i.bundle)}catch(s){if(!(s instanceof Error)||!s.message.includes("already initialized"))throw s}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 je({...e,projectRoot:this.projectRoot})).report}async migrateLegacyEvals(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,specs:0,runs:0};let e=K(this.projectRoot,".popmelt","memory","migrations"),t=K(e,"legacy-evals-v1.json");try{let o=JSON.parse(await pe(t,"utf8"));return{migrated:!1,specs:o.specs??0,runs:o.runs??0}}catch{}let i=[],s=[];try{let o=JSON.parse(await pe(K(this.projectRoot,".popmelt","evals","evals.json"),"utf8"));i=Array.isArray(o.cases)?o.cases:[]}catch{}try{let o=JSON.parse(await pe(K(this.projectRoot,".popmelt","evals","runs.json"),"utf8"));s=Array.isArray(o.runs)?o.runs:[]}catch{}return i.length>0&&(i=(await this.reconcileEvalCases(i)).valid,await this.syncEvalSpecs(i),await this.syncLegacyEvalRuns(i,s)),await Ne(e,{recursive:!0}),await Fe(t,JSON.stringify({version:1,migratedAt:new Date().toISOString(),specs:i.length,runs:s.length,source:".popmelt/evals (frozen)"},null,2)),{migrated:!0,specs:i.length,runs:s.length}}async migrateImprintSnapshot(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{migrated:!1,explanations:0,evidence:0};let e=K(this.projectRoot,".popmelt","memory","migrations"),t=K(e,"imprint-evidence-v1.json");try{let o=JSON.parse(await pe(t,"utf8"));return{migrated:!1,explanations:o.explanations??0,evidence:o.evidence??0}}catch{}let i;try{i=JSON.parse(await pe(K(this.projectRoot,".popmelt","imprint","graph.json"),"utf8"))}catch{}if(!i?.explanations)return await Ne(e,{recursive:!0}),await Fe(t,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:0,evidence:0},null,2)),{migrated:!0,explanations:0,evidence:0};let s=0;for(let o of i.explanations){let n=o.evidence.length?o.evidence:[{id:o.id,kind:"observation",stance:"supports",summary:o.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:o.createdAt}];for(let c of n){let p=c.kind==="confirmation"?"confirm":c.kind==="correction"||c.kind==="rejection"?"reason_wrong":c.kind==="exception"?"exception":void 0;await this.recordImprintEvidence({summary:{transactionId:c.id,kind:p?"strengthened":"added",title:o.statement.slice(0,120),detail:c.summary,changes:[{explanationId:o.id,action:p==="reason_wrong"?"challenged":"supported",statement:o.statement,state:o.state}]},threadId:c.threadId,jobId:c.jobId,action:p,occurredAt:c.createdAt}),s+=1}}return await Ne(e,{recursive:!0}),await Fe(t,JSON.stringify({version:1,migratedAt:new Date().toISOString(),explanations:i.explanations.length,evidence:s,source:".popmelt/imprint (linked projection)"},null,2)),{migrated:!0,explanations:i.explanations.length,evidence:s}}async review(e,t={}){let i=await this.loadSource(t),s=await this.withIndexedCandidates(i,e);return{source:i.source,selection:qe(i.bundle,s)}}async contextualize(e,t={}){let i=await this.loadSource(t),s=await this.withIndexedCandidates(i,e);return{source:i.source,actionPacket:et(i.bundle,s),reviewSelection:qe(i.bundle,s)}}async planReview(e,t={}){let i=await this.loadSource(t);return{source:i.source,result:Ae(i.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 je({projectRoot:this.projectRoot,projectKey:e.projectKey,proofCaseIds:e.proofCaseIds,writerVersion:e.writerVersion});if(t.report.schemaIssues.some(i=>i.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 i=await this.store.load(),s=Ae(i.bundle,e);if(!s.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(s.errors)}`);let o=await this.store.commitReviewPlan(s.plan,t);return await this.refreshIndex(o),o}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(),i=t.bundle.records.find(I=>I.recordType==="proposal"&&I.id===e.proposalId),s=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active");if(!i||i.state!=="pending"||!s)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:i?i.state!=="pending"?`The proposal is already ${i.state}.`:"No active local owner participant is available.":"The reviewed proposal no longer exists."};let o=Date.now(),n=new Date(o).toISOString(),c={proposalId:i.id,participantId:s.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:n},p=e.action==="accept"?{...c,action:"accept",eventId:k(o),decisionId:k(o),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...c,action:"edit_and_accept",withdrawalEventId:k(o),replacementProposalId:k(o),acceptanceEventId:k(o),decisionId:k(o),relationshipId:k(o),claim:e.claim,kind:e.kind,subjects:i.subjects,subjectSemantics:i.subjectSemantics,reason:e.reason}:e.action==="reject"?{...c,action:"reject",eventId:k(o),reason:e.reason}:{...c,action:"defer",eventId:k(o),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:i.subjects.map(I=>I.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},d=Ae(t.bundle,p);if(!d.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:d.errors.map(I=>I.message).join(" ")};let g=await this.store.commitReviewPlan(d.plan,{transactionId:k(o),committedAt:n});await this.refreshIndex(g);let R=d.plan.resultRefs.find(I=>I.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:R,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:g.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(),i=rt(t.bundle,e),s=A(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let o=await this.store.commit(i.mutation,{transactionId:s,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(o),{status:"captured",iterationId:i.iterationId,proposalIds:i.proposalIds,headSequence:o.report.headSequence}}catch(o){if(o instanceof Error&&o.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:i.iterationId,proposalIds:i.proposalIds};throw o}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t=await this.store.load(),i=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="human"&&I.status==="active"),s=t.bundle.records.find(I=>I.recordType==="participant"&&I.kind==="ai"&&I.status==="active"),o=e.action?i:s??i,n=t.bundle.records.find(I=>I.recordType==="subject"&&I.subjectType==="project");if(!o||!n)return;let c=e.occurredAt??new Date().toISOString(),p=Date.parse(c),d=[],g=[];for(let I of e.summary.changes){let w={kind:"external",id:I.explanationId,uri:"popmelt:imprint"},h=t.bundle.records.find(y=>y.recordType==="observation"&&y.sourceRefs.some(m=>m.kind==="external"&&m.id===I.explanationId&&m.uri==="popmelt:imprint"));h||(h={id:k(p),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[w,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}],recordType:"observation",state:"open",statement:I.statement,captureContext:{subjectIds:[n.id],artifactIds:[]},resolvedByIds:[]},d.push(h));let a={id:k(p),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[w,{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:[]};d.push(a),g.push({id:k(p),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[w],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"observation",entityId:h.id},to:{entityType:"evidence",entityId:a.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let R=A(t.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,p);try{let I=await this.store.commit({records:d,events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:R,committedAt:c});await this.refreshIndex(I)}catch(I){if(!(I instanceof Error)||!I.message.includes("Transaction already exists"))throw I}}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 i={};for(let s of t.bundle.records)i[s.recordType]=(i[s.recordType]??0)+1;return{status:e,journal:t.report,records:i,openFreshnessSignals:t.bundle.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open").length,unavailableEvidence:t.bundle.records.filter(s=>s.recordType==="evidence"&&s.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(),i=new Set(t.records.flatMap(n=>n.recordType==="model_projection"&&n.state==="applied"?n.coverage.filter(c=>c.status==="projected").map(c=>c.decisionId):[])),s=new Set(t.relationships.flatMap(n=>n.relationshipType==="contradicts"&&n.from.entityType==="decision"&&n.to.entityType==="decision"?[n.from.entityId,n.to.entityId]:[])),o=new Set(t.records.flatMap(n=>n.recordType==="freshness_signal"&&n.state==="open"&&n.target.entityType==="decision"?[n.target.entityId]:[]));return t.records.filter(n=>n.recordType==="decision"&&n.state==="active"&&!i.has(n.id)&&!s.has(n.id)&&!o.has(n.id)).sort((n,c)=>c.createdAt.localeCompare(n.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(s=>s.recordType==="decision"&&s.state==="active"?[s.id]:[])),i=new Map;for(let s of e.records.filter(o=>o.recordType==="model_entry").sort((o,n)=>o.createdAt.localeCompare(n.createdAt)))s.decisionIds.some(o=>t.has(o))&&i.set(s.key,s);return[...i.values()]}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]:[])),i=new Map;for(let c of e.records.filter(p=>p.recordType==="model_entry").sort((p,d)=>p.createdAt.localeCompare(d.createdAt)))c.decisionIds.some(p=>t.has(p))&&i.set(c.key,c);let s=[...i.values()],o=e.records.filter(c=>c.recordType==="verification_attempt");return{decisions:e.records.filter(c=>c.recordType==="decision"&&c.state==="active").map(c=>{let p=o.filter(d=>d.targets.some(g=>g.entityType==="decision"&&g.entityId===c.id)).sort((d,g)=>g.createdAt.localeCompare(d.createdAt))[0];return{id:c.id,kind:c.kind,claim:c.claim,projected:s.some(d=>d.decisionIds.includes(c.id)),verification:p?p.state:"unverified"}}),entries:s.map(c=>({id:c.id,key:c.key,value:c.value,decisionIds:c.decisionIds}))}}async getEvalDependenciesForDecisions(e){if(!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),i=new Set(t.records.flatMap(o=>o.recordType==="decision"&&e.includes(o.id)?o.subjects.map(n=>n.subjectId):[])),s=[];for(let o of t.records)if(!(o.recordType!=="subject"||!i.has(o.id)))for(let n of o.locators.filter(c=>c.status==="current"))n.kind==="source_file"?s.push({kind:"source_file",value:n.value,subjectId:o.id}):n.kind==="route_pattern"?s.push({kind:"route",value:n.value,subjectId:o.id}):n.kind==="token_path"?s.push({kind:"model_path",value:n.value,subjectId:o.id}):(n.kind==="dom_selector"||n.kind==="file_export"||n.kind==="source_span")&&s.push({kind:"subject",value:n.value,subjectId:o.id});return[...new Map(s.map(o=>[`${o.kind}:${o.value}:${o.subjectId??""}`,o])).values()]}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(),i=t.bundle.records.find(S=>S.recordType==="participant"&&S.kind==="human"&&S.status==="active"),s=t.bundle.records.find(S=>S.recordType==="subject"&&S.subjectType==="project");if(!i||!s)throw new Error("Canonical owner or project subject is unavailable.");let o=Date.now(),n=new Date(o).toISOString(),c=k(o),p=k(o),d=k(o),g=k(o),R=k(o),I=new Set(t.bundle.records.flatMap(S=>S.recordType==="model_entry"&&S.key===e.key?S.decisionIds:[])),w=t.bundle.records.filter(S=>S.recordType==="decision"&&S.state==="active"&&I.has(S.id)),h={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:n,participantId:i.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},a=[{subjectId:s.id,role:"governed"}],y={...h,id:c,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:a,origin:{mode:"declared",sourceText:e.claim,reviewedById:i.id}},m={...h,id:p,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."},f={...h,id:d,recordType:"decision",proposalId:c,acceptanceEventId:p,acceptedById:i.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:a,noChange:!1,effectiveAt:n},l={...h,id:g,recordType:"model_entry",key:e.key,subjectIds:[s.id],decisionIds:[d],value:e.value},b={...h,id:R,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${o}`,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:n,decisionIds:[d],entryIds:[g],coverage:[{decisionId:d,status:"projected"}]},x={...h,id:k(o),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:g},to:{entityType:"decision",entityId:d},reason:"The model change is projected from the owner-confirmed decision."},_=w.map(S=>({...h,id:k(o),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:S.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),v=w.map(S=>({...h,id:k(o),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:f.id},to:{entityType:"decision",entityId:S.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),P=await this.store.commit({records:[y,f,l,b],events:[m,..._],relationships:[x,...v],artifacts:[],tombstones:[],projectionUpdates:w.map(S=>({entityType:"decision",entityId:S.id,fromState:"active",state:"superseded"}))},{transactionId:k(o),committedAt:n});return await this.refreshIndex(P),{decisionId:d,entryId:g}}async syncEvalSpecs(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.length===0)return[];let t=await this.store.load();for(let i of e){let s=this.latestEvalSpec(t.bundle,i.id),o=t.bundle.records.flatMap(h=>h.recordType!=="decision"?[]:i.sourceDecisionIds.some(a=>a===h.id||h.sourceRefs.some(y=>y.id===a))?[h.id]:[]),n=[...new Set(t.bundle.records.flatMap(h=>h.recordType==="decision"&&o.includes(h.id)?h.subjects.map(a=>a.subjectId):[]))],p={state:i.status==="pending"?"draft":i.status==="approved"?"active":"retired",title:i.title,category:i.category,prompt:i.prompt,assertions:i.assertions,rationale:i.rationale,decisionIds:o,subjectIds:n,threadRefs:i.sourceThreadIds,dependencies:i.dependencies??[],scenarios:i.scenarios??[]};if(s&&JSON.stringify({state:s.state,title:s.title,category:s.category,prompt:s.prompt,assertions:s.assertions,rationale:s.rationale,decisionIds:s.decisionIds,subjectIds:s.subjectIds,threadRefs:s.threadRefs,dependencies:s.dependencies??[],scenarios:s.scenarios??[]})===JSON.stringify(p))continue;let d=t.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!d)throw new Error("No active local owner participant is available.");let g=Date.now(),R=new Date(g).toISOString(),I={id:k(g),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:R,participantId:d.id,sourceRefs:[{kind:"external",id:i.id,uri:"popmelt:eval-spec"},...o.map(h=>({kind:"record",id:h}))],recordType:"eval_spec",legacyId:i.id,replacesSpecId:s?.id,...p,targets:o.map(h=>({entityType:"decision",entityId:h})),evaluator:{kind:"ai",name:"Popmelt eval runner",evidenceTypes:["screenshot","dom","code"]},scope:{kind:"current_page"}},w=s?[{id:k(g),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:R,participantId:d.id,sourceRefs:[{kind:"record",id:I.id}],recordType:"relationship",relationshipType:"replaces",from:{entityType:"eval_spec",entityId:I.id},to:{entityType:"eval_spec",entityId:s.id},reason:"A reviewed eval change creates an immutable replacement specification."}]:[];t=await this.store.commit({records:[I],events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:k(g),committedAt:R})}return await this.refreshIndex(t),this.getJournalEvalCases()}async getJournalEvalCases(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Set(e.tombstones.filter(n=>n.objectType==="eval_spec").map(n=>n.objectId)),i=e.records.filter(n=>n.recordType==="eval_spec").reverse().filter((n,c,p)=>p.findIndex(d=>d.legacyId===n.legacyId)===c).filter(n=>!t.has(n.id)),s=e.records.filter(n=>n.recordType==="verification_attempt"),o=e.records.filter(n=>n.recordType==="freshness_signal"&&n.state==="open"&&n.targetKind==="verification_result");return i.map(n=>{let c=s.filter(g=>g.evalSpecId===n.id).sort((g,R)=>R.createdAt.localeCompare(g.createdAt))[0],p=c&&o.some(g=>g.target.entityType==="verification_attempt"&&g.target.entityId===c.id),d=n.state==="draft"?"draft":n.state==="retired"?"retired":c?p?"stale":c.state==="passed"?"passing":c.state==="failed"?"failing":"needs_review":"unverified";return{id:n.legacyId,canonicalSpecId:n.id,verificationState:d,title:n.title,status:n.state==="draft"?"pending":n.state==="active"?"approved":"rejected",category:n.category,prompt:n.prompt,assertions:n.assertions,rationale:n.rationale,sourceDecisionIds:n.decisionIds,sourceThreadIds:n.threadRefs,dependencies:n.dependencies??[],scenarios:n.scenarios??[],verifiedScopeFingerprint:c?.scopeFingerprint,verificationAttemptId:c?.id}})}async findJournalEvalCase(e){return(await this.getJournalEvalCases()).find(t=>t.id===e)??null}async updateJournalEvalCase(e,t){let i=await this.findJournalEvalCase(e);if(!i)return null;let[s]=await this.syncEvalSpecs([{...i,...t}]);return s??null}async getJournalEvalRuns(){if(!(await this.status()).initialized)return[];let{bundle:e}=await this.store.load(),t=new Map(e.records.flatMap(i=>i.recordType==="eval_spec"?[[i.id,i]]:[]));return e.records.flatMap(i=>{if(i.recordType!=="verification_attempt"||!i.evalSpecId)return[];let s=t.get(i.evalSpecId);if(!s)return[];let o=i.evalRun,n=Date.parse(i.createdAt);return[{id:o?.id??i.id,evalId:s.legacyId,threadId:o?.threadId,status:i.state==="passed"?"pass":i.state==="failed"?"fail":"needs_review",createdAt:o?.createdAt??n,completedAt:o?.completedAt??n,durationMs:o?.durationMs??0,scope:o?.scope??{type:"current_page",url:"",viewport:{width:0,height:0}},summary:i.summary??"",assertionResults:o?.assertionResults??s.assertions.map(c=>({assertion:c,status:"needs_review",summary:i.summary??"",evidence:[]})),tooling:o?.tooling??{chromeDevtools:"unknown",evidenceTypes:[]},provider:o?.provider,model:o?.model,screenshotPath:o?.screenshotPath,codeFingerprint:o?.codeFingerprint,scopeFingerprint:i.scopeFingerprint}]}).sort((i,s)=>i.completedAt-s.completedAt)}async recordEvalVerification(e,t){if(!(await this.status()).initialized)return;let i=await this.store.load();if(i.bundle.records.some(I=>I.recordType==="verification_attempt"&&I.evalRun?.id===t.id))return;let s=this.latestEvalSpec(i.bundle,e.id);if(!s)return;let o=i.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active"&&I.kind==="ai")??i.bundle.records.find(I=>I.recordType==="participant"&&I.status==="active");if(!o)return;let n=t.completedAt,c=new Date(n).toISOString(),p={id:k(n),schemaVersion:1,projectId:i.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[{kind:"record",id:s.id},{kind:"external",id:t.id,uri:"popmelt:eval-run"}],recordType:"evidence",kind:"eval",summary:t.summary,availability:"available",artifactIds:[]},d={id:k(n),schemaVersion:1,projectId:i.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[{kind:"record",id:s.id}],recordType:"verification_attempt",evalSpecId:s.id,scopeFingerprint:t.scopeFingerprint,state:t.status==="pass"?"passed":t.status==="fail"?"failed":"inconclusive",evaluator:{kind:"eval",participantId:o.id,name:t.model??t.provider??"Popmelt eval runner"},targets:s.targets,summary:t.summary,evidenceIds:[p.id],evalRun:{id:t.id,threadId:t.threadId,createdAt:t.createdAt,completedAt:t.completedAt,durationMs:t.durationMs,scope:t.scope,assertionResults:t.assertionResults,tooling:t.tooling,provider:t.provider,model:t.model,screenshotPath:t.screenshotPath,codeFingerprint:t.codeFingerprint}},g=s.targets.map(I=>({id:k(n),schemaVersion:1,projectId:i.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[{kind:"record",id:p.id}],recordType:"relationship",relationshipType:"verifies",from:{entityType:"verification_attempt",entityId:d.id},to:I,reason:t.summary})),R=await this.store.commit({records:[p,d],events:[],relationships:g,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:k(n),committedAt:c});await this.refreshIndex(R)}async syncLegacyEvalRuns(e,t){let i=new Map(e.map(s=>[s.id,s]));for(let s of[...t].sort((o,n)=>o.completedAt-n.completedAt)){let o=i.get(s.evalId);o&&await this.recordEvalVerification(o,s)}}async markEvalVerificationExpired(e){if(!(await this.status()).initialized)return;let t=await this.store.load();if(t.bundle.records.some(d=>d.recordType==="freshness_signal"&&d.state==="open"&&d.targetKind==="verification_result"&&d.target.entityType==="verification_attempt"&&d.target.entityId===e.verificationAttemptId))return;let i=t.bundle.records.find(d=>d.recordType==="verification_attempt"&&d.id===e.verificationAttemptId&&d.evalSpecId===e.evalSpecId),s=t.bundle.records.find(d=>d.recordType==="participant"&&d.status==="active"&&d.kind==="system")??t.bundle.records.find(d=>d.recordType==="participant"&&d.status==="active");if(!i||!s)return;let o=Date.now(),n=new Date(o).toISOString(),c={id:k(o),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:n,participantId:s.id,sourceRefs:[{kind:"record",id:e.evalSpecId},{kind:"record",id:i.id}],recordType:"freshness_signal",signalType:"verification_expired",state:"open",targetKind:"verification_result",target:{entityType:"verification_attempt",entityId:i.id},reason:`A dependency changed after this eval passed (${e.previousFingerprint??"unknown"} \u2192 ${e.currentFingerprint??"unknown"}).`,evidenceIds:i.evidenceIds},p=await this.store.commit({records:[c],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:k(o),committedAt:n});await this.refreshIndex(p)}async reconcileEvalCases(e){if(!(await this.status()).initialized)return{valid:e,discardedIds:[]};let t=await this.store.load(),i=new Set(t.bundle.records.flatMap(p=>p.recordType==="decision"&&p.state==="active"?[p.id,...p.sourceRefs.map(d=>d.id)]:[])),s=e.filter(p=>(p.dependencies?.length??0)>0||p.sourceDecisionIds.some(d=>i.has(d))),o=e.filter(p=>!s.includes(p)).map(p=>p.id);if(o.length===0)return{valid:s,discardedIds:o};let n=t.bundle.records.find(p=>p.recordType==="participant"&&p.kind==="human"&&p.status==="active");if(!n)return{valid:s,discardedIds:o};let c=o.flatMap(p=>{let d=this.latestEvalSpec(t.bundle,p);return d?[d]:[]}).filter(p=>!t.bundle.tombstones.some(d=>d.objectType==="eval_spec"&&d.objectId===p.id));if(c.length>0){let p=Date.now(),d=new Date(p).toISOString();t=await this.store.commit({records:[],events:[],relationships:[],artifacts:[],projectionUpdates:[],tombstones:c.map(g=>({id:k(p),schemaVersion:1,projectId:t.bundle.manifest.projectId,objectId:g.id,objectType:"eval_spec",deletedAt:d,deletedById:n.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]}))},{transactionId:k(p),committedAt:d}),await this.refreshIndex(t)}return{valid:s,discardedIds:o}}latestEvalSpec(e,t){return[...e.records].reverse().find(i=>i.recordType==="eval_spec"&&i.legacyId===t)}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),i=t.records.find(s=>s.recordType==="proposal"&&s.state==="pending"&&s.sourceRefs.some(o=>o.id===e));return i?{proposalId:i.id,claim:i.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(),i=t.bundle.records.find(h=>h.recordType==="model_projection"&&h.state==="applied"&&h.runId===e.runId);if(i)return{projectionId:i.id,entryIds:i.entryIds,headSequence:t.report.headSequence};let s=t.bundle.records.filter(h=>h.recordType==="decision"&&e.decisionIds.includes(h.id)&&h.state==="active");if(s.length!==new Set(e.decisionIds).size)throw new Error("Model projection references a missing or inactive canonical decision.");let o=t.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!o)throw new Error("No active local owner participant is available.");let n=Date.now(),c=new Date(n).toISOString(),p=k(n),d=e.changes.map(h=>{let a=h.decisionIds?.filter(f=>e.decisionIds.includes(f)),y=a?.length?a:e.decisionIds,m=[...new Set(s.filter(f=>y.includes(f.id)).flatMap(f=>f.subjects.map(l=>l.subjectId)))];return{id:k(n),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:y.map(f=>({kind:"record",id:f})),recordType:"model_entry",key:h.path.map(String).join("."),subjectIds:m,decisionIds:y,value:h.value}}),g=new Set(d.flatMap(h=>h.decisionIds)),R={id:p,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:e.decisionIds.map(h=>({kind:"record",id:h})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:o.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:c,decisionIds:e.decisionIds,entryIds:d.map(h=>h.id),coverage:e.decisionIds.map(h=>e.coverage?.find(a=>a.decisionId===h)??{decisionId:h,status:g.has(h)?"projected":"unprojected"})},I=d.flatMap(h=>h.decisionIds.map(a=>({id:k(n),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:c,participantId:o.id,sourceRefs:[{kind:"record",id:R.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:h.id},to:{entityType:"decision",entityId:a},reason:"The owner applied this model entry as a projection of accepted product truth."}))),w=await this.store.commit({records:[...d,R],events:[],relationships:I,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:k(n),committedAt:c});return await this.refreshIndex(w),{projectionId:p,entryIds:d.map(h=>h.id),headSequence:w.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 je({...e,projectRoot:this.projectRoot})).bundle}}async withIndexedCandidates(e,t){if(e.source!=="journal"||!e.journal)return t;let i=await this.indexStore.ensure(e.bundle,{sequence:e.journal.headSequence,hash:e.journal.headHash}),s=at(i,t.subjectHints??[]);return s?{...t,subjectIds:[...new Set([...t.subjectIds??[],...s.subjectIds])],candidateDecisionIds:s.decisionIds,candidateProposalIds:s.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 ue(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected a JSON object.");return r}function $(r,e){if(typeof r!="string"||!r.trim())throw new Error(`${e} must be a non-empty string.`);return r}function le(r,e,t){let i=$(r,e);if(!t.includes(i))throw new Error(`${e} is invalid.`);return i}function Zt(r){let e=ue(r),t=ue(e.authority),i=t.level,s=t.mode,o=le(i,"authority.level",["owner","delegate","contributor"]),n=le(s,"authority.mode",["local_trusted","hosted"]),c={proposalId:$(e.proposalId,"proposalId"),participantId:$(e.participantId,"participantId"),occurredAt:$(e.occurredAt,"occurredAt"),authority:{level:o,mode:n,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...c,action:"accept",eventId:$(e.eventId,"eventId"),decisionId:$(e.decisionId,"decisionId"),kind:le(e.kind,"kind",["principle","preference","rule","constraint"]),reason:$(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...c,action:"reject",eventId:$(e.eventId,"eventId"),reason:$(e.reason,"reason")};case"defer":{let p=ue(e.context);if(!Array.isArray(p.subjectIds)||!Array.isArray(p.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...c,action:"defer",eventId:$(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof p.taskContext=="string"?p.taskContext:void 0,subjectIds:p.subjectIds.map(d=>$(d,"subjectId")),resurfaceWhen:p.resurfaceWhen.map(d=>le(d,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof p.revisitAfter=="string"?p.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:$(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:$(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:$(e.acceptanceEventId,"acceptanceEventId"),decisionId:$(e.decisionId,"decisionId"),relationshipId:$(e.relationshipId,"relationshipId"),claim:$(e.claim,"claim"),kind:le(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(p=>{let d=ue(p);return{subjectId:$(d.subjectId,"subjectId"),role:le(d.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:$(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function ei(r){let e=ue(r),t=(o,n)=>{if(o!==void 0){if(!Array.isArray(o))throw new Error(`${n} must be an array.`);return o.map(c=>$(c,n))}},i=(o,n)=>{if(o!==void 0){if(typeof o!="number"||!Number.isFinite(o)||o<=0)throw new Error(`${n} must be a positive number.`);return o}},s=e.resurface===void 0?void 0:ue(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:i(e.maxPackets,"maxPackets"),maxEstimatedTokens:i(e.maxEstimatedTokens,"maxEstimatedTokens"),generatedAt:typeof e.generatedAt=="string"?e.generatedAt:void 0,resurface:s?{differentAction:s.differentAction===!0,newEvidence:s.newEvidence===!0,newConflict:s.newConflict===!0,ownerRequested:s.ownerRequested===!0}:void 0}}export{ge as MemoryJournalStore,He as MemoryService,Be as computeTransactionHash,ei as parseContextualReviewQuery,Zt as parseOwnerReviewCommand};
|