@mnemo-ai/types 3.6.0-alpha.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 +19 -0
- package/README.md +159 -0
- package/dist/chunk-H4A2NIMQ.js +124 -0
- package/dist/chunk-H4A2NIMQ.js.map +1 -0
- package/dist/index.cjs +342 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +371 -0
- package/dist/index.d.ts +371 -0
- package/dist/index.js +192 -0
- package/dist/index.js.map +1 -0
- package/dist/ports-PqoQMXjO.d.cts +3233 -0
- package/dist/ports-PqoQMXjO.d.ts +3233 -0
- package/dist/testing/index.cjs +2716 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +420 -0
- package/dist/testing/index.d.ts +420 -0
- package/dist/testing/index.js +2660 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
you may not use this file except in compliance with the License.
|
|
7
|
+
You may obtain a copy of the License at
|
|
8
|
+
|
|
9
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
|
|
11
|
+
Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
See the License for the specific language governing permissions and
|
|
15
|
+
limitations under the License.
|
|
16
|
+
|
|
17
|
+
Copyright 2024-2026 Lucas Mailland and Mnemosyne contributors
|
|
18
|
+
|
|
19
|
+
See the full Apache 2.0 license text at the URL above.
|
package/README.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# @mnemo-ai/types
|
|
2
|
+
|
|
3
|
+
> **AI pointer:** Port interfaces, domain types, and enum definitions for the entire hexagonal architecture. Zero runtime deps — the shared contract between core, adapters, and server.
|
|
4
|
+
>
|
|
5
|
+
> **Depends on:** nothing (zero deps)
|
|
6
|
+
>
|
|
7
|
+
> **Exposes:** StorageAdapter, CacheAdapter, VectorAdapter, LLMAdapter, EmbedAdapter ports; MnemoFact/Decision/Episode/Entity/Strategy/Workflow/Skill/Task/Event/Reasoning types; SENSITIVITY_ORDER; RelationVerb
|
|
8
|
+
>
|
|
9
|
+
> **Status:** STABLE
|
|
10
|
+
>
|
|
11
|
+
> **See also:** [CLAUDE.md](../../CLAUDE.md) · [docs/INDEX.md](../../docs/INDEX.md) · [docs/architecture/DATA_MODEL.md](../../docs/architecture/DATA_MODEL.md)
|
|
12
|
+
|
|
13
|
+
Shared TypeScript interfaces, enums, and domain types for the entire Mnemosyne
|
|
14
|
+
hexagonal architecture. This package is the single source of truth for every port
|
|
15
|
+
contract and domain primitive used across adapters, core, and server.
|
|
16
|
+
|
|
17
|
+
**Zero logic. Zero infrastructure. Zero runtime dependencies.**
|
|
18
|
+
Import from here when you need types — never from an adapter package.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Architecture Role
|
|
23
|
+
|
|
24
|
+
In Mnemosyne's hexagonal (ports-and-adapters) architecture, `@mnemo-ai/types`
|
|
25
|
+
defines the **ports** — the abstract interfaces that the core domain depends on.
|
|
26
|
+
Concrete adapters (postgres, redis, vector, etc.) implement these interfaces.
|
|
27
|
+
Nothing in `@mnemo-ai/types` contains executable code; it is a pure type boundary.
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
@mnemo-ai/types (ports / contracts)
|
|
31
|
+
↑
|
|
32
|
+
@mnemo-ai/core (domain logic — depends on ports, never on adapters)
|
|
33
|
+
↑
|
|
34
|
+
@mnemo-ai/adapter-* (concrete implementations of each port)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pnpm add @mnemo-ai/types
|
|
43
|
+
# or
|
|
44
|
+
npm install @mnemo-ai/types
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
No peer dependencies. No runtime requirements.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Port Interfaces
|
|
52
|
+
|
|
53
|
+
Each port represents one hexagonal boundary between core and infrastructure.
|
|
54
|
+
|
|
55
|
+
| Port | Description |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `StorageAdapter` | Persist and query sessions, turns, facts, and entities in relational storage |
|
|
58
|
+
| `VectorAdapter` | Upsert and search dense embeddings via nearest-neighbor (pgvector or similar) |
|
|
59
|
+
| `CacheAdapter` | Hot-tier key/value cache and sorted-set operations (Redis / Valkey) |
|
|
60
|
+
| `LLMAdapter` | Send prompts and receive completions from any LLM backend |
|
|
61
|
+
| `EmbedAdapter` | Generate dense vector embeddings from text |
|
|
62
|
+
| `QueueAdapter` | Publish jobs to a durable work queue (consolidation, recall tasks) |
|
|
63
|
+
| `OutboxAdapter` | Transactional outbox for reliably delivering domain events |
|
|
64
|
+
| `AuthAdapter` | Validate API keys and resolve workspace/tenant identity |
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Domain Types
|
|
69
|
+
|
|
70
|
+
### Session & Turn
|
|
71
|
+
|
|
72
|
+
| Type | Description |
|
|
73
|
+
|---|---|
|
|
74
|
+
| `MnemoSession` | A single conversation or context window tracked by the system |
|
|
75
|
+
| `SessionTurn` | One turn (message pair) within a session |
|
|
76
|
+
| `CreateSessionInput` | Input shape for opening a new session |
|
|
77
|
+
|
|
78
|
+
### Facts & Recall
|
|
79
|
+
|
|
80
|
+
| Type | Description |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `UpdateFactInput` | Mutation shape for updating an existing fact |
|
|
83
|
+
| `RememberRequest` | Inbound payload to store a new memory |
|
|
84
|
+
| `RememberResponse` | Confirmation with assigned IDs and extracted entities |
|
|
85
|
+
| `RecallQuery` | Search parameters for memory retrieval |
|
|
86
|
+
| `RecallHit` | A single scored result returned from recall |
|
|
87
|
+
| `PrimitiveKind` | Enum of the 10 cognitive fact types (fact, decision, episode, etc.) |
|
|
88
|
+
| `WorthDelta` | Value object representing a change in a fact's worth score |
|
|
89
|
+
|
|
90
|
+
### LLM I/O
|
|
91
|
+
|
|
92
|
+
| Type | Description |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `LLMInput` | Prompt + parameters sent to an LLM adapter |
|
|
95
|
+
| `LLMOutput` | Completion response with token counts and finish reason |
|
|
96
|
+
| `LLMMessage` | A single role/content message in a chat thread |
|
|
97
|
+
|
|
98
|
+
### System & Auth
|
|
99
|
+
|
|
100
|
+
| Type | Description |
|
|
101
|
+
|---|---|
|
|
102
|
+
| `HealthStatus` | System health report emitted by `/health` endpoints |
|
|
103
|
+
| `SchemaLike` | Generic shape for Zod-compatible schema objects |
|
|
104
|
+
| `AuthContext` | Resolved workspace identity after API key validation |
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## Usage Example
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
import type {
|
|
112
|
+
StorageAdapter,
|
|
113
|
+
VectorAdapter,
|
|
114
|
+
MnemoSession,
|
|
115
|
+
RecallQuery,
|
|
116
|
+
RecallHit,
|
|
117
|
+
PrimitiveKind,
|
|
118
|
+
} from "@mnemo-ai/types";
|
|
119
|
+
|
|
120
|
+
// Implement a custom storage adapter
|
|
121
|
+
class MyStorageAdapter implements StorageAdapter {
|
|
122
|
+
async createSession(input: CreateSessionInput): Promise<MnemoSession> {
|
|
123
|
+
// ...
|
|
124
|
+
}
|
|
125
|
+
// implement remaining methods...
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Use domain types for recall
|
|
129
|
+
const query: RecallQuery = {
|
|
130
|
+
workspaceId: "ws_abc123",
|
|
131
|
+
text: "What did we decide about the auth system?",
|
|
132
|
+
kinds: [PrimitiveKind.Decision],
|
|
133
|
+
limit: 10,
|
|
134
|
+
};
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## When to Use This Package
|
|
140
|
+
|
|
141
|
+
- **Building a custom adapter** — implement the relevant port interface
|
|
142
|
+
- **Writing core domain logic** — depend only on port types, never on adapters
|
|
143
|
+
- **Extending the server** — use domain types for request/response shapes
|
|
144
|
+
- **Writing tests** — mock any port interface without importing infrastructure
|
|
145
|
+
|
|
146
|
+
If you find yourself importing from `@mnemo-ai/adapter-*` in domain code,
|
|
147
|
+
that is an architecture violation. Depend on `@mnemo-ai/types` instead.
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Notes
|
|
152
|
+
|
|
153
|
+
- Port interfaces are **stable**. Breaking changes to any interface require a
|
|
154
|
+
semver major bump and a migration note in CHANGELOG.md.
|
|
155
|
+
- The 10 `PrimitiveKind` values are the cognitive taxonomy that drives
|
|
156
|
+
consolidation, recall ranking, and federation attribution.
|
|
157
|
+
- This package ships CommonJS + ESM dual builds with full `.d.ts` declarations.
|
|
158
|
+
|
|
159
|
+
See [`docs/architecture/DATA_MODEL.md`](../../docs/architecture/DATA_MODEL.md) for the full primitive type reference.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/* @mnemo-ai/types — see https://github.com/lucasmailland/mnemosyne */
|
|
2
|
+
|
|
3
|
+
// src/audit.ts
|
|
4
|
+
function resolveAuditActorType(entry) {
|
|
5
|
+
if (entry.actorType) return entry.actorType;
|
|
6
|
+
return entry.actorId ? "user" : "system";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// src/security.ts
|
|
10
|
+
var SENSITIVITY_ORDER = {
|
|
11
|
+
public: 0,
|
|
12
|
+
// visible to anyone with workspace read access
|
|
13
|
+
internal: 1,
|
|
14
|
+
// workspace-internal, not for external sharing
|
|
15
|
+
confidential: 2,
|
|
16
|
+
// restricted distribution within workspace
|
|
17
|
+
restricted: 3
|
|
18
|
+
// highest tier: need-to-know only
|
|
19
|
+
};
|
|
20
|
+
function sensitivityAtLeast(a, b) {
|
|
21
|
+
return SENSITIVITY_ORDER[a] >= SENSITIVITY_ORDER[b];
|
|
22
|
+
}
|
|
23
|
+
var ALL_SCOPES = [
|
|
24
|
+
"memory:read",
|
|
25
|
+
"memory:write",
|
|
26
|
+
"memory:delete",
|
|
27
|
+
"memory:admin",
|
|
28
|
+
"memory:hard_delete",
|
|
29
|
+
"memory:session",
|
|
30
|
+
"memory:task",
|
|
31
|
+
"memory:event",
|
|
32
|
+
"memory:self_edit",
|
|
33
|
+
"memory:procedural",
|
|
34
|
+
"memory:reasoning",
|
|
35
|
+
"memory:export",
|
|
36
|
+
"memory:governance",
|
|
37
|
+
"memory:subscribe",
|
|
38
|
+
"session:read",
|
|
39
|
+
"session:write",
|
|
40
|
+
"session:manage",
|
|
41
|
+
"entity:read",
|
|
42
|
+
"entity:write",
|
|
43
|
+
"entity:admin",
|
|
44
|
+
"federation:read",
|
|
45
|
+
"federation:write",
|
|
46
|
+
"federation:manage",
|
|
47
|
+
"memory:federation",
|
|
48
|
+
"admin:keys",
|
|
49
|
+
"admin:workspace",
|
|
50
|
+
"admin:billing",
|
|
51
|
+
"admin:tenant"
|
|
52
|
+
];
|
|
53
|
+
var SPEC_SCOPES = [
|
|
54
|
+
"memory:read",
|
|
55
|
+
"memory:write",
|
|
56
|
+
"memory:delete",
|
|
57
|
+
"memory:hard_delete",
|
|
58
|
+
"memory:session",
|
|
59
|
+
"memory:task",
|
|
60
|
+
"memory:event",
|
|
61
|
+
"memory:self_edit",
|
|
62
|
+
"memory:procedural",
|
|
63
|
+
"memory:reasoning",
|
|
64
|
+
"memory:export",
|
|
65
|
+
"memory:admin",
|
|
66
|
+
"memory:federation",
|
|
67
|
+
"memory:governance",
|
|
68
|
+
"memory:subscribe"
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
// src/delta-text.ts
|
|
72
|
+
var DELTA_MAGIC_V1 = "MNEMO_DELTA_V1";
|
|
73
|
+
var FULL_MAGIC_V1 = "MNEMO_FULL_V1";
|
|
74
|
+
function toLines(s) {
|
|
75
|
+
return s.split("\n");
|
|
76
|
+
}
|
|
77
|
+
function encodeDelta(parent, child) {
|
|
78
|
+
const p = toLines(parent);
|
|
79
|
+
const c = toLines(child);
|
|
80
|
+
let prefix = 0;
|
|
81
|
+
const maxPrefix = Math.min(p.length, c.length);
|
|
82
|
+
while (prefix < maxPrefix && p[prefix] === c[prefix]) prefix++;
|
|
83
|
+
let suffix = 0;
|
|
84
|
+
const maxSuffix = Math.min(p.length, c.length) - prefix;
|
|
85
|
+
while (suffix < maxSuffix && p[p.length - 1 - suffix] === c[c.length - 1 - suffix]) {
|
|
86
|
+
suffix++;
|
|
87
|
+
}
|
|
88
|
+
const middle = c.slice(prefix, c.length - suffix);
|
|
89
|
+
const header = `${DELTA_MAGIC_V1} ${prefix} ${suffix}`;
|
|
90
|
+
const residual = [header, ...middle].join("\n");
|
|
91
|
+
const full = `${FULL_MAGIC_V1}
|
|
92
|
+
${child}`;
|
|
93
|
+
return residual.length < full.length ? residual : full;
|
|
94
|
+
}
|
|
95
|
+
function applyDelta(parent, delta) {
|
|
96
|
+
if (delta.startsWith(`${FULL_MAGIC_V1}
|
|
97
|
+
`)) {
|
|
98
|
+
return delta.slice(FULL_MAGIC_V1.length + 1);
|
|
99
|
+
}
|
|
100
|
+
if (delta === FULL_MAGIC_V1) {
|
|
101
|
+
return "";
|
|
102
|
+
}
|
|
103
|
+
if (!delta.startsWith(`${DELTA_MAGIC_V1} `)) {
|
|
104
|
+
return delta;
|
|
105
|
+
}
|
|
106
|
+
const newlineIdx = delta.indexOf("\n");
|
|
107
|
+
const headerLine = newlineIdx === -1 ? delta : delta.slice(0, newlineIdx);
|
|
108
|
+
const body = newlineIdx === -1 ? "" : delta.slice(newlineIdx + 1);
|
|
109
|
+
const parts = headerLine.split(" ");
|
|
110
|
+
const prefix = Number(parts[1]);
|
|
111
|
+
const suffix = Number(parts[2]);
|
|
112
|
+
if (!Number.isInteger(prefix) || !Number.isInteger(suffix)) {
|
|
113
|
+
throw new Error(`applyDelta: malformed ${DELTA_MAGIC_V1} header "${headerLine}"`);
|
|
114
|
+
}
|
|
115
|
+
const p = toLines(parent);
|
|
116
|
+
const middle = newlineIdx === -1 ? [] : toLines(body);
|
|
117
|
+
const head = p.slice(0, prefix);
|
|
118
|
+
const tail = suffix === 0 ? [] : p.slice(p.length - suffix);
|
|
119
|
+
return [...head, ...middle, ...tail].join("\n");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export { ALL_SCOPES, DELTA_MAGIC_V1, FULL_MAGIC_V1, SENSITIVITY_ORDER, SPEC_SCOPES, applyDelta, encodeDelta, resolveAuditActorType, sensitivityAtLeast };
|
|
123
|
+
//# sourceMappingURL=chunk-H4A2NIMQ.js.map
|
|
124
|
+
//# sourceMappingURL=chunk-H4A2NIMQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/audit.ts","../src/security.ts","../src/delta-text.ts"],"names":[],"mappings":";;;AAuEO,SAAS,sBACd,KAAA,EACgB;AAChB,EAAA,IAAI,KAAA,CAAM,SAAA,EAAW,OAAO,KAAA,CAAM,SAAA;AAClC,EAAA,OAAO,KAAA,CAAM,UAAU,MAAA,GAAS,QAAA;AAClC;;;ACxDO,IAAM,iBAAA,GAAiD;AAAA,EAC5D,MAAA,EAAQ,CAAA;AAAA;AAAA,EACR,QAAA,EAAU,CAAA;AAAA;AAAA,EACV,YAAA,EAAc,CAAA;AAAA;AAAA,EACd,UAAA,EAAY;AAAA;AACd;AAYO,SAAS,kBAAA,CAAmB,GAAgB,CAAA,EAAyB;AAC1E,EAAA,OAAO,iBAAA,CAAkB,CAAC,CAAA,IAAK,iBAAA,CAAkB,CAAC,CAAA;AACpD;AA2CO,IAAM,UAAA,GAAsC;AAAA,EACjD,aAAA;AAAA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2NIMQ.js","sourcesContent":["// Audit log types — DATA_MODEL.md §4.8 (SECURITY_ARCHITECTURE.md §6)\n// mnemo_audit_log is append-only: INSERT only for app role, enforced by trigger.\n\nexport type AuditAction =\n | \"recall\"\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"hard_delete\"\n | \"export\"\n | \"self_edit\"\n | \"session_open\"\n | \"session_close\"\n | \"key_create\"\n | \"key_rotate\"\n | \"key_revoke\"\n | \"admin_access\"\n | \"federation_sync\"\n | \"erasure_initiated\"\n | \"erasure_complete\"\n | \"federation_cert_pin_mismatch\"\n | \"federation_cert_rotated\"\n | \"plugin_installed\"\n | \"plugin_removed\"\n | \"workspace_created\"\n | \"workspace_deleted\"\n | \"rls_policy_changed\"\n | \"mfa_verified\"\n | \"ip_denied\";\n\n/**\n * Who performed the audited operation (SECURITY_ARCHITECTURE.md §6 \"Audit\n * Trail\"). The distinction is load-bearing for the threat model: insider-access\n * detection and federation-sync provenance both rely on being able to tell a\n * human `user`, an autonomous `agent`, an internal `system` job, and an inbound\n * `federation` peer apart.\n */\nexport type AuditActorType = \"agent\" | \"user\" | \"system\" | \"federation\";\n\nexport interface AuditLogEntry {\n id: string;\n workspaceId: string;\n /**\n * Origin of the operation. Threaded from the auth context. When omitted, the\n * storage adapter resolves it via {@link resolveAuditActorType} (back-compat:\n * `user` when an actorId is present, else `system`).\n */\n actorType?: AuditActorType;\n actorId?: string;\n action: AuditAction;\n resourceKind: string;\n resourceId?: string;\n ipAddress?: string;\n userAgent?: string;\n detail?: Record<string, unknown>;\n isTerminal: boolean; // true for GDPR erasure terminal records\n merkleHash?: Uint8Array; // hash chain integrity; NULL until terminal record\n createdAt: Date;\n}\n\n/**\n * Resolve the `actor_type` to persist for an audit entry.\n *\n * - Prefer the explicit `actorType` threaded from the auth context (the correct\n * value for `agent` / `federation` / `system` / `user` origins).\n * - Back-compat fallback when callers don't yet pass one: `user` if an actorId\n * is present (matches the historical hardcoded value), otherwise `system`.\n *\n * Pure (no I/O) so it can be unit-tested and shared by every StorageAdapter\n * implementation without coupling `@mnemo-ai/types` to any infrastructure.\n */\nexport function resolveAuditActorType(\n entry: Pick<AuditLogEntry, \"actorType\" | \"actorId\">,\n): AuditActorType {\n if (entry.actorType) return entry.actorType;\n return entry.actorId ? \"user\" : \"system\";\n}\n","// Security, auth, RBAC, and sensitivity types — SECURITY_ARCHITECTURE.md §2, §3, §5\n// TASK-2003 deliverable.\n\nimport type { Sensitivity } from \"./common.js\";\nimport type { HealthStatus } from \"./common.js\";\n\n// ─── Sensitivity ordering (fixes MED-23: comparison was string equality) ──────\n//\n// Sensitivity tiers map to integers. ALWAYS compare using SENSITIVITY_ORDER or\n// sensitivityAtLeast() — NEVER with string equality or alphabetic comparison.\n//\n// MED-23 root cause: \"confidential\" > \"internal\" is alphabetically correct but\n// semantically wrong (internal=1 < confidential=2). String comparison produced\n// inverted access decisions.\n//\n// Enforcement rule:\n// - On ceiling violation: return 404 NOT 403 (anti-probing — do not confirm existence)\n// - Auth context carries maxSensitivity; fact carries sensitivity\n// - Access allowed when: SENSITIVITY_ORDER[fact.sensitivity] <= SENSITIVITY_ORDER[auth.maxSensitivity]\n\nexport const SENSITIVITY_ORDER: Record<Sensitivity, number> = {\n public: 0, // visible to anyone with workspace read access\n internal: 1, // workspace-internal, not for external sharing\n confidential: 2, // restricted distribution within workspace\n restricted: 3, // highest tier: need-to-know only\n};\n\n/**\n * Returns true if sensitivity `a` is at or above tier `b`.\n * Use this when checking if a fact's sensitivity is within the caller's ceiling.\n *\n * @example\n * // Allow access only if caller's ceiling >= fact's sensitivity\n * if (!sensitivityAtLeast(auth.maxSensitivity, fact.sensitivity)) {\n * return notFound(); // 404, never 403 (anti-probing rule)\n * }\n */\nexport function sensitivityAtLeast(a: Sensitivity, b: Sensitivity): boolean {\n return SENSITIVITY_ORDER[a] >= SENSITIVITY_ORDER[b];\n}\n\n// ─── API Key types ─────────────────────────────────────────────────────────────\n\nexport type ApiKeyType =\n | \"mk_live_\"\n | \"mk_test_\"\n | \"mk_sess_\"\n | \"mk_fed_\"\n | \"mk_admin_\";\n\n// ─── Scopes ────────────────────────────────────────────────────────────────────\n\nexport type KeyScope =\n | \"memory:read\"\n | \"memory:write\"\n | \"memory:delete\"\n | \"memory:admin\"\n | \"memory:hard_delete\"\n | \"memory:session\"\n | \"memory:task\"\n | \"memory:event\"\n | \"memory:self_edit\"\n | \"memory:procedural\"\n | \"memory:reasoning\"\n | \"memory:export\"\n | \"memory:governance\"\n | \"memory:subscribe\"\n | \"session:read\"\n | \"session:write\"\n | \"session:manage\"\n | \"entity:read\"\n | \"entity:write\"\n | \"entity:admin\"\n | \"federation:read\"\n | \"federation:write\"\n | \"federation:manage\"\n | \"memory:federation\" // canonical name — XDC-06 fix\n | \"admin:keys\"\n | \"admin:workspace\"\n | \"admin:billing\"\n | \"admin:tenant\";\n\nexport const ALL_SCOPES: ReadonlyArray<KeyScope> = [\n \"memory:read\", \"memory:write\", \"memory:delete\", \"memory:admin\",\n \"memory:hard_delete\", \"memory:session\", \"memory:task\", \"memory:event\",\n \"memory:self_edit\", \"memory:procedural\", \"memory:reasoning\", \"memory:export\",\n \"memory:governance\", \"memory:subscribe\",\n \"session:read\", \"session:write\", \"session:manage\",\n \"entity:read\", \"entity:write\", \"entity:admin\",\n \"federation:read\", \"federation:write\", \"federation:manage\",\n \"memory:federation\",\n \"admin:keys\", \"admin:workspace\", \"admin:billing\", \"admin:tenant\",\n] as const;\n\n// ─── Spec §6 — 15 canonical memory scopes ─────────────────────────────────────\n\nexport const SPEC_SCOPES = [\n \"memory:read\", \"memory:write\", \"memory:delete\", \"memory:hard_delete\",\n \"memory:session\", \"memory:task\", \"memory:event\", \"memory:self_edit\",\n \"memory:procedural\", \"memory:reasoning\", \"memory:export\", \"memory:admin\",\n \"memory:federation\", \"memory:governance\", \"memory:subscribe\",\n] as const;\n\nexport type SpecScope = (typeof SPEC_SCOPES)[number];\n\n// ─── Auth context ──────────────────────────────────────────────────────────────\n\nexport interface KeyDeprecation {\n deprecated: true;\n /** ISO-8601 sunset instant = deprecatedAt + 7 days. */\n sunset: string;\n}\n\n/** One row of markUsed history, newest first (for anomaly detection). */\nexport interface KeyUsageEvent {\n ipAddress: string;\n at: Date;\n}\n\nexport interface RotateKeyResult {\n /** The full new key shown ONCE (SECURITY.md §3.4). */\n newKey: string;\n newKeyId: string;\n /** The old key's ISO sunset (deprecatedAt + 7 days). */\n sunset: string;\n}\n\nexport interface KeyEscrowEntry {\n keyId: string;\n prefix: ApiKeyType;\n workspaceId: string;\n scopes: KeyScope[];\n action: \"rotate\" | \"revoke\" | \"break_glass\";\n reason: string;\n escrowedAt: Date;\n}\n\nexport interface AuthContext {\n workspaceId: string;\n actorId: string;\n actorType: \"agent\" | \"user\" | \"system\" | \"federation\";\n scopes: ReadonlyArray<KeyScope>;\n keyType?: ApiKeyType;\n federationPeer?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n /**\n * Set when the authenticating key is in its 7-day deprecation grace\n * (SECURITY.md §3.3). The middleware emits Deprecation/Sunset/\n * Mnemosyne-Key-Deprecated headers from this.\n */\n keyDeprecation?: KeyDeprecation;\n /**\n * Per-key recall sensitivity ceiling carried by the key grant (§5, MED-23).\n * When present it can only LOWER the effective recall ceiling below the\n * process-wide MNEMO_SENSITIVITY_CEILING — never raise it (the effective\n * ceiling is min(envCeiling, keyMax) via SENSITIVITY_ORDER). Undefined for\n * legacy/non-scoped keys → the process-wide ceiling applies unchanged.\n */\n maxSensitivity?: Sensitivity;\n}\n\nexport type AuthResult =\n | { ok: true; context: AuthContext }\n | {\n ok: false;\n code: \"UNAUTHORIZED\" | \"FORBIDDEN\" | \"TOKEN_EXPIRED\" | \"REVOKED\" | \"INVALID\";\n reason: string;\n };\n\n// ─── Credentials ──────────────────────────────────────────────────────────────\n\nexport interface InheritedContext {\n workspaceId: string;\n actorId: string;\n actorType: \"agent\" | \"user\" | \"system\";\n scopes: KeyScope[];\n hostSignature?: string;\n}\n\nexport interface RawCredentials {\n bearer?: string;\n apiKey?: string;\n clientCert?: Uint8Array; // mTLS peer certificate (DER)\n inherited?: InheritedContext;\n /** SEC-03: client IP for allowlist enforcement in ScopedApiKeyAdapter */\n clientIp?: string;\n /** Break-glass: TOTP code for mk_admin_ keys (SECURITY.md §3.1). */\n mfaToken?: string;\n}\n\nexport interface AuthOperation {\n action: KeyScope;\n resource?: string;\n workspaceId?: string;\n}\n\n// ─── AuthAdapter port ─────────────────────────────────────────────────────────\n\nexport interface AuthAdapter {\n readonly id: string;\n\n authenticate(credentials: RawCredentials): Promise<AuthResult>;\n authorize(context: AuthContext, operation: AuthOperation): Promise<void>;\n healthCheck(): Promise<HealthStatus>;\n}\n\n// ─── API Key store interface (used by ScopedApiKeyAdapter) ───────────────────\n\nexport interface ApiKeyRecord {\n keyId: string;\n prefix: ApiKeyType;\n hashedSecret: string;\n workspaceId: string;\n scopes: KeyScope[];\n status: \"active\" | \"deprecated\" | \"revoked\";\n expiresAt: Date | null;\n rotatedFromId?: string;\n ipAllowlist?: string[];\n createdAt: Date;\n lastUsedAt?: Date;\n /** Set when status flips to \"deprecated\" during rotation (§3.3). */\n deprecatedAt?: Date | null;\n /** TOTP shared secret (base32) for mk_admin_ break-glass keys. */\n mfaSecret?: string | null;\n /** AB6.2: workspace.is_test flag — populated by store to enable test/prod key isolation. */\n isTest?: boolean;\n /**\n * Per-key recall sensitivity ceiling grant (§5). When set, it lowers the\n * effective recall ceiling for requests made with this key below the\n * process-wide MNEMO_SENSITIVITY_CEILING (never raises it). Absent on legacy\n * keys → the process-wide ceiling applies unchanged.\n */\n maxSensitivity?: Sensitivity;\n}\n\nexport interface ApiKeyStore {\n lookup(prefix: ApiKeyType, keyId: string): Promise<ApiKeyRecord | null>;\n markUsed(keyId: string, ipAddress: string): Promise<void>;\n revoke(keyId: string, reason: string): Promise<void>;\n /** Newest-first usage history for anomaly detection. */\n recentUsage(keyId: string, limit: number): Promise<KeyUsageEvent[]>;\n /** Flip a key to deprecated with a grace window (rotation step 3). */\n deprecate(keyId: string, deprecatedAt: Date): Promise<void>;\n /** Persist a new key record (rotation step 1); returns nothing. */\n insert(record: ApiKeyRecord): Promise<void>;\n /** Append-only escrow of key METADATA (never the secret) for forensics. */\n escrow(entry: KeyEscrowEntry): Promise<void>;\n}\n\n// ─── Deployment tier ──────────────────────────────────────────────────────────\n\nexport type DeploymentTier = \"personal\" | \"team\" | \"cloud\" | \"embedded\";\n\n// ─── Agent memory access policy (spec §19) ────────────────────────────────────\n\nexport type ApprovalTrigger =\n | \"delete_fact\"\n | \"overwrite_decision\"\n | \"write_entity\"\n | \"cross_agent_read\"\n | \"bulk_export\"\n | \"federation_share\"\n | \"procedural_evolution\"\n | \"task_delegation\";\n\nexport interface SelfEditPolicy {\n enabled: boolean;\n maxWorthDelta?: number;\n}\n\nexport interface AgentMemoryAccess {\n agentId: string;\n workspaceId: string;\n readScopes: SpecScope[];\n writeScopes: SpecScope[];\n selfEdit: SelfEditPolicy;\n taskScopes: {\n canCreate: boolean;\n canDelegate: boolean;\n canDelegateTo: string[];\n };\n limits: {\n maxRecallsPerMinute: number;\n maxWritesPerMinute: number;\n maxSessionsConcurrent: number;\n maxSelfEditsPerSession: number;\n };\n requireApprovalFor: ApprovalTrigger[];\n federationAccess: \"none\" | \"read\" | \"read_write\";\n}\n\n// ─── Injection guard ──────────────────────────────────────────────────────────\n\nexport interface InjectionGuardResult {\n score: number; // 0–1; high = likely injection attempt\n flagged: boolean;\n reason?: string;\n}\n\n// ─── Wave X — Active Security Detection ──────────────────────────────────────\n\n/**\n * Noisy-OR injection score for recall-path text.\n * Aggregates all matched poisoning categories.\n */\nexport interface InjectionScore {\n /** Composite noisy-OR probability in [0, 1]; high = likely injection. */\n score: number;\n flagged: boolean;\n categories: string[];\n}\n\n// ─── Column-level encryption (SECURITY.md §7.2) ──────────────────────────────\n\n/**\n * Wire format for an AES-256-GCM encrypted field stored in the database.\n * Identified by the sentinel prefix \"enc:v1:\" when serialized to a column.\n */\nexport interface EncryptedField {\n /** AES-256-GCM ciphertext, base64-encoded. */\n ciphertext: string;\n /** GCM IV, base64-encoded (12 bytes). */\n iv: string;\n /** GCM authentication tag, base64-encoded (16 bytes). */\n tag: string;\n /** DEK identifier — used for rotation auditing. */\n dekId: string;\n algorithm: \"AES-256-GCM\";\n}\n\n/**\n * Write-time semantic anomaly score derived from neighbour cosine similarities.\n */\nexport interface AnomalyScore {\n /** Composite anomaly probability in [0, 1]; high = anomalous. */\n score: number;\n flagged: boolean;\n signals: {\n /** Isolation score: 1 − mean(neighbour cosine sims). High = isolated from existing knowledge. */\n distance: number;\n /** Estimated PII density derived from piiRiskScore. */\n piiDensity: number;\n /** Fraction of neighbours in contradiction zone [0.80, 0.97). */\n contradiction: number;\n };\n}\n","// Deterministic, dependency-free text-delta codec for DELTAMEM §16 residual\n// episode trees (MEMORY_IMPROVEMENT.md:1296-1329).\n//\n// A child episode that overlaps its parent stores only the RESIDUAL between the\n// parent's reconstructed narrative and its own. Encoding is line-based: we strip\n// the longest common prefix and longest common suffix of lines, and persist only\n// the differing middle window plus the two anchor counts. Reconstruction splices\n// the residual middle back between the parent's prefix and suffix lines.\n//\n// This module is intentionally free of any runtime dependency so it can live in\n// @mnemo-ai/types — the lowest package depended on by core, adapter-postgres,\n// and the in-memory test adapter. It performs no I/O and is fully deterministic.\n\n/** Magic header marking a residual (prefix/suffix-anchored) payload. */\nexport const DELTA_MAGIC_V1 = \"MNEMO_DELTA_V1\";\n/** Magic header marking a full-text payload (used when a residual would not be smaller). */\nexport const FULL_MAGIC_V1 = \"MNEMO_FULL_V1\";\n\n// Split into lines WITHOUT discarding information: we keep \"\\n\" as the join glue\n// and operate on the array. join(\"\\n\") of split(\"\\n\") is the identity on any\n// string, so prefix/suffix splicing is exact (including blank and trailing lines).\nfunction toLines(s: string): string[] {\n return s.split(\"\\n\");\n}\n\n/**\n * Encode `child` as a residual against `parent`.\n *\n * Format (residual, all parts newline-joined into ONE string):\n * line 0: `MNEMO_DELTA_V1\\t<prefixCount>\\t<suffixCount>`\n * line 1..N: the differing MIDDLE lines of `child`\n *\n * If the residual would not be strictly smaller than a full payload, returns a\n * full payload instead:\n * line 0: `MNEMO_FULL_V1`\n * line 1..N: the full `child` text\n *\n * `applyDelta` inverts whichever form is produced.\n */\nexport function encodeDelta(parent: string, child: string): string {\n const p = toLines(parent);\n const c = toLines(child);\n\n // Longest common prefix of lines.\n let prefix = 0;\n const maxPrefix = Math.min(p.length, c.length);\n while (prefix < maxPrefix && p[prefix] === c[prefix]) prefix++;\n\n // Longest common suffix of lines, not overlapping the matched prefix.\n let suffix = 0;\n const maxSuffix = Math.min(p.length, c.length) - prefix;\n while (\n suffix < maxSuffix &&\n p[p.length - 1 - suffix] === c[c.length - 1 - suffix]\n ) {\n suffix++;\n }\n\n const middle = c.slice(prefix, c.length - suffix);\n const header = `${DELTA_MAGIC_V1}\\t${prefix}\\t${suffix}`;\n const residual = [header, ...middle].join(\"\\n\");\n const full = `${FULL_MAGIC_V1}\\n${child}`;\n\n // Prefer the residual only when it is strictly smaller; otherwise the full\n // payload guarantees correctness with no growth surprise for adversarial input.\n return residual.length < full.length ? residual : full;\n}\n\n/**\n * Reconstruct the child narrative from `parent` and an encoded `delta`.\n *\n * Back-compat: a `delta` that begins with neither magic header is treated as a\n * literal full narrative (legacy rows / raw fixtures written before WP5).\n */\nexport function applyDelta(parent: string, delta: string): string {\n if (delta.startsWith(`${FULL_MAGIC_V1}\\n`)) {\n return delta.slice(FULL_MAGIC_V1.length + 1);\n }\n if (delta === FULL_MAGIC_V1) {\n return \"\";\n }\n if (!delta.startsWith(`${DELTA_MAGIC_V1}\\t`)) {\n // Legacy: deltaContent already holds the full narrative.\n return delta;\n }\n\n const newlineIdx = delta.indexOf(\"\\n\");\n const headerLine = newlineIdx === -1 ? delta : delta.slice(0, newlineIdx);\n const body = newlineIdx === -1 ? \"\" : delta.slice(newlineIdx + 1);\n\n const parts = headerLine.split(\"\\t\");\n const prefix = Number(parts[1]);\n const suffix = Number(parts[2]);\n if (!Number.isInteger(prefix) || !Number.isInteger(suffix)) {\n throw new Error(`applyDelta: malformed ${DELTA_MAGIC_V1} header \"${headerLine}\"`);\n }\n\n const p = toLines(parent);\n // The header had no body line iff the middle window was empty (newlineIdx===-1).\n const middle = newlineIdx === -1 ? [] : toLines(body);\n\n const head = p.slice(0, prefix);\n const tail = suffix === 0 ? [] : p.slice(p.length - suffix);\n return [...head, ...middle, ...tail].join(\"\\n\");\n}\n"]}
|