@3ngram/server 0.7.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.
Files changed (116) hide show
  1. package/LICENSE +202 -0
  2. package/dist/app.d.ts +72 -0
  3. package/dist/app.js +273 -0
  4. package/dist/app.js.map +1 -0
  5. package/dist/boot.d.ts +37 -0
  6. package/dist/boot.js +53 -0
  7. package/dist/boot.js.map +1 -0
  8. package/dist/composition/extension.d.ts +50 -0
  9. package/dist/composition/extension.js +16 -0
  10. package/dist/composition/extension.js.map +1 -0
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +10 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/links.d.ts +17 -0
  15. package/dist/links.js +46 -0
  16. package/dist/links.js.map +1 -0
  17. package/dist/mailer.d.ts +58 -0
  18. package/dist/mailer.js +187 -0
  19. package/dist/mailer.js.map +1 -0
  20. package/dist/mcp/errors.d.ts +14 -0
  21. package/dist/mcp/errors.js +175 -0
  22. package/dist/mcp/errors.js.map +1 -0
  23. package/dist/mcp/prompts.d.ts +29 -0
  24. package/dist/mcp/prompts.js +180 -0
  25. package/dist/mcp/prompts.js.map +1 -0
  26. package/dist/mcp/server.d.ts +14 -0
  27. package/dist/mcp/server.js +34 -0
  28. package/dist/mcp/server.js.map +1 -0
  29. package/dist/mcp/tools-admin.d.ts +8 -0
  30. package/dist/mcp/tools-admin.js +260 -0
  31. package/dist/mcp/tools-admin.js.map +1 -0
  32. package/dist/mcp/tools-orient.d.ts +6 -0
  33. package/dist/mcp/tools-orient.js +110 -0
  34. package/dist/mcp/tools-orient.js.map +1 -0
  35. package/dist/mcp/tools.d.ts +88 -0
  36. package/dist/mcp/tools.js +375 -0
  37. package/dist/mcp/tools.js.map +1 -0
  38. package/dist/middleware/api-key.d.ts +13 -0
  39. package/dist/middleware/api-key.js +83 -0
  40. package/dist/middleware/api-key.js.map +1 -0
  41. package/dist/middleware/api-or-session.d.ts +9 -0
  42. package/dist/middleware/api-or-session.js +22 -0
  43. package/dist/middleware/api-or-session.js.map +1 -0
  44. package/dist/middleware/authenticate.d.ts +21 -0
  45. package/dist/middleware/authenticate.js +51 -0
  46. package/dist/middleware/authenticate.js.map +1 -0
  47. package/dist/middleware/index.d.ts +1 -0
  48. package/dist/middleware/index.js +9 -0
  49. package/dist/middleware/index.js.map +1 -0
  50. package/dist/middleware/oauth-bearer.d.ts +8 -0
  51. package/dist/middleware/oauth-bearer.js +117 -0
  52. package/dist/middleware/oauth-bearer.js.map +1 -0
  53. package/dist/middleware/rate-limit.d.ts +58 -0
  54. package/dist/middleware/rate-limit.js +139 -0
  55. package/dist/middleware/rate-limit.js.map +1 -0
  56. package/dist/middleware/request-context.d.ts +7 -0
  57. package/dist/middleware/request-context.js +14 -0
  58. package/dist/middleware/request-context.js.map +1 -0
  59. package/dist/output-validation.d.ts +18 -0
  60. package/dist/output-validation.js +30 -0
  61. package/dist/output-validation.js.map +1 -0
  62. package/dist/redis.d.ts +9 -0
  63. package/dist/redis.js +37 -0
  64. package/dist/redis.js.map +1 -0
  65. package/dist/rest/cursor.d.ts +14 -0
  66. package/dist/rest/cursor.js +38 -0
  67. package/dist/rest/cursor.js.map +1 -0
  68. package/dist/rest/errors.d.ts +14 -0
  69. package/dist/rest/errors.js +119 -0
  70. package/dist/rest/errors.js.map +1 -0
  71. package/dist/rest/router.d.ts +33 -0
  72. package/dist/rest/router.js +846 -0
  73. package/dist/rest/router.js.map +1 -0
  74. package/dist/rest/scope.d.ts +14 -0
  75. package/dist/rest/scope.js +45 -0
  76. package/dist/rest/scope.js.map +1 -0
  77. package/dist/routes/api-keys.d.ts +2 -0
  78. package/dist/routes/api-keys.js +77 -0
  79. package/dist/routes/api-keys.js.map +1 -0
  80. package/dist/routes/auth.d.ts +20 -0
  81. package/dist/routes/auth.js +325 -0
  82. package/dist/routes/auth.js.map +1 -0
  83. package/dist/routes/capabilities.d.ts +10 -0
  84. package/dist/routes/capabilities.js +17 -0
  85. package/dist/routes/capabilities.js.map +1 -0
  86. package/dist/routes/health.d.ts +7 -0
  87. package/dist/routes/health.js +12 -0
  88. package/dist/routes/health.js.map +1 -0
  89. package/dist/routes/mcp.d.ts +27 -0
  90. package/dist/routes/mcp.js +81 -0
  91. package/dist/routes/mcp.js.map +1 -0
  92. package/dist/routes/oauth-authorize.d.ts +8 -0
  93. package/dist/routes/oauth-authorize.js +245 -0
  94. package/dist/routes/oauth-authorize.js.map +1 -0
  95. package/dist/routes/oauth-clients.d.ts +2 -0
  96. package/dist/routes/oauth-clients.js +59 -0
  97. package/dist/routes/oauth-clients.js.map +1 -0
  98. package/dist/routes/oauth-register.d.ts +8 -0
  99. package/dist/routes/oauth-register.js +59 -0
  100. package/dist/routes/oauth-register.js.map +1 -0
  101. package/dist/routes/oauth-token.d.ts +30 -0
  102. package/dist/routes/oauth-token.js +451 -0
  103. package/dist/routes/oauth-token.js.map +1 -0
  104. package/dist/routes/onboarding.d.ts +2 -0
  105. package/dist/routes/onboarding.js +47 -0
  106. package/dist/routes/onboarding.js.map +1 -0
  107. package/dist/routes/profile.d.ts +2 -0
  108. package/dist/routes/profile.js +35 -0
  109. package/dist/routes/profile.js.map +1 -0
  110. package/dist/routes/well-known.d.ts +2 -0
  111. package/dist/routes/well-known.js +77 -0
  112. package/dist/routes/well-known.js.map +1 -0
  113. package/dist/version.d.ts +1 -0
  114. package/dist/version.js +17 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +67 -0
@@ -0,0 +1,846 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // REST /api/v1 mirror of the core memory tools (ADR-0011
3
+ // "one core, N transports"). A THIN adapter (transports hold zero
4
+ // business logic): each route validates at the ONE boundary (the SAME
5
+ // packages/schema Zod types the MCP tools consume — NO REST-only schemas),
6
+ // calls packages/core (which runs withTenant internally:
7
+ // a route can only ever touch the authenticated key owner's rows), and shapes
8
+ // the JSON mirror of the MCP tool IO.
9
+ //
10
+ // AUTH: mounted BEHIND the EXISTING apiKeyAuth middleware (X-API-Key) — NOT
11
+ // the Bearer/OAuth mount that gates /mcp. apiKeyAuth binds req.userId; a valid
12
+ // key is FULL-ACCESS (rest/scope.ts: the api_keys table has no scope column, so
13
+ // per-route OAuth scope is N/A for v1 keys). The router applies apiKeyAuth to
14
+ // every /api/v1 path itself, so it is mountable independent of the MCP mount.
15
+ //
16
+ // ERRORS: typed core errors map to HTTP status via rest/errors.ts (the MCP
17
+ // reason_code TAXONOMY mapped to HTTP, not the MCP isError function). An unknown
18
+ // error is a generic 500 (crash-safe, no content leaked).
19
+ //
20
+ // PARITY: this ships a SMOKE-level parity guarantee (REST remember -> the
21
+ // same content found via core search); FULL REST≡MCP≡core parity comes later.
22
+ import { log } from '@3ngram/config';
23
+ import { crashSafeError } from '@3ngram/config/otel';
24
+ import { applyProposal, briefing, deleteAccount, describeEnvironment, exportUserData, getBudgetStatus, getCurrentUser, getFacts, getMemoryById, getMemoryHistory, listMemories, listMemoryFacets, listProposals, listScopes, rejectProposal, remember, resolveByMemoryId, revise, search, searchDashboardPage, } from '@3ngram/core';
25
+ import { accountDeleteBodySchema, briefingToolInputSchema, dashboardSearchQuerySchema, factsQueryInputSchema, memoriesListQuerySchema, proposalRejectBodySchema, proposalsListQuerySchema, rememberToolInputSchema, resolveToolInputSchema, reviseToolInputSchema, searchQuerySchema, } from '@3ngram/schema';
26
+ import { Router } from 'express';
27
+ import { z } from 'zod';
28
+ import { apiOrSessionAuth } from '../middleware/api-or-session.js';
29
+ import { decodeCursor, encodeCursor } from './cursor.js';
30
+ import { mapRestError } from './errors.js';
31
+ // A non-UUID :id path segment can never match a stored uuid column, so treat a
32
+ // malformed id the same as an unknown id (404) instead of letting Postgres raise
33
+ // a uuid cast error that guard()'s catch surfaces as a generic 500 (mirrors the
34
+ // apiKeyIdSchema boundary in routes/api-keys.ts).
35
+ const pathIdSchema = z.uuid();
36
+ /** Coerce an optional ISO-8601 string to a Date for the bi-temporal core query. */
37
+ function toDate(value) {
38
+ return value === undefined ? undefined : new Date(value);
39
+ }
40
+ /** Drop keys whose value is undefined so an exactOptional core param type fits. */
41
+ function defined(obj) {
42
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
43
+ }
44
+ /** Map a schema asOf (ISO strings) to the core/db Date coordinates, or undefined. */
45
+ function toAsOf(asOf) {
46
+ if (asOf === undefined)
47
+ return undefined;
48
+ return defined({ validAt: toDate(asOf.validAt), asKnownAt: toDate(asOf.asKnownAt) });
49
+ }
50
+ function historyIdentity(memory) {
51
+ return {
52
+ id: memory.id,
53
+ memoryType: memory.memoryType,
54
+ topic: memory.topic,
55
+ project: memory.project ?? null,
56
+ scope: memory.scope,
57
+ status: memory.status,
58
+ validFrom: memory.validFrom.toISOString(),
59
+ validTo: memory.validTo?.toISOString() ?? null,
60
+ recordedAt: memory.recordedAt.toISOString(),
61
+ createdAt: memory.createdAt.toISOString(),
62
+ isCurrent: memory.isCurrent,
63
+ lifecycleState: memory.lifecycleState,
64
+ };
65
+ }
66
+ function historyEdge(edge) {
67
+ return {
68
+ id: edge.id,
69
+ fromId: edge.fromId,
70
+ toId: edge.toId,
71
+ edgeType: edge.edgeType,
72
+ createdBy: edge.createdBy,
73
+ createdAt: edge.createdAt.toISOString(),
74
+ };
75
+ }
76
+ function historyRelationship(relationship) {
77
+ return {
78
+ memory: historyIdentity(relationship.memory),
79
+ edge: historyEdge(relationship.edge),
80
+ };
81
+ }
82
+ /** The authenticated tenant — apiKeyAuth has bound req.userId before any handler runs. */
83
+ function tenant(req) {
84
+ return req.userId;
85
+ }
86
+ /**
87
+ * Run a route handler with uniform typed-error -> HTTP mapping. A KNOWN typed
88
+ * core error becomes its mapped status + reason_code body (rest/errors.ts); an
89
+ * UNKNOWN error is logged crash-safe (no content) and surfaced as a
90
+ * generic 500. Handlers never log content themselves.
91
+ */
92
+ async function guard(route, res, handler) {
93
+ try {
94
+ await handler();
95
+ }
96
+ catch (err) {
97
+ const mapped = mapRestError(route, err);
98
+ if (mapped !== undefined) {
99
+ res.status(mapped.status).json({ error: mapped.reason });
100
+ return;
101
+ }
102
+ log().error({ route, ...crashSafeError(err) }, 'rest: handler failed');
103
+ if (!res.headersSent)
104
+ res.status(500).json({ error: 'internal_error' });
105
+ }
106
+ }
107
+ /**
108
+ * Build the /api/v1 REST router. Every route is guarded by apiOrSessionAuth
109
+ * (applied at the router level), so the whole mirror is reachable with EITHER a
110
+ * valid X-API-Key (C3) OR a session Bearer token (C2, from POST /auth/login) —
111
+ * both bind req.userId identically. The mount stays independent of the MCP Bearer
112
+ * (OAuth) mount.
113
+ */
114
+ export function restRouter(options) {
115
+ const router = Router();
116
+ // Per-key rate-limiter: mounted BEFORE apiOrSessionAuth so the bucket
117
+ // is the cheapest first gate. Requests without req.apiKeyId (session Bearer)
118
+ // skip it transparently (undefined key -> pass through).
119
+ if (options.rateLimiter !== undefined) {
120
+ router.use('/api/v1', options.rateLimiter);
121
+ }
122
+ // Combined auth on EVERY /api/v1 path: X-API-Key OR session
123
+ // Bearer. Mounted here (not in app.ts) so the router is self-contained and
124
+ // mountable independent of the MCP Bearer mount.
125
+ router.use('/api/v1', apiOrSessionAuth);
126
+ // POST /api/v1/memories — remember (mirrors the MCP remember tool). Core
127
+ // remember() is THE validation boundary; we re-parse here only to echo the
128
+ // NORMALIZED write (scope default + null project) in the response, exactly as
129
+ // the MCP tool does. Embedding is ack-before-embed: never awaited.
130
+ router.post('/api/v1/memories', (req, res) => {
131
+ void guard('memories', res, async () => {
132
+ const input = rememberToolInputSchema.parse(req.body);
133
+ // Budget is wired alongside the gateway: it gates the embed this write will
134
+ // kick, so it applies only when there is an embed to incur cost. The access
135
+ // gate is threaded independently (even on the embeddings-off path) so the
136
+ // write access guard runs on every write (no bypass).
137
+ const gatewayOpts = options.gateway === undefined
138
+ ? { access: options.access }
139
+ : { gateway: options.gateway, budget: options.budget, access: options.access };
140
+ const written = await remember(tenant(req), input, 'user_api', gatewayOpts);
141
+ void written.embed.settled.catch(() => false);
142
+ const embedded = options.gateway === undefined ? 'off' : 'pending';
143
+ res.status(201).json(defined({
144
+ memory: {
145
+ id: written.id,
146
+ memoryType: input.memoryType,
147
+ topic: input.topic,
148
+ scope: input.scope,
149
+ project: input.project ?? null,
150
+ },
151
+ embedded,
152
+ commitmentId: written.commitmentId,
153
+ }));
154
+ });
155
+ });
156
+ // GET /api/v1/memories — bounded LIVE-memory list for the dashboard.
157
+ // Query params (limit/offset/type/scope/project/status) arrive as
158
+ // strings over a GET; the numeric ones are coerced BEFORE the single parse
159
+ // against memoriesListQuerySchema. Core listMemories runs the
160
+ // page + its unpaged total in one withTenant tx; the route shapes the
161
+ // identity-only envelope (NO content).
162
+ // `project` may appear once (string) or repeated (?project=a&project=b → string[])
163
+ // — the schema accepts both; the db layer uses eq/inArray accordingly.
164
+ router.get('/api/v1/memories', (req, res) => {
165
+ void guard('memories.list', res, async () => {
166
+ const query = memoriesListQuerySchema.parse(defined({
167
+ limit: req.query.limit === undefined ? undefined : Number(req.query.limit),
168
+ offset: req.query.offset === undefined ? undefined : Number(req.query.offset),
169
+ type: req.query.type,
170
+ scope: req.query.scope,
171
+ project: req.query.project,
172
+ status: req.query.status,
173
+ }));
174
+ // ACCESS GUARD: read access is asserted BEFORE the db op runs (self-host
175
+ // allowAllAccess allows all; back-compat null-guard when no gate is wired).
176
+ if (options.access)
177
+ await options.access.assertRead(tenant(req));
178
+ // The schema names the filter `type`; the core/db query names it
179
+ // `memoryType` (the column). Bridge here so the wire stays dashboard-facing.
180
+ // limit/offset carry schema defaults (always present); the OPTIONAL filters
181
+ // are stripped of undefined keys so the exactOptional db query type fits.
182
+ const page = await listMemories(tenant(req), {
183
+ limit: query.limit,
184
+ offset: query.offset,
185
+ ...defined({
186
+ memoryType: query.type,
187
+ scope: query.scope,
188
+ project: query.project,
189
+ status: query.status,
190
+ }),
191
+ });
192
+ res.status(200).json({
193
+ memories: page.memories.map((memory) => ({
194
+ id: memory.id,
195
+ memoryType: memory.memoryType,
196
+ topic: memory.topic,
197
+ project: memory.project ?? null,
198
+ scope: memory.scope,
199
+ status: memory.status,
200
+ ...(memory.commitmentStatus === undefined || memory.commitmentStatus === null
201
+ ? {}
202
+ : { commitmentStatus: memory.commitmentStatus }),
203
+ recordedAt: memory.recordedAt.toISOString(),
204
+ createdAt: memory.createdAt.toISOString(),
205
+ })),
206
+ count: page.memories.length,
207
+ total: page.total,
208
+ });
209
+ });
210
+ });
211
+ // GET /api/v1/memories/facets — DISTINCT scope + project values from the
212
+ // tenant's LIVE memories. Registered BEFORE /:id so Express
213
+ // does not match "facets" as an :id param. Returns {scopes, projects} arrays
214
+ // ordered ASC. Content discipline: only user-defined labels.
215
+ router.get('/api/v1/memories/facets', (req, res) => {
216
+ void guard('memories.facets', res, async () => {
217
+ // ACCESS GUARD: facets expose the tenant's scope/project labels
218
+ // (memory-derived), so read access is asserted BEFORE the read (self-host
219
+ // allowAllAccess allows all).
220
+ if (options.access)
221
+ await options.access.assertRead(tenant(req));
222
+ const facets = await listMemoryFacets(tenant(req));
223
+ res.status(200).json({ scopes: facets.scopes, projects: facets.projects });
224
+ });
225
+ });
226
+ // GET /api/v1/scopes — list the tenant's registered scopes.
227
+ router.get('/api/v1/scopes', (req, res) => {
228
+ void guard('scopes.list', res, async () => {
229
+ // ACCESS GUARD: the scope registry is per-tenant user data, so read access
230
+ // is asserted BEFORE the read (self-host allowAllAccess allows all); parity
231
+ // with the MCP configure_scope list action.
232
+ if (options.access)
233
+ await options.access.assertRead(tenant(req));
234
+ const scopes = await listScopes(tenant(req));
235
+ res.status(200).json({
236
+ scopes: scopes.map((s) => ({
237
+ id: s.id,
238
+ name: s.name,
239
+ aliases: s.aliases,
240
+ createdAt: s.createdAt.toISOString(),
241
+ })),
242
+ count: scopes.length,
243
+ });
244
+ });
245
+ });
246
+ // GET /api/v1/memories/:id/history — identity-only lineage + audit trail for
247
+ // dashboard detail. Registered before /:id for route clarity. Returns no
248
+ // content and no raw audit payload values: only identity fields, typed edges,
249
+ // event kind/actor/time, and payload metadata.
250
+ router.get('/api/v1/memories/:id/history', (req, res) => {
251
+ void guard('memories.history', res, async () => {
252
+ const id = pathIdSchema.safeParse(req.params.id);
253
+ if (!id.success) {
254
+ res.status(404).json({ error: 'not_found' });
255
+ return;
256
+ }
257
+ // ACCESS GUARD: history exposes lineage + audit, so read access is asserted
258
+ // BEFORE the read (self-host allowAllAccess allows all); matches the inspect
259
+ // (getMemoryById) guard.
260
+ if (options.access)
261
+ await options.access.assertRead(tenant(req));
262
+ const history = await getMemoryHistory(tenant(req), id.data);
263
+ // Partial-failure degrades to 200 with `sections` flags. Emit a
264
+ // content-free signal (id + status + error class name only)
265
+ // when a section is unavailable so ops can see degradation without a 500.
266
+ if (history.sections.lineage === 'unavailable' || history.sections.events === 'unavailable') {
267
+ log().warn({
268
+ route: 'memories.history',
269
+ memoryId: id.data,
270
+ sections: history.sections,
271
+ sectionErrors: history.sectionErrors ?? {},
272
+ }, 'rest: memory history degraded');
273
+ }
274
+ res.status(200).json({
275
+ memory: historyIdentity(history.memory),
276
+ lineage: {
277
+ nodes: history.lineage.nodes.map(historyIdentity),
278
+ edges: history.lineage.edges.map(historyEdge),
279
+ truncated: history.lineage.truncated,
280
+ },
281
+ directRelationships: {
282
+ predecessors: history.directRelationships.predecessors.map(historyRelationship),
283
+ successors: history.directRelationships.successors.map(historyRelationship),
284
+ truncated: history.directRelationships.truncated,
285
+ },
286
+ auditEvents: history.auditEvents.map((event) => ({
287
+ id: event.id,
288
+ eventKind: event.eventKind,
289
+ actorKind: event.actorKind,
290
+ createdAt: event.createdAt.toISOString(),
291
+ payloadMetadata: event.payloadMetadata,
292
+ })),
293
+ eventsTruncated: history.eventsTruncated,
294
+ sections: history.sections,
295
+ });
296
+ });
297
+ });
298
+ // GET /api/v1/memories/:id — inspect a single memory. Core
299
+ // getMemoryById throws MemoryNotFoundError for an absent/cross-tenant id, which
300
+ // the mapper turns into a 404. Returns the full row INCLUDING content (inspect
301
+ // is its JTBD) — the content is never logged.
302
+ router.get('/api/v1/memories/:id', (req, res) => {
303
+ void guard('memories.inspect', res, async () => {
304
+ const id = pathIdSchema.safeParse(req.params.id);
305
+ if (!id.success) {
306
+ res.status(404).json({ error: 'not_found' });
307
+ return;
308
+ }
309
+ // ACCESS GUARD: read access is asserted BEFORE the row is read (self-host
310
+ // allowAllAccess allows all).
311
+ if (options.access)
312
+ await options.access.assertRead(tenant(req));
313
+ const memory = await getMemoryById(tenant(req), id.data);
314
+ res.status(200).json({
315
+ id: memory.id,
316
+ memoryType: memory.memoryType,
317
+ topic: memory.topic,
318
+ content: memory.content,
319
+ scope: memory.scope,
320
+ project: memory.project ?? null,
321
+ status: memory.status,
322
+ ...(memory.commitmentStatus === undefined || memory.commitmentStatus === null
323
+ ? {}
324
+ : { commitmentStatus: memory.commitmentStatus }),
325
+ tags: memory.tags,
326
+ validFrom: memory.validFrom.toISOString(),
327
+ validTo: memory.validTo?.toISOString() ?? null,
328
+ recordedAt: memory.recordedAt.toISOString(),
329
+ createdAt: memory.createdAt.toISOString(),
330
+ });
331
+ });
332
+ });
333
+ // POST /api/v1/search - public REST mirror of the MCP search tool.
334
+ router.post('/api/v1/search', (req, res) => {
335
+ void guard('search', res, async () => {
336
+ if (options.gateway === undefined) {
337
+ res.status(503).json({ error: 'embedding_unavailable' });
338
+ return;
339
+ }
340
+ const input = searchQuerySchema.parse(req.body);
341
+ const filters = defined({
342
+ memoryType: input.memoryType,
343
+ scope: input.scope,
344
+ project: input.project,
345
+ status: input.status,
346
+ asOf: toAsOf(input.asOf),
347
+ });
348
+ const hits = await search(tenant(req), input.query, { gateway: options.gateway }, { limit: input.limit, filters, budget: options.budget });
349
+ res.status(200).json({
350
+ hits: hits.map((hit) => ({
351
+ id: hit.id,
352
+ memoryType: hit.memoryType,
353
+ topic: hit.topic,
354
+ content: hit.content,
355
+ contentLength: hit.contentLength,
356
+ truncated: hit.truncated,
357
+ score: hit.score,
358
+ })),
359
+ count: hits.length,
360
+ });
361
+ });
362
+ });
363
+ // POST /api/v1/dashboard/search - dashboard continuation contract. This route
364
+ // intentionally does not replace /api/v1/search, which is the SDK/CLI/MCP
365
+ // mirror and must keep returning content excerpts.
366
+ router.post('/api/v1/dashboard/search', (req, res) => {
367
+ void guard('dashboard.search', res, async () => {
368
+ if (options.gateway === undefined) {
369
+ res.status(503).json({ error: 'embedding_unavailable' });
370
+ return;
371
+ }
372
+ const input = dashboardSearchQuerySchema.parse(req.body);
373
+ const filters = defined({
374
+ memoryType: input.memoryType,
375
+ scope: input.scope,
376
+ project: input.project,
377
+ status: input.status,
378
+ asOf: toAsOf(input.asOf),
379
+ });
380
+ // Frozen-ordering cursor: the first page ranks the bounded
381
+ // candidate pool once and freezes the ordering into the cursor; a
382
+ // continuation pages by position within it, so mid-session corpus drift
383
+ // cannot duplicate or skip a row. A malformed cursor throws a ZodError
384
+ // here -> 400 (mapRestError); a stale v1 cursor decodes to undefined and
385
+ // restarts at page 1.
386
+ const decoded = input.cursor === undefined ? undefined : decodeCursor(input.cursor);
387
+ const frozen = decoded === undefined
388
+ ? undefined
389
+ : { ids: decoded.ids, scores: decoded.scores, off: decoded.off };
390
+ const page = await searchDashboardPage(tenant(req), input.query, { gateway: options.gateway }, defined({ limit: input.limit, filters, frozen, budget: options.budget }));
391
+ // Only emit a cursor when there is a further page, so the client stops at
392
+ // the window edge. The cursor carries the frozen ordering + next offset.
393
+ const nextCursor = page.hasMore
394
+ ? encodeCursor({
395
+ v: 2,
396
+ ids: page.frozen.ids,
397
+ scores: page.frozen.scores,
398
+ off: page.nextOffset,
399
+ })
400
+ : undefined;
401
+ res.status(200).json(defined({
402
+ hits: page.hits.map((hit) => defined({
403
+ id: hit.id,
404
+ memoryType: hit.memoryType,
405
+ topic: hit.topic,
406
+ score: hit.score,
407
+ commitmentStatus: hit.commitmentStatus,
408
+ })),
409
+ count: page.hits.length,
410
+ hasMore: page.hasMore,
411
+ nextCursor,
412
+ }));
413
+ });
414
+ });
415
+ // GET /api/v1/facts — get_facts (mirrors the MCP get_facts tool). Filters arrive
416
+ // as query params; factsQueryInputSchema is the boundary. The MCP tool takes the
417
+ // bi-temporal `asOf` coordinate in the body; over a GET querystring we accept it
418
+ // as TWO FLAT keys — `validAt` and `asKnownAt` (ISO-8601 datetime strings) — and
419
+ // reshape them into the nested `{asOf:{validAt?,asKnownAt?}}` object BEFORE the
420
+ // single parse. The SAME factsQueryInputSchema validates it, so asOfSchema's
421
+ // refine still rejects a bare `?asOf` with neither coordinate as a 400 (no silent
422
+ // drop). `asOf` is omitted entirely when neither key is present (current-facts
423
+ // default). ISO strings are coerced to Date at the core boundary via toAsOf,
424
+ // exactly as the MCP get_facts handler bridges (apps/server/src/mcp/tools.ts).
425
+ router.get('/api/v1/facts', (req, res) => {
426
+ void guard('facts', res, async () => {
427
+ const asOf = req.query.validAt === undefined && req.query.asKnownAt === undefined
428
+ ? undefined
429
+ : defined({ validAt: req.query.validAt, asKnownAt: req.query.asKnownAt });
430
+ const input = factsQueryInputSchema.parse(defined({
431
+ subject: req.query.subject,
432
+ predicate: req.query.predicate,
433
+ asOf,
434
+ limit: req.query.limit === undefined ? undefined : Number(req.query.limit),
435
+ }));
436
+ // ACCESS GUARD: read access is asserted BEFORE facts are read (self-host
437
+ // allowAllAccess allows all).
438
+ if (options.access)
439
+ await options.access.assertRead(tenant(req));
440
+ const facts = await getFacts(tenant(req), defined({
441
+ subject: input.subject,
442
+ predicate: input.predicate,
443
+ asOf: toAsOf(input.asOf),
444
+ limit: input.limit,
445
+ }));
446
+ res.status(200).json({
447
+ facts: facts.map((fact) => ({
448
+ id: fact.id,
449
+ subject: fact.subject,
450
+ predicate: fact.predicate,
451
+ value: fact.value,
452
+ confidence: fact.confidence,
453
+ validFrom: fact.validFrom.toISOString(),
454
+ validTo: fact.validTo?.toISOString() ?? null,
455
+ })),
456
+ count: facts.length,
457
+ });
458
+ });
459
+ });
460
+ // GET /api/v1/briefing — mirrors the MCP briefing tool. Flat query params
461
+ // (kind/scope/project/mode) are reshaped into the nested selector BEFORE the
462
+ // single briefingToolInputSchema parse. `now` is stamped here.
463
+ router.get('/api/v1/briefing', (req, res) => {
464
+ void guard('briefing', res, async () => {
465
+ const input = briefingToolInputSchema.parse(defined({
466
+ selector: defined({
467
+ kind: req.query.kind,
468
+ scope: req.query.scope,
469
+ project: req.query.project,
470
+ }),
471
+ mode: req.query.mode,
472
+ }));
473
+ // ACCESS GUARD: the briefing is memory-derived, so read access is asserted
474
+ // BEFORE the read (self-host allowAllAccess allows all); parity with the MCP
475
+ // briefing tool.
476
+ if (options.access)
477
+ await options.access.assertRead(tenant(req));
478
+ const result = await briefing(tenant(req), {
479
+ selector: input.selector,
480
+ mode: input.mode,
481
+ now: new Date(),
482
+ });
483
+ res.status(200).json(result);
484
+ });
485
+ });
486
+ // POST /api/v1/memories/:id/revise — revise (mirrors the MCP revise tool). The
487
+ // body is the full successor write; core revise() is THE validation boundary.
488
+ // :id is the predecessor — merged into the body as predecessorId BEFORE the
489
+ // single parse, so the URL and body cannot disagree (the URL wins).
490
+ router.post('/api/v1/memories/:id/revise', (req, res) => {
491
+ void guard('revise', res, async () => {
492
+ const merged = { ...req.body, predecessorId: req.params.id };
493
+ const input = reviseToolInputSchema.parse(merged);
494
+ const gatewayOpts = options.gateway === undefined
495
+ ? { access: options.access }
496
+ : { gateway: options.gateway, budget: options.budget, access: options.access };
497
+ const written = await revise(tenant(req), input, 'user_api', gatewayOpts);
498
+ void written.embed.settled.catch(() => false);
499
+ const embedded = options.gateway === undefined ? 'off' : 'pending';
500
+ res.status(200).json({
501
+ memory: {
502
+ id: written.id,
503
+ memoryType: input.memoryType,
504
+ topic: input.topic,
505
+ scope: input.scope,
506
+ project: input.project ?? null,
507
+ },
508
+ embedded,
509
+ });
510
+ });
511
+ });
512
+ // POST /api/v1/memories/:id/resolve — resolve (mirrors the MCP resolve tool,
513
+ // keyed on the MEMORY id from D1). :id -> memoryId merged with body -> status,
514
+ // THEN validated against resolveToolInputSchema (single boundary). Serves
515
+ // resolve AND unresolve (resolved -> open) — the FSM owns legality.
516
+ router.post('/api/v1/memories/:id/resolve', (req, res) => {
517
+ void guard('resolve', res, async () => {
518
+ const merged = { ...req.body, memoryId: req.params.id };
519
+ const input = resolveToolInputSchema.parse(merged);
520
+ // ACCESS GUARD: write access is asserted BEFORE the db op runs (self-host
521
+ // allowAllAccess allows all).
522
+ if (options.access)
523
+ await options.access.assertWrite(tenant(req));
524
+ const result = await resolveByMemoryId(tenant(req), input.memoryId, input.status, 'user_api');
525
+ res.status(200).json({ commitmentId: result.id, status: result.status });
526
+ });
527
+ });
528
+ // GET /api/v1/proposals — bounded consolidation-proposal list over
529
+ // the EXISTING core listProposals. status/limit arrive as query params; limit is
530
+ // coerced before the single parse against proposalsListQuerySchema. The route
531
+ // shapes the proposal records (timestamps to ISO; rationale may be null).
532
+ router.get('/api/v1/proposals', (req, res) => {
533
+ void guard('proposals.list', res, async () => {
534
+ const query = proposalsListQuerySchema.parse(defined({
535
+ status: req.query.status,
536
+ limit: req.query.limit === undefined ? undefined : Number(req.query.limit),
537
+ }));
538
+ // ACCESS GUARD: proposals are memory-derived (consolidation candidates over
539
+ // the tenant's memories), so read access is asserted BEFORE the read
540
+ // (self-host allowAllAccess allows all).
541
+ if (options.access)
542
+ await options.access.assertRead(tenant(req));
543
+ // limit carries the schema default (always present); status is OPTIONAL —
544
+ // strip it when undefined so the exactOptional core query type fits.
545
+ const proposals = await listProposals(tenant(req), {
546
+ limit: query.limit,
547
+ ...defined({ status: query.status }),
548
+ });
549
+ res.status(200).json({
550
+ proposals: proposals.map((proposal) => ({
551
+ id: proposal.id,
552
+ fromId: proposal.fromId,
553
+ toId: proposal.toId,
554
+ edgeType: proposal.edgeType,
555
+ memoryType: proposal.memoryType,
556
+ similarity: proposal.similarity,
557
+ rationale: proposal.rationale,
558
+ status: proposal.status,
559
+ decidedAt: proposal.decidedAt?.toISOString() ?? null,
560
+ createdAt: proposal.createdAt.toISOString(),
561
+ })),
562
+ count: proposals.length,
563
+ });
564
+ });
565
+ });
566
+ // POST /api/v1/proposals/:id/apply — accept a proposal over the
567
+ // EXISTING core applyProposal. A dashboard apply is attributed to the user_api
568
+ // actor (the human reviewer acting through the UI). A missing/decided proposal
569
+ // -> ProposalNotFoundError -> 404; a stale-successor apply -> 409 (the mapper).
570
+ router.post('/api/v1/proposals/:id/apply', (req, res) => {
571
+ void guard('proposals.apply', res, async () => {
572
+ const id = pathIdSchema.safeParse(req.params.id);
573
+ if (!id.success) {
574
+ res.status(404).json({ error: 'not_found' });
575
+ return;
576
+ }
577
+ // ACCESS GUARD: applying a proposal mutates the graph — write access is
578
+ // asserted BEFORE the db op (self-host allowAllAccess allows all).
579
+ if (options.access)
580
+ await options.access.assertWrite(tenant(req));
581
+ const applied = await applyProposal(tenant(req), id.data, 'user_api');
582
+ res.status(200).json({ id: applied.id, status: applied.status });
583
+ });
584
+ });
585
+ // POST /api/v1/proposals/:id/reject — reject a proposal. The
586
+ // optional {rationale} body is validated but not yet stored —
587
+ // interim contract until a reviewer-rationale column lands.
588
+ router.post('/api/v1/proposals/:id/reject', (req, res) => {
589
+ void guard('proposals.reject', res, async () => {
590
+ const id = pathIdSchema.safeParse(req.params.id);
591
+ if (!id.success) {
592
+ res.status(404).json({ error: 'not_found' });
593
+ return;
594
+ }
595
+ // Parse (and thereby validate) the optional body even though core does not
596
+ // consume the rationale yet — a malformed body is a 400 at the boundary,
597
+ // never a silent accept.
598
+ proposalRejectBodySchema.parse(req.body ?? {});
599
+ // ACCESS GUARD: rejecting a proposal mutates its state — write access is
600
+ // asserted BEFORE the db op (self-host allowAllAccess allows all).
601
+ if (options.access)
602
+ await options.access.assertWrite(tenant(req));
603
+ const rejected = await rejectProposal(tenant(req), id.data);
604
+ res.status(200).json({ id: rejected.id, status: rejected.status });
605
+ });
606
+ });
607
+ // GET /api/v1/stats — the bounded environment COUNT aggregates via
608
+ // the EXISTING core describeEnvironment (which wraps getEnvironmentStats). Only
609
+ // the stats half is surfaced — counts only, NEVER content/values.
610
+ router.get('/api/v1/stats', (req, res) => {
611
+ void guard('stats', res, async () => {
612
+ // ACCESS GUARD: stats are per-tenant memory-derived counts, so read access
613
+ // is asserted BEFORE the read (self-host allowAllAccess allows all); parity
614
+ // with MCP describe_environment.
615
+ if (options.access)
616
+ await options.access.assertRead(tenant(req));
617
+ const report = await describeEnvironment(tenant(req));
618
+ res.status(200).json(report.stats);
619
+ });
620
+ });
621
+ // GET /api/v1/me — the authenticated identity. Works under BOTH
622
+ // auth paths (X-API-Key and session Bearer both bind req.userId). Returns
623
+ // {id,email}; the email is never logged.
624
+ // DELIBERATELY UNGATED: returns ACCOUNT identity (id + email), not memory
625
+ // or memory-derived data. A denied user must still reach their own account to
626
+ // manage it — gating identity would lock them out of self-service. Not a
627
+ // tenant-memory surface, so no gate applies.
628
+ router.get('/api/v1/me', (req, res) => {
629
+ void guard('me', res, async () => {
630
+ const user = await getCurrentUser(tenant(req));
631
+ res.status(200).json({ id: user.id, email: user.email });
632
+ });
633
+ });
634
+ // GET /api/v1/budget — the caller's current budget status (effective cap +
635
+ // consumed this cycle). Read-only. NOTE: the operator WRITE
636
+ // (PUT cap_usd_override) is intentionally NOT exposed here: effectiveCap =
637
+ // override ?? tierCap, so a self-service override would let a user nullify
638
+ // their own cost cap. The override is operator-managed (admin-write only;
639
+ // app_user has no UPDATE on plan_tiers and the override write awaits a distinct
640
+ // admin-auth surface). 503 when budget enforcement is not wired (mirrors the
641
+ // search embedding-unavailable contract).
642
+ // DELIBERATELY UNGATED: returns cost status (cap + consumption), not memory or
643
+ // memory-derived data. A denied user must keep reading their own budget status —
644
+ // it is the very surface that explains a denial; gating it would be
645
+ // self-defeating.
646
+ router.get('/api/v1/budget', (req, res) => {
647
+ void guard('budget', res, async () => {
648
+ if (options.budget === undefined) {
649
+ res.status(503).json({ error: 'budget_unavailable' });
650
+ return;
651
+ }
652
+ const status = await getBudgetStatus(options.budget, tenant(req));
653
+ res.status(200).json({
654
+ effectiveCapUsd: status.effectiveCapUsd,
655
+ consumedUsd: status.consumedUsd,
656
+ capUsdOverride: status.capUsdOverride,
657
+ periodStart: status.periodStart?.toISOString() ?? null,
658
+ periodEnd: status.periodEnd?.toISOString() ?? null,
659
+ });
660
+ });
661
+ });
662
+ // GET /api/v1/export — GDPR Art. 20 data portability. A
663
+ // self-serve, machine-readable download of the caller's COMPLETE dataset:
664
+ // account identity (never the password hash) + every memory/fact/commitment/
665
+ // scope/edge/memory-event/proposal they own (the full set of tenant PII,
666
+ // plus the typed memory graph), across all lifecycle states
667
+ // (ADR-0005 retains superseded rows —
668
+ // the export includes them). Core exportUserData runs withTenant at REPEATABLE
669
+ // READ, so the whole archive is one consistent snapshot and a route can only ever
670
+ // return the authenticated owner's rows; the content it returns is
671
+ // the JTBD and is NEVER logged.
672
+ // ACCESS GUARD: the export is a memory-derived read, so read access is asserted
673
+ // BEFORE the read (self-host allowAllAccess allows all), matching every other
674
+ // read route's idiom.
675
+ // Content-Disposition makes it a browser download with a dated filename.
676
+ router.get('/api/v1/export', (req, res) => {
677
+ void guard('export', res, async () => {
678
+ if (options.access)
679
+ await options.access.assertRead(tenant(req));
680
+ const data = await exportUserData(tenant(req), options.exportEnricher);
681
+ const stamp = new Date().toISOString().slice(0, 10);
682
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
683
+ res.setHeader('Content-Disposition', `attachment; filename="3ngram-export-${stamp}.json"`);
684
+ res.status(200).json({
685
+ format: '3ngram.account-export.v1',
686
+ exportedAt: new Date().toISOString(),
687
+ account: {
688
+ id: data.account.id,
689
+ email: data.account.email,
690
+ emailVerifiedAt: data.account.emailVerifiedAt?.toISOString() ?? null,
691
+ createdAt: data.account.createdAt.toISOString(),
692
+ updatedAt: data.account.updatedAt.toISOString(),
693
+ },
694
+ memories: data.memories.map((memory) => ({
695
+ id: memory.id,
696
+ memoryType: memory.memoryType,
697
+ topic: memory.topic,
698
+ content: memory.content,
699
+ scope: memory.scope,
700
+ project: memory.project ?? null,
701
+ status: memory.status,
702
+ tags: memory.tags,
703
+ validFrom: memory.validFrom.toISOString(),
704
+ validTo: memory.validTo?.toISOString() ?? null,
705
+ recordedAt: memory.recordedAt.toISOString(),
706
+ createdAt: memory.createdAt.toISOString(),
707
+ updatedAt: memory.updatedAt.toISOString(),
708
+ })),
709
+ facts: data.facts.map((fact) => ({
710
+ id: fact.id,
711
+ memoryId: fact.memoryId,
712
+ subject: fact.subject,
713
+ predicate: fact.predicate,
714
+ value: fact.value,
715
+ confidence: fact.confidence,
716
+ validFrom: fact.validFrom.toISOString(),
717
+ validTo: fact.validTo?.toISOString() ?? null,
718
+ recordedAt: fact.recordedAt.toISOString(),
719
+ createdAt: fact.createdAt.toISOString(),
720
+ })),
721
+ commitments: data.commitments.map((commitment) => ({
722
+ id: commitment.id,
723
+ memoryId: commitment.memoryId,
724
+ status: commitment.status,
725
+ owner: commitment.owner ?? null,
726
+ dueAt: commitment.dueAt?.toISOString() ?? null,
727
+ recurrence: commitment.recurrence ?? null,
728
+ nextSurfacingAt: commitment.nextSurfacingAt?.toISOString() ?? null,
729
+ resolvedAt: commitment.resolvedAt?.toISOString() ?? null,
730
+ createdAt: commitment.createdAt.toISOString(),
731
+ updatedAt: commitment.updatedAt.toISOString(),
732
+ })),
733
+ scopes: data.scopes.map((scope) => ({
734
+ id: scope.id,
735
+ name: scope.name,
736
+ aliases: scope.aliases,
737
+ createdAt: scope.createdAt.toISOString(),
738
+ })),
739
+ edges: data.edges.map((edge) => ({
740
+ id: edge.id,
741
+ fromId: edge.fromId,
742
+ toId: edge.toId,
743
+ edgeType: edge.edgeType,
744
+ createdBy: edge.createdBy,
745
+ createdAt: edge.createdAt.toISOString(),
746
+ })),
747
+ memoryEvents: data.memoryEvents.map((event) => ({
748
+ id: event.id,
749
+ memoryId: event.memoryId,
750
+ eventKind: event.eventKind,
751
+ actorKind: event.actorKind,
752
+ payload: event.payload ?? null,
753
+ createdAt: event.createdAt.toISOString(),
754
+ })),
755
+ proposals: data.proposals.map((proposal) => ({
756
+ id: proposal.id,
757
+ fromId: proposal.fromId,
758
+ toId: proposal.toId,
759
+ edgeType: proposal.edgeType,
760
+ memoryType: proposal.memoryType,
761
+ similarity: proposal.similarity,
762
+ rationale: proposal.rationale ?? null,
763
+ status: proposal.status,
764
+ decidedAt: proposal.decidedAt?.toISOString() ?? null,
765
+ createdAt: proposal.createdAt.toISOString(),
766
+ })),
767
+ userBudgets: data.userBudgets.map((budget) => ({
768
+ id: budget.id,
769
+ capUsdOverride: budget.capUsdOverride ?? null,
770
+ periodStart: budget.periodStart?.toISOString() ?? null,
771
+ periodEnd: budget.periodEnd?.toISOString() ?? null,
772
+ updatedAt: budget.updatedAt.toISOString(),
773
+ })),
774
+ llmUsage: data.llmUsage.map((usage) => ({
775
+ id: usage.id,
776
+ operation: usage.operation,
777
+ model: usage.model,
778
+ inputTokens: usage.inputTokens,
779
+ outputTokens: usage.outputTokens,
780
+ costUsd: usage.costUsd ?? null,
781
+ createdAt: usage.createdAt.toISOString(),
782
+ })),
783
+ profile: data.profile
784
+ ? {
785
+ role: data.profile.role,
786
+ useCase: data.profile.useCase,
787
+ aiTools: data.profile.aiTools,
788
+ referralSource: data.profile.referralSource,
789
+ createdAt: data.profile.createdAt.toISOString(),
790
+ updatedAt: data.profile.updatedAt.toISOString(),
791
+ }
792
+ : null,
793
+ counts: {
794
+ memories: data.memories.length,
795
+ facts: data.facts.length,
796
+ commitments: data.commitments.length,
797
+ scopes: data.scopes.length,
798
+ edges: data.edges.length,
799
+ memoryEvents: data.memoryEvents.length,
800
+ proposals: data.proposals.length,
801
+ userBudgets: data.userBudgets.length,
802
+ llmUsage: data.llmUsage.length,
803
+ },
804
+ });
805
+ });
806
+ });
807
+ // DELETE /api/v1/account — self-serve account deletion (GDPR Art. 17).
808
+ // Requires an explicit { confirm: true } body (validated at the
809
+ // ONE schema boundary). Core deleteAccount erases the caller's PII in place and
810
+ // physically deletes NO memory-domain row (ADR-0005; the runtime
811
+ // grant forbids it), revokes every credential, runs the optional platform
812
+ // cleanup hook (absent on self-host — no private import), and writes a
813
+ // content-free audit tombstone. Idempotent.
814
+ // DELIBERATELY UNGATED (mirrors /me, /budget): a denied user MUST be able to
815
+ // exercise their erasure right — gating deletion behind access status would trap
816
+ // them. Response carries counts only.
817
+ router.delete('/api/v1/account', (req, res) => {
818
+ void guard('account.delete', res, async () => {
819
+ accountDeleteBodySchema.parse(req.body ?? {});
820
+ const result = await deleteAccount(tenant(req), {
821
+ now: new Date(),
822
+ ...(options.onAccountDeletion !== undefined
823
+ ? { onAccountDeletion: options.onAccountDeletion }
824
+ : {}),
825
+ });
826
+ res.status(200).json({
827
+ deleted: true,
828
+ alreadyDeleted: result.alreadyDeleted,
829
+ erased: {
830
+ memories: result.erased.memories,
831
+ facts: result.erased.facts,
832
+ commitments: result.erased.commitments,
833
+ proposals: result.erased.proposals,
834
+ sessionsDeleted: result.erased.sessionsDeleted,
835
+ apiKeysRevoked: result.erased.apiKeysRevoked,
836
+ oauthTokensRevoked: result.erased.oauthTokensRevoked,
837
+ oauthCodesDeleted: result.erased.oauthCodesDeleted,
838
+ passwordResetTokensDeleted: result.erased.passwordResetTokensDeleted,
839
+ emailVerificationTokensDeleted: result.erased.emailVerificationTokensDeleted,
840
+ },
841
+ });
842
+ });
843
+ });
844
+ return router;
845
+ }
846
+ //# sourceMappingURL=router.js.map