humemory 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AGENTS.md +8 -4
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -0
  9. package/dist/agent/maintenance-queue.js +36 -61
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/server.js +3 -2
  22. package/dist/cli/index.js +96 -4
  23. package/dist/core/cues.d.ts +1 -0
  24. package/dist/core/cues.js +19 -7
  25. package/dist/core/embeddings.d.ts +0 -10
  26. package/dist/core/embeddings.js +2 -1
  27. package/dist/core/llm-generator.d.ts +2 -10
  28. package/dist/core/paths.d.ts +5 -0
  29. package/dist/core/paths.js +27 -0
  30. package/dist/core/project-path.d.ts +3 -0
  31. package/dist/core/project-path.js +14 -0
  32. package/dist/core/search.d.ts +1 -1
  33. package/dist/core/search.js +7 -9
  34. package/dist/core/types.d.ts +13 -1
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +5 -0
  37. package/dist/store/sqlite.d.ts +37 -0
  38. package/dist/store/sqlite.js +94 -42
  39. package/package.json +4 -3
  40. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  41. package/public/app/index.html +1 -1
  42. package/scripts/consolidate.js +4 -4
  43. package/scripts/hook-post-commit.ts +2 -1
  44. package/scripts/hook-session-start.ts +2 -1
  45. package/scripts/hook-session.ts +2 -1
  46. package/src/agent/claude-hook.ts +126 -0
  47. package/src/agent/codex-import.ts +129 -0
  48. package/src/agent/codex-rollout-parser.ts +121 -0
  49. package/src/agent/commit-closer.ts +173 -0
  50. package/src/agent/kimi-import.ts +128 -0
  51. package/src/agent/kimi-session-parser.ts +127 -0
  52. package/src/agent/learning-extractor.ts +128 -0
  53. package/src/agent/maintenance-queue.ts +546 -0
  54. package/src/agent/maintenance-runner.ts +322 -0
  55. package/src/agent/maintenance-state.ts +168 -0
  56. package/src/agent/mcp-client-setup.ts +125 -0
  57. package/src/agent/opencode-import.ts +96 -0
  58. package/src/agent/opencode-session-parser.ts +53 -0
  59. package/src/agent/session-context.ts +302 -0
  60. package/src/agent/session-parser.ts +155 -0
  61. package/src/agent/source-registry.ts +135 -0
  62. package/src/api/cors.ts +42 -0
  63. package/src/api/dream-routes.ts +46 -0
  64. package/src/api/errors.ts +45 -0
  65. package/src/api/intentions-routes.ts +348 -0
  66. package/src/api/limits.ts +90 -0
  67. package/src/api/maintenance-routes.ts +73 -0
  68. package/src/api/memory-routes.ts +391 -0
  69. package/src/api/scripts-routes.ts +176 -0
  70. package/src/api/security-headers.ts +54 -0
  71. package/src/api/server.ts +292 -0
  72. package/src/cli/index.ts +1175 -0
  73. package/src/core/clock.ts +64 -0
  74. package/src/core/cue-arg.ts +79 -0
  75. package/src/core/cues.ts +511 -0
  76. package/src/core/decay.ts +198 -0
  77. package/src/core/dreamer.ts +494 -0
  78. package/src/core/embeddings.ts +157 -0
  79. package/src/core/event-bus.ts +100 -0
  80. package/src/core/hybrid.ts +78 -0
  81. package/src/core/llm-cli-client.ts +118 -0
  82. package/src/core/llm-generator.ts +90 -0
  83. package/src/core/paths.ts +28 -0
  84. package/src/core/project-path.ts +14 -0
  85. package/src/core/sanitize.ts +116 -0
  86. package/src/core/scripts.ts +112 -0
  87. package/src/core/search.ts +189 -0
  88. package/src/core/trust.ts +67 -0
  89. package/src/core/types.ts +393 -0
  90. package/src/core/vector-clusterer.ts +131 -0
  91. package/src/index.ts +40 -0
  92. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  93. package/src/mcp/server.ts +202 -0
  94. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,16 @@
1
+ export type HumemoryMcpClient = 'kimi' | 'opencode';
2
+ export interface McpClientSetupOptions {
3
+ clients: HumemoryMcpClient[];
4
+ projectRoot: string;
5
+ dbPath?: string;
6
+ bunPath?: string;
7
+ kimiHome?: string;
8
+ openCodeConfig?: string;
9
+ dryRun?: boolean;
10
+ }
11
+ export interface McpClientSetupEntry {
12
+ client: HumemoryMcpClient;
13
+ path: string;
14
+ changed: boolean;
15
+ }
16
+ export declare function setupHumemoryMcpClients(options: McpClientSetupOptions): Promise<McpClientSetupEntry[]>;
@@ -0,0 +1,108 @@
1
+ /** Safe, merge-only MCP registration for locally installed agent clients. */
2
+ import { mkdir, readFile, writeFile, rename, rm } from 'fs/promises';
3
+ import { randomUUID } from 'crypto';
4
+ import { dirname, join, resolve } from 'path';
5
+ import { homedir } from 'os';
6
+ import { databasePath } from '../core/paths.js';
7
+ import { AdvisoryLock } from '../store/sqlite.js';
8
+ async function readOptional(path) {
9
+ try {
10
+ return await readFile(path, 'utf8');
11
+ }
12
+ catch (error) {
13
+ if (error?.code === 'ENOENT')
14
+ return null;
15
+ throw error;
16
+ }
17
+ }
18
+ function readJson(raw, path) {
19
+ if (raw === null)
20
+ return {};
21
+ try {
22
+ const parsed = JSON.parse(raw);
23
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
24
+ throw new Error('expected an object');
25
+ for (const key of ['mcp', 'mcpServers']) {
26
+ if (key in parsed && (!parsed[key] || typeof parsed[key] !== 'object' || Array.isArray(parsed[key]))) {
27
+ throw new Error(`${key} must be an object`);
28
+ }
29
+ }
30
+ return parsed;
31
+ }
32
+ catch (error) {
33
+ throw new Error(`Refusing to rewrite invalid or commented JSON: ${path} (${error.message})`);
34
+ }
35
+ }
36
+ async function mergeFile(path, update, dryRun) {
37
+ const apply = async () => {
38
+ const original = await readOptional(path);
39
+ const current = readJson(original, path);
40
+ const before = JSON.stringify(current);
41
+ const next = update(current);
42
+ const changed = before !== JSON.stringify(next);
43
+ if (changed && !dryRun) {
44
+ await mkdir(dirname(path), { recursive: true });
45
+ const temporary = `${path}.${randomUUID()}.tmp`;
46
+ try {
47
+ await writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
48
+ if (original !== null)
49
+ await writeFile(`${path}.${randomUUID()}.bak`, original, { mode: 0o600, flag: 'wx' });
50
+ if (await readOptional(path) !== original)
51
+ throw new Error(`Configuration changed during setup: ${path}`);
52
+ await rename(temporary, path);
53
+ }
54
+ finally {
55
+ await rm(temporary, { force: true });
56
+ }
57
+ }
58
+ return changed;
59
+ };
60
+ if (dryRun)
61
+ return apply();
62
+ await mkdir(dirname(path), { recursive: true });
63
+ return new AdvisoryLock(path + '.setup', 50).withLock(apply);
64
+ }
65
+ export async function setupHumemoryMcpClients(options) {
66
+ const projectRoot = resolve(options.projectRoot);
67
+ const serverPath = join(projectRoot, 'src', 'mcp', 'server.ts');
68
+ const configuredDb = options.dbPath ?? databasePath();
69
+ const dbPath = configuredDb === ':memory:' ? configuredDb : resolve(configuredDb);
70
+ const bunPath = resolve(options.bunPath ?? process.execPath);
71
+ const dryRun = options.dryRun ?? false;
72
+ const entries = [];
73
+ for (const client of [...new Set(options.clients)]) {
74
+ if (client === 'kimi') {
75
+ const path = join(options.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), '.kimi-code'), 'mcp.json');
76
+ const changed = await mergeFile(path, (current) => ({
77
+ ...current,
78
+ mcpServers: {
79
+ ...(current.mcpServers ?? {}),
80
+ humemory: {
81
+ command: bunPath,
82
+ args: ['run', serverPath],
83
+ env: { HUMEMORY_AGENT: 'kimi', HUMEMORY_DB: dbPath },
84
+ },
85
+ },
86
+ }), dryRun);
87
+ entries.push({ client, path, changed });
88
+ continue;
89
+ }
90
+ const path = options.openCodeConfig ?? process.env.OPENCODE_CONFIG ??
91
+ join(homedir(), '.config', 'opencode', 'opencode.json');
92
+ const changed = await mergeFile(path, (current) => ({
93
+ ...current,
94
+ $schema: current.$schema ?? 'https://opencode.ai/config.json',
95
+ mcp: {
96
+ ...(current.mcp ?? {}),
97
+ humemory: {
98
+ type: 'local',
99
+ command: [bunPath, 'run', serverPath],
100
+ enabled: true,
101
+ environment: { HUMEMORY_AGENT: 'opencode', HUMEMORY_DB: dbPath },
102
+ },
103
+ },
104
+ }), dryRun);
105
+ entries.push({ client, path, changed });
106
+ }
107
+ return entries;
108
+ }
@@ -0,0 +1,22 @@
1
+ export declare const OPENCODE_SOURCE = "opencode-session";
2
+ export type OpenCodeCommandRunner = (args: string[]) => Promise<string>;
3
+ export interface OpenCodeImportOptions {
4
+ queueDir: string;
5
+ since?: Date;
6
+ limit?: number;
7
+ includeSubagents?: boolean;
8
+ dryRun?: boolean;
9
+ maxLearnings?: number;
10
+ command?: string;
11
+ run?: OpenCodeCommandRunner;
12
+ }
13
+ export interface OpenCodeImportResult {
14
+ scanned: number;
15
+ queued: number;
16
+ created: number;
17
+ skippedEmpty: number;
18
+ unreadable: number;
19
+ }
20
+ export declare function defaultOpenCodeCommand(): string;
21
+ export declare function createOpenCodeRunner(command?: string): OpenCodeCommandRunner;
22
+ export declare function importOpenCodeSessions(options: OpenCodeImportOptions): Promise<OpenCodeImportResult>;
@@ -0,0 +1,71 @@
1
+ /** Import OpenCode's public session exports into the maintenance queue. */
2
+ import { execFile } from 'child_process';
3
+ import { promisify } from 'util';
4
+ import { enqueueSession } from './maintenance-queue.js';
5
+ import { parseOpenCodeExport } from './opencode-session-parser.js';
6
+ import { serializeAgentSession } from './session-parser.js';
7
+ const execFileAsync = promisify(execFile);
8
+ export const OPENCODE_SOURCE = 'opencode-session';
9
+ export function defaultOpenCodeCommand() {
10
+ return process.env.HUMEMORY_OPENCODE_COMMAND ?? (process.platform === 'win32' ? 'opencode.cmd' : 'opencode');
11
+ }
12
+ export function createOpenCodeRunner(command = defaultOpenCodeCommand()) {
13
+ return async (args) => {
14
+ const { stdout } = await execFileAsync(command, args, {
15
+ encoding: 'utf8',
16
+ maxBuffer: 64 * 1024 * 1024,
17
+ windowsHide: true,
18
+ });
19
+ return stdout;
20
+ };
21
+ }
22
+ export async function importOpenCodeSessions(options) {
23
+ const run = options.run ?? createOpenCodeRunner(options.command);
24
+ const conditions = [];
25
+ if (options.since)
26
+ conditions.push(`time_updated >= ${options.since.getTime()}`);
27
+ if (!options.includeSubagents)
28
+ conditions.push('parent_id IS NULL');
29
+ const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
30
+ const sql = `SELECT id, directory FROM session${where} ORDER BY time_updated ASC`;
31
+ const rows = JSON.parse(await run(['db', sql, '--format', 'json']));
32
+ const result = {
33
+ scanned: rows.length,
34
+ queued: 0,
35
+ created: 0,
36
+ skippedEmpty: 0,
37
+ unreadable: 0,
38
+ };
39
+ for (const row of rows) {
40
+ if (options.limit !== undefined && result.queued >= options.limit)
41
+ break;
42
+ if (!row.id) {
43
+ result.unreadable += 1;
44
+ continue;
45
+ }
46
+ try {
47
+ const parsed = parseOpenCodeExport(await run(['export', row.id]), row.directory ?? process.cwd());
48
+ if (!parsed.messages.some((message) => message.role === 'user') ||
49
+ !parsed.messages.some((message) => message.role === 'assistant')) {
50
+ result.skippedEmpty += 1;
51
+ continue;
52
+ }
53
+ result.queued += 1;
54
+ if (options.dryRun)
55
+ continue;
56
+ const queued = await enqueueSession(serializeAgentSession(parsed), {
57
+ queueDir: options.queueDir,
58
+ directory: parsed.directory,
59
+ source: OPENCODE_SOURCE,
60
+ agent: 'opencode',
61
+ maxLearnings: options.maxLearnings,
62
+ });
63
+ if (queued.created)
64
+ result.created += 1;
65
+ }
66
+ catch {
67
+ result.unreadable += 1;
68
+ }
69
+ }
70
+ return result;
71
+ }
@@ -0,0 +1,3 @@
1
+ import type { ParsedSession } from './session-parser.js';
2
+ /** Parse the public `opencode export` JSON shape, excluding tools and reasoning. */
3
+ export declare function parseOpenCodeExport(raw: string, fallbackDirectory: string): ParsedSession;
@@ -0,0 +1,35 @@
1
+ function timestamp(value) {
2
+ if (value === undefined)
3
+ return undefined;
4
+ const date = typeof value === 'number' ? new Date(value) : new Date(value);
5
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
6
+ }
7
+ /** Parse the public `opencode export` JSON shape, excluding tools and reasoning. */
8
+ export function parseOpenCodeExport(raw, fallbackDirectory) {
9
+ const payload = JSON.parse(raw);
10
+ const messages = [];
11
+ for (const entry of payload.messages ?? []) {
12
+ const role = entry.info?.role;
13
+ if (role !== 'user' && role !== 'assistant')
14
+ continue;
15
+ const content = (entry.parts ?? [])
16
+ .filter((part) => part.type === 'text' && typeof part.text === 'string')
17
+ .map((part) => part.text.trim())
18
+ .filter(Boolean)
19
+ .join('\n');
20
+ if (!content)
21
+ continue;
22
+ messages.push({ role, content, timestamp: timestamp(entry.info?.time?.created) });
23
+ }
24
+ const occurredAt = [...messages]
25
+ .reverse()
26
+ .map((message) => message.timestamp ? new Date(message.timestamp) : undefined)
27
+ .find((date) => date && !Number.isNaN(date.getTime()));
28
+ return {
29
+ sessionId: payload.info?.id ?? 'opencode-unknown-session',
30
+ directory: payload.info?.directory ?? payload.info?.path ?? fallbackDirectory,
31
+ messages,
32
+ rawText: messages.map((message) => `${message.role}: ${message.content}`).join('\n\n'),
33
+ occurredAt,
34
+ };
35
+ }
@@ -16,6 +16,14 @@ export interface ParsedSession {
16
16
  */
17
17
  occurredAt?: Date;
18
18
  }
19
+ /**
20
+ * Canonical acquisition envelope consumed by the maintenance queue.
21
+ *
22
+ * Source-specific importers normalize their private formats once, then reuse
23
+ * the same parser/checkpoint path as the live Claude hook. Keeping the envelope
24
+ * here prevents every importer from inventing a subtly different transcript.
25
+ */
26
+ export declare function serializeAgentSession(session: ParsedSession): string;
19
27
  /** The instant a transcript line carries, when it carries a usable one. */
20
28
  export declare function messageTime(message: SessionMessage | undefined): Date | undefined;
21
29
  /** The last usable instant in a run of messages — the session's own clock. */
@@ -1,4 +1,22 @@
1
1
  import { isCodexRollout, parseCodexRollout } from './codex-rollout-parser.js';
2
+ /**
3
+ * Canonical acquisition envelope consumed by the maintenance queue.
4
+ *
5
+ * Source-specific importers normalize their private formats once, then reuse
6
+ * the same parser/checkpoint path as the live Claude hook. Keeping the envelope
7
+ * here prevents every importer from inventing a subtly different transcript.
8
+ */
9
+ export function serializeAgentSession(session) {
10
+ return JSON.stringify({
11
+ session_id: session.sessionId,
12
+ cwd: session.directory,
13
+ transcript: session.messages.map((message) => ({
14
+ role: message.role,
15
+ content: message.content,
16
+ timestamp: message.timestamp,
17
+ })),
18
+ });
19
+ }
2
20
  /** The instant a transcript line carries, when it carries a usable one. */
3
21
  export function messageTime(message) {
4
22
  if (!message?.timestamp)
@@ -21,7 +21,7 @@ export const KNOWN_AGENT_SOURCES = [
21
21
  },
22
22
  {
23
23
  id: 'opencode', name: 'OpenCode', vendor: 'SST', commands: ['opencode'],
24
- roots: [home('.opencode'), appData('opencode'), localAppData('opencode')],
24
+ roots: [home('.opencode'), home('.local', 'share', 'opencode'), home('.config', 'opencode'), appData('opencode'), localAppData('opencode')],
25
25
  },
26
26
  {
27
27
  id: 'qwen-code', name: 'Qwen Code', vendor: 'Alibaba Cloud', commands: ['qwen'],
@@ -1,3 +1,4 @@
1
+ import { databasePath, queueDirectory } from '../core/paths.js';
1
2
  /**
2
3
  * API HTTP pour humemory
3
4
  *
@@ -64,10 +65,10 @@ function safeJoin(baseDir, ...segments) {
64
65
  }
65
66
  // HUMEMORY_DB: same convention as the CLI and the hooks. Without it, the API
66
67
  // cannot be pointed at a demo database without writing to production.
67
- const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
68
+ const DB_PATH = databasePath();
68
69
  const store = new SQLiteStore(DB_PATH);
69
70
  const PUBLIC_DIR = join(__dirname, '../../public');
70
- const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
71
+ const QUEUE_DIR = queueDirectory();
71
72
  const MAINTENANCE_STATE_PATH = defaultStatePath(QUEUE_DIR);
72
73
  // Assigned only when this process hosts the loop; the routes read it to report
73
74
  // whether maintenance lives here and whether a pass is in flight right now.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
+ import { databasePath, queueDirectory } from '../core/paths.js';
3
4
  import { SQLiteStore } from '../store/sqlite.js';
4
5
  import { SqliteCueResolver, loopId, matchIntentionByShortId } from '../core/cues.js';
5
6
  import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
@@ -11,9 +12,9 @@ const __filename = fileURLToPath(import.meta.url);
11
12
  const __dirname = dirname(__filename);
12
13
  // Shared store. HUMEMORY_DB points at another database — same convention as the
13
14
  // hooks, and required to exercise the CLI without touching production.
14
- const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
15
+ const DB_PATH = databasePath();
15
16
  // Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
16
- const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../../data/maintenance-queue');
17
+ const QUEUE_DIR = queueDirectory();
17
18
  let store;
18
19
  function getStore() {
19
20
  if (!store) {
@@ -836,13 +837,18 @@ maintenance
836
837
  maintenance
837
838
  .command('run')
838
839
  .description('Force one consolidation pass here and now, in this process')
839
- .option('--skip-codex', 'Do not import codex rollouts first')
840
+ .option('--skip-imports', 'Do not import any local agent sessions first')
841
+ .option('--skip-codex', 'Do not import Codex rollouts first')
842
+ .option('--skip-kimi', 'Do not import Kimi Code sessions first')
843
+ .option('--skip-opencode', 'Do not import OpenCode sessions first')
840
844
  .action(async (options) => {
841
845
  const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
842
846
  const client = await resolveMaintenanceClient();
843
847
  const { worker } = await runMaintenancePass({
844
848
  client,
845
- codexSinceDays: options.skipCodex ? false : undefined,
849
+ codexSinceDays: options.skipImports || options.skipCodex ? false : 1,
850
+ kimiSinceDays: options.skipImports || options.skipKimi ? false : 1,
851
+ opencodeSinceDays: options.skipImports || options.skipOpencode ? false : 1,
846
852
  runner: 'cli',
847
853
  });
848
854
  console.log(`✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
@@ -950,6 +956,85 @@ sources
950
956
  console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
951
957
  }
952
958
  });
959
+ sources
960
+ .command('import-kimi')
961
+ .description('Queue Kimi Code sessions for maintenance')
962
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
963
+ .option('--all', 'Every session ever recorded, ignoring --since')
964
+ .option('--limit <n>', 'Stop after N queued sessions')
965
+ .option('--dry-run', 'Report what would be queued, write nothing')
966
+ .option('--kimi-home <dir>', 'Override $KIMI_CODE_HOME')
967
+ .action(async (options) => {
968
+ const { importKimiSessions, defaultKimiHome } = await import('../agent/kimi-import.js');
969
+ const kimiHome = options.kimiHome ? resolve(options.kimiHome) : defaultKimiHome();
970
+ const days = Number(options.since);
971
+ const since = options.all || !Number.isFinite(days)
972
+ ? undefined
973
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
974
+ console.log(`⏳ Scanning ${kimiHome}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
975
+ const result = await importKimiSessions({
976
+ queueDir: QUEUE_DIR,
977
+ kimiHome,
978
+ since,
979
+ limit: options.limit ? parseInt(options.limit) : undefined,
980
+ dryRun: options.dryRun,
981
+ });
982
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
983
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
984
+ ` skipped — ${result.skippedOld} older than the window, ${result.skippedEmpty} without a complete turn, ` +
985
+ `${result.unreadable} unreadable`);
986
+ });
987
+ sources
988
+ .command('import-opencode')
989
+ .description('Queue OpenCode session exports for maintenance')
990
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
991
+ .option('--all', 'Every session ever recorded, ignoring --since')
992
+ .option('--limit <n>', 'Stop after N queued sessions')
993
+ .option('--include-subagents', 'Also import child sessions OpenCode spawned')
994
+ .option('--dry-run', 'Report what would be queued, write nothing')
995
+ .option('--command <path>', 'Override the OpenCode executable')
996
+ .action(async (options) => {
997
+ const { importOpenCodeSessions } = await import('../agent/opencode-import.js');
998
+ const days = Number(options.since);
999
+ const since = options.all || !Number.isFinite(days)
1000
+ ? undefined
1001
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
1002
+ console.log(`⏳ Asking OpenCode for sessions${since ? ` from the last ${days} day(s)` : ' from all time'}...`);
1003
+ const result = await importOpenCodeSessions({
1004
+ queueDir: QUEUE_DIR,
1005
+ since,
1006
+ limit: options.limit ? parseInt(options.limit) : undefined,
1007
+ includeSubagents: options.includeSubagents,
1008
+ dryRun: options.dryRun,
1009
+ command: options.command,
1010
+ });
1011
+ console.log(`\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
1012
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
1013
+ ` skipped — ${result.skippedEmpty} without a complete turn, ${result.unreadable} unreadable`);
1014
+ });
1015
+ sources
1016
+ .command('setup')
1017
+ .description('Register humemory as a local MCP server in Kimi Code and OpenCode')
1018
+ .option('--kimi', 'Configure Kimi Code only')
1019
+ .option('--opencode', 'Configure OpenCode only')
1020
+ .option('--dry-run', 'Show which files would change, write nothing')
1021
+ .action(async (options) => {
1022
+ const { setupHumemoryMcpClients } = await import('../agent/mcp-client-setup.js');
1023
+ const clients = options.kimi || options.opencode
1024
+ ? [...(options.kimi ? ['kimi'] : []), ...(options.opencode ? ['opencode'] : [])]
1025
+ : ['kimi', 'opencode'];
1026
+ const projectRoot = resolve(__dirname, '../..');
1027
+ const result = await setupHumemoryMcpClients({
1028
+ clients: [...clients],
1029
+ projectRoot,
1030
+ dbPath: DB_PATH,
1031
+ dryRun: options.dryRun,
1032
+ });
1033
+ for (const entry of result) {
1034
+ const verb = entry.changed ? (options.dryRun ? 'would update' : 'updated') : 'already configured';
1035
+ console.log(`✓ ${entry.client}: ${verb} ${entry.path}`);
1036
+ }
1037
+ });
953
1038
  sources
954
1039
  .command('discover', { isDefault: true })
955
1040
  .description('Show known runtimes and the local evidence found for each one')
@@ -964,6 +1049,13 @@ sources
964
1049
  console.log(` ${evidence}`);
965
1050
  }
966
1051
  });
1052
+ program.command('remap-project <from> <to>')
1053
+ .description('Preview a project root relocation; --apply requires a coherent SQLite backup')
1054
+ .option('--apply', 'Apply the previewed mapping in a transaction')
1055
+ .option('--backup <path>', 'New SQLite backup destination (required with --apply)')
1056
+ .action(async (from, to, options) => {
1057
+ console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
1058
+ });
967
1059
  // Parse and run
968
1060
  program.parse();
969
1061
  // Cleanup
@@ -118,6 +118,7 @@ export declare class SqliteCueResolver implements CueResolver {
118
118
  private liveTargetDirectoryOf;
119
119
  resolveTimeCues(now?: Date): Promise<Cue[]>;
120
120
  resolveEventCues(event: AppEvent): Promise<Cue[]>;
121
+ private armedCues;
121
122
  /**
122
123
  * Marks cue and intention as fired. A cron cue is re-armed after firing: a
123
124
  * recurrence that does not re-arm is a one-shot in disguise.
package/dist/core/cues.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * The data layer (tables, CRUD) is Phase 5.1, in `src/store/sqlite.ts`; there is
10
10
  * nothing but decisions here. See PHASE5_PLAN.md § 5.2.
11
11
  */
12
+ import { projectPath } from './project-path.js';
12
13
  import { systemClock } from './clock.js';
13
14
  // ─────────────────────────────────────────────────────────────────────────────
14
15
  // Cron — minimal matcher, 5 fields (minute hour day-of-month month day-of-week)
@@ -140,8 +141,8 @@ function normalizePath(p) {
140
141
  function directoryMatches(intentionDir, eventDir) {
141
142
  if (!eventDir)
142
143
  return true; // event without context: no filtering
143
- const a = normalizePath(intentionDir).replace(/\/$/, '');
144
- const b = normalizePath(eventDir).replace(/\/$/, '');
144
+ const a = projectPath(intentionDir);
145
+ const b = projectPath(eventDir);
145
146
  return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
146
147
  }
147
148
  /**
@@ -299,12 +300,13 @@ export class SqliteCueResolver {
299
300
  return script && script.status === 'active' ? script.directory : null;
300
301
  }
301
302
  const intention = await this.store.getIntention(cue.targetId);
302
- return intention && intention.status === 'armed' ? intention.directory : null;
303
+ const recurring = cue.triggerSpec.kind === 'time' && Boolean(cue.triggerSpec.cron);
304
+ return intention && (intention.status === 'armed' || (recurring && intention.status === 'fired'))
305
+ ? intention.directory : null;
303
306
  }
304
307
  async resolveTimeCues(now = this.clock.now()) {
305
- const cues = await this.store.listCues({ status: 'armed', kind: 'time', limit: 500 });
306
308
  const due = [];
307
- for (const cue of cues) {
309
+ for await (const cue of this.armedCues('time')) {
308
310
  const spec = cue.triggerSpec;
309
311
  if (spec.kind !== 'time')
310
312
  continue;
@@ -330,9 +332,8 @@ export class SqliteCueResolver {
330
332
  // post-commit hook's job (S5-03b), not this resolver's.
331
333
  if (event.type === 'commit')
332
334
  return [];
333
- const cues = await this.store.listCues({ status: 'armed', kind: 'event', limit: 500 });
334
335
  const matched = [];
335
- for (const cue of cues) {
336
+ for await (const cue of this.armedCues('event')) {
336
337
  const spec = cue.triggerSpec;
337
338
  if (spec.kind !== 'event')
338
339
  continue;
@@ -347,6 +348,17 @@ export class SqliteCueResolver {
347
348
  }
348
349
  return matched;
349
350
  }
351
+ async *armedCues(kind) {
352
+ let afterId = '';
353
+ while (true) {
354
+ const page = await this.store.listCues({ status: 'armed', kind, limit: 500, afterId });
355
+ for (const cue of page)
356
+ yield cue;
357
+ if (page.length < 500)
358
+ return;
359
+ afterId = page[page.length - 1].id;
360
+ }
361
+ }
350
362
  /**
351
363
  * Marks cue and intention as fired. A cron cue is re-armed after firing: a
352
364
  * recurrence that does not re-arm is a one-shot in disguise.
@@ -1,13 +1,3 @@
1
- /**
2
- * Embedders — Phase 7.1.
3
- *
4
- * The test seam (same pattern as `LLMClient`): tests use the deterministic,
5
- * offline `HashEmbedder`; production uses `OnnxEmbedder` (e5-small, local,
6
- * loaded lazily — absent model ⇒ disabled, never a crash).
7
- *
8
- * e5 models expect `query:`/`passage:` prefixes; the Embedder owns them so
9
- * callers never think about it.
10
- */
11
1
  export interface Embedder {
12
2
  readonly modelId: string;
13
3
  readonly dims: number;
@@ -1,3 +1,4 @@
1
+ import { modelCacheDirectory } from './paths.js';
1
2
  /**
2
3
  * Embedders — Phase 7.1.
3
4
  *
@@ -99,7 +100,7 @@ export class OnnxEmbedder {
99
100
  return this.extractor;
100
101
  this.loading ??= (async () => {
101
102
  const { pipeline, env } = await import('@huggingface/transformers');
102
- env.cacheDir = this.options.cacheDir ?? './data/models';
103
+ env.cacheDir = this.options.cacheDir ?? modelCacheDirectory();
103
104
  env.allowLocalModels = true;
104
105
  const model = this.options.model ?? BGE_M3_MODEL_ID;
105
106
  return pipeline('feature-extraction', model, { dtype: this.options.dtype ?? 'q8' });
@@ -1,19 +1,11 @@
1
1
  import type { MemoryType } from './types.js';
2
+ import type { LLMClient } from './types.js';
3
+ export type { LLMClient } from './types.js';
2
4
  export interface GeneratedLevels {
3
5
  level1Summary: string;
4
6
  level2Essential: string;
5
7
  level3Keywords: string;
6
8
  }
7
- export interface LLMClient {
8
- messages: {
9
- create(params: any): Promise<{
10
- content: Array<{
11
- type: string;
12
- text?: string;
13
- }>;
14
- }>;
15
- };
16
- }
17
9
  export declare function setLLMClient(client: LLMClient | null): void;
18
10
  export declare function generateMemoryLevelsDeterministic(content: string): GeneratedLevels;
19
11
  export declare function generateMemoryLevels(content: string, memoryType?: MemoryType, client?: LLMClient): Promise<GeneratedLevels>;
@@ -0,0 +1,5 @@
1
+ /** Preserve an existing checkout's data; new installs use user-owned storage. */
2
+ export declare function dataDirectory(): string;
3
+ export declare function databasePath(): string;
4
+ export declare function queueDirectory(): string;
5
+ export declare function modelCacheDirectory(): string;
@@ -0,0 +1,27 @@
1
+ import { existsSync } from 'fs';
2
+ import { homedir } from 'os';
3
+ import { dirname, join, resolve } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ const installationRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
6
+ /** Preserve an existing checkout's data; new installs use user-owned storage. */
7
+ export function dataDirectory() {
8
+ if (process.env.HUMEMORY_DATA_DIR)
9
+ return resolve(process.env.HUMEMORY_DATA_DIR);
10
+ const legacy = join(installationRoot, 'data');
11
+ if (existsSync(join(legacy, 'humemory.db')))
12
+ return legacy;
13
+ if (process.platform === 'win32')
14
+ return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'humemory');
15
+ if (process.platform === 'darwin')
16
+ return join(homedir(), 'Library', 'Application Support', 'humemory');
17
+ return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'humemory');
18
+ }
19
+ export function databasePath() {
20
+ return process.env.HUMEMORY_DB ?? join(dataDirectory(), 'humemory.db');
21
+ }
22
+ export function queueDirectory() {
23
+ return process.env.HUMEMORY_QUEUE ?? join(dataDirectory(), 'maintenance-queue');
24
+ }
25
+ export function modelCacheDirectory() {
26
+ return process.env.HUMEMORY_MODEL_CACHE ?? join(dataDirectory(), 'models');
27
+ }
@@ -0,0 +1,3 @@
1
+ /** Browser-safe lexical normalization; POSIX identities remain case sensitive. */
2
+ export declare function projectPath(path: string): string;
3
+ export declare function remapPath(path: string, from: string, to: string): string;
@@ -0,0 +1,14 @@
1
+ /** Browser-safe lexical normalization; POSIX identities remain case sensitive. */
2
+ export function projectPath(path) {
3
+ const windows = /^[a-z]:[\\/]/i.test(path) || path.startsWith('\\\\');
4
+ const normalized = path.replace(/\\/g, '/').replace(/\/$/, '').replace(/^\.\//, '');
5
+ return windows ? normalized.toLowerCase() : normalized;
6
+ }
7
+ export function remapPath(path, from, to) {
8
+ const key = projectPath(path);
9
+ const source = projectPath(from);
10
+ if (key !== source && !key.startsWith(source + '/'))
11
+ return path;
12
+ const suffix = path.replace(/\\/g, '/').replace(/\/$/, '').slice(source.length);
13
+ return to.replace(/\\/g, '/').replace(/\/$/, '') + suffix;
14
+ }