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.
Files changed (102) hide show
  1. package/AGENTS.md +14 -7
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +66 -12
  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 -1
  9. package/dist/agent/maintenance-queue.js +36 -62
  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/memory-routes.js +1 -1
  22. package/dist/api/server.js +3 -2
  23. package/dist/cli/index.js +117 -6
  24. package/dist/core/cues.d.ts +1 -0
  25. package/dist/core/cues.js +19 -7
  26. package/dist/core/doctor.d.ts +28 -0
  27. package/dist/core/doctor.js +320 -0
  28. package/dist/core/embeddings.d.ts +0 -10
  29. package/dist/core/embeddings.js +2 -1
  30. package/dist/core/hybrid.d.ts +7 -3
  31. package/dist/core/hybrid.js +7 -3
  32. package/dist/core/llm-generator.d.ts +2 -10
  33. package/dist/core/paths.d.ts +12 -0
  34. package/dist/core/paths.js +36 -0
  35. package/dist/core/project-path.d.ts +3 -0
  36. package/dist/core/project-path.js +14 -0
  37. package/dist/core/search.d.ts +1 -1
  38. package/dist/core/search.js +7 -9
  39. package/dist/core/types.d.ts +13 -1
  40. package/dist/index.d.ts +5 -0
  41. package/dist/index.js +5 -0
  42. package/dist/store/sqlite.d.ts +37 -0
  43. package/dist/store/sqlite.js +94 -42
  44. package/docs/PORTABILITY.md +84 -0
  45. package/package.json +5 -3
  46. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  47. package/public/app/index.html +1 -1
  48. package/scripts/consolidate.js +4 -4
  49. package/scripts/hook-post-commit.ts +2 -1
  50. package/scripts/hook-session-start.ts +2 -1
  51. package/scripts/hook-session.ts +2 -1
  52. package/scripts/maintenance-worker.ts +7 -2
  53. package/src/agent/claude-hook.ts +126 -0
  54. package/src/agent/codex-import.ts +129 -0
  55. package/src/agent/codex-rollout-parser.ts +121 -0
  56. package/src/agent/commit-closer.ts +173 -0
  57. package/src/agent/kimi-import.ts +128 -0
  58. package/src/agent/kimi-session-parser.ts +127 -0
  59. package/src/agent/learning-extractor.ts +128 -0
  60. package/src/agent/maintenance-queue.ts +544 -0
  61. package/src/agent/maintenance-runner.ts +322 -0
  62. package/src/agent/maintenance-state.ts +168 -0
  63. package/src/agent/mcp-client-setup.ts +125 -0
  64. package/src/agent/opencode-import.ts +96 -0
  65. package/src/agent/opencode-session-parser.ts +53 -0
  66. package/src/agent/session-context.ts +302 -0
  67. package/src/agent/session-parser.ts +155 -0
  68. package/src/agent/source-registry.ts +135 -0
  69. package/src/api/cors.ts +42 -0
  70. package/src/api/dream-routes.ts +46 -0
  71. package/src/api/errors.ts +45 -0
  72. package/src/api/intentions-routes.ts +348 -0
  73. package/src/api/limits.ts +90 -0
  74. package/src/api/maintenance-routes.ts +73 -0
  75. package/src/api/memory-routes.ts +391 -0
  76. package/src/api/scripts-routes.ts +176 -0
  77. package/src/api/security-headers.ts +54 -0
  78. package/src/api/server.ts +292 -0
  79. package/src/cli/index.ts +1195 -0
  80. package/src/core/clock.ts +64 -0
  81. package/src/core/cue-arg.ts +79 -0
  82. package/src/core/cues.ts +511 -0
  83. package/src/core/decay.ts +198 -0
  84. package/src/core/doctor.ts +362 -0
  85. package/src/core/dreamer.ts +494 -0
  86. package/src/core/embeddings.ts +157 -0
  87. package/src/core/event-bus.ts +100 -0
  88. package/src/core/hybrid.ts +82 -0
  89. package/src/core/llm-cli-client.ts +118 -0
  90. package/src/core/llm-generator.ts +90 -0
  91. package/src/core/paths.ts +38 -0
  92. package/src/core/project-path.ts +14 -0
  93. package/src/core/sanitize.ts +116 -0
  94. package/src/core/scripts.ts +112 -0
  95. package/src/core/search.ts +189 -0
  96. package/src/core/trust.ts +67 -0
  97. package/src/core/types.ts +393 -0
  98. package/src/core/vector-clusterer.ts +131 -0
  99. package/src/index.ts +40 -0
  100. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  101. package/src/mcp/server.ts +202 -0
  102. package/src/store/sqlite.ts +1958 -0
@@ -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,12 @@
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;
6
+ /**
7
+ * Root of the installed package — the anchor auxiliary entry points (hooks,
8
+ * MCP server, bundled dashboard) are resolved against. `humemory doctor`
9
+ * checks them from here so a package that ships the wrong `files` list fails
10
+ * loudly instead of at the first hook invocation.
11
+ */
12
+ export declare function installationDirectory(): string;
@@ -0,0 +1,36 @@
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
+ }
28
+ /**
29
+ * Root of the installed package — the anchor auxiliary entry points (hooks,
30
+ * MCP server, bundled dashboard) are resolved against. `humemory doctor`
31
+ * checks them from here so a package that ships the wrong `files` list fails
32
+ * loudly instead of at the first hook invocation.
33
+ */
34
+ export function installationDirectory() {
35
+ return installationRoot;
36
+ }
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import type { Memory, SearchQuery, SearchResult } from './types.js';
2
2
  import { type Clock } from './clock.js';
3
3
  /**
4
- * Inverse search engine, BM25-backed.
4
+ * Inverse search engine, FlexSearch candidates with heuristic ranking.
5
5
  * Queries the degraded layers first (level 3), then escalates.
6
6
  */
7
7
  export declare class InverseSearchEngine {
@@ -3,8 +3,9 @@ const require = createRequire(import.meta.url);
3
3
  const flexsearch = require('flexsearch');
4
4
  const { Document } = flexsearch;
5
5
  import { systemClock } from './clock.js';
6
+ import { projectPath } from './project-path.js';
6
7
  /**
7
- * Inverse search engine, BM25-backed.
8
+ * Inverse search engine, FlexSearch candidates with heuristic ranking.
8
9
  * Queries the degraded layers first (level 3), then escalates.
9
10
  */
10
11
  export class InverseSearchEngine {
@@ -75,7 +76,7 @@ export class InverseSearchEngine {
75
76
  const matches = this.index.search({
76
77
  query: searchQuery,
77
78
  field,
78
- limit: limit * 2, // over-fetch, filtering happens below
79
+ limit: Math.max(1, this.memories.size), // rank all candidates after filtering
79
80
  });
80
81
  // FlexSearch retourne [{field, result: [ids]}]
81
82
  // Collect ids from every matched field
@@ -97,7 +98,7 @@ export class InverseSearchEngine {
97
98
  if (!memory)
98
99
  continue;
99
100
  // Filtres optionnels
100
- if (query.directory && memory.directory !== query.directory)
101
+ if (query.directory && projectPath(memory.directory) !== projectPath(query.directory))
101
102
  continue;
102
103
  if (query.sessionId && memory.sessionId !== query.sessionId)
103
104
  continue;
@@ -116,12 +117,9 @@ export class InverseSearchEngine {
116
117
  matchLevel: level,
117
118
  score: this.calculateScore(memory, searchQuery, level),
118
119
  });
119
- if (results.length >= limit) {
120
- return results.sort((a, b) => b.score - a.score);
121
- }
122
120
  }
123
121
  }
124
- return results.sort((a, b) => b.score - a.score);
122
+ return results.sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id)).slice(0, Math.max(0, limit));
125
123
  }
126
124
  /**
127
125
  * Calcule un score de pertinence
@@ -129,7 +127,7 @@ export class InverseSearchEngine {
129
127
  calculateScore(memory, query, matchLevel) {
130
128
  let score = 100;
131
129
  // Bonus for matching on a degraded level: cheaper to reach, more useful
132
- const levelBonus = (4 - matchLevel) * 10;
130
+ const levelBonus = matchLevel * 10;
133
131
  score += levelBonus;
134
132
  // Recency bonus
135
133
  const daysSinceCreation = (this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);
@@ -147,7 +145,7 @@ export class InverseSearchEngine {
147
145
  if (memory.content.length > 1000) {
148
146
  score -= 10;
149
147
  }
150
- return Math.min(100, score);
148
+ return score;
151
149
  }
152
150
  /**
153
151
  * Retourne tous les souvenirs (pour debug/sync)
@@ -7,6 +7,17 @@
7
7
  * 4 = lost / merged
8
8
  */
9
9
  export type DecayLevel = 0 | 1 | 2 | 3 | 4;
10
+ /** Injection contract shared with browser-safe store interfaces. */
11
+ export interface LLMClient {
12
+ messages: {
13
+ create(params: any): Promise<{
14
+ content: Array<{
15
+ type: string;
16
+ text?: string;
17
+ }>;
18
+ }>;
19
+ };
20
+ }
10
21
  /**
11
22
  * Memory types (cognitive neuroscience).
12
23
  * - Episodic: lived events, with their temporal and spatial context
@@ -195,6 +206,7 @@ export interface IntentionStore {
195
206
  addCue(cue: NewCue): Promise<Cue>;
196
207
  getCue(id: string): Promise<Cue | null>;
197
208
  listCues(options?: {
209
+ afterId?: string;
198
210
  intentionId?: string;
199
211
  targetKind?: CueTargetKind;
200
212
  targetId?: string;
@@ -289,7 +301,7 @@ export interface MemoryStore {
289
301
  }): Promise<SearchResult[]>;
290
302
  merge(sourceId: string, targetId: string, options?: {
291
303
  autoMergeContent?: boolean;
292
- client?: import('./llm-generator.js').LLMClient;
304
+ client?: LLMClient;
293
305
  }): Promise<MergeResult>;
294
306
  setPhotographic(id: string, value: boolean): Promise<Memory>;
295
307
  /** Phase 6.0.1 — human override verification; automatic paths set the flag directly. */
package/dist/index.d.ts CHANGED
@@ -15,6 +15,11 @@ export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
15
15
  export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
16
16
  export { processSession } from './agent/claude-hook.js';
17
17
  export { parseClaudeHookPayload } from './agent/session-parser.js';
18
+ export { parseKimiSession } from './agent/kimi-session-parser.js';
19
+ export { importKimiSessions, defaultKimiHome, KIMI_SOURCE } from './agent/kimi-import.js';
20
+ export { parseOpenCodeExport } from './agent/opencode-session-parser.js';
21
+ export { importOpenCodeSessions, defaultOpenCodeCommand, OPENCODE_SOURCE } from './agent/opencode-import.js';
22
+ export { setupHumemoryMcpClients } from './agent/mcp-client-setup.js';
18
23
  export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
19
24
  export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
20
25
  export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
package/dist/index.js CHANGED
@@ -15,6 +15,11 @@ export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
15
15
  export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
16
16
  export { processSession } from './agent/claude-hook.js';
17
17
  export { parseClaudeHookPayload } from './agent/session-parser.js';
18
+ export { parseKimiSession } from './agent/kimi-session-parser.js';
19
+ export { importKimiSessions, defaultKimiHome, KIMI_SOURCE } from './agent/kimi-import.js';
20
+ export { parseOpenCodeExport } from './agent/opencode-session-parser.js';
21
+ export { importOpenCodeSessions, defaultOpenCodeCommand, OPENCODE_SOURCE } from './agent/opencode-import.js';
22
+ export { setupHumemoryMcpClients } from './agent/mcp-client-setup.js';
18
23
  export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
19
24
  export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
20
25
  export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
@@ -22,9 +22,20 @@ export interface RecallOptions {
22
22
  */
23
23
  identityTrusted?: boolean;
24
24
  }
25
+ export declare class AdvisoryLock {
26
+ private lockFile;
27
+ private connection;
28
+ private maxRetries;
29
+ private retryDelay;
30
+ constructor(lockFile: string, maxRetries?: number, retryDelay?: number);
31
+ acquire(): Promise<void>;
32
+ release(): void;
33
+ withLock<T>(fn: () => Promise<T>): Promise<T>;
34
+ }
25
35
  export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptStore {
26
36
  private db;
27
37
  private searchEngine;
38
+ private indexDataVersion;
28
39
  private writeQueue;
29
40
  private advisoryLock;
30
41
  private clock;
@@ -58,6 +69,31 @@ export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptS
58
69
  }): Promise<Memory>;
59
70
  getById(id: string): Promise<Memory | null>;
60
71
  search(query: SearchQuery): Promise<SearchResult[]>;
72
+ /** Explicit project relocation: preview by default, coherent SQLite backup before applying. */
73
+ remapProjectRoot(from: string, to: string, options?: {
74
+ apply?: boolean;
75
+ backupPath?: string;
76
+ }): Promise<{
77
+ applied: boolean;
78
+ changes: {
79
+ table: string;
80
+ id: string;
81
+ before: string;
82
+ after: string;
83
+ column: string;
84
+ }[];
85
+ backupPath?: undefined;
86
+ } | {
87
+ applied: boolean;
88
+ backupPath: string;
89
+ changes: {
90
+ table: string;
91
+ id: string;
92
+ before: string;
93
+ after: string;
94
+ column: string;
95
+ }[];
96
+ }>;
61
97
  recall(id: string, agent?: string, options?: RecallOptions): Promise<Memory>;
62
98
  /**
63
99
  * Phase 6.0.1 — human override verification (`pnpm cli verify <id>`).
@@ -209,6 +245,7 @@ export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptS
209
245
  addCue(cue: NewCue): Promise<Cue>;
210
246
  getCue(id: string): Promise<Cue | null>;
211
247
  listCues(options?: {
248
+ afterId?: string;
212
249
  intentionId?: string;
213
250
  targetKind?: CueTargetKind;
214
251
  targetId?: string;
@@ -2,13 +2,15 @@ import { Database } from 'bun:sqlite';
2
2
  import { join, resolve } from 'path';
3
3
  import { fileURLToPath } from 'url';
4
4
  import { dirname } from 'path';
5
- import { openSync, closeSync, unlinkSync, existsSync } from 'fs';
5
+ import { mkdirSync } from 'fs';
6
6
  import { hostname } from 'os';
7
7
  import { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from '../core/decay.js';
8
8
  import { createHash } from 'crypto';
9
9
  import { InverseSearchEngine } from '../core/search.js';
10
10
  import { generateMemoryLevels } from '../core/llm-generator.js';
11
11
  import { systemClock } from '../core/clock.js';
12
+ import { databasePath, dataDirectory } from '../core/paths.js';
13
+ import { remapPath } from '../core/project-path.js';
12
14
  const __filename = fileURLToPath(import.meta.url);
13
15
  const __dirname = dirname(__filename);
14
16
  const DEFAULT_DB_PATH = join(__dirname, '../../data/humemory.db');
@@ -28,15 +30,15 @@ function assertNotProdDbUnderTest(dbPath) {
28
30
  if (dbPath === ':memory:')
29
31
  return;
30
32
  const resolved = resolve(dbPath);
31
- if (resolved === resolve(DEFAULT_DB_PATH)) {
33
+ if (resolved === resolve(DEFAULT_DB_PATH) || resolved === resolve(join(dataDirectory(), 'humemory.db'))) {
32
34
  throw new Error(`Refusing to open the production database (${resolved}) under NODE_ENV=test. ` +
33
35
  `Use freshStore() / ':memory:' — see docs/TESTING.md.`);
34
36
  }
35
37
  }
36
38
  // Advisory lock for cross-process synchronization
37
- class AdvisoryLock {
39
+ export class AdvisoryLock {
38
40
  lockFile;
39
- lockFd = null;
41
+ connection = null;
40
42
  maxRetries;
41
43
  retryDelay;
42
44
  constructor(lockFile, maxRetries = 10, retryDelay = 100) {
@@ -49,28 +51,24 @@ class AdvisoryLock {
49
51
  let attempts = 0;
50
52
  const tryAcquire = () => {
51
53
  try {
52
- // Use exclusive lock (LOCK_EX) with non-blocking (LOCK_NB)
53
- // On Windows, we'll simulate this with file operations
54
- if (existsSync(this.lockFile)) {
55
- // Lock file exists, wait and retry
56
- attempts++;
57
- if (attempts >= this.maxRetries) {
58
- reject(new Error(`Failed to acquire lock after ${attempts} attempts`));
59
- return;
60
- }
61
- setTimeout(tryAcquire, this.retryDelay);
62
- }
63
- else {
64
- // Create the lock file
65
- this.lockFd = openSync(this.lockFile, 'wx'); // wx = create file exclusively
66
- resolve();
67
- }
54
+ // SQLite's OS lock is released on process death, including SIGKILL.
55
+ // A separate database keeps the lock across asynchronous store work.
56
+ this.connection = new Database(this.lockFile + '.sqlite');
57
+ this.connection.exec('PRAGMA busy_timeout=0; BEGIN IMMEDIATE');
58
+ resolve();
68
59
  }
69
60
  catch (error) {
61
+ this.connection?.close();
62
+ this.connection = null;
63
+ const code = error.code ?? '';
64
+ if (!code.startsWith('SQLITE_BUSY') && !code.startsWith('SQLITE_LOCKED')) {
65
+ reject(error);
66
+ return;
67
+ }
70
68
  attempts++;
71
69
  if (attempts >= this.maxRetries) {
72
70
  const errorMessage = error instanceof Error ? error.message : String(error);
73
- reject(new Error(`Failed to acquire lock: ${errorMessage}`));
71
+ reject(Object.assign(new Error(`Failed to acquire lock: ${errorMessage}`), { code: 'SQLITE_BUSY' }));
74
72
  return;
75
73
  }
76
74
  setTimeout(tryAcquire, this.retryDelay);
@@ -80,16 +78,8 @@ class AdvisoryLock {
80
78
  });
81
79
  }
82
80
  release() {
83
- if (this.lockFd !== null) {
84
- try {
85
- closeSync(this.lockFd);
86
- this.lockFd = null;
87
- unlinkSync(this.lockFile);
88
- }
89
- catch (error) {
90
- console.error('Failed to release lock:', error);
91
- }
92
- }
81
+ this.connection?.close();
82
+ this.connection = null;
93
83
  }
94
84
  async withLock(fn) {
95
85
  await this.acquire();
@@ -115,6 +105,7 @@ class NoopLock {
115
105
  export class SQLiteStore {
116
106
  db;
117
107
  searchEngine;
108
+ indexDataVersion = -1;
118
109
  writeQueue = Promise.resolve();
119
110
  advisoryLock;
120
111
  clock;
@@ -130,10 +121,16 @@ export class SQLiteStore {
130
121
  async enqueueWriteWithLock(fn) {
131
122
  return this.enqueueWrite(() => this.withAdvisoryLock(fn));
132
123
  }
133
- constructor(dbPath = DEFAULT_DB_PATH, options = {}) {
124
+ constructor(dbPath, options = {}) {
125
+ if (dbPath === undefined && process.env.NODE_ENV === 'test') {
126
+ throw new Error('Refusing to open the production database under NODE_ENV=test; pass an explicit temporary database.');
127
+ }
128
+ dbPath ??= databasePath();
134
129
  assertNotProdDbUnderTest(dbPath);
135
130
  this.clock = options.clock ?? systemClock;
136
131
  this.deviceId = resolveDevice(options.device);
132
+ if (dbPath !== ':memory:')
133
+ mkdirSync(dirname(resolve(dbPath)), { recursive: true });
137
134
  this.db = new Database(dbPath);
138
135
  this.db.exec('PRAGMA journal_mode=WAL');
139
136
  this.db.exec('PRAGMA busy_timeout=5000');
@@ -175,14 +172,16 @@ export class SQLiteStore {
175
172
  try {
176
173
  this.db.exec("ALTER TABLE memories ADD COLUMN memory_type TEXT NOT NULL DEFAULT 'semantic'");
177
174
  }
178
- catch {
179
- // column already exists
175
+ catch (error) {
176
+ if (!/duplicate column name/i.test(String(error)))
177
+ throw error;
180
178
  }
181
179
  try {
182
180
  this.db.exec("ALTER TABLE memories ADD COLUMN photographic INTEGER DEFAULT 0");
183
181
  }
184
- catch {
185
- // column already exists
182
+ catch (error) {
183
+ if (!/duplicate column name/i.test(String(error)))
184
+ throw error;
186
185
  }
187
186
  // Phase 6.0.1 — provenance & trust (additive, defaults on every column;
188
187
  // pre-Phase-6 rows keep NULL agent/device — silence is not endorsement).
@@ -198,8 +197,9 @@ export class SQLiteStore {
198
197
  try {
199
198
  this.db.exec(stmt);
200
199
  }
201
- catch {
202
- // column already exists
200
+ catch (error) {
201
+ if (!/duplicate column name/i.test(String(error)))
202
+ throw error;
203
203
  }
204
204
  }
205
205
  this.db.exec(`
@@ -425,13 +425,18 @@ export class SQLiteStore {
425
425
  try {
426
426
  this.db.exec(stmt);
427
427
  }
428
- catch {
429
- // column already exists
428
+ catch (error) {
429
+ if (!/duplicate column name/i.test(String(error)))
430
+ throw error;
430
431
  }
431
432
  }
432
433
  }
433
434
  loadIntoMemory() {
435
+ // Capture before reading: a concurrent commit after this point will force
436
+ // another refresh on the next search, never mark an old snapshot current.
437
+ this.indexDataVersion = this.db.query('PRAGMA data_version').get().data_version;
434
438
  const rows = this.db.query('SELECT * FROM memories').all();
439
+ this.searchEngine.clear();
435
440
  for (const row of rows) {
436
441
  this.searchEngine.add(this.rowToMemory(row));
437
442
  }
@@ -550,8 +555,51 @@ export class SQLiteStore {
550
555
  return this.rowToMemory(row);
551
556
  }
552
557
  async search(query) {
558
+ const version = this.db.query('PRAGMA data_version').get().data_version;
559
+ if (version !== this.indexDataVersion)
560
+ this.loadIntoMemory();
553
561
  return this.searchEngine.search(query);
554
562
  }
563
+ /** Explicit project relocation: preview by default, coherent SQLite backup before applying. */
564
+ async remapProjectRoot(from, to, options = {}) {
565
+ if (!/^(?:[a-z]:[\\/]|\/|\\\\)/i.test(from) || !/^(?:[a-z]:[\\/]|\/|\\\\)/i.test(to)) {
566
+ throw new Error('Project roots must be absolute paths');
567
+ }
568
+ return this.enqueueWriteWithLock(async () => {
569
+ const changes = [];
570
+ for (const table of ['memories', 'intentions', 'scripts']) {
571
+ const rows = this.db.query(`SELECT id, directory FROM ${table}`).all();
572
+ for (const row of rows) {
573
+ const after = remapPath(row.directory, from, to);
574
+ if (after !== row.directory)
575
+ changes.push({ table, id: row.id, before: row.directory, after, column: 'directory' });
576
+ }
577
+ }
578
+ const cues = this.db.query('SELECT id, trigger_spec FROM cues').all();
579
+ for (const cue of cues) {
580
+ const spec = JSON.parse(cue.trigger_spec);
581
+ if (spec.kind !== 'event' || spec.type !== 'file_open')
582
+ continue;
583
+ const path = remapPath(spec.path, from, to);
584
+ if (path !== spec.path)
585
+ changes.push({ table: 'cues', id: cue.id, column: 'trigger_spec', before: cue.trigger_spec, after: JSON.stringify({ ...spec, path }) });
586
+ }
587
+ if (!options.apply || !changes.length)
588
+ return { applied: false, changes };
589
+ if (!options.backupPath)
590
+ throw new Error('Applying a remap requires a new backup path');
591
+ mkdirSync(dirname(resolve(options.backupPath)), { recursive: true });
592
+ // VACUUM INTO includes committed WAL contents and refuses an existing nonempty file.
593
+ this.db.query('VACUUM INTO $path').run({ $path: options.backupPath });
594
+ this.db.transaction(() => {
595
+ for (const change of changes) {
596
+ this.db.query(`UPDATE ${change.table} SET ${change.column} = $after WHERE id = $id`).run({ $after: change.after, $id: change.id });
597
+ }
598
+ })();
599
+ this.loadIntoMemory();
600
+ return { applied: true, backupPath: options.backupPath, changes };
601
+ });
602
+ }
555
603
  async recall(id, agent, options = {}) {
556
604
  const now = this.clock.now();
557
605
  const before = await this.getById(id);
@@ -1415,7 +1463,7 @@ export class SQLiteStore {
1415
1463
  return row ? this.rowToCue(row) : null;
1416
1464
  }
1417
1465
  async listCues(options = {}) {
1418
- const { intentionId, targetKind, targetId, status, kind, limit = 50 } = options;
1466
+ const { intentionId, targetKind, targetId, status, kind, limit = 50, afterId } = options;
1419
1467
  const conditions = [];
1420
1468
  const params = {};
1421
1469
  if (intentionId !== undefined) {
@@ -1442,10 +1490,14 @@ export class SQLiteStore {
1442
1490
  conditions.push('kind = $kind');
1443
1491
  params.$kind = kind;
1444
1492
  }
1493
+ if (afterId !== undefined) {
1494
+ conditions.push('id > $after_id');
1495
+ params.$after_id = afterId;
1496
+ }
1445
1497
  let sql = 'SELECT * FROM cues';
1446
1498
  if (conditions.length)
1447
1499
  sql += ` WHERE ${conditions.join(' AND ')}`;
1448
- sql += ' ORDER BY armed_at ASC LIMIT $limit';
1500
+ sql += afterId === undefined ? ' ORDER BY armed_at ASC, id ASC LIMIT $limit' : ' ORDER BY id ASC LIMIT $limit';
1449
1501
  params.$limit = limit;
1450
1502
  const rows = this.db.query(sql).all(params);
1451
1503
  return rows.map((r) => this.rowToCue(r));
@@ -0,0 +1,84 @@
1
+ # Portability and recovery guarantees
2
+
3
+ ## Installation and data
4
+
5
+ Humemory requires Bun 1.3.14 or newer. The archive deliberately includes `src`
6
+ alongside `dist`: hooks and MCP use those shipped sources, while the executable
7
+ uses the compiled CLI. A checkout is not required at runtime.
8
+
9
+ `HUMEMORY_DATA_DIR` takes precedence over the default data root. Without it, an
10
+ existing installation containing `data/humemory.db` keeps that location. New
11
+ installations use `%LOCALAPPDATA%/humemory` on Windows,
12
+ `~/Library/Application Support/humemory` on macOS, and
13
+ `$XDG_DATA_HOME/humemory` (or `~/.local/share/humemory`) on Linux.
14
+ No existing database is copied, migrated or overwritten implicitly.
15
+
16
+ `HUMEMORY_DB`, `HUMEMORY_QUEUE` and `HUMEMORY_MODEL_CACHE` select individual
17
+ locations. Restart every resident API/MCP/worker process with the same overrides
18
+ when moving shared state. Updating one process does not reconfigure the others.
19
+
20
+ `remap-project <from> <to>` previews directory changes. Applying requires
21
+ `--apply --backup <new-file>` and uses a SQLite snapshot followed by a
22
+ transaction. It covers trace, intention and script directories, plus absolute
23
+ file-open cue paths. It does not rewrite prose, MCP installation paths or queued
24
+ transcripts. Drain or preserve the queue separately before relocating projects.
25
+ The backup contains the database, not model files or pending transcripts.
26
+
27
+ ## Discovery, configuration and encoding
28
+
29
+ Discovery reports local runtime evidence without importing conversations.
30
+ An available import adapter, an installed MCP configuration and a successfully
31
+ encoded trace are distinct states. Use source discovery, configuration reports,
32
+ maintenance status and memory search respectively to check them.
33
+
34
+ To process only already queued transcripts without scanning local agent history:
35
+
36
+ ```bash
37
+ pnpm maintenance --skip-imports
38
+ ```
39
+
40
+ Maintenance uses deterministic extraction by default. Models used by vector
41
+ search require a separate initial download or a populated model cache. An empty
42
+ cache is not proof of an offline-ready vector installation; `humemory doctor`
43
+ reports cache presence, not ONNX execution compatibility.
44
+
45
+ ## Timing, concurrency and recovery
46
+
47
+ Cron expressions are evaluated in UTC. Time cues should use an ISO timestamp
48
+ with an explicit offset. Cron catch-up examines the most recent seven days;
49
+ it does not replay every missed occurrence after a long shutdown. A recurring
50
+ intention remains eligible after firing until it is closed or expires.
51
+
52
+ SQLite advisory locks have no age-based expiry. A live worker retains its lock,
53
+ and the operating system releases it when the process dies. Persistent
54
+ `.sqlite` coordination files are normal and must not be deleted to unlock a
55
+ running process. Stop all old-version workers when upgrading from file locks;
56
+ old and new lock mechanisms do not coordinate with each other.
57
+
58
+ Queue replacements use unique temporary files. If replacement fails, the
59
+ previous destination and the complete temporary remain available for recovery.
60
+ The worker restores abandoned `.processing` files on a later pass. Checkpoints
61
+ avoid ordinary repeated imports, but a crash between memory storage and the
62
+ checkpoint can replay work: this is not a claim of exactly-once encoding.
63
+ Rename-based replacement is not a guarantee against power loss without an
64
+ explicit persistence protocol.
65
+
66
+ MCP setup preserves a backup of the original, checks for changes before the
67
+ rename, and serializes cooperating setup processes. It cannot lock an unrelated
68
+ editor that ignores that protocol; a change in the final check-to-rename window
69
+ remains possible. Keep the `.bak` files until the resulting configuration has
70
+ been checked.
71
+
72
+ ## What the checks establish
73
+
74
+ `pnpm test` is the isolated, deterministic suite with mocked external services.
75
+ `pnpm verify:package` is a separate installation check: dependency installation
76
+ requires network access, while its runtime inputs are synthetic and its HTTP
77
+ requests target the test server on loopback. It verifies the shipped CLI, hooks,
78
+ queue processing, consolidation, MCP and API from a temporary location outside
79
+ the checkout, with spaces and accents in the path and a fresh data profile.
80
+
81
+ The CI defines this sequence for Windows, Linux and macOS. A configured job is
82
+ not evidence that a particular run passed. Real ONNX inference per OS and
83
+ architecture, enforced read-only installation permissions, power-loss recovery,
84
+ and complete database-plus-queue restoration need separate validation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -10,6 +10,7 @@
10
10
  },
11
11
  "files": [
12
12
  "dist",
13
+ "src",
13
14
  "bin",
14
15
  "public",
15
16
  ".githooks",
@@ -48,7 +49,7 @@
48
49
  "url": "https://github.com/medyll/humemory/issues"
49
50
  },
50
51
  "engines": {
51
- "bun": ">=1.0.0"
52
+ "bun": ">=1.3.14"
52
53
  },
53
54
  "dependencies": {
54
55
  "@anthropic-ai/sdk": "^0.92.0",
@@ -81,7 +82,7 @@
81
82
  },
82
83
  "scripts": {
83
84
  "dev": "bun run --watch src/cli/index.ts",
84
- "build": "tsc -p tsconfig.json && bun run build:web",
85
+ "build": "tsc -p tsconfig.json && bun run typecheck:web && bun run build:web",
85
86
  "test": "bun test",
86
87
  "test:watch": "bun test --watch",
87
88
  "start:api": "bun run src/api/server.ts",
@@ -95,6 +96,7 @@
95
96
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
96
97
  "dev:web": "bun build web/index.html --outdir public/app --splitting --watch",
97
98
  "typecheck:web": "tsc -p web/tsconfig.json",
99
+ "verify:package": "bun run scripts/verify-package.ts",
98
100
  "clean:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\""
99
101
  }
100
102
  }