@popmelt.com/core 0.8.13 → 0.8.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-entry.mjs +69 -67
- package/dist/{chunk-X3ENE5RX.mjs → chunk-JJEESG5Y.mjs} +1 -1
- package/dist/cli.mjs +66 -64
- package/dist/index.mjs +45 -39
- package/dist/memory-legacy.d.mts +4 -0
- package/dist/memory-legacy.mjs +1 -1
- package/dist/memory-store.d.mts +17 -3
- package/dist/memory-store.mjs +3 -3
- package/dist/memory.d.mts +4 -0
- package/dist/memory.mjs +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server-SESHQYMR.mjs +213 -0
- package/dist/server.d.mts +52 -9
- package/dist/server.mjs +63 -61
- package/package.json +1 -1
- package/dist/server-UH23TSES.mjs +0 -211
package/dist/memory.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ee=1,te=1;var ie=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function P(t){return ie.test(t)}function W(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function u(t,e,n,c){t.push({path:e,code:n,message:c,severity:"error"})}function N(t,e,n,c){t.push({path:e,code:n,message:c,severity:"warning"})}function R(t,e,n){P(n)||u(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function A(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&u(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function $(t,e,n,c=!1){c&&n.level==="contributor"&&u(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&u(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ne={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),advisory_explanation:new Set(["null->emerging","null->testing","null->grounded","null->challenged","null->retired","emerging->testing","emerging->grounded","emerging->challenged","emerging->retired","testing->grounded","testing->challenged","testing->retired","grounded->challenged","grounded->retired","challenged->testing","challenged->retired"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},oe=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function re(t,e,n){R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),R(t,`${n}.entity.entityId`,e.entity.entityId),A(t,`${n}.createdAt`,e.createdAt),$(t,`${n}.authority`,e.authority);let c=ne[e.entity.entityType],m=`${e.fromState??"null"}->${e.toState}`;c&&!c.has(m)&&u(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${m}.`);let p=`${e.entity.entityType}:${e.toState}`;if(oe.has(p)&&($(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||u(t,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let a=e.transitionContext;(a?.kind!=="proposal_deferral"||a.resurfaceWhen.length===0)&&u(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),a?.resurfaceWhen.includes("after_date")&&!a.revisitAfter&&u(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),a?.revisitAfter&&A(t,`${n}.transitionContext.revisitAfter`,a.revisitAfter)}}function se(t,e,n,c){R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),A(t,`${n}.createdAt`,e.createdAt),e.projectId!==c&&u(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&u(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&u(t,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&u(t,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&($(t,`${n}.authority`,e.authority,!0),e.claim.trim()||u(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&N(t,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&u(t,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),A(t,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&u(t,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(m=>!m.trim())&&u(t,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((m,p)=>{(!m.id.trim()||!m.modelPath.trim())&&u(t,`${n}.concreteBindings[${p}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),A(t,`${n}.concreteBindings[${p}].createdAt`,m.createdAt),A(t,`${n}.concreteBindings[${p}].updatedAt`,m.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&u(t,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(A(t,`${n}.appliedAt`,e.appliedAt),$(t,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&u(t,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&u(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(m=>!m.trim()))&&u(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&N(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&N(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ae(t,e,n){if(R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),R(t,`${n}.from.entityId`,e.from.entityId),R(t,`${n}.to.entityId`,e.to.entityId),A(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||u(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let m=e.from.entityType==="decision"&&e.to.entityType==="decision",p=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!m&&!p&&u(t,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),m&&!e.authority?u(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):m&&e.authority&&$(t,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&u(t,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&u(t,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&u(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&u(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function z(t){let e=[];R(e,"manifest.projectId",t.manifest.projectId),A(e,"manifest.createdAt",t.manifest.createdAt),A(e,"manifest.updatedAt",t.manifest.updatedAt);let n=new Map,c=(i,s)=>{let o=n.get(i);o?u(e,s,"duplicate_id",`ID is already used at ${o}.`):n.set(i,s)};t.records.forEach((i,s)=>{let o=`records[${s}]`;c(i.id,o),se(e,i,o,t.manifest.projectId)}),t.events.forEach((i,s)=>{let o=`events[${s}]`;c(i.id,o),re(e,i,o),i.projectId!==t.manifest.projectId&&u(e,`${o}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((i,s)=>{let o=`relationships[${s}]`;c(i.id,o),ae(e,i,o),i.projectId!==t.manifest.projectId&&u(e,`${o}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((i,s)=>{c(i.id,`artifacts[${s}]`),R(e,`artifacts[${s}].id`,i.id)}),t.tombstones.forEach((i,s)=>{let o=`tombstones[${s}]`;c(i.id,o),R(e,`${o}.id`,i.id),R(e,`${o}.objectId`,i.objectId),R(e,`${o}.deletedById`,i.deletedById),A(e,`${o}.deletedAt`,i.deletedAt),$(e,`${o}.authority`,i.authority,!0)});let m=new Set(t.records.map(i=>`${i.recordType}:${i.id}`)),p=new Set(t.tombstones.map(i=>`${i.objectType}:${i.objectId}`)),a=(i,s)=>{let o=`${i.entityType}:${i.entityId}`;!m.has(o)&&!p.has(o)&&u(e,s,"dangling_entity_reference",`No record or tombstone exists for ${o}.`)};t.events.forEach((i,s)=>a(i.entity,`events[${s}].entity`)),t.relationships.forEach((i,s)=>{a(i.from,`relationships[${s}].from`),a(i.to,`relationships[${s}].to`)});let v=new Set(t.artifacts.map(i=>i.id)),h=(i,s)=>{v.has(i)||u(e,s,"dangling_artifact_reference","No artifact manifest entry exists.")},f=(i,s,o)=>{!m.has(`${i}:${s}`)&&!p.has(`${i}:${s}`)&&u(e,o,"dangling_entity_reference",`No ${i} record or tombstone exists.`)};t.records.forEach((i,s)=>{let o=`records[${s}]`;switch(i.recordType){case"authority_grant":f("participant",i.granteeId,`${o}.granteeId`),f("participant",i.grantedById,`${o}.grantedById`),i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`));break;case"observation":i.captureContext.subjectIds.forEach((r,d)=>f("subject",r,`${o}.captureContext.subjectIds[${d}]`)),i.captureContext.artifactIds.forEach((r,d)=>h(r,`${o}.captureContext.artifactIds[${d}]`));break;case"proposal":case"decision":i.subjects.forEach((r,d)=>f("subject",r.subjectId,`${o}.subjects[${d}].subjectId`));break;case"thread":i.messageArtifactIds.forEach((r,d)=>h(r,`${o}.messageArtifactIds[${d}]`)),i.resultRefs.forEach((r,d)=>a(r,`${o}.resultRefs[${d}]`));break;case"iteration":i.threadIds.forEach((r,d)=>f("thread",r,`${o}.threadIds[${d}]`)),i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"evidence":i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"advisory_explanation":i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`)),i.supersededById&&f("advisory_explanation",i.supersededById,`${o}.supersededById`);break;case"implementation_attempt":i.iterationIds.forEach((r,d)=>f("iteration",r,`${o}.iterationIds[${d}]`)),i.coverageClaims.forEach((r,d)=>f("decision",r.decisionId,`${o}.coverageClaims[${d}].decisionId`)),i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"eval_spec":i.replacesSpecId&&f("eval_spec",i.replacesSpecId,`${o}.replacesSpecId`),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`)),i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),(i.dependencies??[]).forEach((r,d)=>{r.kind==="subject"&&r.subjectId&&f("subject",r.subjectId,`${o}.dependencies[${d}].subjectId`)}),(i.scenarios??[]).forEach((r,d)=>{r.subjectIds?.forEach((I,x)=>f("subject",I,`${o}.scenarios[${d}].subjectIds[${x}]`))}),i.targets.forEach((r,d)=>f(r.entityType,r.entityId,`${o}.targets[${d}]`));break;case"verification_attempt":i.evalSpecId&&f("eval_spec",i.evalSpecId,`${o}.evalSpecId`),i.targets.forEach((r,d)=>f(r.entityType,r.entityId,`${o}.targets[${d}]`)),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`));break;case"model_entry":i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`));break;case"model_projection":$(e,`${o}.authority`,i.authority,!0),f("participant",i.appliedById,`${o}.appliedById`),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`)),i.entryIds.forEach((r,d)=>f("model_entry",r,`${o}.entryIds[${d}]`)),i.coverage.forEach((r,d)=>f("decision",r.decisionId,`${o}.coverage[${d}].decisionId`));break;case"freshness_signal":a(i.target,`${o}.target`),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`));break;default:break}});let S=new Map(t.events.map(i=>[i.id,i])),T=new Map(t.records.map(i=>[`${i.recordType}:${i.id}`,i])),_=new Map;t.events.forEach((i,s)=>{let o=`${i.entity.entityType}:${i.entity.entityId}:${i.fromState??"null"}`,r=_.get(o)??new Set;r.add(i.toState),_.set(o,r),r.size>1&&u(e,`events[${s}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(t.records.flatMap(i=>i.recordType==="authority_grant"?[[i.id,i]]:[])),M=(i,s,o,r,d)=>{if(i.level!=="delegate"||!i.grantId)return;let I=b.get(i.grantId);if(!I){u(e,d,"invalid_authority_grant","Delegated authority references a missing grant.");return}(I.granteeId!==s||I.level!=="delegate")&&u(e,d,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let x=Date.parse(o);(x<Date.parse(I.startsAt)||I.endsAt&&x>Date.parse(I.endsAt)||I.revokedAt&&x>=Date.parse(I.revokedAt))&&u(e,d,"inactive_authority_grant","The delegated authority grant was not active at this time."),I.subjectIds.length&&r.length&&!r.every(y=>I.subjectIds.includes(y))&&u(e,d,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let i of t.records)i.recordType==="decision"&&M(i.authority,i.acceptedById,i.createdAt,i.subjects.map(s=>s.subjectId),`records:${i.id}.authority`);t.events.forEach((i,s)=>{let o=T.get(`${i.entity.entityType}:${i.entity.entityId}`),r=o&&"subjects"in o?o.subjects.map(d=>d.subjectId):[];M(i.authority,i.participantId,i.createdAt,r,`events[${s}].authority`)}),t.relationships.forEach((i,s)=>{if(!i.authority)return;let o=[i.from,i.to].flatMap(r=>{let d=T.get(`${r.entityType}:${r.entityId}`);return d&&"subjects"in d?d.subjects.map(I=>I.subjectId):[]});M(i.authority,i.participantId,i.createdAt,o,`relationships[${s}].authority`)});for(let i of t.records){if(i.recordType!=="decision")continue;let s=S.get(i.acceptanceEventId);(!s||s.entity.entityType!=="proposal"||s.entity.entityId!==i.proposalId||s.toState!=="accepted")&&u(e,`records:${i.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),s&&s.participantId!==i.acceptedById&&u(e,`records:${i.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${i.proposalId}`)||u(e,`records:${i.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),i.state==="superseded"&&(t.relationships.some(r=>r.relationshipType==="supersedes"&&r.to.entityType==="decision"&&r.to.entityId===i.id)||u(e,`records:${i.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),i.state==="revoked"&&(t.events.some(r=>r.entity.entityType==="decision"&&r.entity.entityId===i.id&&r.toState==="revoked"&&!!r.reason?.trim())||u(e,`records:${i.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let i of t.records){if(i.recordType!=="proposal"||i.state!=="accepted")continue;t.records.some(o=>o.recordType==="decision"&&o.proposalId===i.id)||u(e,`records:${i.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return W(e)}function ce(t){let e=[];R(e,"projectId",t.projectId),A(e,"retrievedAt",t.retrievedAt),t.budget.maxEstimatedTokens<=0&&u(e,"budget.maxEstimatedTokens","invalid_budget","Token budget must be positive."),t.budget.estimatedTokens>t.budget.maxEstimatedTokens&&u(e,"budget.estimatedTokens","token_budget_exceeded","Retrieval packet exceeds its declared context budget.");let n=new Set(t.uncertainties.map(p=>p.code));t.subjectMatches.some(p=>p.confidence==="unresolved")&&!n.has("subject_unresolved")&&u(e,"uncertainties","hidden_subject_uncertainty","Unresolved subject matches must be explicit in the packet."),t.decisions.length===0&&t.conflicts.length===0&&!n.has("no_applicable_decision")&&!n.has("subject_unresolved")&&u(e,"uncertainties","ambiguous_empty_result","An empty packet must explain whether no decision applies or the subject is unresolved."),t.completeness.status==="truncated"&&!n.has("retrieval_truncated")&&u(e,"uncertainties","silent_truncation","Truncated retrieval must be reported as uncertainty."),t.completeness.conflictsComplete||(t.completeness.status!=="truncated"&&u(e,"completeness.conflictsComplete","silent_conflict_truncation","Incomplete conflict coverage must mark the whole packet truncated."),n.has("retrieval_truncated")||u(e,"uncertainties","missing_conflict_expansion","Incomplete conflicts require explicit truncation and expansion guidance."));let m=new Set(t.decisions.map(p=>p.id));return t.conflicts.forEach((p,a)=>{p.decisionIds.length<2&&u(e,`conflicts[${a}].decisionIds`,"invalid_conflict","Conflicts need at least two applicable decisions.");for(let v of p.decisionIds)m.has(v)||u(e,`conflicts[${a}].decisionIds`,"missing_conflict_position","Every conflict position must be present in the compact decision list.")}),W(e)}var de=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function L(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function O(t){return new Set(L(t).split(" ").filter(e=>e.length>2&&!de.has(e)))}function Y(t,e){if(!t.size||!e.size)return 0;let n=0;for(let c of t)e.has(c)&&(n+=1);return n/Math.min(t.size,e.size)}function pe(t){return[{value:t.label,by:"label"},...t.aliases.map(e=>({value:e,by:"alias"})),...t.locators.map(e=>({value:e.value,by:"locator"}))]}function le(t,e){let n=new Map,c=new Set(e.subjectIds??[]),m=(e.subjectHints??[]).map(L).filter(Boolean),p=O([e.action,e.text].filter(Boolean).join(" "));for(let a of t){if(c.has(a.id)){n.set(a.id,{subjectId:a.id,label:a.label,confidence:"exact",matchedBy:"id",score:100});continue}let v;for(let h of pe(a)){let f=L(h.value);for(let _ of m){let b=f===_?95:f.includes(_)||_.includes(f)?75:0;b>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:b>=90?"exact":"strong",matchedBy:h.by,score:b})}let T=["/","#","[","]","="].some(_=>h.value.includes(_))?0:Math.round(Y(O(f),p)*55);T>=30&&T>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}v&&n.set(a.id,v)}return n}function ue(t,e){let n=new Set(t.sourceRefs.filter(a=>a.kind==="iteration").map(a=>a.id)),c=new Set(t.sourceRefs.filter(a=>a.kind==="thread").map(a=>a.id)),m=e.filter(a=>a.iterationIds.some(v=>n.has(v))||a.sourceRefs.some(v=>v.kind==="thread"&&c.has(v.id)));if(!m.length)return{state:"none_found",attemptIds:[]};let p=new Set(m.map(a=>a.state));return{state:p.size>1?"mixed":p.has("completed")?"completed":"attempted",attemptIds:m.map(a=>a.id)}}function me(t){return Math.ceil(JSON.stringify(t).length/4)}function ye(t,e){let n=t.records.filter(s=>s.recordType==="subject"),c=e.generatedAt??new Date().toISOString(),m=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,p=t.records.filter(s=>{if(s.recordType!=="proposal"||m&&!m.has(s.id))return!1;if(s.state==="pending")return!0;if(s.state!=="deferred")return!1;let o=[...t.events].reverse().find(r=>r.entity.entityType==="proposal"&&r.entity.entityId===s.id&&r.toState==="deferred"&&r.transitionContext?.kind==="proposal_deferral")?.transitionContext;return o?o.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||o.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||o.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||o.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||o.resurfaceWhen.includes("after_date")&&!!(o.revisitAfter&&Date.parse(c)>=Date.parse(o.revisitAfter)):!1}),a=t.records.filter(s=>s.recordType==="implementation_attempt"),v=le(n,e),h=[...v.values()].sort((s,o)=>o.score-s.score),f=O([e.action,e.text].filter(Boolean).join(" ")),S=p.flatMap(s=>{let o=s.subjects.map(x=>v.get(x.subjectId)).filter(x=>!!x),r=Math.max(0,...o.map(x=>x.score)),d=Math.round(Y(O(s.claim),f)*35),I=r+d;return I>=50?[{proposal:s,proposalMatches:o,score:I}]:[]}).sort((s,o)=>o.score-s.score||s.proposal.id.localeCompare(o.proposal.id)),T=Math.max(1,e.maxPackets??3),_=Math.max(200,e.maxEstimatedTokens??1200),b=[],M=0;for(let s of S){if(b.length>=T)break;let o=s.proposal.sourceRefs.slice(0,4),r={contractVersion:1,packetId:`review:${s.proposal.id}`,projectId:t.manifest.projectId,generatedAt:c,trigger:{action:e.action,reason:s.proposalMatches.length?`Historical proposal intersects ${s.proposalMatches.map(I=>I.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:s.proposalMatches.map(({score:I,...x})=>x)},proposal:{id:s.proposal.id,claim:s.proposal.claim,state:s.proposal.state,proposedKind:s.proposal.proposedKind,subjectIds:s.proposal.subjects.map(I=>I.subjectId),origin:s.proposal.origin.mode},authority:"unaccepted",presentation:s.score>=100&&["constraint","rule"].includes(s.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ue(s.proposal,a),evidence:{sourceCount:s.proposal.sourceRefs.length,sourceRefs:o},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:s.proposal.id},...o]},d={...r,estimatedTokens:me(r)};if(M+d.estimatedTokens>_)break;b.push(d),M+=d.estimatedTokens}let i=Math.max(0,S.length-b.length);return{packets:b,subjectMatches:h.map(({score:s,...o})=>o),completeness:{status:i>0?"truncated":"complete",consideredProposalCount:S.length,omittedPacketCount:i,maxEstimatedTokens:_,estimatedTokens:M},uncertainty:v.size===0?"subject_unresolved":S.length===0?"no_relevant_pending_proposal":void 0}}var fe=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function H(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function V(t){return new Set(H(t).split(" ").filter(e=>e.length>2&&!fe.has(e)))}function G(t,e){if(!t.size||!e.size)return 0;let n=0;for(let c of t)e.has(c)&&(n+=1);return n/Math.min(t.size,e.size)}function ve(t,e){let n=new Set(e.subjectIds??[]),c=(e.subjectHints??[]).map(H).filter(Boolean),m=V([e.action,e.text].filter(Boolean).join(" ")),p=[];for(let a of t){if(n.has(a.id)){p.push({subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:"exact",matchedBy:"id",score:100});continue}let v,h=[{value:a.label,by:"semantic"},...a.aliases.map(f=>({value:f,by:"alias"})),...a.locators.map(f=>({value:f.value,by:"locator"}))];for(let f of h){let S=H(f.value);for(let b of c){let M=S===b?95:S.includes(b)||b.includes(S)?75:0;M>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:M>=90?"exact":"strong",matchedBy:f.by,score:M})}let _=["/","#","[","]","="].some(b=>f.value.includes(b))?0:Math.round(G(V(S),m)*55);_>=30&&_>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:_>=45?"strong":"weak",matchedBy:"semantic",score:_})}v&&p.push(v)}return p.sort((a,v)=>v.score-a.score||a.subjectId.localeCompare(v.subjectId))}function ge(t){return Math.ceil(JSON.stringify(t).length/4)}function C(t,e){return t.relationshipType===e&&t.from.entityType==="decision"&&t.to.entityType==="decision"}function Ie(t,e){let n=e.filter(p=>p.coverageClaims.some(a=>a.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let c=n.filter(p=>p.state==="completed"),m=c.some(p=>p.coverageClaims.some(a=>a.decisionId===t&&a.coverage==="full"));return{decisionId:t,state:m?"implemented":c.length?"partial":"unknown",attemptIds:n.map(p=>p.id)}}function he(t,e,n){let c=e.filter(v=>v.targets.some(h=>h.entityType==="decision"&&h.entityId===t)).sort((v,h)=>h.createdAt.localeCompare(v.createdAt)),m=n.some(v=>v.signalType==="verification_expired"&&v.target.entityType==="decision"&&v.target.entityId===t),p=c[0],a=m?"stale":p?p.state==="passed"?"passing":p.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(p.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:a,attemptIds:c.map(v=>v.id)}}function be(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),c=Math.max(1,e.maxDecisions??6),m=t.records.filter(y=>y.recordType==="subject"),p=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,a=t.records.filter(y=>y.recordType==="decision"&&y.state==="active"),v=p?a.filter(y=>p.has(y.id)):a,h=t.records.filter(y=>y.recordType==="implementation_attempt"),f=t.records.filter(y=>y.recordType==="verification_attempt"),S=t.records.filter(y=>y.recordType==="freshness_signal"&&y.state==="open"),T=t.records.filter(y=>y.recordType==="evidence"),_=t.records.filter(y=>y.recordType==="model_entry"),b=ve(m,e),M=new Map(b.map(y=>[y.subjectId,y.score])),i=V([e.action,e.text].filter(Boolean).join(" ")),s=v.flatMap(y=>{let w=Math.max(0,...y.subjects.map(K=>M.get(K.subjectId)??0)),g=Math.round(G(V(y.claim),i)*35),k=w+g;return k>=50?[{decision:y,score:k}]:[]}).sort((y,w)=>w.score-y.score||y.decision.id.localeCompare(w.decision.id)),o=new Map;for(let y of s.slice(0,c))o.set(y.decision.id,y.decision);for(let y of t.relationships){if(!C(y,"excepts")&&!C(y,"contradicts"))continue;let w=a.find(k=>k.id===y.from.entityId),g=a.find(k=>k.id===y.to.entityId);!w||!g||!o.has(w.id)&&!o.has(g.id)||(o.size<c&&o.set(w.id,w),o.size<c&&o.set(g.id,g))}let r=[...o.values()],d=y=>y.from.entityType==="decision"&&y.to.entityType==="decision"&&o.has(y.from.entityId)&&o.has(y.to.entityId),I=(y,w=!1)=>{let g=new Set(y.map(l=>l.id)),k=S.filter(l=>l.target.entityType==="decision"&&g.has(l.target.entityId)),K=new Set(t.relationships.filter(l=>C(l,"excepts")&&g.has(l.from.entityId)&&g.has(l.to.entityId)).flatMap(l=>[l.from.entityId,l.to.entityId])),D=t.relationships.filter(l=>C(l,"contradicts")&&g.has(l.from.entityId)&&g.has(l.to.entityId)).map(l=>({id:l.id,decisionIds:[l.from.entityId,l.to.entityId],unresolvedQuestion:l.reason,expansionRefs:[{kind:"record",id:l.id}]})),Z=new Set(D.flatMap(l=>l.decisionIds)),F=T.filter(l=>l.sourceRefs.some(j=>j.kind==="record"&&g.has(j.id))||t.relationships.some(j=>j.relationshipType==="supports"&&j.from.entityType==="evidence"&&j.from.entityId===l.id&&j.to.entityType==="decision"&&g.has(j.to.entityId))),q=Math.max(0,s.length-y.length),J=t.relationships.some(l=>C(l,"contradicts")&&d(l)&&(!g.has(l.from.entityId)||!g.has(l.to.entityId))),Q=w||q>0||J,E=[];b.length===0&&(e.subjectHints?.length??0)>0?E.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):y.length===0&&E.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),D.length&&E.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:D.flatMap(l=>l.expansionRefs)}),F.some(l=>l.availability!=="available")&&E.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:F.map(l=>({kind:"record",id:l.id}))}),Q&&E.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:t.manifest.projectId}]});let U={contractVersion:1,projectId:t.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:b.map(({score:l,...j})=>j),modelEntries:_.filter(l=>l.decisionIds.some(j=>g.has(j))).map(l=>({id:l.id,key:l.key,value:l.value,decisionIds:l.decisionIds})),decisions:y.map(l=>({id:l.id,kind:l.kind,claim:l.claim,subjectIds:l.subjects.map(j=>j.subjectId),authority:l.authority,effectiveState:Z.has(l.id)?"conflicted":K.has(l.id)?"excepted":"active",freshness:k.filter(j=>j.target.entityId===l.id).map(j=>j.signalType),expansionRef:{kind:"record",id:l.id}})),conflicts:D,uncertainties:E,implementation:y.map(l=>Ie(l.id,h)),verification:y.map(l=>he(l.id,f,k)),evidence:F.map(l=>({evidenceId:l.id,summary:l.summary,availability:l.availability,sourceRefs:l.sourceRefs})),completeness:{status:Q?"truncated":"complete",omittedDecisionCount:q,omittedEvidenceCount:0,conflictsComplete:!J}};return U.budget.estimatedTokens=ge(U),U},x=I(r);for(;x.budget.estimatedTokens>n&&r.length>0;){let y=r.pop(),w=t.relationships.filter(g=>C(g,"contradicts")&&(g.from.entityId===y.id||g.to.entityId===y.id)).flatMap(g=>[g.from.entityId,g.to.entityId]);r=r.filter(g=>!w.includes(g.id)),x=I(r,!0)}return x}function B(t,e,n,c){return{id:c,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function X(t,e,n,c,m){return{id:m,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:c,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function _e(t){switch(t.action){case"accept":return[t.eventId,t.decisionId];case"edit_and_accept":return[t.withdrawalEventId,t.replacementProposalId,t.acceptanceEventId,t.decisionId,t.relationshipId];case"reject":case"defer":return[t.eventId]}}function je(t,e){let n=[],c=t.records.find(p=>p.recordType==="proposal"&&p.id===e.proposalId);c?c.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${c.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),P(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let p of _e(e))P(p)||n.push({code:"invalid_generated_id",message:`${p} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!c)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let p={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},a=X(t,c,e,p.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[a],events:[p],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:a.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 p={id:e.replacementProposalId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:c.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"}},a={...B(t,c,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},v={...B(t,p,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:p.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},h=X(t,p,e,v.id,e.decisionId),f={id:e.relationshipId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:p.id},to:{entityType:"proposal",entityId:c.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[p,h],events:[a,v],relationships:[f]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:p.id},{entityType:"decision",entityId:h.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let p={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[],events:[p],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}let m={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.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:c.id,append:{records:[],events:[m],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}function Re(t,e){let n=structuredClone(t);for(let m of e.projectionUpdates){let p=n.records.find(a=>a.recordType===m.entityType&&a.id===m.entityId);if(!p||p.recordType!=="proposal"&&p.recordType!=="decision")throw new Error(`Projection target not found: ${m.entityType} ${m.entityId}`);if(p.state!==m.fromState)throw new Error(`Projection state conflict for ${m.entityType} ${m.entityId}: expected ${m.fromState}, found ${p.state}`);p.state=m.state}n.records.push(...e.append.records),n.events.push(...e.append.events),n.relationships.push(...e.append.relationships);let c=e.append.events.map(m=>m.createdAt).sort().at(-1);return c&&(n.manifest.updatedAt=c),{bundle:n,validation:z(n)}}export{ee as MEMORY_FORMAT_VERSION,te as MEMORY_SCHEMA_VERSION,Re as applyOwnerReviewActionPlan,P as isUuidV7,je as planOwnerReviewAction,be as retrieveActionPacket,ye as selectContextualReviewPackets,z as validateProjectMemoryBundle,ce as validateRetrievalPacket};
|
|
1
|
+
var ee=1,te=1;var ie=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function P(t){return ie.test(t)}function W(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function u(t,e,n,c){t.push({path:e,code:n,message:c,severity:"error"})}function N(t,e,n,c){t.push({path:e,code:n,message:c,severity:"warning"})}function R(t,e,n){P(n)||u(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function A(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&u(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function $(t,e,n,c=!1){c&&n.level==="contributor"&&u(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&u(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var ne={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"])},oe=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function re(t,e,n){R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),R(t,`${n}.entity.entityId`,e.entity.entityId),A(t,`${n}.createdAt`,e.createdAt),$(t,`${n}.authority`,e.authority);let c=ne[e.entity.entityType],m=`${e.fromState??"null"}->${e.toState}`;c&&!c.has(m)&&u(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${m}.`);let p=`${e.entity.entityType}:${e.toState}`;if(oe.has(p)&&($(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||u(t,`${n}.reason`,"missing_normative_reason","Normative acceptance, rejection, supersession, and revocation require a reason.")),e.entity.entityType==="proposal"&&e.toState==="deferred"){let a=e.transitionContext;(a?.kind!=="proposal_deferral"||a.resurfaceWhen.length===0)&&u(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),a?.resurfaceWhen.includes("after_date")&&!a.revisitAfter&&u(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),a?.revisitAfter&&A(t,`${n}.transitionContext.revisitAfter`,a.revisitAfter)}}function se(t,e,n,c){R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),A(t,`${n}.createdAt`,e.createdAt),e.projectId!==c&&u(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&u(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&u(t,`${n}.subjectSemantics`,"missing_subject_semantics","Multi-subject claims must explain why the subjects are inseparable."),e.recordType==="proposal"&&e.origin.mode==="inferred"&&(!e.origin.sourceText||!e.origin.iterationId||!e.origin.inferredById)&&u(t,`${n}.origin`,"incomplete_inference_provenance","Inferred structure requires source text, iteration, and inferring participant."),e.recordType==="decision"&&($(t,`${n}.authority`,e.authority,!0),e.claim.trim()||u(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&N(t,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="advisory_explanation"&&((!e.statement.trim()||!e.rationale.trim())&&u(t,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),A(t,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&u(t,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(m=>!m.trim())&&u(t,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((m,p)=>{(!m.id.trim()||!m.modelPath.trim())&&u(t,`${n}.concreteBindings[${p}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),A(t,`${n}.concreteBindings[${p}].createdAt`,m.createdAt),A(t,`${n}.concreteBindings[${p}].updatedAt`,m.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&u(t,n,"incomplete_freshness_resolution","Resolved freshness signals need a time and resolving event."),e.recordType==="model_projection"&&(A(t,`${n}.appliedAt`,e.appliedAt),$(t,`${n}.authority`,e.authority,!0),e.entryIds.length===0&&u(t,`${n}.entryIds`,"empty_model_projection","Applied model projections need at least one model entry.")),e.recordType==="eval_spec"&&((!e.legacyId.trim()||!e.title.trim()||!e.prompt.trim())&&u(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(m=>!m.trim()))&&u(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&N(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&N(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ae(t,e,n){if(R(t,`${n}.id`,e.id),R(t,`${n}.projectId`,e.projectId),R(t,`${n}.participantId`,e.participantId),R(t,`${n}.from.entityId`,e.from.entityId),R(t,`${n}.to.entityId`,e.to.entityId),A(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||u(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let m=e.from.entityType==="decision"&&e.to.entityType==="decision",p=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!m&&!p&&u(t,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),m&&!e.authority?u(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):m&&e.authority&&$(t,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&u(t,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&u(t,n,"invalid_implements_relationship","`implements` points from an implementation attempt to a decision."),e.relationshipType==="verifies"&&(e.from.entityType!=="verification_attempt"||!["decision","implementation_attempt","model_entry"].includes(e.to.entityType))&&u(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&u(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function z(t){let e=[];R(e,"manifest.projectId",t.manifest.projectId),A(e,"manifest.createdAt",t.manifest.createdAt),A(e,"manifest.updatedAt",t.manifest.updatedAt);let n=new Map,c=(i,s)=>{let o=n.get(i);o?u(e,s,"duplicate_id",`ID is already used at ${o}.`):n.set(i,s)};t.records.forEach((i,s)=>{let o=`records[${s}]`;c(i.id,o),se(e,i,o,t.manifest.projectId)}),t.events.forEach((i,s)=>{let o=`events[${s}]`;c(i.id,o),re(e,i,o),i.projectId!==t.manifest.projectId&&u(e,`${o}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((i,s)=>{let o=`relationships[${s}]`;c(i.id,o),ae(e,i,o),i.projectId!==t.manifest.projectId&&u(e,`${o}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((i,s)=>{c(i.id,`artifacts[${s}]`),R(e,`artifacts[${s}].id`,i.id)}),t.tombstones.forEach((i,s)=>{let o=`tombstones[${s}]`;c(i.id,o),R(e,`${o}.id`,i.id),R(e,`${o}.objectId`,i.objectId),R(e,`${o}.deletedById`,i.deletedById),A(e,`${o}.deletedAt`,i.deletedAt),$(e,`${o}.authority`,i.authority,!0)});let m=new Set(t.records.map(i=>`${i.recordType}:${i.id}`)),p=new Set(t.tombstones.map(i=>`${i.objectType}:${i.objectId}`)),a=(i,s)=>{let o=`${i.entityType}:${i.entityId}`;!m.has(o)&&!p.has(o)&&u(e,s,"dangling_entity_reference",`No record or tombstone exists for ${o}.`)};t.events.forEach((i,s)=>a(i.entity,`events[${s}].entity`)),t.relationships.forEach((i,s)=>{a(i.from,`relationships[${s}].from`),a(i.to,`relationships[${s}].to`)});let v=new Set(t.artifacts.map(i=>i.id)),h=(i,s)=>{v.has(i)||u(e,s,"dangling_artifact_reference","No artifact manifest entry exists.")},f=(i,s,o)=>{!m.has(`${i}:${s}`)&&!p.has(`${i}:${s}`)&&u(e,o,"dangling_entity_reference",`No ${i} record or tombstone exists.`)};t.records.forEach((i,s)=>{let o=`records[${s}]`;switch(i.recordType){case"authority_grant":f("participant",i.granteeId,`${o}.granteeId`),f("participant",i.grantedById,`${o}.grantedById`),i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`));break;case"observation":i.captureContext.subjectIds.forEach((r,d)=>f("subject",r,`${o}.captureContext.subjectIds[${d}]`)),i.captureContext.artifactIds.forEach((r,d)=>h(r,`${o}.captureContext.artifactIds[${d}]`));break;case"proposal":case"decision":i.subjects.forEach((r,d)=>f("subject",r.subjectId,`${o}.subjects[${d}].subjectId`));break;case"thread":i.messageArtifactIds.forEach((r,d)=>h(r,`${o}.messageArtifactIds[${d}]`)),i.resultRefs.forEach((r,d)=>a(r,`${o}.resultRefs[${d}]`));break;case"iteration":i.threadIds.forEach((r,d)=>f("thread",r,`${o}.threadIds[${d}]`)),i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"evidence":i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"advisory_explanation":i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`)),i.supersededById&&f("advisory_explanation",i.supersededById,`${o}.supersededById`);break;case"implementation_attempt":i.iterationIds.forEach((r,d)=>f("iteration",r,`${o}.iterationIds[${d}]`)),i.coverageClaims.forEach((r,d)=>f("decision",r.decisionId,`${o}.coverageClaims[${d}].decisionId`)),i.artifactIds.forEach((r,d)=>h(r,`${o}.artifactIds[${d}]`));break;case"eval_spec":i.replacesSpecId&&f("eval_spec",i.replacesSpecId,`${o}.replacesSpecId`),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`)),i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),(i.dependencies??[]).forEach((r,d)=>{r.kind==="subject"&&r.subjectId&&f("subject",r.subjectId,`${o}.dependencies[${d}].subjectId`)}),(i.scenarios??[]).forEach((r,d)=>{r.subjectIds?.forEach((I,x)=>f("subject",I,`${o}.scenarios[${d}].subjectIds[${x}]`))}),i.targets.forEach((r,d)=>f(r.entityType,r.entityId,`${o}.targets[${d}]`));break;case"verification_attempt":i.evalSpecId&&f("eval_spec",i.evalSpecId,`${o}.evalSpecId`),i.targets.forEach((r,d)=>f(r.entityType,r.entityId,`${o}.targets[${d}]`)),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`));break;case"model_entry":i.subjectIds.forEach((r,d)=>f("subject",r,`${o}.subjectIds[${d}]`)),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`));break;case"model_projection":$(e,`${o}.authority`,i.authority,!0),f("participant",i.appliedById,`${o}.appliedById`),i.decisionIds.forEach((r,d)=>f("decision",r,`${o}.decisionIds[${d}]`)),i.entryIds.forEach((r,d)=>f("model_entry",r,`${o}.entryIds[${d}]`)),i.coverage.forEach((r,d)=>f("decision",r.decisionId,`${o}.coverage[${d}].decisionId`));break;case"freshness_signal":a(i.target,`${o}.target`),i.evidenceIds.forEach((r,d)=>f("evidence",r,`${o}.evidenceIds[${d}]`));break;default:break}});let S=new Map(t.events.map(i=>[i.id,i])),T=new Map(t.records.map(i=>[`${i.recordType}:${i.id}`,i])),_=new Map;t.events.forEach((i,s)=>{let o=`${i.entity.entityType}:${i.entity.entityId}:${i.fromState??"null"}`,r=_.get(o)??new Set;r.add(i.toState),_.set(o,r),r.size>1&&u(e,`events[${s}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let b=new Map(t.records.flatMap(i=>i.recordType==="authority_grant"?[[i.id,i]]:[])),M=(i,s,o,r,d)=>{if(i.level!=="delegate"||!i.grantId)return;let I=b.get(i.grantId);if(!I){u(e,d,"invalid_authority_grant","Delegated authority references a missing grant.");return}(I.granteeId!==s||I.level!=="delegate")&&u(e,d,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let x=Date.parse(o);(x<Date.parse(I.startsAt)||I.endsAt&&x>Date.parse(I.endsAt)||I.revokedAt&&x>=Date.parse(I.revokedAt))&&u(e,d,"inactive_authority_grant","The delegated authority grant was not active at this time."),I.subjectIds.length&&r.length&&!r.every(y=>I.subjectIds.includes(y))&&u(e,d,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let i of t.records)i.recordType==="decision"&&M(i.authority,i.acceptedById,i.createdAt,i.subjects.map(s=>s.subjectId),`records:${i.id}.authority`);t.events.forEach((i,s)=>{let o=T.get(`${i.entity.entityType}:${i.entity.entityId}`),r=o&&"subjects"in o?o.subjects.map(d=>d.subjectId):[];M(i.authority,i.participantId,i.createdAt,r,`events[${s}].authority`)}),t.relationships.forEach((i,s)=>{if(!i.authority)return;let o=[i.from,i.to].flatMap(r=>{let d=T.get(`${r.entityType}:${r.entityId}`);return d&&"subjects"in d?d.subjects.map(I=>I.subjectId):[]});M(i.authority,i.participantId,i.createdAt,o,`relationships[${s}].authority`)});for(let i of t.records){if(i.recordType!=="decision")continue;let s=S.get(i.acceptanceEventId);(!s||s.entity.entityType!=="proposal"||s.entity.entityId!==i.proposalId||s.toState!=="accepted")&&u(e,`records:${i.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),s&&s.participantId!==i.acceptedById&&u(e,`records:${i.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),T.has(`proposal:${i.proposalId}`)||u(e,`records:${i.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),i.state==="superseded"&&(t.relationships.some(r=>r.relationshipType==="supersedes"&&r.to.entityType==="decision"&&r.to.entityId===i.id)||u(e,`records:${i.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),i.state==="revoked"&&(t.events.some(r=>r.entity.entityType==="decision"&&r.entity.entityId===i.id&&r.toState==="revoked"&&!!r.reason?.trim())||u(e,`records:${i.id}.state`,"missing_revocation_event","Revoked decisions require an authorized event with a reason."))}for(let i of t.records){if(i.recordType!=="proposal"||i.state!=="accepted")continue;t.records.some(o=>o.recordType==="decision"&&o.proposalId===i.id)||u(e,`records:${i.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return W(e)}function ce(t){let e=[];R(e,"projectId",t.projectId),A(e,"retrievedAt",t.retrievedAt),t.budget.maxEstimatedTokens<=0&&u(e,"budget.maxEstimatedTokens","invalid_budget","Token budget must be positive."),t.budget.estimatedTokens>t.budget.maxEstimatedTokens&&u(e,"budget.estimatedTokens","token_budget_exceeded","Retrieval packet exceeds its declared context budget.");let n=new Set(t.uncertainties.map(p=>p.code));t.subjectMatches.some(p=>p.confidence==="unresolved")&&!n.has("subject_unresolved")&&u(e,"uncertainties","hidden_subject_uncertainty","Unresolved subject matches must be explicit in the packet."),t.decisions.length===0&&t.conflicts.length===0&&!n.has("no_applicable_decision")&&!n.has("subject_unresolved")&&u(e,"uncertainties","ambiguous_empty_result","An empty packet must explain whether no decision applies or the subject is unresolved."),t.completeness.status==="truncated"&&!n.has("retrieval_truncated")&&u(e,"uncertainties","silent_truncation","Truncated retrieval must be reported as uncertainty."),t.completeness.conflictsComplete||(t.completeness.status!=="truncated"&&u(e,"completeness.conflictsComplete","silent_conflict_truncation","Incomplete conflict coverage must mark the whole packet truncated."),n.has("retrieval_truncated")||u(e,"uncertainties","missing_conflict_expansion","Incomplete conflicts require explicit truncation and expansion guidance."));let m=new Set(t.decisions.map(p=>p.id));return t.conflicts.forEach((p,a)=>{p.decisionIds.length<2&&u(e,`conflicts[${a}].decisionIds`,"invalid_conflict","Conflicts need at least two applicable decisions.");for(let v of p.decisionIds)m.has(v)||u(e,`conflicts[${a}].decisionIds`,"missing_conflict_position","Every conflict position must be present in the compact decision list.")}),W(e)}var de=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function L(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function O(t){return new Set(L(t).split(" ").filter(e=>e.length>2&&!de.has(e)))}function Y(t,e){if(!t.size||!e.size)return 0;let n=0;for(let c of t)e.has(c)&&(n+=1);return n/Math.min(t.size,e.size)}function pe(t){return[{value:t.label,by:"label"},...t.aliases.map(e=>({value:e,by:"alias"})),...t.locators.map(e=>({value:e.value,by:"locator"}))]}function le(t,e){let n=new Map,c=new Set(e.subjectIds??[]),m=(e.subjectHints??[]).map(L).filter(Boolean),p=O([e.action,e.text].filter(Boolean).join(" "));for(let a of t){if(c.has(a.id)){n.set(a.id,{subjectId:a.id,label:a.label,confidence:"exact",matchedBy:"id",score:100});continue}let v;for(let h of pe(a)){let f=L(h.value);for(let _ of m){let b=f===_?95:f.includes(_)||_.includes(f)?75:0;b>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:b>=90?"exact":"strong",matchedBy:h.by,score:b})}let T=["/","#","[","]","="].some(_=>h.value.includes(_))?0:Math.round(Y(O(f),p)*55);T>=30&&T>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:T>=45?"strong":"weak",matchedBy:"query_text",score:T})}v&&n.set(a.id,v)}return n}function ue(t,e){let n=new Set(t.sourceRefs.filter(a=>a.kind==="iteration").map(a=>a.id)),c=new Set(t.sourceRefs.filter(a=>a.kind==="thread").map(a=>a.id)),m=e.filter(a=>a.iterationIds.some(v=>n.has(v))||a.sourceRefs.some(v=>v.kind==="thread"&&c.has(v.id)));if(!m.length)return{state:"none_found",attemptIds:[]};let p=new Set(m.map(a=>a.state));return{state:p.size>1?"mixed":p.has("completed")?"completed":"attempted",attemptIds:m.map(a=>a.id)}}function me(t){return Math.ceil(JSON.stringify(t).length/4)}function ye(t,e){let n=t.records.filter(s=>s.recordType==="subject"),c=e.generatedAt??new Date().toISOString(),m=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,p=t.records.filter(s=>{if(s.recordType!=="proposal"||m&&!m.has(s.id))return!1;if(s.state==="pending")return!0;if(s.state!=="deferred")return!1;let o=[...t.events].reverse().find(r=>r.entity.entityType==="proposal"&&r.entity.entityId===s.id&&r.toState==="deferred"&&r.transitionContext?.kind==="proposal_deferral")?.transitionContext;return o?o.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||o.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||o.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||o.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||o.resurfaceWhen.includes("after_date")&&!!(o.revisitAfter&&Date.parse(c)>=Date.parse(o.revisitAfter)):!1}),a=t.records.filter(s=>s.recordType==="implementation_attempt"),v=le(n,e),h=[...v.values()].sort((s,o)=>o.score-s.score),f=O([e.action,e.text].filter(Boolean).join(" ")),S=p.flatMap(s=>{let o=s.subjects.map(x=>v.get(x.subjectId)).filter(x=>!!x),r=Math.max(0,...o.map(x=>x.score)),d=Math.round(Y(O(s.claim),f)*35),I=r+d;return I>=50?[{proposal:s,proposalMatches:o,score:I}]:[]}).sort((s,o)=>o.score-s.score||s.proposal.id.localeCompare(o.proposal.id)),T=Math.max(1,e.maxPackets??3),_=Math.max(200,e.maxEstimatedTokens??1200),b=[],M=0;for(let s of S){if(b.length>=T)break;let o=s.proposal.sourceRefs.slice(0,4),r={contractVersion:1,packetId:`review:${s.proposal.id}`,projectId:t.manifest.projectId,generatedAt:c,trigger:{action:e.action,reason:s.proposalMatches.length?`Historical proposal intersects ${s.proposalMatches.map(I=>I.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:s.proposalMatches.map(({score:I,...x})=>x)},proposal:{id:s.proposal.id,claim:s.proposal.claim,state:s.proposal.state,proposedKind:s.proposal.proposedKind,subjectIds:s.proposal.subjects.map(I=>I.subjectId),origin:s.proposal.origin.mode},authority:"unaccepted",presentation:s.score>=100&&["constraint","rule"].includes(s.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:ue(s.proposal,a),evidence:{sourceCount:s.proposal.sourceRefs.length,sourceRefs:o},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:s.proposal.id},...o]},d={...r,estimatedTokens:me(r)};if(M+d.estimatedTokens>_)break;b.push(d),M+=d.estimatedTokens}let i=Math.max(0,S.length-b.length);return{packets:b,subjectMatches:h.map(({score:s,...o})=>o),completeness:{status:i>0?"truncated":"complete",consideredProposalCount:S.length,omittedPacketCount:i,maxEstimatedTokens:_,estimatedTokens:M},uncertainty:v.size===0?"subject_unresolved":S.length===0?"no_relevant_pending_proposal":void 0}}var fe=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function H(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function V(t){return new Set(H(t).split(" ").filter(e=>e.length>2&&!fe.has(e)))}function G(t,e){if(!t.size||!e.size)return 0;let n=0;for(let c of t)e.has(c)&&(n+=1);return n/Math.min(t.size,e.size)}function ve(t,e){let n=new Set(e.subjectIds??[]),c=(e.subjectHints??[]).map(H).filter(Boolean),m=V([e.action,e.text].filter(Boolean).join(" ")),p=[];for(let a of t){if(n.has(a.id)){p.push({subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:"exact",matchedBy:"id",score:100});continue}let v,h=[{value:a.label,by:"semantic"},...a.aliases.map(f=>({value:f,by:"alias"})),...a.locators.map(f=>({value:f.value,by:"locator"}))];for(let f of h){let S=H(f.value);for(let b of c){let M=S===b?95:S.includes(b)||b.includes(S)?75:0;M>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:M>=90?"exact":"strong",matchedBy:f.by,score:M})}let _=["/","#","[","]","="].some(b=>f.value.includes(b))?0:Math.round(G(V(S),m)*55);_>=30&&_>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:_>=45?"strong":"weak",matchedBy:"semantic",score:_})}v&&p.push(v)}return p.sort((a,v)=>v.score-a.score||a.subjectId.localeCompare(v.subjectId))}function ge(t){return Math.ceil(JSON.stringify(t).length/4)}function C(t,e){return t.relationshipType===e&&t.from.entityType==="decision"&&t.to.entityType==="decision"}function Ie(t,e){let n=e.filter(p=>p.coverageClaims.some(a=>a.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let c=n.filter(p=>p.state==="completed"),m=c.some(p=>p.coverageClaims.some(a=>a.decisionId===t&&a.coverage==="full"));return{decisionId:t,state:m?"implemented":c.length?"partial":"unknown",attemptIds:n.map(p=>p.id)}}function he(t,e,n){let c=e.filter(v=>v.targets.some(h=>h.entityType==="decision"&&h.entityId===t)).sort((v,h)=>h.createdAt.localeCompare(v.createdAt)),m=n.some(v=>v.signalType==="verification_expired"&&v.target.entityType==="decision"&&v.target.entityId===t),p=c[0],a=m?"stale":p?p.state==="passed"?"passing":p.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(p.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:a,attemptIds:c.map(v=>v.id)}}function be(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),c=Math.max(1,e.maxDecisions??6),m=t.records.filter(y=>y.recordType==="subject"),p=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,a=t.records.filter(y=>y.recordType==="decision"&&y.state==="active"),v=p?a.filter(y=>p.has(y.id)):a,h=t.records.filter(y=>y.recordType==="implementation_attempt"),f=t.records.filter(y=>y.recordType==="verification_attempt"),S=t.records.filter(y=>y.recordType==="freshness_signal"&&y.state==="open"),T=t.records.filter(y=>y.recordType==="evidence"),_=t.records.filter(y=>y.recordType==="model_entry"),b=ve(m,e),M=new Map(b.map(y=>[y.subjectId,y.score])),i=V([e.action,e.text].filter(Boolean).join(" ")),s=v.flatMap(y=>{let w=Math.max(0,...y.subjects.map(K=>M.get(K.subjectId)??0)),g=Math.round(G(V(y.claim),i)*35),k=w+g;return k>=50?[{decision:y,score:k}]:[]}).sort((y,w)=>w.score-y.score||y.decision.id.localeCompare(w.decision.id)),o=new Map;for(let y of s.slice(0,c))o.set(y.decision.id,y.decision);for(let y of t.relationships){if(!C(y,"excepts")&&!C(y,"contradicts"))continue;let w=a.find(k=>k.id===y.from.entityId),g=a.find(k=>k.id===y.to.entityId);!w||!g||!o.has(w.id)&&!o.has(g.id)||(o.size<c&&o.set(w.id,w),o.size<c&&o.set(g.id,g))}let r=[...o.values()],d=y=>y.from.entityType==="decision"&&y.to.entityType==="decision"&&o.has(y.from.entityId)&&o.has(y.to.entityId),I=(y,w=!1)=>{let g=new Set(y.map(l=>l.id)),k=S.filter(l=>l.target.entityType==="decision"&&g.has(l.target.entityId)),K=new Set(t.relationships.filter(l=>C(l,"excepts")&&g.has(l.from.entityId)&&g.has(l.to.entityId)).flatMap(l=>[l.from.entityId,l.to.entityId])),D=t.relationships.filter(l=>C(l,"contradicts")&&g.has(l.from.entityId)&&g.has(l.to.entityId)).map(l=>({id:l.id,decisionIds:[l.from.entityId,l.to.entityId],unresolvedQuestion:l.reason,expansionRefs:[{kind:"record",id:l.id}]})),Z=new Set(D.flatMap(l=>l.decisionIds)),F=T.filter(l=>l.sourceRefs.some(j=>j.kind==="record"&&g.has(j.id))||t.relationships.some(j=>j.relationshipType==="supports"&&j.from.entityType==="evidence"&&j.from.entityId===l.id&&j.to.entityType==="decision"&&g.has(j.to.entityId))),q=Math.max(0,s.length-y.length),J=t.relationships.some(l=>C(l,"contradicts")&&d(l)&&(!g.has(l.from.entityId)||!g.has(l.to.entityId))),Q=w||q>0||J,E=[];b.length===0&&(e.subjectHints?.length??0)>0?E.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):y.length===0&&E.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),D.length&&E.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:D.flatMap(l=>l.expansionRefs)}),F.some(l=>l.availability!=="available")&&E.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:F.map(l=>({kind:"record",id:l.id}))}),Q&&E.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:t.manifest.projectId}]});let U={contractVersion:1,projectId:t.manifest.projectId,retrievedAt:e.retrievedAt??new Date().toISOString(),query:{text:e.text,action:e.action,subjectHints:e.subjectHints??[]},budget:{maxEstimatedTokens:n,estimatedTokens:0},subjectMatches:b.map(({score:l,...j})=>j),modelEntries:_.filter(l=>l.decisionIds.some(j=>g.has(j))).map(l=>({id:l.id,key:l.key,value:l.value,decisionIds:l.decisionIds})),decisions:y.map(l=>({id:l.id,kind:l.kind,claim:l.claim,subjectIds:l.subjects.map(j=>j.subjectId),authority:l.authority,effectiveState:Z.has(l.id)?"conflicted":K.has(l.id)?"excepted":"active",freshness:k.filter(j=>j.target.entityId===l.id).map(j=>j.signalType),expansionRef:{kind:"record",id:l.id}})),conflicts:D,uncertainties:E,implementation:y.map(l=>Ie(l.id,h)),verification:y.map(l=>he(l.id,f,k)),evidence:F.map(l=>({evidenceId:l.id,summary:l.summary,availability:l.availability,sourceRefs:l.sourceRefs})),completeness:{status:Q?"truncated":"complete",omittedDecisionCount:q,omittedEvidenceCount:0,conflictsComplete:!J}};return U.budget.estimatedTokens=ge(U),U},x=I(r);for(;x.budget.estimatedTokens>n&&r.length>0;){let y=r.pop(),w=t.relationships.filter(g=>C(g,"contradicts")&&(g.from.entityId===y.id||g.to.entityId===y.id)).flatMap(g=>[g.from.entityId,g.to.entityId]);r=r.filter(g=>!w.includes(g.id)),x=I(r,!0)}return x}function B(t,e,n,c){return{id:c,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"lifecycle_event",authority:n.authority}}function X(t,e,n,c,m){return{id:m,schemaVersion:1,projectId:t.manifest.projectId,createdAt:n.occurredAt,participantId:n.participantId,sourceRefs:[{kind:"record",id:e.id},...n.sourceRefs??[]],recordType:"decision",proposalId:e.id,acceptanceEventId:c,acceptedById:n.participantId,authority:n.authority,state:"active",kind:n.kind,claim:e.claim,rationale:n.rationale??e.rationale,subjects:e.subjects,subjectSemantics:e.subjectSemantics,noChange:!1}}function _e(t){switch(t.action){case"accept":return[t.eventId,t.decisionId];case"edit_and_accept":return[t.withdrawalEventId,t.replacementProposalId,t.acceptanceEventId,t.decisionId,t.relationshipId];case"reject":case"defer":return[t.eventId]}}function je(t,e){let n=[],c=t.records.find(p=>p.recordType==="proposal"&&p.id===e.proposalId);c?c.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${c.state}, not pending.`}):n.push({code:"proposal_not_found",message:"Proposal does not exist."}),e.authority.level==="contributor"&&n.push({code:"insufficient_authority",message:"Contributors cannot resolve owner review."}),e.authority.level==="delegate"&&!e.authority.grantId&&n.push({code:"missing_authority_grant",message:"Delegate review requires a grant ID."}),P(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let p of _e(e))P(p)||n.push({code:"invalid_generated_id",message:`${p} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!c)return{ok:!1,errors:n};if(e.action==="accept"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Acceptance requires a reason."}]};let p={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},a=X(t,c,e,p.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[a],events:[p],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"accepted"}],resultRefs:[{entityType:"decision",entityId:a.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 p={id:e.replacementProposalId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:c.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"}},a={...B(t,c,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},v={...B(t,p,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:p.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},h=X(t,p,e,v.id,e.decisionId),f={id:e.relationshipId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:c.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:p.id},to:{entityType:"proposal",entityId:c.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[p,h],events:[a,v],relationships:[f]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:p.id},{entityType:"decision",entityId:h.id}]}}}if(e.action==="reject"){if(!e.reason.trim())return{ok:!1,errors:[{code:"reason_required",message:"Rejection requires a reason."}]};let p={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[],events:[p],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}let m={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.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:c.id,append:{records:[],events:[m],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}function Re(t,e){let n=structuredClone(t);for(let m of e.projectionUpdates){let p=n.records.find(a=>a.recordType===m.entityType&&a.id===m.entityId);if(!p||p.recordType!=="proposal"&&p.recordType!=="decision")throw new Error(`Projection target not found: ${m.entityType} ${m.entityId}`);if(p.state!==m.fromState)throw new Error(`Projection state conflict for ${m.entityType} ${m.entityId}: expected ${m.fromState}, found ${p.state}`);p.state=m.state}n.records.push(...e.append.records),n.events.push(...e.append.events),n.relationships.push(...e.append.relationships);let c=e.append.events.map(m=>m.createdAt).sort().at(-1);return c&&(n.manifest.updatedAt=c),{bundle:n,validation:z(n)}}export{ee as MEMORY_FORMAT_VERSION,te as MEMORY_SCHEMA_VERSION,Re as applyOwnerReviewActionPlan,P as isUuidV7,je as planOwnerReviewAction,be as retrieveActionPacket,ye as selectContextualReviewPackets,z as validateProjectMemoryBundle,ce as validateRetrievalPacket};
|
package/dist/plugin-astro.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,b as d,c as l,d as g}from"./chunk-
|
|
1
|
+
import{a as p,b as d,c as l,d as g}from"./chunk-JJEESG5Y.mjs";import"./chunk-NOHXTT24.mjs";import{Buffer as c}from"buffer";function u(e){return typeof e=="string"?e:e instanceof Uint8Array?c.from(e).toString("utf8"):String(e??"")}function m(e,t,r){let o=e.url||"";if(r.port===null||!(e.headers.accept?.includes("text/html")||o==="/"||o.endsWith(".html")))return;let a=t.write.bind(t),s=t.end.bind(t),n="";t.write=(i=>(n+=u(i),!0)),t.end=(i=>(i!==void 0&&(n+=u(i)),n=n.replace("<head>",`<head><script type="text/javascript">${g(r)}</script>`),t.getHeader("content-length")&&t.setHeader("content-length",c.byteLength(n)),a(n,"utf8"),s()))}function y(e){let t=e?.basePath??"/popmelt",r={port:null,projectId:null};return{name:"popmelt",hooks:{async"astro:server:setup"({server:o}){r=await p(e,o,4321),await d(r,o);let a=l(t,()=>r);o.middlewares.use((s,n,i)=>{if((s.url||"").startsWith(t))return a(s,n,i);m(s,n,r),i()})}}}}export{y as popmelt};
|
package/dist/plugin-vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as n,b as i,c as o,d as a}from"./chunk-
|
|
1
|
+
import{a as n,b as i,c as o,d as a}from"./chunk-JJEESG5Y.mjs";import"./chunk-NOHXTT24.mjs";function s(r){let d=r?.basePath??"/popmelt",e={port:null,projectId:null};return{name:"popmelt",async configureServer(t){e=await n(r,t,5173),await i(e,t),t.middlewares.use(o(d,()=>e))},transformIndexHtml(){if(e.port!==null)return[{tag:"script",attrs:{type:"text/javascript"},children:a(e),injectTo:"head-prepend"}]}}}export{s as popmelt};
|