humemory 0.2.7 → 0.2.9
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 +14 -7
- package/CHANGELOG.md +23 -0
- package/README.md +66 -12
- 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 +2 -1
- package/dist/agent/maintenance-queue.js +36 -62
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- 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/memory-routes.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +117 -6
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +320 -0
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/hybrid.d.ts +7 -3
- package/dist/core/hybrid.js +7 -3
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +12 -0
- package/dist/core/paths.js +36 -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/docs/PORTABILITY.md +84 -0
- package/package.json +5 -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/scripts/maintenance-worker.ts +7 -2
- 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 +544 -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 +1195 -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/doctor.ts +362 -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 +82 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +38 -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,135 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import { posix, win32 } from 'path';
|
|
3
|
+
|
|
4
|
+
export type AgentSourceId =
|
|
5
|
+
| 'claude-code'
|
|
6
|
+
| 'codex'
|
|
7
|
+
| 'kimi-code'
|
|
8
|
+
| 'kimi-desktop'
|
|
9
|
+
| 'opencode'
|
|
10
|
+
| 'qwen-code'
|
|
11
|
+
| 'mistral-vibe'
|
|
12
|
+
| 'gemini-cli'
|
|
13
|
+
| 'github-copilot-cli'
|
|
14
|
+
| 'aider'
|
|
15
|
+
| 'cursor'
|
|
16
|
+
| 'windsurf';
|
|
17
|
+
|
|
18
|
+
export interface AgentSourceDefinition {
|
|
19
|
+
id: AgentSourceId;
|
|
20
|
+
name: string;
|
|
21
|
+
vendor: string;
|
|
22
|
+
commands: string[];
|
|
23
|
+
/** Known local roots. Discovery only: no file below these roots is read. */
|
|
24
|
+
roots: RootCandidate[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type RootCandidate =
|
|
28
|
+
| { base: 'home' | 'appData' | 'localAppData'; parts: string[] }
|
|
29
|
+
| { base: 'env'; variable: string; parts?: string[] };
|
|
30
|
+
|
|
31
|
+
export interface DiscoveredAgentSource extends AgentSourceDefinition {
|
|
32
|
+
installed: boolean;
|
|
33
|
+
evidence: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface DiscoveryOptions {
|
|
37
|
+
homeDir?: string;
|
|
38
|
+
env?: Record<string, string | undefined>;
|
|
39
|
+
platform?: NodeJS.Platform;
|
|
40
|
+
exists?: (path: string) => boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const home = (...parts: string[]): RootCandidate => ({ base: 'home', parts });
|
|
44
|
+
const appData = (...parts: string[]): RootCandidate => ({ base: 'appData', parts });
|
|
45
|
+
const localAppData = (...parts: string[]): RootCandidate => ({ base: 'localAppData', parts });
|
|
46
|
+
const envRoot = (variable: string, ...parts: string[]): RootCandidate => ({ base: 'env', variable, parts });
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Non-exhaustive catalog of local AI agent runtimes. A catalog entry means
|
|
50
|
+
* "discoverable", not "its private session format is already importable".
|
|
51
|
+
*/
|
|
52
|
+
export const KNOWN_AGENT_SOURCES: readonly AgentSourceDefinition[] = [
|
|
53
|
+
{ id: 'claude-code', name: 'Claude Code', vendor: 'Anthropic', commands: ['claude'], roots: [home('.claude')] },
|
|
54
|
+
{ id: 'codex', name: 'Codex', vendor: 'OpenAI', commands: ['codex'], roots: [home('.codex')] },
|
|
55
|
+
{
|
|
56
|
+
id: 'kimi-code', name: 'Kimi Code', vendor: 'Moonshot AI', commands: ['kimi'],
|
|
57
|
+
roots: [home('.kimi-code'), home('.kimi-work'), localAppData('kimi-code')],
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
id: 'kimi-desktop', name: 'Kimi Desktop', vendor: 'Moonshot AI', commands: [],
|
|
61
|
+
roots: [appData('kimi-desktop'), localAppData('kimi-desktop-updater')],
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
id: 'opencode', name: 'OpenCode', vendor: 'SST', commands: ['opencode'],
|
|
65
|
+
roots: [home('.opencode'), home('.local', 'share', 'opencode'), home('.config', 'opencode'), appData('opencode'), localAppData('opencode')],
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
id: 'qwen-code', name: 'Qwen Code', vendor: 'Alibaba Cloud', commands: ['qwen'],
|
|
69
|
+
roots: [envRoot('QWEN_RUNTIME_DIR'), envRoot('QWEN_HOME'), home('.qwen')],
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
id: 'mistral-vibe', name: 'Mistral Vibe', vendor: 'Mistral AI', commands: ['vibe'],
|
|
73
|
+
roots: [envRoot('VIBE_HOME'), home('.vibe')],
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: 'gemini-cli', name: 'Gemini CLI', vendor: 'Google', commands: ['gemini'],
|
|
77
|
+
roots: [envRoot('GEMINI_CLI_HOME', '.gemini'), home('.gemini')],
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: 'github-copilot-cli', name: 'GitHub Copilot CLI', vendor: 'GitHub', commands: ['copilot'],
|
|
81
|
+
roots: [home('.copilot')],
|
|
82
|
+
},
|
|
83
|
+
{ id: 'aider', name: 'Aider', vendor: 'Aider-AI', commands: ['aider'], roots: [home('.aider.conf.yml')] },
|
|
84
|
+
{ id: 'cursor', name: 'Cursor', vendor: 'Anysphere', commands: ['cursor'], roots: [appData('Cursor')] },
|
|
85
|
+
{ id: 'windsurf', name: 'Windsurf', vendor: 'Cognition', commands: ['windsurf'], roots: [appData('Windsurf')] },
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
function resolveRoot(
|
|
89
|
+
candidate: RootCandidate,
|
|
90
|
+
context: { homeDir: string; env: Record<string, string | undefined>; join: (...parts: string[]) => string },
|
|
91
|
+
): string | null {
|
|
92
|
+
let base: string | undefined;
|
|
93
|
+
if (candidate.base === 'home') base = context.homeDir;
|
|
94
|
+
else if (candidate.base === 'appData') base = context.env.APPDATA;
|
|
95
|
+
else if (candidate.base === 'localAppData') base = context.env.LOCALAPPDATA;
|
|
96
|
+
else if (candidate.base === 'env') base = context.env[candidate.variable];
|
|
97
|
+
if (!base) return null;
|
|
98
|
+
return context.join(base, ...(candidate.parts ?? []));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function executableCandidates(
|
|
102
|
+
command: string,
|
|
103
|
+
env: Record<string, string | undefined>,
|
|
104
|
+
platform: NodeJS.Platform,
|
|
105
|
+
join: (...parts: string[]) => string,
|
|
106
|
+
): string[] {
|
|
107
|
+
const separator = platform === 'win32' ? ';' : ':';
|
|
108
|
+
const pathEntries = (env.PATH ?? env.Path ?? '').split(separator).filter(Boolean);
|
|
109
|
+
const extensions = platform === 'win32'
|
|
110
|
+
? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
|
|
111
|
+
: [''];
|
|
112
|
+
return pathEntries.flatMap((entry) => extensions.map((extension) => join(entry, `${command}${extension.toLowerCase()}`)));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function discoverLocalAgentSources(options: DiscoveryOptions = {}): DiscoveredAgentSource[] {
|
|
116
|
+
const env = options.env ?? process.env;
|
|
117
|
+
const platform = options.platform ?? process.platform;
|
|
118
|
+
const pathApi = platform === 'win32' ? win32 : posix;
|
|
119
|
+
const homeDir = options.homeDir ?? env.USERPROFILE ?? env.HOME ?? '';
|
|
120
|
+
const exists = options.exists ?? existsSync;
|
|
121
|
+
const join = pathApi.join;
|
|
122
|
+
|
|
123
|
+
return KNOWN_AGENT_SOURCES.map((source) => {
|
|
124
|
+
const evidence = new Set<string>();
|
|
125
|
+
for (const root of source.roots) {
|
|
126
|
+
const resolved = resolveRoot(root, { homeDir, env, join });
|
|
127
|
+
if (resolved && exists(resolved)) evidence.add(resolved);
|
|
128
|
+
}
|
|
129
|
+
for (const command of source.commands) {
|
|
130
|
+
const executable = executableCandidates(command, env, platform, join).find(exists);
|
|
131
|
+
if (executable) evidence.add(executable);
|
|
132
|
+
}
|
|
133
|
+
return { ...source, installed: evidence.size > 0, evidence: [...evidence] };
|
|
134
|
+
});
|
|
135
|
+
}
|
package/src/api/cors.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CORS origin allow-list (SECURITY_AUDIT.md M-04).
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `server.ts` for the same reason as the route modules: importing
|
|
5
|
+
* `server.ts` constructs the store and would open the production database, so
|
|
6
|
+
* anything that needs testing lives outside it (BUG-08).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Normalises an origin to its canonical `scheme://host[:port]` form, or null if
|
|
11
|
+
* it is not a parseable absolute URL.
|
|
12
|
+
*/
|
|
13
|
+
export function normalizeOrigin(value: string): string | null {
|
|
14
|
+
try {
|
|
15
|
+
return new URL(value.trim()).origin;
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Builds an exact-match origin checker for hono's `cors({ origin })`.
|
|
23
|
+
*
|
|
24
|
+
* The previous check was `origin.includes(allowed)`, a substring test: with a
|
|
25
|
+
* custom CORS_ORIGINS entry, `http://localhost:3456.evil.example` contains the
|
|
26
|
+
* allowed value and passed. Both sides are now parsed and compared as whole
|
|
27
|
+
* origins, and anything unparseable is refused.
|
|
28
|
+
*/
|
|
29
|
+
export function makeOriginChecker(allowed: string[]): (origin: string) => string | undefined {
|
|
30
|
+
const normalized = new Set(
|
|
31
|
+
allowed.map((a) => normalizeOrigin(a)).filter((a): a is string => a !== null)
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
return (origin: string) => {
|
|
35
|
+
// No Origin header (curl, a native client): CORS does not apply, and
|
|
36
|
+
// answering `*` alongside `credentials: true` is a combination browsers
|
|
37
|
+
// reject anyway. Send no allow-origin at all.
|
|
38
|
+
if (!origin) return undefined;
|
|
39
|
+
const candidate = normalizeOrigin(origin);
|
|
40
|
+
return candidate && normalized.has(candidate) ? candidate : undefined;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP routes for dreaming (Phase 6.1). Same testable-sub-router pattern as
|
|
3
|
+
* memory-routes.ts: the store is a parameter, no production DB in tests.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { Hono } from 'hono';
|
|
7
|
+
import type { SQLiteStore } from '../store/sqlite.js';
|
|
8
|
+
import { runDreamer, applyDreamProposal } from '../core/dreamer.js';
|
|
9
|
+
import { serverErrorBody } from './errors.js';
|
|
10
|
+
|
|
11
|
+
export function createDreamRoutes(store: SQLiteStore) {
|
|
12
|
+
const app = new Hono();
|
|
13
|
+
|
|
14
|
+
app.get('/dreams', async (c) => {
|
|
15
|
+
const status = c.req.query('status') ?? 'pending';
|
|
16
|
+
const proposals = await store.listDreamProposals({ status: status as any });
|
|
17
|
+
return c.json({ success: true, proposals });
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
app.post('/dreams/run', async (c) => {
|
|
21
|
+
const report = await runDreamer({ store });
|
|
22
|
+
return c.json({ success: true, report });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
for (const verb of ['approve', 'reject'] as const) {
|
|
26
|
+
app.post(`/dreams/:id/${verb}`, async (c) => {
|
|
27
|
+
try {
|
|
28
|
+
const id = c.req.param('id');
|
|
29
|
+
if (verb === 'approve') {
|
|
30
|
+
const pending = await store.listDreamProposals({ status: 'pending', includeExpired: true });
|
|
31
|
+
const target = pending.find((p) => p.id === id);
|
|
32
|
+
if (!target) return c.json({ success: false, error: 'Not found or not pending' }, 404);
|
|
33
|
+
const effect = await applyDreamProposal(store, target);
|
|
34
|
+
const proposal = await store.resolveDreamProposal(id, 'approved');
|
|
35
|
+
return c.json({ success: true, proposal, effect });
|
|
36
|
+
}
|
|
37
|
+
const proposal = await store.resolveDreamProposal(id, 'rejected');
|
|
38
|
+
return c.json({ success: true, proposal });
|
|
39
|
+
} catch (error) {
|
|
40
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return app;
|
|
46
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uniform server-error responses (SECURITY_AUDIT.md L-01).
|
|
3
|
+
*
|
|
4
|
+
* Handlers used to return `String(error)` to the caller, so a SQLite message
|
|
5
|
+
* could hand out the schema, a constraint name or an absolute local path — free
|
|
6
|
+
* reconnaissance on an API that is meant to be reachable only from loopback but
|
|
7
|
+
* may be exposed deliberately. The full error is now logged server-side under a
|
|
8
|
+
* correlation id, and the client gets that id and nothing else.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomUUID } from 'crypto';
|
|
12
|
+
|
|
13
|
+
/** Body returned for any unexpected failure. */
|
|
14
|
+
export interface ServerErrorBody {
|
|
15
|
+
success: false;
|
|
16
|
+
error: string;
|
|
17
|
+
errorId: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Set HUMEMORY_VERBOSE_ERRORS=1 to echo the real message back to the caller.
|
|
22
|
+
* Intended for local debugging only — it re-enables exactly the disclosure this
|
|
23
|
+
* module exists to prevent, so it is opt-in and never the default.
|
|
24
|
+
*/
|
|
25
|
+
function verboseErrors(): boolean {
|
|
26
|
+
return process.env.HUMEMORY_VERBOSE_ERRORS === '1';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Logs `error` with a fresh correlation id and builds the client-facing body.
|
|
31
|
+
*
|
|
32
|
+
* `context` should say which operation failed (e.g. `POST /memories`) so the log
|
|
33
|
+
* line is useful without the request body.
|
|
34
|
+
*/
|
|
35
|
+
export function serverErrorBody(context: string, error: unknown): ServerErrorBody {
|
|
36
|
+
const errorId = randomUUID();
|
|
37
|
+
// Full detail stays here, on the server, where it is useful and not exposed.
|
|
38
|
+
console.error(`[${errorId}] ${context}:`, error);
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
success: false,
|
|
42
|
+
error: verboseErrors() && error instanceof Error ? error.message : 'Internal server error',
|
|
43
|
+
errorId,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,348 @@
|
|
|
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
|
+
|
|
9
|
+
import { Hono } from 'hono';
|
|
10
|
+
import type { SQLiteStore } from '../store/sqlite.js';
|
|
11
|
+
import {
|
|
12
|
+
SqliteCueResolver,
|
|
13
|
+
loopId,
|
|
14
|
+
isDangerousPattern,
|
|
15
|
+
MAX_PATTERN_LENGTH,
|
|
16
|
+
MAX_MATCH_TEXT_LENGTH,
|
|
17
|
+
} from '../core/cues.js';
|
|
18
|
+
import {
|
|
19
|
+
LimitExceeded,
|
|
20
|
+
boundedString,
|
|
21
|
+
MAX_CONTENT_LENGTH,
|
|
22
|
+
MAX_SHORT_FIELD_LENGTH,
|
|
23
|
+
MAX_COLLECTION_ITEMS,
|
|
24
|
+
} from './limits.js';
|
|
25
|
+
import type { AppEvent } from '../core/event-bus.js';
|
|
26
|
+
import type {
|
|
27
|
+
Cue,
|
|
28
|
+
Intention,
|
|
29
|
+
IntentionStatus,
|
|
30
|
+
CueStatus,
|
|
31
|
+
CueKind,
|
|
32
|
+
TriggerSpec,
|
|
33
|
+
} from '../core/types.js';
|
|
34
|
+
import type { Clock } from '../core/clock.js';
|
|
35
|
+
import { serverErrorBody } from './errors.js';
|
|
36
|
+
|
|
37
|
+
const INTENTION_STATUSES: IntentionStatus[] = ['armed', 'fired', 'closed', 'expired'];
|
|
38
|
+
const CUE_STATUSES: CueStatus[] = ['armed', 'fired', 'cancelled'];
|
|
39
|
+
const CUE_KINDS: CueKind[] = ['time', 'event'];
|
|
40
|
+
const EVENT_TYPES = ['file_open', 'branch_switch', 'error_pattern', 'commit'] as const;
|
|
41
|
+
|
|
42
|
+
/** Input validation error — surfaced as a 400 rather than a 500. */
|
|
43
|
+
class BadRequest extends Error {
|
|
44
|
+
constructor(message: string) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = 'BadRequest'; // scripts-routes matches on this across module boundaries
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function parseStatuses<T extends string>(raw: string | undefined, allowed: T[]): T[] | undefined {
|
|
51
|
+
if (!raw) return undefined;
|
|
52
|
+
const values = raw.split(',').map((s) => s.trim()).filter(Boolean);
|
|
53
|
+
const invalid = values.filter((v) => !allowed.includes(v as T));
|
|
54
|
+
if (invalid.length) throw new BadRequest(`Unknown status: ${invalid.join(', ')}`);
|
|
55
|
+
return values as T[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function parseLimit(raw: string | undefined, fallback = 50): number {
|
|
59
|
+
if (raw === undefined) return fallback;
|
|
60
|
+
const n = Number(raw);
|
|
61
|
+
if (!Number.isInteger(n) || n < 1 || n > 500) {
|
|
62
|
+
throw new BadRequest('limit must be an integer between 1 and 500');
|
|
63
|
+
}
|
|
64
|
+
return n;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Validates a trigger coming off the network. Incoming JSON is not trusted: a
|
|
69
|
+
* malformed `triggerSpec` would be stored as is and would never wake anything.
|
|
70
|
+
*/
|
|
71
|
+
export function validateTriggerSpec(raw: unknown): TriggerSpec {
|
|
72
|
+
if (!raw || typeof raw !== 'object') throw new BadRequest('triggerSpec is required');
|
|
73
|
+
const spec = raw as Record<string, unknown>;
|
|
74
|
+
|
|
75
|
+
if (spec.kind === 'time') {
|
|
76
|
+
const { at, cron } = spec;
|
|
77
|
+
if (at === undefined && cron === undefined) {
|
|
78
|
+
throw new BadRequest('a time cue requires "at" (ISO) or "cron"');
|
|
79
|
+
}
|
|
80
|
+
if (at !== undefined) {
|
|
81
|
+
if (typeof at !== 'string' || Number.isNaN(new Date(at).getTime())) {
|
|
82
|
+
throw new BadRequest('"at" must be a valid ISO date');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (cron !== undefined && typeof cron !== 'string') {
|
|
86
|
+
throw new BadRequest('"cron" must be a string');
|
|
87
|
+
}
|
|
88
|
+
return { kind: 'time', ...(at ? { at: at as string } : {}), ...(cron ? { cron: cron as string } : {}) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (spec.kind === 'event') {
|
|
92
|
+
switch (spec.type) {
|
|
93
|
+
case 'file_open':
|
|
94
|
+
if (typeof spec.path !== 'string' || !spec.path) throw new BadRequest('"path" is required');
|
|
95
|
+
return { kind: 'event', type: 'file_open', path: spec.path };
|
|
96
|
+
case 'branch_switch':
|
|
97
|
+
if (typeof spec.branch !== 'string' || !spec.branch) throw new BadRequest('"branch" is required');
|
|
98
|
+
return { kind: 'event', type: 'branch_switch', branch: spec.branch };
|
|
99
|
+
case 'error_pattern':
|
|
100
|
+
if (typeof spec.pattern !== 'string' || !spec.pattern) throw new BadRequest('"pattern" is required');
|
|
101
|
+
// SECURITY_AUDIT.md M-01: refuse oversized/backtracking-prone patterns here
|
|
102
|
+
// rather than silently degrading them to a literal search at match time.
|
|
103
|
+
if (spec.pattern.length > MAX_PATTERN_LENGTH) {
|
|
104
|
+
throw new BadRequest(`"pattern" must be at most ${MAX_PATTERN_LENGTH} characters`);
|
|
105
|
+
}
|
|
106
|
+
if (isDangerousPattern(spec.pattern)) {
|
|
107
|
+
throw new BadRequest('"pattern" contains a nested quantifier that risks catastrophic backtracking');
|
|
108
|
+
}
|
|
109
|
+
return { kind: 'event', type: 'error_pattern', pattern: spec.pattern };
|
|
110
|
+
default:
|
|
111
|
+
throw new BadRequest('unknown event type (file_open | branch_switch | error_pattern)');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
throw new BadRequest('kind must be "time" or "event"');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Validates an event pushed to `POST /events`. */
|
|
119
|
+
export function validateAppEvent(raw: unknown): AppEvent {
|
|
120
|
+
if (!raw || typeof raw !== 'object') throw new BadRequest('event is required');
|
|
121
|
+
const e = raw as Record<string, unknown>;
|
|
122
|
+
|
|
123
|
+
if (typeof e.type !== 'string' || !EVENT_TYPES.includes(e.type as any)) {
|
|
124
|
+
throw new BadRequest(`type must be one of: ${EVENT_TYPES.join(', ')}`);
|
|
125
|
+
}
|
|
126
|
+
if (typeof e.directory !== 'string' || !e.directory) throw new BadRequest('"directory" is required');
|
|
127
|
+
|
|
128
|
+
switch (e.type) {
|
|
129
|
+
case 'file_open':
|
|
130
|
+
if (typeof e.path !== 'string' || !e.path) throw new BadRequest('"path" is required');
|
|
131
|
+
return { type: 'file_open', path: e.path, directory: e.directory };
|
|
132
|
+
case 'branch_switch':
|
|
133
|
+
if (typeof e.branch !== 'string' || !e.branch) throw new BadRequest('"branch" is required');
|
|
134
|
+
return { type: 'branch_switch', branch: e.branch, directory: e.directory };
|
|
135
|
+
case 'error_pattern':
|
|
136
|
+
if (typeof e.text !== 'string' || !e.text) throw new BadRequest('"text" is required');
|
|
137
|
+
if (e.text.length > MAX_MATCH_TEXT_LENGTH) {
|
|
138
|
+
throw new BadRequest(`"text" must be at most ${MAX_MATCH_TEXT_LENGTH} characters`);
|
|
139
|
+
}
|
|
140
|
+
return { type: 'error_pattern', text: e.text, directory: e.directory };
|
|
141
|
+
default:
|
|
142
|
+
if (typeof e.sha !== 'string' || !e.sha) throw new BadRequest('"sha" is required');
|
|
143
|
+
return {
|
|
144
|
+
type: 'commit',
|
|
145
|
+
sha: e.sha,
|
|
146
|
+
message: typeof e.message === 'string' ? e.message : '',
|
|
147
|
+
files: Array.isArray(e.files) ? (e.files.filter((f) => typeof f === 'string') as string[]) : [],
|
|
148
|
+
directory: e.directory,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** JSON shape of an intention: the short id is exposed, since that is what humans handle. */
|
|
154
|
+
function serializeIntention(intention: Intention) {
|
|
155
|
+
return { ...intention, loopId: loopId(intention.id) };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function serializeCue(cue: Cue) {
|
|
159
|
+
return cue;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface IntentionRoutesOptions {
|
|
163
|
+
clock?: Clock;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function createIntentionRoutes(store: SQLiteStore, options: IntentionRoutesOptions = {}) {
|
|
167
|
+
const app = new Hono();
|
|
168
|
+
const resolver = new SqliteCueResolver(store, { clock: options.clock });
|
|
169
|
+
|
|
170
|
+
// Invalid input is the client's error, not the server's — including a value
|
|
171
|
+
// that busts a size limit (SECURITY_AUDIT.md M-02).
|
|
172
|
+
const guard = async (c: any, fn: () => Promise<Response>): Promise<Response> => {
|
|
173
|
+
try {
|
|
174
|
+
return await fn();
|
|
175
|
+
} catch (err) {
|
|
176
|
+
if (err instanceof BadRequest || err instanceof LimitExceeded) {
|
|
177
|
+
return c.json({ error: err.message }, 400);
|
|
178
|
+
}
|
|
179
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, err), 500);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
app.post('/intentions', (c) =>
|
|
184
|
+
guard(c, async () => {
|
|
185
|
+
const body = await c.req.json().catch(() => null);
|
|
186
|
+
if (!body || typeof body.content !== 'string' || !body.content.trim()) {
|
|
187
|
+
throw new BadRequest('"content" is required');
|
|
188
|
+
}
|
|
189
|
+
if (typeof body.directory !== 'string' || !body.directory) {
|
|
190
|
+
throw new BadRequest('"directory" is required');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// SECURITY_AUDIT.md M-02: bound the stored fields and the cue collection.
|
|
194
|
+
const content = boundedString(body.content, MAX_CONTENT_LENGTH, 'content');
|
|
195
|
+
const directory = boundedString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
|
|
196
|
+
|
|
197
|
+
let expiresAt: Date | undefined;
|
|
198
|
+
if (body.expiresAt) {
|
|
199
|
+
expiresAt = new Date(body.expiresAt);
|
|
200
|
+
if (Number.isNaN(expiresAt.getTime())) throw new BadRequest('"expiresAt" is invalid');
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (Array.isArray(body.cues) && body.cues.length > MAX_COLLECTION_ITEMS) {
|
|
204
|
+
throw new BadRequest(`"cues" must hold at most ${MAX_COLLECTION_ITEMS} items`);
|
|
205
|
+
}
|
|
206
|
+
const cues: TriggerSpec[] = Array.isArray(body.cues)
|
|
207
|
+
? body.cues.map((spec: unknown) => validateTriggerSpec(spec))
|
|
208
|
+
: [];
|
|
209
|
+
|
|
210
|
+
const intention = await store.addIntention(
|
|
211
|
+
{
|
|
212
|
+
content: content.trim(),
|
|
213
|
+
directory,
|
|
214
|
+
expiresAt,
|
|
215
|
+
relatedMemoryId: typeof body.relatedMemoryId === 'string' ? body.relatedMemoryId : undefined,
|
|
216
|
+
},
|
|
217
|
+
cues
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
return c.json({ intention: serializeIntention(intention) }, 201);
|
|
221
|
+
})
|
|
222
|
+
);
|
|
223
|
+
|
|
224
|
+
app.get('/intentions', (c) =>
|
|
225
|
+
guard(c, async () => {
|
|
226
|
+
const status = parseStatuses(c.req.query('status'), INTENTION_STATUSES);
|
|
227
|
+
const directory = c.req.query('directory');
|
|
228
|
+
const limit = parseLimit(c.req.query('limit'));
|
|
229
|
+
|
|
230
|
+
const intentions = await store.listIntentions({ status, directory, limit });
|
|
231
|
+
return c.json({ intentions: intentions.map(serializeIntention), count: intentions.length });
|
|
232
|
+
})
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
app.get('/intentions/:id', (c) =>
|
|
236
|
+
guard(c, async () => {
|
|
237
|
+
const intention = await store.getIntention(c.req.param('id'));
|
|
238
|
+
if (!intention) return c.json({ error: 'Intention not found' }, 404);
|
|
239
|
+
|
|
240
|
+
const cues = await store.listCues({ intentionId: intention.id });
|
|
241
|
+
return c.json({ intention: serializeIntention(intention), cues: cues.map(serializeCue) });
|
|
242
|
+
})
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
/** Closes a loop. Remaining cues are cancelled — otherwise they would wake a ghost. */
|
|
246
|
+
app.post('/intentions/:id/close', (c) =>
|
|
247
|
+
guard(c, async () => {
|
|
248
|
+
const id = c.req.param('id');
|
|
249
|
+
if (!(await store.getIntention(id))) return c.json({ error: 'Intention not found' }, 404);
|
|
250
|
+
|
|
251
|
+
const body = await c.req.json().catch(() => ({}));
|
|
252
|
+
const intention = await store.updateIntentionStatus(id, 'closed', {
|
|
253
|
+
closedByCommit: typeof body?.commit === 'string' ? body.commit : undefined,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
for (const cue of await store.listCues({ intentionId: id, status: 'armed' })) {
|
|
257
|
+
await store.updateCueStatus(cue.id, 'cancelled');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return c.json({ intention: serializeIntention(intention) });
|
|
261
|
+
})
|
|
262
|
+
);
|
|
263
|
+
|
|
264
|
+
/** Force-fire, useful for debugging and for the dashboard. */
|
|
265
|
+
app.post('/intentions/:id/fire', (c) =>
|
|
266
|
+
guard(c, async () => {
|
|
267
|
+
const id = c.req.param('id');
|
|
268
|
+
if (!(await store.getIntention(id))) return c.json({ error: 'Intention not found' }, 404);
|
|
269
|
+
|
|
270
|
+
const intention = await store.updateIntentionStatus(id, 'fired');
|
|
271
|
+
return c.json({ intention: serializeIntention(intention) });
|
|
272
|
+
})
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
app.delete('/intentions/:id', (c) =>
|
|
276
|
+
guard(c, async () => {
|
|
277
|
+
const id = c.req.param('id');
|
|
278
|
+
if (!(await store.getIntention(id))) return c.json({ error: 'Intention not found' }, 404);
|
|
279
|
+
|
|
280
|
+
await store.deleteIntention(id); // cues cascade away
|
|
281
|
+
return c.json({ success: true });
|
|
282
|
+
})
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
app.post('/cues', (c) =>
|
|
286
|
+
guard(c, async () => {
|
|
287
|
+
const body = await c.req.json().catch(() => null);
|
|
288
|
+
if (!body || typeof body.intentionId !== 'string') throw new BadRequest('"intentionId" is required');
|
|
289
|
+
if (!(await store.getIntention(body.intentionId))) {
|
|
290
|
+
return c.json({ error: 'Intention not found' }, 404);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const cue = await store.addCue({
|
|
294
|
+
intentionId: body.intentionId,
|
|
295
|
+
triggerSpec: validateTriggerSpec(body.triggerSpec),
|
|
296
|
+
});
|
|
297
|
+
return c.json({ cue: serializeCue(cue) }, 201);
|
|
298
|
+
})
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
app.get('/cues', (c) =>
|
|
302
|
+
guard(c, async () => {
|
|
303
|
+
const status = parseStatuses(c.req.query('status'), CUE_STATUSES);
|
|
304
|
+
const kindRaw = c.req.query('kind');
|
|
305
|
+
if (kindRaw && !CUE_KINDS.includes(kindRaw as CueKind)) {
|
|
306
|
+
throw new BadRequest('kind must be "time" or "event"');
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const cues = await store.listCues({
|
|
310
|
+
intentionId: c.req.query('intentionId'),
|
|
311
|
+
status,
|
|
312
|
+
kind: kindRaw as CueKind | undefined,
|
|
313
|
+
limit: parseLimit(c.req.query('limit')),
|
|
314
|
+
});
|
|
315
|
+
return c.json({ cues: cues.map(serializeCue), count: cues.length });
|
|
316
|
+
})
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
/** Pushes an event: the resolver wakes the loops that match. */
|
|
320
|
+
app.post('/events', (c) =>
|
|
321
|
+
guard(c, async () => {
|
|
322
|
+
const event = validateAppEvent(await c.req.json().catch(() => null));
|
|
323
|
+
|
|
324
|
+
const fired: Intention[] = [];
|
|
325
|
+
for (const cue of await resolver.resolveEventCues(event)) {
|
|
326
|
+
fired.push(await resolver.fire(cue.id));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return c.json({ event, fired: fired.map(serializeIntention), count: fired.length });
|
|
330
|
+
})
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
/** Sweeps: expires overdue loops, fires due time cues. */
|
|
334
|
+
app.post('/cues/resolve', (c) =>
|
|
335
|
+
guard(c, async () => {
|
|
336
|
+
const expired = await resolver.expireStale();
|
|
337
|
+
|
|
338
|
+
const fired: Intention[] = [];
|
|
339
|
+
for (const cue of await resolver.resolveTimeCues()) {
|
|
340
|
+
fired.push(await resolver.fire(cue.id));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return c.json({ expired, fired: fired.map(serializeIntention), count: fired.length });
|
|
344
|
+
})
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
return app;
|
|
348
|
+
}
|