humemory 0.2.1

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 (81) hide show
  1. package/.githooks/post-commit +22 -0
  2. package/AGENTS.md +328 -0
  3. package/CHANGELOG.md +198 -0
  4. package/LICENSE +21 -0
  5. package/README.md +488 -0
  6. package/bin/humemory.js +19 -0
  7. package/dist/agent/claude-hook.d.ts +15 -0
  8. package/dist/agent/claude-hook.js +38 -0
  9. package/dist/agent/commit-closer.d.ts +60 -0
  10. package/dist/agent/commit-closer.js +125 -0
  11. package/dist/agent/learning-extractor.d.ts +10 -0
  12. package/dist/agent/learning-extractor.js +75 -0
  13. package/dist/agent/session-context.d.ts +63 -0
  14. package/dist/agent/session-context.js +216 -0
  15. package/dist/agent/session-parser.d.ts +12 -0
  16. package/dist/agent/session-parser.js +85 -0
  17. package/dist/api/dream-routes.d.ts +7 -0
  18. package/dist/api/dream-routes.js +40 -0
  19. package/dist/api/intentions-routes.d.ts +23 -0
  20. package/dist/api/intentions-routes.js +252 -0
  21. package/dist/api/memory-routes.d.ts +10 -0
  22. package/dist/api/memory-routes.js +277 -0
  23. package/dist/api/scripts-routes.d.ts +13 -0
  24. package/dist/api/scripts-routes.js +129 -0
  25. package/dist/api/server.d.ts +33 -0
  26. package/dist/api/server.js +157 -0
  27. package/dist/cli/index.d.ts +2 -0
  28. package/dist/cli/index.js +798 -0
  29. package/dist/core/clock.d.ts +38 -0
  30. package/dist/core/clock.js +52 -0
  31. package/dist/core/cue-arg.d.ts +19 -0
  32. package/dist/core/cue-arg.js +72 -0
  33. package/dist/core/cues.d.ts +138 -0
  34. package/dist/core/cues.js +372 -0
  35. package/dist/core/decay.d.ts +49 -0
  36. package/dist/core/decay.js +157 -0
  37. package/dist/core/dreamer.d.ts +114 -0
  38. package/dist/core/dreamer.js +427 -0
  39. package/dist/core/embeddings.d.ts +79 -0
  40. package/dist/core/embeddings.js +133 -0
  41. package/dist/core/event-bus.d.ts +71 -0
  42. package/dist/core/event-bus.js +67 -0
  43. package/dist/core/hybrid.d.ts +33 -0
  44. package/dist/core/hybrid.js +63 -0
  45. package/dist/core/llm-generator.d.ts +18 -0
  46. package/dist/core/llm-generator.js +69 -0
  47. package/dist/core/sanitize.d.ts +57 -0
  48. package/dist/core/sanitize.js +87 -0
  49. package/dist/core/scripts.d.ts +55 -0
  50. package/dist/core/scripts.js +96 -0
  51. package/dist/core/search.d.ts +42 -0
  52. package/dist/core/search.js +173 -0
  53. package/dist/core/trust.d.ts +48 -0
  54. package/dist/core/trust.js +57 -0
  55. package/dist/core/types.d.ts +333 -0
  56. package/dist/core/types.js +1 -0
  57. package/dist/core/vector-clusterer.d.ts +53 -0
  58. package/dist/core/vector-clusterer.js +113 -0
  59. package/dist/index.d.ts +28 -0
  60. package/dist/index.js +18 -0
  61. package/dist/mcp/server.d.ts +22 -0
  62. package/dist/mcp/server.js +158 -0
  63. package/dist/store/sqlite.d.ts +240 -0
  64. package/dist/store/sqlite.js +1653 -0
  65. package/docs/TESTING.md +244 -0
  66. package/package.json +95 -0
  67. package/public/app/galaxy-f42190mq.js +10 -0
  68. package/public/app/index-2cf31xxn.css +1 -0
  69. package/public/app/index-epqg22cp.js +1 -0
  70. package/public/app/index-f9h80bzq.js +12 -0
  71. package/public/app/index-gbfwa9vq.js +2 -0
  72. package/public/app/index-kvhc17mz.js +2 -0
  73. package/public/app/index-pbd5t4dj.js +2 -0
  74. package/public/app/index.html +12 -0
  75. package/public/app/promenade-cnzzpm73.js +4111 -0
  76. package/public/app/river-tyawhh8w.js +13 -0
  77. package/public/session.html +659 -0
  78. package/scripts/consolidate.js +46 -0
  79. package/scripts/hook-post-commit.ts +80 -0
  80. package/scripts/hook-session-start.ts +92 -0
  81. package/scripts/hook-session.ts +60 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * HTTP routes for prospective memory — Phase 5.4.
3
+ *
4
+ * Sub-router mounted by `src/api/server.ts`. It takes its store as a parameter
5
+ * rather than opening one at module load: that is what makes it testable without
6
+ * touching the production database (see docs/TESTING.md).
7
+ */
8
+ import { Hono } from 'hono';
9
+ import { SqliteCueResolver, loopId } from '../core/cues.js';
10
+ const INTENTION_STATUSES = ['armed', 'fired', 'closed', 'expired'];
11
+ const CUE_STATUSES = ['armed', 'fired', 'cancelled'];
12
+ const CUE_KINDS = ['time', 'event'];
13
+ const EVENT_TYPES = ['file_open', 'branch_switch', 'error_pattern', 'commit'];
14
+ /** Input validation error — surfaced as a 400 rather than a 500. */
15
+ class BadRequest extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = 'BadRequest'; // scripts-routes matches on this across module boundaries
19
+ }
20
+ }
21
+ function parseStatuses(raw, allowed) {
22
+ if (!raw)
23
+ return undefined;
24
+ const values = raw.split(',').map((s) => s.trim()).filter(Boolean);
25
+ const invalid = values.filter((v) => !allowed.includes(v));
26
+ if (invalid.length)
27
+ throw new BadRequest(`Unknown status: ${invalid.join(', ')}`);
28
+ return values;
29
+ }
30
+ function parseLimit(raw, fallback = 50) {
31
+ if (raw === undefined)
32
+ return fallback;
33
+ const n = Number(raw);
34
+ if (!Number.isInteger(n) || n < 1 || n > 500) {
35
+ throw new BadRequest('limit must be an integer between 1 and 500');
36
+ }
37
+ return n;
38
+ }
39
+ /**
40
+ * Validates a trigger coming off the network. Incoming JSON is not trusted: a
41
+ * malformed `triggerSpec` would be stored as is and would never wake anything.
42
+ */
43
+ export function validateTriggerSpec(raw) {
44
+ if (!raw || typeof raw !== 'object')
45
+ throw new BadRequest('triggerSpec is required');
46
+ const spec = raw;
47
+ if (spec.kind === 'time') {
48
+ const { at, cron } = spec;
49
+ if (at === undefined && cron === undefined) {
50
+ throw new BadRequest('a time cue requires "at" (ISO) or "cron"');
51
+ }
52
+ if (at !== undefined) {
53
+ if (typeof at !== 'string' || Number.isNaN(new Date(at).getTime())) {
54
+ throw new BadRequest('"at" must be a valid ISO date');
55
+ }
56
+ }
57
+ if (cron !== undefined && typeof cron !== 'string') {
58
+ throw new BadRequest('"cron" must be a string');
59
+ }
60
+ return { kind: 'time', ...(at ? { at: at } : {}), ...(cron ? { cron: cron } : {}) };
61
+ }
62
+ if (spec.kind === 'event') {
63
+ switch (spec.type) {
64
+ case 'file_open':
65
+ if (typeof spec.path !== 'string' || !spec.path)
66
+ throw new BadRequest('"path" is required');
67
+ return { kind: 'event', type: 'file_open', path: spec.path };
68
+ case 'branch_switch':
69
+ if (typeof spec.branch !== 'string' || !spec.branch)
70
+ throw new BadRequest('"branch" is required');
71
+ return { kind: 'event', type: 'branch_switch', branch: spec.branch };
72
+ case 'error_pattern':
73
+ if (typeof spec.pattern !== 'string' || !spec.pattern)
74
+ throw new BadRequest('"pattern" is required');
75
+ return { kind: 'event', type: 'error_pattern', pattern: spec.pattern };
76
+ default:
77
+ throw new BadRequest('unknown event type (file_open | branch_switch | error_pattern)');
78
+ }
79
+ }
80
+ throw new BadRequest('kind must be "time" or "event"');
81
+ }
82
+ /** Validates an event pushed to `POST /events`. */
83
+ export function validateAppEvent(raw) {
84
+ if (!raw || typeof raw !== 'object')
85
+ throw new BadRequest('event is required');
86
+ const e = raw;
87
+ if (typeof e.type !== 'string' || !EVENT_TYPES.includes(e.type)) {
88
+ throw new BadRequest(`type must be one of: ${EVENT_TYPES.join(', ')}`);
89
+ }
90
+ if (typeof e.directory !== 'string' || !e.directory)
91
+ throw new BadRequest('"directory" is required');
92
+ switch (e.type) {
93
+ case 'file_open':
94
+ if (typeof e.path !== 'string' || !e.path)
95
+ throw new BadRequest('"path" is required');
96
+ return { type: 'file_open', path: e.path, directory: e.directory };
97
+ case 'branch_switch':
98
+ if (typeof e.branch !== 'string' || !e.branch)
99
+ throw new BadRequest('"branch" is required');
100
+ return { type: 'branch_switch', branch: e.branch, directory: e.directory };
101
+ case 'error_pattern':
102
+ if (typeof e.text !== 'string' || !e.text)
103
+ throw new BadRequest('"text" is required');
104
+ return { type: 'error_pattern', text: e.text, directory: e.directory };
105
+ default:
106
+ if (typeof e.sha !== 'string' || !e.sha)
107
+ throw new BadRequest('"sha" is required');
108
+ return {
109
+ type: 'commit',
110
+ sha: e.sha,
111
+ message: typeof e.message === 'string' ? e.message : '',
112
+ files: Array.isArray(e.files) ? e.files.filter((f) => typeof f === 'string') : [],
113
+ directory: e.directory,
114
+ };
115
+ }
116
+ }
117
+ /** JSON shape of an intention: the short id is exposed, since that is what humans handle. */
118
+ function serializeIntention(intention) {
119
+ return { ...intention, loopId: loopId(intention.id) };
120
+ }
121
+ function serializeCue(cue) {
122
+ return cue;
123
+ }
124
+ export function createIntentionRoutes(store, options = {}) {
125
+ const app = new Hono();
126
+ const resolver = new SqliteCueResolver(store, { clock: options.clock });
127
+ // Invalid input is the client's error, not the server's.
128
+ const guard = async (c, fn) => {
129
+ try {
130
+ return await fn();
131
+ }
132
+ catch (err) {
133
+ if (err instanceof BadRequest)
134
+ return c.json({ error: err.message }, 400);
135
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
136
+ }
137
+ };
138
+ app.post('/intentions', (c) => guard(c, async () => {
139
+ const body = await c.req.json().catch(() => null);
140
+ if (!body || typeof body.content !== 'string' || !body.content.trim()) {
141
+ throw new BadRequest('"content" is required');
142
+ }
143
+ if (typeof body.directory !== 'string' || !body.directory) {
144
+ throw new BadRequest('"directory" is required');
145
+ }
146
+ let expiresAt;
147
+ if (body.expiresAt) {
148
+ expiresAt = new Date(body.expiresAt);
149
+ if (Number.isNaN(expiresAt.getTime()))
150
+ throw new BadRequest('"expiresAt" is invalid');
151
+ }
152
+ const cues = Array.isArray(body.cues)
153
+ ? body.cues.map((spec) => validateTriggerSpec(spec))
154
+ : [];
155
+ const intention = await store.addIntention({
156
+ content: body.content.trim(),
157
+ directory: body.directory,
158
+ expiresAt,
159
+ relatedMemoryId: typeof body.relatedMemoryId === 'string' ? body.relatedMemoryId : undefined,
160
+ }, cues);
161
+ return c.json({ intention: serializeIntention(intention) }, 201);
162
+ }));
163
+ app.get('/intentions', (c) => guard(c, async () => {
164
+ const status = parseStatuses(c.req.query('status'), INTENTION_STATUSES);
165
+ const directory = c.req.query('directory');
166
+ const limit = parseLimit(c.req.query('limit'));
167
+ const intentions = await store.listIntentions({ status, directory, limit });
168
+ return c.json({ intentions: intentions.map(serializeIntention), count: intentions.length });
169
+ }));
170
+ app.get('/intentions/:id', (c) => guard(c, async () => {
171
+ const intention = await store.getIntention(c.req.param('id'));
172
+ if (!intention)
173
+ return c.json({ error: 'Intention not found' }, 404);
174
+ const cues = await store.listCues({ intentionId: intention.id });
175
+ return c.json({ intention: serializeIntention(intention), cues: cues.map(serializeCue) });
176
+ }));
177
+ /** Closes a loop. Remaining cues are cancelled — otherwise they would wake a ghost. */
178
+ app.post('/intentions/:id/close', (c) => guard(c, async () => {
179
+ const id = c.req.param('id');
180
+ if (!(await store.getIntention(id)))
181
+ return c.json({ error: 'Intention not found' }, 404);
182
+ const body = await c.req.json().catch(() => ({}));
183
+ const intention = await store.updateIntentionStatus(id, 'closed', {
184
+ closedByCommit: typeof body?.commit === 'string' ? body.commit : undefined,
185
+ });
186
+ for (const cue of await store.listCues({ intentionId: id, status: 'armed' })) {
187
+ await store.updateCueStatus(cue.id, 'cancelled');
188
+ }
189
+ return c.json({ intention: serializeIntention(intention) });
190
+ }));
191
+ /** Force-fire, useful for debugging and for the dashboard. */
192
+ app.post('/intentions/:id/fire', (c) => guard(c, async () => {
193
+ const id = c.req.param('id');
194
+ if (!(await store.getIntention(id)))
195
+ return c.json({ error: 'Intention not found' }, 404);
196
+ const intention = await store.updateIntentionStatus(id, 'fired');
197
+ return c.json({ intention: serializeIntention(intention) });
198
+ }));
199
+ app.delete('/intentions/:id', (c) => guard(c, async () => {
200
+ const id = c.req.param('id');
201
+ if (!(await store.getIntention(id)))
202
+ return c.json({ error: 'Intention not found' }, 404);
203
+ await store.deleteIntention(id); // cues cascade away
204
+ return c.json({ success: true });
205
+ }));
206
+ app.post('/cues', (c) => guard(c, async () => {
207
+ const body = await c.req.json().catch(() => null);
208
+ if (!body || typeof body.intentionId !== 'string')
209
+ throw new BadRequest('"intentionId" is required');
210
+ if (!(await store.getIntention(body.intentionId))) {
211
+ return c.json({ error: 'Intention not found' }, 404);
212
+ }
213
+ const cue = await store.addCue({
214
+ intentionId: body.intentionId,
215
+ triggerSpec: validateTriggerSpec(body.triggerSpec),
216
+ });
217
+ return c.json({ cue: serializeCue(cue) }, 201);
218
+ }));
219
+ app.get('/cues', (c) => guard(c, async () => {
220
+ const status = parseStatuses(c.req.query('status'), CUE_STATUSES);
221
+ const kindRaw = c.req.query('kind');
222
+ if (kindRaw && !CUE_KINDS.includes(kindRaw)) {
223
+ throw new BadRequest('kind must be "time" or "event"');
224
+ }
225
+ const cues = await store.listCues({
226
+ intentionId: c.req.query('intentionId'),
227
+ status,
228
+ kind: kindRaw,
229
+ limit: parseLimit(c.req.query('limit')),
230
+ });
231
+ return c.json({ cues: cues.map(serializeCue), count: cues.length });
232
+ }));
233
+ /** Pushes an event: the resolver wakes the loops that match. */
234
+ app.post('/events', (c) => guard(c, async () => {
235
+ const event = validateAppEvent(await c.req.json().catch(() => null));
236
+ const fired = [];
237
+ for (const cue of await resolver.resolveEventCues(event)) {
238
+ fired.push(await resolver.fire(cue.id));
239
+ }
240
+ return c.json({ event, fired: fired.map(serializeIntention), count: fired.length });
241
+ }));
242
+ /** Sweeps: expires overdue loops, fires due time cues. */
243
+ app.post('/cues/resolve', (c) => guard(c, async () => {
244
+ const expired = await resolver.expireStale();
245
+ const fired = [];
246
+ for (const cue of await resolver.resolveTimeCues()) {
247
+ fired.push(await resolver.fire(cue.id));
248
+ }
249
+ return c.json({ expired, fired: fired.map(serializeIntention), count: fired.length });
250
+ }));
251
+ return app;
252
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * HTTP routes for retrospective memory.
3
+ *
4
+ * Extracted from `server.ts` for the same reason as the prospective routes: they
5
+ * take their store as a parameter, so they can be tested without opening the
6
+ * production database or raising a server (BUG-08).
7
+ */
8
+ import { Hono } from 'hono';
9
+ import type { SQLiteStore } from '../store/sqlite.js';
10
+ export declare function createMemoryRoutes(store: SQLiteStore): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,277 @@
1
+ /**
2
+ * HTTP routes for retrospective memory.
3
+ *
4
+ * Extracted from `server.ts` for the same reason as the prospective routes: they
5
+ * take their store as a parameter, so they can be tested without opening the
6
+ * production database or raising a server (BUG-08).
7
+ */
8
+ import { Hono } from 'hono';
9
+ export function createMemoryRoutes(store) {
10
+ const app = new Hono();
11
+ // === MEMORIES ===
12
+ app.post('/memories', async (c) => {
13
+ const body = await c.req.json();
14
+ try {
15
+ const validTypes = ['episodic', 'semantic', 'procedural'];
16
+ const memoryType = validTypes.includes(body.memoryType) ? body.memoryType : 'semantic';
17
+ const memory = await store.add({
18
+ content: body.content,
19
+ directory: body.directory || process.cwd(),
20
+ day: body.day || new Date().toISOString().split('T')[0],
21
+ keywords: body.keywords || [],
22
+ sessionId: body.sessionId || 'default',
23
+ level1Summary: body.level1Summary,
24
+ level2Essential: body.level2Essential,
25
+ level3Keywords: body.level3Keywords,
26
+ memoryType: memoryType,
27
+ // Phase 6.0.1 — attribution on every write path
28
+ source: body.source ?? 'agent',
29
+ agent: c.req.header('X-Humemory-Agent') ?? body.agent ?? 'unknown',
30
+ });
31
+ return c.json({ success: true, memory }, 201);
32
+ }
33
+ catch (error) {
34
+ return c.json({ success: false, error: String(error) }, 500);
35
+ }
36
+ });
37
+ app.get('/memories', async (c) => {
38
+ const limit = parseInt(c.req.query('limit') || '50');
39
+ const level = c.req.query('level');
40
+ const memories = await store.list({
41
+ limit,
42
+ level: level !== undefined ? parseInt(level) : undefined,
43
+ });
44
+ return c.json({ success: true, memories });
45
+ });
46
+ app.get('/memories/:id', async (c) => {
47
+ const memory = await store.getById(c.req.param('id'));
48
+ if (!memory) {
49
+ return c.json({ success: false, error: 'Not found' }, 404);
50
+ }
51
+ return c.json({ success: true, memory });
52
+ });
53
+ app.post('/memories/:id/recall', async (c) => {
54
+ try {
55
+ // Phase 6.0.1 — the calling agent earns (or not) the `reused` verification
56
+ const agent = c.req.header('X-Humemory-Agent');
57
+ // Attribution only. `X-Humemory-Agent` is an unauthenticated header on a
58
+ // server with no auth, so a recall here reinforces the trace and records
59
+ // who asked, but cannot earn the `reused` verification — that would let
60
+ // any caller on :3456 verify any trace by naming itself someone else.
61
+ const memory = await store.recall(c.req.param('id'), agent, { identityTrusted: false });
62
+ return c.json({ success: true, memory });
63
+ }
64
+ catch (error) {
65
+ return c.json({ success: false, error: String(error) }, 500);
66
+ }
67
+ });
68
+ // Phase 6.0.1 — trust layer
69
+ //
70
+ // There is deliberately no `POST /memories/:id/verify` route. `human` is the
71
+ // strongest verification reason (+25 trust) and the only one that lets a
72
+ // trace render *bare*, outside the untrusted markers, in the next session's
73
+ // context block. The API has no authentication, so exposing it would let any
74
+ // caller on :3456 grant "a human looked at this" to a trace it just wrote.
75
+ // Human verification requires a human at a terminal: `pnpm cli verify <id>`.
76
+ // Earned verification (reused / grounded / corroborated) is set by the store
77
+ // itself from evidence, never by a request.
78
+ app.post('/memories/:id/refute', async (c) => {
79
+ try {
80
+ const body = await c.req.json().catch(() => ({}));
81
+ const memory = await store.refute(c.req.param('id'), body.reason);
82
+ return c.json({ success: true, memory });
83
+ }
84
+ catch (error) {
85
+ return c.json({ success: false, error: String(error) }, 500);
86
+ }
87
+ });
88
+ // Phase 6.0.2 — contradiction: this trace wins against `otherId`
89
+ app.post('/memories/:id/contradicts', async (c) => {
90
+ try {
91
+ const body = await c.req.json();
92
+ if (!body.otherId)
93
+ return c.json({ success: false, error: 'otherId required' }, 400);
94
+ const result = await store.contradict(c.req.param('id'), body.otherId, {
95
+ reason: body.reason,
96
+ agent: c.req.header('X-Humemory-Agent'),
97
+ });
98
+ return c.json({ success: true, ...result });
99
+ }
100
+ catch (error) {
101
+ return c.json({ success: false, error: String(error) }, 500);
102
+ }
103
+ });
104
+ app.delete('/memories/:id', async (c) => {
105
+ await store.delete(c.req.param('id'));
106
+ return c.json({ success: true });
107
+ });
108
+ // === SEARCH ===
109
+ app.get('/search', async (c) => {
110
+ const query = c.req.query('q');
111
+ if (!query) {
112
+ return c.json({ success: false, error: 'Missing query parameter "q"' }, 400);
113
+ }
114
+ const dateFrom = c.req.query('dateFrom') ? new Date(c.req.query('dateFrom')) : undefined;
115
+ const dateTo = c.req.query('dateTo') ? new Date(c.req.query('dateTo')) : undefined;
116
+ const minSaillance = c.req.query('minSaillance') ? parseInt(c.req.query('minSaillance')) : undefined;
117
+ const minRecalls = c.req.query('minRecalls') ? parseInt(c.req.query('minRecalls')) : undefined;
118
+ const memoryType = c.req.query('type');
119
+ const results = await store.search({
120
+ query,
121
+ directory: c.req.query('directory'),
122
+ sessionId: c.req.query('sessionId'),
123
+ maxLevel: parseInt(c.req.query('maxLevel') || '3'),
124
+ limit: parseInt(c.req.query('limit') || '10'),
125
+ memoryType,
126
+ dateFrom,
127
+ dateTo,
128
+ minSaillance,
129
+ minRecalls,
130
+ });
131
+ return c.json({ success: true, results });
132
+ });
133
+ // === PHOTOGRAPHIC ===
134
+ app.post('/memories/:id/photo', async (c) => {
135
+ try {
136
+ const body = await c.req.json().catch(() => ({}));
137
+ const enable = body.enable !== false; // default true
138
+ const memory = await store.setPhotographic(c.req.param('id'), enable);
139
+ return c.json({ success: true, memory });
140
+ }
141
+ catch (error) {
142
+ return c.json({ success: false, error: String(error) }, 500);
143
+ }
144
+ });
145
+ // === SIMILAR ===
146
+ app.get('/memories/:id/similar', async (c) => {
147
+ try {
148
+ const limit = parseInt(c.req.query('limit') || '5');
149
+ const threshold = parseInt(c.req.query('threshold') || '50');
150
+ const results = await store.findSimilar(c.req.param('id'), { limit, threshold });
151
+ return c.json({ success: true, results });
152
+ }
153
+ catch (error) {
154
+ return c.json({ success: false, error: String(error) }, 500);
155
+ }
156
+ });
157
+ // === MERGE ===
158
+ app.post('/memories/:id/merge', async (c) => {
159
+ try {
160
+ const body = await c.req.json();
161
+ if (!body.targetId) {
162
+ return c.json({ success: false, error: 'Missing targetId' }, 400);
163
+ }
164
+ const result = await store.merge(c.req.param('id'), body.targetId, {
165
+ autoMergeContent: body.autoMergeContent ?? false,
166
+ });
167
+ return c.json({ success: true, result });
168
+ }
169
+ catch (error) {
170
+ return c.json({ success: false, error: String(error) }, 500);
171
+ }
172
+ });
173
+ // === DECAY ===
174
+ app.post('/decay', async (c) => {
175
+ await store.updateDecay();
176
+ return c.json({ success: true });
177
+ });
178
+ // === STATUS ===
179
+ app.get('/status', async (c) => {
180
+ const memories = await store.list({ limit: 1000 });
181
+ const byLevel = [0, 0, 0, 0, 0];
182
+ for (const m of memories) {
183
+ byLevel[m.currentLevel]++;
184
+ }
185
+ const avgSaillance = memories.reduce((sum, m) => sum + m.saillance, 0) / (memories.length || 1);
186
+ const avgRecalls = memories.reduce((sum, m) => sum + m.recallCount, 0) / (memories.length || 1);
187
+ return c.json({
188
+ success: true,
189
+ status: {
190
+ total: memories.length,
191
+ byLevel: {
192
+ level0: byLevel[0],
193
+ level1: byLevel[1],
194
+ level2: byLevel[2],
195
+ level3: byLevel[3],
196
+ level4: byLevel[4],
197
+ },
198
+ averages: {
199
+ saillance: Math.round(avgSaillance),
200
+ recalls: parseFloat(avgRecalls.toFixed(1)),
201
+ },
202
+ },
203
+ });
204
+ });
205
+ // === SESSIONS (for Replay visualization) ===
206
+ app.get('/sessions', async (c) => {
207
+ const memories = await store.list({ limit: 1000 });
208
+ const sessionMap = new Map();
209
+ for (const m of memories) {
210
+ const existing = sessionMap.get(m.sessionId);
211
+ if (existing) {
212
+ existing.count++;
213
+ if (new Date(m.createdAt) < existing.firstEvent)
214
+ existing.firstEvent = new Date(m.createdAt);
215
+ if (new Date(m.createdAt) > existing.lastEvent)
216
+ existing.lastEvent = new Date(m.createdAt);
217
+ }
218
+ else {
219
+ sessionMap.set(m.sessionId, {
220
+ sessionId: m.sessionId,
221
+ count: 1,
222
+ firstEvent: new Date(m.createdAt),
223
+ lastEvent: new Date(m.createdAt),
224
+ directory: m.directory,
225
+ });
226
+ }
227
+ }
228
+ const sessions = Array.from(sessionMap.values())
229
+ .sort((a, b) => b.lastEvent.getTime() - a.lastEvent.getTime());
230
+ return c.json({ success: true, sessions });
231
+ });
232
+ app.get('/sessions/:id', async (c) => {
233
+ const sessionId = decodeURIComponent(c.req.param('id'));
234
+ const memories = await store.list({ limit: 1000 });
235
+ const sessionMemories = memories.filter(m => m.sessionId === sessionId);
236
+ const events = [];
237
+ for (const m of sessionMemories) {
238
+ events.push({
239
+ type: 'encoded',
240
+ timestamp: new Date(m.createdAt),
241
+ content: m.content,
242
+ memoryId: m.id,
243
+ level: m.currentLevel,
244
+ saillance: m.saillance,
245
+ });
246
+ if (m.lastRecalled) {
247
+ events.push({
248
+ type: 'recalled',
249
+ timestamp: new Date(m.lastRecalled),
250
+ content: m.content,
251
+ memoryId: m.id,
252
+ level: m.currentLevel,
253
+ saillance: m.saillance,
254
+ });
255
+ }
256
+ if (m.currentLevel > 0) {
257
+ const decayTime = new Date(new Date(m.createdAt).getTime() + 24 * 60 * 60 * 1000);
258
+ events.push({
259
+ type: 'decayed',
260
+ timestamp: decayTime,
261
+ content: m.content,
262
+ memoryId: m.id,
263
+ level: m.currentLevel,
264
+ saillance: m.saillance,
265
+ });
266
+ }
267
+ }
268
+ events.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
269
+ return c.json({
270
+ success: true,
271
+ sessionId,
272
+ events,
273
+ totalMemories: sessionMemories.length,
274
+ });
275
+ });
276
+ return app;
277
+ }
@@ -0,0 +1,13 @@
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
+ import { Hono } from 'hono';
12
+ import type { SQLiteStore } from '../store/sqlite.js';
13
+ export declare function createScriptRoutes(store: SQLiteStore): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,129 @@
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
+ import { Hono } from 'hono';
12
+ import { validateTriggerSpec } from './intentions-routes.js';
13
+ const SCRIPT_STATUSES = ['draft', 'active', 'archived'];
14
+ /** Input validation error — surfaced as a 400 rather than a 500. */
15
+ class BadRequest extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = 'BadRequest'; // subclasses default to 'Error' — see guard
19
+ }
20
+ }
21
+ function serializeScript(script) {
22
+ return { ...script, shortId: script.id.slice(0, 8) };
23
+ }
24
+ function validateSteps(raw) {
25
+ if (!Array.isArray(raw) || !raw.length)
26
+ throw new BadRequest('"steps" must be a non-empty array');
27
+ const steps = raw.map((s) => (typeof s === 'string' ? s.trim() : ''));
28
+ if (steps.some((s) => !s))
29
+ throw new BadRequest('every step must be a non-empty string');
30
+ return steps;
31
+ }
32
+ export function createScriptRoutes(store) {
33
+ const app = new Hono();
34
+ const guard = async (c, fn) => {
35
+ try {
36
+ return await fn();
37
+ }
38
+ catch (err) {
39
+ // validateTriggerSpec throws intentions-routes' own BadRequest class —
40
+ // instanceof would miss it across module boundaries, so match by name.
41
+ if (err instanceof Error && err.name === 'BadRequest') {
42
+ return c.json({ error: err.message }, 400);
43
+ }
44
+ return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
45
+ }
46
+ };
47
+ /** Unambiguous prefix match — humans handle short ids, like dream review. */
48
+ const findByPrefix = async (prefix) => {
49
+ const direct = await store.getScript(prefix);
50
+ if (direct)
51
+ return direct;
52
+ const all = await store.listScripts({ status: SCRIPT_STATUSES, limit: 500 });
53
+ const hits = all.filter((s) => s.id.startsWith(prefix));
54
+ return hits.length === 1 ? hits[0] : null;
55
+ };
56
+ app.post('/scripts', (c) => guard(c, async () => {
57
+ const body = await c.req.json().catch(() => null);
58
+ if (!body || typeof body.name !== 'string' || !body.name.trim()) {
59
+ throw new BadRequest('"name" is required');
60
+ }
61
+ if (typeof body.description !== 'string' || !body.description.trim()) {
62
+ throw new BadRequest('"description" is required');
63
+ }
64
+ if (typeof body.directory !== 'string' || !body.directory) {
65
+ throw new BadRequest('"directory" is required');
66
+ }
67
+ const steps = validateSteps(body.steps);
68
+ const cues = Array.isArray(body.cues)
69
+ ? body.cues.map((spec) => validateTriggerSpec(spec))
70
+ : [];
71
+ const script = await store.addScript({
72
+ name: body.name.trim(),
73
+ description: body.description.trim(),
74
+ steps,
75
+ directory: body.directory,
76
+ pinned: body.pinned === true,
77
+ // HTTP = agent claim → draft, always (8.3). No source override.
78
+ source: 'agent',
79
+ agent: c.req.header('X-Humemory-Agent') || undefined,
80
+ }, cues);
81
+ return c.json({ script: serializeScript(script) }, 201);
82
+ }));
83
+ app.get('/scripts', (c) => guard(c, async () => {
84
+ const raw = c.req.query('status');
85
+ let status;
86
+ if (raw) {
87
+ const values = raw.split(',').map((s) => s.trim());
88
+ const invalid = values.filter((v) => !SCRIPT_STATUSES.includes(v));
89
+ if (invalid.length)
90
+ throw new BadRequest(`Unknown status: ${invalid.join(', ')}`);
91
+ status = values;
92
+ }
93
+ const scripts = await store.listScripts({
94
+ status,
95
+ directory: c.req.query('directory'),
96
+ limit: 500,
97
+ });
98
+ return c.json({ scripts: scripts.map(serializeScript), count: scripts.length });
99
+ }));
100
+ app.get('/scripts/:id', (c) => guard(c, async () => {
101
+ const script = await findByPrefix(c.req.param('id'));
102
+ if (!script)
103
+ return c.json({ error: 'Script not found' }, 404);
104
+ const cues = await store.listCues({ targetKind: 'script', targetId: script.id });
105
+ return c.json({ script: serializeScript(script), cues });
106
+ }));
107
+ app.post('/scripts/:id/activate', (c) => guard(c, async () => {
108
+ const script = await findByPrefix(c.req.param('id'));
109
+ if (!script)
110
+ return c.json({ error: 'Script not found' }, 404);
111
+ return c.json({ script: serializeScript(await store.updateScriptStatus(script.id, 'active')) });
112
+ }));
113
+ app.post('/scripts/:id/archive', (c) => guard(c, async () => {
114
+ const script = await findByPrefix(c.req.param('id'));
115
+ if (!script)
116
+ return c.json({ error: 'Script not found' }, 404);
117
+ return c.json({ script: serializeScript(await store.updateScriptStatus(script.id, 'archived')) });
118
+ }));
119
+ app.post('/scripts/:id/fire', (c) => guard(c, async () => {
120
+ const script = await findByPrefix(c.req.param('id'));
121
+ if (!script)
122
+ return c.json({ error: 'Script not found' }, 404);
123
+ if (script.status !== 'active') {
124
+ return c.json({ error: `Script is ${script.status} — only active drills fire` }, 409);
125
+ }
126
+ return c.json({ script: serializeScript(await store.markScriptFired(script.id)) });
127
+ }));
128
+ return app;
129
+ }