@mnemo-ai/types 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.es.md +155 -0
- package/README.md +155 -0
- package/dist/chunk-2PEOVZQ5.js +1133 -0
- package/dist/chunk-2PEOVZQ5.js.map +1 -0
- package/dist/chunk-BZD2CQAU.js +109 -0
- package/dist/chunk-BZD2CQAU.js.map +1 -0
- package/dist/harness-runtime-C-bRQP8g.d.cts +233 -0
- package/dist/harness-runtime-C-bRQP8g.d.ts +233 -0
- package/dist/harness-runtime.cjs +119 -0
- package/dist/harness-runtime.cjs.map +1 -0
- package/dist/harness-runtime.d.cts +1 -0
- package/dist/harness-runtime.d.ts +1 -0
- package/dist/harness-runtime.js +3 -0
- package/dist/harness-runtime.js.map +1 -0
- package/dist/index.cjs +1350 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +757 -0
- package/dist/index.d.ts +757 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/ports-BSlOiFxE.d.cts +6577 -0
- package/dist/ports-BTJeMaJJ.d.ts +6577 -0
- package/dist/testing/index.cjs +9854 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +997 -0
- package/dist/testing/index.d.ts +997 -0
- package/dist/testing/index.js +9192 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +75 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,757 @@
|
|
|
1
|
+
import { G as GraphNode, a as GraphEdge, b as GraphSnapshot, A as AuditActivity, c as AuditFeedStats, H as HealthSnapshot, d as HealthSnapshotDay, S as SessionStats, P as PrimitiveKind } from './ports-BTJeMaJJ.js';
|
|
2
|
+
export { e as ALL_SCOPES, f as APPROVAL_PENDING_TTL_MS, g as APPROVAL_USE_TTL_MS, h as AccessPolicyRecord, i as AccessPolicyStore, j as ActionDsl, k as ActionDslSchema, l as ActiveLearningReviewFilter, m as ActiveLearningReviewPort, n as ActiveLearningReviewReason, o as ActiveLearningReviewResolution, p as ActiveLearningReviewRow, q as AgentMemoryAccess, r as AgentPort, s as AnomalyScore, t as AnticipationPort, u as ApiKeyRecord, v as ApiKeyStore, w as ApiKeyType, x as AppendInferenceInput, y as ApplyConsolidationMergeInput, z as ApplyRelationJudgmentInput, B as ApprovalRequest, C as ApprovalRequestInput, D as ApprovalStore, E as ApprovalTrigger, F as AuditAction, I as AuditActorType, J as AuditFeedEntry, K as AuditFeedFilter, L as AuditLogEntry, M as AuditPort, N as AuthAdapter, O as AuthContext, Q as AuthOperation, R as AuthResult, T as BeginResult, U as BillingPort, V as BreakGlassRequestInput, W as BreakGlassRequestRecord, X as BreakGlassStore, Y as CacheAdapter, Z as CacheCapabilities, _ as CacheInfo, $ as CacheSetOpts, a0 as CapabilitiesPort, a1 as CitationFilter, a2 as CitationMemoryKind, a3 as CitationPort, a4 as CitationSourceKind, a5 as CoOccurrencePatternRow, a6 as CognitivePrimitive, a7 as CompositionPort, a8 as CompositionRuleFilter, a9 as ConditionDsl, aa as ConditionDslSchema, ab as ConditionalPatternRow, ac as ConfidenceMapRow, ad as ConflictResolutionAction, ae as ConflictVerdictAction, af as ConsolidationMergeSnapshot, ag as ConsolidationPort, ah as ConsolidationWorthSnapshot, ai as ContradictingFact, aj as CreateCompositionRuleInput, ak as CreateDecisionInput, al as CreateEntityInput, am as CreateEpisodeInput, an as CreateEventInput, ao as CreateFactInput, ap as CreateHyperedgeInput, aq as CreateReasoningInput, ar as CreateRelationInput, as as CreateReminderInput, at as CreateSessionInput, au as CreateSkillInput, av as CreateStrategyInput, aw as CreateTaskInput, ax as CreateWebhookDeliveryInput, ay as CreateWebhookEndpointInput, az as CreateWorkflowInput, aA as DEFAULT_CONTRADICTION_MIN_SIMILARITY, aB as DecisionFilter, aC as DecisionPort, aD as DelegateTaskInput, aE as DeploymentTier, aF as DerivedInference, aG as DriftReviewPort, aH as EmbedAdapter, aI as EmbeddableTable, aJ as EmbeddingMaintenancePort, aK as EncryptedField, aL as EnqueueActiveLearningReviewInput, aM as EnqueueActiveLearningReviewResult, aN as EnqueueOpts, aO as EntityFilter, aP as EntityPort, aQ as EpisodeFilter, aR as EpisodePort, aS as EventAnnotation, aT as EventFilter, aU as EventPort, aV as FactFilter, aW as FactIndexPort, aX as FactPage, aY as FactPageFilter, aZ as FactPort, a_ as FactRedaction, a$ as FactRevisionConflictError, b0 as FactStats, b1 as FederatedRecallCandidate, b2 as FederatedRecallQuery, b3 as FindContradictingFactsInput, b4 as FindLiveFactByStatementInput, b5 as FtsCandidate, b6 as GENERIC_FACT_SUBJECT, b7 as GetHealthSnapshotInput, b8 as GraphNodeKind, b9 as GraphPort, ba as GraphSnapshotFilter, bb as HarnessBatchAckV1, bc as HarnessBatchV1, bd as HarnessEvent, be as HarnessEventAck, bf as HarnessIngestionPort, bg as HarnessPayloadLimitError, bh as HarnessProbeAckV1, bi as HarnessProbeV1, bj as HarnessSemanticErrorCode, bk as HitFreshness, bl as HotTierPort, bm as HotTierSnapshotRow, bn as HyperedgeFilter, bo as HyperedgePort, bp as IdempotencyStore, bq as InferenceLogFilter, br as InheritedContext, bs as InjectionGuardResult, bt as InjectionScore, bu as InsertQueryCacheInput, bv as JobHandler, bw as JudgmentStatus, bx as KeyDeprecation, by as KeyEscrowEntry, bz as KeyScope, bA as KeyUsageEvent, bB as KnowledgeGapRow, bC as LLMAdapter, bD as LLMInput, bE as LLMMessage, bF as LLMOutput, bG as LLMTask, bH as LifecyclePort, bI as LogContext, bJ as Logger, bK as LookupQueryCacheInput, bL as LshBandValue, bM as ManagedCandidateSupport, bN as ManagedCollapseCandidate, bO as ManagedCollapseCommitResult, bP as ManagedCollapsePlan, bQ as ManagedCollapsePlanBase, bR as ManagedCollapsePort, bS as ManagedEffectClaim, bT as ManagedPostCommitEffect, bU as ManagedPostCommitEffectKind, bV as ManagedPreparedCollapsePlan, bW as ManagedRejectedCandidate, bX as ManagedSessionLifecyclePort, bY as ManagedSessionProvenance, bZ as ManagedSessionWorkerPort, b_ as MarkerKind, b$ as MaterialiseInferenceInput, c0 as MergeDecisionByTopicKeyInput, c1 as MergeFactByTopicKeyInput, c2 as MetacognitionPort, c3 as MetacognitionTrends, c4 as MetricsPort, c5 as MnemoAgentProfile, c6 as MnemoCitation, c7 as MnemoCompositionRule, c8 as MnemoDecision, c9 as MnemoEntity, ca as MnemoEpisode, cb as MnemoEvent, cc as MnemoFact, cd as MnemoFactHash, ce as MnemoHyperedge, cf as MnemoInferenceLogEntry, cg as MnemoReasoning, ch as MnemoRelation, ci as MnemoReminder, cj as MnemoSkill, ck as MnemoStrategy, cl as MnemoTask, cm as MnemoWebhookDelivery, cn as MnemoWebhookEndpoint, co as MnemoWorkflow, cp as NeuroDynamicsPort, cq as OutboxAdapter, cr as OutboxEntry, cs as OutboxEventType, ct as OutboxPort, cu as OutboxStats, cv as PRIMITIVE_KINDS, cw as PRIMITIVE_SUBTYPES, cx as PeriodicPatternRow, cy as PluginStatePort, cz as PointerCandidate, cA as PointerCandidateQuery, cB as PrimitiveCandidate, cC as PrimitiveCandidateQuery, cD as Provenance, cE as PurgeFactsFilter, cF as PurgeFactsResult, cG as QueryCachePort, cH as QueueAdapter, cI as RECALL_PRECISION_METHODOLOGY_NOTE, cJ as RECOVERY_POINTS, cK as RELATION_NODE_KINDS, cL as RawCredentials, cM as ReasoningFilter, cN as ReasoningPort, cO as ReasoningStep, cP as RecallEffectsContext, cQ as RecallFilter, cR as RecallHit, cS as RecallHitObservation, cT as RecallHitStatus, cU as RecallLogEntry, cV as RecallLogRecord, cW as RecallMetrics, cX as RecallMetricsWindow, cY as RecallObservationContext, cZ as RecallObservationStatus, c_ as RecallPort, c$ as RecallPrecisionAtK, d0 as RecallPrecisionReport, d1 as RecallPrimitiveRecord, d2 as RecallPrimitiveRef, d3 as RecallPrimitiveValue, d4 as RecallQuery, d5 as RecallRequestObservation, d6 as RecallResponse, d7 as RecallStructures, d8 as RecallTraceStage, d9 as RecallTrafficOrigin, da as RecoveryPoint, db as RelationFilter, dc as RelationNodeKind, dd as RelationPort, de as RelationSummary, df as RelationVerb, dg as RememberConflict, dh as RememberConflictCandidate, di as RememberKind, dj as RememberRequest, dk as RememberResponse, dl as ReminderPort, dm as ReplaceFactInput, dn as ReplaceFactResult, dp as ReplayFailureReview, dq as ResolveActiveLearningReviewInput, dr as ResolveActiveLearningReviewResult, ds as ResolveConflictInput, dt as ResolveConflictResult, du as RetentionPort, dv as RotateKeyResult, dw as SENSITIVITY_ORDER, dx as SPEC_SCOPES, dy as SchemaLike, dz as SelfEditPolicy, dA as SensitiveTextPolicy, dB as SequentialPatternRow, dC as SessionPort, dD as SessionTokenRecord, dE as SessionTokenStore, dF as SimilarEntity, dG as SimilarEpisode, dH as SkillFilter, dI as SkillPort, dJ as Span, dK as SpanOpts, dL as SpecScope, dM as StorageAdapter, dN as StorageCapabilities, dO as StoredWriteFacts, dP as StrategyFilter, dQ as StrategyPort, dR as SupersedeDecisionInput, dS as SupersedeEntityInput, dT as TERMINAL_TASK_STATUSES, dU as TaskFilter, dV as TaskPort, dW as Telemetry, dX as TrendPair, dY as UpdateCompositionRuleInput, dZ as UpdateDecisionInput, d_ as UpdateEntityInput, d$ as UpdateEpisodeInput, e0 as UpdateFactInput, e1 as UpdateHyperedgeInput, e2 as UpdateReasoningInput, e3 as UpdateSkillInput, e4 as UpdateStrategyInput, e5 as UpdateTaskInput, e6 as UpdateWebhookEndpointInput, e7 as UpdateWorkflowInput, e8 as UpsertFactHashInput, e9 as UpsertFactLshInput, ea as VectorAdapter, eb as VectorFilter, ec as VectorSearchHit, ed as VectorSearchInput, ee as WORKSPACE_GOVERNED_SCOPES, ef as WORKSPACE_ROLE_ORDER, eg as WORKSPACE_ROLE_SCOPES, eh as WebhookFirePayload, ei as WebhookPort, ej as WorkflowFilter, ek as WorkflowPort, el as WorkflowStep, em as WorkspacePort, en as WorkspaceRole, eo as WorkspaceVitals, ep as computeHarnessPayloadHash, eq as isSensitiveTier, er as isSpecificFactSubject, es as managedCollapseOperationId, et as narrowScopesForWorkspaceRole, eu as parseActionDsl, ev as parseConditionDsl, ew as parseHarnessBatchV1, ex as parseHarnessProbeV1, ey as resolveAuditActorType, ez as roleAtLeast, eA as sensitiveTextMayReachEmbedder, eB as sensitiveTextMayReachLlm, eC as sensitivityAtLeast, eD as tiersAtOrBelow, eE as validateHarnessEventSemantics } from './ports-BTJeMaJJ.js';
|
|
3
|
+
export { A as ActorNamespace, a as ActorProvenance, b as ActorRef, c as ActorType, d as Attribution, D as DecayClass, H as HARNESS_CHUNK_VERSION, e as HARNESS_CLOSE_GRACE_MS, f as HARNESS_MAX_BATCH_BYTES, g as HARNESS_MAX_BATCH_EVENTS, h as HARNESS_MAX_CHUNKS_PER_MESSAGE, i as HARNESS_MAX_ENQUEUE_SEQUENCE, j as HARNESS_MAX_GENERATION, k as HARNESS_MAX_IDENTITY_BYTES, l as HARNESS_MAX_MESSAGE_BYTES, m as HARNESS_PROTOCOL_VERSION, n as HarnessTerminalMember, o as HarnessTurnAppendChunk, p as HealthStatus, M as ManagedArchiveReason, q as ManagedCloseKind, r as ManagedCollapseRetry, s as ManagedLifecycleQuiesceResult, t as ManagedSessionClaim, u as MnemoSession, P as PaginatedResult, R as RECOVERABLE_MANAGED_ARCHIVE_REASONS, S as Sensitivity, v as SessionStatus, w as SessionTurn, T as TRAFFIC_ORIGINS, x as TURN_ORIGINS, y as TrafficOrigin, z as TurnOrigin, V as VectorEmbedding, B as VectorQuery, C as VectorSearchResult, W as WorthDelta, E as canonicalJson, F as classifyTurnOrigin, G as computeTerminalDigestV1, I as formatActorRef, J as parseActorRef, K as sha256Hex } from './harness-runtime-C-bRQP8g.js';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
type WorkspaceId = string & {
|
|
7
|
+
readonly _brand: "WorkspaceId";
|
|
8
|
+
};
|
|
9
|
+
type FactId = string & {
|
|
10
|
+
readonly _brand: "FactId";
|
|
11
|
+
};
|
|
12
|
+
type DecisionId = string & {
|
|
13
|
+
readonly _brand: "DecisionId";
|
|
14
|
+
};
|
|
15
|
+
type EpisodeId = string & {
|
|
16
|
+
readonly _brand: "EpisodeId";
|
|
17
|
+
};
|
|
18
|
+
type EntityId = string & {
|
|
19
|
+
readonly _brand: "EntityId";
|
|
20
|
+
};
|
|
21
|
+
type StrategyId = string & {
|
|
22
|
+
readonly _brand: "StrategyId";
|
|
23
|
+
};
|
|
24
|
+
type WorkflowId = string & {
|
|
25
|
+
readonly _brand: "WorkflowId";
|
|
26
|
+
};
|
|
27
|
+
type SkillId = string & {
|
|
28
|
+
readonly _brand: "SkillId";
|
|
29
|
+
};
|
|
30
|
+
type TaskId = string & {
|
|
31
|
+
readonly _brand: "TaskId";
|
|
32
|
+
};
|
|
33
|
+
type EventId = string & {
|
|
34
|
+
readonly _brand: "EventId";
|
|
35
|
+
};
|
|
36
|
+
type ReasoningId = string & {
|
|
37
|
+
readonly _brand: "ReasoningId";
|
|
38
|
+
};
|
|
39
|
+
type SessionId = string & {
|
|
40
|
+
readonly _brand: "SessionId";
|
|
41
|
+
};
|
|
42
|
+
type RelationId = string & {
|
|
43
|
+
readonly _brand: "RelationId";
|
|
44
|
+
};
|
|
45
|
+
type HyperedgeId = string & {
|
|
46
|
+
readonly _brand: "HyperedgeId";
|
|
47
|
+
};
|
|
48
|
+
declare const asWorkspaceId: (s: string) => WorkspaceId;
|
|
49
|
+
declare const asFactId: (s: string) => FactId;
|
|
50
|
+
declare const asDecisionId: (s: string) => DecisionId;
|
|
51
|
+
declare const asEpisodeId: (s: string) => EpisodeId;
|
|
52
|
+
declare const asEntityId: (s: string) => EntityId;
|
|
53
|
+
declare const asStrategyId: (s: string) => StrategyId;
|
|
54
|
+
declare const asWorkflowId: (s: string) => WorkflowId;
|
|
55
|
+
declare const asSkillId: (s: string) => SkillId;
|
|
56
|
+
declare const asTaskId: (s: string) => TaskId;
|
|
57
|
+
declare const asEventId: (s: string) => EventId;
|
|
58
|
+
declare const asReasoningId: (s: string) => ReasoningId;
|
|
59
|
+
declare const asSessionId: (s: string) => SessionId;
|
|
60
|
+
declare const asRelationId: (s: string) => RelationId;
|
|
61
|
+
/** Returns true iff `s` is a well-formed UUID (any version, case-insensitive). */
|
|
62
|
+
declare function isWorkspaceId(s: string): boolean;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Typed event envelope for the Mnemosyne internal event bus (spec §4).
|
|
66
|
+
*
|
|
67
|
+
* The bus is a pure in-process pub/sub: no network, no persistence, no
|
|
68
|
+
* at-least-once guarantees. Its primary consumers are the WebSocket
|
|
69
|
+
* subscription handler (§4 /memory/ws) and monitoring.
|
|
70
|
+
*/
|
|
71
|
+
type MnemoEventType = "fact.created" | "fact.updated" | "fact.archived" | "task.created" | "task.transitioned" | "task.completed" | "event.recorded" | "recall.hit" | "session.collapsed" | "health.alert" | "federation.conflict" | "reminder.triggered";
|
|
72
|
+
interface MnemoBusEvent<P = unknown> {
|
|
73
|
+
id?: string;
|
|
74
|
+
channel: string;
|
|
75
|
+
type: MnemoEventType;
|
|
76
|
+
payload: P;
|
|
77
|
+
timestamp: string;
|
|
78
|
+
traceId: string;
|
|
79
|
+
}
|
|
80
|
+
type MnemoChannelPattern = "facts.*" | "facts.created" | "tasks.*" | "events.*" | `session.${string}` | `agent.${string}.recall` | "health" | "federation.sync";
|
|
81
|
+
interface MnemoEventFilter {
|
|
82
|
+
entityId?: string;
|
|
83
|
+
agentId?: string;
|
|
84
|
+
memoryType?: string;
|
|
85
|
+
}
|
|
86
|
+
interface WsSubscription {
|
|
87
|
+
subscribe?: {
|
|
88
|
+
channel: string;
|
|
89
|
+
filter?: MnemoEventFilter;
|
|
90
|
+
};
|
|
91
|
+
unsubscribe?: {
|
|
92
|
+
channel: string;
|
|
93
|
+
};
|
|
94
|
+
/** §35 reconnection: replay events since lastEventId on these channels */
|
|
95
|
+
resubscribe?: {
|
|
96
|
+
channels: string[];
|
|
97
|
+
lastEventId: string;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Observability types — Wave AC §AC2
|
|
103
|
+
*
|
|
104
|
+
* CognitiveHealthSnapshot gives a high-level view of a workspace's
|
|
105
|
+
* memory health across four key dimensions from spec §28–§34:
|
|
106
|
+
*
|
|
107
|
+
* worthConvergenceRate — fraction of facts whose worth has stabilised
|
|
108
|
+
* (α/(α+β) within ε of previous evaluation).
|
|
109
|
+
* compositionUtilization — ratio of active composition rules that fired
|
|
110
|
+
* at least once in the last 7 days.
|
|
111
|
+
* knowledgeTypeBalance — Shannon entropy over primitive type distribution
|
|
112
|
+
* (fact/decision/episode/entity/…), in bits.
|
|
113
|
+
* proceduralEvolutionDelta — mean score-delta of the last activated prompt
|
|
114
|
+
* version (avgScoreAfter − avgScoreBefore).
|
|
115
|
+
* unitEconomics.roiMultiplier — always null: no measured value of a recall
|
|
116
|
+
* exists (APP-015). Kept for wire compatibility.
|
|
117
|
+
* unitEconomics.costUsdThisMonth — total LLM cost for the billing period.
|
|
118
|
+
* unitEconomics.recallCount — number of recall operations this billing period.
|
|
119
|
+
*
|
|
120
|
+
* All numeric fields are in [0,∞) unless noted; null means the metric
|
|
121
|
+
* could not be computed (e.g. no facts in the workspace yet).
|
|
122
|
+
*/
|
|
123
|
+
interface CognitiveHealthUnitEconomics {
|
|
124
|
+
/** Always null: nothing measures a recall in dollars (APP-015). */
|
|
125
|
+
roiMultiplier: number | null;
|
|
126
|
+
/** Total LLM spend in USD for the current calendar month. */
|
|
127
|
+
costUsdThisMonth: number;
|
|
128
|
+
/** Number of recall operations executed this calendar month. */
|
|
129
|
+
recallCount: number;
|
|
130
|
+
}
|
|
131
|
+
interface CognitiveHealthSnapshot {
|
|
132
|
+
/** Workspace this snapshot is scoped to. */
|
|
133
|
+
workspaceId: string;
|
|
134
|
+
/** ISO-8601 timestamp when the snapshot was computed. */
|
|
135
|
+
computedAt: string;
|
|
136
|
+
/**
|
|
137
|
+
* Fraction [0,1] of active facts whose Beta-Bernoulli worth has
|
|
138
|
+
* stabilised (|α/(α+β) − previous| < 0.01). null if no facts.
|
|
139
|
+
*/
|
|
140
|
+
worthConvergenceRate: number | null;
|
|
141
|
+
/**
|
|
142
|
+
* Fraction [0,1] of active composition rules that fired at least
|
|
143
|
+
* once in the last 7 days. 0 if no rules exist.
|
|
144
|
+
*/
|
|
145
|
+
compositionUtilization: number | null;
|
|
146
|
+
/**
|
|
147
|
+
* Shannon entropy (bits) over the distribution of memory primitive
|
|
148
|
+
* types in the workspace. Higher = more diverse memory portfolio.
|
|
149
|
+
* null if workspace has no primitives.
|
|
150
|
+
*/
|
|
151
|
+
knowledgeTypeBalance: number | null;
|
|
152
|
+
/**
|
|
153
|
+
* Score delta (avgScoreAfter − avgScoreBefore) of the most recently
|
|
154
|
+
* activated prompt version for any agent in this workspace.
|
|
155
|
+
* Positive = procedural improvement. null if no prompt versions exist.
|
|
156
|
+
*/
|
|
157
|
+
proceduralEvolutionDelta: number | null;
|
|
158
|
+
/** Unit economics for the current billing period. */
|
|
159
|
+
unitEconomics: CognitiveHealthUnitEconomics;
|
|
160
|
+
/**
|
|
161
|
+
* Fraction of sessions that were collapsed due to turn-limit/inactivity
|
|
162
|
+
* (i.e. involuntary collapses / total sessions started).
|
|
163
|
+
* null if no sessions have been started in-process.
|
|
164
|
+
*/
|
|
165
|
+
sessionCollapseRate?: number | null;
|
|
166
|
+
/**
|
|
167
|
+
* Fraction of reasoning.resolve() calls served from the CoT distillation
|
|
168
|
+
* cache (cache_hit / (cache_hit + execute)).
|
|
169
|
+
* null if no reasoning.resolve calls recorded.
|
|
170
|
+
*/
|
|
171
|
+
reasoningCacheHitRate?: number | null;
|
|
172
|
+
/**
|
|
173
|
+
* Mean Beta-Bernoulli worth (α/(α+β)) across active facts in the workspace.
|
|
174
|
+
* null if the workspace has no active facts.
|
|
175
|
+
*/
|
|
176
|
+
avgMemoryWorth?: number | null;
|
|
177
|
+
/**
|
|
178
|
+
* Fraction of recall operations served from the hot (Redis L1) tier
|
|
179
|
+
* (hot / (hot + cold + unified + miss)).
|
|
180
|
+
* null if no recall tier hits recorded.
|
|
181
|
+
*/
|
|
182
|
+
hotTierHitRate?: number | null;
|
|
183
|
+
/**
|
|
184
|
+
* Per-workspace anticipation accuracy: fraction of pre-staged anticipated
|
|
185
|
+
* memories subsequently recalled in the same session.
|
|
186
|
+
* null if no session for this workspace has collapsed yet.
|
|
187
|
+
*/
|
|
188
|
+
anticipationAccuracy?: number | null;
|
|
189
|
+
/**
|
|
190
|
+
* Fraction of consolidation jobs that were gated (skipped) rather than
|
|
191
|
+
* merged (skipped / (merged + skipped + failed)).
|
|
192
|
+
* null if no consolidation decisions recorded.
|
|
193
|
+
*/
|
|
194
|
+
consolidationGateRate?: number | null;
|
|
195
|
+
/**
|
|
196
|
+
* Fraction of consolidation jobs that failed (failed / total).
|
|
197
|
+
* Note: `failed` is a superset of `rolled_back` until the scheduler emits
|
|
198
|
+
* a dedicated `rolled_back` outcome label.
|
|
199
|
+
* null if no consolidation decisions recorded.
|
|
200
|
+
* @remarks FIXME: failed is a superset of rolled_back
|
|
201
|
+
*/
|
|
202
|
+
consolidationRollbackRate?: number | null;
|
|
203
|
+
}
|
|
204
|
+
declare const MNEMO_ERROR_CODES: {
|
|
205
|
+
readonly STORAGE_NOT_FOUND: "mnemo.storage.not_found";
|
|
206
|
+
readonly STORAGE_CONFLICT: "mnemo.storage.conflict";
|
|
207
|
+
readonly STORAGE_CONSTRAINT: "mnemo.storage.constraint_violation";
|
|
208
|
+
readonly STORAGE_TIMEOUT: "mnemo.storage.timeout";
|
|
209
|
+
readonly AUTH_MISSING_KEY: "mnemo.auth.missing_key";
|
|
210
|
+
readonly AUTH_EXPIRED_KEY: "mnemo.auth.expired_key";
|
|
211
|
+
readonly AUTH_INSUFFICIENT_SCOPE: "mnemo.auth.insufficient_scope";
|
|
212
|
+
readonly AUTH_WORKSPACE_MISMATCH: "mnemo.auth.workspace_mismatch";
|
|
213
|
+
readonly RECALL_BUDGET_EXCEEDED: "mnemo.recall.budget_exceeded";
|
|
214
|
+
readonly RECALL_VECTOR_MISSING: "mnemo.recall.vector_missing";
|
|
215
|
+
readonly RECALL_UPSTREAM_TIMEOUT: "mnemo.recall.upstream_timeout";
|
|
216
|
+
readonly COMPOSE_DSL_INVALID: "mnemo.compose.dsl_invalid";
|
|
217
|
+
readonly COMPOSE_MAX_FIRINGS: "mnemo.compose.max_firings_reached";
|
|
218
|
+
readonly COMPOSE_MATERIALISE_FAIL: "mnemo.compose.materialise_failed";
|
|
219
|
+
readonly SELF_EDIT_BUDGET: "mnemo.self_edit.budget_exceeded";
|
|
220
|
+
readonly SELF_EDIT_COOLDOWN: "mnemo.self_edit.cooldown_active";
|
|
221
|
+
readonly SELF_EDIT_SCOPE: "mnemo.self_edit.scope_denied";
|
|
222
|
+
readonly SELF_EDIT_ABUSE_FLAG: "mnemo.self_edit.abuse_flagged";
|
|
223
|
+
readonly SELF_EDIT_WORTH_FROZEN: "mnemo.self_edit.worth_frozen";
|
|
224
|
+
readonly FED_SIGNATURE_INVALID: "mnemo.federation.signature_invalid";
|
|
225
|
+
readonly FED_VERSION_SKEW: "mnemo.federation.version_skew";
|
|
226
|
+
readonly FED_QUORUM_UNREACHABLE: "mnemo.federation.quorum_unreachable";
|
|
227
|
+
readonly PROC_BUDGET_BELOW_GATE: "mnemo.procedural.budget_below_gate";
|
|
228
|
+
readonly PROC_NO_TRAJECTORIES: "mnemo.procedural.no_trajectories";
|
|
229
|
+
readonly RATE_LIMIT: "mnemo.rate_limit";
|
|
230
|
+
readonly VALIDATION: "mnemo.validation";
|
|
231
|
+
readonly INTERNAL: "mnemo.internal";
|
|
232
|
+
};
|
|
233
|
+
type MnemoErrorCode = typeof MNEMO_ERROR_CODES[keyof typeof MNEMO_ERROR_CODES];
|
|
234
|
+
interface MnemoSpanAttributes {
|
|
235
|
+
/** Workspace the operation is scoped to. */
|
|
236
|
+
"mnemo.workspace_id"?: string;
|
|
237
|
+
/** Agent (actor) the operation was performed on behalf of. */
|
|
238
|
+
"mnemo.agent_id"?: string;
|
|
239
|
+
/** Session the operation belongs to, when one is active. */
|
|
240
|
+
"mnemo.session_id"?: string;
|
|
241
|
+
/** W3C trace id, propagated across service boundaries. */
|
|
242
|
+
"mnemo.trace_id"?: string;
|
|
243
|
+
/** Primitive kind being operated on (fact/episode/entity/…). */
|
|
244
|
+
"mnemo.kind"?: string;
|
|
245
|
+
/** Operation being performed. */
|
|
246
|
+
"mnemo.operation"?: string;
|
|
247
|
+
/** Surprise/PE score for remember() calls. */
|
|
248
|
+
"mnemo.pe"?: number;
|
|
249
|
+
/** Whether the result was served from hot-tier cache. */
|
|
250
|
+
"mnemo.from_hot_tier"?: boolean;
|
|
251
|
+
/** Which tier served the result: "hot" | "pointer" | "cold" | "l3_cache" | "none". */
|
|
252
|
+
"mnemo.tier_hit"?: string;
|
|
253
|
+
/** True when the result was served from a cache layer (L3 query cache). */
|
|
254
|
+
"mnemo.cache_hit"?: boolean;
|
|
255
|
+
/** Number of hits returned by recall. */
|
|
256
|
+
"mnemo.hit_count"?: number;
|
|
257
|
+
/** Number of results returned (spec alias of hit_count for recall). */
|
|
258
|
+
"mnemo.result_count"?: number;
|
|
259
|
+
/** Mean worth (α/(α+β) or score fallback) across returned hits. */
|
|
260
|
+
"mnemo.worth_avg"?: number;
|
|
261
|
+
/** LLM tokens saved by serving this operation without a model call. */
|
|
262
|
+
"mnemo.tokens_saved"?: number;
|
|
263
|
+
/** LLM tokens consumed by this operation. */
|
|
264
|
+
"mnemo.llm_tokens_used"?: number;
|
|
265
|
+
/** LLM cost in USD attributed to this operation. */
|
|
266
|
+
"mnemo.llm_cost_usd"?: number;
|
|
267
|
+
/** Latency in milliseconds. */
|
|
268
|
+
"mnemo.latency_ms"?: number;
|
|
269
|
+
/** Error code from MNEMO_ERROR_CODES. */
|
|
270
|
+
"mnemo.error_code"?: MnemoErrorCode;
|
|
271
|
+
/** Rule ID that triggered a composition inference. */
|
|
272
|
+
"mnemo.rule_id"?: string;
|
|
273
|
+
/** Number of composition rule firings in a call. */
|
|
274
|
+
"mnemo.firings"?: number;
|
|
275
|
+
/** Self-edit action applied. */
|
|
276
|
+
"mnemo.self_edit.action"?: string;
|
|
277
|
+
/** Idempotency key for mutating operations. */
|
|
278
|
+
"mnemo.idempotency_key"?: string;
|
|
279
|
+
/** Reason the session was collapsed (e.g. "turn_limit", "inactivity", "manual"). */
|
|
280
|
+
"mnemo.collapse.reason"?: string;
|
|
281
|
+
/** Number of turns processed in the collapsed session. */
|
|
282
|
+
"mnemo.collapse.turns"?: number;
|
|
283
|
+
/** Outcome of a reasoning resolve operation. */
|
|
284
|
+
"mnemo.reasoning.result"?: "cache_hit" | "execute";
|
|
285
|
+
/** Federation peer ID for sync operations. */
|
|
286
|
+
"mnemo.federation.peer"?: string;
|
|
287
|
+
/** Plugin name/ID for spans that trace a single named plugin's execution. */
|
|
288
|
+
"mnemo.plugin.name"?: string;
|
|
289
|
+
/** Event hook name for spans that dispatch a hook to all active plugins. */
|
|
290
|
+
"mnemo.plugin.hook"?: string;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Canonical span names emitted by Mnemosyne.
|
|
294
|
+
* Import and use these constants at span-creation sites so dashboards
|
|
295
|
+
* can correlate spans by name without string-matching fragility.
|
|
296
|
+
*
|
|
297
|
+
* `write` is the spec's name (Observability §, line 1718) for the persist
|
|
298
|
+
* span; it is an ALIAS of the live `mnemo.remember` span name (see WP13
|
|
299
|
+
* RECONCILE note). Use MNEMO_SPAN_NAMES.write when referring to the spec
|
|
300
|
+
* concept; the emitted span string remains "mnemo.remember".
|
|
301
|
+
*/
|
|
302
|
+
declare const MNEMO_SPAN_NAMES: {
|
|
303
|
+
readonly recall: "mnemo.recall";
|
|
304
|
+
readonly remember: "mnemo.remember";
|
|
305
|
+
/** Spec alias of `remember` (spec calls this span "mnemo.write"). */
|
|
306
|
+
readonly write: "mnemo.remember";
|
|
307
|
+
readonly sessionCollapse: "mnemo.session.collapse";
|
|
308
|
+
readonly reasoningResolve: "mnemo.reasoning.resolve";
|
|
309
|
+
readonly federationSync: "mnemo.federation.sync";
|
|
310
|
+
/** Auth middleware span — wraps the bearer-token resolution path. */
|
|
311
|
+
readonly auth: "mnemo.auth";
|
|
312
|
+
/** Embedding span — wraps embedSingle / embed batch calls. */
|
|
313
|
+
readonly embed: "mnemo.embed";
|
|
314
|
+
/** Re-ranking span — wraps RecMem rerank on the cold path. */
|
|
315
|
+
readonly rerank: "mnemo.rerank";
|
|
316
|
+
/** Composition span — wraps composeInferences on the cold path. */
|
|
317
|
+
readonly composition: "mnemo.composition";
|
|
318
|
+
/** Render span — wraps renderFactsCompact at the call site. */
|
|
319
|
+
readonly render: "mnemo.render";
|
|
320
|
+
readonly plugin: (name: string) => string;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
/** Magic header marking a residual (prefix/suffix-anchored) payload. */
|
|
324
|
+
declare const DELTA_MAGIC_V1 = "MNEMO_DELTA_V1";
|
|
325
|
+
/** Magic header marking a full-text payload (used when a residual would not be smaller). */
|
|
326
|
+
declare const FULL_MAGIC_V1 = "MNEMO_FULL_V1";
|
|
327
|
+
/**
|
|
328
|
+
* Encode `child` as a residual against `parent`.
|
|
329
|
+
*
|
|
330
|
+
* Format (residual, all parts newline-joined into ONE string):
|
|
331
|
+
* line 0: `MNEMO_DELTA_V1\t<prefixCount>\t<suffixCount>`
|
|
332
|
+
* line 1..N: the differing MIDDLE lines of `child`
|
|
333
|
+
*
|
|
334
|
+
* If the residual would not be strictly smaller than a full payload, returns a
|
|
335
|
+
* full payload instead:
|
|
336
|
+
* line 0: `MNEMO_FULL_V1`
|
|
337
|
+
* line 1..N: the full `child` text
|
|
338
|
+
*
|
|
339
|
+
* `applyDelta` inverts whichever form is produced.
|
|
340
|
+
*/
|
|
341
|
+
declare function encodeDelta(parent: string, child: string): string;
|
|
342
|
+
/**
|
|
343
|
+
* Reconstruct the child narrative from `parent` and an encoded `delta`.
|
|
344
|
+
*
|
|
345
|
+
* Back-compat: a `delta` that begins with neither magic header is treated as a
|
|
346
|
+
* literal full narrative (legacy rows / raw fixtures written before WP5).
|
|
347
|
+
*/
|
|
348
|
+
declare function applyDelta(parent: string, delta: string): string;
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Canonical EmbeddingSpace identity (§B4.1).
|
|
352
|
+
*
|
|
353
|
+
* Vectors can only be compared when they share the exact same EmbeddingSpace.
|
|
354
|
+
*/
|
|
355
|
+
interface EmbeddingSpace {
|
|
356
|
+
spaceId: string;
|
|
357
|
+
provider: string;
|
|
358
|
+
model: string;
|
|
359
|
+
modelRevision?: string;
|
|
360
|
+
dimensions: number;
|
|
361
|
+
distanceMetric: "cosine" | "ip" | "l2";
|
|
362
|
+
inputType?: "document" | "query" | "symmetric";
|
|
363
|
+
normalization?: "l2" | "none";
|
|
364
|
+
dtype?: "float32" | "float16" | "int8";
|
|
365
|
+
preprocessingVersion?: string;
|
|
366
|
+
}
|
|
367
|
+
type EmbeddingSpaceStatus = "building" | "active" | "dormant" | "stale" | "superseded" | "failed";
|
|
368
|
+
/**
|
|
369
|
+
* Generate a deterministic canonical spaceId string.
|
|
370
|
+
*/
|
|
371
|
+
declare function generateSpaceId(space: Omit<EmbeddingSpace, "spaceId">): string;
|
|
372
|
+
|
|
373
|
+
interface AssembleGraphSnapshotOptions {
|
|
374
|
+
/** Restrict the returned snapshot to this node + its 1-hop neighbourhood. */
|
|
375
|
+
focusEntityId?: string;
|
|
376
|
+
}
|
|
377
|
+
declare function assembleGraphSnapshot(allNodes: GraphNode[], edges: GraphEdge[], opts?: AssembleGraphSnapshotOptions): GraphSnapshot;
|
|
378
|
+
|
|
379
|
+
/** `days` UTC day keys (`YYYY-MM-DD`) ending today, oldest first. */
|
|
380
|
+
declare function utcDayKeys(days: number, now?: number): string[];
|
|
381
|
+
/**
|
|
382
|
+
* Shared by the Postgres repository and the in-memory twin, so the two never drift:
|
|
383
|
+
* session rows grouped by (start day, status), and the window's episodes with their
|
|
384
|
+
* readable linked-fact count, become {@link SessionStats}.
|
|
385
|
+
*/
|
|
386
|
+
declare function tallySessionStats(days: number, sessions: Array<{
|
|
387
|
+
day: string;
|
|
388
|
+
status: string;
|
|
389
|
+
n: number;
|
|
390
|
+
collapsed: number;
|
|
391
|
+
turns: number;
|
|
392
|
+
}>, episodes: Array<{
|
|
393
|
+
topics: string[];
|
|
394
|
+
facts: number;
|
|
395
|
+
}>): SessionStats;
|
|
396
|
+
/** Shared by the Postgres repository and the twin: (day, action) groups → {@link AuditActivity}. */
|
|
397
|
+
declare function tallyAuditActivity(days: number, groups: Array<{
|
|
398
|
+
day: string;
|
|
399
|
+
action: string;
|
|
400
|
+
n: number;
|
|
401
|
+
}>, lastAt: Record<string, string>): AuditActivity;
|
|
402
|
+
/** Shared by the repository and the twin: each day's latest snapshot → {@link HealthSnapshotDay}. */
|
|
403
|
+
declare function tallyHealthSnapshots(days: number, latestByDay: Map<string, Pick<HealthSnapshot, "factCountActive" | "factCountEmbedded" | "factCountUnembedded" | "factsWithZeroHits" | "recallHitRate30d" | "extractionJobsFailed7d">>): HealthSnapshotDay[];
|
|
404
|
+
/** Shared by the repository and the twin: (day, actor kind) groups → {@link AuditFeedStats}. */
|
|
405
|
+
declare function tallyAuditFeedStats(days: number, groups: Array<{
|
|
406
|
+
day: string;
|
|
407
|
+
actorKind: "user" | "system";
|
|
408
|
+
n: number;
|
|
409
|
+
}>): AuditFeedStats;
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Primitive kinds whose write path is guaranteed to produce a `vector_upsert`
|
|
413
|
+
* outbox entry in the same transaction that persists the row (spec.md
|
|
414
|
+
* Requirement 1). A kind NOT in this set is persisted but never indexed —
|
|
415
|
+
* "write-only memory", the exact defect this change fixes for `decision`.
|
|
416
|
+
*/
|
|
417
|
+
declare const RECALLABLE_KINDS: readonly ["fact", "decision", "strategy", "workflow", "skill", "episode", "task", "event", "reasoning"];
|
|
418
|
+
type RecallableKind = (typeof RECALLABLE_KINDS)[number];
|
|
419
|
+
/**
|
|
420
|
+
* Kinds `recallCold` searches when a caller supplies no `RecallQuery.kinds`
|
|
421
|
+
* filter (spec.md Requirement 4 / design.md D4 — conservatism lives in the
|
|
422
|
+
* damping/gating parameters, not in an opt-out here). Defined as its own
|
|
423
|
+
* export, distinct from RECALLABLE_KINDS, because the two lists are allowed
|
|
424
|
+
* to diverge later: a kind can become recallable (indexed on write) before
|
|
425
|
+
* it ships default-on in recall results.
|
|
426
|
+
*/
|
|
427
|
+
declare const DEFAULT_RECALL_KINDS: readonly RecallableKind[];
|
|
428
|
+
/**
|
|
429
|
+
* The three kinds that are INDEXED but not returned by default. Kept as its own
|
|
430
|
+
* export so the split is stated once and readable, rather than inferred by
|
|
431
|
+
* diffing two lists.
|
|
432
|
+
*
|
|
433
|
+
* `task` and `event` are operational records, not knowledge: a cancelled ticket
|
|
434
|
+
* or a webhook delivery surfacing on an unrelated question is noise, and noise
|
|
435
|
+
* in a recall budget costs a real answer its slot. `reasoning` is a stored
|
|
436
|
+
* chain-of-thought — valuable when you ask for it ("how did we conclude X?"),
|
|
437
|
+
* and misleading when it arrives unbidden, because a discarded line of
|
|
438
|
+
* reasoning reads exactly like a conclusion.
|
|
439
|
+
*
|
|
440
|
+
* All three ARE reachable: `RecallQuery.kinds` overrides this entirely, so an
|
|
441
|
+
* agent that wants them asks for them.
|
|
442
|
+
*/
|
|
443
|
+
declare const NON_DEFAULT_RECALLABLE_KINDS: readonly RecallableKind[];
|
|
444
|
+
/**
|
|
445
|
+
* P65 wave 1 — why `strategy` and `workflow` went first, and why they are
|
|
446
|
+
* default-on rather than merely indexed.
|
|
447
|
+
*
|
|
448
|
+
* They are reusable heuristics and processes: "when X, do Y" and "here is how
|
|
449
|
+
* we do Z". That is precisely the content an agent benefits from finding
|
|
450
|
+
* WITHOUT having been told to look, which is what default-on means. A `task` or
|
|
451
|
+
* an `event` surfacing on every unrelated recall is noise — those are next, and
|
|
452
|
+
* the plan is to index them without defaulting them, which is the distinction
|
|
453
|
+
* `RECALLABLE_KINDS` vs `DEFAULT_RECALL_KINDS` exists to express and which was
|
|
454
|
+
* unused until now (the two lists were identical).
|
|
455
|
+
*
|
|
456
|
+
* What the backlog under-estimated: adding a kind is NOT only a registry entry.
|
|
457
|
+
* Of the seven write-only kinds, only `episode`, `skill`, `strategy` and
|
|
458
|
+
* `reasoning` had an `embedding` column at all, and NONE had `text_lemmatized`.
|
|
459
|
+
* `workflow`, `task` and `event` had neither. Migration 0033 gave these two what
|
|
460
|
+
* recall needs; the remaining five each still need theirs.
|
|
461
|
+
*/
|
|
462
|
+
/** Narrows `kind` to `RecallableKind` when it is one of RECALLABLE_KINDS. */
|
|
463
|
+
declare function isRecallableKind(kind: PrimitiveKind): kind is RecallableKind;
|
|
464
|
+
/**
|
|
465
|
+
* Declares exactly which fields of a primitive's row are embedded/indexed
|
|
466
|
+
* for a given recallable kind, and how they are joined into one text blob.
|
|
467
|
+
* `separator` is inserted only between fields that are actually present
|
|
468
|
+
* (non-empty strings) — a missing/empty field is skipped, never emitted as
|
|
469
|
+
* the literal string `"undefined"`.
|
|
470
|
+
*/
|
|
471
|
+
interface TextProjection {
|
|
472
|
+
readonly fields: readonly string[];
|
|
473
|
+
readonly separator: string;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Per-kind text projection — the single source of truth for "what exactly
|
|
477
|
+
* gets embedded" for each recallable kind. Replaces the three previously
|
|
478
|
+
* hardcoded `title + " " + body` sites for decisions
|
|
479
|
+
* (`DecisionRepository.ts:57`, `:121`, `EmbeddingRepository.ts:16`); all
|
|
480
|
+
* three now derive from this constant instead of duplicating the join.
|
|
481
|
+
*/
|
|
482
|
+
declare const PRIMITIVE_TEXT_PROJECTION: Record<RecallableKind, TextProjection>;
|
|
483
|
+
/**
|
|
484
|
+
* The vector widths this schema physically supports — the single source of
|
|
485
|
+
* truth, replacing "whatever positive integer someone typed".
|
|
486
|
+
*
|
|
487
|
+
* These four are not a preference, they are what the database has tables for:
|
|
488
|
+
* `mnemo_fact_embeddings_1024 / _1536 / _2048 / _4096`
|
|
489
|
+
* (`adapter-postgres/src/schema/vector_space.ts`), plus the dimension-scoped
|
|
490
|
+
* HNSW indexes migration 0010 builds over them.
|
|
491
|
+
*
|
|
492
|
+
* P117 is why this constant exists. `MNEMO_EMBED_DIMENSIONS` accepted any
|
|
493
|
+
* positive integer, and `mnemo_fact.embedding` is an unconstrained `halfvec`,
|
|
494
|
+
* so a workspace configured at 768 wrote facts perfectly well — and could never
|
|
495
|
+
* delete them, because `archiveFact()` copies the row into a table that WAS
|
|
496
|
+
* pinned at 1536. Data you can create and cannot forget. The archive column is
|
|
497
|
+
* unconstrained now (migration 0032), but the wider point stands: a width with
|
|
498
|
+
* no index behind it is a silent performance cliff, and the place to refuse it
|
|
499
|
+
* is the moment it is configured or written — not three operations later, in an
|
|
500
|
+
* error message at the end of an 8 KB SQL dump.
|
|
501
|
+
*
|
|
502
|
+
* Adding a width means adding its table and index first. This list follows the
|
|
503
|
+
* schema; it never leads it.
|
|
504
|
+
*/
|
|
505
|
+
declare const SUPPORTED_EMBED_DIMENSIONS: readonly [1024, 1536, 2048, 4096];
|
|
506
|
+
type SupportedEmbedDimension = (typeof SUPPORTED_EMBED_DIMENSIONS)[number];
|
|
507
|
+
/** Narrows `n` to a width the schema has a table and an index for. */
|
|
508
|
+
declare function isSupportedEmbedDimension(n: number): n is SupportedEmbedDimension;
|
|
509
|
+
/**
|
|
510
|
+
* Throws unless `n` is a supported width. `context` names the caller so the
|
|
511
|
+
* message says which knob to turn — the failure this replaces surfaced as
|
|
512
|
+
* `expected 1536 dimensions, not 768` from deep inside a Drizzle insert, which
|
|
513
|
+
* named neither the setting nor the fact.
|
|
514
|
+
*/
|
|
515
|
+
declare function assertSupportedEmbedDimension(n: number, context: string): void;
|
|
516
|
+
/**
|
|
517
|
+
* Joins a recallable kind's declared fields out of `row` into the one text blob
|
|
518
|
+
* that gets embedded and lexically indexed. Pure.
|
|
519
|
+
*
|
|
520
|
+
* A missing or non-string field is skipped rather than emitted as the literal
|
|
521
|
+
* `"undefined"` — which matters for optional projected fields like
|
|
522
|
+
* `workflow.description`: a name-only workflow must index as its name, not as
|
|
523
|
+
* `"deploy undefined"`.
|
|
524
|
+
*
|
|
525
|
+
* P65 moved this here from `@mnemo-ai/core`. It is a pure function over
|
|
526
|
+
* PRIMITIVE_TEXT_PROJECTION, and the in-memory adapter in `types/testing` needs
|
|
527
|
+
* it to satisfy the same write contract the real adapters do — types cannot
|
|
528
|
+
* import from core, so a helper living in core made the double structurally
|
|
529
|
+
* unable to mirror the thing it doubles. Core re-exports it, so every existing
|
|
530
|
+
* import keeps working.
|
|
531
|
+
*/
|
|
532
|
+
declare function projectPrimitiveText(kind: RecallableKind, row: Record<string, unknown>): string;
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Typed storage failures that a caller is expected to turn into a 4xx instead
|
|
536
|
+
* of a 500. Adapters throw these for conditions the CLIENT caused (a name that
|
|
537
|
+
* is already taken, a lineage target that does not exist), so the HTTP layer
|
|
538
|
+
* never has to parse driver error text.
|
|
539
|
+
*/
|
|
540
|
+
/** A referenced row does not exist in this workspace (or is not visible to the caller). */
|
|
541
|
+
declare class StorageNotFoundError extends Error {
|
|
542
|
+
readonly code: "not_found";
|
|
543
|
+
constructor(message: string);
|
|
544
|
+
}
|
|
545
|
+
/** The write conflicts with the current state: a live row already owns the key, or the row was already closed. */
|
|
546
|
+
declare class StorageConflictError extends Error {
|
|
547
|
+
readonly code: "conflict";
|
|
548
|
+
constructor(message: string);
|
|
549
|
+
}
|
|
550
|
+
/** The input is structurally invalid for the graph (self-loop, repeated member, wrong kind). */
|
|
551
|
+
declare class StorageValidationError extends Error {
|
|
552
|
+
readonly code: "invalid";
|
|
553
|
+
constructor(message: string);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* P135: the scope_ref values a read filter accepts — `scopeRef` plus the other
|
|
558
|
+
* spellings of the same project (`scopeRefAliases`), deduplicated. `undefined`
|
|
559
|
+
* when the filter names no scopeRef, so callers keep their "no condition" path.
|
|
560
|
+
*/
|
|
561
|
+
declare function scopeRefValues(filter: {
|
|
562
|
+
scopeRef?: string | undefined;
|
|
563
|
+
scopeRefAliases?: string[] | undefined;
|
|
564
|
+
}): string[] | undefined;
|
|
565
|
+
/** True when `value` is one of the scope_ref values the filter accepts (or the filter names none). */
|
|
566
|
+
declare function scopeRefMatches(value: string | null | undefined, filter: {
|
|
567
|
+
scopeRef?: string | undefined;
|
|
568
|
+
scopeRefAliases?: string[] | undefined;
|
|
569
|
+
}): boolean;
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* ISO 8601 date-time for request inputs. Seconds and fractions are optional
|
|
573
|
+
* (`2026-08-01T09:00Z`, `…T09:00:00Z`, `…T09:00:00.000Z`): the set
|
|
574
|
+
* `z.string().datetime()` accepted before zod 4.5 made seconds mandatory.
|
|
575
|
+
* Same issue (`invalid_format`, format `datetime`), same JSON Schema
|
|
576
|
+
* (`format: date-time`). Responses keep zod's strict `datetime()`.
|
|
577
|
+
*/
|
|
578
|
+
declare function isoDateTimeInput(opts?: {
|
|
579
|
+
offset?: boolean;
|
|
580
|
+
}): z.ZodCustomStringFormat<"datetime">;
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* The content fingerprint behind `mnemo_fact_hash`.
|
|
584
|
+
*
|
|
585
|
+
* P126 — this lived inline in five places: three in `cognitive/remember.ts`
|
|
586
|
+
* (the dedupe lookup and two upserts), one in `FactRepository`'s supersede
|
|
587
|
+
* path, and a sixth was about to be added by the fix for the in-place-edit
|
|
588
|
+
* case. Five copies of a hash formula is not a style problem: the fingerprint
|
|
589
|
+
* only works if the writer and the reader agree BYTE FOR BYTE, and a drifted
|
|
590
|
+
* copy does not error — it silently stops matching, and the dedupe it backs
|
|
591
|
+
* quietly turns into a duplicate factory.
|
|
592
|
+
*
|
|
593
|
+
* The normalisation is deliberately shallow: trim and lowercase only. It is not
|
|
594
|
+
* trying to decide that two differently-worded statements mean the same thing —
|
|
595
|
+
* that is `remember()`'s surprise gate and the conflict machinery, both of
|
|
596
|
+
* which reason about embeddings. This answers the narrower question "is this
|
|
597
|
+
* the SAME TEXT, said again".
|
|
598
|
+
*
|
|
599
|
+
* `subject` participates because the same sentence under a different subject is
|
|
600
|
+
* a different assertion, and the trailing `fact` keeps the space from colliding
|
|
601
|
+
* with a future primitive's fingerprints.
|
|
602
|
+
*/
|
|
603
|
+
declare function factStatementHash(statement: string, subject: string): string;
|
|
604
|
+
|
|
605
|
+
declare const LSH_DIMS = 64;
|
|
606
|
+
declare const LSH_BANDS = 6;
|
|
607
|
+
declare const LSH_PLANES_PER_BAND = 8;
|
|
608
|
+
interface LshBand {
|
|
609
|
+
bandIdx: number;
|
|
610
|
+
bandHash: bigint;
|
|
611
|
+
}
|
|
612
|
+
declare function lshBands(embedding: Float32Array | number[], spaceId?: string): LshBand[];
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* PG-TIMEOUTS: server-side time limits for every runtime Postgres pool.
|
|
616
|
+
*
|
|
617
|
+
* Without them a stuck connection stays stuck: on the chaos stack an
|
|
618
|
+
* `idle in transaction` audit append held an advisory lock forever while nine
|
|
619
|
+
* other connections waited on it (`SHOW statement_timeout` etc. all `0`), and
|
|
620
|
+
* the instance never recovered (CHAOS-1). These limits are sent as startup
|
|
621
|
+
* parameters on each connection, so they need no migration and no role change.
|
|
622
|
+
*
|
|
623
|
+
* - `statement_timeout` cancels one statement that runs too long.
|
|
624
|
+
* - `lock_timeout` cancels a statement waiting too long for a lock (advisory
|
|
625
|
+
* locks included). It must be shorter than `statement_timeout`, or it never
|
|
626
|
+
* fires first.
|
|
627
|
+
* - `idle_in_transaction_session_timeout` ends a session that holds a
|
|
628
|
+
* transaction open while the application does nothing on it.
|
|
629
|
+
*
|
|
630
|
+
* Migrations open their own connections and never get these limits; long
|
|
631
|
+
* maintenance statements raise them per transaction (see
|
|
632
|
+
* {@link resolvePgMaintenanceTimeoutMs}).
|
|
633
|
+
*
|
|
634
|
+
* Pure: takes the environment as an argument (no `process` access here).
|
|
635
|
+
*/
|
|
636
|
+
/** Each limit in ms. 0 means "not set here": the role or server default applies. */
|
|
637
|
+
interface PgSessionTimeouts {
|
|
638
|
+
/** `statement_timeout`, in ms. */
|
|
639
|
+
statementTimeoutMs: number;
|
|
640
|
+
/** `lock_timeout`, in ms. */
|
|
641
|
+
lockTimeoutMs: number;
|
|
642
|
+
/** `idle_in_transaction_session_timeout`, in ms. */
|
|
643
|
+
idleInTransactionTimeoutMs: number;
|
|
644
|
+
}
|
|
645
|
+
declare const DEFAULT_PG_SESSION_TIMEOUTS: Readonly<PgSessionTimeouts>;
|
|
646
|
+
/** Env var → field. Values are milliseconds; `0` leaves that limit to the role/server. */
|
|
647
|
+
declare const PG_SESSION_TIMEOUT_ENV: Readonly<{
|
|
648
|
+
readonly statementTimeoutMs: "MNEMO_PG_STATEMENT_TIMEOUT_MS";
|
|
649
|
+
readonly lockTimeoutMs: "MNEMO_PG_LOCK_TIMEOUT_MS";
|
|
650
|
+
readonly idleInTransactionTimeoutMs: "MNEMO_PG_IDLE_IN_TRANSACTION_TIMEOUT_MS";
|
|
651
|
+
}>;
|
|
652
|
+
/** Statement budget for long maintenance work (matview refreshes). 0 = no limit. */
|
|
653
|
+
declare const PG_MAINTENANCE_TIMEOUT_ENV = "MNEMO_PG_MAINTENANCE_STATEMENT_TIMEOUT_MS";
|
|
654
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
655
|
+
/**
|
|
656
|
+
* Resolve the runtime pool limits from the environment. Throws on a value
|
|
657
|
+
* that is not a non-negative integer, and when `lock_timeout` is not shorter
|
|
658
|
+
* than `statement_timeout` (both set): a misconfiguration should stop the
|
|
659
|
+
* boot, not surface as the next outage.
|
|
660
|
+
*/
|
|
661
|
+
declare function resolvePgSessionTimeouts(env: Env): PgSessionTimeouts;
|
|
662
|
+
/**
|
|
663
|
+
* The startup parameters for a postgres.js `connection` option. Postgres
|
|
664
|
+
* applies them to the session as if set with `SET`; a transaction can still
|
|
665
|
+
* override them with `SET LOCAL`. A limit of 0 is left out, so a role-level
|
|
666
|
+
* setting (`ALTER ROLE … SET`) still applies and a pooler that rejects unknown
|
|
667
|
+
* startup parameters can be served by setting all three to 0.
|
|
668
|
+
*/
|
|
669
|
+
declare function pgSessionTimeoutParams(t: PgSessionTimeouts): Record<string, string>;
|
|
670
|
+
/** Statement and lock budget for long maintenance statements, in ms (0 = no limit). */
|
|
671
|
+
declare function resolvePgMaintenanceTimeoutMs(env: Env): number;
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* CHAOS-10: tell a database that is unavailable or too slow right now from a
|
|
675
|
+
* request that can never succeed.
|
|
676
|
+
*
|
|
677
|
+
* With Postgres stopped, writes answered 500 `internal_error`, which tells a
|
|
678
|
+
* client nothing about retrying. An error this function accepts means "the
|
|
679
|
+
* dependency failed, retry later" (503 + Retry-After in the server's error
|
|
680
|
+
* handler); anything else — constraint, privilege, syntax — is not fixed by
|
|
681
|
+
* retrying. A timeout after the statement was sent does NOT prove that nothing
|
|
682
|
+
* was written; callers that retry writes still need idempotency.
|
|
683
|
+
*
|
|
684
|
+
* Pure: reads only `err.code` (postgres.js / Node socket codes and SQLSTATEs),
|
|
685
|
+
* so it lives here, next to the PG-TIMEOUTS limits whose errors it classifies.
|
|
686
|
+
*/
|
|
687
|
+
/**
|
|
688
|
+
* opossum's own timeout: code `ETIMEDOUT` (the same string as a socket timeout)
|
|
689
|
+
* and the message "Timed out after Nms". It says a breaker-wrapped call ran
|
|
690
|
+
* long, whatever that call was (a recall that includes an LLM rerank, an
|
|
691
|
+
* embed), so it is not evidence about the database.
|
|
692
|
+
*/
|
|
693
|
+
declare function isBreakerTimeoutError(err: unknown): boolean;
|
|
694
|
+
/** True when `err` (or an error in its `cause` chain) is a transient database failure. */
|
|
695
|
+
declare function isTransientDbError(err: unknown): boolean;
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Tiny, dependency-free i18n core shared by the CLI, the MCP server and the
|
|
699
|
+
* server's error messages. Dictionaries live in each package; this file only
|
|
700
|
+
* resolves a locale, renders a key, and matches English templates.
|
|
701
|
+
*/
|
|
702
|
+
type Locale = "en-US" | "es-419";
|
|
703
|
+
declare const LOCALES: readonly Locale[];
|
|
704
|
+
declare const DEFAULT_LOCALE: Locale;
|
|
705
|
+
/**
|
|
706
|
+
* BCP 47 (`es`, `es-AR`) and POSIX (`es_MX.UTF-8`, `es_AR@euro`) tags to a
|
|
707
|
+
* Locale. `C`, `POSIX`, empty and unknown languages give undefined.
|
|
708
|
+
*/
|
|
709
|
+
declare function normalizeLocale(tag?: string): Locale | undefined;
|
|
710
|
+
/** First candidate that normalizes wins, then q-sorted Accept-Language, then en-US. */
|
|
711
|
+
declare function resolveLocale(candidates: Array<string | undefined>, acceptLanguage?: string): Locale;
|
|
712
|
+
type Plural = {
|
|
713
|
+
one: string;
|
|
714
|
+
other: string;
|
|
715
|
+
};
|
|
716
|
+
/** A dictionary: nested objects whose leaves are strings or `{ one, other }` plurals. */
|
|
717
|
+
type Dict<T = string> = {
|
|
718
|
+
readonly [key: string]: T | Plural | Dict<T>;
|
|
719
|
+
};
|
|
720
|
+
type Vars = Record<string, string | number>;
|
|
721
|
+
/**
|
|
722
|
+
* Renders `key` (dotted) from `dict`. `{name}` is replaced from `vars`; an
|
|
723
|
+
* unknown `{name}` stays visible. A `{ one, other }` leaf picks its branch from
|
|
724
|
+
* `vars.count` with Intl.PluralRules. A missing key returns the key.
|
|
725
|
+
*/
|
|
726
|
+
declare function translate(dict: Dict, key: string, vars?: Vars, locale?: Locale): string;
|
|
727
|
+
interface CompiledTemplate {
|
|
728
|
+
key: string;
|
|
729
|
+
/** Literal pieces around the placeholders: `literals.length === names.length + 1`. */
|
|
730
|
+
literals: string[];
|
|
731
|
+
names: string[];
|
|
732
|
+
/** Literal characters (placeholders excluded): more means more specific. */
|
|
733
|
+
weight: number;
|
|
734
|
+
}
|
|
735
|
+
/** Messages longer than this are never matched (they stay untranslated). */
|
|
736
|
+
declare const MAX_MATCH_LENGTH = 2048;
|
|
737
|
+
/**
|
|
738
|
+
* Compiles English `{name}` templates (key -> template), most specific (most
|
|
739
|
+
* literal characters, then fewest placeholders) first. Throws on a duplicate
|
|
740
|
+
* placeholder name or two adjacent placeholders (unmatchable without a separator).
|
|
741
|
+
*/
|
|
742
|
+
declare function compileTemplates(table: Record<string, string>): CompiledTemplate[];
|
|
743
|
+
/**
|
|
744
|
+
* The key and captured values of the first template matching `message`, else
|
|
745
|
+
* undefined. Linear time, no RegExp: the message must start and end with the
|
|
746
|
+
* template's outer literals and contain the middle ones in order. Each middle
|
|
747
|
+
* literal is taken at its FIRST occurrence after the previous one, so it can
|
|
748
|
+
* differ from a backtracking regex only when a separator also occurs inside a
|
|
749
|
+
* captured value. Captures are non-empty.
|
|
750
|
+
*/
|
|
751
|
+
declare function matchTemplate(compiled: readonly CompiledTemplate[], message: string): {
|
|
752
|
+
key: string;
|
|
753
|
+
vars: Record<string, string>;
|
|
754
|
+
} | undefined;
|
|
755
|
+
|
|
756
|
+
export { AuditActivity, AuditFeedStats, DEFAULT_LOCALE, DEFAULT_PG_SESSION_TIMEOUTS, DEFAULT_RECALL_KINDS, DELTA_MAGIC_V1, FULL_MAGIC_V1, GraphEdge, GraphNode, GraphSnapshot, HealthSnapshot, HealthSnapshotDay, LOCALES, LSH_BANDS, LSH_DIMS, LSH_PLANES_PER_BAND, MAX_MATCH_LENGTH, MNEMO_ERROR_CODES, MNEMO_SPAN_NAMES, NON_DEFAULT_RECALLABLE_KINDS, PG_MAINTENANCE_TIMEOUT_ENV, PG_SESSION_TIMEOUT_ENV, PRIMITIVE_TEXT_PROJECTION, PrimitiveKind, RECALLABLE_KINDS, SUPPORTED_EMBED_DIMENSIONS, SessionStats, StorageConflictError, StorageNotFoundError, StorageValidationError, applyDelta, asDecisionId, asEntityId, asEpisodeId, asEventId, asFactId, asReasoningId, asRelationId, asSessionId, asSkillId, asStrategyId, asTaskId, asWorkflowId, asWorkspaceId, assembleGraphSnapshot, assertSupportedEmbedDimension, compileTemplates, encodeDelta, factStatementHash, generateSpaceId, isBreakerTimeoutError, isRecallableKind, isSupportedEmbedDimension, isTransientDbError, isWorkspaceId, isoDateTimeInput, lshBands, matchTemplate, normalizeLocale, pgSessionTimeoutParams, projectPrimitiveText, resolveLocale, resolvePgMaintenanceTimeoutMs, resolvePgSessionTimeouts, scopeRefMatches, scopeRefValues, tallyAuditActivity, tallyAuditFeedStats, tallyHealthSnapshots, tallySessionStats, translate, utcDayKeys };
|
|
757
|
+
export type { AssembleGraphSnapshotOptions, CognitiveHealthSnapshot, CognitiveHealthUnitEconomics, CompiledTemplate, DecisionId, Dict, EmbeddingSpace, EmbeddingSpaceStatus, EntityId, EpisodeId, EventId, FactId, HyperedgeId, Locale, LshBand, MnemoBusEvent, MnemoChannelPattern, MnemoErrorCode, MnemoEventFilter, MnemoEventType, MnemoSpanAttributes, PgSessionTimeouts, Plural, ReasoningId, RecallableKind, RelationId, SessionId, SkillId, StrategyId, SupportedEmbedDimension, TaskId, TextProjection, Vars, WorkflowId, WorkspaceId, WsSubscription };
|