humemory 0.2.6 → 0.2.8

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 (95) hide show
  1. package/AGENTS.md +49 -4
  2. package/CHANGELOG.md +12 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +89 -0
  9. package/dist/agent/maintenance-queue.js +245 -87
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +68 -17
  12. package/dist/agent/maintenance-state.d.ts +4 -0
  13. package/dist/agent/mcp-client-setup.d.ts +16 -0
  14. package/dist/agent/mcp-client-setup.js +108 -0
  15. package/dist/agent/opencode-import.d.ts +22 -0
  16. package/dist/agent/opencode-import.js +71 -0
  17. package/dist/agent/opencode-session-parser.d.ts +3 -0
  18. package/dist/agent/opencode-session-parser.js +35 -0
  19. package/dist/agent/session-parser.d.ts +8 -0
  20. package/dist/agent/session-parser.js +18 -0
  21. package/dist/agent/source-registry.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +164 -4
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/embeddings.d.ts +0 -10
  27. package/dist/core/embeddings.js +2 -1
  28. package/dist/core/llm-generator.d.ts +2 -10
  29. package/dist/core/paths.d.ts +5 -0
  30. package/dist/core/paths.js +27 -0
  31. package/dist/core/project-path.d.ts +3 -0
  32. package/dist/core/project-path.js +14 -0
  33. package/dist/core/search.d.ts +1 -1
  34. package/dist/core/search.js +7 -9
  35. package/dist/core/types.d.ts +13 -1
  36. package/dist/index.d.ts +5 -0
  37. package/dist/index.js +5 -0
  38. package/dist/store/sqlite.d.ts +37 -0
  39. package/dist/store/sqlite.js +94 -42
  40. package/package.json +4 -3
  41. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  42. package/public/app/index.html +1 -1
  43. package/scripts/consolidate.js +4 -4
  44. package/scripts/hook-post-commit.ts +2 -1
  45. package/scripts/hook-session-start.ts +2 -1
  46. package/scripts/hook-session.ts +2 -1
  47. package/src/agent/claude-hook.ts +126 -0
  48. package/src/agent/codex-import.ts +129 -0
  49. package/src/agent/codex-rollout-parser.ts +121 -0
  50. package/src/agent/commit-closer.ts +173 -0
  51. package/src/agent/kimi-import.ts +128 -0
  52. package/src/agent/kimi-session-parser.ts +127 -0
  53. package/src/agent/learning-extractor.ts +128 -0
  54. package/src/agent/maintenance-queue.ts +546 -0
  55. package/src/agent/maintenance-runner.ts +322 -0
  56. package/src/agent/maintenance-state.ts +168 -0
  57. package/src/agent/mcp-client-setup.ts +125 -0
  58. package/src/agent/opencode-import.ts +96 -0
  59. package/src/agent/opencode-session-parser.ts +53 -0
  60. package/src/agent/session-context.ts +302 -0
  61. package/src/agent/session-parser.ts +155 -0
  62. package/src/agent/source-registry.ts +135 -0
  63. package/src/api/cors.ts +42 -0
  64. package/src/api/dream-routes.ts +46 -0
  65. package/src/api/errors.ts +45 -0
  66. package/src/api/intentions-routes.ts +348 -0
  67. package/src/api/limits.ts +90 -0
  68. package/src/api/maintenance-routes.ts +73 -0
  69. package/src/api/memory-routes.ts +391 -0
  70. package/src/api/scripts-routes.ts +176 -0
  71. package/src/api/security-headers.ts +54 -0
  72. package/src/api/server.ts +292 -0
  73. package/src/cli/index.ts +1175 -0
  74. package/src/core/clock.ts +64 -0
  75. package/src/core/cue-arg.ts +79 -0
  76. package/src/core/cues.ts +511 -0
  77. package/src/core/decay.ts +198 -0
  78. package/src/core/dreamer.ts +494 -0
  79. package/src/core/embeddings.ts +157 -0
  80. package/src/core/event-bus.ts +100 -0
  81. package/src/core/hybrid.ts +78 -0
  82. package/src/core/llm-cli-client.ts +118 -0
  83. package/src/core/llm-generator.ts +90 -0
  84. package/src/core/paths.ts +28 -0
  85. package/src/core/project-path.ts +14 -0
  86. package/src/core/sanitize.ts +116 -0
  87. package/src/core/scripts.ts +112 -0
  88. package/src/core/search.ts +189 -0
  89. package/src/core/trust.ts +67 -0
  90. package/src/core/types.ts +393 -0
  91. package/src/core/vector-clusterer.ts +131 -0
  92. package/src/index.ts +40 -0
  93. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  94. package/src/mcp/server.ts +202 -0
  95. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * HTTP routes for cognitive scripts — Phase 8.3.
3
+ *
4
+ * Sub-router mounted by `src/api/server.ts`, same testability contract as
5
+ * intentions-routes.ts: the store comes in as a parameter, never opened here.
6
+ *
7
+ * Trust gate (8.3): anything arriving over HTTP is agent-authored and lands
8
+ * as a DRAFT — a header is a claim, not a fact (6.0.1 identity rule). Only
9
+ * the human `activate` call flips a draft to active; drafts never fire.
10
+ */
11
+
12
+ import { Hono } from 'hono';
13
+ import type { SQLiteStore } from '../store/sqlite.js';
14
+ import type { Script, ScriptStatus, TriggerSpec } from '../core/types.js';
15
+ import { validateTriggerSpec } from './intentions-routes.js';
16
+ import { serverErrorBody } from './errors.js';
17
+ import {
18
+ boundedString,
19
+ MAX_CONTENT_LENGTH,
20
+ MAX_SHORT_FIELD_LENGTH,
21
+ MAX_COLLECTION_ITEMS,
22
+ } from './limits.js';
23
+
24
+ const SCRIPT_STATUSES: ScriptStatus[] = ['draft', 'active', 'archived'];
25
+
26
+ /** Input validation error — surfaced as a 400 rather than a 500. */
27
+ class BadRequest extends Error {
28
+ constructor(message: string) {
29
+ super(message);
30
+ this.name = 'BadRequest'; // subclasses default to 'Error' — see guard
31
+ }
32
+ }
33
+
34
+ function serializeScript(script: Script) {
35
+ return { ...script, shortId: script.id.slice(0, 8) };
36
+ }
37
+
38
+ function validateSteps(raw: unknown): string[] {
39
+ if (!Array.isArray(raw) || !raw.length) throw new BadRequest('"steps" must be a non-empty array');
40
+ // SECURITY_AUDIT.md M-02: a script could otherwise declare unlimited steps,
41
+ // each of unlimited length.
42
+ if (raw.length > MAX_COLLECTION_ITEMS) {
43
+ throw new BadRequest(`"steps" must hold at most ${MAX_COLLECTION_ITEMS} items`);
44
+ }
45
+ const steps = raw.map((s, i) =>
46
+ typeof s === 'string' ? boundedString(s, MAX_CONTENT_LENGTH, `steps[${i}]`).trim() : ''
47
+ );
48
+ if (steps.some((s) => !s)) throw new BadRequest('every step must be a non-empty string');
49
+ return steps;
50
+ }
51
+
52
+ export function createScriptRoutes(store: SQLiteStore) {
53
+ const app = new Hono();
54
+
55
+ const guard = async (c: any, fn: () => Promise<Response>): Promise<Response> => {
56
+ try {
57
+ return await fn();
58
+ } catch (err) {
59
+ // validateTriggerSpec throws intentions-routes' own BadRequest class —
60
+ // instanceof would miss it across module boundaries, so match by name.
61
+ // LimitExceeded (SECURITY_AUDIT.md M-02) is the caller's error too.
62
+ if (err instanceof Error && (err.name === 'BadRequest' || err.name === 'LimitExceeded')) {
63
+ return c.json({ error: err.message }, 400);
64
+ }
65
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, err), 500);
66
+ }
67
+ };
68
+
69
+ /** Unambiguous prefix match — humans handle short ids, like dream review. */
70
+ const findByPrefix = async (prefix: string): Promise<Script | null> => {
71
+ const direct = await store.getScript(prefix);
72
+ if (direct) return direct;
73
+ const all = await store.listScripts({ status: SCRIPT_STATUSES, limit: 500 });
74
+ const hits = all.filter((s) => s.id.startsWith(prefix));
75
+ return hits.length === 1 ? hits[0] : null;
76
+ };
77
+
78
+ app.post('/scripts', (c) =>
79
+ guard(c, async () => {
80
+ const body = await c.req.json().catch(() => null);
81
+ if (!body || typeof body.name !== 'string' || !body.name.trim()) {
82
+ throw new BadRequest('"name" is required');
83
+ }
84
+ if (typeof body.description !== 'string' || !body.description.trim()) {
85
+ throw new BadRequest('"description" is required');
86
+ }
87
+ if (typeof body.directory !== 'string' || !body.directory) {
88
+ throw new BadRequest('"directory" is required');
89
+ }
90
+ const name = boundedString(body.name, MAX_SHORT_FIELD_LENGTH, 'name');
91
+ const description = boundedString(body.description, MAX_CONTENT_LENGTH, 'description');
92
+ const directory = boundedString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
93
+
94
+ const steps = validateSteps(body.steps);
95
+ if (Array.isArray(body.cues) && body.cues.length > MAX_COLLECTION_ITEMS) {
96
+ throw new BadRequest(`"cues" must hold at most ${MAX_COLLECTION_ITEMS} items`);
97
+ }
98
+ const cues: TriggerSpec[] = Array.isArray(body.cues)
99
+ ? body.cues.map((spec: unknown) => validateTriggerSpec(spec))
100
+ : [];
101
+
102
+ const script = await store.addScript(
103
+ {
104
+ name: name.trim(),
105
+ description: description.trim(),
106
+ steps,
107
+ directory,
108
+ pinned: body.pinned === true,
109
+ // HTTP = agent claim → draft, always (8.3). No source override.
110
+ source: 'agent',
111
+ agent: c.req.header('X-Humemory-Agent') || undefined,
112
+ },
113
+ cues
114
+ );
115
+
116
+ return c.json({ script: serializeScript(script) }, 201);
117
+ })
118
+ );
119
+
120
+ app.get('/scripts', (c) =>
121
+ guard(c, async () => {
122
+ const raw = c.req.query('status');
123
+ let status: ScriptStatus[] | undefined;
124
+ if (raw) {
125
+ const values = raw.split(',').map((s) => s.trim());
126
+ const invalid = values.filter((v) => !SCRIPT_STATUSES.includes(v as ScriptStatus));
127
+ if (invalid.length) throw new BadRequest(`Unknown status: ${invalid.join(', ')}`);
128
+ status = values as ScriptStatus[];
129
+ }
130
+ const scripts = await store.listScripts({
131
+ status,
132
+ directory: c.req.query('directory'),
133
+ limit: 500,
134
+ });
135
+ return c.json({ scripts: scripts.map(serializeScript), count: scripts.length });
136
+ })
137
+ );
138
+
139
+ app.get('/scripts/:id', (c) =>
140
+ guard(c, async () => {
141
+ const script = await findByPrefix(c.req.param('id'));
142
+ if (!script) return c.json({ error: 'Script not found' }, 404);
143
+ const cues = await store.listCues({ targetKind: 'script', targetId: script.id });
144
+ return c.json({ script: serializeScript(script), cues });
145
+ })
146
+ );
147
+
148
+ app.post('/scripts/:id/activate', (c) =>
149
+ guard(c, async () => {
150
+ const script = await findByPrefix(c.req.param('id'));
151
+ if (!script) return c.json({ error: 'Script not found' }, 404);
152
+ return c.json({ script: serializeScript(await store.updateScriptStatus(script.id, 'active')) });
153
+ })
154
+ );
155
+
156
+ app.post('/scripts/:id/archive', (c) =>
157
+ guard(c, async () => {
158
+ const script = await findByPrefix(c.req.param('id'));
159
+ if (!script) return c.json({ error: 'Script not found' }, 404);
160
+ return c.json({ script: serializeScript(await store.updateScriptStatus(script.id, 'archived')) });
161
+ })
162
+ );
163
+
164
+ app.post('/scripts/:id/fire', (c) =>
165
+ guard(c, async () => {
166
+ const script = await findByPrefix(c.req.param('id'));
167
+ if (!script) return c.json({ error: 'Script not found' }, 404);
168
+ if (script.status !== 'active') {
169
+ return c.json({ error: `Script is ${script.status} — only active drills fire` }, 409);
170
+ }
171
+ return c.json({ script: serializeScript(await store.markScriptFired(script.id)) });
172
+ })
173
+ );
174
+
175
+ return app;
176
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Browser defence headers (SECURITY_AUDIT.md M-04).
3
+ *
4
+ * These do not replace escaping the data — H-02 is fixed at the sink — but they
5
+ * cap the blast radius of any sink we missed and stop the dashboard being framed.
6
+ *
7
+ * Extracted from `server.ts` so the policy can be tested: importing `server.ts`
8
+ * constructs the store and would open the production database (BUG-08).
9
+ */
10
+
11
+ import { NONCE, secureHeaders } from 'hono/secure-headers';
12
+
13
+ // hono does not export its options type; derive it from the middleware itself so
14
+ // this object stays checked against the version actually installed.
15
+ type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
16
+
17
+ export const SECURE_HEADERS_OPTIONS: SecureHeadersOptions = {
18
+ contentSecurityPolicy: {
19
+ defaultSrc: ["'self'"],
20
+ baseUri: ["'self'"],
21
+ objectSrc: ["'none'"],
22
+ frameAncestors: ["'none'"],
23
+ formAction: ["'self'"],
24
+ // React/d3/three are bundled to /app/*.js; the only inline script is
25
+ // session.html's, which carries the nonce.
26
+ scriptSrc: [NONCE, "'self'"],
27
+ // style-src covers <style> blocks and stylesheets. Element.style writes from
28
+ // JS go through the CSSOM and are not affected by this directive; the
29
+ // `style="…"` attributes in session.html are, hence styleSrcAttr.
30
+ styleSrc: [NONCE, "'self'"],
31
+ styleSrcAttr: ["'unsafe-inline'"],
32
+ imgSrc: ["'self'", 'data:'],
33
+ fontSrc: ["'self'", 'data:'],
34
+ connectSrc: ["'self'"],
35
+ workerSrc: ["'self'", 'blob:'],
36
+ },
37
+ // The dashboard is served over plain HTTP on loopback by default; forcing
38
+ // HSTS there would poison the browser for every other localhost service.
39
+ strictTransportSecurity: false,
40
+ xFrameOptions: 'DENY',
41
+ xContentTypeOptions: 'nosniff',
42
+ referrerPolicy: 'no-referrer',
43
+ };
44
+
45
+ /**
46
+ * Stamps the per-request CSP nonce onto the inline <script>/<style> tags of a
47
+ * static HTML page, so they run without weakening the policy to 'unsafe-inline'.
48
+ * A tag that already carries a nonce is left as it is.
49
+ */
50
+ export function injectNonce(html: string, nonce: string): string {
51
+ return html
52
+ .replace(/<script(?![^>]*\bnonce=)/g, `<script nonce="${nonce}"`)
53
+ .replace(/<style(?![^>]*\bnonce=)/g, `<style nonce="${nonce}"`);
54
+ }
@@ -0,0 +1,292 @@
1
+ import { databasePath, queueDirectory } from '../core/paths.js';
2
+ /**
3
+ * API HTTP pour humemory
4
+ *
5
+ * Endpoints:
6
+ * POST /memories - Add a memory
7
+ * GET /memories - List memories
8
+ * GET /memories/:id - Fetch one memory
9
+ * POST /memories/:id/recall - Recall a memory
10
+ * DELETE /memories/:id - Delete a memory
11
+ * GET /search - Search
12
+ * POST /decay - Run the decay sweep
13
+ * GET /status - Memory state
14
+ *
15
+ * Fronts :
16
+ * GET / - React app (explicit 503 when the bundle is missing)
17
+ * GET /app - Same app, historical URL
18
+ * GET /session - Mnemonic context composer (standalone page)
19
+ *
20
+ * Prospective memory (src/api/intentions-routes.ts):
21
+ * POST /intentions - Arm a loop (and its cues)
22
+ * GET /intentions - List (status, directory filters)
23
+ * GET /intentions/:id - Detail plus cues
24
+ * POST /intentions/:id/close - Close (cancels remaining cues)
25
+ * POST /intentions/:id/fire - Force-fire (debug/dashboard)
26
+ * DELETE /intentions/:id - Delete (cues cascade)
27
+ * POST /cues - Attach a cue
28
+ * GET /cues - List (intentionId, status, kind filters)
29
+ * POST /events - Push an event, waking the loops that match
30
+ * POST /cues/resolve - Sweep: expire overdue loops, fire due deadlines
31
+ */
32
+
33
+ import { Hono } from 'hono';
34
+ import { cors } from 'hono/cors';
35
+ import { bodyLimit } from 'hono/body-limit';
36
+ import { secureHeaders } from 'hono/secure-headers';
37
+ import type { SecureHeadersVariables } from 'hono/secure-headers';
38
+ import { MAX_BODY_BYTES } from './limits.js';
39
+ import { makeOriginChecker } from './cors.js';
40
+ import { SECURE_HEADERS_OPTIONS, injectNonce } from './security-headers.js';
41
+ import { serve } from '@hono/node-server';
42
+ import { SQLiteStore } from '../store/sqlite.js';
43
+ import { createIntentionRoutes } from './intentions-routes.js';
44
+ import { createMemoryRoutes } from './memory-routes.js';
45
+ import { createDreamRoutes } from './dream-routes.js';
46
+ import { createScriptRoutes } from './scripts-routes.js';
47
+ import { createMaintenanceRoutes } from './maintenance-routes.js';
48
+ import { defaultStatePath } from '../agent/maintenance-state.js';
49
+ import {
50
+ startMaintenanceLoop,
51
+ configuredIntervalMs,
52
+ type MaintenanceLoop,
53
+ } from '../agent/maintenance-runner.js';
54
+ import { join, dirname, resolve, sep } from 'path';
55
+ import { fileURLToPath } from 'url';
56
+ import { readFileSync } from 'fs';
57
+ import { timingSafeEqual } from 'crypto';
58
+
59
+ const __filename = fileURLToPath(import.meta.url);
60
+ const __dirname = dirname(__filename);
61
+
62
+ /**
63
+ * Resolve a request-supplied path under a trusted base dir, refusing any
64
+ * result that escapes the base (path traversal / CWE-22). Returns null if
65
+ * the path would leave baseDir.
66
+ */
67
+ function safeJoin(baseDir: string, ...segments: string[]): string | null {
68
+ const base = resolve(baseDir);
69
+ const full = resolve(base, ...segments);
70
+ if (full !== base && !full.startsWith(base + sep)) return null;
71
+ return full;
72
+ }
73
+
74
+ // HUMEMORY_DB: same convention as the CLI and the hooks. Without it, the API
75
+ // cannot be pointed at a demo database without writing to production.
76
+ const DB_PATH = databasePath();
77
+ const store = new SQLiteStore(DB_PATH);
78
+ const PUBLIC_DIR = join(__dirname, '../../public');
79
+ const QUEUE_DIR = queueDirectory();
80
+ const MAINTENANCE_STATE_PATH = defaultStatePath(QUEUE_DIR);
81
+
82
+ // Assigned only when this process hosts the loop; the routes read it to report
83
+ // whether maintenance lives here and whether a pass is in flight right now.
84
+ let maintenanceLoop: MaintenanceLoop | undefined;
85
+
86
+ // Configure CORS securely (allow localhost for development, restrict in production)
87
+ const allowedOrigins = process.env.NODE_ENV === 'production'
88
+ ? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
89
+ : ['http://localhost:3456', 'http://localhost:3000', 'http://127.0.0.1:3456'];
90
+
91
+
92
+ const app = new Hono<{ Variables: SecureHeadersVariables }>();
93
+
94
+ // Transport-level cap, ahead of any route (SECURITY_AUDIT.md M-02). The
95
+ // per-field caps in `limits.ts` are the business-level floor underneath it.
96
+ app.use('*', bodyLimit({
97
+ maxSize: MAX_BODY_BYTES,
98
+ onError: (c) => c.json({ success: false, error: 'Request body too large' }, 413),
99
+ }));
100
+
101
+ app.use('*', cors({
102
+ origin: makeOriginChecker(allowedOrigins),
103
+ credentials: true,
104
+ maxAge: 600,
105
+ }));
106
+
107
+ // === BROWSER DEFENCE HEADERS (SECURITY_AUDIT.md M-04) ===
108
+ // Policy and nonce stamping live in ./security-headers.ts so they stay testable.
109
+ app.use('*', secureHeaders(SECURE_HEADERS_OPTIONS));
110
+
111
+ // === AUTH (SECURITY_AUDIT.md H-01) ===
112
+ // HUMEMORY_API_TOKEN, when set, is required (Bearer or x-humemory-token) on every
113
+ // data/mutation route. Static dashboard assets and /health stay open so the front
114
+ // end can load; the front end then attaches the token to its own API calls.
115
+ const API_TOKEN = process.env.HUMEMORY_API_TOKEN;
116
+ const PUBLIC_PATHS = new Set(['/health']);
117
+
118
+ function isPublicPath(path: string): boolean {
119
+ return PUBLIC_PATHS.has(path) || path === '/' || path === '/app' || path === '/session' || path.startsWith('/app/');
120
+ }
121
+
122
+ function tokenMatches(supplied: string | undefined, expected: string): boolean {
123
+ if (!supplied) return false;
124
+ const a = Buffer.from(supplied);
125
+ const b = Buffer.from(expected);
126
+ // Constant-time compare requires equal length; a length check alone leaks
127
+ // little (token lengths aren't secret), and avoids throwing on mismatch.
128
+ return a.length === b.length && timingSafeEqual(a, b);
129
+ }
130
+
131
+ app.use('*', async (c, next) => {
132
+ if (!API_TOKEN || isPublicPath(c.req.path)) return next();
133
+
134
+ const header = c.req.header('authorization');
135
+ const bearer = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
136
+ const supplied = bearer ?? c.req.header('x-humemory-token');
137
+
138
+ if (!tokenMatches(supplied, API_TOKEN)) {
139
+ return c.json({ error: 'Unauthorized' }, 401);
140
+ }
141
+ return next();
142
+ });
143
+
144
+ // Static files (dashboard)
145
+ const APP_DIR = join(PUBLIC_DIR, 'app');
146
+
147
+ /**
148
+ * The React app page, served at `/` as well as `/app`.
149
+ *
150
+ * bun emits relative references (`./index-abc.js`). Served anywhere other than
151
+ * `/app/`, the browser resolves them against the root and finds nothing — so they
152
+ * are absolutised to `/app/`.
153
+ */
154
+ function reactAppHtml(nonce: string): string {
155
+ const html = readFileSync(join(APP_DIR, 'index.html'), 'utf-8');
156
+ return injectNonce(html.replace(/(src|href)="\.\//g, '$1="/app/'), nonce);
157
+ }
158
+
159
+ app.get('/', (c) => {
160
+ try {
161
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
162
+ } catch {
163
+ // Missing bundle: say what to run rather than serve a dead page.
164
+ return c.text('Front non construit. Lance `pnpm build:web`.', 503);
165
+ }
166
+ });
167
+
168
+ app.get('/session', (c) => {
169
+ const html = readFileSync(join(PUBLIC_DIR, 'session.html'), 'utf-8');
170
+ return c.html(injectNonce(html, c.get('secureHeadersNonce') ?? ''));
171
+ });
172
+
173
+ // React front end (web/ → public/app/ through `pnpm build:web`), served at / and /app.
174
+ const APP_MIME: Record<string, string> = {
175
+ js: 'application/javascript',
176
+ css: 'text/css',
177
+ html: 'text/html',
178
+ json: 'application/json',
179
+ svg: 'image/svg+xml',
180
+ png: 'image/png',
181
+ woff2: 'font/woff2',
182
+ };
183
+
184
+ app.get('/app', (c) => {
185
+ try {
186
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
187
+ } catch {
188
+ // Missing bundle: say what to run rather than a silent 404.
189
+ return c.text('Front non construit. Lance `pnpm build:web`.', 503);
190
+ }
191
+ });
192
+
193
+ app.get('/app/*', (c) => {
194
+ const filePath = c.req.path.replace('/app/', '');
195
+ const fullPath = safeJoin(APP_DIR, filePath);
196
+ if (!fullPath) return c.notFound();
197
+
198
+ try {
199
+ const ext = filePath.split('.').pop() ?? '';
200
+ const content = readFileSync(fullPath);
201
+ return c.body(content, 200, { 'Content-Type': APP_MIME[ext] ?? 'application/octet-stream' });
202
+ } catch {
203
+ return c.notFound();
204
+ }
205
+ });
206
+
207
+ // === RETROSPECTIVE MEMORY ===
208
+ // Testable sub-router (src/api/memory-routes.ts), mounted here.
209
+ app.route('/', createMemoryRoutes(store));
210
+
211
+ // === PROSPECTIVE MEMORY (Phase 5.4) ===
212
+ // Isolated sub-router: it takes the store as a parameter, so it is testable
213
+ // without opening the production database (see tests/api-intentions.test.ts).
214
+ app.route('/', createIntentionRoutes(store));
215
+
216
+ // === DREAMING (Phase 6.1) ===
217
+ app.route('/', createDreamRoutes(store));
218
+
219
+ // === COGNITIVE SCRIPTS (Phase 8.3) ===
220
+ app.route('/', createScriptRoutes(store));
221
+
222
+ // === MAINTENANCE HEALTH ===
223
+ // Behind the token like every other data route: `lastError` is internal detail.
224
+ app.route('/', createMaintenanceRoutes({
225
+ statePath: MAINTENANCE_STATE_PATH,
226
+ loop: () => maintenanceLoop,
227
+ }));
228
+
229
+ // === HEALTH ===
230
+ app.get('/health', (c) => {
231
+ return c.json({ status: 'ok', timestamp: new Date().toISOString() });
232
+ });
233
+
234
+ export { app };
235
+
236
+ // Only starts when run directly: importing this module (a test, a tool) must not
237
+ // raise a server or seize the port.
238
+ if (import.meta.main) {
239
+ const port = parseInt(process.env.PORT || '3456');
240
+ // Default loopback-only (SECURITY_AUDIT.md H-01): the previous code passed no
241
+ // hostname, which node-server forwards straight to server.listen(), binding
242
+ // every interface while the log line still claimed "localhost".
243
+ const hostname = process.env.HUMEMORY_HOST || '127.0.0.1';
244
+ const isLoopback = hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1';
245
+
246
+ if (!isLoopback && !API_TOKEN) {
247
+ console.error(
248
+ `Refusing to start: HUMEMORY_HOST=${hostname} exposes the API beyond loopback ` +
249
+ `without HUMEMORY_API_TOKEN set. Set a token or unset HUMEMORY_HOST.`
250
+ );
251
+ process.exit(1);
252
+ }
253
+
254
+ console.log(`🧠 humemory API running on http://${hostname}:${port}`);
255
+ console.log(`📊 Dashboard: http://${hostname}:${port}/`);
256
+ if (!API_TOKEN) {
257
+ console.warn('⚠️ HUMEMORY_API_TOKEN not set — data routes are unauthenticated (loopback only).');
258
+ }
259
+
260
+ serve({ fetch: app.fetch, port, hostname });
261
+
262
+ // Maintenance runs here rather than in an external scheduler: on Windows a
263
+ // scheduled task under an interactive token flashes a console window at every
264
+ // tick, and running it "whether the user is logged on or not" needs elevation
265
+ // this machine does not grant. This process is already resident and hidden.
266
+ // HUMEMORY_MAINTENANCE_INTERVAL_MS=0 hands the job back to a scheduler; the
267
+ // state file and /maintenance/status stay meaningful either way.
268
+ const maintenanceInterval = configuredIntervalMs();
269
+ if (maintenanceInterval > 0) {
270
+ maintenanceLoop = startMaintenanceLoop({
271
+ intervalMs: maintenanceInterval,
272
+ queueDir: QUEUE_DIR,
273
+ dbPath: DB_PATH,
274
+ statePath: MAINTENANCE_STATE_PATH,
275
+ runner: `api:${process.pid}`,
276
+ });
277
+ console.log(`🧹 Maintenance pass every ${Math.round(maintenanceInterval / 60_000)} min (in-process)`);
278
+ } else {
279
+ console.log('🧹 Maintenance loop disabled — an external scheduler is expected to run it.');
280
+ }
281
+
282
+ // In-flight work finishes before the process goes: a pass killed mid-write
283
+ // leaves a job in `.processing` that only the stale-lock timeout recovers.
284
+ const shutdown = (signal: string) => {
285
+ console.log(`\n${signal} — stopping maintenance loop and closing the store.`);
286
+ maintenanceLoop?.stop();
287
+ try { store.close?.(); } catch { /* already closed */ }
288
+ process.exit(0);
289
+ };
290
+ process.on('SIGINT', () => shutdown('SIGINT'));
291
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
292
+ }