humemory 0.2.8 → 0.2.10

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.
@@ -24,9 +24,31 @@ export declare class InverseSearchEngine {
24
24
  */
25
25
  remove(id: string): void;
26
26
  /**
27
- * Inverse search: starts at level 3 and escalates when needed
27
+ * Inverse search: starts at level 3 and escalates when needed.
28
+ *
29
+ * Two passes. The first is strict, and answers almost every query. The second
30
+ * only runs when the first found nothing anywhere, and exists because of
31
+ * audit A13: FlexSearch requires EVERY query term inside a SINGLE field, and
32
+ * the decay levels are indexed as separate fields — so a query whose terms
33
+ * straddle the L3 keyword line and the full content matched neither and
34
+ * returned nothing at all. "sqlite lock" found the trace; "sqlite concurrent
35
+ * write lock" found silence, which is the worst possible answer to a user
36
+ * being more precise.
28
37
  */
29
38
  search(query: SearchQuery): SearchResult[];
39
+ /** Runs one pass over the levels, filtering and scoring what the ids yield. */
40
+ private collect;
41
+ /** Ids matching the whole query inside one field — FlexSearch's own AND. */
42
+ private strictIds;
43
+ /**
44
+ * Ids matching all but at most one term of the query inside one field.
45
+ *
46
+ * FlexSearch's own `suggest: true` would accept a single term out of five,
47
+ * which turns a missed recall into a confident wrong neighbour — measurably:
48
+ * it put an auth token race at the top of "sqlite concurrent write lock".
49
+ * Counting the terms ourselves keeps the near-misses and drops the strangers.
50
+ */
51
+ private nearMissIds;
30
52
  /**
31
53
  * Calcule un score de pertinence
32
54
  */
@@ -4,6 +4,24 @@ const flexsearch = require('flexsearch');
4
4
  const { Document } = flexsearch;
5
5
  import { systemClock } from './clock.js';
6
6
  import { projectPath } from './project-path.js';
7
+ /**
8
+ * Cost of having matched only part of the query. Larger than the widest level
9
+ * bonus (3 * 10) so no partial match can outrank an exact one.
10
+ */
11
+ const PARTIAL_MATCH_PENALTY = 35;
12
+ /** FlexSearch answers as [{field, result: [ids]}] or, sometimes, bare ids. */
13
+ function flattenIds(matches) {
14
+ if (!Array.isArray(matches))
15
+ return [];
16
+ const ids = [];
17
+ for (const match of matches) {
18
+ if (typeof match === 'string')
19
+ ids.push(match);
20
+ else if (Array.isArray(match?.result))
21
+ ids.push(...match.result);
22
+ }
23
+ return ids;
24
+ }
7
25
  /**
8
26
  * Inverse search engine, FlexSearch candidates with heuristic ranking.
9
27
  * Queries the degraded layers first (level 3), then escalates.
@@ -55,10 +73,18 @@ export class InverseSearchEngine {
55
73
  this.memories.delete(id);
56
74
  }
57
75
  /**
58
- * Inverse search: starts at level 3 and escalates when needed
76
+ * Inverse search: starts at level 3 and escalates when needed.
77
+ *
78
+ * Two passes. The first is strict, and answers almost every query. The second
79
+ * only runs when the first found nothing anywhere, and exists because of
80
+ * audit A13: FlexSearch requires EVERY query term inside a SINGLE field, and
81
+ * the decay levels are indexed as separate fields — so a query whose terms
82
+ * straddle the L3 keyword line and the full content matched neither and
83
+ * returned nothing at all. "sqlite lock" found the trace; "sqlite concurrent
84
+ * write lock" found silence, which is the worst possible answer to a user
85
+ * being more precise.
59
86
  */
60
87
  search(query) {
61
- const results = [];
62
88
  const { query: searchQuery, maxLevel = 3, limit = 10 } = query;
63
89
  // Level-by-level strategy, from most degraded to most detailed
64
90
  const searchOrder = [
@@ -67,30 +93,23 @@ export class InverseSearchEngine {
67
93
  { field: 'level1Summary', level: 1 },
68
94
  { field: 'content', level: 0 },
69
95
  ];
96
+ const levels = searchOrder.filter(({ level }) => level <= maxLevel);
97
+ const strict = this.collect(query, levels, (field) => this.strictIds(searchQuery, field));
98
+ // Whole-query match found something: it is the better answer by definition,
99
+ // and relaxing further would only add neighbours below it.
100
+ const results = strict.length
101
+ ? strict
102
+ : this.collect(query, levels, (field) => this.nearMissIds(searchQuery, field), true);
103
+ return results
104
+ .sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id))
105
+ .slice(0, Math.max(0, limit));
106
+ }
107
+ /** Runs one pass over the levels, filtering and scoring what the ids yield. */
108
+ collect(query, levels, idsFor, partial = false) {
109
+ const results = [];
70
110
  const seenIds = new Set();
71
- for (const { field, level } of searchOrder) {
72
- // Skip once past the caller's maximum level
73
- if (level > maxLevel)
74
- continue;
75
- // Recherche sur ce niveau
76
- const matches = this.index.search({
77
- query: searchQuery,
78
- field,
79
- limit: Math.max(1, this.memories.size), // rank all candidates after filtering
80
- });
81
- // FlexSearch retourne [{field, result: [ids]}]
82
- // Collect ids from every matched field
83
- const ids = [];
84
- for (const match of matches) {
85
- if (match && typeof match === 'object' && 'result' in match) {
86
- ids.push(...match.result);
87
- }
88
- else if (typeof match === 'string') {
89
- ids.push(match);
90
- }
91
- }
92
- // Process the results
93
- for (const id of ids) {
111
+ for (const { field, level } of levels) {
112
+ for (const id of idsFor(field)) {
94
113
  if (seenIds.has(id))
95
114
  continue;
96
115
  seenIds.add(id);
@@ -115,20 +134,59 @@ export class InverseSearchEngine {
115
134
  results.push({
116
135
  memory,
117
136
  matchLevel: level,
118
- score: this.calculateScore(memory, searchQuery, level),
137
+ score: this.calculateScore(memory, query.query, level, partial),
119
138
  });
120
139
  }
121
140
  }
122
- return results.sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id)).slice(0, Math.max(0, limit));
141
+ return results;
142
+ }
143
+ /** Ids matching the whole query inside one field — FlexSearch's own AND. */
144
+ strictIds(searchQuery, field) {
145
+ return flattenIds(this.index.search({
146
+ query: searchQuery,
147
+ field,
148
+ limit: Math.max(1, this.memories.size), // rank all candidates after filtering
149
+ }));
150
+ }
151
+ /**
152
+ * Ids matching all but at most one term of the query inside one field.
153
+ *
154
+ * FlexSearch's own `suggest: true` would accept a single term out of five,
155
+ * which turns a missed recall into a confident wrong neighbour — measurably:
156
+ * it put an auth token race at the top of "sqlite concurrent write lock".
157
+ * Counting the terms ourselves keeps the near-misses and drops the strangers.
158
+ */
159
+ nearMissIds(searchQuery, field) {
160
+ const terms = searchQuery.split(/\s+/).filter(Boolean);
161
+ if (terms.length < 2)
162
+ return [];
163
+ const hits = new Map();
164
+ for (const term of terms) {
165
+ for (const id of this.strictIds(term, field)) {
166
+ hits.set(id, (hits.get(id) ?? 0) + 1);
167
+ }
168
+ }
169
+ const required = terms.length - 1;
170
+ return [...hits.entries()]
171
+ .filter(([, count]) => count >= required)
172
+ // More terms satisfied first: the pass keeps insertion order downstream.
173
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
174
+ .map(([id]) => id);
123
175
  }
124
176
  /**
125
177
  * Calcule un score de pertinence
126
178
  */
127
- calculateScore(memory, query, matchLevel) {
179
+ calculateScore(memory, query, matchLevel, partial = false) {
128
180
  let score = 100;
129
181
  // Bonus for matching on a degraded level: cheaper to reach, more useful
130
182
  const levelBonus = matchLevel * 10;
131
183
  score += levelBonus;
184
+ // A partial match satisfied only some of the query terms (A13 fallback).
185
+ // The penalty exceeds the widest level bonus on purpose: an exact match at
186
+ // any level must outrank a partial one at every level, or a loose hit on
187
+ // the keyword line would bury an exact hit in the full content.
188
+ if (partial)
189
+ score -= PARTIAL_MATCH_PENALTY;
132
190
  // Recency bonus
133
191
  const daysSinceCreation = (this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);
134
192
  if (daysSinceCreation < 7) {
@@ -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.8",
3
+ "version": "0.2.10",
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",
@@ -96,6 +96,8 @@
96
96
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
97
97
  "dev:web": "bun build web/index.html --outdir public/app --splitting --watch",
98
98
  "typecheck:web": "tsc -p web/tsconfig.json",
99
+ "verify:package": "bun run scripts/verify-package.ts",
100
+ "measure:recall": "bun run scripts/measure-recall.ts",
99
101
  "clean:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\""
100
102
  }
101
103
  }
@@ -13,11 +13,16 @@ const llmTimeoutMs = defaultLlmTimeoutMs();
13
13
  const client = await resolveMaintenanceClient(llmTimeoutMs);
14
14
 
15
15
  // --skip-codex for a machine where the rollouts are imported some other way.
16
- const codexSinceDays = process.argv.includes('--skip-codex')
16
+ const skipImports = process.argv.includes('--skip-imports');
17
+ const codexSinceDays = skipImports || process.argv.includes('--skip-codex')
17
18
  ? false as const
18
19
  : Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
19
20
 
20
- const { worker: result } = await runMaintenancePass({ client, llmTimeoutMs, codexSinceDays });
21
+ const { worker: result } = await runMaintenancePass({
22
+ client, llmTimeoutMs, codexSinceDays,
23
+ kimiSinceDays: skipImports ? false : undefined,
24
+ opencodeSinceDays: skipImports ? false : undefined,
25
+ });
21
26
 
22
27
  if (result.busy) {
23
28
  if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');
@@ -45,7 +45,6 @@ export interface WorkerOptions {
45
45
  client?: LLMClient;
46
46
  llmTimeoutMs?: number;
47
47
  maxJobs?: number;
48
- lockStaleMs?: number;
49
48
  maxAttempts?: number;
50
49
  /**
51
50
  * Consecutive job failures that trip the circuit breaker and end the pass.
@@ -70,7 +69,6 @@ export interface WorkerResult {
70
69
  aborted: boolean;
71
70
  }
72
71
 
73
- const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
74
72
  const DEFAULT_MAX_ATTEMPTS = 5;
75
73
  const DEFAULT_FAILURE_THRESHOLD = 3;
76
74
  const DEAD_LETTER_SUFFIX = '.dead.json';
@@ -48,7 +48,7 @@ export function createMemoryRoutes(store: SQLiteStore) {
48
48
  maxItemLength: MAX_KEYWORD_LENGTH,
49
49
  name: 'keywords',
50
50
  });
51
- // level3Keywords is the flat BM25 keyword line, not an array (core/types.ts).
51
+ // level3Keywords is the flat lexical keyword line, not an array (core/types.ts).
52
52
  const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
53
53
  const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
54
54
  const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
package/src/cli/index.ts CHANGED
@@ -10,6 +10,7 @@ import { join, dirname, resolve } from 'path';
10
10
  import { fileURLToPath } from 'url';
11
11
  import { readFileSync } from 'fs';
12
12
  import { discoverLocalAgentSources } from '../agent/source-registry.js';
13
+ import { runDoctor, renderDoctorReport } from '../core/doctor.js';
13
14
 
14
15
  const __filename = fileURLToPath(import.meta.url);
15
16
  const __dirname = dirname(__filename);
@@ -31,9 +32,13 @@ function getStore(): SQLiteStore {
31
32
  const program = new Command();
32
33
 
33
34
  // Version read from the package: hard-coded, it drifted at every release.
34
- const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8')) as {
35
+ const { version, engines } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8')) as {
35
36
  version: string;
37
+ engines?: { bun?: string };
36
38
  };
39
+ // Declared minimum, not a hard-coded one: `humemory doctor` must fail when the
40
+ // runtime is below what the package claims to support, whatever that becomes.
41
+ const minimumBunVersion = engines?.bun;
37
42
 
38
43
  program
39
44
  .name('humemory')
@@ -103,7 +108,7 @@ program
103
108
  .option('--to <date>', 'End date YYYY-MM-DD')
104
109
  .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
105
110
  .option('--min-recalls <n>', 'Minimum recall count')
106
- .option('--semantic', 'Hybrid search: fuse BM25 with vector similarity (Phase 7.4, needs the model)')
111
+ .option('--semantic', 'Hybrid search: fuse the lexical lane with vector similarity (Phase 7.4, needs the model)')
107
112
  .action(async (query, options) => {
108
113
  const s = getStore();
109
114
 
@@ -1166,6 +1171,21 @@ program.command('remap-project <from> <to>')
1166
1171
  console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
1167
1172
  });
1168
1173
 
1174
+ // === DOCTOR ===
1175
+ // Deliberately does not go through getStore(): the point is to diagnose an
1176
+ // installation that may not have a usable store yet.
1177
+ program
1178
+ .command('doctor')
1179
+ .description('Diagnose the installation: runtime, paths, rights, schema, locks, models, entry points')
1180
+ .option('--json', 'Machine-readable report')
1181
+ .action(async (options) => {
1182
+ const report = await runDoctor({ minimumBun: minimumBunVersion });
1183
+ console.log(options.json ? JSON.stringify(report, null, 2) : renderDoctorReport(report));
1184
+ // Non-zero only on a real fault: warnings are states an install can sit in
1185
+ // (no model cached yet, a maintenance worker currently running).
1186
+ if (report.status === 'fail') process.exitCode = 1;
1187
+ });
1188
+
1169
1189
  // Parse and run
1170
1190
  program.parse();
1171
1191