@popmelt.com/core 0.27.0 → 0.28.0
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/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/ParticipantRuntime-4NMUTZL3.mjs +139 -0
- package/dist/PopmeltTasteConnectedPane-ZMJXKDPJ.mjs +221 -0
- package/dist/PreviewRuntime-AZAHK27Q.mjs +2 -0
- package/dist/bridge-entry.mjs +2 -229
- package/dist/browser-runtime-57XUOV3C.mjs +2 -0
- package/dist/browser.mjs +1 -1
- package/dist/chunk-3LBOX7HQ.mjs +3 -0
- package/dist/chunk-BISCKKOX.mjs +2 -0
- package/dist/chunk-DPSBNNGU.mjs +2 -0
- package/dist/chunk-GL4I4MI6.mjs +3 -0
- package/dist/chunk-HGW2U6PD.mjs +2 -0
- package/dist/chunk-HPQJKWK5.mjs +1 -0
- package/dist/chunk-JNR6PO2Z.mjs +369 -0
- package/dist/chunk-LVEMYZOA.mjs +2 -0
- package/dist/chunk-M3MBL5NR.mjs +2 -0
- package/dist/chunk-O4HZP3RP.mjs +2 -0
- package/dist/chunk-PKTQWFUA.mjs +2 -0
- package/dist/chunk-Q5PC5FWC.mjs +347 -0
- package/dist/chunk-QXVMGZFP.mjs +1 -0
- package/dist/chunk-R5RMIYS5.mjs +77 -0
- package/dist/chunk-WNZFCDVR.mjs +289 -0
- package/dist/chunk-XTOCFTVW.mjs +2 -0
- package/dist/{chunk-C5Q6LDAS.mjs → chunk-YBULEE33.mjs} +1 -1
- package/dist/chunk-YIAZGECE.mjs +2 -0
- package/dist/cli.mjs +169 -106
- package/dist/focus-inspection-ZKWDPDRI.mjs +2 -0
- package/dist/index-CHp2bgs1.d.mts +565 -0
- package/dist/index.mjs +1 -1
- package/dist/memory-legacy.d.mts +1 -489
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +2 -660
- package/dist/memory-store.mjs +1 -3
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-nuxt.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server.d.mts +3 -291
- package/dist/server.mjs +7 -234
- package/dist/taste-proposal-session-XU4N7RUV.mjs +2 -0
- package/dist/types-Bur49CLH.d.mts +349 -0
- package/dist/workspace-snapshot-EJQHHDQ4.mjs +2 -0
- package/package.json +23 -25
- package/dist/ParticipantRuntime-AD3YD4FW.mjs +0 -139
- package/dist/PopmeltTasteConnectedPane-HLCTVPJP.mjs +0 -81
- package/dist/PreviewRuntime-KGLZJGUN.mjs +0 -2
- package/dist/browser-runtime-3JZGB3P2.mjs +0 -2
- package/dist/chunk-7YCLSSQA.mjs +0 -2
- package/dist/chunk-7YIQQYRU.mjs +0 -77
- package/dist/chunk-D7HY2EDH.mjs +0 -2
- package/dist/chunk-MDJYUX5S.mjs +0 -370
- package/dist/chunk-MTRUVFH7.mjs +0 -1
- package/dist/chunk-TFPKDKDO.mjs +0 -345
- package/dist/chunk-TSY2K45H.mjs +0 -2
- package/dist/server-MJF4KF26.mjs +0 -241
package/dist/memory-store.mjs
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{createHash as Mt}from"crypto";import{mkdir as tt,open as ze,readFile as Le,readdir as _t,rename as $t,unlink as Ve}from"fs/promises";import{join as K}from"path";var jt=/^[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(n){return jt.test(n)}function Rt(n){return{valid:!n.some(e=>e.severity==="error"),issues:n}}function A(n,e,t,i){n.push({path:e,code:t,message:i,severity:"error"})}function Je(n,e,t,i){n.push({path:e,code:t,message:i,severity:"warning"})}function B(n,e,t){ae(t)||A(n,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function H(n,e,t){(!t||Number.isNaN(Date.parse(t)))&&A(n,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function X(n,e,t,i=!1){i&&t.level==="contributor"&&A(n,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),t.level==="delegate"&&!t.grantId&&A(n,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var xt={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"])},Tt=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function St(n,e,t){B(n,`${t}.id`,e.id),B(n,`${t}.projectId`,e.projectId),B(n,`${t}.participantId`,e.participantId),B(n,`${t}.entity.entityId`,e.entity.entityId),H(n,`${t}.createdAt`,e.createdAt),X(n,`${t}.authority`,e.authority);let i=xt[e.entity.entityType],r=`${e.fromState??"null"}->${e.toState}`;i&&!i.has(r)&&A(n,t,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${r}.`);let c=`${e.entity.entityType}:${e.toState}`;if(Tt.has(c)&&(X(n,`${t}.authority`,e.authority,!0),e.reason?.trim()||A(n,`${t}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let d=e.transitionContext;(d?.kind!=="proposal_deferral"||d.resurfaceWhen.length===0)&&A(n,`${t}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),d?.resurfaceWhen.includes("after_date")&&!d.revisitAfter&&A(n,`${t}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),d?.revisitAfter&&H(n,`${t}.transitionContext.revisitAfter`,d.revisitAfter)}}function kt(n,e,t,i){B(n,`${t}.id`,e.id),B(n,`${t}.projectId`,e.projectId),B(n,`${t}.participantId`,e.participantId),H(n,`${t}.createdAt`,e.createdAt),e.projectId!==i&&A(n,`${t}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&A(n,`${t}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&A(n,`${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)&&A(n,`${t}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&(X(n,`${t}.authority`,e.authority,!0),e.claim.trim()||A(n,`${t}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&Je(n,`${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())&&A(n,t,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),H(n,`${t}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&A(n,`${t}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(r=>!r.trim())&&A(n,`${t}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((r,c)=>{(!r.id.trim()||!r.modelPath.trim())&&A(n,`${t}.concreteBindings[${c}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),H(n,`${t}.concreteBindings[${c}].createdAt`,r.createdAt),H(n,`${t}.concreteBindings[${c}].updatedAt`,r.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&A(n,t,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(H(n,`${t}.appliedAt`,e.appliedAt),X(n,`${t}.authority`,e.authority,!0),e.entryIds.length===0&&A(n,`${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())&&A(n,t,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(r=>!r.trim()))&&A(n,`${t}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&Je(n,t,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&Je(n,`${t}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function At(n,e,t){if(B(n,`${t}.id`,e.id),B(n,`${t}.projectId`,e.projectId),B(n,`${t}.participantId`,e.participantId),B(n,`${t}.from.entityId`,e.from.entityId),B(n,`${t}.to.entityId`,e.to.entityId),e.from.storeId!==void 0&&!e.from.storeId.trim()&&A(n,`${t}.from.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),e.to.storeId!==void 0&&!e.to.storeId.trim()&&A(n,`${t}.to.storeId`,"invalid_store_reference","Qualified store IDs cannot be empty."),H(n,`${t}.createdAt`,e.createdAt),e.reason.trim()||A(n,`${t}.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",c=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!r&&!c&&A(n,t,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),r&&!e.authority?A(n,`${t}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):r&&e.authority&&X(n,`${t}.authority`,e.authority,!0)}["expresses","operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&A(n,t,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&A(n,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))&&A(n,t,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&A(n,t,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function Z(n){let e=[];B(e,"manifest.projectId",n.manifest.projectId),H(e,"manifest.createdAt",n.manifest.createdAt),H(e,"manifest.updatedAt",n.manifest.updatedAt);let t=new Map,i=(a,p)=>{let u=t.get(a);u?A(e,p,"duplicate_id",`ID is already used at ${u}.`):t.set(a,p)};n.records.forEach((a,p)=>{let u=`records[${p}]`;i(a.id,u),kt(e,a,u,n.manifest.projectId)}),n.events.forEach((a,p)=>{let u=`events[${p}]`;i(a.id,u),St(e,a,u),a.projectId!==n.manifest.projectId&&A(e,`${u}.projectId`,"project_mismatch","Event belongs to another project.")}),n.relationships.forEach((a,p)=>{let u=`relationships[${p}]`;i(a.id,u),At(e,a,u),a.projectId!==n.manifest.projectId&&A(e,`${u}.projectId`,"project_mismatch","Relationship belongs to another project.")}),n.artifacts.forEach((a,p)=>{i(a.id,`artifacts[${p}]`),B(e,`artifacts[${p}].id`,a.id)}),n.tombstones.forEach((a,p)=>{let u=`tombstones[${p}]`;i(a.id,u),B(e,`${u}.id`,a.id),B(e,`${u}.objectId`,a.objectId),B(e,`${u}.deletedById`,a.deletedById),H(e,`${u}.deletedAt`,a.deletedAt),X(e,`${u}.authority`,a.authority,!0)});let r=new Set(n.records.map(a=>`${a.recordType}:${a.id}`)),c=new Set(n.tombstones.map(a=>`${a.objectType}:${a.objectId}`)),d=(a,p)=>{if(a.storeId)return;let u=`${a.entityType}:${a.entityId}`;!r.has(u)&&!c.has(u)&&A(e,p,"dangling_entity_reference",`No record or tombstone exists for ${u}.`)};n.events.forEach((a,p)=>d(a.entity,`events[${p}].entity`)),n.relationships.forEach((a,p)=>{d(a.from,`relationships[${p}].from`),d(a.to,`relationships[${p}].to`)});let m=new Set(n.artifacts.map(a=>a.id)),y=(a,p)=>{m.has(a)||A(e,p,"dangling_artifact_reference","No artifact manifest entry exists.")},f=(a,p,u)=>{!r.has(`${a}:${p}`)&&!c.has(`${a}:${p}`)&&A(e,u,"dangling_entity_reference",`No ${a} record or tombstone exists.`)};n.records.forEach((a,p)=>{let u=`records[${p}]`;switch(a.recordType){case"authority_grant":f("participant",a.granteeId,`${u}.granteeId`),f("participant",a.grantedById,`${u}.grantedById`),a.subjectIds.forEach((l,o)=>f("subject",l,`${u}.subjectIds[${o}]`));break;case"observation":a.captureContext.subjectIds.forEach((l,o)=>f("subject",l,`${u}.captureContext.subjectIds[${o}]`)),a.captureContext.artifactIds.forEach((l,o)=>y(l,`${u}.captureContext.artifactIds[${o}]`));break;case"proposal":case"decision":a.subjects.forEach((l,o)=>f("subject",l.subjectId,`${u}.subjects[${o}].subjectId`));break;case"thread":a.messageArtifactIds.forEach((l,o)=>y(l,`${u}.messageArtifactIds[${o}]`)),a.resultRefs.forEach((l,o)=>d(l,`${u}.resultRefs[${o}]`));break;case"iteration":a.threadIds.forEach((l,o)=>f("thread",l,`${u}.threadIds[${o}]`)),a.artifactIds.forEach((l,o)=>y(l,`${u}.artifactIds[${o}]`));break;case"evidence":a.artifactIds.forEach((l,o)=>y(l,`${u}.artifactIds[${o}]`));break;case"advisory_explanation":a.subjectIds.forEach((l,o)=>f("subject",l,`${u}.subjectIds[${o}]`)),a.evidenceIds.forEach((l,o)=>f("evidence",l,`${u}.evidenceIds[${o}]`)),a.supersededById&&f("advisory_explanation",a.supersededById,`${u}.supersededById`);break;case"implementation_attempt":a.iterationIds.forEach((l,o)=>f("iteration",l,`${u}.iterationIds[${o}]`)),a.coverageClaims.forEach((l,o)=>f("decision",l.decisionId,`${u}.coverageClaims[${o}].decisionId`)),a.artifactIds.forEach((l,o)=>y(l,`${u}.artifactIds[${o}]`));break;case"eval_spec":a.replacesSpecId&&f("eval_spec",a.replacesSpecId,`${u}.replacesSpecId`),a.decisionIds.forEach((l,o)=>f("decision",l,`${u}.decisionIds[${o}]`)),a.subjectIds.forEach((l,o)=>f("subject",l,`${u}.subjectIds[${o}]`)),(a.dependencies??[]).forEach((l,o)=>{l.kind==="subject"&&l.subjectId&&f("subject",l.subjectId,`${u}.dependencies[${o}].subjectId`)}),(a.scenarios??[]).forEach((l,o)=>{l.subjectIds?.forEach((g,I)=>f("subject",g,`${u}.scenarios[${o}].subjectIds[${I}]`))}),a.targets.forEach((l,o)=>f(l.entityType,l.entityId,`${u}.targets[${o}]`));break;case"verification_attempt":a.evalSpecId&&f("eval_spec",a.evalSpecId,`${u}.evalSpecId`),a.targets.forEach((l,o)=>f(l.entityType,l.entityId,`${u}.targets[${o}]`)),a.evidenceIds.forEach((l,o)=>f("evidence",l,`${u}.evidenceIds[${o}]`));break;case"model_entry":a.subjectIds.forEach((l,o)=>f("subject",l,`${u}.subjectIds[${o}]`)),a.decisionIds.forEach((l,o)=>f("decision",l,`${u}.decisionIds[${o}]`));break;case"model_projection":X(e,`${u}.authority`,a.authority,!0),f("participant",a.appliedById,`${u}.appliedById`),a.decisionIds.forEach((l,o)=>f("decision",l,`${u}.decisionIds[${o}]`)),a.entryIds.forEach((l,o)=>f("model_entry",l,`${u}.entryIds[${o}]`)),a.coverage.forEach((l,o)=>f("decision",l.decisionId,`${u}.coverage[${o}].decisionId`));break;case"freshness_signal":d(a.target,`${u}.target`),a.evidenceIds.forEach((l,o)=>f("evidence",l,`${u}.evidenceIds[${o}]`));break;default:break}});let x=new Map(n.events.map(a=>[a.id,a])),T=new Map(n.records.map(a=>[`${a.recordType}:${a.id}`,a])),v=new Map;n.events.forEach((a,p)=>{let u=`${a.entity.entityType}:${a.entity.entityId}:${a.fromState??"null"}`,l=v.get(u)??new Set;l.add(a.toState),v.set(u,l),l.size>1&&A(e,`events[${p}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let w=new Map(n.records.flatMap(a=>a.recordType==="authority_grant"?[[a.id,a]]:[])),h=(a,p,u,l,o)=>{if(a.level!=="delegate"||!a.grantId)return;let g=w.get(a.grantId);if(!g){A(e,o,"invalid_authority_grant","Delegated authority references a missing grant.");return}(g.granteeId!==p||g.level!=="delegate")&&A(e,o,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let I=Date.parse(u);(I<Date.parse(g.startsAt)||g.endsAt&&I>Date.parse(g.endsAt)||g.revokedAt&&I>=Date.parse(g.revokedAt))&&A(e,o,"inactive_authority_grant","The delegated authority grant was not active at this time."),g.subjectIds.length&&l.length&&!l.every(s=>g.subjectIds.includes(s))&&A(e,o,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let a of n.records)a.recordType==="decision"&&h(a.authority,a.acceptedById,a.createdAt,a.subjects.map(p=>p.subjectId),`records:${a.id}.authority`);n.events.forEach((a,p)=>{let u=T.get(`${a.entity.entityType}:${a.entity.entityId}`),l=u&&"subjects"in u?u.subjects.map(o=>o.subjectId):[];h(a.authority,a.participantId,a.createdAt,l,`events[${p}].authority`)}),n.relationships.forEach((a,p)=>{if(!a.authority)return;let u=[a.from,a.to].flatMap(l=>{let o=T.get(`${l.entityType}:${l.entityId}`);return o&&"subjects"in o?o.subjects.map(g=>g.subjectId):[]});h(a.authority,a.participantId,a.createdAt,u,`relationships[${p}].authority`)});for(let a of n.records){if(a.recordType!=="decision")continue;let p=x.get(a.acceptanceEventId);(!p||p.entity.entityType!=="proposal"||p.entity.entityId!==a.proposalId||p.toState!=="accepted")&&A(e,`records:${a.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),p&&p.participantId!==a.acceptedById&&A(e,`records:${a.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${a.proposalId}`)||A(e,`records:${a.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),a.state==="superseded"&&(n.relationships.some(l=>l.relationshipType==="supersedes"&&l.to.entityType==="decision"&&l.to.entityId===a.id)||A(e,`records:${a.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),a.state==="revoked"&&(n.events.some(l=>l.entity.entityType==="decision"&&l.entity.entityId===a.id&&l.toState==="revoked"&&!!l.reason?.trim())||A(e,`records:${a.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let a of n.records){if(a.recordType!=="proposal"||a.state!=="accepted")continue;n.records.some(u=>u.recordType==="decision"&&u.proposalId===a.id)||A(e,`records:${a.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Rt(e)}var Pt={records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]};function Me(n){return Mt("sha256").update(JSON.stringify(n)).digest("hex")}function Ne(n){return Me(n)}function nt(n,e,t){[...e.records,...e.recordReplacements??[]].some(i=>i.recordType==="advisory_explanation")&&!n.manifest.features.includes("advisory_explanations")&&n.manifest.features.push("advisory_explanations");for(let i of e.recordReplacements??[]){if(i.recordType!=="advisory_explanation")throw new Error(`Record replacement is not supported for ${i.recordType}.`);let r=n.records.findIndex(d=>d.recordType===i.recordType&&d.id===i.id);if(r<0)throw new Error(`Record replacement target not found: ${i.recordType} ${i.id}`);let c=n.records[r];if(c.projectId!==i.projectId||c.createdAt!==i.createdAt||c.participantId!==i.participantId)throw new Error(`Record replacement changed immutable identity for ${i.id}.`);n.records[r]=structuredClone(i)}for(let i of e.projectionUpdates){let r=n.records.find(c=>c.recordType===i.entityType&&c.id===i.entityId);if(!r||r.recordType!=="proposal"&&r.recordType!=="decision")throw new Error(`Projection target not found: ${i.entityType} ${i.entityId}`);if(r.state!==i.fromState)throw new Error(`Projection state conflict for ${i.entityType} ${i.entityId}: expected ${i.fromState}, found ${r.state}`);r.state=i.state}return n.records.push(...e.records),n.events.push(...e.events),n.relationships.push(...e.relationships),n.artifacts.push(...e.artifacts),n.tombstones.push(...e.tombstones),n.manifest.updatedAt=t,n}function Et(n,e,t){return nt(structuredClone(n),e,t)}async function ee(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,i=await ze(t,"w");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
2
|
-
`,"utf8"),await i.sync()}finally{await i.close()}try{await $t(t,n)}catch(r){throw await Ve(t).catch(()=>{}),r}}async function ve(n){return JSON.parse(await Le(n,"utf8"))}var we=class{constructor(e){this.writeChain=Promise.resolve();this.memoryDir=K(e,".popmelt","memory"),this.journalDir=K(this.memoryDir,"journal"),this.manifestPath=K(this.memoryDir,"manifest.json"),this.checkpointPath=K(this.memoryDir,"checkpoint.json"),this.lockPath=K(this.memoryDir,"writer.lock")}async readHead(){let e=await ve(this.manifestPath);return{...e.head,checkpointSequence:e.checkpoint.sequence,checkpointHash:e.checkpoint.hash}}async initialize(e){let t=Z(e);if(!t.valid)throw new Error(`Cannot initialize invalid memory bundle: ${JSON.stringify(t.issues)}`);await tt(this.journalDir,{recursive:!0});try{throw await Le(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 Le(this.manifestPath,"utf8"),new Error("Memory journal is already initialized.")}catch(d){if(d instanceof Error&&d.message==="Memory journal is already initialized."||d.code!=="ENOENT")throw d}let i=Me(e),r={storageVersion:1,sequence:0,hash:i,journalHash:null,bundle:e},c={storageVersion:1,projectId:e.manifest.projectId,checkpoint:{file:"checkpoint.json",sequence:0,hash:i},head:{sequence:0,hash:null},updatedAt:e.manifest.updatedAt};await ee(this.checkpointPath,r),await ee(this.manifestPath,c)})}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 ee(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=Me(e.bundle),i=`checkpoint-${String(e.report.headSequence).padStart(12,"0")}.json`,r={storageVersion:1,sequence:e.report.headSequence,hash:t,journalHash:e.report.headHash,bundle:e.bundle};return await ee(K(this.memoryDir,i),r),e.manifest.checkpoint={file:i,sequence:r.sequence,hash:t},await ee(this.manifestPath,e.manifest),{bundle:e.bundle,report:{...e.report,checkpointSequence:r.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 r=i.report.headSequence+1,c={storageVersion:1,sequence:r,transactionId:t.transactionId,projectId:i.bundle.manifest.projectId,committedAt:t.committedAt,previousHash:i.report.headHash,mutation:e},d={...c,hash:Ne(c)},m=Et(i.bundle,e,t.committedAt),y=Z(m);if(!y.valid)throw new Error(`Journal mutation produces invalid memory: ${JSON.stringify(y.issues)}`);let f=`${String(r).padStart(12,"0")}-${t.transactionId}.json`;return await ee(K(this.journalDir,f),d),i.manifest.head={sequence:r,hash:d.hash},i.manifest.updatedAt=t.committedAt,await ee(this.manifestPath,i.manifest),{bundle:m,report:{checkpointSequence:i.report.checkpointSequence,appliedTransactions:i.report.appliedTransactions+1,recoveredTransactions:0,ignoredTemporaryFiles:i.report.ignoredTemporaryFiles,headSequence:r,headHash:d.hash}}}))}async commitReviewPlan(e,t){return this.commit({...Pt,records:e.append.records,events:e.append.events,relationships:e.append.relationships,projectionUpdates:e.projectionUpdates},t)}async loadInternal(){let e=await ve(this.manifestPath),t=await ve(K(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!==Me(t.bundle)||t.hash!==e.checkpoint.hash)throw new Error("Memory checkpoint hash mismatch.");let i=await _t(this.journalDir),r=i.filter(v=>v.endsWith(".tmp")),d=i.filter(v=>/^\d{12}-[0-9a-f-]+\.json$/i.test(v)).sort().filter(v=>Number(v.slice(0,12))>t.sequence),m=structuredClone(t.bundle),y=t.sequence,f=t.journalHash??null,x=new Set;for(let v of d){let w=await ve(K(this.journalDir,v)),{hash:h,...a}=w;if(h!==Ne(a))throw new Error(`Journal hash mismatch: ${v}`);if(w.sequence!==y+1)throw new Error(`Journal sequence gap at ${v}`);if(w.previousHash!==f)throw new Error(`Journal chain mismatch at ${v}`);if(w.projectId!==e.projectId)throw new Error(`Journal project mismatch at ${v}`);if(x.has(w.transactionId))throw new Error(`Duplicate transaction ID: ${w.transactionId}`);nt(m,w.mutation,w.committedAt),y=w.sequence,f=w.hash,x.add(w.transactionId)}if(e.head.sequence>y)throw new Error("Journal manifest points beyond available transactions.");if(e.head.sequence===y&&e.head.hash!==f)throw new Error("Journal manifest head hash mismatch.");let T=Z(m);if(!T.valid)throw new Error(`Loaded journal is invalid: ${JSON.stringify(T.issues)}`);return{bundle:m,manifest:e,transactionIds:x,report:{checkpointSequence:t.sequence,appliedTransactions:d.length,recoveredTransactions:Math.max(0,y-e.head.sequence),ignoredTemporaryFiles:r.length,headSequence:y,headHash:f}}}enqueueWrite(e){let t=this.writeChain.then(e,e);return this.writeChain=t.then(()=>{},()=>{}),t}async withWriterLock(e){await tt(this.memoryDir,{recursive:!0});let t;try{t=await ze(this.lockPath,"wx")}catch(i){if(i.code!=="EEXIST")throw i;let r=await ve(this.lockPath).catch(()=>({})),c=!0;if(typeof r.pid=="number")try{process.kill(r.pid,0)}catch(d){c=d.code!=="ESRCH"}if(c)throw new Error("Memory journal is locked by another writer.");await Ve(this.lockPath),t=await ze(this.lockPath,"wx")}try{return await t.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await e()}finally{await t.close(),await Ve(this.lockPath).catch(()=>{})}}};import{mkdir as yt,readFile as xe,writeFile as ht}from"fs/promises";import{join as pe}from"path";var it={project:0,route:1,component:2,selector:2,file:3},rt={intention:0,principle:1,pattern:2};function Ct(n,e){let t=it[n.scope.kind]-it[e.scope.kind];return t!==0?t:rt[n.kind]-rt[e.kind]}function Dt(n,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=n.explanations.find(c=>c.id===e.fromId),i=n.explanations.find(c=>c.id===e.toId);if(!t||!i)return;let r=Ct(t,i);return r===0?void 0:r>0?{...structuredClone(e),type:"expresses"}:{...structuredClone(e),type:"expresses",fromId:e.toId,toId:e.fromId}}}function _e(n){let e=structuredClone(n),t=new Set;return e.relations=n.relations.flatMap(i=>{let r=Dt(n,i);if(!r)return[];let c=`${r.type}:${r.fromId}:${r.toStoreId??""}:${r.toId}`;return t.has(c)?[]:(t.add(c),[r])}),e}var Bt=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function He(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function $e(n){return new Set(He(n).split(" ").filter(e=>e.length>2&&!Bt.has(e)))}function ot(n,e){if(!n.size||!e.size)return 0;let t=0;for(let i of n)e.has(i)&&(t+=1);return t/Math.min(n.size,e.size)}function Ot(n,e){let t=new Set(e.subjectIds??[]),i=(e.subjectHints??[]).map(He).filter(Boolean),r=$e([e.action,e.text].filter(Boolean).join(" ")),c=[];for(let d of n){if(t.has(d.id)){c.push({subjectId:d.id,subjectType:d.subjectType,label:d.label,confidence:"exact",matchedBy:"id",score:100});continue}let m,y=[{value:d.label,by:"semantic"},...d.aliases.map(f=>({value:f,by:"alias"})),...d.locators.map(f=>({value:f.value,by:"locator"}))];for(let f of y){let x=He(f.value);for(let w of i){let h=x===w?95:x.includes(w)||w.includes(x)?75:0;h>(m?.score??0)&&(m={subjectId:d.id,subjectType:d.subjectType,label:d.label,confidence:h>=90?"exact":"strong",matchedBy:f.by,score:h})}let v=["/","#","[","]","="].some(w=>f.value.includes(w))?0:Math.round(ot($e(x),r)*55);v>=30&&v>(m?.score??0)&&(m={subjectId:d.id,subjectType:d.subjectType,label:d.label,confidence:v>=45?"strong":"weak",matchedBy:"semantic",score:v})}m&&c.push(m)}return c.sort((d,m)=>m.score-d.score||d.subjectId.localeCompare(m.subjectId))}function qt(n){return Math.ceil(JSON.stringify(n).length/4)}function ce(n,e){return n.relationshipType===e&&n.from.entityType==="decision"&&n.to.entityType==="decision"}function Jt(n,e){let t=e.filter(c=>c.coverageClaims.some(d=>d.decisionId===n));if(!t.length)return{decisionId:n,state:"unimplemented",attemptIds:[]};let i=t.filter(c=>c.state==="completed"),r=i.some(c=>c.coverageClaims.some(d=>d.decisionId===n&&d.coverage==="full"));return{decisionId:n,state:r?"implemented":i.length?"partial":"unknown",attemptIds:t.map(c=>c.id)}}function zt(n,e,t){let i=e.filter(m=>m.targets.some(y=>y.entityType==="decision"&&y.entityId===n)).sort((m,y)=>y.createdAt.localeCompare(m.createdAt)),r=t.some(m=>m.signalType==="verification_expired"&&m.target.entityType==="decision"&&m.target.entityId===n),c=i[0],d=r?"stale":c?c.state==="passed"?"passing":c.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(c.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:n},state:d,attemptIds:i.map(m=>m.id)}}function st(n,e){let t=Math.max(300,e.maxEstimatedTokens??1200),i=Math.max(1,e.maxDecisions??6),r=n.records.filter(s=>s.recordType==="subject"),c=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,d=n.records.filter(s=>s.recordType==="decision"&&s.state==="active"),m=c?d.filter(s=>c.has(s.id)):d,y=n.records.filter(s=>s.recordType==="implementation_attempt"),f=n.records.filter(s=>s.recordType==="verification_attempt"),x=n.records.filter(s=>s.recordType==="freshness_signal"&&s.state==="open"),T=n.records.filter(s=>s.recordType==="evidence"),v=n.records.filter(s=>s.recordType==="model_entry"),w=Ot(r,e),h=new Map(w.map(s=>[s.subjectId,s.score])),a=$e([e.action,e.text].filter(Boolean).join(" ")),p=m.flatMap(s=>{let S=Math.max(0,...s.subjects.map(P=>h.get(P.subjectId)??0)),k=Math.round(ot($e(s.claim),a)*35),b=S+k;return b>=50?[{decision:s,score:b}]:[]}).sort((s,S)=>S.score-s.score||s.decision.id.localeCompare(S.decision.id)),u=new Map;for(let s of p.slice(0,i))u.set(s.decision.id,s.decision);for(let s of n.relationships){if(!ce(s,"excepts")&&!ce(s,"contradicts"))continue;let S=d.find(b=>b.id===s.from.entityId),k=d.find(b=>b.id===s.to.entityId);!S||!k||!u.has(S.id)&&!u.has(k.id)||(u.size<i&&u.set(S.id,S),u.size<i&&u.set(k.id,k))}let l=[...u.values()],o=s=>s.from.entityType==="decision"&&s.to.entityType==="decision"&&u.has(s.from.entityId)&&u.has(s.to.entityId),g=(s,S=!1)=>{let k=new Set(s.map(j=>j.id)),b=x.filter(j=>j.target.entityType==="decision"&&k.has(j.target.entityId)),P=new Set(n.relationships.filter(j=>ce(j,"excepts")&&k.has(j.from.entityId)&&k.has(j.to.entityId)).flatMap(j=>[j.from.entityId,j.to.entityId])),F=n.relationships.filter(j=>ce(j,"contradicts")&&k.has(j.from.entityId)&&k.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}]})),Be=new Set(F.flatMap(j=>j.decisionIds)),te=T.filter(j=>j.sourceRefs.some(R=>R.kind==="record"&&k.has(R.id))||n.relationships.some(R=>R.relationshipType==="supports"&&R.from.entityType==="evidence"&&R.from.entityId===j.id&&R.to.entityType==="decision"&&k.has(R.to.entityId))),fe=Math.max(0,p.length-s.length),Q=n.relationships.some(j=>ce(j,"contradicts")&&o(j)&&(!k.has(j.from.entityId)||!k.has(j.to.entityId))),ye=S||fe>0||Q,W=[];w.length===0&&(e.subjectHints?.length??0)>0?W.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):s.length===0&&W.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),F.length&&W.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:F.flatMap(j=>j.expansionRefs)}),te.some(j=>j.availability!=="available")&&W.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:te.map(j=>({kind:"record",id:j.id}))}),ye&&W.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:n.manifest.projectId}]});let ke={contractVersion:1,projectId:n.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:t,estimatedTokens:0},subjectMatches:w.map(({score:j,...R})=>R),modelEntries:v.filter(j=>j.decisionIds.some(R=>k.has(R))).map(j=>({id:j.id,key:j.key,value:j.value,decisionIds:j.decisionIds})),decisions:s.map(j=>({id:j.id,kind:j.kind,claim:j.claim,subjectIds:j.subjects.map(R=>R.subjectId),authority:j.authority,effectiveState:Be.has(j.id)?"conflicted":P.has(j.id)?"excepted":"active",freshness:b.filter(R=>R.target.entityId===j.id).map(R=>R.signalType),expansionRef:{kind:"record",id:j.id}})),conflicts:F,uncertainties:W,implementation:s.map(j=>Jt(j.id,y)),verification:s.map(j=>zt(j.id,f,b)),evidence:te.map(j=>({evidenceId:j.id,summary:j.summary,availability:j.availability,sourceRefs:j.sourceRefs})),completeness:{status:ye?"truncated":"complete",omittedDecisionCount:fe,omittedEvidenceCount:0,conflictsComplete:!Q}};return ke.budget.estimatedTokens=qt(ke),ke},I=g(l);for(;I.budget.estimatedTokens>t&&l.length>0;){let s=l.pop(),S=n.relationships.filter(k=>ce(k,"contradicts")&&(k.from.entityId===s.id||k.to.entityId===s.id)).flatMap(k=>[k.from.entityId,k.to.entityId]);l=l.filter(k=>!S.includes(k.id)),I=g(l,!0)}return I}var Lt=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function Ue(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function Pe(n){return new Set(Ue(n).split(" ").filter(e=>e.length>2&&!Lt.has(e)))}function at(n,e){if(!n.size||!e.size)return 0;let t=0;for(let i of n)e.has(i)&&(t+=1);return t/Math.min(n.size,e.size)}function Vt(n){return[{value:n.label,by:"label"},...n.aliases.map(e=>({value:e,by:"alias"})),...n.locators.map(e=>({value:e.value,by:"locator"}))]}function Nt(n,e){let t=new Map,i=new Set(e.subjectIds??[]),r=(e.subjectHints??[]).map(Ue).filter(Boolean),c=Pe([e.action,e.text].filter(Boolean).join(" "));for(let d of n){if(i.has(d.id)){t.set(d.id,{subjectId:d.id,label:d.label,confidence:"exact",matchedBy:"id",score:100});continue}let m;for(let y of Vt(d)){let f=Ue(y.value);for(let v of r){let w=f===v?95:f.includes(v)||v.includes(f)?75:0;w>(m?.score??0)&&(m={subjectId:d.id,label:d.label,confidence:w>=90?"exact":"strong",matchedBy:y.by,score:w})}let T=["/","#","[","]","="].some(v=>y.value.includes(v))?0:Math.round(at(Pe(f),c)*55);T>=30&&T>(m?.score??0)&&(m={subjectId:d.id,label:d.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}m&&t.set(d.id,m)}return t}function Ht(n,e){let t=new Set(n.sourceRefs.filter(d=>d.kind==="iteration").map(d=>d.id)),i=new Set(n.sourceRefs.filter(d=>d.kind==="thread").map(d=>d.id)),r=e.filter(d=>d.iterationIds.some(m=>t.has(m))||d.sourceRefs.some(m=>m.kind==="thread"&&i.has(m.id)));if(!r.length)return{state:"none_found",attemptIds:[]};let c=new Set(r.map(d=>d.state));return{state:c.size>1?"mixed":c.has("completed")?"completed":"attempted",attemptIds:r.map(d=>d.id)}}function Ut(n){return Math.ceil(JSON.stringify(n).length/4)}function Fe(n,e){let t=n.records.filter(p=>p.recordType==="subject"),i=e.generatedAt??new Date().toISOString(),r=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,c=n.records.filter(p=>{if(p.recordType!=="proposal"||r&&!r.has(p.id))return!1;if(p.state==="pending")return!0;if(p.state!=="deferred")return!1;let u=[...n.events].reverse().find(l=>l.entity.entityType==="proposal"&&l.entity.entityId===p.id&&l.toState==="deferred"&&l.transitionContext?.kind==="proposal_deferral")?.transitionContext;return u?u.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||u.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||u.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||u.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||u.resurfaceWhen.includes("after_date")&&!!(u.revisitAfter&&Date.parse(i)>=Date.parse(u.revisitAfter)):!1}),d=n.records.filter(p=>p.recordType==="implementation_attempt"),m=Nt(t,e),y=[...m.values()].sort((p,u)=>u.score-p.score),f=Pe([e.action,e.text].filter(Boolean).join(" ")),x=c.flatMap(p=>{let u=p.subjects.map(I=>m.get(I.subjectId)).filter(I=>!!I),l=Math.max(0,...u.map(I=>I.score)),o=Math.round(at(Pe(p.claim),f)*35),g=l+o;return g>=50?[{proposal:p,proposalMatches:u,score:g}]:[]}).sort((p,u)=>u.score-p.score||p.proposal.id.localeCompare(u.proposal.id)),T=Math.max(1,e.maxPackets??3),v=Math.max(200,e.maxEstimatedTokens??1200),w=[],h=0;for(let p of x){if(w.length>=T)break;let u=p.proposal.sourceRefs.slice(0,4),l={contractVersion:1,packetId:`review:${p.proposal.id}`,projectId:n.manifest.projectId,generatedAt:i,trigger:{action:e.action,reason:p.proposalMatches.length?`Historical proposal intersects ${p.proposalMatches.map(g=>g.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:p.proposalMatches.map(({score:g,...I})=>I)},proposal:{id:p.proposal.id,claim:p.proposal.claim,state:p.proposal.state,proposedKind:p.proposal.proposedKind,subjectIds:p.proposal.subjects.map(g=>g.subjectId),origin:p.proposal.origin.mode},authority:"unaccepted",presentation:p.score>=100&&["constraint","rule"].includes(p.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:Ht(p.proposal,d),evidence:{sourceCount:p.proposal.sourceRefs.length,sourceRefs:u},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:p.proposal.id},...u]},o={...l,estimatedTokens:Ut(l)};if(h+o.estimatedTokens>v)break;w.push(o),h+=o.estimatedTokens}let a=Math.max(0,x.length-w.length);return{packets:w,subjectMatches:y.map(({score:p,...u})=>u),completeness:{status:a>0?"truncated":"complete",consideredProposalCount:x.length,omittedPacketCount:a,maxEstimatedTokens:v,estimatedTokens:h},uncertainty:m.size===0?"subject_unresolved":x.length===0?"no_relevant_pending_proposal":void 0}}function be(n,e,t,i){return{id:i,schemaVersion:1,projectId:n.manifest.projectId,createdAt:t.occurredAt,participantId:t.participantId,sourceRefs:[{kind:"record",id:e.id},...t.sourceRefs??[]],recordType:"lifecycle_event",authority:t.authority}}function ct(n,e,t,i,r){return{id:r,schemaVersion:1,projectId:n.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 Ft(n){switch(n.action){case"accept":return[n.eventId,n.decisionId];case"edit_and_accept":return[n.withdrawalEventId,n.replacementProposalId,n.acceptanceEventId,n.decisionId,n.relationshipId];case"reject":case"defer":return[n.eventId]}}function Ee(n,e){let t=[],i=n.records.find(c=>c.recordType==="proposal"&&c.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 c of Ft(e))ae(c)||t.push({code:"invalid_generated_id",message:`${c} 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 c={...be(n,i,e,e.eventId),entity:{entityType:"proposal",entityId:i.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},d=ct(n,i,e,c.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:i.id,append:{records:[d],events:[c],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:d.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 c={id:e.replacementProposalId,schemaVersion:1,projectId:n.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"}},d={...be(n,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."},m={...be(n,c,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},y=ct(n,c,e,m.id,e.decisionId),f={id:e.relationshipId,schemaVersion:1,projectId:n.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:i.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:c.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:[c,y],events:[d,m],relationships:[f]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:c.id},{entityType:"decision",entityId:y.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let c={...be(n,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:[c],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:i.id}]}}}let r={...be(n,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:[r],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:i.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:i.id}]}}}import{createHash as Kt}from"crypto";import{readFile as Wt,readdir as Gt,realpath as Qt}from"fs/promises";import{join as je,relative as Yt}from"path";var Xt=["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(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function z(n,e=0){return new Date(Number.isFinite(n)?n:e).toISOString()}function dt(...n){return n.find(e=>!!e?.trim())?.trim()}function M(n,e,t,i){let c=Math.max(0,Math.min(Math.floor(i),0xffffffffffff)).toString(16).padStart(12,"0"),d=Kt("sha256").update(`${n}\0${e}\0${t}`).digest("hex"),m=(Number.parseInt(d[3],16)&3|8).toString(16);return`${c.slice(0,8)}-${c.slice(8)}-7${d.slice(0,3)}-${m}${d.slice(4,7)}-${d.slice(7,19)}`}async function Ke(n,e){try{return JSON.parse(await Wt(n,"utf8"))}catch(t){return e.push({severity:"warning",code:"source_unavailable",source:n,message:t instanceof Error?t.message:String(t)}),null}}function Zt(n){let e=de(n);if(!e)return 0;let t=0,i=r=>{let c=de(r);if(!c){t+=1;return}for(let d of Object.values(c))i(d)};for(let r of Object.values(e))i(r);return t}function en(n){let e={};for(let t of n)e[t.recordType]=(e[t.recordType]??0)+1;return e}async function Re(n){let e=[],t=await Qt(n.projectRoot).catch(()=>n.projectRoot),i=je(t,".popmelt"),r=await Ke(je(i,"threads.json"),e),c=await Ke(je(i,"model.json"),e),d=de(r),m=de(d?.threads)??{},y=Object.entries(m).map(([R,_])=>({key:R,value:de(_)})).filter(R=>!!R.value),f=je(i,"decisions"),x=await Gt(f).catch(()=>[]),T=[];for(let R of x.filter(_=>_.endsWith(".json")).sort()){let _=de(await Ke(je(f,R),e));_&&T.push({file:R,value:_})}let v=y.flatMap(({value:R})=>[R.createdAt,R.updatedAt]).filter(R=>typeof R=="number"&&Number.isFinite(R)),w=v.length?Math.min(...v):0,h=n.projectKey??t;n.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=M(h,"project",h,w),p=M(h,"participant","legacy-owner",w),u=M(h,"participant","legacy-agent",w),l=M(h,"subject","project",w),o=z(Math.max(w,...v)),g=[],I=[],s=new Map,S=new Map,k=new Map(T.map(R=>[R.value.id??R.file.replace(/^d-|\.json$/g,""),R.value])),b=new Map,P=(R,_,$,O,L)=>{let U=s.get($);if(U)return U;let G=M(h,"artifact",R,O);return I.push({id:G,kind:_,mediaType:L,location:$,availability:"available"}),s.set($,G),G};for(let{file:R,value:_}of T){let $=_.id??R.replace(/^d-|\.json$/g,""),O=_.createdAt??w,L=[P(`${$}:envelope`,"other",`.popmelt/decisions/${R}`,O,"application/json")];_.screenshotPath&&L.push(P(`${$}:screenshot`,"screenshot",`.popmelt/${_.screenshotPath.replace(/^\.popmelt\//,"")}`,O,_.screenshotPath.endsWith(".png")?"image/png":"image/webp"));for(let[U,G]of(_.pastedImagePaths??[]).entries())L.push(P(`${$}:image:${U}`,"image",G,O));b.set($,L)}let q=(R,_,$)=>({id:R,schemaVersion:1,projectId:a,createdAt:o,participantId:_,sourceRefs:$}),F=(R,_)=>{g.push(_);let $=S.get(R)??[];$.push(_.id),S.set(R,$)},Be=[{...q(p,p,[]),recordType:"participant",kind:"human",displayName:"Legacy project owner",status:"active"},{...q(u,u,[]),recordType:"participant",kind:"ai",displayName:"Legacy coding agent",status:"active"}];g.push(...Be),g.push({...q(l,p,[]),recordType:"subject",subjectType:"project",label:Yt(process.cwd(),t)||t,aliases:[],locators:[{id:M(h,"locator",t,w),kind:"project_root",value:t,status:"current",validFrom:z(w),sourceRefs:[]}]});let te=new Map,fe=(R,_)=>{let $=te.get(R);if($)return $;let O=M(h,"subject",R,_),L={...q(O,p,[{kind:"external",id:R}]),createdAt:z(_),recordType:"subject",subjectType:"element",label:R,aliases:[],locators:[{id:M(h,"locator",R,_),kind:"dom_selector",value:R,status:"current",validFrom:z(_),sourceRefs:[{kind:"external",id:R}]}]};return g.push(L),te.set(R,O),O};for(let{key:R,value:_}of y){let $=_.id??R,O=_.createdAt??w,L=M(h,"thread",$,O),U={kind:"thread",id:$},G=[],he=[],Ye=Array.isArray(_.messages)?_.messages:[],ne,Oe,Xe=0;Ye.forEach((C,ie)=>{let J=C.timestamp??O,Y=M(h,"artifact",`${$}:message:${ie}`,J);if(G.push(Y),I.push({id:Y,kind:"message",mediaType:"application/json",location:`.popmelt/threads.json#/threads/${$}/messages/${ie}`,availability:"available"}),s.set(`.popmelt/threads.json#/threads/${$}/messages/${ie}`,Y),C.screenshotPath&&P(`${$}:message:${ie}:screenshot`,"screenshot",C.screenshotPath,J),C.role==="human"){ne=C;let V=C.feedbackSummary??C.replyToQuestion;if(V?.trim()){let N=M(h,"observation",`${$}:${ie}`,J),se=_.elementIdentifiers??[],Ae={...q(N,p,[U,{kind:"message",id:Y}]),createdAt:z(J),recordType:"observation",state:"open",statement:V,captureContext:{subjectIds:se.map(ge=>fe(ge,O)),artifactIds:[Y]},resolvedByIds:[]};F($,Ae),Oe=N,he.push({entityType:"observation",entityId:N})}return}if(C.role!=="assistant")return;let re=C.jobId??`${$}:${ie}`,oe=M(h,"iteration",re,J),Ie=k.get(re),vt=C.cancelled?"cancelled":C.error?"failed":C.question?"question_asked":(C.resolutions?.length??0)>0?"completed":"no_change",wt={...q(oe,u,[U,{kind:"message",id:Y},...(b.get(re)??[]).map(V=>({kind:"artifact",id:V}))]),createdAt:z(J),recordType:"iteration",threadIds:[L],startedAt:z(ne?.timestamp,J),completedAt:z(J),requestSummary:dt(ne?.feedbackSummary,ne?.replyToQuestion)??"[legacy request unavailable]",responseSummary:C.question??C.error??C.responseText?.slice(0,1e3),outcome:vt,execution:{provider:C.provider??Ie?.provider,model:C.model??Ie?.model,sessionId:C.sessionId??Ie?.sessionId},artifactIds:[Y,...b.get(re)??[]]};F($,wt),he.push({entityType:"iteration",entityId:oe});let qe=C.resolutions??Ie?.resolutions??[];for(let[V,N]of qe.entries()){if(N.status!=="resolved"||!N.summary?.trim())continue;let se=_.elementIdentifiers??[],Ae=(se.length?se:[t]).map(et=>({subjectId:et===t?l:fe(et,O),role:"governed"})),ge=M(h,"proposal",`${re}:${N.annotationId??"resolution"}:${V}`,J),bt={...q(ge,u,[U,{kind:"iteration",id:oe}]),createdAt:z(J),recordType:"proposal",state:"pending",claim:N.summary,subjects:Ae,subjectSemantics:Ae.length>1?"Legacy thread grouped these selected elements; independent scope requires owner review.":void 0,origin:{mode:"inferred",sourceText:dt(ne?.feedbackSummary,ne?.replyToQuestion,N.summary),iterationId:oe,inferredById:u}};F($,bt),he.push({entityType:"proposal",entityId:ge}),e.push({severity:"warning",code:"acceptance_unresolved",source:$,message:`Proposal ${ge} remains pending; legacy resolved status proves an outcome, not explicit acceptance.`})}if(qe.some(V=>V.status==="resolved")||Ie?.gitDiff){let V=M(h,"implementation",re,J),N={...q(V,u,[U,{kind:"iteration",id:oe}]),createdAt:z(J),recordType:"implementation_attempt",state:"completed",iterationIds:[oe],coverageClaims:[],summary:qe.map(se=>se.summary).filter(Boolean).join(" ")||"Legacy implementation outcome.",artifactIds:[]};F($,N),he.push({entityType:"implementation_attempt",entityId:V}),Xe+=1}Oe&&(Oe=void 0)});let Ze=Ye.at(-1),gt={...q(L,p,[U]),createdAt:z(O),recordType:"thread",state:Ze?.question?"open":"resolved",messageArtifactIds:G,outcome:Ze?.question?"question_unresolved":Xe?"implementation_only":"no_outcome",resultRefs:he};g.push(gt),S.set($,[L,...S.get($)??[]])}let Q=Zt(c);Q&&e.push({severity:"warning",code:"model_entries_deferred",source:".popmelt/model.json",message:`${Q} model values were not promoted because their accepted decision provenance is unresolved.`});let ye={manifest:{formatVersion:1,projectId:a,createdAt:z(w),updatedAt:o,features:["authority","subjects","implementations","portable_artifacts","bounded_retrieval"],writer:{name:"@popmelt.com/core legacy importer",version:n.writerVersion??"0.8.4-dev"}},records:g,events:[],relationships:[],artifacts:I,tombstones:[]},W=Z(ye),j=(n.proofCaseIds??Xt).map(R=>({legacyId:R,threadFound:y.some(({key:_,value:$})=>($.id??_)===R),decisionEnvelopeFound:k.has(R),recordIds:S.get(R)??[]}));return{bundle:ye,report:{projectRoot:t,source:{threads:y.length,messages:y.reduce((R,_)=>R+(_.value.messages?.length??0),0),decisionEnvelopes:T.length,modelEntries:Q,artifactsReferenced:I.length},imported:en(g),unresolvedAcceptance:e.filter(R=>R.code==="acceptance_unresolved").length,deferredModelEntries:Q,proofCases:j,issues:e,schemaIssues:W.issues}}}var tn=()=>({records:[],events:[],relationships:[],artifacts:[],tombstones:[],projectionUpdates:[]});function pt(n,e){let t=n.records.find(o=>o.recordType==="participant"&&o.kind==="human"&&o.status==="active"),i=n.records.find(o=>o.recordType==="participant"&&o.kind==="ai"&&o.status==="active");if(!t||!i)throw new Error("Canonical memory requires active human and AI participants before job capture.");let r=n.manifest.projectId,c=`${e.threadId}:${e.jobId}`,d=new Date(e.createdAt).toISOString(),m=new Date(e.completedAt).toISOString(),y=tn(),f=y.records,x=n.records.find(o=>o.recordType==="thread"&&o.sourceRefs.some(g=>g.kind==="thread"&&g.id===e.threadId));x||(x={id:M(r,"live-thread",e.threadId,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:d,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(o=>o.status==="resolved")?"implementation_only":"no_outcome",resultRefs:[]},f.push(x));let T=[];for(let o of[...new Set(e.subjectHints.filter(Boolean))]){let g=n.records.find(I=>I.recordType==="subject"&&I.locators.some(s=>s.value===o&&s.status==="current"));g||(g={id:M(r,"live-subject",o,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"external",id:o}],recordType:"subject",subjectType:"element",label:o,aliases:[],locators:[{id:M(r,"live-locator",o,e.createdAt),kind:"dom_selector",value:o,status:"current",validFrom:d,sourceRefs:[{kind:"external",id:o}]}]},f.push(g)),T.push(g)}for(let o of[...new Set((e.filePaths??[]).filter(Boolean))]){let g=n.records.find(I=>I.recordType==="subject"&&I.locators.some(s=>s.kind==="source_file"&&s.value===o&&s.status==="current"));g||(g={id:M(r,"live-file-subject",o,e.createdAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"external",id:o}],recordType:"subject",subjectType:"file",label:o,aliases:[],locators:[{id:M(r,"live-file-locator",o,e.createdAt),kind:"source_file",value:o,status:"current",validFrom:d,sourceRefs:[{kind:"external",id:o}]}]},f.push(g)),T.push(g)}let v=(e.semanticCandidates??[]).filter(o=>o.claim.trim()),w;if(v.length>0){w=M(r,"live-observation",c,e.createdAt);let o={id:w,schemaVersion:1,projectId:n.manifest.projectId,createdAt:d,participantId:t.id,sourceRefs:[{kind:"thread",id:e.threadId}],recordType:"observation",state:"open",statement:v.map(g=>g.claim.trim()).join(" "),captureContext:{subjectIds:T.map(g=>g.id),artifactIds:[]},resolvedByIds:[]};f.push(o)}let h=M(r,"live-iteration",c,e.completedAt),a={id:h,schemaVersion:1,projectId:n.manifest.projectId,createdAt:d,participantId:i.id,sourceRefs:[{kind:"thread",id:e.threadId},{kind:"external",id:e.jobId,uri:"popmelt:job"},...(e.submissionIds??[]).map(o=>({kind:"external",id:o,uri:"popmelt:submission"})),...e.outcomeId?[{kind:"external",id:e.outcomeId,uri:"popmelt:outcome"}]:[],...(e.imprintEvidenceIds??[]).map(o=>({kind:"external",id:o,uri:"popmelt:imprint-evidence"})),...w?[{kind:"record",id:w}]:[]],recordType:"iteration",threadIds:[x.id],startedAt:d,completedAt:m,requestSummary:e.requestSummary||"[request unavailable]",responseSummary:e.responseSummary?.slice(0,2e3),outcome:e.outcome,execution:e.execution,artifactIds:[],...e.imprintAssessment?{imprintAssessment:e.imprintAssessment}:{}};f.push(a);let p=[],u=e.resolutions.filter(o=>o.status==="resolved"&&o.summary.trim()),l=T.length>0?T:n.records.filter(o=>o.recordType==="subject"&&o.subjectType==="project").slice(0,1);if(v.length>0&&l.length===0)throw new Error("Canonical memory has no project subject for an unscoped proposal.");for(let[o,g]of v.entries()){let I=M(r,"live-proposal",`${c}:${o}`,e.completedAt),s=l.map(k=>({subjectId:k.id,role:"governed"})),S={id:I,schemaVersion:1,projectId:n.manifest.projectId,createdAt:m,participantId:i.id,sourceRefs:[{kind:"iteration",id:h},{kind:"thread",id:e.threadId}],recordType:"proposal",state:"pending",claim:g.claim.trim(),rationale:g.rationale?.trim()||void 0,proposedKind:g.proposedKind,subjects:s,subjectSemantics:s.length>1?"The task selected these subjects together; independent authority remains unresolved.":void 0,origin:{mode:"inferred",sourceText:g.sourceText?.trim()||e.requestSummary,iterationId:h,inferredById:i.id}};f.push(S),p.push(I)}if(u.length>0){let o=new Set(e.governingDecisionIds??[]),g=n.records.filter(s=>s.recordType==="decision"&&s.state==="active"&&o.has(s.id)),I={id:M(r,"live-implementation",c,e.completedAt),schemaVersion:1,projectId:n.manifest.projectId,createdAt:m,participantId:i.id,sourceRefs:[{kind:"iteration",id:h}],recordType:"implementation_attempt",state:"completed",iterationIds:[h],coverageClaims:g.map(s=>({decisionId:s.id,coverage:"partial",claim:`This iteration applied the decision while completing: ${u.map(S=>S.summary).join(" ")}`,sourceRefs:[{kind:"iteration",id:h}]})),summary:u.map(s=>s.summary).join(" "),artifactIds:[]};f.push(I)}return{mutation:y,iterationId:h,proposalIds:p,observationId:w}}import{createHash as nn}from"crypto";import{mkdir as rn,open as on,readFile as sn,rename as an,unlink as cn}from"fs/promises";import{join as lt}from"path";function ut(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function mt(n){return nn("sha256").update(JSON.stringify(n)).digest("hex")}async function dn(n,e){let t=`${n}.${process.pid}.${Date.now()}.tmp`,i=await on(t,"w");try{await i.writeFile(`${JSON.stringify(e,null,2)}
|
|
3
|
-
`,"utf8"),await i.sync()}finally{await i.close()}try{await an(t,n)}catch(r){throw await cn(t).catch(()=>{}),r}}function pn(n,e,t=new Date().toISOString()){let i={},r={},c={},d=(y,f,x)=>{let T=y[f]??=[];T.includes(x)||T.push(x)};for(let y of n.records)if(y.recordType==="subject"){let f=y;for(let x of[f.label,...f.aliases,...f.locators.filter(T=>T.status==="current").map(T=>T.value)]){let T=ut(x);T&&d(i,T,f.id)}}else if(y.recordType==="decision"&&y.state==="active")for(let f of y.subjects)d(r,f.subjectId,y.id);else if(y.recordType==="proposal"&&["pending","deferred"].includes(y.state))for(let f of y.subjects)d(c,f.subjectId,y.id);let m={version:1,projectId:n.manifest.projectId,journalHead:e,generatedAt:t,subjectIdsByValue:i,decisionIdsBySubject:r,proposalIdsBySubject:c};return{...m,checksum:mt(m)}}function ft(n,e){let t=[...new Set(e.flatMap(i=>n.subjectIdsByValue[ut(i)]??[]))];if(t.length)return{subjectIds:t,decisionIds:[...new Set(t.flatMap(i=>n.decisionIdsBySubject[i]??[]))],proposalIds:[...new Set(t.flatMap(i=>n.proposalIdsBySubject[i]??[]))]}}var Ce=class{constructor(e){this.indexDir=lt(e,".popmelt","memory","indexes"),this.indexPath=lt(this.indexDir,"retrieval-v1.json")}async ensure(e,t){try{let r=JSON.parse(await sn(this.indexPath,"utf8")),{checksum:c,...d}=r;if(r.version===1&&r.projectId===e.manifest.projectId&&r.journalHead.sequence===t.sequence&&r.journalHead.hash===t.hash&&c===mt(d))return r}catch(r){if(r.code!=="ENOENT"&&!(r instanceof SyntaxError))throw r}let i=pn(e,t);return await rn(this.indexDir,{recursive:!0}),await dn(this.indexPath,i),i}};import{randomBytes as ln}from"crypto";function E(n=Date.now()){let t=Math.max(0,Math.min(Math.floor(n),0xffffffffffff)).toString(16).padStart(12,"0"),i=ln(10).toString("hex"),r=(Number.parseInt(i[3],16)&3|8).toString(16);return`${t.slice(0,8)}-${t.slice(8)}-7${i.slice(0,3)}-${r}${i.slice(4,7)}-${i.slice(7,19)}`}var Se="popmelt:imprint",It="popmelt:imprint-evidence",le="popmelt:imprint-relation";function Te(n){return n.sourceRefs.find(e=>e.kind==="external"&&e.uri===Se)?.id}function We(n){let e=new Set;return n.filter(t=>{let i=`${t.kind}:${t.id}:${t.uri??""}`;return e.has(i)?!1:(e.add(i),!0)})}function De(n,e){if(!n)return[];let t=new Set(n.relations.flatMap(i=>i.type==="expresses"&&!i.toStoreId&&i.toId===e?[i.fromId]:[]));return n.concrete.filter(i=>t.has(i.id)).map(i=>({id:i.id,modelPath:i.modelPath,value:structuredClone(i.value),createdAt:i.createdAt,updatedAt:i.updatedAt}))}function Ge(n){if(n==="expresses")return"expresses";if(n==="excepts")return"excepts"}var Qe=class{constructor(e){this.projectRoot=e;this.store=new we(e),this.indexStore=new Ce(e),this.manifestPath=pe(e,".popmelt","memory","manifest.json")}async status(){try{let e=JSON.parse(await xe(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 i=await Re({...e,projectRoot:this.projectRoot});if(i.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(i.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(t){return this.runtimeState={state:"degraded",error:t instanceof Error?t.message:String(t)},await this.status()}})(),this.initializationPromise)}async analyzeLegacy(e={}){return(await Re({...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=pe(this.projectRoot,".popmelt","memory","migrations"),t=pe(e,"imprint-advisories-v2.json");try{let o=JSON.parse(await xe(t,"utf8"));return{migrated:!1,explanations:o.explanations??0,evidence:o.evidence??0}}catch{}let i;try{i=_e(JSON.parse(await xe(pe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}if(!i?.explanations)return await yt(e,{recursive:!0}),await ht(t,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(),c=r.bundle.records.find(o=>o.recordType==="participant"&&o.kind==="human"&&o.status==="active"),m=r.bundle.records.find(o=>o.recordType==="participant"&&o.kind==="ai"&&o.status==="active")??c,y=r.bundle.records.find(o=>o.recordType==="subject"&&o.subjectType==="project");if(!m||!y)return{migrated:!1,explanations:0,evidence:0};let f=r.bundle.manifest.projectId,x=new Set(r.bundle.records.map(o=>o.id)),T=new Set(r.bundle.relationships.flatMap(o=>o.sourceRefs.flatMap(g=>g.kind==="external"&&g.uri===le?[g.id]:[]))),v=new Map,w=r.bundle.records.filter(o=>o.recordType==="advisory_explanation");for(let o of i.explanations){let g=w.find(I=>Te(I)===o.id);v.set(o.id,g?.id??M(f,"imprint-explanation",o.id,Date.parse(o.createdAt)))}let h=[],a=[],p=[],u=0;for(let o of i.explanations){let g=v.get(o.id),I=w.find(b=>b.id===g),s=[],S=o.evidence.length?o.evidence:[{id:`fallback:${o.id}`,kind:"observation",stance:"supports",summary:o.rationale,threadId:"imprint-migration",jobId:"imprint-migration",createdAt:o.createdAt}];for(let b of S){let P=M(f,"imprint-evidence-record",b.id,Date.parse(b.createdAt));s.push(P),!x.has(P)&&(h.push({id:P,schemaVersion:1,projectId:f,createdAt:b.createdAt,participantId:m.id,sourceRefs:We([{kind:"external",id:b.id,uri:It},{kind:"external",id:o.id,uri:Se},{kind:"thread",id:b.threadId},{kind:"message",id:b.jobId}]),recordType:"evidence",kind:["confirmation","correction","exception","rejection"].includes(b.kind)?"user_feedback":"judgment",summary:b.summary,availability:"available",artifactIds:[]}),p.push({id:M(f,"imprint-evidence-link",`${o.id}:${b.id}`,Date.parse(b.createdAt)),schemaVersion:1,projectId:f,createdAt:b.createdAt,participantId:m.id,sourceRefs:[{kind:"external",id:b.id,uri:It}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:g},to:{entityType:"evidence",entityId:P},reason:"This advisory explanation was derived from collaboration evidence."}),u+=1)}let k={id:g,schemaVersion:1,projectId:f,createdAt:I?.createdAt??o.createdAt,participantId:I?.participantId??m.id,sourceRefs:We([...I?.sourceRefs??[],{kind:"external",id:o.id,uri:Se}]),recordType:"advisory_explanation",kind:o.kind,state:o.state,statement:o.statement,rationale:o.rationale,scope:structuredClone(o.scope),subjectIds:[y.id],evidenceIds:[...new Set([...I?.evidenceIds??[],...s])],concreteBindings:De(i,o.id),supersededById:o.supersededBy?v.get(o.supersededBy):void 0,updatedAt:o.updatedAt};I?a.push(k):h.push(k)}for(let o of i.relations){let g=Ge(o.type);if(!g||o.toStoreId)continue;let I=v.get(o.fromId),s=v.get(o.toId);!I||!s||T.has(o.id)||p.push({id:M(f,"imprint-relation",o.id,Date.parse(o.createdAt)),schemaVersion:1,projectId:f,createdAt:o.createdAt,participantId:m.id,sourceRefs:[{kind:"external",id:o.id,uri:le}],recordType:"relationship",relationshipType:g,from:{entityType:"advisory_explanation",entityId:I},to:{entityType:"advisory_explanation",entityId:s},reason:o.rationale||"The Imprint graph connected these explanations."})}let l=new Date().toISOString();if(h.length||a.length||p.length)try{let o=await this.store.commit({records:h,recordReplacements:a,events:[],relationships:p,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:M(f,"imprint-advisories-v2",i.projectId,Date.parse(i.updatedAt)),committedAt:l});await this.refreshIndex(o)}catch(o){if(!(o instanceof Error)||!o.message.includes("Transaction already exists"))throw o}return await yt(e,{recursive:!0}),await ht(t,JSON.stringify({version:2,migratedAt:l,explanations:i.explanations.length,evidence:u,source:".popmelt/imprint (canonical cutover)"},null,2)),{migrated:!0,explanations:i.explanations.length,evidence:u}}async review(e,t={}){let i=await this.loadSource(t),r=await this.withIndexedCandidates(i,e);return{source:i.source,selection:Fe(i.bundle,r)}}async contextualize(e,t={}){let i=await this.loadSource(t),r=await this.withIndexedCandidates(i,e);return{source:i.source,actionPacket:st(i.bundle,r),reviewSelection:Fe(i.bundle,r)}}async imprintTopology(){let e;try{e=await this.loadJournalSource()}catch(t){if(t.code==="ENOENT")return{explanations:[],relations:[]};throw t}return{explanations:e.bundle.records.flatMap(t=>t.recordType==="advisory_explanation"?[{memoryId:t.id,explanationId:Te(t)??t.id}]:[]),relations:e.bundle.relationships.flatMap(t=>t.relationshipType!=="expresses"&&t.relationshipType!=="excepts"||t.from.entityType!=="advisory_explanation"||t.to.entityType!=="advisory_explanation"?[]:[{id:t.id,type:t.relationshipType,from:{memoryId:t.from.entityId,...t.from.storeId?{storeId:t.from.storeId}:{}},to:{memoryId:t.to.entityId,...t.to.storeId?{storeId:t.to.storeId}:{}},rationale:t.reason}])}}async planReview(e,t={}){let i=await this.loadSource(t);return{source:i.source,result:Ee(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 Re({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(),r=Ee(i.bundle,e);if(!r.ok)throw new Error(`Owner review action is invalid: ${JSON.stringify(r.errors)}`);let c=await this.store.commitReviewPlan(r.plan,t);return await this.refreshIndex(c),c}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(v=>v.recordType==="proposal"&&v.id===e.proposalId),r=t.bundle.records.find(v=>v.recordType==="participant"&&v.kind==="human"&&v.status==="active");if(!i||i.state!=="pending"||!r)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 c=Date.now(),d=new Date(c).toISOString(),m={proposalId:i.id,participantId:r.id,authority:{level:"owner",mode:"local_trusted"},occurredAt:d},y=e.action==="accept"?{...m,action:"accept",eventId:E(c),decisionId:E(c),kind:e.kind,reason:e.reason}:e.action==="edit_and_accept"?{...m,action:"edit_and_accept",withdrawalEventId:E(c),replacementProposalId:E(c),acceptanceEventId:E(c),decisionId:E(c),relationshipId:E(c),claim:e.claim,kind:e.kind,subjects:i.subjects,subjectSemantics:i.subjectSemantics,reason:e.reason}:e.action==="reject"?{...m,action:"reject",eventId:E(c),reason:e.reason}:{...m,action:"defer",eventId:E(c),reason:e.reason,context:{taskContext:e.taskContext,subjectIds:i.subjects.map(v=>v.subjectId),resurfaceWhen:e.resurfaceWhen?.length?e.resurfaceWhen:["different_action","owner_request"]}},f=Ee(t.bundle,y);if(!f.ok)return{status:"rejected",action:e.action,proposalId:e.proposalId,message:f.errors.map(v=>v.message).join(" ")};let x=await this.store.commitReviewPlan(f.plan,{transactionId:E(c),committedAt:d});await this.refreshIndex(x);let T=f.plan.resultRefs.find(v=>v.entityType==="decision")?.entityId;return{status:"committed",action:e.action,proposalId:e.proposalId,decisionId:T,message:e.action==="accept"||e.action==="edit_and_accept"?"Accepted product memory was committed.":e.action==="reject"?"Historical candidate was rejected.":"Historical candidate was deferred.",headSequence:x.report.headSequence}}async captureCompletedJob(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",proposalIds:[]};let t=await this.store.load(),i=pt(t.bundle,e),r=M(t.bundle.manifest.projectId,"live-capture-transaction",`${e.threadId}:${e.jobId}`,e.completedAt);try{let c=await this.store.commit(i.mutation,{transactionId:r,committedAt:new Date(e.completedAt).toISOString()});return await this.refreshIndex(c),{status:"captured",iterationId:i.iterationId,proposalIds:i.proposalIds,headSequence:c.report.headSequence}}catch(c){if(c instanceof Error&&c.message.includes("Transaction already exists"))return{status:"duplicate",iterationId:i.iterationId,proposalIds:i.proposalIds};throw c}}async recordImprintEvidence(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized||e.summary.changes.length===0)return;let t;try{t=_e(JSON.parse(await xe(pe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{}let i=await this.store.load(),r=i.bundle.records.find(l=>l.recordType==="participant"&&l.kind==="human"&&l.status==="active"),c=i.bundle.records.find(l=>l.recordType==="participant"&&l.kind==="ai"&&l.status==="active"),d=e.action?r:c??r,m=i.bundle.records.find(l=>l.recordType==="subject"&&l.subjectType==="project");if(!d||!m)return;let y=e.occurredAt??new Date().toISOString(),f=Date.parse(y),x=i.bundle.manifest.projectId,T=[],v=[],w=[],h=i.bundle.records.filter(l=>l.recordType==="advisory_explanation"),a=new Map(h.flatMap(l=>{let o=Te(l);return o?[[o,l.id]]:[]}));for(let l of e.summary.changes)if(!a.has(l.explanationId)){let o=t?.explanations.find(g=>g.id===l.explanationId);a.set(l.explanationId,M(x,"imprint-explanation",l.explanationId,Date.parse(o?.createdAt??y)))}for(let l of e.summary.changes){let o={kind:"external",id:l.explanationId,uri:Se},g=a.get(l.explanationId),I=h.find(b=>b.id===g),s=t?.explanations.find(b=>b.id===l.explanationId),S={id:M(x,"imprint-live-evidence",`${e.summary.transactionId}:${l.explanationId}:${e.action??"automatic"}`,f),schemaVersion:1,projectId:x,createdAt:y,participantId:d.id,sourceRefs:[o,{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(S);let k={id:g,schemaVersion:1,projectId:x,createdAt:I?.createdAt??s?.createdAt??y,participantId:I?.participantId??d.id,sourceRefs:We([...I?.sourceRefs??[],o,{kind:"thread",id:e.threadId},{kind:"message",id:e.jobId}]),recordType:"advisory_explanation",kind:s?.kind??I?.kind??"pattern",state:s?.state??l.state,statement:s?.statement??l.statement,rationale:s?.rationale??I?.rationale??e.summary.detail,scope:structuredClone(s?.scope??I?.scope??{kind:"project",values:[]}),subjectIds:I?.subjectIds??[m.id],evidenceIds:[...new Set([...I?.evidenceIds??[],S.id])],concreteBindings:s?De(t,l.explanationId):I?.concreteBindings??[],supersededById:s?.supersededBy?a.get(s.supersededBy):I?.supersededById,updatedAt:s?.updatedAt??y};I?v.push(k):T.push(k),w.push({id:M(x,"imprint-live-evidence-link",`${e.summary.transactionId}:${l.explanationId}:${e.action??"automatic"}`,f),schemaVersion:1,projectId:x,createdAt:y,participantId:d.id,sourceRefs:[o],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"advisory_explanation",entityId:k.id},to:{entityType:"evidence",entityId:S.id},reason:e.action?"The developer grounding response updates this advisory explanation.":"The Imprint explanation was derived from this collaboration evidence."})}let p=new Set(i.bundle.relationships.flatMap(l=>l.sourceRefs.flatMap(o=>o.kind==="external"&&o.uri===le?[o.id]:[])));for(let l of t?.relations??[]){let o=Ge(l.type);if(!o)continue;let g=a.get(l.fromId),I=l.toStoreId?e.qualifiedExplanationMemoryIds?.[`${l.toStoreId}:${l.toId}`]:a.get(l.toId);!g||!I||p.has(l.id)||w.push({id:M(x,"imprint-relation",l.id,Date.parse(l.createdAt)),schemaVersion:1,projectId:x,createdAt:l.createdAt,participantId:d.id,sourceRefs:[{kind:"external",id:l.id,uri:le}],recordType:"relationship",relationshipType:o,from:{entityType:"advisory_explanation",entityId:g},to:{entityType:"advisory_explanation",entityId:I,...l.toStoreId?{storeId:l.toStoreId}:{}},reason:l.rationale||"The Imprint graph connected these explanations."})}let u=M(i.bundle.manifest.projectId,"imprint-evidence",`${e.summary.transactionId}:${e.action??"automatic"}`,f);try{let l=await this.store.commit({records:T,recordReplacements:v,events:[],relationships:w,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:u,committedAt:y});await this.refreshIndex(l)}catch(l){if(!(l instanceof Error)||!l.message.includes("Transaction already exists"))throw l}}async syncImprintGraph(){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return{status:"not_ready",relationships:0,explanations:0};let e;try{e=_e(JSON.parse(await xe(pe(this.projectRoot,".popmelt","imprint","graph.json"),"utf8")))}catch{return{status:"no_change",relationships:0,explanations:0}}let t=await this.store.load(),i=t.bundle.records.find(s=>s.recordType==="participant"&&s.kind==="human"&&s.status==="active"),c=t.bundle.records.find(s=>s.recordType==="participant"&&s.kind==="ai"&&s.status==="active")??i;if(!c)return{status:"not_ready",relationships:0,explanations:0};let d=t.bundle.records.find(s=>s.recordType==="subject"&&s.subjectType==="project");if(!d)return{status:"not_ready",relationships:0,explanations:0};let m=t.bundle.manifest.projectId,y=t.bundle.records.filter(s=>s.recordType==="advisory_explanation"),f=new Map(y.flatMap(s=>{let S=Te(s);return S?[[S,s]]:[]})),x=new Map([...[...f].map(([s,S])=>[s,S.id]),...e.explanations.filter(s=>!f.has(s.id)).map(s=>[s.id,M(m,"imprint-explanation",s.id,Date.parse(s.createdAt))])]),T=[],v=[],w=new Set(e.explanations.map(s=>s.id));for(let s of e.explanations){let S=f.get(s.id);if(!S){T.push({id:x.get(s.id),schemaVersion:1,projectId:m,createdAt:s.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:s.id,uri:Se}],recordType:"advisory_explanation",kind:s.kind,state:s.state,statement:s.statement,rationale:s.rationale,scope:structuredClone(s.scope),subjectIds:[d.id],evidenceIds:[],concreteBindings:De(e,s.id),supersededById:s.supersededBy?x.get(s.supersededBy):void 0,updatedAt:s.updatedAt});continue}let k={...structuredClone(S),kind:s.kind,state:s.state,statement:s.statement,rationale:s.rationale,scope:structuredClone(s.scope),concreteBindings:De(e,s.id),supersededById:s.supersededBy?x.get(s.supersededBy):void 0,updatedAt:s.updatedAt},b=P=>JSON.stringify({kind:P.kind,state:P.state,statement:P.statement,rationale:P.rationale,scope:P.scope,concreteBindings:P.concreteBindings,supersededById:P.supersededById,updatedAt:P.updatedAt});b(S)!==b(k)&&v.push(k)}for(let[s,S]of f)w.has(s)||S.state==="retired"||v.push({...structuredClone(S),state:"retired",supersededById:void 0,updatedAt:e.updatedAt});let h=new Set(t.bundle.tombstones.flatMap(s=>s.objectType==="relationship"?[s.objectId]:[])),a=new Map(t.bundle.relationships.flatMap(s=>{if(h.has(s.id))return[];let S=s.sourceRefs.find(k=>k.kind==="external"&&k.uri===le)?.id;return S?[[S,s]]:[]})),p=[],u=new Set;for(let s of e.relations){let S=Ge(s.type);if(!S||s.toStoreId)continue;let k=x.get(s.fromId),b=x.get(s.toId);if(!k||!b)continue;let P=a.get(s.id);P&&P.relationshipType===S&&P.from.entityType==="advisory_explanation"&&P.from.entityId===k&&P.to.entityType==="advisory_explanation"&&P.to.entityId===b||(P&&u.add(s.id),p.push({id:M(m,"imprint-relation",`${s.id}:${S}:${k}:${b}`,Date.parse(s.createdAt)),schemaVersion:1,projectId:m,createdAt:s.createdAt,participantId:c.id,sourceRefs:[{kind:"external",id:s.id,uri:le}],recordType:"relationship",relationshipType:S,from:{entityType:"advisory_explanation",entityId:k},to:{entityType:"advisory_explanation",entityId:b},reason:s.rationale||"The Imprint graph connected these explanations."}))}let l=new Set(e.relations.map(s=>s.id)),o=i?[...a].filter(([s])=>!l.has(s)||u.has(s)).map(([,s])=>({id:M(m,"imprint-relationship-tombstone",s.id,Date.parse(e.updatedAt)),schemaVersion:1,projectId:m,objectId:s.id,objectType:"relationship",deletedAt:e.updatedAt,deletedById:i.id,authority:{level:"owner",mode:"local_trusted"},reasonCategory:"serious_error",erasureLevel:"content",invalidates:[]})):[];if(!T.length&&!v.length&&!p.length&&!o.length)return{status:"no_change",relationships:0,explanations:0,headSequence:t.report.headSequence};let g=e.updatedAt,I=M(m,"imprint-graph-sync",e.head.hash??String(e.head.sequence),Date.parse(g));try{let s=await this.store.commit({records:T,recordReplacements:v,events:[],relationships:p,artifacts:[],tombstones:o,projectionUpdates:[]},{transactionId:I,committedAt:g});return await this.refreshIndex(s),{status:"synced",relationships:p.length+o.length,explanations:T.length+v.length,headSequence:s.report.headSequence}}catch(s){if(!(s instanceof Error)||!s.message.includes("Transaction already exists"))throw s;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 i={};for(let r of t.bundle.records)i[r.recordType]=(i[r.recordType]??0)+1;return{status:e,journal:t.report,records:i,openFreshnessSignals:t.bundle.records.filter(r=>r.recordType==="freshness_signal"&&r.state==="open").length,unavailableEvidence:t.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:t}=await this.store.load(),i=new Set(t.records.flatMap(d=>d.recordType==="model_projection"&&d.state==="applied"?d.coverage.filter(m=>m.status==="projected").map(m=>m.decisionId):[])),r=new Set(t.relationships.flatMap(d=>d.relationshipType==="contradicts"&&d.from.entityType==="decision"&&d.to.entityType==="decision"?[d.from.entityId,d.to.entityId]:[])),c=new Set(t.records.flatMap(d=>d.recordType==="freshness_signal"&&d.state==="open"&&d.target.entityType==="decision"?[d.target.entityId]:[]));return t.records.filter(d=>d.recordType==="decision"&&d.state==="active"&&!i.has(d.id)&&!r.has(d.id)&&!c.has(d.id)).sort((d,m)=>m.createdAt.localeCompare(d.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(r=>r.recordType==="decision"&&r.state==="active"?[r.id]:[])),i=new Map;for(let r of e.records.filter(c=>c.recordType==="model_entry").sort((c,d)=>c.createdAt.localeCompare(d.createdAt)))r.decisionIds.some(c=>t.has(c))&&i.set(r.key,r);return[...i.values()]}async getImprintView(e=[],t){let i=()=>({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 i();let r=await this.store.load(),c=r.bundle.records.filter(p=>p.recordType==="advisory_explanation"),d=new Map(c.map(p=>[p.id,p])),m=new Map(c.flatMap(p=>{let u=Te(p);return u?[[u,p.id]]:[]})),y=new Set(e.map(p=>m.get(p)??p)),f=new Map(r.bundle.records.flatMap(p=>p.recordType==="participant"?[[p.id,p.kind]]:[])),x=new Map(r.bundle.records.flatMap(p=>p.recordType==="evidence"?[[p.id,p]]:[])),T=new Set(r.bundle.tombstones.flatMap(p=>p.objectType==="relationship"?[p.objectId]:[])),v=new Set(["expresses","operationalizes","excepts"]),w={testing:0,emerging:1,grounded:2,challenged:3,retired:4},h=c.map(p=>{let u=p.evidenceIds.flatMap(I=>{let s=x.get(I);if(!s)return[];let S=s.sourceRefs.find(q=>q.kind==="thread")?.id,k=s.sourceRefs.find(q=>q.kind==="message")?.id,b=s.kind==="judgment"||s.kind==="user_feedback"||s.kind==="project_state"?s.kind:"other",P=f.get(s.participantId)??"unknown";return[{id:s.id,kind:b,summary:s.summary,createdAt:s.createdAt,participantKind:P,threadId:S,jobId:k}]}).sort((I,s)=>s.createdAt.localeCompare(I.createdAt)),l=r.bundle.relationships.flatMap(I=>{if(T.has(I.id))return[];if(!v.has(I.relationshipType))return[];let s=I.from.entityType==="advisory_explanation"&&I.from.entityId===p.id&&I.to.entityType==="advisory_explanation",S=I.to.entityType==="advisory_explanation"&&I.to.entityId===p.id&&I.from.entityType==="advisory_explanation";if(!s&&!S)return[];let k=s?I.to.entityId:I.from.entityId,b=d.get(k);return b?[{id:I.id,type:I.relationshipType==="excepts"?"excepts":"expresses",direction:s?"outgoing":"incoming",explanationId:b.id,statement:b.statement,rationale:I.reason}]:[]}),o=[...(p.supersededById?[p.supersededById]:[]).flatMap(I=>{let s=d.get(I);return s?[{id:`supersedes:${p.id}:${s.id}`,type:"supersedes",direction:"incoming",explanationId:s.id,statement:s.statement,rationale:"A later explanation replaced this challenged wording."}]:[]}),...c.flatMap(I=>I.supersededById===p.id?[{id:`supersedes:${I.id}:${p.id}`,type:"supersedes",direction:"outgoing",explanationId:I.id,statement:I.statement,rationale:"This explanation replaced earlier challenged wording."}]:[])],g=[...new Set([...p.sourceRefs.flatMap(I=>I.kind==="thread"?[I.id]:[]),...u.flatMap(I=>I.threadId?[I.threadId]:[])])].filter(I=>!t||t.has(I));return{id:p.id,kind:p.kind,state:p.state,statement:p.statement,rationale:p.rationale,scope:structuredClone(p.scope),createdAt:p.createdAt,updatedAt:p.updatedAt,evidenceCount:u.length,recentEvidence:u.slice(0,4),concrete:p.concreteBindings.map(I=>({...structuredClone(I)})),relations:[...l,...o],sourceThreadIds:g,needsGrounding:p.state==="testing"&&y.has(p.id)}}).sort((p,u)=>Number(u.needsGrounding)-Number(p.needsGrounding)||w[p.state]-w[u.state]||u.updatedAt.localeCompare(p.updatedAt)),a={total:h.filter(p=>p.state!=="retired").length,emerging:h.filter(p=>p.state==="emerging").length,testing:h.filter(p=>p.state==="testing").length,grounded:h.filter(p=>p.state==="grounded").length,challenged:h.filter(p=>p.state==="challenged").length,retired:h.filter(p=>p.state==="retired").length,needsGrounding:h.filter(p=>p.needsGrounding).length};return{head:{sequence:r.report.headSequence,updatedAt:r.bundle.manifest.updatedAt},counts:a,explanations:h}}async getModelView(){if(!(await this.status()).initialized)return{decisions:[],entries:[]};let{bundle:e}=await this.store.load(),t=new Set(e.records.flatMap(m=>m.recordType==="decision"&&m.state==="active"?[m.id]:[])),i=new Map;for(let m of e.records.filter(y=>y.recordType==="model_entry").sort((y,f)=>y.createdAt.localeCompare(f.createdAt)))m.decisionIds.some(y=>t.has(y))&&i.set(m.key,m);let r=[...i.values()],c=e.records.filter(m=>m.recordType==="verification_attempt");return{decisions:e.records.filter(m=>m.recordType==="decision"&&m.state==="active").map(m=>{let y=c.filter(f=>f.targets.some(x=>x.entityType==="decision"&&x.entityId===m.id)).sort((f,x)=>x.createdAt.localeCompare(f.createdAt))[0];return{id:m.id,kind:m.kind,claim:m.claim,projected:r.some(f=>f.decisionIds.includes(m.id)),verification:y?y.state:"unverified"}}),entries:r.map(m=>({id:m.id,key:m.key,value:m.value,decisionIds:m.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(),i=t.bundle.records.find(b=>b.recordType==="participant"&&b.kind==="human"&&b.status==="active"),r=t.bundle.records.find(b=>b.recordType==="subject"&&b.subjectType==="project");if(!i||!r)throw new Error("Canonical owner or project subject is unavailable.");let c=Date.now(),d=new Date(c).toISOString(),m=E(c),y=E(c),f=E(c),x=E(c),T=E(c),v=new Set(t.bundle.records.flatMap(b=>b.recordType==="model_entry"&&b.key===e.key?b.decisionIds:[])),w=t.bundle.records.filter(b=>b.recordType==="decision"&&b.state==="active"&&v.has(b.id)),h={schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:d,participantId:i.id,sourceRefs:[{kind:"external",id:e.key,uri:"popmelt:model-pane"}]},a=[{subjectId:r.id,role:"governed"}],p={...h,id:m,recordType:"proposal",state:"accepted",claim:e.claim,proposedKind:"rule",subjects:a,origin:{mode:"declared",sourceText:e.claim,reviewedById:i.id}},u={...h,id:y,recordType:"lifecycle_event",entity:{entityType:"proposal",entityId:m},eventType:"accept",fromState:"pending",toState:"accepted",authority:{level:"owner",mode:"local_trusted"},reason:"The owner explicitly changed the projected model in the Model pane."},l={...h,id:f,recordType:"decision",proposalId:m,acceptanceEventId:y,acceptedById:i.id,authority:{level:"owner",mode:"local_trusted"},state:"active",kind:"rule",claim:e.claim,subjects:a,noChange:!1,effectiveAt:d},o={...h,id:x,recordType:"model_entry",key:e.key,subjectIds:[r.id],decisionIds:[f],value:e.value},g={...h,id:T,recordType:"model_projection",state:"applied",runId:`model-pane:${e.key}:${c}`,appliedById:i.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:d,decisionIds:[f],entryIds:[x],coverage:[{decisionId:f,status:"projected"}]},I={...h,id:E(c),recordType:"relationship",relationshipType:"derived_from",from:{entityType:"model_entry",entityId:x},to:{entityType:"decision",entityId:f},reason:"The model change is projected from the owner-confirmed decision."},s=w.map(b=>({...h,id:E(c),recordType:"lifecycle_event",entity:{entityType:"decision",entityId:b.id},eventType:"decision.superseded",fromState:"active",toState:"superseded",authority:{level:"owner",mode:"local_trusted"},reason:`A newer explicit model declaration replaced ${e.key}.`})),S=w.map(b=>({...h,id:E(c),recordType:"relationship",relationshipType:"supersedes",from:{entityType:"decision",entityId:l.id},to:{entityType:"decision",entityId:b.id},reason:`The owner replaced the previous declaration for ${e.key}.`,authority:{level:"owner",mode:"local_trusted"}})),k=await this.store.commit({records:[p,l,o,g],events:[u,...s],relationships:[I,...S],artifacts:[],tombstones:[],projectionUpdates:w.map(b=>({entityType:"decision",entityId:b.id,fromState:"active",state:"superseded"}))},{transactionId:E(c),committedAt:d});return await this.refreshIndex(k),{decisionId:f,entryId:x}}async findPendingProposalForLegacyDecision(e){if(!(await this.status()).initialized)return null;let{bundle:t}=await this.store.load(),i=t.records.find(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(c=>c.id===e));return i?{proposalId:i.id,claim:i.claim}:null}async findPendingProposalsForThread(e){if(this.initializationPromise&&await this.initializationPromise,!(await this.status()).initialized)return[];let{bundle:t}=await this.store.load(),i=new Map(t.records.flatMap(r=>r.recordType==="subject"?[[r.id,r.label]]:[]));return t.records.filter(r=>r.recordType==="proposal"&&r.state==="pending"&&r.sourceRefs.some(c=>c.kind==="thread"&&c.id===e)).sort((r,c)=>r.createdAt.localeCompare(c.createdAt)).map(r=>({proposalId:r.id,claim:r.claim,rationale:r.rationale,proposedKind:r.proposedKind,subjectLabels:r.subjects.flatMap(c=>{let d=i.get(c.subjectId);return d?[d]:[]})}))}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 r=t.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 c=t.bundle.records.find(h=>h.recordType==="participant"&&h.kind==="human"&&h.status==="active");if(!c)throw new Error("No active local owner participant is available.");let d=Date.now(),m=new Date(d).toISOString(),y=E(d),f=e.changes.map(h=>{let a=h.decisionIds?.filter(l=>e.decisionIds.includes(l)),p=a?.length?a:e.decisionIds,u=[...new Set(r.filter(l=>p.includes(l.id)).flatMap(l=>l.subjects.map(o=>o.subjectId)))];return{id:E(d),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:m,participantId:c.id,sourceRefs:p.map(l=>({kind:"record",id:l})),recordType:"model_entry",key:h.path.map(String).join("."),subjectIds:u,decisionIds:p,value:h.value}}),x=new Set(f.flatMap(h=>h.decisionIds)),T={id:y,schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:m,participantId:c.id,sourceRefs:e.decisionIds.map(h=>({kind:"record",id:h})),recordType:"model_projection",state:"applied",runId:e.runId,presentationJobId:e.presentationJobId,appliedById:c.id,authority:{level:"owner",mode:"local_trusted"},appliedAt:m,decisionIds:e.decisionIds,entryIds:f.map(h=>h.id),coverage:e.decisionIds.map(h=>e.coverage?.find(a=>a.decisionId===h)??{decisionId:h,status:x.has(h)?"projected":"unprojected"})},v=f.flatMap(h=>h.decisionIds.map(a=>({id:E(d),schemaVersion:1,projectId:t.bundle.manifest.projectId,createdAt:m,participantId:c.id,sourceRefs:[{kind:"record",id:T.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:[...f,T],events:[],relationships:v,artifacts:[],tombstones:[],projectionUpdates:[]},{transactionId:E(d),committedAt:m});return await this.refreshIndex(w),{projectionId:y,entryIds:f.map(h=>h.id),headSequence:w.report.headSequence}}async loadSource(e){return(await this.status()).initialized?this.loadJournalSource():{source:"legacy_preview",bundle:(await Re({...e,projectRoot:this.projectRoot})).bundle}}async loadJournalSource(){let e=await this.store.readHead(),t=`${e.checkpointSequence}:${e.checkpointHash}:${e.sequence}:${e.hash??""}`;if(this.contextualSourceCache?.headKey===t)return this.contextualSourceCache.value;let i=await this.store.load(),r={source:"journal",bundle:i.bundle,journal:i.report};return this.contextualSourceCache={headKey:t,value:r},r}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}),r=ft(i,t.subjectHints??[]);return r?{...t,subjectIds:[...new Set([...t.subjectIds??[],...r.subjectIds])],candidateDecisionIds:r.decisionIds,candidateProposalIds:r.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 me(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Expected a JSON object.");return n}function D(n,e){if(typeof n!="string"||!n.trim())throw new Error(`${e} must be a non-empty string.`);return n}function ue(n,e,t){let i=D(n,e);if(!t.includes(i))throw new Error(`${e} is invalid.`);return i}function un(n){let e=me(n),t=me(e.authority),i=t.level,r=t.mode,c=ue(i,"authority.level",["owner","delegate","contributor"]),d=ue(r,"authority.mode",["local_trusted","hosted"]),m={proposalId:D(e.proposalId,"proposalId"),participantId:D(e.participantId,"participantId"),occurredAt:D(e.occurredAt,"occurredAt"),authority:{level:c,mode:d,grantId:typeof t.grantId=="string"?t.grantId:void 0}};switch(e.action){case"accept":return{...m,action:"accept",eventId:D(e.eventId,"eventId"),decisionId:D(e.decisionId,"decisionId"),kind:ue(e.kind,"kind",["principle","preference","rule","constraint"]),reason:D(e.reason,"reason"),rationale:typeof e.rationale=="string"?e.rationale:void 0};case"reject":return{...m,action:"reject",eventId:D(e.eventId,"eventId"),reason:D(e.reason,"reason")};case"defer":{let y=me(e.context);if(!Array.isArray(y.subjectIds)||!Array.isArray(y.resurfaceWhen))throw new Error("Deferral context requires subjectIds and resurfaceWhen arrays.");return{...m,action:"defer",eventId:D(e.eventId,"eventId"),reason:typeof e.reason=="string"?e.reason:void 0,context:{taskContext:typeof y.taskContext=="string"?y.taskContext:void 0,subjectIds:y.subjectIds.map(f=>D(f,"subjectId")),resurfaceWhen:y.resurfaceWhen.map(f=>ue(f,"resurfaceWhen",["different_action","new_evidence","new_conflict","owner_request","after_date"])),revisitAfter:typeof y.revisitAfter=="string"?y.revisitAfter:void 0}}}case"edit_and_accept":{if(!Array.isArray(e.subjects))throw new Error("subjects must be an array.");return{...m,action:"edit_and_accept",withdrawalEventId:D(e.withdrawalEventId,"withdrawalEventId"),replacementProposalId:D(e.replacementProposalId,"replacementProposalId"),acceptanceEventId:D(e.acceptanceEventId,"acceptanceEventId"),decisionId:D(e.decisionId,"decisionId"),relationshipId:D(e.relationshipId,"relationshipId"),claim:D(e.claim,"claim"),kind:ue(e.kind,"kind",["principle","preference","rule","constraint"]),subjects:e.subjects.map(y=>{let f=me(y);return{subjectId:D(f.subjectId,"subjectId"),role:ue(f.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:D(e.reason,"reason")}}default:throw new Error("Unsupported owner review action.")}}function mn(n){let e=me(n),t=(c,d)=>{if(c!==void 0){if(!Array.isArray(c))throw new Error(`${d} must be an array.`);return c.map(m=>D(m,d))}},i=(c,d)=>{if(c!==void 0){if(typeof c!="number"||!Number.isFinite(c)||c<=0)throw new Error(`${d} must be a positive number.`);return c}},r=e.resurface===void 0?void 0:me(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:r?{differentAction:r.differentAction===!0,newEvidence:r.newEvidence===!0,newConflict:r.newConflict===!0,ownerRequested:r.ownerRequested===!0}:void 0}}export{we as MemoryJournalStore,Qe as MemoryService,Ne as computeTransactionHash,mn as parseContextualReviewQuery,un as parseOwnerReviewCommand};
|
|
1
|
+
import{f as e,g as o,h as r,i as t,j as a}from"./chunk-GL4I4MI6.mjs";import"./chunk-QXVMGZFP.mjs";export{o as MemoryJournalStore,r as MemoryService,e as computeTransactionHash,a as parseContextualReviewQuery,t as parseOwnerReviewCommand};
|
package/dist/plugin-astro.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-YBULEE33.mjs";import"./chunk-HPQJKWK5.mjs";import"./chunk-NOHXTT24.mjs";import{fileURLToPath as d}from"url";function c(t={}){return{name:"popmelt",hooks:{"astro:config:setup"({command:r,config:i,updateConfig:n,injectScript:p}){if(r!=="dev")return;let{client:e=!0,multiplayer:a=!1,...s}=t;n({vite:{plugins:[o({...s,projectRoot:t.projectRoot??d(i.root)})],optimizeDeps:{include:e?["react","react/jsx-runtime","react/jsx-dev-runtime","react-dom","react-dom/client","lucide-react"]:[]}}}),p("page",e?l(a):`
|
|
2
2
|
import { bridgeUrl, projectId } from 'virtual:popmelt/bridge';
|
|
3
3
|
if (bridgeUrl) window.__POPMELT_BRIDGE_URL__ = bridgeUrl;
|
|
4
4
|
if (projectId) window.__POPMELT_PROJECT_ID__ = projectId;
|
package/dist/plugin-nuxt.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as s,b as l}from"./chunk-
|
|
1
|
+
import{a as s,b as l}from"./chunk-HPQJKWK5.mjs";import{b as i}from"./chunk-NOHXTT24.mjs";import{addPluginTemplate as d,defineNuxtModule as m}from"nuxt/kit";var a=m({meta:{name:"@popmelt.com/core/nuxt",configKey:"popmelt"},async setup(o,e){if(!e.options.dev)return;let n={config:{server:e.options.devServer},middlewares:{use(){}}},t=await s({...o,projectRoot:o.projectRoot??e.options.rootDir},n,3e3);if(t.port===null)return;e.hook("vite:extend",({config:p})=>{p.optimizeDeps??={},p.optimizeDeps.include=[...new Set([...p.optimizeDeps.include??[],"react","react/jsx-runtime","react/jsx-dev-runtime","react-dom","react-dom/client","lucide-react"])]});let r=await l(t,n),u=r?i(r):void 0;e.hook("close",async()=>{u?.(),await r?.release()}),d({filename:"popmelt.client.mjs",mode:"client",getContents:()=>`import { defineNuxtPlugin } from '#app';
|
|
2
2
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
3
3
|
let disposed = false;
|
|
4
4
|
let mounting;
|
package/dist/plugin-vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-YBULEE33.mjs";import"./chunk-HPQJKWK5.mjs";import"./chunk-NOHXTT24.mjs";export{a as popmelt};
|
package/dist/server.d.mts
CHANGED
|
@@ -1,296 +1,8 @@
|
|
|
1
|
+
import { P as ParticipantAgentAdapter, c as ParticipantCredential, d as PopmeltHandle, e as ImprintGraph, f as ImprintTransaction, g as ImprintMutation, h as ImprintContext, i as ImprintSummaryKind, j as ImprintExplanationKind, k as ImprintScope, l as ImprintTopologyRelationType, m as ImprintExplanationRef, I as ImprintThreadSummary, a as ImprintGroundingAction, n as ImprintRelation, Q as QualifiedImprintRelation, o as PopmeltOptions } from './types-Bur49CLH.mjs';
|
|
2
|
+
export { p as ImprintConcrete, q as ImprintEvidence, r as ImprintExplanation, s as ImprintExplanationState, t as ImprintRelationType, u as ParticipantAgentView } from './types-Bur49CLH.mjs';
|
|
1
3
|
import * as node_http from 'node:http';
|
|
2
4
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
3
5
|
|
|
4
|
-
declare const STICKER_COLOR_NAMES: readonly ["slate", "gray", "zinc", "neutral", "stone", "red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "sky", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose"];
|
|
5
|
-
type StickerColorName = (typeof STICKER_COLOR_NAMES)[number];
|
|
6
|
-
|
|
7
|
-
declare const STICKER_FAMILIES: readonly ["padding", "margin", "border", "radius", "stack", "grid", "text", "color", "transform", "opacity"];
|
|
8
|
-
type StickerFamily = (typeof STICKER_FAMILIES)[number];
|
|
9
|
-
type StickerSubproperty = 'all' | 'x' | 'y' | 'top' | 'right' | 'bottom' | 'left' | 'top-left' | 'top-right' | 'bottom-right' | 'bottom-left' | 'vertical' | 'horizontal' | 'direction' | 'gap' | 'align' | 'justify' | 'rows' | 'columns' | 'size' | 'weight' | 'line-height' | 'letter-spacing' | 'text-align' | 'color' | 'translate' | 'scale' | 'rotate' | 'opacity' | 'mix-blend' | StickerColorName;
|
|
10
|
-
|
|
11
|
-
type Provider = 'claude' | 'codex' | 'copilot' | 'omp';
|
|
12
|
-
|
|
13
|
-
/** Renderer-owned identity for a target that does not exist as a DOM node. */
|
|
14
|
-
type OpaqueTargetReference = {
|
|
15
|
-
adapter: string;
|
|
16
|
-
key: string;
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
/** Local preview protocol. Peers never supply reducer actions or host authority. */
|
|
20
|
-
type PeerAction = {
|
|
21
|
-
type: 'tokens';
|
|
22
|
-
family?: StickerFamily;
|
|
23
|
-
subproperty?: StickerSubproperty;
|
|
24
|
-
} | {
|
|
25
|
-
type: 'inspect';
|
|
26
|
-
selector: string;
|
|
27
|
-
target?: OpaqueTargetReference;
|
|
28
|
-
properties?: string[];
|
|
29
|
-
plane?: 'own' | 'host';
|
|
30
|
-
} | {
|
|
31
|
-
type: 'comment';
|
|
32
|
-
selector: string;
|
|
33
|
-
target?: OpaqueTargetReference;
|
|
34
|
-
text: string;
|
|
35
|
-
} | {
|
|
36
|
-
type: 'clear';
|
|
37
|
-
selector: string;
|
|
38
|
-
kind: 'comment' | 'style' | 'all';
|
|
39
|
-
} | {
|
|
40
|
-
type: 'style';
|
|
41
|
-
selector: string;
|
|
42
|
-
property: string;
|
|
43
|
-
value: string;
|
|
44
|
-
} | {
|
|
45
|
-
type: 'style';
|
|
46
|
-
selector: string;
|
|
47
|
-
token: string;
|
|
48
|
-
family?: StickerFamily;
|
|
49
|
-
} | {
|
|
50
|
-
type: 'attention';
|
|
51
|
-
selector: string | null;
|
|
52
|
-
target?: OpaqueTargetReference;
|
|
53
|
-
activity?: 'looking' | 'working';
|
|
54
|
-
} | {
|
|
55
|
-
type: 'undo' | 'redo' | 'send' | 'rebase';
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
/** A capability for a person/agent. Keep out of URLs, logs, and peer snapshots. */
|
|
59
|
-
type ParticipantCredential = {
|
|
60
|
-
participantId: string;
|
|
61
|
-
token: string;
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
/** Browser hosting is replaceable; this boundary owns only local agent enrollment. */
|
|
65
|
-
type ParticipantAgentView = {
|
|
66
|
-
act(action: PeerAction): Promise<unknown>;
|
|
67
|
-
close(): Promise<void>;
|
|
68
|
-
};
|
|
69
|
-
type ParticipantAgentAdapter = (credential: ParticipantCredential) => Promise<ParticipantAgentView>;
|
|
70
|
-
|
|
71
|
-
/** Public endpoints only. Signing keys and credentials never belong here. */
|
|
72
|
-
type CloudTasteEnvironment = 'production' | 'staging';
|
|
73
|
-
|
|
74
|
-
type ImprintExplanationKind = 'intention' | 'principle' | 'pattern';
|
|
75
|
-
type ImprintExplanationState = 'emerging' | 'testing' | 'grounded' | 'challenged' | 'retired';
|
|
76
|
-
type ImprintScopeKind = 'project' | 'route' | 'component' | 'selector' | 'file';
|
|
77
|
-
type ImprintScope = {
|
|
78
|
-
kind: ImprintScopeKind;
|
|
79
|
-
values: string[];
|
|
80
|
-
};
|
|
81
|
-
/** A store-qualified address; abstraction level is intentionally not encoded. */
|
|
82
|
-
type ImprintExplanationRef = {
|
|
83
|
-
storeId: string;
|
|
84
|
-
explanationId: string;
|
|
85
|
-
};
|
|
86
|
-
type ImprintEvidence = {
|
|
87
|
-
id: string;
|
|
88
|
-
kind: 'observation' | 'application' | 'confirmation' | 'correction' | 'exception' | 'rejection';
|
|
89
|
-
stance: 'supports' | 'challenges' | 'excepts';
|
|
90
|
-
summary: string;
|
|
91
|
-
threadId: string;
|
|
92
|
-
jobId: string;
|
|
93
|
-
createdAt: string;
|
|
94
|
-
};
|
|
95
|
-
type ImprintExplanation = {
|
|
96
|
-
id: string;
|
|
97
|
-
kind: ImprintExplanationKind;
|
|
98
|
-
statement: string;
|
|
99
|
-
rationale: string;
|
|
100
|
-
scope: ImprintScope;
|
|
101
|
-
state: ImprintExplanationState;
|
|
102
|
-
createdAt: string;
|
|
103
|
-
updatedAt: string;
|
|
104
|
-
evidence: ImprintEvidence[];
|
|
105
|
-
supersededBy?: string;
|
|
106
|
-
};
|
|
107
|
-
type ImprintConcrete = {
|
|
108
|
-
id: string;
|
|
109
|
-
modelPath: string;
|
|
110
|
-
value: unknown;
|
|
111
|
-
createdAt: string;
|
|
112
|
-
updatedAt: string;
|
|
113
|
-
};
|
|
114
|
-
type ImprintTopologyRelationType = 'expresses' | 'excepts';
|
|
115
|
-
/**
|
|
116
|
-
* Historical relation names remain readable so append-only Imprint journals can
|
|
117
|
-
* be replayed. New writers must use ImprintTopologyRelationType.
|
|
118
|
-
*/
|
|
119
|
-
type LegacyImprintRelationType = 'operationalizes' | 'refines' | 'supports' | 'contradicts' | 'instantiates' | 'supersedes';
|
|
120
|
-
type ImprintRelationType = ImprintTopologyRelationType | LegacyImprintRelationType;
|
|
121
|
-
type ImprintRelation = {
|
|
122
|
-
id: string;
|
|
123
|
-
type: ImprintRelationType;
|
|
124
|
-
/** The source explanation is always owned by this relation's store. */
|
|
125
|
-
fromId: string;
|
|
126
|
-
/** Omitted for a target in this relation's owning store. */
|
|
127
|
-
toStoreId?: string;
|
|
128
|
-
toId: string;
|
|
129
|
-
rationale: string;
|
|
130
|
-
createdAt: string;
|
|
131
|
-
};
|
|
132
|
-
type QualifiedImprintRelation = Omit<ImprintRelation, 'fromId' | 'toId' | 'toStoreId'> & {
|
|
133
|
-
from: ImprintExplanationRef;
|
|
134
|
-
to: ImprintExplanationRef;
|
|
135
|
-
};
|
|
136
|
-
type ImprintGraph = {
|
|
137
|
-
version: 1;
|
|
138
|
-
projectId: string;
|
|
139
|
-
createdAt: string;
|
|
140
|
-
updatedAt: string;
|
|
141
|
-
head: {
|
|
142
|
-
sequence: number;
|
|
143
|
-
hash: string | null;
|
|
144
|
-
};
|
|
145
|
-
explanations: ImprintExplanation[];
|
|
146
|
-
concrete: ImprintConcrete[];
|
|
147
|
-
relations: ImprintRelation[];
|
|
148
|
-
};
|
|
149
|
-
type ImprintMutation = {
|
|
150
|
-
op: 'add_explanation';
|
|
151
|
-
explanation: ImprintExplanation;
|
|
152
|
-
} | {
|
|
153
|
-
op: 'replace_explanation';
|
|
154
|
-
explanation: ImprintExplanation;
|
|
155
|
-
} | {
|
|
156
|
-
op: 'remove_explanation';
|
|
157
|
-
explanationId: string;
|
|
158
|
-
} | {
|
|
159
|
-
op: 'add_concrete';
|
|
160
|
-
concrete: ImprintConcrete;
|
|
161
|
-
} | {
|
|
162
|
-
op: 'remove_concrete';
|
|
163
|
-
concreteId: string;
|
|
164
|
-
} | {
|
|
165
|
-
op: 'add_evidence';
|
|
166
|
-
explanationId: string;
|
|
167
|
-
evidence: ImprintEvidence;
|
|
168
|
-
} | {
|
|
169
|
-
op: 'revise_explanation';
|
|
170
|
-
explanationId: string;
|
|
171
|
-
patch: Partial<Pick<ImprintExplanation, 'statement' | 'rationale' | 'scope' | 'state' | 'supersededBy'>>;
|
|
172
|
-
updatedAt: string;
|
|
173
|
-
} | {
|
|
174
|
-
op: 'add_relation';
|
|
175
|
-
relation: ImprintRelation;
|
|
176
|
-
} | {
|
|
177
|
-
op: 'remove_relation';
|
|
178
|
-
relationId: string;
|
|
179
|
-
};
|
|
180
|
-
type ImprintTransaction = {
|
|
181
|
-
version: 1;
|
|
182
|
-
sequence: number;
|
|
183
|
-
transactionId: string;
|
|
184
|
-
projectId: string;
|
|
185
|
-
committedAt: string;
|
|
186
|
-
previousHash: string | null;
|
|
187
|
-
hash: string;
|
|
188
|
-
source: {
|
|
189
|
-
kind: 'automatic' | 'grounding' | 'correction' | 'migration' | 'undo';
|
|
190
|
-
threadId: string;
|
|
191
|
-
jobId: string;
|
|
192
|
-
};
|
|
193
|
-
summary: string;
|
|
194
|
-
mutations: ImprintMutation[];
|
|
195
|
-
inverseMutations: ImprintMutation[];
|
|
196
|
-
undoesTransactionId?: string;
|
|
197
|
-
};
|
|
198
|
-
type ImprintSummaryKind = 'added' | 'strengthened' | 'refined' | 'challenged' | 'exception' | 'consolidated';
|
|
199
|
-
type ImprintThreadSummary = {
|
|
200
|
-
transactionId: string;
|
|
201
|
-
coalescedTransactionIds?: string[];
|
|
202
|
-
additionalObservationCount?: number;
|
|
203
|
-
kind: ImprintSummaryKind;
|
|
204
|
-
title: string;
|
|
205
|
-
detail: string;
|
|
206
|
-
changes: Array<{
|
|
207
|
-
explanationId: string;
|
|
208
|
-
action: 'added' | 'revised' | 'supported' | 'challenged' | 'retired' | 'related';
|
|
209
|
-
statement: string;
|
|
210
|
-
state: ImprintExplanationState;
|
|
211
|
-
}>;
|
|
212
|
-
grounding?: {
|
|
213
|
-
explanationId: string;
|
|
214
|
-
question: string;
|
|
215
|
-
state: 'testing';
|
|
216
|
-
};
|
|
217
|
-
resolvedAction?: ImprintGroundingAction;
|
|
218
|
-
};
|
|
219
|
-
type ImprintGroundingAction = 'yes' | 'this_time' | 'no';
|
|
220
|
-
type ImprintContext = {
|
|
221
|
-
explanations: Array<Pick<ImprintExplanation, 'id' | 'kind' | 'statement' | 'rationale' | 'scope' | 'state'> & {
|
|
222
|
-
concrete: Array<Pick<ImprintConcrete, 'id' | 'modelPath' | 'value'>>;
|
|
223
|
-
/** Internal canonical-memory address; omitted from model-facing prompts. */
|
|
224
|
-
memoryId?: string;
|
|
225
|
-
storeId?: string;
|
|
226
|
-
storeRoot?: string;
|
|
227
|
-
readOnly?: boolean;
|
|
228
|
-
}>;
|
|
229
|
-
truncated: boolean;
|
|
230
|
-
pendingGroundingExplanationIds?: string[];
|
|
231
|
-
correctionExplanationIds?: string[];
|
|
232
|
-
relations?: Array<Pick<ImprintRelation, 'id' | 'type' | 'fromId' | 'toId' | 'toStoreId' | 'rationale'> & {
|
|
233
|
-
/** The store that owns the relation record. */
|
|
234
|
-
storeId?: string;
|
|
235
|
-
readOnly?: boolean;
|
|
236
|
-
/** Present for composed reads; local single-store callers retain fromId/toId. */
|
|
237
|
-
from?: ImprintExplanationRef;
|
|
238
|
-
to?: ImprintExplanationRef;
|
|
239
|
-
}>;
|
|
240
|
-
/** Explicit target/reference language detected in the current request. */
|
|
241
|
-
retrievalIntent?: {
|
|
242
|
-
target: string;
|
|
243
|
-
reference: string;
|
|
244
|
-
};
|
|
245
|
-
/**
|
|
246
|
-
* Directly relevant rejected history. These are warnings, not active
|
|
247
|
-
* explanations, and therefore cannot be cited as Imprint usage.
|
|
248
|
-
*/
|
|
249
|
-
historicalCaveats?: Array<Pick<ImprintExplanation, 'id' | 'kind' | 'statement' | 'rationale' | 'scope' | 'state'> & {
|
|
250
|
-
storeId?: string;
|
|
251
|
-
storeRoot?: string;
|
|
252
|
-
readOnly?: boolean;
|
|
253
|
-
}>;
|
|
254
|
-
unavailableStoreIds?: string[];
|
|
255
|
-
unavailableTopologyStoreIds?: string[];
|
|
256
|
-
};
|
|
257
|
-
|
|
258
|
-
type PopmeltOptions = {
|
|
259
|
-
port?: number;
|
|
260
|
-
projectRoot?: string;
|
|
261
|
-
tempDir?: string;
|
|
262
|
-
maxTurns?: number;
|
|
263
|
-
maxBudgetUsd?: number;
|
|
264
|
-
allowedTools?: string[];
|
|
265
|
-
claudePath?: string;
|
|
266
|
-
copilotPath?: string;
|
|
267
|
-
ompPath?: string;
|
|
268
|
-
provider?: Provider;
|
|
269
|
-
timeoutMs?: number;
|
|
270
|
-
devOrigin?: string;
|
|
271
|
-
/** Optional Chromium DevTools endpoint, e.g. http://127.0.0.1:9222. */
|
|
272
|
-
nativeCaptureUrl?: string;
|
|
273
|
-
restartMode?: 'embedded' | 'detached';
|
|
274
|
-
/** Requires a proven local host or participant host. Defaults to production; false disables cloud access. */
|
|
275
|
-
cloudTaste?: false | {
|
|
276
|
-
environment: CloudTasteEnvironment;
|
|
277
|
-
};
|
|
278
|
-
/** Internal opt-in. Collaboration authority is independent of app revisions. */
|
|
279
|
-
participantSessions?: {
|
|
280
|
-
/** Optional context metadata. Never used as a save, Send, or approval gate. */
|
|
281
|
-
sourceRevision?: () => Promise<string>;
|
|
282
|
-
agentAdapter?: ParticipantAgentAdapter;
|
|
283
|
-
};
|
|
284
|
-
};
|
|
285
|
-
type PopmeltHandle = {
|
|
286
|
-
port: number;
|
|
287
|
-
projectId: string;
|
|
288
|
-
storeId?: string;
|
|
289
|
-
/** Trusted local launch/recovery only; never publish this capability in HTML. */
|
|
290
|
-
participantHost?: () => Promise<ParticipantCredential>;
|
|
291
|
-
close: () => Promise<void>;
|
|
292
|
-
};
|
|
293
|
-
|
|
294
6
|
/** One disposable, local Chrome profile per agent. Never attaches to a user's browser. */
|
|
295
7
|
declare function managedParticipantBrowser(url: string): ParticipantAgentAdapter;
|
|
296
8
|
|
|
@@ -543,4 +255,4 @@ type StartPopmeltOptions = PopmeltOptions & {
|
|
|
543
255
|
};
|
|
544
256
|
declare function startPopmelt(options?: StartPopmeltOptions): Promise<PopmeltHandle>;
|
|
545
257
|
|
|
546
|
-
export {
|
|
258
|
+
export { ImprintContext, ImprintExplanationKind, ImprintExplanationRef, ImprintGraph, ImprintGroundingAction, ImprintMutation, ImprintRelation, ImprintScope, ImprintService, ImprintStore, ImprintThreadSummary, ImprintTransaction, ParticipantAgentAdapter, PopmeltHandle, PopmeltOptions, QualifiedImprintRelation, type StartPopmeltOptions, createParticipantDevBootstrap, createParticipantHostEntry, formatImprintPrompt, imprintExplanationRef, managedParticipantBrowser, parseImprintDraft, qualifyImprintRelation, startPopmelt };
|