humemory 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +49 -4
- package/CHANGELOG.md +12 -0
- package/README.md +22 -10
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +89 -0
- package/dist/agent/maintenance-queue.js +245 -87
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +68 -17
- package/dist/agent/maintenance-state.d.ts +4 -0
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +164 -4
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +5 -0
- package/dist/core/paths.js +27 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/package.json +4 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +546 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1175 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +78 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +28 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,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,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
|
+
}
|
package/dist/core/search.d.ts
CHANGED
|
@@ -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,
|
|
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 {
|
package/dist/core/search.js
CHANGED
|
@@ -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,
|
|
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:
|
|
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 =
|
|
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
|
|
148
|
+
return score;
|
|
151
149
|
}
|
|
152
150
|
/**
|
|
153
151
|
* Retourne tous les souvenirs (pour debug/sync)
|
package/dist/core/types.d.ts
CHANGED
|
@@ -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?:
|
|
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';
|
package/dist/store/sqlite.d.ts
CHANGED
|
@@ -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;
|
package/dist/store/sqlite.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
//
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
84
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "humemory",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
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.
|
|
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",
|