@kinqs/brainrouter-types 0.3.4

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/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # @kinqs/brainrouter-types
2
+
3
+ Shared TypeScript types for the [BrainRouter](https://github.com/kinqsradiollc/BrainRouter) monorepo — used by `brainrouter` (CLI), `@kinqs/brainrouter-mcp-server`, and `@kinqs/brainrouter-sdk`.
4
+
5
+ No runtime code, just types.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install --save-dev @kinqs/brainrouter-types
11
+ ```
12
+
13
+ ## License
14
+
15
+ MIT
package/dist/api.d.ts ADDED
@@ -0,0 +1,251 @@
1
+ import type { EvidenceKind, ContradictionRecord, DiagnosticsBundle, ImportResult, CognitiveRecord, ContextualFocusRecord, MemoryEvidence, MemoryExport, MemoryImport, MemoryOperation, MemoryStatus, RecallResult, SkillActivationRecord } from "./memory.js";
2
+ import type { MemoryListItem } from "./store.js";
3
+ import { PublicUserRecord } from "./memory.js";
4
+ export interface SigninRequest {
5
+ email: string;
6
+ password?: string;
7
+ }
8
+ export interface SigninResponse {
9
+ jwt: string;
10
+ userId: string;
11
+ isAdmin: boolean;
12
+ displayName: string;
13
+ apiKey: string;
14
+ }
15
+ export interface SignupRequest {
16
+ email: string;
17
+ password?: string;
18
+ displayName?: string;
19
+ }
20
+ export interface SignupResponse {
21
+ jwt: string;
22
+ userId: string;
23
+ isAdmin: boolean;
24
+ displayName: string;
25
+ }
26
+ export interface MeResponse extends PublicUserRecord {
27
+ apiKey: string;
28
+ mcpPath?: string;
29
+ }
30
+ export interface UserStatusRequest {
31
+ status: "active" | "disabled";
32
+ }
33
+ export interface UserResetKeyResponse {
34
+ apiKey: string;
35
+ }
36
+ export interface CursorPaginationParams {
37
+ cursor?: string;
38
+ limit?: number;
39
+ }
40
+ export interface CursorPaginatedResponse<T> {
41
+ nextCursor: string | null;
42
+ limit: number;
43
+ hasMore: boolean;
44
+ data: T[];
45
+ }
46
+ export interface NamedCursorPaginatedResponse<T, K extends string> {
47
+ nextCursor: string | null;
48
+ limit: number;
49
+ hasMore: boolean;
50
+ [key: string]: T[] | string | number | boolean | null;
51
+ }
52
+ export interface MemoryStatsResponse {
53
+ total: number;
54
+ archived: number;
55
+ byType: Record<string, number>;
56
+ citationRate: number;
57
+ lastRecallAt: string | null;
58
+ extraction: unknown;
59
+ }
60
+ export type MemoriesResponse = {
61
+ memories: MemoryListItem[];
62
+ nextCursor: string | null;
63
+ limit: number;
64
+ hasMore: boolean;
65
+ };
66
+ export type OperationsResponse = {
67
+ operations: MemoryOperation[];
68
+ nextCursor: string | null;
69
+ limit: number;
70
+ hasMore: boolean;
71
+ };
72
+ export type EvidenceResponse = {
73
+ evidence: MemoryEvidence[];
74
+ nextCursor: string | null;
75
+ limit: number;
76
+ hasMore: boolean;
77
+ };
78
+ export type ScenesResponse = {
79
+ scenes: ContextualFocusRecord[];
80
+ nextCursor: string | null;
81
+ limit: number;
82
+ hasMore: boolean;
83
+ };
84
+ export type ContradictionsResponse = {
85
+ contradictions: ContradictionRecord[];
86
+ nextCursor: string | null;
87
+ limit: number;
88
+ hasMore: boolean;
89
+ };
90
+ export type DiagnosticsResponse = DiagnosticsBundle;
91
+ export interface MemoryWithEvidenceResponse {
92
+ memory: CognitiveRecord;
93
+ evidence: MemoryEvidence[];
94
+ }
95
+ export interface MemoryEvidenceByRecordResponse {
96
+ evidence: MemoryEvidence[];
97
+ total?: number;
98
+ }
99
+ export interface UpdateMemoryRequest {
100
+ content?: string;
101
+ status?: MemoryStatus;
102
+ confidence?: number;
103
+ verificationStatus?: CognitiveRecord["verificationStatus"];
104
+ note?: string;
105
+ }
106
+ export interface AddEvidenceRequest {
107
+ kind: EvidenceKind;
108
+ ref: string;
109
+ excerpt?: string;
110
+ metadata?: Record<string, unknown>;
111
+ }
112
+ export interface AddEvidenceResponse {
113
+ evidence: MemoryEvidence;
114
+ }
115
+ export interface ExplainRecallRequest {
116
+ query: string;
117
+ sessionKey?: string;
118
+ activeSkill?: string;
119
+ userId?: string;
120
+ }
121
+ export type ExplainRecallResponse = RecallResult;
122
+ export interface WorkingStep {
123
+ nodeId: string;
124
+ title: string;
125
+ summary: string;
126
+ kind: string;
127
+ createdAt: string;
128
+ refPath?: string;
129
+ tokenEstimate: number;
130
+ }
131
+ export type TokenPressureLevel = "none" | "mild" | "aggressive";
132
+ export interface WorkingMemoryState {
133
+ sessionKey: string;
134
+ workDir: string;
135
+ pressureLevel: TokenPressureLevel;
136
+ contextWindowTokens: number;
137
+ estimatedTokens: number;
138
+ injectedState: {
139
+ currentNode?: WorkingStep;
140
+ recentSteps: WorkingStep[];
141
+ refs: Array<{
142
+ nodeId: string;
143
+ refPath?: string;
144
+ title: string;
145
+ }>;
146
+ rawPayloadsIncluded: false;
147
+ };
148
+ updatedAt: string;
149
+ }
150
+ export interface WorkingContextRequest extends CursorPaginationParams {
151
+ workspacePath?: string;
152
+ userId?: string;
153
+ sessionKey: string;
154
+ nodeId?: string;
155
+ activeNodeId?: string;
156
+ contextWindowTokens?: number;
157
+ estimatedTokens?: number;
158
+ }
159
+ export interface WorkingContextResponse {
160
+ sessionKey: string;
161
+ workDir: string;
162
+ canvas: string;
163
+ annotatedCanvas?: string;
164
+ state: WorkingMemoryState;
165
+ steps: WorkingStep[];
166
+ ref?: {
167
+ nodeId: string;
168
+ path: string;
169
+ content: string;
170
+ };
171
+ }
172
+ export interface WorkingOffloadRequest {
173
+ workspacePath?: string;
174
+ userId?: string;
175
+ sessionKey: string;
176
+ payload: string;
177
+ title?: string;
178
+ summary?: string;
179
+ kind?: string;
180
+ contextWindowTokens?: number;
181
+ estimatedTokens?: number;
182
+ forceAggressive?: boolean;
183
+ }
184
+ export interface WorkingOffloadResponse {
185
+ nodeId: string;
186
+ refPath: string;
187
+ pressureLevel: TokenPressureLevel;
188
+ canvas: string;
189
+ state: WorkingMemoryState;
190
+ }
191
+ export interface WorkingResetRequest {
192
+ workspacePath?: string;
193
+ userId?: string;
194
+ sessionKey: string;
195
+ }
196
+ export interface WorkingResetResponse {
197
+ deleted: boolean;
198
+ workDir: string;
199
+ }
200
+ export type HostHookSource = "claude-code" | "codex" | "generic-mcp";
201
+ export interface RegisteredHook {
202
+ id: string;
203
+ userId: string;
204
+ source: HostHookSource | string;
205
+ events: string[];
206
+ sessionKey?: string;
207
+ workspacePath?: string;
208
+ registeredAt: string;
209
+ lastSeenAt: string | null;
210
+ lastEvent: string | null;
211
+ metadata: Record<string, unknown>;
212
+ }
213
+ export interface HookRegisterRequest {
214
+ source: HostHookSource;
215
+ events?: string[];
216
+ userId?: string;
217
+ sessionKey?: string;
218
+ sessionId?: string;
219
+ workspacePath?: string;
220
+ event?: string;
221
+ payload?: Record<string, unknown>;
222
+ metadata?: Record<string, unknown>;
223
+ }
224
+ export interface HookRegisterResponse {
225
+ registered: RegisteredHook;
226
+ captureResult?: {
227
+ hookId: string;
228
+ l0RecordedCount: number;
229
+ l0RecordId: string;
230
+ flushedWorkingMemory: boolean;
231
+ };
232
+ }
233
+ export interface HookStatusParams {
234
+ source?: HostHookSource;
235
+ userId?: string;
236
+ }
237
+ export interface HookStatusResponse {
238
+ hooks: RegisteredHook[];
239
+ }
240
+ export type ExportMemoriesResponse = MemoryExport;
241
+ export type ImportMemoriesRequest = MemoryImport;
242
+ export type ImportMemoriesResponse = ImportResult;
243
+ export interface ActiveSessionInfo {
244
+ sessionKey: string;
245
+ workspaceId: string;
246
+ updatedAt: string;
247
+ }
248
+ export interface ActiveSessionsResponse {
249
+ sessions: ActiveSessionInfo[];
250
+ }
251
+ export type SkillActivationsResponse = SkillActivationRecord[];
package/dist/api.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ export * from "./memory.js";
2
+ export * from "./store.js";
3
+ export * from "./api.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./memory.js";
2
+ export * from "./store.js";
3
+ export * from "./api.js";
@@ -0,0 +1,391 @@
1
+ /**
2
+ * BrainRouter Memory Types
3
+ *
4
+ * Defines the types and boundaries for the BrainRouter memory engine.
5
+ * Inspired by the reference architecture but scoped explicitly for MCP + Multi-tenant.
6
+ */
7
+ export interface BrainRouterMemoryContext {
8
+ /** User identifier — REQUIRED. Enables multi-tenant isolation. */
9
+ userId: string;
10
+ /** Session identifier (unique per conversation session). */
11
+ sessionKey: string;
12
+ /** Sub-session identifier (optional). */
13
+ sessionId?: string;
14
+ /** Which BrainRouter skill is currently active (if any) */
15
+ activeSkill?: string;
16
+ }
17
+ export interface SensoryRecord {
18
+ id: string;
19
+ userId: string;
20
+ sessionKey: string;
21
+ sessionId: string;
22
+ role: string;
23
+ messageText: string;
24
+ recordedAt: string;
25
+ timestamp: number;
26
+ skillTag: string;
27
+ }
28
+ export type MemoryType = "persona" | "episodic" | "instruction" | "skill_context" | "tool_preference" | "codebase_fact" | "api_contract" | "data_model" | "dependency_constraint" | "environment_constraint" | "architecture_decision" | "implementation_decision" | "design_constraint" | "security_policy" | "performance_baseline" | "bug_finding" | "debug_trace" | "fix_summary" | "verification_result" | "failed_attempt" | "regression_risk" | "task_state" | "handover_note" | "blocked_reason" | "review_comment" | "release_note" | "source_evidence" | "artifact_reference" | "file_history" | "command_knowledge";
29
+ export type MemoryStatus = "active" | "superseded" | "archived" | "needs_verification";
30
+ export type MemorySourceKind = "" | "user_instruction" | "source_file" | "command_output" | "test_result" | "model_inference" | "prior_memory";
31
+ export type MemoryVerificationStatus = "" | "verified" | "unverified" | "stale";
32
+ export type EvidenceKind = "file" | "command" | "url" | "test" | "benchmark" | "memory" | "other";
33
+ export interface EvidenceRef {
34
+ kind: EvidenceKind;
35
+ ref: string;
36
+ }
37
+ export interface CognitiveRecord {
38
+ id: string;
39
+ userId: string;
40
+ sessionKey: string;
41
+ sessionId: string;
42
+ content: string;
43
+ type: MemoryType;
44
+ priority: number;
45
+ sceneName: string;
46
+ skillTag: string;
47
+ halfLifeDays: number | null;
48
+ supersededBy: string | null;
49
+ invalidAt?: string | null;
50
+ timestampStr: string;
51
+ timestampStart: string;
52
+ timestampEnd: string;
53
+ createdTime: string;
54
+ updatedTime: string;
55
+ metadata: Record<string, unknown>;
56
+ confidence: number;
57
+ status: MemoryStatus;
58
+ sourceKind: MemorySourceKind;
59
+ verificationStatus: MemoryVerificationStatus;
60
+ repoPaths: string[];
61
+ filePaths: string[];
62
+ commands: string[];
63
+ citationCount: number;
64
+ lastCitedAt: string | null;
65
+ neverCitedCount: number;
66
+ archived: boolean;
67
+ }
68
+ export interface MemoryEvidence {
69
+ id: string;
70
+ userId: string;
71
+ recordId: string;
72
+ kind: EvidenceKind;
73
+ ref: string;
74
+ excerpt: string;
75
+ observedAt: string;
76
+ metadata: Record<string, unknown>;
77
+ }
78
+ export interface MemoryOperation {
79
+ id: string;
80
+ userId: string;
81
+ recordId: string | null;
82
+ operation: string;
83
+ actor: string;
84
+ sessionKey: string;
85
+ reason: string;
86
+ createdAt: string;
87
+ metadata: Record<string, unknown>;
88
+ }
89
+ export interface MemoryExport {
90
+ version: 1;
91
+ exportedAt: string;
92
+ userId: string;
93
+ memories: CognitiveRecord[];
94
+ evidence: MemoryEvidence[];
95
+ operations: MemoryOperation[];
96
+ }
97
+ export interface MemoryImport {
98
+ version: 1;
99
+ memories: CognitiveRecord[];
100
+ evidence?: MemoryEvidence[];
101
+ operations?: MemoryOperation[];
102
+ }
103
+ export interface ImportResult {
104
+ importedMemories: number;
105
+ importedEvidence: number;
106
+ importedOperations: number;
107
+ }
108
+ export interface DiagnosticsBundle {
109
+ timestamp: string;
110
+ sqliteVersion: string;
111
+ nodeVersion: string;
112
+ databaseStats: {
113
+ userStats: {
114
+ total: number;
115
+ archived: number;
116
+ byType: Record<string, number>;
117
+ citationRate: number;
118
+ lastRecallAt: string | null;
119
+ extraction: ExtractionStatus;
120
+ };
121
+ };
122
+ envKeys: string[];
123
+ recentErrors: MemoryOperation[];
124
+ }
125
+ export interface VectorSearchResult {
126
+ record_id: string;
127
+ user_id: string;
128
+ content: string;
129
+ type: string;
130
+ priority: number;
131
+ scene_name: string;
132
+ skill_tag: string;
133
+ score: number;
134
+ timestamp_str: string;
135
+ timestamp_start: string;
136
+ timestamp_end: string;
137
+ session_key: string;
138
+ session_id: string;
139
+ metadata_json: string;
140
+ created_time: string;
141
+ }
142
+ export interface CognitiveFtsResult {
143
+ record_id: string;
144
+ user_id: string;
145
+ content: string;
146
+ type: string;
147
+ priority: number;
148
+ scene_name: string;
149
+ skill_tag: string;
150
+ score: number;
151
+ timestamp_str: string;
152
+ timestamp_start: string;
153
+ timestamp_end: string;
154
+ session_key: string;
155
+ session_id: string;
156
+ metadata_json: string;
157
+ created_time: string;
158
+ /** ACE feedback: number of times this memory was cited by the agent. */
159
+ citation_count?: number;
160
+ }
161
+ export interface RecalledMemory {
162
+ content: string;
163
+ score: number;
164
+ type: string;
165
+ recordId: string;
166
+ skillTag?: string;
167
+ }
168
+ export type MemoryTaskIntent = "build" | "debug" | "review" | "test" | "plan" | "refactor" | "security" | "performance" | "release";
169
+ export interface RecallExplanation {
170
+ /** Number of FTS5 BM25 hits returned before RRF merge. */
171
+ ftsHits: number;
172
+ /** Number of vector search hits returned before RRF merge. */
173
+ vecHits: number;
174
+ /** Number of file-path expansion hits. */
175
+ filePathHits: number;
176
+ /** Top RRF fusion score (pre-decay). */
177
+ rrfTopScore: number;
178
+ /** Task intent detected from the query. */
179
+ intentDetected: MemoryTaskIntent | "none";
180
+ /** Memory types that received an intent boost (type → multiplier). */
181
+ typeBoosts: Record<string, number>;
182
+ /** Whether the active skill triggered a 1.2× skill boost. */
183
+ skillBoostApplied: boolean;
184
+ /** Whether the neural reranker was used in Stage 3. */
185
+ rerankerUsed: boolean;
186
+ /** Whether graph context expansion was appended. */
187
+ graphExpansion: boolean;
188
+ /** Per-record citation boost contribution (recordId → boost). */
189
+ citationBoosts: Record<string, number>;
190
+ /** Total recall pipeline duration in milliseconds. */
191
+ durationMs: number;
192
+ /** Number of candidates sent to reranker (pre-filter). */
193
+ rerankerCandidates: number;
194
+ /** Final ranked records (recordId → finalScore). */
195
+ scoredRecords: Array<{
196
+ recordId: string;
197
+ finalScore: number;
198
+ type: string;
199
+ }>;
200
+ /**
201
+ * Per-node trace of the neural-spark spreading activation pass.
202
+ *
203
+ * Each entry carries the node id, its final potential (clamped to [0, 1]),
204
+ * whether it crossed the firing threshold, and human-readable label fields
205
+ * so the UI can show "codebase_fact · the cli uses sqlite for…" instead of
206
+ * an opaque record id. The full id stays on the entry for click-through.
207
+ *
208
+ * Order is: initial seeds first (whether or not they fired), then propagated
209
+ * nodes that fired via 2-hop excitation.
210
+ */
211
+ sparkedNodes?: Array<{
212
+ id: string;
213
+ potential: number;
214
+ fired: boolean;
215
+ /** Memory type, e.g. "codebase_fact", "instruction". */
216
+ type?: string;
217
+ /** Optional short content preview (≤ 100 chars, single-line). */
218
+ preview?: string;
219
+ /** Optional focus-scene name the memory belongs to. */
220
+ sceneName?: string;
221
+ }>;
222
+ }
223
+ export interface RecallResult {
224
+ /** Cognitive relevant memories — prepended to user prompt text (dynamic, per-turn). */
225
+ prependContext?: string;
226
+ /** Stable recall context appended to system prompt (core identity, focus nav, tools guide). */
227
+ appendSystemContext?: string;
228
+ /** Recalled Cognitive memories with scores (for metrics/debugging). */
229
+ recalledCognitiveMemories?: RecalledMemory[];
230
+ /** Strategy used. Phase 1 = keyword. */
231
+ recallStrategy: string;
232
+ /** Core identity markdown (for metrics/debugging). */
233
+ coreIdentitySummary?: string;
234
+ /** Current most active focus scene name (for metrics/debugging). */
235
+ activeFocusName?: string;
236
+ /** Full recall pipeline explanation (populated in explain mode or always). */
237
+ recallExplanation?: RecallExplanation;
238
+ }
239
+ /**
240
+ * Outcome of the cognitive extraction step for a single capture call. Lets
241
+ * the CLI distinguish "the LLM said nothing notable here" (ok, zero records)
242
+ * from "the LLM call itself failed" (failed) from "extraction wasn't tried
243
+ * this turn" (skipped — below the every-N-turns threshold).
244
+ */
245
+ export type CognitiveExtractionStatus = "ok" | "failed" | "skipped";
246
+ export interface CaptureResult {
247
+ /** Number of Sensory messages recorded. */
248
+ sensoryRecordedCount: number;
249
+ /** Whether Cognitive extraction was triggered this turn. */
250
+ cognitiveExtractionTriggered: boolean;
251
+ /** Number of Cognitive memories extracted (if triggered). */
252
+ cognitiveExtractedCount: number;
253
+ /**
254
+ * Status of the extraction LLM call. `ok` means it ran and returned a
255
+ * (possibly empty) list of records. `failed` means the LLM call itself
256
+ * errored. `skipped` means we didn't try this turn. Callers should only
257
+ * surface a warning to the user on `failed`.
258
+ */
259
+ cognitiveExtractionStatus?: CognitiveExtractionStatus;
260
+ /** Error string when status === "failed", for diagnostic display. */
261
+ cognitiveExtractionError?: string;
262
+ }
263
+ export interface EmbeddingServiceConfig {
264
+ endpoint?: string;
265
+ apiKey?: string;
266
+ model?: string;
267
+ dimensions?: number;
268
+ }
269
+ export interface RerankerServiceConfig {
270
+ endpoint?: string;
271
+ apiKey?: string;
272
+ model?: string;
273
+ topN?: number;
274
+ }
275
+ export interface SkillHintsRecord {
276
+ skillName: string;
277
+ hints: string;
278
+ sourceFile: string;
279
+ registeredAt: string;
280
+ }
281
+ export interface SkillActivationRecord {
282
+ skillName: string;
283
+ potential: number;
284
+ lastDecayTime: string;
285
+ }
286
+ export interface UserRecord {
287
+ userId: string;
288
+ apiKey: string;
289
+ passwordHash: string | null;
290
+ displayName: string;
291
+ email: string;
292
+ isAdmin: boolean;
293
+ status: "active" | "disabled";
294
+ createdAt: string;
295
+ }
296
+ export interface PublicUserRecord {
297
+ userId: string;
298
+ displayName: string;
299
+ email: string;
300
+ isAdmin: boolean;
301
+ status: "active" | "disabled";
302
+ createdAt: string;
303
+ }
304
+ export interface LLMRunParams {
305
+ prompt: string;
306
+ systemPrompt?: string;
307
+ taskId: string;
308
+ timeoutMs?: number;
309
+ }
310
+ export interface LLMRunner {
311
+ run(params: LLMRunParams): Promise<string>;
312
+ }
313
+ export interface ContextualFocusRecord {
314
+ id: string;
315
+ userId: string;
316
+ sceneName: string;
317
+ summaryMd: string;
318
+ heatScore: number;
319
+ lastActiveTime: string;
320
+ createdTime: string;
321
+ updatedTime: string;
322
+ }
323
+ export interface CoreIdentityRecord {
324
+ userId: string;
325
+ personaMd: string;
326
+ cognitiveCountAtGeneration: number;
327
+ createdTime: string;
328
+ updatedTime: string;
329
+ }
330
+ export interface ContradictionRecord {
331
+ id: string;
332
+ user_id?: string;
333
+ userId?: string;
334
+ record_id_a?: string;
335
+ recordIdA?: string;
336
+ record_id_b?: string;
337
+ recordIdB?: string;
338
+ reason: string;
339
+ confidence: number;
340
+ status?: "pending" | "resolved" | "dismissed";
341
+ created_time?: string;
342
+ createdTime?: string;
343
+ content_a?: string;
344
+ contentA?: string;
345
+ content_b?: string;
346
+ contentB?: string;
347
+ }
348
+ export interface SchedulerState {
349
+ cognitiveCountSinceLastFocus: number;
350
+ cognitiveCountSinceLastIdentity: number;
351
+ totalCognitiveCount: number;
352
+ extractionErrors: number;
353
+ lastErrorMessage: string | null;
354
+ lastErrorAt: string | null;
355
+ }
356
+ export interface StalledExtractionBacklog {
357
+ userId: string;
358
+ sessionKey: string;
359
+ sessionId: string;
360
+ unextractedCount: number;
361
+ latestRecordedAt: string;
362
+ extractionErrors: number;
363
+ lastErrorMessage: string | null;
364
+ }
365
+ export interface ExtractionStatus {
366
+ extractionErrors: number;
367
+ lastErrorMessage: string | null;
368
+ lastErrorAt: string | null;
369
+ syncPaused: boolean;
370
+ }
371
+ export interface GraphNode {
372
+ id: string;
373
+ userId: string;
374
+ entity: string;
375
+ entityType: string;
376
+ skillTag: string;
377
+ confidence: number;
378
+ sourceRecordId: string;
379
+ createdTime: string;
380
+ }
381
+ export interface GraphEdge {
382
+ id: string;
383
+ userId: string;
384
+ fromNodeId: string;
385
+ toNodeId: string;
386
+ relation: string;
387
+ skillTag: string;
388
+ confidence: number;
389
+ sourceRecordId: string;
390
+ createdTime: string;
391
+ }
package/dist/memory.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * BrainRouter Memory Types
3
+ *
4
+ * Defines the types and boundaries for the BrainRouter memory engine.
5
+ * Inspired by the reference architecture but scoped explicitly for MCP + Multi-tenant.
6
+ */
7
+ export {};
@@ -0,0 +1,195 @@
1
+ import type { GraphEdge, GraphNode, ContradictionRecord, ImportResult, SensoryRecord, CognitiveFtsResult, CognitiveRecord, ContextualFocusRecord, CoreIdentityRecord, MemoryEvidence, MemoryExport, MemoryImport, ExtractionStatus, MemoryOperation, MemoryStatus, SchedulerState, SkillActivationRecord, SkillHintsRecord, StalledExtractionBacklog, UserRecord, VectorSearchResult } from "./memory.js";
2
+ export interface CursorPaginationOptions<TCursor = Record<string, unknown>> {
3
+ cursor?: TCursor;
4
+ limit: number;
5
+ }
6
+ export interface CursorPage<T> {
7
+ items: T[];
8
+ nextCursor: string | null;
9
+ hasMore: boolean;
10
+ }
11
+ export interface MemoryListFilters {
12
+ query?: string;
13
+ type?: string;
14
+ scene?: string;
15
+ skill?: string;
16
+ archived?: boolean;
17
+ }
18
+ export interface MemoryListItem {
19
+ recordId: string;
20
+ content: string;
21
+ type: string;
22
+ priority: number;
23
+ sceneName: string;
24
+ skillTag: string;
25
+ createdTime: string;
26
+ citationCount: number;
27
+ neverCitedCount: number;
28
+ archived: boolean;
29
+ }
30
+ export interface EvidenceListFilters {
31
+ recordId?: string;
32
+ kind?: string;
33
+ }
34
+ export interface OperationLogFilters {
35
+ operation?: string;
36
+ sessionKey?: string;
37
+ createdAfter?: string;
38
+ createdBefore?: string;
39
+ }
40
+ export interface IMemoryStore {
41
+ init(): void;
42
+ initVec(dimensions: number): void;
43
+ reembedStaleRecords(embedder: (text: string) => Promise<Float32Array>): Promise<number>;
44
+ getSqliteVersion(): string;
45
+ upsertSensory(record: SensoryRecord): void;
46
+ getRecentSensoryMessages(userId: string, sessionKey: string, limit: number, afterIsoTime?: string): SensoryRecord[];
47
+ getUnextractedSensoryCount(userId: string, sessionKey: string): number;
48
+ markSensoryExtracted(userId: string, sessionKey: string, recordIds: string[], extractedAt?: string): void;
49
+ upsertCognitive(record: CognitiveRecord, options?: {
50
+ skipAudit?: boolean;
51
+ }): void;
52
+ /** Batch upsert with optional embedding vectors. Pass skipAudit to suppress per-record
53
+ * cognitive_upsert noise when the caller will write a higher-level audit entry itself. */
54
+ upsertCognitiveBatch(entries: Array<{
55
+ record: CognitiveRecord;
56
+ embedding?: Float32Array;
57
+ }>, options?: {
58
+ skipAudit?: boolean;
59
+ }): void;
60
+ invalidateCognitiveRecord(userId: string, recordId: string, supersededById: string): void;
61
+ getMemoryById(userId: string, recordId: string): CognitiveRecord | null;
62
+ getMemoriesByFilePath(userId: string, filePath: string, limit: number): CognitiveRecord[];
63
+ updateCognitiveConfidence(userId: string, recordId: string, confidence: number, status: MemoryStatus): void;
64
+ insertEvidence(ev: MemoryEvidence): void;
65
+ getEvidenceByRecord(userId: string, recordId: string): MemoryEvidence[];
66
+ listEvidence(userId: string, filters?: EvidenceListFilters, pagination?: CursorPaginationOptions<{
67
+ observedAt: string;
68
+ id: string;
69
+ }>): MemoryEvidence[];
70
+ /** Write an audit operation. Kept on the interface because the engine layer needs to
71
+ * correlate external events (memory_update, import) with store writes atomically.
72
+ * It is NOT intended for use by any caller outside of SqliteMemoryStore or MemoryEngine. */
73
+ insertOperation(op: MemoryOperation): void;
74
+ getOperationLog(userId: string, options?: CursorPaginationOptions<{
75
+ createdAt: string;
76
+ id: string;
77
+ }>, filters?: OperationLogFilters): MemoryOperation[];
78
+ exportMemories(userId: string): MemoryExport;
79
+ importMemories(userId: string, data: MemoryImport): ImportResult;
80
+ hardDeleteMemory(userId: string, recordId: string, reason: string): void;
81
+ searchCognitiveFts(userId: string, query: string, limit: number): CognitiveFtsResult[];
82
+ searchCognitiveFtsAsOf(userId: string, query: string, limit: number, asOf: string): CognitiveFtsResult[];
83
+ upsertCognitiveVec(recordId: string, embedding: Float32Array): void;
84
+ searchCognitiveVec(userId: string, queryEmbedding: Float32Array, limit: number): VectorSearchResult[];
85
+ upsertContradiction(data: {
86
+ id: string;
87
+ userId: string;
88
+ recordIdA: string;
89
+ recordIdB: string;
90
+ reason: string;
91
+ confidence: number;
92
+ createdTime?: string;
93
+ }): void;
94
+ getPendingContradictions(userId: string, pagination?: CursorPaginationOptions<{
95
+ confidence: number;
96
+ id: string;
97
+ }>): ContradictionRecord[];
98
+ resolveContradiction(id: string, userId: string, status: "resolved" | "dismissed"): void;
99
+ upsertSkillHints(skillName: string, hints: string, sourceFile?: string): void;
100
+ listSkillHints(): SkillHintsRecord[];
101
+ getSkillHints(skillName: string): string | null;
102
+ getSkillActivations(userId: string): SkillActivationRecord[];
103
+ upsertSkillActivations(userId: string, activations: SkillActivationRecord[]): void;
104
+ upsertContextualFocus(record: ContextualFocusRecord): void;
105
+ getTopContextualFocus(userId: string, limit?: number, cursor?: {
106
+ heatScore: number;
107
+ id: string;
108
+ }): ContextualFocusRecord[];
109
+ decayContextualFocusHeatScores(userId: string, decayFactor?: number): void;
110
+ boostContextualFocusHeatScore(userId: string, sceneName: string, boost?: number): void;
111
+ getCognitivesByFocus(userId: string, sceneName: string, limit?: number): any[];
112
+ getContextualFocusCount(userId: string): number;
113
+ getColdContextualFocus(userId: string, limit: number): ContextualFocusRecord[];
114
+ deleteContextualFocus(userId: string, sceneIds: string[]): void;
115
+ getContextualFocusByName(userId: string, sceneName: string): ContextualFocusRecord | null;
116
+ getDistinctSceneNames(userId: string): string[];
117
+ renameFocusInCognitiveRecords(userId: string, oldName: string, canonicalName: string): void;
118
+ upsertCoreIdentity(record: CoreIdentityRecord): void;
119
+ getCoreIdentity(userId: string): CoreIdentityRecord | null;
120
+ getIdentityAndInstructionCognitives(userId: string, limit?: number): any[];
121
+ getSchedulerState(userId: string): SchedulerState;
122
+ incrementSchedulerCognitiveCount(userId: string, count: number): void;
123
+ resetSchedulerFocusCount(userId: string): void;
124
+ resetSchedulerIdentityCount(userId: string): void;
125
+ recordExtractionFailure(userId: string, message: string): void;
126
+ resetExtractionFailures(userId: string): void;
127
+ getExtractionStatus(userId: string): ExtractionStatus;
128
+ sweepUnextractedBacklog(options: {
129
+ olderThanMs: number;
130
+ minUnextracted?: number;
131
+ maxFailures?: number;
132
+ limit?: number;
133
+ }): StalledExtractionBacklog[];
134
+ getAllGraphNodes(userId: string): GraphNode[];
135
+ upsertGraphNode(node: GraphNode): void;
136
+ upsertGraphEdge(edge: GraphEdge): void;
137
+ getGraphNodeByEntity(userId: string, entity: string): GraphNode | null;
138
+ getGraphNeighbors(userId: string, entityId: string, skillTag?: string, maxHops?: number): {
139
+ nodes: GraphNode[];
140
+ edges: GraphEdge[];
141
+ };
142
+ markCited(userId: string, recordIds: string[]): void;
143
+ incrementNeverCited(userId: string, recordIds: string[]): {
144
+ recordId: string;
145
+ neverCitedCount: number;
146
+ }[];
147
+ archiveCognitiveRecord(userId: string, recordId: string): void;
148
+ getRecentSkillContextCognitives(userId: string, limit: number): {
149
+ skillTag: string;
150
+ createdTime: string;
151
+ }[];
152
+ createUser(userId: string, apiKey: string, displayName?: string, isAdmin?: boolean): UserRecord;
153
+ getUserByApiKey(apiKey: string): UserRecord | null;
154
+ getUserByEmail(email: string): UserRecord | null;
155
+ getUserById(userId: string): UserRecord | null;
156
+ updateUserPassword(userId: string, passwordHash: string): void;
157
+ updateUserEmail(userId: string, email: string): void;
158
+ updateUserDisplayName(userId: string, displayName: string): void;
159
+ updateUserStatus(userId: string, status: "active" | "disabled"): void;
160
+ updateUserApiKey(userId: string, apiKey: string): void;
161
+ listUsers(pagination?: CursorPaginationOptions<{
162
+ createdAt: string;
163
+ userId: string;
164
+ }>): UserRecord[];
165
+ deleteUser(userId: string): void;
166
+ listMemories(userId: string, filters?: MemoryListFilters, pagination?: CursorPaginationOptions<{
167
+ createdTime: string;
168
+ recordId: string;
169
+ }>): MemoryListItem[];
170
+ getMemoryStats(userId: string): {
171
+ total: number;
172
+ archived: number;
173
+ byType: Record<string, number>;
174
+ citationRate: number;
175
+ lastRecallAt: string | null;
176
+ extraction: ExtractionStatus;
177
+ };
178
+ upsertConnection(userId: string, sourceId: string, targetId: string, weight: number): void;
179
+ getConnectionsForSource(userId: string, sourceId: string): Array<{
180
+ targetId: string;
181
+ weight: number;
182
+ }>;
183
+ strengthenConnectionsBatch(userId: string, pairs: Array<{
184
+ source: string;
185
+ target: string;
186
+ }>, delta: number): void;
187
+ decayConnections(userId: string, decayFactor: number): void;
188
+ pruneConnections(userId: string, threshold: number): void;
189
+ getAllConnections(userId: string): Array<{
190
+ sourceId: string;
191
+ targetId: string;
192
+ weight: number;
193
+ lastActivatedAt: string;
194
+ }>;
195
+ }
package/dist/store.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@kinqs/brainrouter-types",
3
+ "version": "0.3.4",
4
+ "description": "Shared TypeScript types for BrainRouter — used by the CLI, MCP server, and SDK.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsc -p tsconfig.json",
13
+ "prepack": "npm run build"
14
+ },
15
+ "devDependencies": {
16
+ "typescript": "^5.5.4"
17
+ },
18
+ "keywords": [
19
+ "brainrouter",
20
+ "types",
21
+ "typescript"
22
+ ],
23
+ "license": "MIT",
24
+ "author": "BrainRouter contributors",
25
+ "homepage": "https://github.com/kinqsradiollc/BrainRouter#readme",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/kinqsradiollc/BrainRouter.git",
29
+ "directory": "packages/types"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/kinqsradiollc/BrainRouter/issues"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ }
37
+ }