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.
- package/AGENTS.md +49 -4
- package/CHANGELOG.md +12 -0
- package/README.md +22 -10
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +89 -0
- package/dist/agent/maintenance-queue.js +245 -87
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +68 -17
- package/dist/agent/maintenance-state.d.ts +4 -0
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +164 -4
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +5 -0
- package/dist/core/paths.js +27 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/package.json +4 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +546 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1175 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +78 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +28 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-size and cost limits shared by every route (SECURITY_AUDIT.md M-02).
|
|
3
|
+
*
|
|
4
|
+
* The API accepted JSON of any size and read cost parameters with a bare
|
|
5
|
+
* `parseInt`, so `?limit=999999999` or `NaN` reached the store unchecked and a
|
|
6
|
+
* single request could fill SQLite or pin the process. These caps are the
|
|
7
|
+
* business-level floor; `bodyLimit` in `server.ts` is the transport-level one.
|
|
8
|
+
*
|
|
9
|
+
* The values are deliberately generous — they exist to stop abuse, not to
|
|
10
|
+
* constrain ordinary use. A real learning trace is a few kilobytes at most.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Longest memory/intention content accepted on a write. */
|
|
14
|
+
export const MAX_CONTENT_LENGTH = 100_000;
|
|
15
|
+
/** Longest single keyword, and how many a memory may carry. */
|
|
16
|
+
export const MAX_KEYWORD_LENGTH = 200;
|
|
17
|
+
export const MAX_KEYWORDS = 100;
|
|
18
|
+
/** Longest short free-text field (directory, sessionId, agent, summaries…). */
|
|
19
|
+
export const MAX_SHORT_FIELD_LENGTH = 2_000;
|
|
20
|
+
/** Longest search query string. */
|
|
21
|
+
export const MAX_QUERY_LENGTH = 1_000;
|
|
22
|
+
/** How many steps or cues one script/intention may declare. */
|
|
23
|
+
export const MAX_COLLECTION_ITEMS = 100;
|
|
24
|
+
/** Ceiling for any `limit`-style pagination parameter. */
|
|
25
|
+
export const MAX_RESULT_LIMIT = 500;
|
|
26
|
+
/** Transport-level cap on a JSON request body, in bytes. */
|
|
27
|
+
export const MAX_BODY_BYTES = 1_000_000;
|
|
28
|
+
|
|
29
|
+
/** Thrown on a limit violation; routes map it to a 400. */
|
|
30
|
+
export class LimitExceeded extends Error {
|
|
31
|
+
constructor(message: string) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = 'LimitExceeded';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Parses a numeric query parameter with a finite, enforced range.
|
|
39
|
+
*
|
|
40
|
+
* Unlike `parseInt`, this rejects `NaN`, `Infinity`, floats and out-of-range
|
|
41
|
+
* values instead of passing them to the store.
|
|
42
|
+
*/
|
|
43
|
+
export function boundedInt(
|
|
44
|
+
raw: string | undefined,
|
|
45
|
+
opts: { fallback: number; min: number; max: number; name: string }
|
|
46
|
+
): number {
|
|
47
|
+
if (raw === undefined || raw === '') return opts.fallback;
|
|
48
|
+
const n = Number(raw);
|
|
49
|
+
if (!Number.isInteger(n) || n < opts.min || n > opts.max) {
|
|
50
|
+
throw new LimitExceeded(`"${opts.name}" must be an integer between ${opts.min} and ${opts.max}`);
|
|
51
|
+
}
|
|
52
|
+
return n;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Same, for an optional parameter with no default. */
|
|
56
|
+
export function boundedOptionalInt(
|
|
57
|
+
raw: string | undefined,
|
|
58
|
+
opts: { min: number; max: number; name: string }
|
|
59
|
+
): number | undefined {
|
|
60
|
+
if (raw === undefined || raw === '') return undefined;
|
|
61
|
+
return boundedInt(raw, { ...opts, fallback: 0 });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Requires a string no longer than `max`. */
|
|
65
|
+
export function boundedString(value: unknown, max: number, name: string): string {
|
|
66
|
+
if (typeof value !== 'string') throw new LimitExceeded(`"${name}" must be a string`);
|
|
67
|
+
if (value.length > max) {
|
|
68
|
+
throw new LimitExceeded(`"${name}" must be at most ${max} characters`);
|
|
69
|
+
}
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Same, but tolerates an absent value. */
|
|
74
|
+
export function boundedOptionalString(value: unknown, max: number, name: string): string | undefined {
|
|
75
|
+
if (value === undefined || value === null) return undefined;
|
|
76
|
+
return boundedString(value, max, name);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Requires an array of bounded strings, itself of bounded length. */
|
|
80
|
+
export function boundedStringArray(
|
|
81
|
+
value: unknown,
|
|
82
|
+
opts: { maxItems: number; maxItemLength: number; name: string }
|
|
83
|
+
): string[] {
|
|
84
|
+
if (value === undefined || value === null) return [];
|
|
85
|
+
if (!Array.isArray(value)) throw new LimitExceeded(`"${opts.name}" must be an array`);
|
|
86
|
+
if (value.length > opts.maxItems) {
|
|
87
|
+
throw new LimitExceeded(`"${opts.name}" must hold at most ${opts.maxItems} items`);
|
|
88
|
+
}
|
|
89
|
+
return value.map((item, i) => boundedString(item, opts.maxItemLength, `${opts.name}[${i}]`));
|
|
90
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP surface for maintenance health (same testable-sub-router pattern as
|
|
3
|
+
* dream-routes.ts: every path is a parameter, no production files in tests).
|
|
4
|
+
*
|
|
5
|
+
* These routes sit behind the API token like every other data route. `/health`
|
|
6
|
+
* deliberately stays coarse and public — the watchdog only needs liveness, and
|
|
7
|
+
* `lastError` is internal detail that has no business on an unauthenticated
|
|
8
|
+
* endpoint (SECURITY_AUDIT.md L-01).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Hono } from 'hono';
|
|
12
|
+
import { assessMaintenance, readMaintenanceState, DEFAULT_STALE_AFTER_MS } from '../agent/maintenance-state.js';
|
|
13
|
+
import { serverErrorBody } from './errors.js';
|
|
14
|
+
|
|
15
|
+
export interface MaintenanceLoopHandle {
|
|
16
|
+
runNow(): Promise<void>;
|
|
17
|
+
readonly busy: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface MaintenanceRoutesOptions {
|
|
21
|
+
statePath: string;
|
|
22
|
+
staleAfterMs?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Resolves the loop this process hosts, or undefined when an external
|
|
25
|
+
* scheduler drives maintenance instead. A getter rather than a value because
|
|
26
|
+
* the server binds the routes before it decides to start the loop.
|
|
27
|
+
*/
|
|
28
|
+
loop?: () => MaintenanceLoopHandle | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createMaintenanceRoutes(options: MaintenanceRoutesOptions) {
|
|
32
|
+
const app = new Hono();
|
|
33
|
+
const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
|
|
34
|
+
|
|
35
|
+
app.get('/maintenance/status', async (c) => {
|
|
36
|
+
try {
|
|
37
|
+
const state = await readMaintenanceState(options.statePath);
|
|
38
|
+
const health = assessMaintenance(state, { staleAfterMs });
|
|
39
|
+
return c.json({
|
|
40
|
+
success: true,
|
|
41
|
+
maintenance: {
|
|
42
|
+
...health,
|
|
43
|
+
hostedHere: options.loop?.() !== undefined,
|
|
44
|
+
running: options.loop?.()?.busy ?? false,
|
|
45
|
+
staleAfterMs,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
} catch (error) {
|
|
49
|
+
return c.json(serverErrorBody('maintenance status', error), 500);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Force a pass — the dashboard's "consolidate now", and the escape hatch when
|
|
54
|
+
// the schedule is known to have missed a window.
|
|
55
|
+
app.post('/maintenance/run', async (c) => {
|
|
56
|
+
const loop = options.loop?.();
|
|
57
|
+
if (!loop) {
|
|
58
|
+
return c.json({ success: false, error: 'No maintenance loop in this process' }, 409);
|
|
59
|
+
}
|
|
60
|
+
if (loop.busy) {
|
|
61
|
+
return c.json({ success: false, error: 'A maintenance pass is already running' }, 409);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
await loop.runNow();
|
|
65
|
+
const state = await readMaintenanceState(options.statePath);
|
|
66
|
+
return c.json({ success: true, maintenance: assessMaintenance(state, { staleAfterMs }) });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return c.json(serverErrorBody('maintenance run', error), 500);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
return app;
|
|
73
|
+
}
|
|
@@ -0,0 +1,391 @@
|
|
|
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
|
+
|
|
9
|
+
import { Hono } from 'hono';
|
|
10
|
+
import type { SQLiteStore } from '../store/sqlite.js';
|
|
11
|
+
import { serverErrorBody } from './errors.js';
|
|
12
|
+
import {
|
|
13
|
+
LimitExceeded,
|
|
14
|
+
boundedInt,
|
|
15
|
+
boundedOptionalInt,
|
|
16
|
+
boundedString,
|
|
17
|
+
boundedOptionalString,
|
|
18
|
+
boundedStringArray,
|
|
19
|
+
MAX_CONTENT_LENGTH,
|
|
20
|
+
MAX_KEYWORDS,
|
|
21
|
+
MAX_KEYWORD_LENGTH,
|
|
22
|
+
MAX_SHORT_FIELD_LENGTH,
|
|
23
|
+
MAX_QUERY_LENGTH,
|
|
24
|
+
MAX_RESULT_LIMIT,
|
|
25
|
+
} from './limits.js';
|
|
26
|
+
|
|
27
|
+
export function createMemoryRoutes(store: SQLiteStore) {
|
|
28
|
+
const app = new Hono();
|
|
29
|
+
|
|
30
|
+
// Limit violations are the caller's fault, not ours: 400, not 500
|
|
31
|
+
// (SECURITY_AUDIT.md M-02).
|
|
32
|
+
app.onError((error, c) => {
|
|
33
|
+
if (error instanceof LimitExceeded) {
|
|
34
|
+
return c.json({ success: false, error: error.message }, 400);
|
|
35
|
+
}
|
|
36
|
+
throw error;
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// === MEMORIES ===
|
|
40
|
+
app.post('/memories', async (c) => {
|
|
41
|
+
const body = await c.req.json();
|
|
42
|
+
|
|
43
|
+
// Every user-supplied field is bounded before it reaches the store: without
|
|
44
|
+
// this a single request could write an arbitrarily large row (M-02).
|
|
45
|
+
const content = boundedString(body.content, MAX_CONTENT_LENGTH, 'content');
|
|
46
|
+
const keywords = boundedStringArray(body.keywords, {
|
|
47
|
+
maxItems: MAX_KEYWORDS,
|
|
48
|
+
maxItemLength: MAX_KEYWORD_LENGTH,
|
|
49
|
+
name: 'keywords',
|
|
50
|
+
});
|
|
51
|
+
// level3Keywords is the flat BM25 keyword line, not an array (core/types.ts).
|
|
52
|
+
const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
|
|
53
|
+
const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
|
|
54
|
+
const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
|
|
55
|
+
const sessionId = boundedOptionalString(body.sessionId, MAX_SHORT_FIELD_LENGTH, 'sessionId');
|
|
56
|
+
const level1Summary = boundedOptionalString(body.level1Summary, MAX_CONTENT_LENGTH, 'level1Summary');
|
|
57
|
+
const level2Essential = boundedOptionalString(body.level2Essential, MAX_CONTENT_LENGTH, 'level2Essential');
|
|
58
|
+
const agentField = boundedOptionalString(body.agent, MAX_SHORT_FIELD_LENGTH, 'agent');
|
|
59
|
+
const agentHeader = boundedOptionalString(
|
|
60
|
+
c.req.header('X-Humemory-Agent'),
|
|
61
|
+
MAX_SHORT_FIELD_LENGTH,
|
|
62
|
+
'X-Humemory-Agent'
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const validTypes = ['episodic', 'semantic', 'procedural'];
|
|
67
|
+
const memoryType = validTypes.includes(body.memoryType) ? body.memoryType : 'semantic';
|
|
68
|
+
|
|
69
|
+
const memory = await store.add({
|
|
70
|
+
content,
|
|
71
|
+
directory: directory || process.cwd(),
|
|
72
|
+
day: day || new Date().toISOString().split('T')[0],
|
|
73
|
+
keywords,
|
|
74
|
+
sessionId: sessionId || 'default',
|
|
75
|
+
level1Summary,
|
|
76
|
+
level2Essential,
|
|
77
|
+
level3Keywords,
|
|
78
|
+
memoryType: memoryType as 'episodic' | 'semantic' | 'procedural',
|
|
79
|
+
// Phase 6.0.1 — attribution on every write path
|
|
80
|
+
source: body.source ?? 'agent',
|
|
81
|
+
agent: agentHeader ?? agentField ?? 'unknown',
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
return c.json({ success: true, memory }, 201);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
app.get('/memories', async (c) => {
|
|
91
|
+
const limit = boundedInt(c.req.query('limit'), {
|
|
92
|
+
fallback: 50,
|
|
93
|
+
min: 1,
|
|
94
|
+
max: MAX_RESULT_LIMIT,
|
|
95
|
+
name: 'limit',
|
|
96
|
+
});
|
|
97
|
+
const level = boundedOptionalInt(c.req.query('level'), { min: 0, max: 4, name: 'level' });
|
|
98
|
+
|
|
99
|
+
const memories = await store.list({ limit, level: level as any });
|
|
100
|
+
|
|
101
|
+
return c.json({ success: true, memories });
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
app.get('/memories/:id', async (c) => {
|
|
105
|
+
const memory = await store.getById(c.req.param('id'));
|
|
106
|
+
|
|
107
|
+
if (!memory) {
|
|
108
|
+
return c.json({ success: false, error: 'Not found' }, 404);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return c.json({ success: true, memory });
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
app.post('/memories/:id/recall', async (c) => {
|
|
115
|
+
try {
|
|
116
|
+
// Phase 6.0.1 — the calling agent earns (or not) the `reused` verification
|
|
117
|
+
const agent = c.req.header('X-Humemory-Agent');
|
|
118
|
+
// Attribution only. `X-Humemory-Agent` is an unauthenticated header on a
|
|
119
|
+
// server with no auth, so a recall here reinforces the trace and records
|
|
120
|
+
// who asked, but cannot earn the `reused` verification — that would let
|
|
121
|
+
// any caller on :3456 verify any trace by naming itself someone else.
|
|
122
|
+
const memory = await store.recall(c.req.param('id'), agent, { identityTrusted: false });
|
|
123
|
+
return c.json({ success: true, memory });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Phase 6.0.1 — trust layer
|
|
130
|
+
//
|
|
131
|
+
// There is deliberately no `POST /memories/:id/verify` route. `human` is the
|
|
132
|
+
// strongest verification reason (+25 trust) and the only one that lets a
|
|
133
|
+
// trace render *bare*, outside the untrusted markers, in the next session's
|
|
134
|
+
// context block. The API has no authentication, so exposing it would let any
|
|
135
|
+
// caller on :3456 grant "a human looked at this" to a trace it just wrote.
|
|
136
|
+
// Human verification requires a human at a terminal: `pnpm cli verify <id>`.
|
|
137
|
+
// Earned verification (reused / grounded / corroborated) is set by the store
|
|
138
|
+
// itself from evidence, never by a request.
|
|
139
|
+
|
|
140
|
+
app.post('/memories/:id/refute', async (c) => {
|
|
141
|
+
try {
|
|
142
|
+
const body = await c.req.json().catch(() => ({}));
|
|
143
|
+
const memory = await store.refute(c.req.param('id'), body.reason);
|
|
144
|
+
return c.json({ success: true, memory });
|
|
145
|
+
} catch (error) {
|
|
146
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// Phase 6.0.2 — contradiction: this trace wins against `otherId`
|
|
151
|
+
app.post('/memories/:id/contradicts', async (c) => {
|
|
152
|
+
try {
|
|
153
|
+
const body = await c.req.json();
|
|
154
|
+
if (!body.otherId) return c.json({ success: false, error: 'otherId required' }, 400);
|
|
155
|
+
const result = await store.contradict!(c.req.param('id'), body.otherId, {
|
|
156
|
+
reason: body.reason,
|
|
157
|
+
agent: c.req.header('X-Humemory-Agent'),
|
|
158
|
+
});
|
|
159
|
+
return c.json({ success: true, ...result });
|
|
160
|
+
} catch (error) {
|
|
161
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
app.delete('/memories/:id', async (c) => {
|
|
166
|
+
await store.delete(c.req.param('id'));
|
|
167
|
+
return c.json({ success: true });
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// === SEARCH ===
|
|
171
|
+
app.get('/search', async (c) => {
|
|
172
|
+
const query = c.req.query('q');
|
|
173
|
+
|
|
174
|
+
if (!query) {
|
|
175
|
+
return c.json({ success: false, error: 'Missing query parameter "q"' }, 400);
|
|
176
|
+
}
|
|
177
|
+
boundedString(query, MAX_QUERY_LENGTH, 'q');
|
|
178
|
+
|
|
179
|
+
const dateFrom = c.req.query('dateFrom') ? new Date(c.req.query('dateFrom')!) : undefined;
|
|
180
|
+
const dateTo = c.req.query('dateTo') ? new Date(c.req.query('dateTo')!) : undefined;
|
|
181
|
+
const minSaillance = boundedOptionalInt(c.req.query('minSaillance'), {
|
|
182
|
+
min: 0,
|
|
183
|
+
max: 100,
|
|
184
|
+
name: 'minSaillance',
|
|
185
|
+
});
|
|
186
|
+
const minRecalls = boundedOptionalInt(c.req.query('minRecalls'), {
|
|
187
|
+
min: 0,
|
|
188
|
+
max: 1_000_000,
|
|
189
|
+
name: 'minRecalls',
|
|
190
|
+
});
|
|
191
|
+
const memoryType = c.req.query('type') as any;
|
|
192
|
+
|
|
193
|
+
const results = await store.search({
|
|
194
|
+
query,
|
|
195
|
+
directory: boundedOptionalString(c.req.query('directory'), MAX_SHORT_FIELD_LENGTH, 'directory'),
|
|
196
|
+
sessionId: boundedOptionalString(c.req.query('sessionId'), MAX_SHORT_FIELD_LENGTH, 'sessionId'),
|
|
197
|
+
maxLevel: boundedInt(c.req.query('maxLevel'), { fallback: 3, min: 0, max: 4, name: 'maxLevel' }) as any,
|
|
198
|
+
limit: boundedInt(c.req.query('limit'), {
|
|
199
|
+
fallback: 10,
|
|
200
|
+
min: 1,
|
|
201
|
+
max: MAX_RESULT_LIMIT,
|
|
202
|
+
name: 'limit',
|
|
203
|
+
}),
|
|
204
|
+
memoryType,
|
|
205
|
+
dateFrom,
|
|
206
|
+
dateTo,
|
|
207
|
+
minSaillance,
|
|
208
|
+
minRecalls,
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
return c.json({ success: true, results });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// === PHOTOGRAPHIC ===
|
|
215
|
+
app.post('/memories/:id/photo', async (c) => {
|
|
216
|
+
try {
|
|
217
|
+
const body = await c.req.json().catch(() => ({}));
|
|
218
|
+
const enable = body.enable !== false; // default true
|
|
219
|
+
const memory = await store.setPhotographic(c.req.param('id'), enable);
|
|
220
|
+
return c.json({ success: true, memory });
|
|
221
|
+
} catch (error) {
|
|
222
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
// === SIMILAR ===
|
|
227
|
+
app.get('/memories/:id/similar', async (c) => {
|
|
228
|
+
const limit = boundedInt(c.req.query('limit'), {
|
|
229
|
+
fallback: 5,
|
|
230
|
+
min: 1,
|
|
231
|
+
max: MAX_RESULT_LIMIT,
|
|
232
|
+
name: 'limit',
|
|
233
|
+
});
|
|
234
|
+
const threshold = boundedInt(c.req.query('threshold'), {
|
|
235
|
+
fallback: 50,
|
|
236
|
+
min: 0,
|
|
237
|
+
max: 100,
|
|
238
|
+
name: 'threshold',
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
const results = await store.findSimilar(c.req.param('id'), { limit, threshold });
|
|
243
|
+
return c.json({ success: true, results });
|
|
244
|
+
} catch (error) {
|
|
245
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// === MERGE ===
|
|
250
|
+
app.post('/memories/:id/merge', async (c) => {
|
|
251
|
+
try {
|
|
252
|
+
const body = await c.req.json();
|
|
253
|
+
if (!body.targetId) {
|
|
254
|
+
return c.json({ success: false, error: 'Missing targetId' }, 400);
|
|
255
|
+
}
|
|
256
|
+
const result = await store.merge(c.req.param('id'), body.targetId, {
|
|
257
|
+
autoMergeContent: body.autoMergeContent ?? false,
|
|
258
|
+
});
|
|
259
|
+
return c.json({ success: true, result });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
// === DECAY ===
|
|
266
|
+
app.post('/decay', async (c) => {
|
|
267
|
+
await store.updateDecay();
|
|
268
|
+
return c.json({ success: true });
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// === STATUS ===
|
|
272
|
+
app.get('/status', async (c) => {
|
|
273
|
+
const memories = await store.list({ limit: 1000 });
|
|
274
|
+
|
|
275
|
+
const byLevel = [0, 0, 0, 0, 0];
|
|
276
|
+
for (const m of memories) {
|
|
277
|
+
byLevel[m.currentLevel]++;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const avgSaillance = memories.reduce((sum, m) => sum + m.saillance, 0) / (memories.length || 1);
|
|
281
|
+
const avgRecalls = memories.reduce((sum, m) => sum + m.recallCount, 0) / (memories.length || 1);
|
|
282
|
+
|
|
283
|
+
return c.json({
|
|
284
|
+
success: true,
|
|
285
|
+
status: {
|
|
286
|
+
total: memories.length,
|
|
287
|
+
byLevel: {
|
|
288
|
+
level0: byLevel[0],
|
|
289
|
+
level1: byLevel[1],
|
|
290
|
+
level2: byLevel[2],
|
|
291
|
+
level3: byLevel[3],
|
|
292
|
+
level4: byLevel[4],
|
|
293
|
+
},
|
|
294
|
+
averages: {
|
|
295
|
+
saillance: Math.round(avgSaillance),
|
|
296
|
+
recalls: parseFloat(avgRecalls.toFixed(1)),
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// === SESSIONS (for Replay visualization) ===
|
|
303
|
+
app.get('/sessions', async (c) => {
|
|
304
|
+
const memories = await store.list({ limit: 1000 });
|
|
305
|
+
|
|
306
|
+
const sessionMap = new Map<string, { sessionId: string; count: number; firstEvent: Date; lastEvent: Date; directory: string }>();
|
|
307
|
+
|
|
308
|
+
for (const m of memories) {
|
|
309
|
+
const existing = sessionMap.get(m.sessionId);
|
|
310
|
+
if (existing) {
|
|
311
|
+
existing.count++;
|
|
312
|
+
if (new Date(m.createdAt) < existing.firstEvent) existing.firstEvent = new Date(m.createdAt);
|
|
313
|
+
if (new Date(m.createdAt) > existing.lastEvent) existing.lastEvent = new Date(m.createdAt);
|
|
314
|
+
} else {
|
|
315
|
+
sessionMap.set(m.sessionId, {
|
|
316
|
+
sessionId: m.sessionId,
|
|
317
|
+
count: 1,
|
|
318
|
+
firstEvent: new Date(m.createdAt),
|
|
319
|
+
lastEvent: new Date(m.createdAt),
|
|
320
|
+
directory: m.directory,
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const sessions = Array.from(sessionMap.values())
|
|
326
|
+
.sort((a, b) => b.lastEvent.getTime() - a.lastEvent.getTime());
|
|
327
|
+
|
|
328
|
+
return c.json({ success: true, sessions });
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
app.get('/sessions/:id', async (c) => {
|
|
332
|
+
const sessionId = decodeURIComponent(c.req.param('id'));
|
|
333
|
+
const memories = await store.list({ limit: 1000 });
|
|
334
|
+
|
|
335
|
+
const sessionMemories = memories.filter(m => m.sessionId === sessionId);
|
|
336
|
+
|
|
337
|
+
const events: Array<{
|
|
338
|
+
type: 'encoded' | 'decayed' | 'recalled';
|
|
339
|
+
timestamp: Date;
|
|
340
|
+
content: string;
|
|
341
|
+
memoryId: string;
|
|
342
|
+
level?: number;
|
|
343
|
+
saillance?: number;
|
|
344
|
+
}> = [];
|
|
345
|
+
|
|
346
|
+
for (const m of sessionMemories) {
|
|
347
|
+
events.push({
|
|
348
|
+
type: 'encoded',
|
|
349
|
+
timestamp: new Date(m.createdAt),
|
|
350
|
+
content: m.content,
|
|
351
|
+
memoryId: m.id,
|
|
352
|
+
level: m.currentLevel,
|
|
353
|
+
saillance: m.saillance,
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
if (m.lastRecalled) {
|
|
357
|
+
events.push({
|
|
358
|
+
type: 'recalled',
|
|
359
|
+
timestamp: new Date(m.lastRecalled),
|
|
360
|
+
content: m.content,
|
|
361
|
+
memoryId: m.id,
|
|
362
|
+
level: m.currentLevel,
|
|
363
|
+
saillance: m.saillance,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (m.currentLevel > 0) {
|
|
368
|
+
const decayTime = new Date(new Date(m.createdAt).getTime() + 24 * 60 * 60 * 1000);
|
|
369
|
+
events.push({
|
|
370
|
+
type: 'decayed',
|
|
371
|
+
timestamp: decayTime,
|
|
372
|
+
content: m.content,
|
|
373
|
+
memoryId: m.id,
|
|
374
|
+
level: m.currentLevel,
|
|
375
|
+
saillance: m.saillance,
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
events.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
|
381
|
+
|
|
382
|
+
return c.json({
|
|
383
|
+
success: true,
|
|
384
|
+
sessionId,
|
|
385
|
+
events,
|
|
386
|
+
totalMemories: sessionMemories.length,
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
return app;
|
|
391
|
+
}
|