@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.
@@ -0,0 +1,1133 @@
1
+ import { HARNESS_MAX_IDENTITY_BYTES, HARNESS_MAX_GENERATION, HARNESS_MAX_ENQUEUE_SEQUENCE, HARNESS_MAX_CHUNKS_PER_MESSAGE, HARNESS_CHUNK_VERSION, HARNESS_MAX_BATCH_EVENTS, HARNESS_PROTOCOL_VERSION, sha256Hex, canonicalJson, HARNESS_MAX_BATCH_BYTES, HARNESS_MAX_MESSAGE_BYTES } from './chunk-BZD2CQAU.js';
2
+ import { z } from 'zod';
3
+ import { createHash } from 'crypto';
4
+
5
+ /* @mnemo-ai/types — see https://github.com/lucasmailland/mnemosyne */
6
+
7
+ // src/branded.ts
8
+ var asWorkspaceId = (s) => s;
9
+ var asFactId = (s) => s;
10
+ var asDecisionId = (s) => s;
11
+ var asEpisodeId = (s) => s;
12
+ var asEntityId = (s) => s;
13
+ var asStrategyId = (s) => s;
14
+ var asWorkflowId = (s) => s;
15
+ var asSkillId = (s) => s;
16
+ var asTaskId = (s) => s;
17
+ var asEventId = (s) => s;
18
+ var asReasoningId = (s) => s;
19
+ var asSessionId = (s) => s;
20
+ var asRelationId = (s) => s;
21
+ var WORKSPACE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
+ function isWorkspaceId(s) {
23
+ return WORKSPACE_UUID_RE.test(s);
24
+ }
25
+
26
+ // src/primitives.ts
27
+ var PRIMITIVE_KINDS = [
28
+ "fact",
29
+ "decision",
30
+ "episode",
31
+ "entity",
32
+ "strategy",
33
+ "workflow",
34
+ "skill",
35
+ "task",
36
+ "event",
37
+ "reasoning",
38
+ "hyperedge"
39
+ ];
40
+ var PRIMITIVE_SUBTYPES = {
41
+ // Q-3: architecture … process are the categories agents file facts under
42
+ // (the decision vocabulary). Not "decision" itself: a fact whose kind names
43
+ // another primitive is hydrated as that primitive by recall.
44
+ fact: [
45
+ "preference",
46
+ "trait",
47
+ "event",
48
+ "relationship",
49
+ "skill",
50
+ "concern",
51
+ "architecture",
52
+ "bugfix",
53
+ "config",
54
+ "discovery",
55
+ "policy",
56
+ "process",
57
+ "other"
58
+ ],
59
+ decision: [
60
+ "decision",
61
+ "architecture",
62
+ "policy",
63
+ "process",
64
+ "bugfix",
65
+ "learning",
66
+ "discovery",
67
+ "config"
68
+ ],
69
+ entity: ["person", "organization", "project", "concept", "place", "other"]
70
+ };
71
+
72
+ // src/relations.ts
73
+ var RELATION_NODE_KINDS = [
74
+ "fact",
75
+ "decision",
76
+ "entity",
77
+ "episode",
78
+ "strategy",
79
+ "workflow",
80
+ "skill",
81
+ "task",
82
+ "event",
83
+ "reasoning"
84
+ ];
85
+
86
+ // src/audit.ts
87
+ function resolveAuditActorType(entry) {
88
+ if (entry.actorType) return entry.actorType;
89
+ return entry.actorId ? "user" : "system";
90
+ }
91
+
92
+ // src/ports.ts
93
+ var FactRevisionConflictError = class extends Error {
94
+ constructor(factId, expectedRevision, currentRevision) {
95
+ super(`fact ${factId} is at revision ${currentRevision}, not the expected ${expectedRevision}`);
96
+ this.factId = factId;
97
+ this.expectedRevision = expectedRevision;
98
+ this.currentRevision = currentRevision;
99
+ this.name = "FactRevisionConflictError";
100
+ }
101
+ factId;
102
+ expectedRevision;
103
+ currentRevision;
104
+ code = "REVISION_CONFLICT";
105
+ };
106
+ var DEFAULT_CONTRADICTION_MIN_SIMILARITY = 0.55;
107
+ var GENERIC_FACT_SUBJECT = "general";
108
+ function isSpecificFactSubject(subject) {
109
+ const s = subject.trim().toLowerCase();
110
+ return s !== "" && s !== GENERIC_FACT_SUBJECT;
111
+ }
112
+ var TERMINAL_TASK_STATUSES = ["completed", "cancelled"];
113
+ var RECALL_PRECISION_METHODOLOGY_NOTE = 'TD(\u03BB) credit is a coarse session-level proxy, not per-hit attribution: a hit counts as "credited" only when its session collapsed AND created at least one fact, and the hit falls within the 20-most-recently-recalled window that propagateTdCredit actually reads (mnemo_session.fact_count > 0, recency rank \u2264 20 within its session) \u2014 not because this specific hit was verified to shape that fact. Hits whose session never collapsed are excluded from every denominator, not counted as failures (design.md). Per-hit attribution requires the D5 citation write path, which is out of scope for this report.';
114
+ var APPROVAL_PENDING_TTL_MS = 24 * 60 * 6e4;
115
+ var APPROVAL_USE_TTL_MS = 60 * 6e4;
116
+ var RECOVERY_POINTS = [
117
+ "started",
118
+ "session_locked",
119
+ "llm_called",
120
+ "facts_persisted",
121
+ "completed"
122
+ ];
123
+
124
+ // src/security.ts
125
+ var SENSITIVITY_ORDER = {
126
+ public: 0,
127
+ // visible to anyone with workspace read access
128
+ internal: 1,
129
+ // workspace-internal, not for external sharing
130
+ confidential: 2,
131
+ // restricted distribution within workspace
132
+ restricted: 3
133
+ // highest tier: need-to-know only
134
+ };
135
+ function sensitivityAtLeast(a, b) {
136
+ return SENSITIVITY_ORDER[a] >= SENSITIVITY_ORDER[b];
137
+ }
138
+ function tiersAtOrBelow(ceiling) {
139
+ return Object.keys(SENSITIVITY_ORDER).filter(
140
+ (tier) => SENSITIVITY_ORDER[tier] <= SENSITIVITY_ORDER[ceiling]
141
+ );
142
+ }
143
+ function isSensitiveTier(tier) {
144
+ const rank = typeof tier === "string" && Object.prototype.hasOwnProperty.call(SENSITIVITY_ORDER, tier) ? SENSITIVITY_ORDER[tier] : void 0;
145
+ return typeof rank !== "number" || rank >= SENSITIVITY_ORDER.confidential;
146
+ }
147
+ function sensitiveTextMayReachEmbedder(policy, embed) {
148
+ return (policy ?? "embed") !== "none" || embed?.local === true;
149
+ }
150
+ function sensitiveTextMayReachLlm(policy, llm, task) {
151
+ if (policy === "all") return true;
152
+ return task !== void 0 && Array.isArray(llm?.localTasks) && llm.localTasks.includes(task);
153
+ }
154
+ var ALL_SCOPES = [
155
+ "memory:read",
156
+ "memory:write",
157
+ "memory:delete",
158
+ "memory:admin",
159
+ "memory:hard_delete",
160
+ "memory:session",
161
+ "memory:task",
162
+ "memory:event",
163
+ "memory:self_edit",
164
+ "memory:procedural",
165
+ "memory:reasoning",
166
+ "memory:export",
167
+ "memory:governance",
168
+ "memory:subscribe",
169
+ "session:read",
170
+ "session:write",
171
+ "session:manage",
172
+ "entity:read",
173
+ "entity:write",
174
+ "entity:admin",
175
+ "federation:read",
176
+ "federation:write",
177
+ "federation:manage",
178
+ "federation:admin",
179
+ "memory:federation",
180
+ "admin:keys",
181
+ "admin:workspace",
182
+ "admin:billing",
183
+ "admin:tenant"
184
+ ];
185
+ var SPEC_SCOPES = [
186
+ "memory:read",
187
+ "memory:write",
188
+ "memory:delete",
189
+ "memory:hard_delete",
190
+ "memory:session",
191
+ "memory:task",
192
+ "memory:event",
193
+ "memory:self_edit",
194
+ "memory:procedural",
195
+ "memory:reasoning",
196
+ "memory:export",
197
+ "memory:admin",
198
+ "memory:federation",
199
+ "memory:governance",
200
+ "memory:subscribe"
201
+ ];
202
+ var WORKSPACE_ROLE_ORDER = {
203
+ read: 0,
204
+ write: 1,
205
+ admin: 2,
206
+ owner: 3
207
+ };
208
+ function roleAtLeast(a, b) {
209
+ return WORKSPACE_ROLE_ORDER[a] >= WORKSPACE_ROLE_ORDER[b];
210
+ }
211
+ var WORKSPACE_GOVERNED_SCOPES = new Set(
212
+ ALL_SCOPES.filter((s) => s !== "admin:tenant" && s !== "admin:billing" && s !== "admin:workspace")
213
+ );
214
+ var WORKSPACE_READ_SCOPES = [
215
+ "memory:read",
216
+ "memory:subscribe",
217
+ "session:read",
218
+ "entity:read",
219
+ "federation:read"
220
+ ];
221
+ var WORKSPACE_WRITE_SCOPES = [
222
+ ...WORKSPACE_READ_SCOPES,
223
+ "memory:write",
224
+ "memory:delete",
225
+ "memory:session",
226
+ "memory:task",
227
+ "memory:event",
228
+ "memory:reasoning",
229
+ "memory:procedural",
230
+ "memory:self_edit",
231
+ "session:write",
232
+ "entity:write"
233
+ ];
234
+ var WORKSPACE_ADMIN_SCOPES = [
235
+ ...WORKSPACE_WRITE_SCOPES,
236
+ "memory:admin",
237
+ "memory:hard_delete",
238
+ "memory:export",
239
+ "memory:governance",
240
+ "memory:federation",
241
+ "admin:keys",
242
+ "session:manage",
243
+ "entity:admin",
244
+ "federation:write",
245
+ "federation:manage",
246
+ "federation:admin"
247
+ ];
248
+ var WORKSPACE_ROLE_SCOPES = {
249
+ read: new Set(WORKSPACE_READ_SCOPES),
250
+ write: new Set(WORKSPACE_WRITE_SCOPES),
251
+ admin: new Set(WORKSPACE_ADMIN_SCOPES),
252
+ owner: new Set(WORKSPACE_ADMIN_SCOPES)
253
+ };
254
+ function narrowScopesForWorkspaceRole(keyScopes, role) {
255
+ const allowed = WORKSPACE_ROLE_SCOPES[role];
256
+ return keyScopes.filter((s) => !WORKSPACE_GOVERNED_SCOPES.has(s) || allowed.has(s));
257
+ }
258
+ var FactKindClause = z.object({
259
+ op: z.literal("fact_kind"),
260
+ kind: z.string().min(1).max(64),
261
+ bind: z.string().regex(/^\$[a-z][a-z0-9_]*$/i).optional()
262
+ }).strict();
263
+ var TopicKeyInClause = z.object({
264
+ op: z.literal("topic_key_in"),
265
+ topicKeys: z.array(z.string().min(1).max(200)).min(1).max(32),
266
+ bind: z.string().regex(/^\$[a-z][a-z0-9_]*$/i).optional()
267
+ }).strict();
268
+ var TextContainsClause = z.object({
269
+ op: z.literal("text_contains"),
270
+ needle: z.string().min(1).max(500),
271
+ bind: z.string().regex(/^\$[a-z][a-z0-9_]*$/i).optional()
272
+ }).strict();
273
+ var RELATION_VERBS = [
274
+ "related",
275
+ "compatible",
276
+ "scoped",
277
+ "conflicts_with",
278
+ "supersedes",
279
+ "not_conflict",
280
+ "derived_from",
281
+ "part_of",
282
+ "member_of"
283
+ ];
284
+ var BIND_RE = /^\$[a-z][a-z0-9_]*$/i;
285
+ var RelationClause = z.object({
286
+ op: z.literal("relation"),
287
+ from: z.string().regex(BIND_RE),
288
+ to: z.string().regex(BIND_RE),
289
+ verb: z.enum(RELATION_VERBS)
290
+ }).strict();
291
+ var NumberOrBind = z.union([z.number(), z.string().regex(BIND_RE)]);
292
+ var FactValueClause = z.object({
293
+ op: z.literal("fact_value"),
294
+ subject: z.string().regex(BIND_RE),
295
+ predicate: z.string().min(1).max(128),
296
+ valueType: z.enum(["duration", "number"]),
297
+ compare: z.object({
298
+ lt: NumberOrBind.optional(),
299
+ gt: NumberOrBind.optional(),
300
+ lte: NumberOrBind.optional(),
301
+ gte: NumberOrBind.optional()
302
+ }).strict().partial().optional(),
303
+ bind: z.string().regex(BIND_RE).optional()
304
+ }).strict();
305
+ var ConditionClause = z.discriminatedUnion("op", [
306
+ FactKindClause,
307
+ TopicKeyInClause,
308
+ TextContainsClause,
309
+ RelationClause,
310
+ FactValueClause
311
+ ]);
312
+ var ConditionDslSchema = z.object({
313
+ all: z.array(ConditionClause).min(1).max(8)
314
+ }).strict();
315
+ var DeriveFactAction = z.object({
316
+ op: z.literal("derive_fact"),
317
+ statementTemplate: z.string().min(1).max(2e3),
318
+ // DSL kind: NOT a valid MnemoFact.kind — stored in metadata.inference.derivedKind.
319
+ // Engine writes kind='other' to mnemo_fact (valid kind) and attribution='inferred'.
320
+ kind: z.string().min(1).max(64).default("inferred"),
321
+ topicKey: z.string().max(200).optional(),
322
+ baseConfidence: z.number().min(0).max(1).default(0.7),
323
+ sensitivity: z.enum(["public", "internal", "confidential", "restricted"]).default("internal"),
324
+ type: z.literal("fact").default("fact")
325
+ }).strict();
326
+ var DeriveWarningAction = z.object({
327
+ op: z.literal("derive_warning"),
328
+ statementTemplate: z.string().min(1).max(2e3),
329
+ kind: z.string().min(1).max(64).default("inferred"),
330
+ topicKey: z.string().max(200).optional(),
331
+ baseConfidence: z.number().min(0).max(1).default(0.7),
332
+ sensitivity: z.enum(["public", "internal", "confidential", "restricted"]).default("internal"),
333
+ type: z.literal("warning").default("warning")
334
+ }).strict();
335
+ var ActionDslSchema = z.discriminatedUnion("op", [DeriveFactAction, DeriveWarningAction]);
336
+ function parseConditionDsl(raw) {
337
+ return ConditionDslSchema.parse(raw);
338
+ }
339
+ function parseActionDsl(raw) {
340
+ return ActionDslSchema.parse(raw);
341
+ }
342
+
343
+ // src/observability.ts
344
+ var MNEMO_ERROR_CODES = {
345
+ // Storage errors
346
+ STORAGE_NOT_FOUND: "mnemo.storage.not_found",
347
+ STORAGE_CONFLICT: "mnemo.storage.conflict",
348
+ STORAGE_CONSTRAINT: "mnemo.storage.constraint_violation",
349
+ STORAGE_TIMEOUT: "mnemo.storage.timeout",
350
+ // Auth errors
351
+ AUTH_MISSING_KEY: "mnemo.auth.missing_key",
352
+ AUTH_EXPIRED_KEY: "mnemo.auth.expired_key",
353
+ AUTH_INSUFFICIENT_SCOPE: "mnemo.auth.insufficient_scope",
354
+ AUTH_WORKSPACE_MISMATCH: "mnemo.auth.workspace_mismatch",
355
+ // Recall errors
356
+ RECALL_BUDGET_EXCEEDED: "mnemo.recall.budget_exceeded",
357
+ RECALL_VECTOR_MISSING: "mnemo.recall.vector_missing",
358
+ RECALL_UPSTREAM_TIMEOUT: "mnemo.recall.upstream_timeout",
359
+ // Composition errors
360
+ COMPOSE_DSL_INVALID: "mnemo.compose.dsl_invalid",
361
+ COMPOSE_MAX_FIRINGS: "mnemo.compose.max_firings_reached",
362
+ COMPOSE_MATERIALISE_FAIL: "mnemo.compose.materialise_failed",
363
+ // Self-edit errors
364
+ SELF_EDIT_BUDGET: "mnemo.self_edit.budget_exceeded",
365
+ SELF_EDIT_COOLDOWN: "mnemo.self_edit.cooldown_active",
366
+ SELF_EDIT_SCOPE: "mnemo.self_edit.scope_denied",
367
+ SELF_EDIT_ABUSE_FLAG: "mnemo.self_edit.abuse_flagged",
368
+ SELF_EDIT_WORTH_FROZEN: "mnemo.self_edit.worth_frozen",
369
+ // Federation errors
370
+ FED_SIGNATURE_INVALID: "mnemo.federation.signature_invalid",
371
+ FED_VERSION_SKEW: "mnemo.federation.version_skew",
372
+ FED_QUORUM_UNREACHABLE: "mnemo.federation.quorum_unreachable",
373
+ // Procedural errors
374
+ PROC_BUDGET_BELOW_GATE: "mnemo.procedural.budget_below_gate",
375
+ PROC_NO_TRAJECTORIES: "mnemo.procedural.no_trajectories",
376
+ // General
377
+ RATE_LIMIT: "mnemo.rate_limit",
378
+ VALIDATION: "mnemo.validation",
379
+ INTERNAL: "mnemo.internal"
380
+ };
381
+ var MNEMO_SPAN_NAMES = {
382
+ recall: "mnemo.recall",
383
+ remember: "mnemo.remember",
384
+ /** Spec alias of `remember` (spec calls this span "mnemo.write"). */
385
+ write: "mnemo.remember",
386
+ sessionCollapse: "mnemo.session.collapse",
387
+ reasoningResolve: "mnemo.reasoning.resolve",
388
+ federationSync: "mnemo.federation.sync",
389
+ /** Auth middleware span — wraps the bearer-token resolution path. */
390
+ auth: "mnemo.auth",
391
+ /** Embedding span — wraps embedSingle / embed batch calls. */
392
+ embed: "mnemo.embed",
393
+ /** Re-ranking span — wraps RecMem rerank on the cold path. */
394
+ rerank: "mnemo.rerank",
395
+ /** Composition span — wraps composeInferences on the cold path. */
396
+ composition: "mnemo.composition",
397
+ /** Render span — wraps renderFactsCompact at the call site. */
398
+ render: "mnemo.render",
399
+ plugin: (name) => `mnemo.plugin.${name}`
400
+ };
401
+
402
+ // src/delta-text.ts
403
+ var DELTA_MAGIC_V1 = "MNEMO_DELTA_V1";
404
+ var FULL_MAGIC_V1 = "MNEMO_FULL_V1";
405
+ function toLines(s) {
406
+ return s.split("\n");
407
+ }
408
+ function encodeDelta(parent, child) {
409
+ const p = toLines(parent);
410
+ const c = toLines(child);
411
+ let prefix = 0;
412
+ const maxPrefix = Math.min(p.length, c.length);
413
+ while (prefix < maxPrefix && p[prefix] === c[prefix]) prefix++;
414
+ let suffix = 0;
415
+ const maxSuffix = Math.min(p.length, c.length) - prefix;
416
+ while (suffix < maxSuffix && p[p.length - 1 - suffix] === c[c.length - 1 - suffix]) {
417
+ suffix++;
418
+ }
419
+ const middle = c.slice(prefix, c.length - suffix);
420
+ const header = `${DELTA_MAGIC_V1} ${prefix} ${suffix}`;
421
+ const residual = [header, ...middle].join("\n");
422
+ const full = `${FULL_MAGIC_V1}
423
+ ${child}`;
424
+ return residual.length < full.length ? residual : full;
425
+ }
426
+ function applyDelta(parent, delta) {
427
+ if (delta.startsWith(`${FULL_MAGIC_V1}
428
+ `)) {
429
+ return delta.slice(FULL_MAGIC_V1.length + 1);
430
+ }
431
+ if (delta === FULL_MAGIC_V1) {
432
+ return "";
433
+ }
434
+ if (!delta.startsWith(`${DELTA_MAGIC_V1} `)) {
435
+ return delta;
436
+ }
437
+ const newlineIdx = delta.indexOf("\n");
438
+ const headerLine = newlineIdx === -1 ? delta : delta.slice(0, newlineIdx);
439
+ const body = newlineIdx === -1 ? "" : delta.slice(newlineIdx + 1);
440
+ const parts = headerLine.split(" ");
441
+ const prefix = Number(parts[1]);
442
+ const suffix = Number(parts[2]);
443
+ if (!Number.isInteger(prefix) || !Number.isInteger(suffix)) {
444
+ throw new Error(`applyDelta: malformed ${DELTA_MAGIC_V1} header "${headerLine}"`);
445
+ }
446
+ const p = toLines(parent);
447
+ const middle = newlineIdx === -1 ? [] : toLines(body);
448
+ const head = p.slice(0, prefix);
449
+ const tail = suffix === 0 ? [] : p.slice(p.length - suffix);
450
+ return [...head, ...middle, ...tail].join("\n");
451
+ }
452
+
453
+ // src/embedding.ts
454
+ function generateSpaceId(space) {
455
+ const parts = [
456
+ space.provider,
457
+ space.model,
458
+ space.modelRevision ?? "v1",
459
+ String(space.dimensions),
460
+ space.distanceMetric ?? "cosine",
461
+ space.dtype ?? "float32"
462
+ ];
463
+ return parts.join(":").toLowerCase();
464
+ }
465
+
466
+ // src/provenance.ts
467
+ function formatActorRef(namespace, id) {
468
+ return `${namespace}:${id}`;
469
+ }
470
+ var ACTOR_NAMESPACES = /* @__PURE__ */ new Set([
471
+ "user",
472
+ "key",
473
+ "system",
474
+ "peer"
475
+ ]);
476
+ function parseActorRef(value) {
477
+ const idx = value.indexOf(":");
478
+ if (idx <= 0) return null;
479
+ const namespace = value.slice(0, idx);
480
+ const id = value.slice(idx + 1);
481
+ if (!id || !ACTOR_NAMESPACES.has(namespace)) return null;
482
+ return { namespace, id };
483
+ }
484
+
485
+ // src/graph-assembly.ts
486
+ function countMeta(nodes, edges) {
487
+ return {
488
+ entityCount: nodes.filter((n) => n.kind === "entity").length,
489
+ episodeCount: nodes.filter((n) => n.kind === "episode").length,
490
+ decisionCount: nodes.filter((n) => n.kind === "decision").length,
491
+ relationCount: edges.length
492
+ };
493
+ }
494
+ function withMentionCounts(nodes, edges) {
495
+ const episodes = new Set(nodes.filter((n) => n.kind === "episode").map((n) => n.id));
496
+ const episodesByNode = /* @__PURE__ */ new Map();
497
+ const link = (nodeId, episodeId) => {
498
+ const seen = episodesByNode.get(nodeId) ?? /* @__PURE__ */ new Set();
499
+ seen.add(episodeId);
500
+ episodesByNode.set(nodeId, seen);
501
+ };
502
+ for (const e of edges) {
503
+ if (e.provenance === "episode_facts") continue;
504
+ if (episodes.has(e.source)) link(e.target, e.source);
505
+ if (episodes.has(e.target)) link(e.source, e.target);
506
+ }
507
+ return nodes.map(
508
+ (n) => n.kind === "entity" ? { ...n, mentionCount: n.factCount + (episodesByNode.get(n.id)?.size ?? 0) } : n
509
+ );
510
+ }
511
+ function assembleGraphSnapshot(allNodes, edges, opts = {}) {
512
+ const nodes = withMentionCounts(allNodes, edges);
513
+ if (opts.focusEntityId) {
514
+ const focus = opts.focusEntityId;
515
+ const neighborIds = /* @__PURE__ */ new Set([focus]);
516
+ for (const e of edges) {
517
+ if (e.source === focus) neighborIds.add(e.target);
518
+ if (e.target === focus) neighborIds.add(e.source);
519
+ }
520
+ const focusNodes = nodes.filter((n) => neighborIds.has(n.id));
521
+ const focusEdges = edges.filter((e) => neighborIds.has(e.source) && neighborIds.has(e.target));
522
+ return { nodes: focusNodes, edges: focusEdges, meta: countMeta(focusNodes, focusEdges) };
523
+ }
524
+ return { nodes, edges, meta: countMeta(nodes, edges) };
525
+ }
526
+
527
+ // src/dashboard-aggregates.ts
528
+ function utcDayKeys(days, now = Date.now()) {
529
+ const today = Date.parse(new Date(now).toISOString().slice(0, 10));
530
+ return Array.from(
531
+ { length: days },
532
+ (_, i) => new Date(today - (days - 1 - i) * 864e5).toISOString().slice(0, 10)
533
+ );
534
+ }
535
+ function tallySessionStats(days, sessions, episodes) {
536
+ const byDay = new Map(
537
+ utcDayKeys(days).map((day) => [day, { day, active: 0, collapsed: 0, archived: 0 }])
538
+ );
539
+ let n = 0;
540
+ let collapsed = 0;
541
+ let turns = 0;
542
+ for (const r of sessions) {
543
+ n += r.n;
544
+ collapsed += r.collapsed;
545
+ turns += r.turns;
546
+ const d = byDay.get(r.day);
547
+ if (d && (r.status === "active" || r.status === "collapsed" || r.status === "archived"))
548
+ d[r.status] += r.n;
549
+ }
550
+ const topics = /* @__PURE__ */ new Map();
551
+ for (const e of episodes)
552
+ for (const t of new Set(e.topics)) topics.set(t, (topics.get(t) ?? 0) + 1);
553
+ const facts = episodes.reduce((sum, e) => sum + e.facts, 0);
554
+ return {
555
+ days: [...byDay.values()],
556
+ totals: {
557
+ sessions: n,
558
+ collapsed,
559
+ avgTurns: n > 0 ? turns / n : null,
560
+ episodes: episodes.length,
561
+ factsPerEpisode: episodes.length > 0 ? facts / episodes.length : null
562
+ },
563
+ topics: [...topics].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 5).map(([topic, count]) => ({ topic, count }))
564
+ };
565
+ }
566
+ function tallyAuditActivity(days, groups, lastAt) {
567
+ const perDay = new Map(utcDayKeys(days).map((day) => [day, 0]));
568
+ const byAction = /* @__PURE__ */ new Map();
569
+ for (const g of groups) {
570
+ if (perDay.has(g.day)) perDay.set(g.day, perDay.get(g.day) + g.n);
571
+ byAction.set(g.action, (byAction.get(g.action) ?? 0) + g.n);
572
+ }
573
+ return {
574
+ days: [...perDay].map(([day, count]) => ({ day, count })),
575
+ byAction: [...byAction].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([action, count]) => ({ action, count })),
576
+ lastAt
577
+ };
578
+ }
579
+ function tallyHealthSnapshots(days, latestByDay) {
580
+ return utcDayKeys(days).map((day) => {
581
+ const s = latestByDay.get(day);
582
+ if (!s)
583
+ return {
584
+ day,
585
+ recallHitRate30d: null,
586
+ zeroHitShare: null,
587
+ embeddedShare: null,
588
+ failedJobs7d: null
589
+ };
590
+ const indexable = s.factCountEmbedded + s.factCountUnembedded;
591
+ return {
592
+ day,
593
+ recallHitRate30d: s.recallHitRate30d,
594
+ zeroHitShare: s.factCountActive > 0 ? s.factsWithZeroHits / s.factCountActive : null,
595
+ embeddedShare: indexable > 0 ? s.factCountEmbedded / indexable : null,
596
+ failedJobs7d: s.extractionJobsFailed7d
597
+ };
598
+ });
599
+ }
600
+ function tallyAuditFeedStats(days, groups) {
601
+ const byDay = new Map(utcDayKeys(days).map((day) => [day, { day, user: 0, system: 0 }]));
602
+ const totals = { user: 0, system: 0 };
603
+ for (const g of groups) {
604
+ const d = byDay.get(g.day);
605
+ if (!d) continue;
606
+ d[g.actorKind] += g.n;
607
+ totals[g.actorKind] += g.n;
608
+ }
609
+ return { days: [...byDay.values()], totals };
610
+ }
611
+
612
+ // src/indexing.ts
613
+ var RECALLABLE_KINDS = [
614
+ "fact",
615
+ "decision",
616
+ "strategy",
617
+ "workflow",
618
+ "skill",
619
+ "episode",
620
+ "task",
621
+ "event",
622
+ "reasoning"
623
+ ];
624
+ var DEFAULT_RECALL_KINDS = [
625
+ "fact",
626
+ "decision",
627
+ "strategy",
628
+ "workflow",
629
+ "skill",
630
+ "episode"
631
+ ];
632
+ var NON_DEFAULT_RECALLABLE_KINDS = [
633
+ "task",
634
+ "event",
635
+ "reasoning"
636
+ ];
637
+ function isRecallableKind(kind) {
638
+ return RECALLABLE_KINDS.includes(kind);
639
+ }
640
+ var PRIMITIVE_TEXT_PROJECTION = {
641
+ fact: { fields: ["statement"], separator: " " },
642
+ decision: { fields: ["title", "body"], separator: " " },
643
+ // The trigger→action pair IS the heuristic; either half alone is
644
+ // unsearchable. "when the build goes red" means nothing without what to do
645
+ // about it, and "re-run with --no-cache" means nothing without when.
646
+ strategy: { fields: ["trigger", "action"], separator: " " },
647
+ // `description` is optional on MnemoWorkflow, and projectPrimitiveText skips
648
+ // empty fields rather than emitting the literal "undefined", so a
649
+ // name-only workflow still projects cleanly.
650
+ workflow: { fields: ["name", "description"], separator: " " },
651
+ // The template IS the skill; the name alone is a label.
652
+ skill: { fields: ["name", "promptTemplate"], separator: " " },
653
+ // Matches the createEpisode producer's text-form outbox payload, so a §36
654
+ // model migration re-embeds the same text the lexical column indexes.
655
+ episode: { fields: ["title", "narrative"], separator: " " },
656
+ task: { fields: ["title", "description"], separator: " " },
657
+ event: { fields: ["name", "description"], separator: " " },
658
+ reasoning: { fields: ["question", "conclusion"], separator: " " }
659
+ };
660
+ var SUPPORTED_EMBED_DIMENSIONS = [1024, 1536, 2048, 4096];
661
+ function isSupportedEmbedDimension(n) {
662
+ return SUPPORTED_EMBED_DIMENSIONS.includes(n);
663
+ }
664
+ function assertSupportedEmbedDimension(n, context) {
665
+ if (!isSupportedEmbedDimension(n)) {
666
+ throw new Error(
667
+ `${context}: unsupported embedding width ${n}. This schema has vector tables and indexes only for ${SUPPORTED_EMBED_DIMENSIONS.join(", ")}. Pick an embedding model with one of those widths (or add the table, index and migration for ${n} first).`
668
+ );
669
+ }
670
+ }
671
+ function projectPrimitiveText(kind, row) {
672
+ const projection = PRIMITIVE_TEXT_PROJECTION[kind];
673
+ return projection.fields.map((field) => row[field]).filter((value) => typeof value === "string" && value.length > 0).join(projection.separator);
674
+ }
675
+ var DATE = z.regexes.date.source.slice(1, -1);
676
+ var TIME = "(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?";
677
+ var OFFSET = "[+-](?:[01]\\d|2[0-3]):[0-5]\\d";
678
+ var UTC_ONLY = new RegExp(`^${DATE}T(?:${TIME}(?:Z))$`);
679
+ var WITH_OFFSET = new RegExp(`^${DATE}T(?:${TIME}(?:Z|(${OFFSET})))$`);
680
+ function isoDateTimeInput(opts = {}) {
681
+ return z.stringFormat("datetime", opts.offset ? WITH_OFFSET : UTC_ONLY);
682
+ }
683
+
684
+ // src/harness.ts
685
+ var HASH_PATTERN = /^[0-9a-f]{64}$/;
686
+ var NON_EMPTY_STRING = z.string().min(1);
687
+ var IDENTITY_STRING = NON_EMPTY_STRING.refine(
688
+ (value) => Buffer.byteLength(value, "utf8") <= HARNESS_MAX_IDENTITY_BYTES,
689
+ `Identity exceeds ${HARNESS_MAX_IDENTITY_BYTES} UTF-8 bytes`
690
+ );
691
+ var GENERATION = z.number().int().nonnegative().max(HARNESS_MAX_GENERATION);
692
+ var ENQUEUE_SEQUENCE = z.number().int().positive().max(HARNESS_MAX_ENQUEUE_SEQUENCE);
693
+ var occurredAtSchema = isoDateTimeInput({ offset: true });
694
+ var HarnessPayloadLimitError = class extends Error {
695
+ constructor(limit, maxBytes, actualBytes) {
696
+ super(`Harness ${limit} exceeds ${maxBytes} bytes`);
697
+ this.limit = limit;
698
+ this.maxBytes = maxBytes;
699
+ this.actualBytes = actualBytes;
700
+ }
701
+ limit;
702
+ maxBytes;
703
+ actualBytes;
704
+ name = "HarnessPayloadLimitError";
705
+ };
706
+ var eventBase = {
707
+ eventId: IDENTITY_STRING,
708
+ host: z.enum(["opencode", "claude-code", "codex"]),
709
+ hostSessionId: IDENTITY_STRING,
710
+ clientInstanceId: IDENTITY_STRING,
711
+ enqueueSequence: ENQUEUE_SEQUENCE,
712
+ occurredAt: occurredAtSchema,
713
+ payloadHash: z.string().regex(HASH_PATTERN),
714
+ normalizationVersion: z.literal(1)
715
+ };
716
+ var harnessTurnAppendChunkSchema = z.strictObject({
717
+ version: z.literal(HARNESS_CHUNK_VERSION),
718
+ chunkIndex: z.number().int().nonnegative().max(HARNESS_MAX_CHUNKS_PER_MESSAGE - 1),
719
+ chunkCount: z.number().int().min(2).max(HARNESS_MAX_CHUNKS_PER_MESSAGE),
720
+ messageContentHash: z.string().regex(HASH_PATTERN)
721
+ }).refine((chunk) => chunk.chunkIndex < chunk.chunkCount, {
722
+ message: "chunkIndex must be less than chunkCount"
723
+ });
724
+ var harnessEventSchema = z.discriminatedUnion("type", [
725
+ z.strictObject({
726
+ ...eventBase,
727
+ type: z.literal("session.start"),
728
+ requestedGeneration: GENERATION.optional(),
729
+ sensitivity: z.enum(["public", "internal"]).optional(),
730
+ metadata: z.record(z.string(), z.string()).optional()
731
+ }),
732
+ z.strictObject({
733
+ ...eventBase,
734
+ type: z.literal("turn.append"),
735
+ sourceGeneration: GENERATION,
736
+ hostMessageId: IDENTITY_STRING,
737
+ supersedesSourceMessageId: IDENTITY_STRING.optional(),
738
+ role: z.enum(["user", "assistant"]),
739
+ content: z.string(),
740
+ contentHash: z.string().regex(HASH_PATTERN),
741
+ turnOrigin: z.enum([
742
+ "human",
743
+ "agent_message",
744
+ "task_notification",
745
+ "pasted_content",
746
+ "assistant",
747
+ "unknown"
748
+ ]).optional(),
749
+ turnOriginEvidence: z.string().max(256).optional(),
750
+ chunk: harnessTurnAppendChunkSchema.optional()
751
+ }),
752
+ z.strictObject({
753
+ ...eventBase,
754
+ type: z.literal("turn.retract"),
755
+ sourceGeneration: GENERATION,
756
+ hostMessageId: IDENTITY_STRING,
757
+ reason: z.enum(["superseded", "branch_removed"])
758
+ }),
759
+ z.strictObject({
760
+ ...eventBase,
761
+ type: z.literal("sequence.loss"),
762
+ sourceGeneration: GENERATION,
763
+ reason: z.enum(["capacity", "invalid_payload", "permanent_rejection"]),
764
+ lostEventType: z.enum(["turn.append", "turn.retract"]),
765
+ lostHostMessageId: IDENTITY_STRING,
766
+ lostRole: z.enum(["user", "assistant"]),
767
+ lostContentHash: z.string().regex(HASH_PATTERN)
768
+ }),
769
+ z.strictObject({
770
+ ...eventBase,
771
+ type: z.literal("event.cancel"),
772
+ sourceGeneration: GENERATION,
773
+ targetEventId: IDENTITY_STRING,
774
+ reason: z.enum(["generation_redirect", "terminal_rebuild"])
775
+ }),
776
+ z.strictObject({
777
+ ...eventBase,
778
+ type: z.literal("session.end"),
779
+ sourceGeneration: GENERATION,
780
+ reason: z.enum(["host_end", "host_delete", "inactivity"]),
781
+ finalMessageSetDigest: z.string().regex(HASH_PATTERN),
782
+ maxEnqueueSequence: ENQUEUE_SEQUENCE
783
+ })
784
+ ]);
785
+ var harnessBatchV1Schema = z.strictObject({
786
+ protocolVersion: z.literal(HARNESS_PROTOCOL_VERSION),
787
+ expectedWorkspaceId: IDENTITY_STRING,
788
+ clientInstanceId: IDENTITY_STRING,
789
+ events: z.array(harnessEventSchema).max(HARNESS_MAX_BATCH_EVENTS)
790
+ });
791
+ var harnessProbeV1Schema = z.strictObject({
792
+ protocolVersion: z.literal(HARNESS_PROTOCOL_VERSION),
793
+ expectedWorkspaceId: IDENTITY_STRING,
794
+ clientInstanceId: IDENTITY_STRING
795
+ });
796
+ function computeHarnessPayloadHash(event) {
797
+ const { payloadHash: _payloadHash, ...body } = event;
798
+ return sha256Hex(canonicalJson(body));
799
+ }
800
+ function validateHarnessEventSemantics(event, receivedAt) {
801
+ if (computeHarnessPayloadHash(event) !== event.payloadHash) return "payload_hash_mismatch";
802
+ if (event.type === "turn.append" && sha256Hex(event.content) !== event.contentHash) {
803
+ return "content_hash_mismatch";
804
+ }
805
+ if (event.type === "session.end" && event.enqueueSequence !== event.maxEnqueueSequence + 1) {
806
+ return "terminal_sequence_mismatch";
807
+ }
808
+ if (Date.parse(event.occurredAt) > receivedAt.getTime() + 24 * 60 * 60 * 1e3) {
809
+ return "future_timestamp";
810
+ }
811
+ return null;
812
+ }
813
+ function parseHarnessBatchV1(input) {
814
+ const serialized = typeof input === "string" ? input : JSON.stringify(input);
815
+ if (serialized !== void 0) {
816
+ const serializedBytes = Buffer.byteLength(serialized, "utf8");
817
+ if (serializedBytes > HARNESS_MAX_BATCH_BYTES) {
818
+ throw new HarnessPayloadLimitError("batch", HARNESS_MAX_BATCH_BYTES, serializedBytes);
819
+ }
820
+ }
821
+ const batch = harnessBatchV1Schema.parse(typeof input === "string" ? JSON.parse(input) : input);
822
+ for (const event of batch.events) {
823
+ if (event.clientInstanceId !== batch.clientInstanceId) {
824
+ throw new Error("Event clientInstanceId must match the batch clientInstanceId");
825
+ }
826
+ if (event.type === "turn.append") {
827
+ const messageBytes = Buffer.byteLength(event.content, "utf8");
828
+ if (messageBytes > HARNESS_MAX_MESSAGE_BYTES) {
829
+ throw new HarnessPayloadLimitError("message", HARNESS_MAX_MESSAGE_BYTES, messageBytes);
830
+ }
831
+ }
832
+ }
833
+ return batch;
834
+ }
835
+ function parseHarnessProbeV1(input) {
836
+ return harnessProbeV1Schema.parse(input);
837
+ }
838
+
839
+ // src/storage-errors.ts
840
+ var StorageNotFoundError = class extends Error {
841
+ code = "not_found";
842
+ constructor(message) {
843
+ super(message);
844
+ this.name = "StorageNotFoundError";
845
+ }
846
+ };
847
+ var StorageConflictError = class extends Error {
848
+ code = "conflict";
849
+ constructor(message) {
850
+ super(message);
851
+ this.name = "StorageConflictError";
852
+ }
853
+ };
854
+ var StorageValidationError = class extends Error {
855
+ code = "invalid";
856
+ constructor(message) {
857
+ super(message);
858
+ this.name = "StorageValidationError";
859
+ }
860
+ };
861
+
862
+ // src/scope-ref.ts
863
+ function scopeRefValues(filter) {
864
+ if (!filter.scopeRef) return void 0;
865
+ return [.../* @__PURE__ */ new Set([filter.scopeRef, ...filter.scopeRefAliases ?? []])];
866
+ }
867
+ function scopeRefMatches(value, filter) {
868
+ const accepted = scopeRefValues(filter);
869
+ return accepted === void 0 || value != null && accepted.includes(value);
870
+ }
871
+ function factStatementHash(statement, subject) {
872
+ const normalised = `${statement.trim().toLowerCase()}|${subject}|fact`;
873
+ return createHash("sha256").update(normalised).digest("hex");
874
+ }
875
+
876
+ // src/managed-collapse.ts
877
+ function managedCollapseOperationId(session) {
878
+ return session.collapseOperationId ?? `managed:${session.workspaceId}:${session.id}:${session.sourceGeneration ?? -1}`;
879
+ }
880
+
881
+ // src/lsh.ts
882
+ var LSH_DIMS = 64;
883
+ var LSH_BANDS = 6;
884
+ var LSH_PLANES_PER_BAND = 8;
885
+ var LSH_SEED = 2654435769;
886
+ function xorshift32(state) {
887
+ state ^= state << 13;
888
+ state ^= state >>> 17;
889
+ state ^= state << 5;
890
+ return state >>> 0;
891
+ }
892
+ var PLANES = [];
893
+ {
894
+ let rng = LSH_SEED;
895
+ for (let b = 0; b < LSH_BANDS; b++) {
896
+ const band = [];
897
+ for (let p = 0; p < LSH_PLANES_PER_BAND; p++) {
898
+ const plane = [];
899
+ for (let d = 0; d < LSH_DIMS; d++) {
900
+ rng = xorshift32(rng);
901
+ plane.push(rng & 1 ? 1 : -1);
902
+ }
903
+ band.push(plane);
904
+ }
905
+ PLANES.push(band);
906
+ }
907
+ }
908
+ function fnv1a64(bandIdx, sketch, spaceId) {
909
+ let h = 0xcbf29ce484222325n;
910
+ const prime = 0x100000001b3n;
911
+ const mask = 0xffffffffffffffffn;
912
+ const str = spaceId ? `${spaceId}:${bandIdx}` : `${bandIdx}`;
913
+ for (let i = 0; i < str.length; i++) {
914
+ h = (h ^ BigInt(str.charCodeAt(i))) & mask;
915
+ h = h * prime & mask;
916
+ }
917
+ h = (h ^ BigInt(sketch & 255)) & mask;
918
+ h = h * prime & mask;
919
+ return h;
920
+ }
921
+ function lshBands(embedding, spaceId) {
922
+ const out = [];
923
+ for (let b = 0; b < LSH_BANDS; b++) {
924
+ let sketch = 0;
925
+ for (let p = 0; p < LSH_PLANES_PER_BAND; p++) {
926
+ const plane = PLANES[b][p];
927
+ let dot = 0;
928
+ for (let d = 0; d < plane.length; d++) {
929
+ dot += (embedding[d] ?? 0) * plane[d];
930
+ }
931
+ if (dot >= 0) sketch |= 1 << p;
932
+ }
933
+ out.push({ bandIdx: b, bandHash: fnv1a64(b, sketch, spaceId) });
934
+ }
935
+ return out;
936
+ }
937
+
938
+ // src/pg-session.ts
939
+ var DEFAULT_PG_SESSION_TIMEOUTS = Object.freeze({
940
+ statementTimeoutMs: 6e4,
941
+ lockTimeoutMs: 15e3,
942
+ idleInTransactionTimeoutMs: 6e4
943
+ });
944
+ var PG_SESSION_TIMEOUT_ENV = Object.freeze({
945
+ statementTimeoutMs: "MNEMO_PG_STATEMENT_TIMEOUT_MS",
946
+ lockTimeoutMs: "MNEMO_PG_LOCK_TIMEOUT_MS",
947
+ idleInTransactionTimeoutMs: "MNEMO_PG_IDLE_IN_TRANSACTION_TIMEOUT_MS"
948
+ });
949
+ var PG_MAINTENANCE_TIMEOUT_ENV = "MNEMO_PG_MAINTENANCE_STATEMENT_TIMEOUT_MS";
950
+ function readMs(env, name, fallback) {
951
+ const raw = env[name];
952
+ if (raw === void 0 || raw.trim() === "") return fallback;
953
+ const n = Number(raw);
954
+ if (!Number.isSafeInteger(n) || n < 0) {
955
+ throw new Error(`${name} must be a whole number of milliseconds >= 0, got "${raw}"`);
956
+ }
957
+ return n;
958
+ }
959
+ function resolvePgSessionTimeouts(env) {
960
+ const t = {
961
+ statementTimeoutMs: readMs(
962
+ env,
963
+ PG_SESSION_TIMEOUT_ENV.statementTimeoutMs,
964
+ DEFAULT_PG_SESSION_TIMEOUTS.statementTimeoutMs
965
+ ),
966
+ lockTimeoutMs: readMs(
967
+ env,
968
+ PG_SESSION_TIMEOUT_ENV.lockTimeoutMs,
969
+ DEFAULT_PG_SESSION_TIMEOUTS.lockTimeoutMs
970
+ ),
971
+ idleInTransactionTimeoutMs: readMs(
972
+ env,
973
+ PG_SESSION_TIMEOUT_ENV.idleInTransactionTimeoutMs,
974
+ DEFAULT_PG_SESSION_TIMEOUTS.idleInTransactionTimeoutMs
975
+ )
976
+ };
977
+ if (t.statementTimeoutMs > 0 && t.lockTimeoutMs >= t.statementTimeoutMs) {
978
+ throw new Error(
979
+ `${PG_SESSION_TIMEOUT_ENV.lockTimeoutMs} (${t.lockTimeoutMs}) must be shorter than ${PG_SESSION_TIMEOUT_ENV.statementTimeoutMs} (${t.statementTimeoutMs})`
980
+ );
981
+ }
982
+ return t;
983
+ }
984
+ function pgSessionTimeoutParams(t) {
985
+ const params = {};
986
+ if (t.statementTimeoutMs > 0) params["statement_timeout"] = String(t.statementTimeoutMs);
987
+ if (t.lockTimeoutMs > 0) params["lock_timeout"] = String(t.lockTimeoutMs);
988
+ if (t.idleInTransactionTimeoutMs > 0) {
989
+ params["idle_in_transaction_session_timeout"] = String(t.idleInTransactionTimeoutMs);
990
+ }
991
+ return params;
992
+ }
993
+ function resolvePgMaintenanceTimeoutMs(env) {
994
+ return readMs(env, PG_MAINTENANCE_TIMEOUT_ENV, 0);
995
+ }
996
+
997
+ // src/pg-errors.ts
998
+ var TRANSIENT_DRIVER_CODES = /* @__PURE__ */ new Set([
999
+ "ECONNREFUSED",
1000
+ "ECONNRESET",
1001
+ "ETIMEDOUT",
1002
+ "EPIPE",
1003
+ "EHOSTUNREACH",
1004
+ "ENETUNREACH",
1005
+ "ENOTFOUND",
1006
+ "EAI_AGAIN",
1007
+ "CONNECT_TIMEOUT",
1008
+ "CONNECTION_CLOSED",
1009
+ "CONNECTION_ENDED",
1010
+ "CONNECTION_DESTROYED"
1011
+ ]);
1012
+ var TRANSIENT_SQLSTATES = /* @__PURE__ */ new Set([
1013
+ "53300",
1014
+ // too_many_connections
1015
+ "57P01",
1016
+ // admin_shutdown
1017
+ "57P02",
1018
+ // crash_shutdown
1019
+ "57P03",
1020
+ // cannot_connect_now (starting up / recovery)
1021
+ "57014",
1022
+ // query_canceled — statement_timeout
1023
+ "55P03",
1024
+ // lock_not_available — lock_timeout
1025
+ "25P03"
1026
+ // idle_in_transaction_session_timeout
1027
+ ]);
1028
+ function codeOf(err) {
1029
+ if (typeof err !== "object" || err === null) return void 0;
1030
+ const code = err.code;
1031
+ return typeof code === "string" ? code : void 0;
1032
+ }
1033
+ function isBreakerTimeoutError(err) {
1034
+ return err instanceof Error && codeOf(err) === "ETIMEDOUT" && /^Timed out after \d+ms$/.test(err.message);
1035
+ }
1036
+ function isTransientDbError(err) {
1037
+ let current = err;
1038
+ for (let depth = 0; depth < 5 && current instanceof Error; depth++) {
1039
+ const code = isBreakerTimeoutError(current) ? void 0 : codeOf(current);
1040
+ if (code !== void 0) {
1041
+ if (TRANSIENT_DRIVER_CODES.has(code) || TRANSIENT_SQLSTATES.has(code)) return true;
1042
+ if (/^08[0-9A-Z]{3}$/.test(code)) return true;
1043
+ }
1044
+ current = current.cause;
1045
+ }
1046
+ return false;
1047
+ }
1048
+
1049
+ // src/i18n.ts
1050
+ var LOCALES = ["en-US", "es-419"];
1051
+ var DEFAULT_LOCALE = "en-US";
1052
+ var PRIMARY = { en: "en-US", es: "es-419" };
1053
+ function normalizeLocale(tag) {
1054
+ if (typeof tag !== "string" || !tag) return void 0;
1055
+ const primary = tag.trim().toLowerCase().split(/[-_.@]/)[0] ?? "";
1056
+ return Object.hasOwn(PRIMARY, primary) ? PRIMARY[primary] : void 0;
1057
+ }
1058
+ function resolveLocale(candidates, acceptLanguage) {
1059
+ for (const c of candidates) {
1060
+ const locale = normalizeLocale(c);
1061
+ if (locale) return locale;
1062
+ }
1063
+ const ranked = (acceptLanguage ?? "").split(",").map((part, i) => {
1064
+ const [tag, ...params] = part.trim().split(";");
1065
+ const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
1066
+ return { tag, q: q ? Number(q.slice(2)) : 1, i };
1067
+ }).filter((e) => e.tag && e.q > 0).sort((a, b) => b.q - a.q || a.i - b.i);
1068
+ for (const { tag } of ranked) {
1069
+ const locale = normalizeLocale(tag);
1070
+ if (locale) return locale;
1071
+ }
1072
+ return DEFAULT_LOCALE;
1073
+ }
1074
+ function translate(dict, key, vars, locale = DEFAULT_LOCALE) {
1075
+ let node = dict;
1076
+ for (const part of key.split("."))
1077
+ node = node && typeof node === "object" && Object.hasOwn(node, part) ? node[part] : void 0;
1078
+ if (node && typeof node === "object") {
1079
+ const p = node;
1080
+ const count = vars?.count;
1081
+ const branch = typeof count === "number" ? new Intl.PluralRules(locale).select(count) : "other";
1082
+ node = Object.hasOwn(p, branch) ? p[branch] : p.other;
1083
+ }
1084
+ if (typeof node !== "string") return key;
1085
+ return node.replace(
1086
+ /\{(\w+)\}/g,
1087
+ (m, name) => vars && Object.hasOwn(vars, name) ? String(vars[name]) : m
1088
+ );
1089
+ }
1090
+ var MAX_MATCH_LENGTH = 2048;
1091
+ function compileTemplates(table) {
1092
+ return Object.entries(table).map(([key, template]) => {
1093
+ const pieces = template.split(/\{(\w+)\}/);
1094
+ const literals = pieces.filter((_, i) => i % 2 === 0);
1095
+ const names = pieces.filter((_, i) => i % 2 === 1);
1096
+ if (new Set(names).size !== names.length)
1097
+ throw new Error(`duplicate placeholder in "${key}"`);
1098
+ if (literals.slice(1, -1).includes("")) throw new Error(`adjacent placeholders in "${key}"`);
1099
+ return { key, literals, names, weight: literals.join("").length };
1100
+ }).sort((a, b) => b.weight - a.weight || a.names.length - b.names.length);
1101
+ }
1102
+ function matchTemplate(compiled, message) {
1103
+ if (message.length > MAX_MATCH_LENGTH) return void 0;
1104
+ for (const { key, literals, names } of compiled) {
1105
+ const first = literals[0] ?? "";
1106
+ if (names.length === 0) {
1107
+ if (message === first) return { key, vars: /* @__PURE__ */ Object.create(null) };
1108
+ continue;
1109
+ }
1110
+ const last = literals[literals.length - 1] ?? "";
1111
+ if (!message.startsWith(first) || !message.endsWith(last)) continue;
1112
+ const end = message.length - last.length;
1113
+ if (end < first.length) continue;
1114
+ const vars = /* @__PURE__ */ Object.create(null);
1115
+ let pos = first.length;
1116
+ let ok = true;
1117
+ for (let i = 0; i < names.length && ok; i++) {
1118
+ const sep = i < names.length - 1 ? literals[i + 1] ?? "" : void 0;
1119
+ const stop = sep === void 0 ? end : message.indexOf(sep, pos + 1);
1120
+ if (stop <= pos || sep !== void 0 && stop + sep.length > end) ok = false;
1121
+ else {
1122
+ vars[names[i]] = message.slice(pos, stop);
1123
+ pos = stop + (sep?.length ?? 0);
1124
+ }
1125
+ }
1126
+ if (ok) return { key, vars };
1127
+ }
1128
+ return void 0;
1129
+ }
1130
+
1131
+ export { ALL_SCOPES, APPROVAL_PENDING_TTL_MS, APPROVAL_USE_TTL_MS, ActionDslSchema, ConditionDslSchema, DEFAULT_CONTRADICTION_MIN_SIMILARITY, DEFAULT_LOCALE, DEFAULT_PG_SESSION_TIMEOUTS, DEFAULT_RECALL_KINDS, DELTA_MAGIC_V1, FULL_MAGIC_V1, FactRevisionConflictError, GENERIC_FACT_SUBJECT, HarnessPayloadLimitError, 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_KINDS, PRIMITIVE_SUBTYPES, PRIMITIVE_TEXT_PROJECTION, RECALLABLE_KINDS, RECALL_PRECISION_METHODOLOGY_NOTE, RECOVERY_POINTS, RELATION_NODE_KINDS, SENSITIVITY_ORDER, SPEC_SCOPES, SUPPORTED_EMBED_DIMENSIONS, StorageConflictError, StorageNotFoundError, StorageValidationError, TERMINAL_TASK_STATUSES, WORKSPACE_GOVERNED_SCOPES, WORKSPACE_ROLE_ORDER, WORKSPACE_ROLE_SCOPES, applyDelta, asDecisionId, asEntityId, asEpisodeId, asEventId, asFactId, asReasoningId, asRelationId, asSessionId, asSkillId, asStrategyId, asTaskId, asWorkflowId, asWorkspaceId, assembleGraphSnapshot, assertSupportedEmbedDimension, compileTemplates, computeHarnessPayloadHash, encodeDelta, factStatementHash, formatActorRef, generateSpaceId, isBreakerTimeoutError, isRecallableKind, isSensitiveTier, isSpecificFactSubject, isSupportedEmbedDimension, isTransientDbError, isWorkspaceId, isoDateTimeInput, lshBands, managedCollapseOperationId, matchTemplate, narrowScopesForWorkspaceRole, normalizeLocale, parseActionDsl, parseActorRef, parseConditionDsl, parseHarnessBatchV1, parseHarnessProbeV1, pgSessionTimeoutParams, projectPrimitiveText, resolveAuditActorType, resolveLocale, resolvePgMaintenanceTimeoutMs, resolvePgSessionTimeouts, roleAtLeast, scopeRefMatches, scopeRefValues, sensitiveTextMayReachEmbedder, sensitiveTextMayReachLlm, sensitivityAtLeast, tallyAuditActivity, tallyAuditFeedStats, tallyHealthSnapshots, tallySessionStats, tiersAtOrBelow, translate, utcDayKeys, validateHarnessEventSemantics };
1132
+ //# sourceMappingURL=chunk-2PEOVZQ5.js.map
1133
+ //# sourceMappingURL=chunk-2PEOVZQ5.js.map