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,157 @@
|
|
|
1
|
+
import { modelCacheDirectory } from './paths.js';
|
|
2
|
+
/**
|
|
3
|
+
* Embedders — Phase 7.1.
|
|
4
|
+
*
|
|
5
|
+
* The test seam (same pattern as `LLMClient`): tests use the deterministic,
|
|
6
|
+
* offline `HashEmbedder`; production uses `OnnxEmbedder` (e5-small, local,
|
|
7
|
+
* loaded lazily — absent model ⇒ disabled, never a crash).
|
|
8
|
+
*
|
|
9
|
+
* e5 models expect `query:`/`passage:` prefixes; the Embedder owns them so
|
|
10
|
+
* callers never think about it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createHash } from 'crypto';
|
|
14
|
+
|
|
15
|
+
export interface Embedder {
|
|
16
|
+
readonly modelId: string;
|
|
17
|
+
readonly dims: number;
|
|
18
|
+
/** L2-normalized embeddings, one per input text. `kind` selects the e5 prefix. */
|
|
19
|
+
embed(texts: string[], kind?: 'query' | 'passage'): Promise<Float32Array[]>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The text actually embedded for a trace (A5: L3 FIRST — e5 truncates at
|
|
23
|
+
* 512 tokens, and the keywords are what keeps a decayed trace findable). */
|
|
24
|
+
export function embeddableText(input: { content: string; level3Keywords?: string; keywords?: string[] }): string {
|
|
25
|
+
const head = input.level3Keywords ?? input.keywords?.join(' ') ?? '';
|
|
26
|
+
return head ? `${head}\n${input.content}` : input.content;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const HASH_DIMS = 384;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Deterministic, offline embedder for tests. Hashes each token into a sparse
|
|
33
|
+
* 384-dim space — semantically meaningless, but reproducible, and texts that
|
|
34
|
+
* share tokens get high cosine, so pipeline behavior (clustering shape,
|
|
35
|
+
* thresholds, storage) is fully testable without a model.
|
|
36
|
+
*/
|
|
37
|
+
export class HashEmbedder implements Embedder {
|
|
38
|
+
readonly modelId = 'hash-v1';
|
|
39
|
+
readonly dims = HASH_DIMS;
|
|
40
|
+
|
|
41
|
+
async embed(texts: string[]): Promise<Float32Array[]> {
|
|
42
|
+
return texts.map((text) => {
|
|
43
|
+
const vec = new Float32Array(this.dims);
|
|
44
|
+
for (const token of text.toLowerCase().split(/[^a-z0-9àâäéèêëîïôöùûüç_-]+/i).filter((t) => t.length > 2)) {
|
|
45
|
+
const h = createHash('sha1').update(token).digest();
|
|
46
|
+
const idx = h.readUInt32LE(0) % this.dims;
|
|
47
|
+
const sign = h[4] % 2 === 0 ? 1 : -1;
|
|
48
|
+
vec[idx] += sign;
|
|
49
|
+
}
|
|
50
|
+
const norm = Math.sqrt(vec.reduce((s, x) => s + x * x, 0));
|
|
51
|
+
if (norm > 0) for (let i = 0; i < this.dims; i++) vec[i] /= norm;
|
|
52
|
+
return vec;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function cosine(a: Float32Array, b: Float32Array): number {
|
|
58
|
+
let dot = 0;
|
|
59
|
+
for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
|
|
60
|
+
return dot; // inputs are L2-normalized
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const E5_MODEL_ID = 'Xenova/multilingual-e5-small';
|
|
64
|
+
export const E5_BASE_MODEL_ID = 'Xenova/multilingual-e5-base';
|
|
65
|
+
export const BGE_M3_MODEL_ID = 'Xenova/bge-m3';
|
|
66
|
+
|
|
67
|
+
/** Known output dims per model — e5-small 384, e5-base 768, bge-m3 1024. */
|
|
68
|
+
export const MODEL_DIMS: Record<string, number> = {
|
|
69
|
+
[E5_MODEL_ID]: 384,
|
|
70
|
+
[E5_BASE_MODEL_ID]: 768,
|
|
71
|
+
[BGE_M3_MODEL_ID]: 1024,
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Calibrated cluster thresholds per model (7.5, 52 labelled pairs incl. hard
|
|
76
|
+
* negatives, scripts/calibrate-embeddings.ts). Thresholds are MODEL-SPECIFIC:
|
|
77
|
+
* bge-m3's cosine space sits lower than e5's. No model reaches a P=1.0
|
|
78
|
+
* corroboration gate — see DREAM_CONFIG.vectorCorroborateThreshold.
|
|
79
|
+
*/
|
|
80
|
+
export const CLUSTER_THRESHOLDS: Record<string, number> = {
|
|
81
|
+
[E5_MODEL_ID]: 0.855, // round 1: F1 0.84 (P 0.76 / R 0.93)
|
|
82
|
+
[E5_BASE_MODEL_ID]: 0.825, // round 3: F1 0.80 (P 0.71 / R 0.92)
|
|
83
|
+
[BGE_M3_MODEL_ID]: 0.74, // round 4: F1 0.89 (P 0.83 / R 0.96) — best
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export interface OnnxEmbedderOptions {
|
|
87
|
+
/** q8 (default) or fp32. fp16 is accepted but BROKEN on win32/onnxruntime-node
|
|
88
|
+
* (graph-fusion error at load, 7.5 calibration) — do not use it there. */
|
|
89
|
+
dtype?: 'q8' | 'fp16' | 'fp32';
|
|
90
|
+
/** Model to load; defaults to bge-m3 (7.5 round-4 calibration: best cluster
|
|
91
|
+
* F1 0.89 vs 0.80 for e5-base; no model reaches a P=1.0 corroborate gate). */
|
|
92
|
+
model?: string;
|
|
93
|
+
cacheDir?: string;
|
|
94
|
+
/** Pre-flight probe: pass false to disable instead of throwing on load failure. */
|
|
95
|
+
onLoadError?: (err: unknown) => void;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Production embedder: Transformers.js + bge-m3 (default; e5-base / e5-small
|
|
100
|
+
* via `model` option), fully local after the one-time download into
|
|
101
|
+
* `data/models/`. Loaded lazily on first use and reused across calls.
|
|
102
|
+
*/
|
|
103
|
+
export class OnnxEmbedder implements Embedder {
|
|
104
|
+
readonly modelId: string;
|
|
105
|
+
readonly dims: number;
|
|
106
|
+
/** Calibrated cluster threshold for this model (see CLUSTER_THRESHOLDS). */
|
|
107
|
+
readonly suggestedClusterThreshold: number;
|
|
108
|
+
private extractor: any = null;
|
|
109
|
+
private loading: Promise<any> | null = null;
|
|
110
|
+
|
|
111
|
+
constructor(private options: OnnxEmbedderOptions = {}) {
|
|
112
|
+
const model = options.model ?? BGE_M3_MODEL_ID;
|
|
113
|
+
this.modelId = `${model}@${options.dtype ?? 'q8'}`;
|
|
114
|
+
const dims = MODEL_DIMS[model];
|
|
115
|
+
if (!dims) throw new Error(`unknown model dims for ${model} — extend MODEL_DIMS`);
|
|
116
|
+
this.dims = dims;
|
|
117
|
+
const threshold = CLUSTER_THRESHOLDS[model];
|
|
118
|
+
if (!threshold) throw new Error(`no calibrated cluster threshold for ${model} — calibrate first`);
|
|
119
|
+
this.suggestedClusterThreshold = threshold;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private async load() {
|
|
123
|
+
if (this.extractor) return this.extractor;
|
|
124
|
+
this.loading ??= (async () => {
|
|
125
|
+
const { pipeline, env } = await import('@huggingface/transformers');
|
|
126
|
+
env.cacheDir = this.options.cacheDir ?? modelCacheDirectory();
|
|
127
|
+
env.allowLocalModels = true;
|
|
128
|
+
const model = this.options.model ?? BGE_M3_MODEL_ID;
|
|
129
|
+
return pipeline('feature-extraction', model, { dtype: this.options.dtype ?? 'q8' });
|
|
130
|
+
})();
|
|
131
|
+
try {
|
|
132
|
+
this.extractor = await this.loading;
|
|
133
|
+
} catch (err) {
|
|
134
|
+
this.loading = null;
|
|
135
|
+
this.options.onLoadError?.(err);
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
return this.extractor;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** `kind` picks the e5 prefix: queries for search, passages for storage. */
|
|
142
|
+
/** e5 models require `query:`/`passage:` prefixes; bge models must NOT get them. */
|
|
143
|
+
private get usesE5Prefix(): boolean {
|
|
144
|
+
return (this.options.model ?? E5_BASE_MODEL_ID).includes('e5');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async embed(texts: string[], kind: 'query' | 'passage' = 'passage'): Promise<Float32Array[]> {
|
|
148
|
+
const extractor = await this.load();
|
|
149
|
+
const prefixed = this.usesE5Prefix ? texts.map((t) => `${kind}: ${t}`) : texts;
|
|
150
|
+
const out = await extractor(prefixed, { pooling: 'mean', normalize: true });
|
|
151
|
+
const dims = this.dims;
|
|
152
|
+
const flat = out.data as Float32Array;
|
|
153
|
+
const rows: Float32Array[] = [];
|
|
154
|
+
for (let i = 0; i < texts.length; i++) rows.push(flat.slice(i * dims, (i + 1) * dims));
|
|
155
|
+
return rows;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Event bus seam — lets tests drive events.
|
|
3
|
+
*
|
|
4
|
+
* Counterpart to the clock seam ([clock.ts](./clock.ts)): prospective memory
|
|
5
|
+
* (Phase 5) is not only time-driven, it is event-driven. A cue can be armed on
|
|
6
|
+
* `file_open`, `branch_switch`, `error_pattern` or `commit`. Without this seam,
|
|
7
|
+
* testing "this cue fires when the branch changes" would mean actually touching
|
|
8
|
+
* the filesystem or git.
|
|
9
|
+
*
|
|
10
|
+
* - `InMemoryEventBus` — tests: `publish()` an event by hand, synchronously.
|
|
11
|
+
* - `FileSystemEventBus` — production: to be wired in Phase 5.2, once there is a
|
|
12
|
+
* resolver to feed (fs.watch / chokidar plus git hooks). Deliberately absent
|
|
13
|
+
* here: nothing to observe while the `intentions`/`cues` tables do not exist.
|
|
14
|
+
*
|
|
15
|
+
* See docs/TESTING.md → pillar 4, and PHASE5_PLAN.md § 5.0.2.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Application events a cue can be armed on (see PHASE5_PLAN.md § 5.2). */
|
|
19
|
+
export type AppEvent =
|
|
20
|
+
| { type: 'file_open'; path: string; directory: string }
|
|
21
|
+
| { type: 'branch_switch'; branch: string; directory: string }
|
|
22
|
+
| { type: 'error_pattern'; text: string; directory: string }
|
|
23
|
+
| { type: 'commit'; sha: string; message: string; files: string[]; directory: string };
|
|
24
|
+
|
|
25
|
+
export type AppEventType = AppEvent['type'];
|
|
26
|
+
|
|
27
|
+
/** Extracts the `AppEvent` variant matching `T`. */
|
|
28
|
+
export type AppEventOf<T extends AppEventType> = Extract<AppEvent, { type: T }>;
|
|
29
|
+
|
|
30
|
+
export type EventHandler<E extends AppEvent = AppEvent> = (event: E) => void | Promise<void>;
|
|
31
|
+
|
|
32
|
+
/** Unsubscribes the registered handler. Idempotent. */
|
|
33
|
+
export type Unsubscribe = () => void;
|
|
34
|
+
|
|
35
|
+
export interface EventBus {
|
|
36
|
+
/** Dispatches an event to subscribers of its type, then to global subscribers. */
|
|
37
|
+
publish(event: AppEvent): Promise<void>;
|
|
38
|
+
/** Subscribes a handler to one event type. */
|
|
39
|
+
subscribe<T extends AppEventType>(type: T, handler: EventHandler<AppEventOf<T>>): Unsubscribe;
|
|
40
|
+
/** Subscribes a handler to *every* event. */
|
|
41
|
+
subscribeAll(handler: EventHandler): Unsubscribe;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* In-memory bus, no I/O. Handlers are awaited in subscription order, so that
|
|
46
|
+
* `await bus.publish(e)` guarantees everything has been handled — a test should
|
|
47
|
+
* never need a `setTimeout` to observe an effect.
|
|
48
|
+
*/
|
|
49
|
+
export class InMemoryEventBus implements EventBus {
|
|
50
|
+
private handlers = new Map<AppEventType, Set<EventHandler<any>>>();
|
|
51
|
+
private globalHandlers = new Set<EventHandler>();
|
|
52
|
+
private log: AppEvent[] = [];
|
|
53
|
+
|
|
54
|
+
async publish(event: AppEvent): Promise<void> {
|
|
55
|
+
this.log.push(event);
|
|
56
|
+
// Snapshot: a handler unsubscribing mid-dispatch must not corrupt the
|
|
57
|
+
// iteration in progress.
|
|
58
|
+
const typed = [...(this.handlers.get(event.type) ?? [])];
|
|
59
|
+
const globals = [...this.globalHandlers];
|
|
60
|
+
for (const handler of [...typed, ...globals]) {
|
|
61
|
+
await handler(event);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
subscribe<T extends AppEventType>(type: T, handler: EventHandler<AppEventOf<T>>): Unsubscribe {
|
|
66
|
+
let set = this.handlers.get(type);
|
|
67
|
+
if (!set) {
|
|
68
|
+
set = new Set();
|
|
69
|
+
this.handlers.set(type, set);
|
|
70
|
+
}
|
|
71
|
+
set.add(handler);
|
|
72
|
+
return () => {
|
|
73
|
+
set!.delete(handler);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
subscribeAll(handler: EventHandler): Unsubscribe {
|
|
78
|
+
this.globalHandlers.add(handler);
|
|
79
|
+
return () => {
|
|
80
|
+
this.globalHandlers.delete(handler);
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Events published since the last `reset()` — for test assertions. */
|
|
85
|
+
published(): readonly AppEvent[] {
|
|
86
|
+
return this.log;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Published events of a given type, typed. */
|
|
90
|
+
publishedOf<T extends AppEventType>(type: T): AppEventOf<T>[] {
|
|
91
|
+
return this.log.filter((e): e is AppEventOf<T> => e.type === type);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Clears the log and every subscription. */
|
|
95
|
+
reset(): void {
|
|
96
|
+
this.handlers.clear();
|
|
97
|
+
this.globalHandlers.clear();
|
|
98
|
+
this.log = [];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hybrid search — Phase 7.4.
|
|
3
|
+
*
|
|
4
|
+
* Reciprocal Rank Fusion of the BM25 lane (exact identifiers: loop-ab12, file
|
|
5
|
+
* paths) and the vector lane (paraphrases). Additive by design: with no
|
|
6
|
+
* embeddings in the store, the vector lane contributes nothing and the result
|
|
7
|
+
* is exactly the BM25 ranking — no regression on bare installs.
|
|
8
|
+
*
|
|
9
|
+
* Exclusion filters are inherited from the lanes themselves: the vector lane
|
|
10
|
+
* reads `memory_embeddings`, whose rows are deleted on merge (A4), so merged
|
|
11
|
+
* traces contribute no vector rank; contradicted losers stay searchable per
|
|
12
|
+
* the 6.0.2 rule ("ghosted, not deleted") in BOTH lanes.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { MemoryStore, SearchResult } from './types.js';
|
|
16
|
+
import { cosine, embeddableText, type Embedder } from './embeddings.js';
|
|
17
|
+
|
|
18
|
+
export const RRF_K = 60;
|
|
19
|
+
|
|
20
|
+
export interface EmbeddingLister {
|
|
21
|
+
listEmbeddings(options?: { modelId?: string }): Promise<{ memoryId: string; embedding: Float32Array }[]>;
|
|
22
|
+
getById(id: string): Promise<SearchResult['memory'] | null>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* RRF fusion: score(d) = Σ 1/(k + rank_lane(d)). The query is embedded with
|
|
27
|
+
* the `query:` prefix (e5 convention, owned by the Embedder).
|
|
28
|
+
*/
|
|
29
|
+
export async function hybridSearch(
|
|
30
|
+
store: MemoryStore & EmbeddingLister,
|
|
31
|
+
embedder: Embedder,
|
|
32
|
+
query: string,
|
|
33
|
+
options: { directory?: string; limit?: number } = {}
|
|
34
|
+
): Promise<SearchResult[]> {
|
|
35
|
+
const limit = options.limit ?? 10;
|
|
36
|
+
|
|
37
|
+
// BM25 lane — the existing inverse search, widened for fusion.
|
|
38
|
+
const bm25 = await store.search({ query, directory: options.directory, limit: limit * 3 });
|
|
39
|
+
|
|
40
|
+
// Vector lane — absent embeddings ⇒ empty lane ⇒ pure BM25 result.
|
|
41
|
+
const stored = await store.listEmbeddings({ modelId: embedder.modelId });
|
|
42
|
+
const byId = new Map<string, number>();
|
|
43
|
+
if (stored.length) {
|
|
44
|
+
const [q] = await embedder.embed([query], 'query');
|
|
45
|
+
const ranked = stored
|
|
46
|
+
.map((row) => ({ memoryId: row.memoryId, cos: cosine(q, row.embedding) }))
|
|
47
|
+
.sort((a, b) => b.cos - a.cos)
|
|
48
|
+
.slice(0, limit * 3);
|
|
49
|
+
ranked.forEach((r, rank) => byId.set(r.memoryId, rank));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const bm25Rank = new Map<string, number>();
|
|
53
|
+
bm25.forEach((r, i) => bm25Rank.set(r.memory.id, i));
|
|
54
|
+
|
|
55
|
+
const candidateIds = new Set([...bm25Rank.keys(), ...byId.keys()]);
|
|
56
|
+
const fused: { id: string; rrf: number }[] = [];
|
|
57
|
+
for (const id of candidateIds) {
|
|
58
|
+
let rrf = 0;
|
|
59
|
+
if (bm25Rank.has(id)) rrf += 1 / (RRF_K + bm25Rank.get(id)!);
|
|
60
|
+
if (byId.has(id)) rrf += 1 / (RRF_K + byId.get(id)!);
|
|
61
|
+
fused.push({ id, rrf });
|
|
62
|
+
}
|
|
63
|
+
fused.sort((a, b) => b.rrf - a.rrf);
|
|
64
|
+
|
|
65
|
+
const results: SearchResult[] = [];
|
|
66
|
+
for (const { id, rrf } of fused.slice(0, limit)) {
|
|
67
|
+
const fromBm25 = bm25.find((r) => r.memory.id === id);
|
|
68
|
+
const memory = fromBm25?.memory ?? (await store.getById(id));
|
|
69
|
+
if (!memory) continue;
|
|
70
|
+
if (options.directory && memory.directory !== options.directory) continue;
|
|
71
|
+
results.push({
|
|
72
|
+
memory,
|
|
73
|
+
matchLevel: fromBm25?.matchLevel ?? memory.currentLevel,
|
|
74
|
+
score: Math.round(rrf * 10_000) / 100, // readable, deterministic
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return results;
|
|
78
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `LLMClient` backed by a local agent CLI instead of a hosted API key.
|
|
3
|
+
*
|
|
4
|
+
* humemory's consolidation path is deterministic and network-free by default;
|
|
5
|
+
* this adapter exists for machines that have no `ANTHROPIC_API_KEY` but do have
|
|
6
|
+
* a logged-in coding agent on the PATH. It is opt-in
|
|
7
|
+
* (`HUMEMORY_MAINTENANCE_LLM=codex`) and every failure falls back to the
|
|
8
|
+
* deterministic extractor upstream, so a missing binary is never fatal.
|
|
9
|
+
*
|
|
10
|
+
* Three flags matter and none of them are cosmetic:
|
|
11
|
+
* --ephemeral no rollout is written under ~/.codex/sessions. Without
|
|
12
|
+
* it, each consolidation leaves a session that humemory
|
|
13
|
+
* would later ingest as a trace — memory eating itself.
|
|
14
|
+
* --ignore-user-config skips the user's skills, plugins and hooks. Cheaper
|
|
15
|
+
* (~2k fewer tokens per call, half the latency) and it
|
|
16
|
+
* stops a humemory Stop hook wired into codex from
|
|
17
|
+
* re-entering humemory while maintenance is running.
|
|
18
|
+
* -s read-only consolidation summarises text; it never needs a write.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { mkdtempSync, readFileSync, rmSync } from 'fs';
|
|
22
|
+
import { tmpdir } from 'os';
|
|
23
|
+
import { join } from 'path';
|
|
24
|
+
import type { LLMClient } from './llm-generator.js';
|
|
25
|
+
|
|
26
|
+
/** Runs one non-interactive agent turn and resolves with its final message. */
|
|
27
|
+
export type CliRunner = (prompt: string, opts: { timeoutMs: number }) => Promise<string>;
|
|
28
|
+
|
|
29
|
+
export interface CodexClientOptions {
|
|
30
|
+
/** Model id. Unset means the CLI's own default — mini models are rejected on ChatGPT accounts. */
|
|
31
|
+
model?: string;
|
|
32
|
+
/** Wall-clock budget for one turn. Agent start-up alone is several seconds. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
/** Injected in tests; the default spawns the real `codex` binary. */
|
|
35
|
+
runner?: CliRunner;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Strips the ```json fences a chat-tuned model wraps around structured output. */
|
|
39
|
+
export function unfence(text: string): string {
|
|
40
|
+
const fenced = text.trim().match(/^```(?:json)?\s*\n([\s\S]*?)\n?```$/);
|
|
41
|
+
return (fenced ? fenced[1] : text).trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Flattens an Anthropic-shaped request into one prompt string for a CLI turn. */
|
|
45
|
+
export function flattenPrompt(params: any): string {
|
|
46
|
+
const blocks: string[] = [];
|
|
47
|
+
const system = params?.system;
|
|
48
|
+
if (typeof system === 'string') blocks.push(system);
|
|
49
|
+
else if (Array.isArray(system)) {
|
|
50
|
+
for (const part of system) if (typeof part?.text === 'string') blocks.push(part.text);
|
|
51
|
+
}
|
|
52
|
+
for (const message of params?.messages ?? []) {
|
|
53
|
+
const content = message?.content;
|
|
54
|
+
if (typeof content === 'string') blocks.push(content);
|
|
55
|
+
else if (Array.isArray(content)) {
|
|
56
|
+
for (const part of content) if (typeof part?.text === 'string') blocks.push(part.text);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return blocks.join('\n\n');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function codexArgs(outputPath: string, model?: string): string[] {
|
|
63
|
+
return [
|
|
64
|
+
'exec',
|
|
65
|
+
'--ephemeral',
|
|
66
|
+
'--ignore-user-config',
|
|
67
|
+
'--ignore-rules',
|
|
68
|
+
'--skip-git-repo-check',
|
|
69
|
+
'-s', 'read-only',
|
|
70
|
+
'-c', 'model_reasoning_effort="low"',
|
|
71
|
+
'-c', 'model_verbosity="low"',
|
|
72
|
+
...(model ? ['-m', model] : []),
|
|
73
|
+
'--color', 'never',
|
|
74
|
+
'-o', outputPath,
|
|
75
|
+
'-',
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const spawnCodex: CliRunner = async (prompt, { timeoutMs }) => {
|
|
80
|
+
const dir = mkdtempSync(join(tmpdir(), 'humemory-codex-'));
|
|
81
|
+
const outputPath = join(dir, 'last-message.txt');
|
|
82
|
+
try {
|
|
83
|
+
const proc = Bun.spawn(['codex', ...codexArgs(outputPath, process.env.HUMEMORY_LLM_MODEL)], {
|
|
84
|
+
stdin: new TextEncoder().encode(prompt),
|
|
85
|
+
stdout: 'ignore',
|
|
86
|
+
stderr: 'pipe',
|
|
87
|
+
});
|
|
88
|
+
const timer = setTimeout(() => proc.kill(), timeoutMs);
|
|
89
|
+
let code: number;
|
|
90
|
+
try {
|
|
91
|
+
code = await proc.exited;
|
|
92
|
+
} finally {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
}
|
|
95
|
+
if (code !== 0) throw new Error(`codex exec exited ${code}: ${(await new Response(proc.stderr).text()).slice(0, 200)}`);
|
|
96
|
+
return readFileSync(outputPath, 'utf-8');
|
|
97
|
+
} finally {
|
|
98
|
+
rmSync(dir, { recursive: true, force: true });
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Wraps a coding-agent CLI in the `LLMClient` shape the consolidation path expects.
|
|
104
|
+
* Only the fields `generateMemoryLevels` reads are honoured — this is a duck, not
|
|
105
|
+
* an SDK: no streaming, no tools, no token accounting.
|
|
106
|
+
*/
|
|
107
|
+
export function createCodexClient(options: CodexClientOptions = {}): LLMClient {
|
|
108
|
+
const runner = options.runner ?? spawnCodex;
|
|
109
|
+
const timeoutMs = options.timeoutMs ?? 60_000;
|
|
110
|
+
return {
|
|
111
|
+
messages: {
|
|
112
|
+
create: async (params: any) => {
|
|
113
|
+
const text = await runner(flattenPrompt(params), { timeoutMs });
|
|
114
|
+
return { content: [{ type: 'text', text: unfence(text) }] };
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { MemoryType } from './types.js';
|
|
2
|
+
import type { LLMClient } from './types.js';
|
|
3
|
+
export type { LLMClient } from './types.js';
|
|
4
|
+
|
|
5
|
+
export interface GeneratedLevels {
|
|
6
|
+
level1Summary: string;
|
|
7
|
+
level2Essential: string;
|
|
8
|
+
level3Keywords: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
const SYSTEM_PROMPT = `You are a memory consolidation system.
|
|
13
|
+
For each trace, produce 3 decay levels as strict JSON.
|
|
14
|
+
Write the levels in the same language as the trace itself.
|
|
15
|
+
Answer with a JSON object ONLY — no markdown, no explanation.`;
|
|
16
|
+
|
|
17
|
+
let _client: LLMClient | null = null;
|
|
18
|
+
|
|
19
|
+
export function setLLMClient(client: LLMClient | null): void {
|
|
20
|
+
_client = client;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function generateMemoryLevelsDeterministic(content: string): GeneratedLevels {
|
|
24
|
+
const compact = content.trim().replace(/\s+/g, ' ');
|
|
25
|
+
const keywords = [...new Set(compact.toLocaleLowerCase().match(/[\p{L}\p{N}_-]{3,}/gu) ?? [])]
|
|
26
|
+
.slice(0, 12)
|
|
27
|
+
.join(' ');
|
|
28
|
+
return {
|
|
29
|
+
level1Summary: compact.slice(0, 300),
|
|
30
|
+
level2Essential: compact.slice(0, 100),
|
|
31
|
+
level3Keywords: keywords || compact.split(/\s+/).slice(0, 10).join(' '),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function generateMemoryLevels(
|
|
36
|
+
content: string,
|
|
37
|
+
memoryType: MemoryType = 'semantic',
|
|
38
|
+
client?: LLMClient
|
|
39
|
+
): Promise<GeneratedLevels> {
|
|
40
|
+
const llm = client ?? _client;
|
|
41
|
+
if (!llm) return generateMemoryLevelsDeterministic(content);
|
|
42
|
+
const typeHints: Record<MemoryType, string> = {
|
|
43
|
+
episodic: 'a lived event, with its temporal and spatial context',
|
|
44
|
+
semantic: 'a fact or a concept',
|
|
45
|
+
procedural: 'know-how or a procedure',
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const response = await llm.messages.create({
|
|
50
|
+
model: process.env.HUMEMORY_LLM_MODEL ?? 'claude-haiku-4-5-20251001',
|
|
51
|
+
max_tokens: 512,
|
|
52
|
+
system: [
|
|
53
|
+
{
|
|
54
|
+
type: 'text',
|
|
55
|
+
text: SYSTEM_PROMPT,
|
|
56
|
+
cache_control: { type: 'ephemeral' },
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
messages: [
|
|
60
|
+
{
|
|
61
|
+
role: 'user',
|
|
62
|
+
content: `Memory type: ${typeHints[memoryType]}
|
|
63
|
+
|
|
64
|
+
Trace to consolidate:
|
|
65
|
+
"""
|
|
66
|
+
${content}
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
Produce exactly this JSON:
|
|
70
|
+
{
|
|
71
|
+
"level1Summary": "<2-3 sentences, keep the key context>",
|
|
72
|
+
"level2Essential": "<1 sentence, the irreducible information>",
|
|
73
|
+
"level3Keywords": "<8-12 BM25 keywords separated by spaces>"
|
|
74
|
+
}`,
|
|
75
|
+
},
|
|
76
|
+
],
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const text = response.content[0].type === 'text' ? (response.content[0].text ?? '') : '';
|
|
80
|
+
|
|
81
|
+
const parsed = JSON.parse(text.trim());
|
|
82
|
+
if (!parsed.level1Summary || !parsed.level2Essential || !parsed.level3Keywords) {
|
|
83
|
+
throw new Error('Missing fields in LLM response');
|
|
84
|
+
}
|
|
85
|
+
return parsed as GeneratedLevels;
|
|
86
|
+
} catch {
|
|
87
|
+
// Invalid output, quota, timeout, or network loss: consolidation still proceeds locally.
|
|
88
|
+
return generateMemoryLevelsDeterministic(content);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import { homedir } from 'os';
|
|
3
|
+
import { dirname, join, resolve } from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
|
|
6
|
+
const installationRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
|
|
7
|
+
|
|
8
|
+
/** Preserve an existing checkout's data; new installs use user-owned storage. */
|
|
9
|
+
export function dataDirectory(): string {
|
|
10
|
+
if (process.env.HUMEMORY_DATA_DIR) return resolve(process.env.HUMEMORY_DATA_DIR);
|
|
11
|
+
const legacy = join(installationRoot, 'data');
|
|
12
|
+
if (existsSync(join(legacy, 'humemory.db'))) return legacy;
|
|
13
|
+
if (process.platform === 'win32') return join(process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local'), 'humemory');
|
|
14
|
+
if (process.platform === 'darwin') return join(homedir(), 'Library', 'Application Support', 'humemory');
|
|
15
|
+
return join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'humemory');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function databasePath(): string {
|
|
19
|
+
return process.env.HUMEMORY_DB ?? join(dataDirectory(), 'humemory.db');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function queueDirectory(): string {
|
|
23
|
+
return process.env.HUMEMORY_QUEUE ?? join(dataDirectory(), 'maintenance-queue');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function modelCacheDirectory(): string {
|
|
27
|
+
return process.env.HUMEMORY_MODEL_CACHE ?? join(dataDirectory(), 'models');
|
|
28
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Browser-safe lexical normalization; POSIX identities remain case sensitive. */
|
|
2
|
+
export function projectPath(path: string): string {
|
|
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
|
+
|
|
8
|
+
export function remapPath(path: string, from: string, to: string): string {
|
|
9
|
+
const key = projectPath(path);
|
|
10
|
+
const source = projectPath(from);
|
|
11
|
+
if (key !== source && !key.startsWith(source + '/')) return path;
|
|
12
|
+
const suffix = path.replace(/\\/g, '/').replace(/\/$/, '').slice(source.length);
|
|
13
|
+
return to.replace(/\\/g, '/').replace(/\/$/, '') + suffix;
|
|
14
|
+
}
|