@popmelt.com/core 0.8.6 → 0.8.8

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';
@@ -185,12 +216,15 @@ type VerificationTarget = {
185
216
  entityType: 'decision' | 'implementation_attempt' | 'model_entry';
186
217
  entityId: MemoryId;
187
218
  };
219
+ /** @deprecated Retained only so existing memory journals remain readable. */
188
220
  type EvalSpecState = 'draft' | 'active' | 'retired';
221
+ /** @deprecated Retained only so existing memory journals remain readable. */
189
222
  type EvalDependency = {
190
223
  kind: 'model_path' | 'source_file' | 'route' | 'subject';
191
224
  value: string;
192
225
  subjectId?: MemoryId;
193
226
  };
227
+ /** @deprecated Retained only so existing memory journals remain readable. */
194
228
  type EvalScenario = {
195
229
  id: string;
196
230
  label?: string;
@@ -213,6 +247,7 @@ type EvalScenario = {
213
247
  value?: string;
214
248
  }>;
215
249
  };
250
+ /** @deprecated Retained only so existing memory journals remain readable. */
216
251
  type EvalSpecRecord = Provenance & {
217
252
  recordType: 'eval_spec';
218
253
  state: EvalSpecState;
@@ -252,7 +287,7 @@ type VerificationAttemptRecord = Provenance & {
252
287
  targets: VerificationTarget[];
253
288
  summary?: string;
254
289
  evidenceIds: MemoryId[];
255
- /** Compact presentation data for an eval run; raw output remains an artifact/thread detail. */
290
+ /** @deprecated Historical presentation data retained for journal compatibility. */
256
291
  evalRun?: {
257
292
  id: string;
258
293
  threadId?: string;
@@ -305,13 +340,13 @@ type ModelProjectionRecord = Provenance & {
305
340
  status: 'unprojected' | 'partially_projected' | 'projected' | 'stale';
306
341
  }>;
307
342
  };
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';
343
+ 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
344
  type MemoryObjectType = EntityType | 'relationship' | 'lifecycle_event' | 'artifact';
310
345
  type EntityReference = {
311
346
  entityType: EntityType;
312
347
  entityId: MemoryId;
313
348
  };
314
- type RelationshipType = 'supports' | 'contradicts' | 'supersedes' | 'excepts' | 'duplicates' | 'implements' | 'verifies' | 'replaces' | 'derived_from';
349
+ type RelationshipType = 'supports' | 'contradicts' | 'supersedes' | 'excepts' | 'duplicates' | 'implements' | 'verifies' | 'replaces' | 'derived_from' | 'operationalizes' | 'refines' | 'instantiates';
315
350
  type RelationshipRecord = Provenance & {
316
351
  recordType: 'relationship';
317
352
  relationshipType: RelationshipType;
@@ -374,8 +409,8 @@ type Tombstone = {
374
409
  erasureLevel: 'content' | 'content_and_evidence' | 'full_where_permitted';
375
410
  invalidates: EntityReference[];
376
411
  };
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';
412
+ type CanonicalRecord = ParticipantRecord | AuthorityGrantRecord | SubjectRecord | ObservationRecord | ProposalRecord | DecisionRecord | ThreadRecord | IterationRecord | EvidenceRecord | AdvisoryExplanationRecord | ImplementationAttemptRecord | EvalSpecRecord | VerificationAttemptRecord | ModelEntryRecord | ModelProjectionRecord | FreshnessSignalRecord;
413
+ type MemoryFeature = 'authority' | 'subjects' | 'decisions' | 'advisory_explanations' | 'implementations' | 'verification' | 'eval_specs' | 'model_projection' | 'freshness' | 'portable_artifacts' | 'bounded_retrieval';
379
414
  type ProjectMemoryManifest = {
380
415
  formatVersion: MemoryFormatVersion;
381
416
  projectId: MemoryId;
@@ -450,15 +485,6 @@ type RetrievalPacket = {
450
485
  value: JsonValue;
451
486
  decisionIds: MemoryId[];
452
487
  }>;
453
- evalSpecs: Array<{
454
- id: MemoryId;
455
- legacyId: string;
456
- state: EvalSpecState;
457
- title: string;
458
- assertionCount: number;
459
- decisionIds: MemoryId[];
460
- expansionRef: SourceReference;
461
- }>;
462
488
  decisions: RetrievalDecision[];
463
489
  conflicts: RetrievalConflict[];
464
490
  uncertainties: RetrievalUncertainty[];
@@ -659,4 +685,4 @@ declare function applyOwnerReviewActionPlan(bundle: ProjectMemoryBundle, plan: O
659
685
  validation: SchemaValidationResult;
660
686
  };
661
687
 
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 };
688
+ 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 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 +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-DLYPQXHS.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-DLYPQXHS.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};