humemory 0.2.9 → 0.2.11

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 CHANGED
@@ -92,6 +92,8 @@ scripts/hook-session.ts # Claude Code Stop hook → queue raw session onl
92
92
  scripts/hook-session-start.ts # Claude Code SessionStart hook → inject context
93
93
  scripts/maintenance-worker.ts # async extraction/storage; deterministic by default
94
94
  scripts/verify-package.ts # packs, installs outside the checkout, drives every entry point
95
+ scripts/measure-recall.ts # cognitive-quality report over tests/fixtures/relevance.corpus.json
96
+ scripts/bench-scale.ts # cost of loadIntoMemory() and the index rebuild vs corpus size
95
97
  tests/ # bun test (hermetic; helpers/ + fixtures/)
96
98
  data/humemory.db # legacy in-checkout DB; new installs use the OS data dir (core/paths.ts)
97
99
  ```
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.11] - 2026-09-08
4
+ **Features:**
5
+ - measure what the index rebuild actually costs
6
+
7
+
8
+
9
+ ## [0.2.10] - 2026-09-08
10
+ **Features:**
11
+ - measure whether the right memory comes back
12
+
13
+ **Bug Fixes:**
14
+ - answer a query whose terms straddle the decay levels
15
+
16
+
17
+
3
18
  ## [0.2.9] - 2026-09-07
4
19
  **Features:**
5
20
  - diagnose an installation, and prove the packaged one
package/README.md CHANGED
@@ -611,6 +611,35 @@ pnpm cli <command>
611
611
  pnpm consolidate
612
612
  ```
613
613
 
614
+ ### Measuring recall quality
615
+
616
+ ```bash
617
+ pnpm measure:recall
618
+ ```
619
+
620
+ Runs a frozen corpus of 26 traces at controlled ages against 14 queries and
621
+ prints, per query, what came back and what was missed — plus which open loops
622
+ come due at a given instant, and what a session actually opens with. The suite
623
+ proves the machinery works; this asks the question the machinery exists for:
624
+ does the *right* memory come back. `tests/relevance.test.ts` turns the same
625
+ measurement into a regression floor.
626
+
627
+ Thresholds there are floors recording current behaviour, not targets. Raising
628
+ one is a result; lowering one needs a reason in the commit that lowers it.
629
+
630
+ ### Measuring cost at scale
631
+
632
+ ```bash
633
+ pnpm bench:scale
634
+ ```
635
+
636
+ `loadIntoMemory()` reads every trace and rebuilds the whole search index. It
637
+ runs in the store's constructor — so every CLI command, every SessionStart hook
638
+ and every post-commit hook pays it — and again inside `search()` whenever
639
+ another process has committed since the last load. This measures what that
640
+ costs as the corpus grows. `--sizes=250,1000,5000` to choose the points,
641
+ `--json` for the raw rows.
642
+
614
643
  ### Verifying the published package
615
644
 
616
645
  ```bash
@@ -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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
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",
@@ -97,6 +97,8 @@
97
97
  "dev:web": "bun build web/index.html --outdir public/app --splitting --watch",
98
98
  "typecheck:web": "tsc -p web/tsconfig.json",
99
99
  "verify:package": "bun run scripts/verify-package.ts",
100
+ "measure:recall": "bun run scripts/measure-recall.ts",
101
+ "bench:scale": "bun run scripts/bench-scale.ts",
100
102
  "clean:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\""
101
103
  }
102
104
  }
@@ -7,6 +7,23 @@ import type { Memory, SearchQuery, SearchResult, DecayLevel } from './types.js';
7
7
  import { systemClock, type Clock } from './clock.js';
8
8
  import { projectPath } from './project-path.js';
9
9
 
10
+ /**
11
+ * Cost of having matched only part of the query. Larger than the widest level
12
+ * bonus (3 * 10) so no partial match can outrank an exact one.
13
+ */
14
+ const PARTIAL_MATCH_PENALTY = 35;
15
+
16
+ /** FlexSearch answers as [{field, result: [ids]}] or, sometimes, bare ids. */
17
+ function flattenIds(matches: any): string[] {
18
+ if (!Array.isArray(matches)) return [];
19
+ const ids: string[] = [];
20
+ for (const match of matches) {
21
+ if (typeof match === 'string') ids.push(match);
22
+ else if (Array.isArray(match?.result)) ids.push(...(match.result as string[]));
23
+ }
24
+ return ids;
25
+ }
26
+
10
27
  /**
11
28
  * Inverse search engine, FlexSearch candidates with heuristic ranking.
12
29
  * Queries the degraded layers first (level 3), then escalates.
@@ -64,10 +81,18 @@ export class InverseSearchEngine {
64
81
  }
65
82
 
66
83
  /**
67
- * Inverse search: starts at level 3 and escalates when needed
84
+ * Inverse search: starts at level 3 and escalates when needed.
85
+ *
86
+ * Two passes. The first is strict, and answers almost every query. The second
87
+ * only runs when the first found nothing anywhere, and exists because of
88
+ * audit A13: FlexSearch requires EVERY query term inside a SINGLE field, and
89
+ * the decay levels are indexed as separate fields — so a query whose terms
90
+ * straddle the L3 keyword line and the full content matched neither and
91
+ * returned nothing at all. "sqlite lock" found the trace; "sqlite concurrent
92
+ * write lock" found silence, which is the worst possible answer to a user
93
+ * being more precise.
68
94
  */
69
95
  search(query: SearchQuery): SearchResult[] {
70
- const results: SearchResult[] = [];
71
96
  const { query: searchQuery, maxLevel = 3, limit = 10 } = query;
72
97
 
73
98
  // Level-by-level strategy, from most degraded to most detailed
@@ -77,33 +102,32 @@ export class InverseSearchEngine {
77
102
  { field: 'level1Summary', level: 1 },
78
103
  { field: 'content', level: 0 },
79
104
  ];
105
+ const levels = searchOrder.filter(({ level }) => level <= maxLevel);
80
106
 
81
- const seenIds = new Set<string>();
107
+ const strict = this.collect(query, levels, (field) => this.strictIds(searchQuery, field));
108
+ // Whole-query match found something: it is the better answer by definition,
109
+ // and relaxing further would only add neighbours below it.
110
+ const results = strict.length
111
+ ? strict
112
+ : this.collect(query, levels, (field) => this.nearMissIds(searchQuery, field), true);
82
113
 
83
- for (const { field, level } of searchOrder) {
84
- // Skip once past the caller's maximum level
85
- if (level > maxLevel) continue;
114
+ return results
115
+ .sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id))
116
+ .slice(0, Math.max(0, limit));
117
+ }
86
118
 
87
- // Recherche sur ce niveau
88
- const matches = this.index.search({
89
- query: searchQuery,
90
- field,
91
- limit: Math.max(1, this.memories.size), // rank all candidates after filtering
92
- });
93
-
94
- // FlexSearch retourne [{field, result: [ids]}]
95
- // Collect ids from every matched field
96
- const ids: string[] = [];
97
- for (const match of matches) {
98
- if (match && typeof match === 'object' && 'result' in match) {
99
- ids.push(...(match.result as string[]));
100
- } else if (typeof match === 'string') {
101
- ids.push(match);
102
- }
103
- }
119
+ /** Runs one pass over the levels, filtering and scoring what the ids yield. */
120
+ private collect(
121
+ query: SearchQuery,
122
+ levels: { field: string; level: DecayLevel }[],
123
+ idsFor: (field: string) => string[],
124
+ partial = false
125
+ ): SearchResult[] {
126
+ const results: SearchResult[] = [];
127
+ const seenIds = new Set<string>();
104
128
 
105
- // Process the results
106
- for (const id of ids) {
129
+ for (const { field, level } of levels) {
130
+ for (const id of idsFor(field)) {
107
131
  if (seenIds.has(id)) continue;
108
132
  seenIds.add(id);
109
133
 
@@ -122,25 +146,73 @@ export class InverseSearchEngine {
122
146
  results.push({
123
147
  memory,
124
148
  matchLevel: level,
125
- score: this.calculateScore(memory, searchQuery, level),
149
+ score: this.calculateScore(memory, query.query, level, partial),
126
150
  });
151
+ }
152
+ }
153
+
154
+ return results;
155
+ }
156
+
157
+ /** Ids matching the whole query inside one field — FlexSearch's own AND. */
158
+ private strictIds(searchQuery: string, field: string): string[] {
159
+ return flattenIds(
160
+ this.index.search({
161
+ query: searchQuery,
162
+ field,
163
+ limit: Math.max(1, this.memories.size), // rank all candidates after filtering
164
+ })
165
+ );
166
+ }
127
167
 
168
+ /**
169
+ * Ids matching all but at most one term of the query inside one field.
170
+ *
171
+ * FlexSearch's own `suggest: true` would accept a single term out of five,
172
+ * which turns a missed recall into a confident wrong neighbour — measurably:
173
+ * it put an auth token race at the top of "sqlite concurrent write lock".
174
+ * Counting the terms ourselves keeps the near-misses and drops the strangers.
175
+ */
176
+ private nearMissIds(searchQuery: string, field: string): string[] {
177
+ const terms = searchQuery.split(/\s+/).filter(Boolean);
178
+ if (terms.length < 2) return [];
179
+
180
+ const hits = new Map<string, number>();
181
+ for (const term of terms) {
182
+ for (const id of this.strictIds(term, field)) {
183
+ hits.set(id, (hits.get(id) ?? 0) + 1);
128
184
  }
129
185
  }
130
186
 
131
- return results.sort((a, b) => b.score - a.score || a.memory.id.localeCompare(b.memory.id)).slice(0, Math.max(0, limit));
187
+ const required = terms.length - 1;
188
+ return [...hits.entries()]
189
+ .filter(([, count]) => count >= required)
190
+ // More terms satisfied first: the pass keeps insertion order downstream.
191
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
192
+ .map(([id]) => id);
132
193
  }
133
194
 
134
195
  /**
135
196
  * Calcule un score de pertinence
136
197
  */
137
- private calculateScore(memory: Memory, query: string, matchLevel: DecayLevel): number {
198
+ private calculateScore(
199
+ memory: Memory,
200
+ query: string,
201
+ matchLevel: DecayLevel,
202
+ partial = false
203
+ ): number {
138
204
  let score = 100;
139
205
 
140
206
  // Bonus for matching on a degraded level: cheaper to reach, more useful
141
207
  const levelBonus = matchLevel * 10;
142
208
  score += levelBonus;
143
209
 
210
+ // A partial match satisfied only some of the query terms (A13 fallback).
211
+ // The penalty exceeds the widest level bonus on purpose: an exact match at
212
+ // any level must outrank a partial one at every level, or a loose hit on
213
+ // the keyword line would bury an exact hit in the full content.
214
+ if (partial) score -= PARTIAL_MATCH_PENALTY;
215
+
144
216
  // Recency bonus
145
217
  const daysSinceCreation =
146
218
  (this.clock.now().getTime() - memory.createdAt.getTime()) / (1000 * 60 * 60 * 24);