@popmelt.com/core 0.8.6 → 0.8.7

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/memory.d.mts CHANGED
@@ -164,6 +164,37 @@ type EvidenceRecord = Provenance & {
164
164
  stance?: ParticipantStance;
165
165
  artifactIds: MemoryId[];
166
166
  };
167
+ /**
168
+ * An advisory explanation is learned, revisable shared understanding. It can
169
+ * guide future work, but it is deliberately distinct from accepted product
170
+ * truth (`decision`).
171
+ */
172
+ type AdvisoryExplanationKind = 'intention' | 'principle' | 'pattern';
173
+ type AdvisoryExplanationState = 'emerging' | 'testing' | 'grounded' | 'challenged' | 'retired';
174
+ type AdvisoryExplanationScope = {
175
+ kind: 'project' | 'route' | 'component' | 'selector' | 'file';
176
+ values: string[];
177
+ };
178
+ type AdvisoryConcreteBinding = {
179
+ id: string;
180
+ modelPath: string;
181
+ value: JsonValue;
182
+ createdAt: Timestamp;
183
+ updatedAt: Timestamp;
184
+ };
185
+ type AdvisoryExplanationRecord = Provenance & {
186
+ recordType: 'advisory_explanation';
187
+ kind: AdvisoryExplanationKind;
188
+ state: AdvisoryExplanationState;
189
+ statement: string;
190
+ rationale: string;
191
+ scope: AdvisoryExplanationScope;
192
+ subjectIds: MemoryId[];
193
+ evidenceIds: MemoryId[];
194
+ concreteBindings: AdvisoryConcreteBinding[];
195
+ supersededById?: MemoryId;
196
+ updatedAt: Timestamp;
197
+ };
167
198
  type CoverageClaim = {
168
199
  decisionId: MemoryId;
169
200
  coverage: 'partial' | 'full';
@@ -305,13 +336,13 @@ type ModelProjectionRecord = Provenance & {
305
336
  status: 'unprojected' | 'partially_projected' | 'projected' | 'stale';
306
337
  }>;
307
338
  };
308
- type EntityType = 'participant' | 'authority_grant' | 'subject' | 'observation' | 'proposal' | 'decision' | 'thread' | 'iteration' | 'evidence' | 'implementation_attempt' | 'eval_spec' | 'verification_attempt' | 'model_entry' | 'model_projection' | 'freshness_signal';
339
+ type EntityType = 'participant' | 'authority_grant' | 'subject' | 'observation' | 'proposal' | 'decision' | 'thread' | 'iteration' | 'evidence' | 'advisory_explanation' | 'implementation_attempt' | 'eval_spec' | 'verification_attempt' | 'model_entry' | 'model_projection' | 'freshness_signal';
309
340
  type MemoryObjectType = EntityType | 'relationship' | 'lifecycle_event' | 'artifact';
310
341
  type EntityReference = {
311
342
  entityType: EntityType;
312
343
  entityId: MemoryId;
313
344
  };
314
- type RelationshipType = 'supports' | 'contradicts' | 'supersedes' | 'excepts' | 'duplicates' | 'implements' | 'verifies' | 'replaces' | 'derived_from';
345
+ type RelationshipType = 'supports' | 'contradicts' | 'supersedes' | 'excepts' | 'duplicates' | 'implements' | 'verifies' | 'replaces' | 'derived_from' | 'operationalizes' | 'refines' | 'instantiates';
315
346
  type RelationshipRecord = Provenance & {
316
347
  recordType: 'relationship';
317
348
  relationshipType: RelationshipType;
@@ -374,8 +405,8 @@ type Tombstone = {
374
405
  erasureLevel: 'content' | 'content_and_evidence' | 'full_where_permitted';
375
406
  invalidates: EntityReference[];
376
407
  };
377
- type CanonicalRecord = ParticipantRecord | AuthorityGrantRecord | SubjectRecord | ObservationRecord | ProposalRecord | DecisionRecord | ThreadRecord | IterationRecord | EvidenceRecord | ImplementationAttemptRecord | EvalSpecRecord | VerificationAttemptRecord | ModelEntryRecord | ModelProjectionRecord | FreshnessSignalRecord;
378
- type MemoryFeature = 'authority' | 'subjects' | 'decisions' | 'implementations' | 'verification' | 'eval_specs' | 'model_projection' | 'freshness' | 'portable_artifacts' | 'bounded_retrieval';
408
+ type CanonicalRecord = ParticipantRecord | AuthorityGrantRecord | SubjectRecord | ObservationRecord | ProposalRecord | DecisionRecord | ThreadRecord | IterationRecord | EvidenceRecord | AdvisoryExplanationRecord | ImplementationAttemptRecord | EvalSpecRecord | VerificationAttemptRecord | ModelEntryRecord | ModelProjectionRecord | FreshnessSignalRecord;
409
+ type MemoryFeature = 'authority' | 'subjects' | 'decisions' | 'advisory_explanations' | 'implementations' | 'verification' | 'eval_specs' | 'model_projection' | 'freshness' | 'portable_artifacts' | 'bounded_retrieval';
379
410
  type ProjectMemoryManifest = {
380
411
  formatVersion: MemoryFormatVersion;
381
412
  projectId: MemoryId;
@@ -659,4 +690,4 @@ declare function applyOwnerReviewActionPlan(bundle: ProjectMemoryBundle, plan: O
659
690
  validation: SchemaValidationResult;
660
691
  };
661
692
 
662
- export { type AcceptReviewCommand, type ArtifactKind, type ArtifactManifestEntry, type AssertionOrigin, type AuthorityContext, type AuthorityGrantRecord, type AuthorityLevel, type AuthorityMode, type CanonicalRecord, type CaptureContext, type ContextualReviewPacket, type ContextualReviewQuery, type ContextualReviewSelection, type ContextualSubjectMatch, type CoverageClaim, type DecisionKind, type DecisionRecord, type DecisionState, type DecisionSubject, type DeferReviewCommand, type EditAndAcceptReviewCommand, type EntityReference, type EntityType, type EvalDependency, type EvalScenario, type EvalSpecRecord, type EvalSpecState, type EvidenceKind, type EvidenceRecord, type ExecutionContext, type FreshnessSignalRecord, type FreshnessSignalType, type FreshnessTargetKind, type ImplementationAttemptRecord, type ImplementationState, type IterationOutcome, type IterationRecord, type JsonPrimitive, type JsonValue, type LifecycleEvent, MEMORY_FORMAT_VERSION, MEMORY_SCHEMA_VERSION, type MemoryFeature, type MemoryFormatVersion, type MemoryId, type MemoryObjectType, type MemorySchemaVersion, type ModelEntryRecord, type ModelProjectionRecord, type ObservationRecord, type ObservationState, type OwnerReviewAction, type OwnerReviewActionPlan, type OwnerReviewCommand, type OwnerReviewPlanResult, type ParticipantKind, type ParticipantRecord, type ParticipantStance, type ProjectMemoryBundle, type ProjectMemoryManifest, type ProposalDeferralContext, type ProposalRecord, type ProposalState, type Provenance, type RejectReviewCommand, type RelationshipRecord, type RelationshipType, type RetrievalConflict, type RetrievalDecision, type RetrievalEvidenceSummary, type RetrievalPacket, type RetrievalQuery, type RetrievalUncertainty, type ReviewProjectionUpdate, type SchemaIssue, type SchemaValidationResult, type SourceReference, type SourceReferenceKind, type SubjectLocator, type SubjectLocatorKind, type SubjectMatch, type SubjectRecord, type SubjectType, type ThreadOutcome, type ThreadRecord, type Timestamp, type Tombstone, type VerificationAttemptRecord, type VerificationState, type VerificationTarget, applyOwnerReviewActionPlan, isUuidV7, planOwnerReviewAction, retrieveActionPacket, selectContextualReviewPackets, validateProjectMemoryBundle, validateRetrievalPacket };
693
+ export { type AcceptReviewCommand, type AdvisoryConcreteBinding, type AdvisoryExplanationKind, type AdvisoryExplanationRecord, type AdvisoryExplanationScope, type AdvisoryExplanationState, type ArtifactKind, type ArtifactManifestEntry, type AssertionOrigin, type AuthorityContext, type AuthorityGrantRecord, type AuthorityLevel, type AuthorityMode, type CanonicalRecord, type CaptureContext, type ContextualReviewPacket, type ContextualReviewQuery, type ContextualReviewSelection, type ContextualSubjectMatch, type CoverageClaim, type DecisionKind, type DecisionRecord, type DecisionState, type DecisionSubject, type DeferReviewCommand, type EditAndAcceptReviewCommand, type EntityReference, type EntityType, type EvalDependency, type EvalScenario, type EvalSpecRecord, type EvalSpecState, type EvidenceKind, type EvidenceRecord, type ExecutionContext, type FreshnessSignalRecord, type FreshnessSignalType, type FreshnessTargetKind, type ImplementationAttemptRecord, type ImplementationState, type IterationOutcome, type IterationRecord, type JsonPrimitive, type JsonValue, type LifecycleEvent, MEMORY_FORMAT_VERSION, MEMORY_SCHEMA_VERSION, type MemoryFeature, type MemoryFormatVersion, type MemoryId, type MemoryObjectType, type MemorySchemaVersion, type ModelEntryRecord, type ModelProjectionRecord, type ObservationRecord, type ObservationState, type OwnerReviewAction, type OwnerReviewActionPlan, type OwnerReviewCommand, type OwnerReviewPlanResult, type ParticipantKind, type ParticipantRecord, type ParticipantStance, type ProjectMemoryBundle, type ProjectMemoryManifest, type ProposalDeferralContext, type ProposalRecord, type ProposalState, type Provenance, type RejectReviewCommand, type RelationshipRecord, type RelationshipType, type RetrievalConflict, type RetrievalDecision, type RetrievalEvidenceSummary, type RetrievalPacket, type RetrievalQuery, type RetrievalUncertainty, type ReviewProjectionUpdate, type SchemaIssue, type SchemaValidationResult, type SourceReference, type SourceReferenceKind, type SubjectLocator, type SubjectLocatorKind, type SubjectMatch, type SubjectRecord, type SubjectType, type ThreadOutcome, type ThreadRecord, type Timestamp, type Tombstone, type VerificationAttemptRecord, type VerificationState, type VerificationTarget, applyOwnerReviewActionPlan, isUuidV7, planOwnerReviewAction, retrieveActionPacket, selectContextualReviewPackets, validateProjectMemoryBundle, validateRetrievalPacket };
package/dist/memory.mjs CHANGED
@@ -1 +1 @@
1
- var te=1,ie=1;var ne=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function D(t){return ne.test(t)}function Y(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function m(t,e,n,c){t.push({path:e,code:n,message:c,severity:"error"})}function L(t,e,n,c){t.push({path:e,code:n,message:c,severity:"warning"})}function _(t,e,n){D(n)||m(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function A(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&m(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function $(t,e,n,c=!1){c&&n.level==="contributor"&&m(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&m(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var re={observation:new Set(["null->open","open->resolved","open->dismissed","resolved->open","dismissed->open"]),proposal:new Set(["null->draft","draft->pending","pending->accepted","pending->rejected","pending->withdrawn","pending->deferred","deferred->pending"]),decision:new Set(["null->active","active->superseded","active->revoked"]),implementation_attempt:new Set(["null->planned","planned->in_progress","planned->abandoned","in_progress->completed","in_progress->failed","in_progress->abandoned"]),eval_spec:new Set(["null->draft","null->active","draft->active","draft->retired","active->retired"]),verification_attempt:new Set(["null->queued","queued->running","queued->cancelled","running->passed","running->failed","running->inconclusive","running->error","running->cancelled"]),freshness_signal:new Set(["null->open","open->resolved"])},oe=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function se(t,e,n){_(t,`${n}.id`,e.id),_(t,`${n}.projectId`,e.projectId),_(t,`${n}.participantId`,e.participantId),_(t,`${n}.entity.entityId`,e.entity.entityId),A(t,`${n}.createdAt`,e.createdAt),$(t,`${n}.authority`,e.authority);let c=re[e.entity.entityType],v=`${e.fromState??"null"}->${e.toState}`;c&&!c.has(v)&&m(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${v}.`);let l=`${e.entity.entityType}:${e.toState}`;if(oe.has(l)&&($(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||m(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)&&m(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),a?.resurfaceWhen.includes("after_date")&&!a.revisitAfter&&m(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),a?.revisitAfter&&A(t,`${n}.transitionContext.revisitAfter`,a.revisitAfter)}}function ae(t,e,n,c){_(t,`${n}.id`,e.id),_(t,`${n}.projectId`,e.projectId),_(t,`${n}.participantId`,e.participantId),A(t,`${n}.createdAt`,e.createdAt),e.projectId!==c&&m(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&m(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&m(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)&&m(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()||m(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&L(t,`${n}.level`,"owner_grant_requires_policy_review","Owner grants are valid but should receive explicit policy review."),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&m(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&&m(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())&&m(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(v=>!v.trim()))&&m(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&L(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&L(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ce(t,e,n){_(t,`${n}.id`,e.id),_(t,`${n}.projectId`,e.projectId),_(t,`${n}.participantId`,e.participantId),_(t,`${n}.from.entityId`,e.from.entityId),_(t,`${n}.to.entityId`,e.to.entityId),A(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||m(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)&&((e.from.entityType!=="decision"||e.to.entityType!=="decision")&&m(t,n,"invalid_normative_relationship","Normative relationships connect decisions to decisions."),e.authority?$(t,`${n}.authority`,e.authority,!0):m(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context.")),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&m(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))&&m(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&m(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function z(t){let e=[];_(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 r=n.get(i);r?m(e,s,"duplicate_id",`ID is already used at ${r}.`):n.set(i,s)};t.records.forEach((i,s)=>{let r=`records[${s}]`;c(i.id,r),ae(e,i,r,t.manifest.projectId)}),t.events.forEach((i,s)=>{let r=`events[${s}]`;c(i.id,r),se(e,i,r),i.projectId!==t.manifest.projectId&&m(e,`${r}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((i,s)=>{let r=`relationships[${s}]`;c(i.id,r),ce(e,i,r),i.projectId!==t.manifest.projectId&&m(e,`${r}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((i,s)=>{c(i.id,`artifacts[${s}]`),_(e,`artifacts[${s}].id`,i.id)}),t.tombstones.forEach((i,s)=>{let r=`tombstones[${s}]`;c(i.id,r),_(e,`${r}.id`,i.id),_(e,`${r}.objectId`,i.objectId),_(e,`${r}.deletedById`,i.deletedById),A(e,`${r}.deletedAt`,i.deletedAt),$(e,`${r}.authority`,i.authority,!0)});let v=new Set(t.records.map(i=>`${i.recordType}:${i.id}`)),l=new Set(t.tombstones.map(i=>`${i.objectType}:${i.objectId}`)),a=(i,s)=>{let r=`${i.entityType}:${i.entityId}`;!v.has(r)&&!l.has(r)&&m(e,s,"dangling_entity_reference",`No record or tombstone exists for ${r}.`)};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 y=new Set(t.artifacts.map(i=>i.id)),h=(i,s)=>{y.has(i)||m(e,s,"dangling_artifact_reference","No artifact manifest entry exists.")},f=(i,s,r)=>{!v.has(`${i}:${s}`)&&!l.has(`${i}:${s}`)&&m(e,r,"dangling_entity_reference",`No ${i} record or tombstone exists.`)};t.records.forEach((i,s)=>{let r=`records[${s}]`;switch(i.recordType){case"authority_grant":f("participant",i.granteeId,`${r}.granteeId`),f("participant",i.grantedById,`${r}.grantedById`),i.subjectIds.forEach((o,p)=>f("subject",o,`${r}.subjectIds[${p}]`));break;case"observation":i.captureContext.subjectIds.forEach((o,p)=>f("subject",o,`${r}.captureContext.subjectIds[${p}]`)),i.captureContext.artifactIds.forEach((o,p)=>h(o,`${r}.captureContext.artifactIds[${p}]`));break;case"proposal":case"decision":i.subjects.forEach((o,p)=>f("subject",o.subjectId,`${r}.subjects[${p}].subjectId`));break;case"thread":i.messageArtifactIds.forEach((o,p)=>h(o,`${r}.messageArtifactIds[${p}]`)),i.resultRefs.forEach((o,p)=>a(o,`${r}.resultRefs[${p}]`));break;case"iteration":i.threadIds.forEach((o,p)=>f("thread",o,`${r}.threadIds[${p}]`)),i.artifactIds.forEach((o,p)=>h(o,`${r}.artifactIds[${p}]`));break;case"evidence":i.artifactIds.forEach((o,p)=>h(o,`${r}.artifactIds[${p}]`));break;case"implementation_attempt":i.iterationIds.forEach((o,p)=>f("iteration",o,`${r}.iterationIds[${p}]`)),i.coverageClaims.forEach((o,p)=>f("decision",o.decisionId,`${r}.coverageClaims[${p}].decisionId`)),i.artifactIds.forEach((o,p)=>h(o,`${r}.artifactIds[${p}]`));break;case"eval_spec":i.replacesSpecId&&f("eval_spec",i.replacesSpecId,`${r}.replacesSpecId`),i.decisionIds.forEach((o,p)=>f("decision",o,`${r}.decisionIds[${p}]`)),i.subjectIds.forEach((o,p)=>f("subject",o,`${r}.subjectIds[${p}]`)),(i.dependencies??[]).forEach((o,p)=>{o.kind==="subject"&&o.subjectId&&f("subject",o.subjectId,`${r}.dependencies[${p}].subjectId`)}),(i.scenarios??[]).forEach((o,p)=>{o.subjectIds?.forEach((g,x)=>f("subject",g,`${r}.scenarios[${p}].subjectIds[${x}]`))}),i.targets.forEach((o,p)=>f(o.entityType,o.entityId,`${r}.targets[${p}]`));break;case"verification_attempt":i.evalSpecId&&f("eval_spec",i.evalSpecId,`${r}.evalSpecId`),i.targets.forEach((o,p)=>f(o.entityType,o.entityId,`${r}.targets[${p}]`)),i.evidenceIds.forEach((o,p)=>f("evidence",o,`${r}.evidenceIds[${p}]`));break;case"model_entry":i.subjectIds.forEach((o,p)=>f("subject",o,`${r}.subjectIds[${p}]`)),i.decisionIds.forEach((o,p)=>f("decision",o,`${r}.decisionIds[${p}]`));break;case"model_projection":$(e,`${r}.authority`,i.authority,!0),f("participant",i.appliedById,`${r}.appliedById`),i.decisionIds.forEach((o,p)=>f("decision",o,`${r}.decisionIds[${p}]`)),i.entryIds.forEach((o,p)=>f("model_entry",o,`${r}.entryIds[${p}]`)),i.coverage.forEach((o,p)=>f("decision",o.decisionId,`${r}.coverage[${p}].decisionId`));break;case"freshness_signal":a(i.target,`${r}.target`),i.evidenceIds.forEach((o,p)=>f("evidence",o,`${r}.evidenceIds[${p}]`));break;default:break}});let M=new Map(t.events.map(i=>[i.id,i])),w=new Map(t.records.map(i=>[`${i.recordType}:${i.id}`,i])),R=new Map;t.events.forEach((i,s)=>{let r=`${i.entity.entityType}:${i.entity.entityId}:${i.fromState??"null"}`,o=R.get(r)??new Set;o.add(i.toState),R.set(r,o),o.size>1&&m(e,`events[${s}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let j=new Map(t.records.flatMap(i=>i.recordType==="authority_grant"?[[i.id,i]]:[])),S=(i,s,r,o,p)=>{if(i.level!=="delegate"||!i.grantId)return;let g=j.get(i.grantId);if(!g){m(e,p,"invalid_authority_grant","Delegated authority references a missing grant.");return}(g.granteeId!==s||g.level!=="delegate")&&m(e,p,"authority_grantee_mismatch","The grant does not authorize this participant as a delegate.");let x=Date.parse(r);(x<Date.parse(g.startsAt)||g.endsAt&&x>Date.parse(g.endsAt)||g.revokedAt&&x>=Date.parse(g.revokedAt))&&m(e,p,"inactive_authority_grant","The delegated authority grant was not active at this time."),g.subjectIds.length&&o.length&&!o.every(P=>g.subjectIds.includes(P))&&m(e,p,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let i of t.records)i.recordType==="decision"&&S(i.authority,i.acceptedById,i.createdAt,i.subjects.map(s=>s.subjectId),`records:${i.id}.authority`);t.events.forEach((i,s)=>{let r=w.get(`${i.entity.entityType}:${i.entity.entityId}`),o=r&&"subjects"in r?r.subjects.map(p=>p.subjectId):[];S(i.authority,i.participantId,i.createdAt,o,`events[${s}].authority`)}),t.relationships.forEach((i,s)=>{if(!i.authority)return;let r=[i.from,i.to].flatMap(o=>{let p=w.get(`${o.entityType}:${o.entityId}`);return p&&"subjects"in p?p.subjects.map(g=>g.subjectId):[]});S(i.authority,i.participantId,i.createdAt,r,`relationships[${s}].authority`)});for(let i of t.records){if(i.recordType!=="decision")continue;let s=M.get(i.acceptanceEventId);(!s||s.entity.entityType!=="proposal"||s.entity.entityId!==i.proposalId||s.toState!=="accepted")&&m(e,`records:${i.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),s&&s.participantId!==i.acceptedById&&m(e,`records:${i.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),w.has(`proposal:${i.proposalId}`)||m(e,`records:${i.id}.proposalId`,"missing_proposal","Accepted decisions must retain their proposal."),i.state==="superseded"&&(t.relationships.some(o=>o.relationshipType==="supersedes"&&o.to.entityType==="decision"&&o.to.entityId===i.id)||m(e,`records:${i.id}.state`,"missing_successor","Superseded decisions require an explicit successor relationship.")),i.state==="revoked"&&(t.events.some(o=>o.entity.entityType==="decision"&&o.entity.entityId===i.id&&o.toState==="revoked"&&!!o.reason?.trim())||m(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(r=>r.recordType==="decision"&&r.proposalId===i.id)||m(e,`records:${i.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Y(e)}function de(t){let e=[];_(e,"projectId",t.projectId),A(e,"retrievedAt",t.retrievedAt),t.budget.maxEstimatedTokens<=0&&m(e,"budget.maxEstimatedTokens","invalid_budget","Token budget must be positive."),t.budget.estimatedTokens>t.budget.maxEstimatedTokens&&m(e,"budget.estimatedTokens","token_budget_exceeded","Retrieval packet exceeds its declared context budget.");let n=new Set(t.uncertainties.map(l=>l.code));t.subjectMatches.some(l=>l.confidence==="unresolved")&&!n.has("subject_unresolved")&&m(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")&&m(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")&&m(e,"uncertainties","silent_truncation","Truncated retrieval must be reported as uncertainty."),t.completeness.conflictsComplete||(t.completeness.status!=="truncated"&&m(e,"completeness.conflictsComplete","silent_conflict_truncation","Incomplete conflict coverage must mark the whole packet truncated."),n.has("retrieval_truncated")||m(e,"uncertainties","missing_conflict_expansion","Incomplete conflicts require explicit truncation and expansion guidance."));let v=new Set(t.decisions.map(l=>l.id));return t.conflicts.forEach((l,a)=>{l.decisionIds.length<2&&m(e,`conflicts[${a}].decisionIds`,"invalid_conflict","Conflicts need at least two applicable decisions.");for(let y of l.decisionIds)v.has(y)||m(e,`conflicts[${a}].decisionIds`,"missing_conflict_position","Every conflict position must be present in the compact decision list.")}),Y(e)}var pe=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&&!pe.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 le(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 ue(t,e){let n=new Map,c=new Set(e.subjectIds??[]),v=(e.subjectHints??[]).map(H).filter(Boolean),l=V([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 y;for(let h of le(a)){let f=H(h.value);for(let R of v){let j=f===R?95:f.includes(R)||R.includes(f)?75:0;j>(y?.score??0)&&(y={subjectId:a.id,label:a.label,confidence:j>=90?"exact":"strong",matchedBy:h.by,score:j})}let w=["/","#","[","]","="].some(R=>h.value.includes(R))?0:Math.round(G(V(f),l)*55);w>=30&&w>(y?.score??0)&&(y={subjectId:a.id,label:a.label,confidence:w>=45?"strong":"weak",matchedBy:"query_text",score:w})}y&&n.set(a.id,y)}return n}function me(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)),v=e.filter(a=>a.iterationIds.some(y=>n.has(y))||a.sourceRefs.some(y=>y.kind==="thread"&&c.has(y.id)));if(!v.length)return{state:"none_found",attemptIds:[]};let l=new Set(v.map(a=>a.state));return{state:l.size>1?"mixed":l.has("completed")?"completed":"attempted",attemptIds:v.map(a=>a.id)}}function ye(t){return Math.ceil(JSON.stringify(t).length/4)}function fe(t,e){let n=t.records.filter(s=>s.recordType==="subject"),c=e.generatedAt??new Date().toISOString(),v=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,l=t.records.filter(s=>{if(s.recordType!=="proposal"||v&&!v.has(s.id))return!1;if(s.state==="pending")return!0;if(s.state!=="deferred")return!1;let r=[...t.events].reverse().find(o=>o.entity.entityType==="proposal"&&o.entity.entityId===s.id&&o.toState==="deferred"&&o.transitionContext?.kind==="proposal_deferral")?.transitionContext;return r?r.resurfaceWhen.includes("different_action")&&e.resurface?.differentAction||r.resurfaceWhen.includes("new_evidence")&&e.resurface?.newEvidence||r.resurfaceWhen.includes("new_conflict")&&e.resurface?.newConflict||r.resurfaceWhen.includes("owner_request")&&e.resurface?.ownerRequested||r.resurfaceWhen.includes("after_date")&&!!(r.revisitAfter&&Date.parse(c)>=Date.parse(r.revisitAfter)):!1}),a=t.records.filter(s=>s.recordType==="implementation_attempt"),y=ue(n,e),h=[...y.values()].sort((s,r)=>r.score-s.score),f=V([e.action,e.text].filter(Boolean).join(" ")),M=l.flatMap(s=>{let r=s.subjects.map(x=>y.get(x.subjectId)).filter(x=>!!x),o=Math.max(0,...r.map(x=>x.score)),p=Math.round(G(V(s.claim),f)*35),g=o+p;return g>=50?[{proposal:s,proposalMatches:r,score:g}]:[]}).sort((s,r)=>r.score-s.score||s.proposal.id.localeCompare(r.proposal.id)),w=Math.max(1,e.maxPackets??3),R=Math.max(200,e.maxEstimatedTokens??1200),j=[],S=0;for(let s of M){if(j.length>=w)break;let r=s.proposal.sourceRefs.slice(0,4),o={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(g=>g.label).join(", ")}.`:"Historical proposal materially overlaps the current task.",subjectMatches:s.proposalMatches.map(({score:g,...x})=>x)},proposal:{id:s.proposal.id,claim:s.proposal.claim,state:s.proposal.state,proposedKind:s.proposal.proposedKind,subjectIds:s.proposal.subjects.map(g=>g.subjectId),origin:s.proposal.origin.mode},authority:"unaccepted",presentation:s.score>=100&&["constraint","rule"].includes(s.proposal.proposedKind??"")?"surface_before_action":"advisory",implementation:me(s.proposal,a),evidence:{sourceCount:s.proposal.sourceRefs.length,sourceRefs:r},actions:["accept","edit_and_accept","split","bundle","reject","defer","request_evidence"],expansionRefs:[{kind:"record",id:s.proposal.id},...r]},p={...o,estimatedTokens:ye(o)};if(S+p.estimatedTokens>R)break;j.push(p),S+=p.estimatedTokens}let i=Math.max(0,M.length-j.length);return{packets:j,subjectMatches:h.map(({score:s,...r})=>r),completeness:{status:i>0?"truncated":"complete",consideredProposalCount:M.length,omittedPacketCount:i,maxEstimatedTokens:R,estimatedTokens:S},uncertainty:y.size===0?"subject_unresolved":M.length===0?"no_relevant_pending_proposal":void 0}}var ve=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function q(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function K(t){return new Set(q(t).split(" ").filter(e=>e.length>2&&!ve.has(e)))}function X(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 Ie(t,e){let n=new Set(e.subjectIds??[]),c=(e.subjectHints??[]).map(q).filter(Boolean),v=K([e.action,e.text].filter(Boolean).join(" ")),l=[];for(let a of t){if(n.has(a.id)){l.push({subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:"exact",matchedBy:"id",score:100});continue}let y,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 M=q(f.value);for(let j of c){let S=M===j?95:M.includes(j)||j.includes(M)?75:0;S>(y?.score??0)&&(y={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:S>=90?"exact":"strong",matchedBy:f.by,score:S})}let R=["/","#","[","]","="].some(j=>f.value.includes(j))?0:Math.round(X(K(M),v)*55);R>=30&&R>(y?.score??0)&&(y={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:R>=45?"strong":"weak",matchedBy:"semantic",score:R})}y&&l.push(y)}return l.sort((a,y)=>y.score-a.score||a.subjectId.localeCompare(y.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 he(t,e){let n=e.filter(l=>l.coverageClaims.some(a=>a.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let c=n.filter(l=>l.state==="completed"),v=c.some(l=>l.coverageClaims.some(a=>a.decisionId===t&&a.coverage==="full"));return{decisionId:t,state:v?"implemented":c.length?"partial":"unknown",attemptIds:n.map(l=>l.id)}}function be(t,e,n){let c=e.filter(y=>y.targets.some(h=>h.entityType==="decision"&&h.entityId===t)).sort((y,h)=>h.createdAt.localeCompare(y.createdAt)),v=n.some(y=>y.signalType==="verification_expired"&&y.target.entityType==="decision"&&y.target.entityId===t),l=c[0],a=v?"stale":l?l.state==="passed"?"passing":l.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(l.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:a,attemptIds:c.map(y=>y.id)}}function Re(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),c=Math.max(1,e.maxDecisions??6),v=t.records.filter(u=>u.recordType==="subject"),l=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,a=t.records.filter(u=>u.recordType==="decision"&&u.state==="active"),y=l?a.filter(u=>l.has(u.id)):a,h=t.records.filter(u=>u.recordType==="implementation_attempt"),f=t.records.filter(u=>u.recordType==="verification_attempt"),M=t.records.filter(u=>u.recordType==="freshness_signal"&&u.state==="open"),w=t.records.filter(u=>u.recordType==="evidence"),R=t.records.filter(u=>u.recordType==="model_entry"),j=[...t.records].reverse().filter(u=>u.recordType==="eval_spec").filter((u,T,I)=>I.findIndex(k=>k.legacyId===u.legacyId)===T),S=Ie(v,e),i=new Map(S.map(u=>[u.subjectId,u.score])),s=K([e.action,e.text].filter(Boolean).join(" ")),r=y.flatMap(u=>{let T=Math.max(0,...u.subjects.map(F=>i.get(F.subjectId)??0)),I=Math.round(X(K(u.claim),s)*35),k=T+I;return k>=50?[{decision:u,score:k}]:[]}).sort((u,T)=>T.score-u.score||u.decision.id.localeCompare(T.decision.id)),o=new Map;for(let u of r.slice(0,c))o.set(u.decision.id,u.decision);for(let u of t.relationships){if(!C(u,"excepts")&&!C(u,"contradicts"))continue;let T=a.find(k=>k.id===u.from.entityId),I=a.find(k=>k.id===u.to.entityId);!T||!I||!o.has(T.id)&&!o.has(I.id)||(o.size<c&&o.set(T.id,T),o.size<c&&o.set(I.id,I))}let p=[...o.values()],g=u=>u.from.entityType==="decision"&&u.to.entityType==="decision"&&o.has(u.from.entityId)&&o.has(u.to.entityId),x=(u,T=!1)=>{let I=new Set(u.map(d=>d.id)),k=M.filter(d=>d.target.entityType==="decision"&&I.has(d.target.entityId)),F=new Set(t.relationships.filter(d=>C(d,"excepts")&&I.has(d.from.entityId)&&I.has(d.to.entityId)).flatMap(d=>[d.from.entityId,d.to.entityId])),O=t.relationships.filter(d=>C(d,"contradicts")&&I.has(d.from.entityId)&&I.has(d.to.entityId)).map(d=>({id:d.id,decisionIds:[d.from.entityId,d.to.entityId],unresolvedQuestion:d.reason,expansionRefs:[{kind:"record",id:d.id}]})),ee=new Set(O.flatMap(d=>d.decisionIds)),N=w.filter(d=>d.sourceRefs.some(b=>b.kind==="record"&&I.has(b.id))||t.relationships.some(b=>b.relationshipType==="supports"&&b.from.entityType==="evidence"&&b.from.entityId===d.id&&b.to.entityType==="decision"&&I.has(b.to.entityId))),J=Math.max(0,r.length-u.length),Q=t.relationships.some(d=>C(d,"contradicts")&&g(d)&&(!I.has(d.from.entityId)||!I.has(d.to.entityId))),W=T||J>0||Q,E=[];S.length===0&&(e.subjectHints?.length??0)>0?E.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):u.length===0&&E.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),O.length&&E.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:O.flatMap(d=>d.expansionRefs)}),N.some(d=>d.availability!=="available")&&E.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:N.map(d=>({kind:"record",id:d.id}))}),W&&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:S.map(({score:d,...b})=>b),modelEntries:R.filter(d=>d.decisionIds.some(b=>I.has(b))).map(d=>({id:d.id,key:d.key,value:d.value,decisionIds:d.decisionIds})),evalSpecs:j.filter(d=>d.decisionIds.some(b=>I.has(b))).map(d=>({id:d.id,legacyId:d.legacyId,state:d.state,title:d.title,assertionCount:d.assertions.length,decisionIds:d.decisionIds,expansionRef:{kind:"record",id:d.id}})),decisions:u.map(d=>({id:d.id,kind:d.kind,claim:d.claim,subjectIds:d.subjects.map(b=>b.subjectId),authority:d.authority,effectiveState:ee.has(d.id)?"conflicted":F.has(d.id)?"excepted":"active",freshness:k.filter(b=>b.target.entityId===d.id).map(b=>b.signalType),expansionRef:{kind:"record",id:d.id}})),conflicts:O,uncertainties:E,implementation:u.map(d=>he(d.id,h)),verification:u.map(d=>be(d.id,f,k)),evidence:N.map(d=>({evidenceId:d.id,summary:d.summary,availability:d.availability,sourceRefs:d.sourceRefs})),completeness:{status:W?"truncated":"complete",omittedDecisionCount:J,omittedEvidenceCount:0,conflictsComplete:!Q}};return U.budget.estimatedTokens=ge(U),U},P=x(p);for(;P.budget.estimatedTokens>n&&p.length>0;){let u=p.pop(),T=t.relationships.filter(I=>C(I,"contradicts")&&(I.from.entityId===u.id||I.to.entityId===u.id)).flatMap(I=>[I.from.entityId,I.to.entityId]);p=p.filter(I=>!T.includes(I.id)),P=x(p,!0)}return P}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 Z(t,e,n,c,v){return{id:v,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 je(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 _e(t,e){let n=[],c=t.records.find(l=>l.recordType==="proposal"&&l.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."}),D(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let l of je(e))D(l)||n.push({code:"invalid_generated_id",message:`${l} 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 l={...B(t,c,e,e.eventId),entity:{entityType:"proposal",entityId:c.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},a=Z(t,c,e,l.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:c.id,append:{records:[a],events:[l],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 l={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."},y={...B(t,l,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:l.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},h=Z(t,l,e,y.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:l.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:[l,h],events:[a,y],relationships:[f]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:l.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 l={...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:[l],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}let v={...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:[v],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:c.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:c.id}]}}}function xe(t,e){let n=structuredClone(t);for(let v of e.projectionUpdates){let l=n.records.find(a=>a.recordType===v.entityType&&a.id===v.entityId);if(!l||l.recordType!=="proposal"&&l.recordType!=="decision")throw new Error(`Projection target not found: ${v.entityType} ${v.entityId}`);if(l.state!==v.fromState)throw new Error(`Projection state conflict for ${v.entityType} ${v.entityId}: expected ${v.fromState}, found ${l.state}`);l.state=v.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(v=>v.createdAt).sort().at(-1);return c&&(n.manifest.updatedAt=c),{bundle:n,validation:z(n)}}export{te as MEMORY_FORMAT_VERSION,ie as MEMORY_SCHEMA_VERSION,xe as applyOwnerReviewActionPlan,D as isUuidV7,_e as planOwnerReviewAction,Re as retrieveActionPacket,fe as selectContextualReviewPackets,z as validateProjectMemoryBundle,de as validateRetrievalPacket};
1
+ var te=1,ie=1;var ne=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function B(t){return ne.test(t)}function Y(t){return{valid:!t.some(e=>e.severity==="error"),issues:t}}function m(t,e,n,d){t.push({path:e,code:n,message:d,severity:"error"})}function z(t,e,n,d){t.push({path:e,code:n,message:d,severity:"warning"})}function j(t,e,n){B(n)||m(t,e,"invalid_uuid_v7","Canonical IDs must be UUIDv7 values.")}function A(t,e,n){(!n||Number.isNaN(Date.parse(n)))&&m(t,e,"invalid_timestamp","Timestamps must be parseable ISO-8601 strings.")}function $(t,e,n,d=!1){d&&n.level==="contributor"&&m(t,`${e}.level`,"insufficient_authority","Contributors cannot accept or change normative product truth."),n.level==="delegate"&&!n.grantId&&m(t,`${e}.grantId`,"missing_authority_grant","Delegate authority must reference the grant used for this action.")}var oe={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"])},re=new Set(["proposal:accepted","proposal:rejected","decision:superseded","decision:revoked"]);function se(t,e,n){j(t,`${n}.id`,e.id),j(t,`${n}.projectId`,e.projectId),j(t,`${n}.participantId`,e.participantId),j(t,`${n}.entity.entityId`,e.entity.entityId),A(t,`${n}.createdAt`,e.createdAt),$(t,`${n}.authority`,e.authority);let d=oe[e.entity.entityType],y=`${e.fromState??"null"}->${e.toState}`;d&&!d.has(y)&&m(t,n,"invalid_lifecycle_transition",`${e.entity.entityType} does not allow ${y}.`);let l=`${e.entity.entityType}:${e.toState}`;if(re.has(l)&&($(t,`${n}.authority`,e.authority,!0),e.reason?.trim()||m(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)&&m(t,`${n}.transitionContext`,"missing_deferral_policy","Deferred proposals require structured resurfacing conditions."),a?.resurfaceWhen.includes("after_date")&&!a.revisitAfter&&m(t,`${n}.transitionContext.revisitAfter`,"missing_revisit_date","after_date resurfacing requires revisitAfter."),a?.revisitAfter&&A(t,`${n}.transitionContext.revisitAfter`,a.revisitAfter)}}function ae(t,e,n,d){j(t,`${n}.id`,e.id),j(t,`${n}.projectId`,e.projectId),j(t,`${n}.participantId`,e.participantId),A(t,`${n}.createdAt`,e.createdAt),e.projectId!==d&&m(t,`${n}.projectId`,"project_mismatch","Record belongs to another project."),"subjects"in e&&e.subjects.length===0&&m(t,`${n}.subjects`,"missing_subject","Proposals and decisions need a subject."),"subjects"in e&&e.subjects.length>1&&!e.subjectSemantics?.trim()&&m(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)&&m(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()||m(t,`${n}.claim`,"empty_claim","Accepted decisions require a claim.")),e.recordType==="authority_grant"&&e.level==="owner"&&z(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())&&m(t,n,"incomplete_advisory_explanation","Advisory explanations need a statement and rationale."),A(t,`${n}.updatedAt`,e.updatedAt),e.subjectIds.length===0&&m(t,`${n}.subjectIds`,"missing_subject","Advisory explanations need a subject."),e.scope.values.some(y=>!y.trim())&&m(t,`${n}.scope.values`,"empty_scope_value","Advisory scope values cannot be empty."),e.concreteBindings.forEach((y,l)=>{(!y.id.trim()||!y.modelPath.trim())&&m(t,`${n}.concreteBindings[${l}]`,"incomplete_concrete_binding","Concrete bindings need an id and model path."),A(t,`${n}.concreteBindings[${l}].createdAt`,y.createdAt),A(t,`${n}.concreteBindings[${l}].updatedAt`,y.updatedAt)})),e.recordType==="freshness_signal"&&e.state==="resolved"&&(!e.resolvedAt||!e.resolvedByEventId)&&m(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&&m(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())&&m(t,n,"incomplete_eval_spec","Eval specs need a stable id, title, and prompt."),(e.assertions.length===0||e.assertions.some(y=>!y.trim()))&&m(t,`${n}.assertions`,"empty_eval_assertions","Eval specs need at least one non-empty assertion."),e.targets.length===0&&e.decisionIds.length===0&&z(t,n,"unbound_eval_spec","Eval spec is not yet bound to canonical product truth."),(e.dependencies?.length??0)===0&&z(t,`${n}.dependencies`,"unscoped_eval_spec","Eval spec has no freshness dependencies."))}function ce(t,e,n){if(j(t,`${n}.id`,e.id),j(t,`${n}.projectId`,e.projectId),j(t,`${n}.participantId`,e.participantId),j(t,`${n}.from.entityId`,e.from.entityId),j(t,`${n}.to.entityId`,e.to.entityId),A(t,`${n}.createdAt`,e.createdAt),e.reason.trim()||m(t,`${n}.reason`,"missing_relationship_reason","Relationships need a reason."),new Set(["supports","contradicts","supersedes","excepts"]).has(e.relationshipType)){let y=e.from.entityType==="decision"&&e.to.entityType==="decision",l=e.from.entityType==="advisory_explanation"&&e.to.entityType==="advisory_explanation";!y&&!l&&m(t,n,"invalid_normative_relationship","These relationships connect decisions to decisions or advisory explanations to advisory explanations."),y&&!e.authority?m(t,`${n}.authority`,"missing_relationship_authority","Normative relationships require explicit authority context."):y&&e.authority&&$(t,`${n}.authority`,e.authority,!0)}["operationalizes","refines","instantiates"].includes(e.relationshipType)&&(e.from.entityType!=="advisory_explanation"||e.to.entityType!=="advisory_explanation")&&m(t,n,"invalid_advisory_relationship","Advisory topology relationships connect advisory explanations."),e.relationshipType==="implements"&&(e.from.entityType!=="implementation_attempt"||e.to.entityType!=="decision")&&m(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))&&m(t,n,"invalid_verifies_relationship","`verifies` points from a verification attempt to a verifiable target."),e.relationshipType==="replaces"&&e.from.entityType!==e.to.entityType&&m(t,n,"invalid_replaces_relationship","`replaces` connects records of the same entity type.")}function L(t){let e=[];j(e,"manifest.projectId",t.manifest.projectId),A(e,"manifest.createdAt",t.manifest.createdAt),A(e,"manifest.updatedAt",t.manifest.updatedAt);let n=new Map,d=(i,s)=>{let o=n.get(i);o?m(e,s,"duplicate_id",`ID is already used at ${o}.`):n.set(i,s)};t.records.forEach((i,s)=>{let o=`records[${s}]`;d(i.id,o),ae(e,i,o,t.manifest.projectId)}),t.events.forEach((i,s)=>{let o=`events[${s}]`;d(i.id,o),se(e,i,o),i.projectId!==t.manifest.projectId&&m(e,`${o}.projectId`,"project_mismatch","Event belongs to another project.")}),t.relationships.forEach((i,s)=>{let o=`relationships[${s}]`;d(i.id,o),ce(e,i,o),i.projectId!==t.manifest.projectId&&m(e,`${o}.projectId`,"project_mismatch","Relationship belongs to another project.")}),t.artifacts.forEach((i,s)=>{d(i.id,`artifacts[${s}]`),j(e,`artifacts[${s}].id`,i.id)}),t.tombstones.forEach((i,s)=>{let o=`tombstones[${s}]`;d(i.id,o),j(e,`${o}.id`,i.id),j(e,`${o}.objectId`,i.objectId),j(e,`${o}.deletedById`,i.deletedById),A(e,`${o}.deletedAt`,i.deletedAt),$(e,`${o}.authority`,i.authority,!0)});let y=new Set(t.records.map(i=>`${i.recordType}:${i.id}`)),l=new Set(t.tombstones.map(i=>`${i.objectType}:${i.objectId}`)),a=(i,s)=>{let o=`${i.entityType}:${i.entityId}`;!y.has(o)&&!l.has(o)&&m(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)||m(e,s,"dangling_artifact_reference","No artifact manifest entry exists.")},f=(i,s,o)=>{!y.has(`${i}:${s}`)&&!l.has(`${i}:${s}`)&&m(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,c)=>f("subject",r,`${o}.subjectIds[${c}]`));break;case"observation":i.captureContext.subjectIds.forEach((r,c)=>f("subject",r,`${o}.captureContext.subjectIds[${c}]`)),i.captureContext.artifactIds.forEach((r,c)=>h(r,`${o}.captureContext.artifactIds[${c}]`));break;case"proposal":case"decision":i.subjects.forEach((r,c)=>f("subject",r.subjectId,`${o}.subjects[${c}].subjectId`));break;case"thread":i.messageArtifactIds.forEach((r,c)=>h(r,`${o}.messageArtifactIds[${c}]`)),i.resultRefs.forEach((r,c)=>a(r,`${o}.resultRefs[${c}]`));break;case"iteration":i.threadIds.forEach((r,c)=>f("thread",r,`${o}.threadIds[${c}]`)),i.artifactIds.forEach((r,c)=>h(r,`${o}.artifactIds[${c}]`));break;case"evidence":i.artifactIds.forEach((r,c)=>h(r,`${o}.artifactIds[${c}]`));break;case"advisory_explanation":i.subjectIds.forEach((r,c)=>f("subject",r,`${o}.subjectIds[${c}]`)),i.evidenceIds.forEach((r,c)=>f("evidence",r,`${o}.evidenceIds[${c}]`)),i.supersededById&&f("advisory_explanation",i.supersededById,`${o}.supersededById`);break;case"implementation_attempt":i.iterationIds.forEach((r,c)=>f("iteration",r,`${o}.iterationIds[${c}]`)),i.coverageClaims.forEach((r,c)=>f("decision",r.decisionId,`${o}.coverageClaims[${c}].decisionId`)),i.artifactIds.forEach((r,c)=>h(r,`${o}.artifactIds[${c}]`));break;case"eval_spec":i.replacesSpecId&&f("eval_spec",i.replacesSpecId,`${o}.replacesSpecId`),i.decisionIds.forEach((r,c)=>f("decision",r,`${o}.decisionIds[${c}]`)),i.subjectIds.forEach((r,c)=>f("subject",r,`${o}.subjectIds[${c}]`)),(i.dependencies??[]).forEach((r,c)=>{r.kind==="subject"&&r.subjectId&&f("subject",r.subjectId,`${o}.dependencies[${c}].subjectId`)}),(i.scenarios??[]).forEach((r,c)=>{r.subjectIds?.forEach((I,x)=>f("subject",I,`${o}.scenarios[${c}].subjectIds[${x}]`))}),i.targets.forEach((r,c)=>f(r.entityType,r.entityId,`${o}.targets[${c}]`));break;case"verification_attempt":i.evalSpecId&&f("eval_spec",i.evalSpecId,`${o}.evalSpecId`),i.targets.forEach((r,c)=>f(r.entityType,r.entityId,`${o}.targets[${c}]`)),i.evidenceIds.forEach((r,c)=>f("evidence",r,`${o}.evidenceIds[${c}]`));break;case"model_entry":i.subjectIds.forEach((r,c)=>f("subject",r,`${o}.subjectIds[${c}]`)),i.decisionIds.forEach((r,c)=>f("decision",r,`${o}.decisionIds[${c}]`));break;case"model_projection":$(e,`${o}.authority`,i.authority,!0),f("participant",i.appliedById,`${o}.appliedById`),i.decisionIds.forEach((r,c)=>f("decision",r,`${o}.decisionIds[${c}]`)),i.entryIds.forEach((r,c)=>f("model_entry",r,`${o}.entryIds[${c}]`)),i.coverage.forEach((r,c)=>f("decision",r.decisionId,`${o}.coverage[${c}].decisionId`));break;case"freshness_signal":a(i.target,`${o}.target`),i.evidenceIds.forEach((r,c)=>f("evidence",r,`${o}.evidenceIds[${c}]`));break;default:break}});let M=new Map(t.events.map(i=>[i.id,i])),w=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&&m(e,`events[${s}]`,"concurrent_incompatible_transitions","The same entity state has multiple incompatible successor states.")});let R=new Map(t.records.flatMap(i=>i.recordType==="authority_grant"?[[i.id,i]]:[])),S=(i,s,o,r,c)=>{if(i.level!=="delegate"||!i.grantId)return;let I=R.get(i.grantId);if(!I){m(e,c,"invalid_authority_grant","Delegated authority references a missing grant.");return}(I.granteeId!==s||I.level!=="delegate")&&m(e,c,"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))&&m(e,c,"inactive_authority_grant","The delegated authority grant was not active at this time."),I.subjectIds.length&&r.length&&!r.every(P=>I.subjectIds.includes(P))&&m(e,c,"authority_scope_mismatch","The delegated action exceeds the grant subject scope.")};for(let i of t.records)i.recordType==="decision"&&S(i.authority,i.acceptedById,i.createdAt,i.subjects.map(s=>s.subjectId),`records:${i.id}.authority`);t.events.forEach((i,s)=>{let o=w.get(`${i.entity.entityType}:${i.entity.entityId}`),r=o&&"subjects"in o?o.subjects.map(c=>c.subjectId):[];S(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 c=w.get(`${r.entityType}:${r.entityId}`);return c&&"subjects"in c?c.subjects.map(I=>I.subjectId):[]});S(i.authority,i.participantId,i.createdAt,o,`relationships[${s}].authority`)});for(let i of t.records){if(i.recordType!=="decision")continue;let s=M.get(i.acceptanceEventId);(!s||s.entity.entityType!=="proposal"||s.entity.entityId!==i.proposalId||s.toState!=="accepted")&&m(e,`records:${i.id}.acceptanceEventId`,"invalid_acceptance_event","A decision must reference the proposal event that explicitly accepted it."),s&&s.participantId!==i.acceptedById&&m(e,`records:${i.id}.acceptedById`,"acceptor_mismatch","Decision acceptor must match the acceptance event participant."),w.has(`proposal:${i.proposalId}`)||m(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)||m(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())||m(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)||m(e,`records:${i.id}.state`,"accepted_proposal_without_decision","Every accepted proposal must produce an immutable decision.")}return Y(e)}function de(t){let e=[];j(e,"projectId",t.projectId),A(e,"retrievedAt",t.retrievedAt),t.budget.maxEstimatedTokens<=0&&m(e,"budget.maxEstimatedTokens","invalid_budget","Token budget must be positive."),t.budget.estimatedTokens>t.budget.maxEstimatedTokens&&m(e,"budget.estimatedTokens","token_budget_exceeded","Retrieval packet exceeds its declared context budget.");let n=new Set(t.uncertainties.map(l=>l.code));t.subjectMatches.some(l=>l.confidence==="unresolved")&&!n.has("subject_unresolved")&&m(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")&&m(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")&&m(e,"uncertainties","silent_truncation","Truncated retrieval must be reported as uncertainty."),t.completeness.conflictsComplete||(t.completeness.status!=="truncated"&&m(e,"completeness.conflictsComplete","silent_conflict_truncation","Incomplete conflict coverage must mark the whole packet truncated."),n.has("retrieval_truncated")||m(e,"uncertainties","missing_conflict_expansion","Incomplete conflicts require explicit truncation and expansion guidance."));let y=new Set(t.decisions.map(l=>l.id));return t.conflicts.forEach((l,a)=>{l.decisionIds.length<2&&m(e,`conflicts[${a}].decisionIds`,"invalid_conflict","Conflicts need at least two applicable decisions.");for(let v of l.decisionIds)y.has(v)||m(e,`conflicts[${a}].decisionIds`,"missing_conflict_position","Every conflict position must be present in the compact decision list.")}),Y(e)}var pe=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&&!pe.has(e)))}function G(t,e){if(!t.size||!e.size)return 0;let n=0;for(let d of t)e.has(d)&&(n+=1);return n/Math.min(t.size,e.size)}function le(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 ue(t,e){let n=new Map,d=new Set(e.subjectIds??[]),y=(e.subjectHints??[]).map(H).filter(Boolean),l=V([e.action,e.text].filter(Boolean).join(" "));for(let a of t){if(d.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 le(a)){let f=H(h.value);for(let _ of y){let R=f===_?95:f.includes(_)||_.includes(f)?75:0;R>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:R>=90?"exact":"strong",matchedBy:h.by,score:R})}let w=["/","#","[","]","="].some(_=>h.value.includes(_))?0:Math.round(G(V(f),l)*55);w>=30&&w>(v?.score??0)&&(v={subjectId:a.id,label:a.label,confidence:w>=45?"strong":"weak",matchedBy:"query_text",score:w})}v&&n.set(a.id,v)}return n}function me(t,e){let n=new Set(t.sourceRefs.filter(a=>a.kind==="iteration").map(a=>a.id)),d=new Set(t.sourceRefs.filter(a=>a.kind==="thread").map(a=>a.id)),y=e.filter(a=>a.iterationIds.some(v=>n.has(v))||a.sourceRefs.some(v=>v.kind==="thread"&&d.has(v.id)));if(!y.length)return{state:"none_found",attemptIds:[]};let l=new Set(y.map(a=>a.state));return{state:l.size>1?"mixed":l.has("completed")?"completed":"attempted",attemptIds:y.map(a=>a.id)}}function ye(t){return Math.ceil(JSON.stringify(t).length/4)}function fe(t,e){let n=t.records.filter(s=>s.recordType==="subject"),d=e.generatedAt??new Date().toISOString(),y=e.candidateProposalIds?new Set(e.candidateProposalIds):void 0,l=t.records.filter(s=>{if(s.recordType!=="proposal"||y&&!y.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(d)>=Date.parse(o.revisitAfter)):!1}),a=t.records.filter(s=>s.recordType==="implementation_attempt"),v=ue(n,e),h=[...v.values()].sort((s,o)=>o.score-s.score),f=V([e.action,e.text].filter(Boolean).join(" ")),M=l.flatMap(s=>{let o=s.subjects.map(x=>v.get(x.subjectId)).filter(x=>!!x),r=Math.max(0,...o.map(x=>x.score)),c=Math.round(G(V(s.claim),f)*35),I=r+c;return I>=50?[{proposal:s,proposalMatches:o,score:I}]:[]}).sort((s,o)=>o.score-s.score||s.proposal.id.localeCompare(o.proposal.id)),w=Math.max(1,e.maxPackets??3),_=Math.max(200,e.maxEstimatedTokens??1200),R=[],S=0;for(let s of M){if(R.length>=w)break;let o=s.proposal.sourceRefs.slice(0,4),r={contractVersion:1,packetId:`review:${s.proposal.id}`,projectId:t.manifest.projectId,generatedAt:d,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:me(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]},c={...r,estimatedTokens:ye(r)};if(S+c.estimatedTokens>_)break;R.push(c),S+=c.estimatedTokens}let i=Math.max(0,M.length-R.length);return{packets:R,subjectMatches:h.map(({score:s,...o})=>o),completeness:{status:i>0?"truncated":"complete",consideredProposalCount:M.length,omittedPacketCount:i,maxEstimatedTokens:_,estimatedTokens:S},uncertainty:v.size===0?"subject_unresolved":M.length===0?"no_relevant_pending_proposal":void 0}}var ve=new Set(["about","after","again","before","being","change","from","have","into","make","should","that","the","their","this","with","would","here","only"]);function q(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().replace(/\s+/g," ")}function K(t){return new Set(q(t).split(" ").filter(e=>e.length>2&&!ve.has(e)))}function X(t,e){if(!t.size||!e.size)return 0;let n=0;for(let d of t)e.has(d)&&(n+=1);return n/Math.min(t.size,e.size)}function ge(t,e){let n=new Set(e.subjectIds??[]),d=(e.subjectHints??[]).map(q).filter(Boolean),y=K([e.action,e.text].filter(Boolean).join(" ")),l=[];for(let a of t){if(n.has(a.id)){l.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 M=q(f.value);for(let R of d){let S=M===R?95:M.includes(R)||R.includes(M)?75:0;S>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:S>=90?"exact":"strong",matchedBy:f.by,score:S})}let _=["/","#","[","]","="].some(R=>f.value.includes(R))?0:Math.round(X(K(M),y)*55);_>=30&&_>(v?.score??0)&&(v={subjectId:a.id,subjectType:a.subjectType,label:a.label,confidence:_>=45?"strong":"weak",matchedBy:"semantic",score:_})}v&&l.push(v)}return l.sort((a,v)=>v.score-a.score||a.subjectId.localeCompare(v.subjectId))}function Ie(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 he(t,e){let n=e.filter(l=>l.coverageClaims.some(a=>a.decisionId===t));if(!n.length)return{decisionId:t,state:"unimplemented",attemptIds:[]};let d=n.filter(l=>l.state==="completed"),y=d.some(l=>l.coverageClaims.some(a=>a.decisionId===t&&a.coverage==="full"));return{decisionId:t,state:y?"implemented":d.length?"partial":"unknown",attemptIds:n.map(l=>l.id)}}function be(t,e,n){let d=e.filter(v=>v.targets.some(h=>h.entityType==="decision"&&h.entityId===t)).sort((v,h)=>h.createdAt.localeCompare(v.createdAt)),y=n.some(v=>v.signalType==="verification_expired"&&v.target.entityType==="decision"&&v.target.entityId===t),l=d[0],a=y?"stale":l?l.state==="passed"?"passing":l.state==="failed"?"failing":["inconclusive","error","cancelled"].includes(l.state)?"blocked":"unverified":"unverified";return{target:{entityType:"decision",entityId:t},state:a,attemptIds:d.map(v=>v.id)}}function _e(t,e){let n=Math.max(300,e.maxEstimatedTokens??1200),d=Math.max(1,e.maxDecisions??6),y=t.records.filter(u=>u.recordType==="subject"),l=e.candidateDecisionIds?new Set(e.candidateDecisionIds):void 0,a=t.records.filter(u=>u.recordType==="decision"&&u.state==="active"),v=l?a.filter(u=>l.has(u.id)):a,h=t.records.filter(u=>u.recordType==="implementation_attempt"),f=t.records.filter(u=>u.recordType==="verification_attempt"),M=t.records.filter(u=>u.recordType==="freshness_signal"&&u.state==="open"),w=t.records.filter(u=>u.recordType==="evidence"),_=t.records.filter(u=>u.recordType==="model_entry"),R=[...t.records].reverse().filter(u=>u.recordType==="eval_spec").filter((u,T,g)=>g.findIndex(k=>k.legacyId===u.legacyId)===T),S=ge(y,e),i=new Map(S.map(u=>[u.subjectId,u.score])),s=K([e.action,e.text].filter(Boolean).join(" ")),o=v.flatMap(u=>{let T=Math.max(0,...u.subjects.map(F=>i.get(F.subjectId)??0)),g=Math.round(X(K(u.claim),s)*35),k=T+g;return k>=50?[{decision:u,score:k}]:[]}).sort((u,T)=>T.score-u.score||u.decision.id.localeCompare(T.decision.id)),r=new Map;for(let u of o.slice(0,d))r.set(u.decision.id,u.decision);for(let u of t.relationships){if(!C(u,"excepts")&&!C(u,"contradicts"))continue;let T=a.find(k=>k.id===u.from.entityId),g=a.find(k=>k.id===u.to.entityId);!T||!g||!r.has(T.id)&&!r.has(g.id)||(r.size<d&&r.set(T.id,T),r.size<d&&r.set(g.id,g))}let c=[...r.values()],I=u=>u.from.entityType==="decision"&&u.to.entityType==="decision"&&r.has(u.from.entityId)&&r.has(u.to.entityId),x=(u,T=!1)=>{let g=new Set(u.map(p=>p.id)),k=M.filter(p=>p.target.entityType==="decision"&&g.has(p.target.entityId)),F=new Set(t.relationships.filter(p=>C(p,"excepts")&&g.has(p.from.entityId)&&g.has(p.to.entityId)).flatMap(p=>[p.from.entityId,p.to.entityId])),O=t.relationships.filter(p=>C(p,"contradicts")&&g.has(p.from.entityId)&&g.has(p.to.entityId)).map(p=>({id:p.id,decisionIds:[p.from.entityId,p.to.entityId],unresolvedQuestion:p.reason,expansionRefs:[{kind:"record",id:p.id}]})),ee=new Set(O.flatMap(p=>p.decisionIds)),U=w.filter(p=>p.sourceRefs.some(b=>b.kind==="record"&&g.has(b.id))||t.relationships.some(b=>b.relationshipType==="supports"&&b.from.entityType==="evidence"&&b.from.entityId===p.id&&b.to.entityType==="decision"&&g.has(b.to.entityId))),J=Math.max(0,o.length-u.length),Q=t.relationships.some(p=>C(p,"contradicts")&&I(p)&&(!g.has(p.from.entityId)||!g.has(p.to.entityId))),W=T||J>0||Q,E=[];S.length===0&&(e.subjectHints?.length??0)>0?E.push({code:"subject_unresolved",message:"No canonical subject matched the supplied task hints.",expansionRefs:[]}):u.length===0&&E.push({code:"no_applicable_decision",message:"No accepted decision applies to the resolved task subjects.",expansionRefs:[]}),O.length&&E.push({code:"known_conflict",message:"Applicable accepted decisions contain an unresolved contradiction.",expansionRefs:O.flatMap(p=>p.expansionRefs)}),U.some(p=>p.availability!=="available")&&E.push({code:"evidence_unavailable",message:"Some supporting evidence is unavailable.",expansionRefs:U.map(p=>({kind:"record",id:p.id}))}),W&&E.push({code:"retrieval_truncated",message:"Additional applicable memory exists outside this packet.",expansionRefs:[{kind:"record",id:t.manifest.projectId}]});let N={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:S.map(({score:p,...b})=>b),modelEntries:_.filter(p=>p.decisionIds.some(b=>g.has(b))).map(p=>({id:p.id,key:p.key,value:p.value,decisionIds:p.decisionIds})),evalSpecs:R.filter(p=>p.decisionIds.some(b=>g.has(b))).map(p=>({id:p.id,legacyId:p.legacyId,state:p.state,title:p.title,assertionCount:p.assertions.length,decisionIds:p.decisionIds,expansionRef:{kind:"record",id:p.id}})),decisions:u.map(p=>({id:p.id,kind:p.kind,claim:p.claim,subjectIds:p.subjects.map(b=>b.subjectId),authority:p.authority,effectiveState:ee.has(p.id)?"conflicted":F.has(p.id)?"excepted":"active",freshness:k.filter(b=>b.target.entityId===p.id).map(b=>b.signalType),expansionRef:{kind:"record",id:p.id}})),conflicts:O,uncertainties:E,implementation:u.map(p=>he(p.id,h)),verification:u.map(p=>be(p.id,f,k)),evidence:U.map(p=>({evidenceId:p.id,summary:p.summary,availability:p.availability,sourceRefs:p.sourceRefs})),completeness:{status:W?"truncated":"complete",omittedDecisionCount:J,omittedEvidenceCount:0,conflictsComplete:!Q}};return N.budget.estimatedTokens=Ie(N),N},P=x(c);for(;P.budget.estimatedTokens>n&&c.length>0;){let u=c.pop(),T=t.relationships.filter(g=>C(g,"contradicts")&&(g.from.entityId===u.id||g.to.entityId===u.id)).flatMap(g=>[g.from.entityId,g.to.entityId]);c=c.filter(g=>!T.includes(g.id)),P=x(c,!0)}return P}function D(t,e,n,d){return{id:d,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 Z(t,e,n,d,y){return{id:y,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:d,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 Re(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=[],d=t.records.find(l=>l.recordType==="proposal"&&l.id===e.proposalId);d?d.state!=="pending"&&n.push({code:"proposal_not_pending",message:`Proposal is ${d.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."}),B(e.participantId)||n.push({code:"invalid_participant_id",message:"Participant ID must be UUIDv7."});for(let l of Re(e))B(l)||n.push({code:"invalid_generated_id",message:`${l} is not UUIDv7.`});if(Number.isNaN(Date.parse(e.occurredAt))&&n.push({code:"invalid_timestamp",message:"occurredAt must be ISO-8601."}),n.length||!d)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 l={...D(t,d,e,e.eventId),entity:{entityType:"proposal",entityId:d.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},a=Z(t,d,e,l.id,e.decisionId);return{ok:!0,plan:{action:e.action,proposalId:d.id,append:{records:[a],events:[l],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:d.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 l={id:e.replacementProposalId,schemaVersion:1,projectId:t.manifest.projectId,createdAt:e.occurredAt,participantId:e.participantId,sourceRefs:[{kind:"record",id:d.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={...D(t,d,e,e.withdrawalEventId),entity:{entityType:"proposal",entityId:d.id},eventType:"proposal.withdrawn",fromState:"pending",toState:"withdrawn",reason:"Owner replaced the inferred proposal with edited wording during review."},v={...D(t,l,e,e.acceptanceEventId),entity:{entityType:"proposal",entityId:l.id},eventType:"proposal.accepted",fromState:"pending",toState:"accepted",reason:e.reason},h=Z(t,l,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:d.id}],recordType:"relationship",relationshipType:"derived_from",from:{entityType:"proposal",entityId:l.id},to:{entityType:"proposal",entityId:d.id},reason:"Owner-edited proposal derives from the historical review candidate."};return{ok:!0,plan:{action:e.action,proposalId:d.id,append:{records:[l,h],events:[a,v],relationships:[f]},projectionUpdates:[{entityType:"proposal",entityId:d.id,fromState:"pending",state:"withdrawn"}],resultRefs:[{entityType:"proposal",entityId:l.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 l={...D(t,d,e,e.eventId),entity:{entityType:"proposal",entityId:d.id},eventType:"proposal.rejected",fromState:"pending",toState:"rejected",reason:e.reason};return{ok:!0,plan:{action:e.action,proposalId:d.id,append:{records:[],events:[l],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:d.id,fromState:"pending",state:"rejected"}],resultRefs:[{entityType:"proposal",entityId:d.id}]}}}let y={...D(t,d,e,e.eventId),entity:{entityType:"proposal",entityId:d.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:d.id,append:{records:[],events:[y],relationships:[]},projectionUpdates:[{entityType:"proposal",entityId:d.id,fromState:"pending",state:"deferred"}],resultRefs:[{entityType:"proposal",entityId:d.id}]}}}function xe(t,e){let n=structuredClone(t);for(let y of e.projectionUpdates){let l=n.records.find(a=>a.recordType===y.entityType&&a.id===y.entityId);if(!l||l.recordType!=="proposal"&&l.recordType!=="decision")throw new Error(`Projection target not found: ${y.entityType} ${y.entityId}`);if(l.state!==y.fromState)throw new Error(`Projection state conflict for ${y.entityType} ${y.entityId}: expected ${y.fromState}, found ${l.state}`);l.state=y.state}n.records.push(...e.append.records),n.events.push(...e.append.events),n.relationships.push(...e.append.relationships);let d=e.append.events.map(y=>y.createdAt).sort().at(-1);return d&&(n.manifest.updatedAt=d),{bundle:n,validation:L(n)}}export{te as MEMORY_FORMAT_VERSION,ie as MEMORY_SCHEMA_VERSION,xe as applyOwnerReviewActionPlan,B as isUuidV7,je as planOwnerReviewAction,_e as retrieveActionPacket,fe as selectContextualReviewPackets,L as validateProjectMemoryBundle,de as validateRetrievalPacket};
@@ -1 +1 @@
1
- import{a as p,b as d,c as l,d as g}from"./chunk-EYFN72RC.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};
1
+ import{a as p,b as d,c as l,d as g}from"./chunk-ETDSTV4E.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};
@@ -1 +1 @@
1
- import{a as n,b as i,c as o,d as a}from"./chunk-EYFN72RC.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};
1
+ import{a as n,b as i,c as o,d as a}from"./chunk-ETDSTV4E.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};