humemory 0.2.1 → 0.2.2

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
@@ -42,6 +42,7 @@ pnpm cli <cmd> # run CLI directly
42
42
  pnpm test # bun test, single pass
43
43
  pnpm test:watch # bun test --watch
44
44
  pnpm consolidate # manual decay pass (cron-friendly)
45
+ pnpm maintenance # process queued sessions (network-free by default)
45
46
  ```
46
47
 
47
48
  Single test file: `bun test tests/humemory.test.ts`
@@ -56,13 +57,15 @@ src/
56
57
  │ ├── types.ts # Memory, DecayLevel, SearchQuery, MemoryStore iface
57
58
  │ ├── decay.ts # degradation curve + thresholds
58
59
  │ ├── search.ts # inverse search (BM25, degraded-first)
59
- │ └── llm-generator.ts # auto-generate L1/L2/L3 via Claude Haiku (prompt cache)
60
+ │ └── llm-generator.ts # deterministic L1/L2/L3; optional injected LLM
60
61
  ├── store/
61
62
  │ └── sqlite.ts # bun:sqlite store (WAL), findSimilar/merge/setPhotographic
62
63
  ├── agent/
63
64
  │ ├── session-parser.ts # parse Claude Code session transcripts
65
+ │ ├── source-registry.ts # discover local AI runtimes without reading sessions
64
66
  │ ├── learning-extractor.ts # extract decisions/bugs/solutions
65
- │ ├── claude-hook.ts # Stop-hook → auto-encode session learnings
67
+ │ ├── maintenance-queue.ts # durable async inbox, session checkpoints, dead-letter
68
+ │ ├── claude-hook.ts # worker-side session learning encoder
66
69
  │ └── session-context.ts # SessionStart → markdown block (open loops + traces)
67
70
  ├── core/
68
71
  │ ├── clock.ts # Clock seam (systemClock / FakeClock)
@@ -73,8 +76,9 @@ src/
73
76
  ├── cli/index.ts # commander CLI
74
77
  └── index.ts # library exports
75
78
  web/ # React front (bun bundler → public/app, served at /app)
76
- scripts/hook-session.ts # Claude Code Stop hook → encode learnings
79
+ scripts/hook-session.ts # Claude Code Stop hook → queue raw session only
77
80
  scripts/hook-session-start.ts # Claude Code SessionStart hook → inject context
81
+ scripts/maintenance-worker.ts # async extraction/storage; deterministic by default
78
82
  tests/ # bun test (hermetic; helpers/ + fixtures/)
79
83
  data/humemory.db # shared DB (created on first run)
80
84
  ```
@@ -149,9 +153,9 @@ clock- and event-driven and cannot be trusted without it.
149
153
  - Core decay + inverse search; `bun:sqlite` store (WAL, write-queue serialization)
150
154
  - CLI + Hono API + web dashboard ("palais de mémoire")
151
155
  - Nightly cron consolidation (`0 3 * * *`)
152
- - LLM auto-generation of L1/L2/L3 (Claude Haiku + prompt caching)
156
+ - Deterministic L1/L2/L3 generation; optional injected LLM enhancement
153
157
  - Similar-detection + merge (L4); enriched search (type/period/saillance/recalls)
154
- - Photographic mode; Claude Code `Stop` hook → session learning capture
158
+ - Photographic mode; Claude Code `Stop` hook → durable async maintenance queue
155
159
 
156
160
  ### 🎯 Phase 5 — Prospective memory (the destiny)
157
161
  > Detailed corrected plan in **[PHASE5_PLAN.md](./PHASE5_PLAN.md)**. Summary below.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.2] - 2026-08-15
4
+ **Features:**
5
+ - add async multi-agent session capture
6
+
7
+
8
+
3
9
  ## [0.2.1] - 2026-08-09
4
10
  **Features:**
5
11
  - correction kills the script — contradictions target scripts too
package/README.md CHANGED
@@ -37,7 +37,8 @@ the curve. A **photographic** flag pins critical traces so they never fade.
37
37
  escalates toward full content only on a match — the human recall pattern, fast by
38
38
  construction.
39
39
 
40
- A Claude Code `Stop` hook already auto-encodes the learnings of each dev session.
40
+ A Claude Code `Stop` hook can queue each completed session instantly; maintenance
41
+ extracts and stores its learnings afterward, outside the agent's critical path.
41
42
 
42
43
  ### 2. Prospective memory — *what to resurface* 🎯 the destiny
43
44
 
@@ -63,9 +64,37 @@ pnpm install
63
64
  pnpm build:web # bundle the React front (bun's own bundler, no extra tooling)
64
65
  pnpm start:api # API + dashboards → http://localhost:3456
65
66
  pnpm cli status # state of the memory palace
67
+ pnpm cli sources discover # discover local AI runtimes; reads no sessions
66
68
  pnpm test # bun test — backend and React components, one runner
67
69
  ```
68
70
 
71
+ ### Local AI sources — a non-exhaustive registry
72
+
73
+ humemory keeps acquisition outside the cognitive core: the registry discovers
74
+ local producers, while humemory decides what becomes a trace, how it decays, and
75
+ when it resurfaces. Discovery only checks commands and known data roots; importing
76
+ historical sessions remains an explicit, opt-in step.
77
+
78
+ The non-exhaustive catalog currently recognizes:
79
+
80
+ | Runtime | Vendor | Discovery hints |
81
+ | --- | --- | --- |
82
+ | Claude Code | Anthropic | `claude`, `~/.claude` |
83
+ | Codex | OpenAI | `codex`, `~/.codex` |
84
+ | Kimi Code / Kimi Desktop | Moonshot AI | `kimi`, `~/.kimi-code`, desktop data roots |
85
+ | Mistral Vibe | **Mistral AI** | `vibe`, `$VIBE_HOME`, `~/.vibe` |
86
+ | OpenCode | SST | `opencode`, `~/.opencode` |
87
+ | Qwen Code | Alibaba Cloud | `qwen`, `$QWEN_RUNTIME_DIR`, `$QWEN_HOME`, `~/.qwen` |
88
+ | Gemini CLI | Google | `gemini`, `$GEMINI_CLI_HOME`, `~/.gemini` |
89
+ | GitHub Copilot CLI | GitHub | `copilot`, `~/.copilot` |
90
+ | Aider | Aider-AI | `aider`, `~/.aider.conf.yml` |
91
+ | Cursor | Anysphere | `cursor`, desktop data roots |
92
+ | Windsurf | Cognition | `windsurf`, desktop data roots |
93
+
94
+ An entry means **ready to be discovered**, not that its evolving private session
95
+ format is already parsed. Run `pnpm cli sources discover --installed-only` for a
96
+ local inventory without exposing conversation content.
97
+
69
98
  The React app is served at **`/`** (and `/app`). The original vanilla dashboard
70
99
  has been removed — the React front reached parity first, and git keeps the old
71
100
  one if it is ever needed.
@@ -133,7 +162,8 @@ more than leaving one open.
133
162
 
134
163
  ### Wiring the Claude Code hooks
135
164
 
136
- Two hooks, both optional and both fail-open — neither will ever block a session:
165
+ Two hooks, both optional and both fail-open. `Stop` only writes the raw session to
166
+ a durable local queue; it never waits for a model or a network request:
137
167
 
138
168
  ```jsonc
139
169
  // ~/.claude/settings.json
@@ -143,7 +173,7 @@ Two hooks, both optional and both fail-open — neither will ever block a sessio
143
173
  "SessionStart": [{ "matcher": "", "hooks": [
144
174
  { "type": "command", "command": "bun /path/to/humemory/scripts/hook-session-start.ts" }
145
175
  ]}],
146
- // end of session: encodes what was learned
176
+ // end of session: queues the transcript for asynchronous maintenance
147
177
  "Stop": [{ "matcher": "", "hooks": [
148
178
  { "type": "command", "command": "bun /path/to/humemory/scripts/hook-session.ts" }
149
179
  ]}]
@@ -155,9 +185,34 @@ Two hooks, both optional and both fail-open — neither will ever block a sessio
155
185
  fires any due time cues, and writes a markdown block on stdout — which Claude Code
156
186
  injects into the session. Nothing relevant means nothing written.
157
187
 
188
+ Process queued sessions independently from the agent flow:
189
+
190
+ ```bash
191
+ pnpm maintenance
192
+ ```
193
+
194
+ The default maintenance path is deterministic and network-free. To opt into
195
+ Claude as an asynchronous quality enhancement, set
196
+ `HUMEMORY_MAINTENANCE_LLM=anthropic` and `ANTHROPIC_API_KEY`; quota errors and
197
+ timeouts fall back to the deterministic extractor. A queue item is deleted only
198
+ after its extracted memories are committed successfully.
199
+
200
+ The queue directory is the whole contract, and it is inspectable at any time:
201
+
202
+ | Entry | Meaning |
203
+ | --- | --- |
204
+ | `<id>.json` | a session waiting to be encoded, keyed on session — not on transcript content, since `Stop` resends a longer transcript every turn |
205
+ | `<id>.json.processing` | claimed by the running worker; a newer transcript may land on the free `<id>.json` slot meanwhile, and survives |
206
+ | `checkpoints/<id>.json` | how many messages of that session are already encoded, so a resent transcript only contributes its delta |
207
+ | `<id>.dead.json` | gave up after `maxAttempts` (5), or unparseable on disk; never retried, never deleted |
208
+ | `.worker.lock` | single-worker token; a lock left by a dead worker is reclaimed atomically after 5 min |
209
+
158
210
  | Env var | Default | Effect |
159
211
  | --- | --- | --- |
160
212
  | `HUMEMORY_DB` | `data/humemory.db` | database path |
213
+ | `HUMEMORY_QUEUE` | `data/maintenance-queue` | durable raw-session inbox |
214
+ | `HUMEMORY_MAINTENANCE_LLM` | `none` | optional enhancement (`anthropic`) |
215
+ | `HUMEMORY_MAINTENANCE_TIMEOUT_MS` | `8000` | model timeout; never affects the agent hook |
161
216
  | `HUMEMORY_DIR` | `cwd` | mental place to scope loops and traces to |
162
217
  | `HUMEMORY_SESSION_BUDGET` | `10` | max items listed per section |
163
218
  | `HUMEMORY_SAILLANCE_MIN` | `60` | salience floor for recalling a decayed trace |
@@ -171,10 +226,42 @@ A log remembers everything and reminds you of nothing. A human memory forgets mo
171
226
  of it and hands you the one thing that matters, at the moment it matters. humemory
172
227
  is an attempt to give an AI agent the second kind.
173
228
 
229
+ ## A memory engine, not an integration bundle
230
+
231
+ humemory has a narrow job: decide what deserves to become a memory, how that
232
+ trace changes with time, and when it should return. Everything that brings data
233
+ in sits outside the cognitive core.
234
+
235
+ - **Connectors live in a registry.** Discovery and future import adapters identify
236
+ Claude Code, Codex, Kimi, Qwen, Mistral and other local producers; they don't
237
+ become memory primitives. Adding a source doesn't change decay, recall, trust
238
+ or cue logic.
239
+ - **SQLite owns the truth.** Provenance, decay levels, intentions, scripts and
240
+ review decisions remain queryable and recoverable. Vector embeddings form a
241
+ second, disposable search lane: humemory can rebuild them, change the embedding
242
+ model or disable semantic search without putting the memory store at risk.
243
+ - **Several agents can share one brain.** MCP and source attribution let Claude,
244
+ Codex, Kimi, OpenCode and future clients use the same store. Every write keeps
245
+ its agent and device provenance instead of inheriting one vendor's session model.
246
+ - **Maintenance stays out of the agent's path.** Hooks queue a raw session locally,
247
+ then exit. A separate worker filters, consolidates and stores it; a slow GPU,
248
+ a network outage or an exhausted quota doesn't make the agent wait.
249
+ - **LLMs are optional, not governors.** Decay, salience, recall, cues, scripts,
250
+ trust and deterministic consolidation work without an API key. A configured
251
+ model may improve the generated text, but failure always returns to the local
252
+ deterministic path.
253
+ - **Automation stops before judgment.** The dreamer files proposals, agent-authored
254
+ scripts begin as drafts, and contradictions stay inspectable. A model doesn't
255
+ silently turn a guess into permanent memory.
256
+
257
+ Historical absorption stays opt-in. `sources discover` checks commands and known
258
+ paths without reading conversations. Each runtime still needs a parser before
259
+ humemory can import its sessions, and discovery never pretends otherwise.
260
+
174
261
  ## Stack
175
262
 
176
263
  TypeScript · `bun:sqlite` (WAL) · `flexsearch` (BM25) · `hono` (API) ·
177
- `commander` (CLI) · `@anthropic-ai/sdk` (level generation).
264
+ `commander` (CLI) · `@anthropic-ai/sdk` (optional maintenance adapter).
178
265
 
179
266
  ---
180
267
 
@@ -202,7 +289,7 @@ The CLI provides several commands to interact with humemory:
202
289
  - `-l2, --level2 <essential>`: Essential for consolidation N2
203
290
  - `-l3, --level3 <keywords>`: Trace for fast search N3
204
291
  - `-t, --type <type>`: Memory type (episodic/semantic/procedural)
205
- - `--auto`: Auto-generate N1/N2/N3 via LLM (requires ANTHROPIC_API_KEY)
292
+ - `--auto`: Auto-generate N1/N2/N3 locally; an injected LLM may enhance them
206
293
  - `--photographic`: Photographic mode — disable degradation
207
294
 
208
295
  - **Search for memory traces**:
@@ -446,9 +533,9 @@ keywords >5. `photographic: true` disables decay entirely.
446
533
  - Core decay + inverse search; `bun:sqlite` store (WAL, write-queue serialization)
447
534
  - CLI + Hono API + web dashboard ("palais de mémoire")
448
535
  - Nightly cron consolidation (`0 3 * * *`)
449
- - LLM auto-generation of L1/L2/L3 (Claude Haiku + prompt caching)
536
+ - Deterministic L1/L2/L3 generation; optional injected LLM enhancement
450
537
  - Similar-detection + merge (L4); enriched search (type/period/saillance/recalls)
451
- - Photographic mode; Claude Code `Stop` hook → session learning capture
538
+ - Photographic mode; Claude Code `Stop` hook → durable async maintenance queue
452
539
 
453
540
  ### 🎯 Phase 5 — Prospective memory (the destiny)
454
541
  > Corrected plan in **[PHASE5_PLAN.md](./PHASE5_PLAN.md)**. Summary:
@@ -1,9 +1,19 @@
1
1
  import type { LLMClient } from '../core/llm-generator.js';
2
+ import type { TraceSource } from '../core/types.js';
2
3
  export interface HookOptions {
3
4
  dbPath: string;
4
5
  directory?: string;
5
6
  maxLearnings?: number;
6
7
  client?: LLMClient;
8
+ llmTimeoutMs?: number;
9
+ source?: TraceSource;
10
+ agent?: string;
11
+ /**
12
+ * Number of leading transcript messages already encoded for this session.
13
+ * `Stop` fires once per turn and resends the whole transcript, so without a
14
+ * checkpoint every pass would re-encode the entire history as new memories.
15
+ */
16
+ sinceMessage?: number;
7
17
  verbose?: boolean;
8
18
  }
9
19
  export interface HookResult {
@@ -11,5 +21,8 @@ export interface HookResult {
11
21
  directory: string;
12
22
  memoriesStored: number;
13
23
  learnings: string[];
24
+ extractionMode: 'llm' | 'deterministic';
25
+ /** Total messages in the transcript — the checkpoint to persist after success. */
26
+ messagesSeen: number;
14
27
  }
15
28
  export declare function processSession(rawTranscript: string, options: HookOptions): Promise<HookResult>;
@@ -1,14 +1,53 @@
1
1
  import { SQLiteStore } from '../store/sqlite.js';
2
2
  import { parseClaudeHookPayload } from './session-parser.js';
3
- import { extractLearnings } from './learning-extractor.js';
4
- import Anthropic from '@anthropic-ai/sdk';
3
+ import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
4
+ async function withTimeout(promise, timeoutMs) {
5
+ let timer;
6
+ try {
7
+ return await Promise.race([
8
+ promise,
9
+ new Promise((_, reject) => {
10
+ timer = setTimeout(() => reject(new Error(`maintenance model timed out after ${timeoutMs}ms`)), timeoutMs);
11
+ }),
12
+ ]);
13
+ }
14
+ finally {
15
+ if (timer)
16
+ clearTimeout(timer);
17
+ }
18
+ }
5
19
  export async function processSession(rawTranscript, options) {
6
20
  const directory = options.directory ?? process.cwd();
7
- const client = options.client ?? new Anthropic();
8
21
  const session = parseClaudeHookPayload(rawTranscript, directory);
9
- const learnings = await extractLearnings(session, client, options.maxLearnings ?? 5);
22
+ const maxLearnings = options.maxLearnings ?? 5;
23
+ const messagesSeen = session.messages.length;
24
+ // Only the messages added since the last successful pass are candidates.
25
+ const since = Math.max(0, Math.min(options.sinceMessage ?? 0, messagesSeen));
26
+ const pending = session.messages.slice(since);
27
+ if (pending.length === 0) {
28
+ return {
29
+ sessionId: session.sessionId, directory: session.directory,
30
+ memoriesStored: 0, learnings: [], extractionMode: 'deterministic', messagesSeen,
31
+ };
32
+ }
33
+ const scoped = {
34
+ ...session,
35
+ messages: pending,
36
+ rawText: pending.map((m) => `${m.role}: ${m.content}`).join('\n\n'),
37
+ };
38
+ let extractionMode = 'deterministic';
39
+ let learnings = extractLearningsDeterministic(scoped, maxLearnings);
40
+ if (options.client) {
41
+ try {
42
+ learnings = await withTimeout(extractLearnings(scoped, options.client, maxLearnings), options.llmTimeoutMs ?? 8_000);
43
+ extractionMode = 'llm';
44
+ }
45
+ catch {
46
+ // Quota, network, timeout: the deterministic path already produced a result.
47
+ }
48
+ }
10
49
  if (learnings.length === 0) {
11
- return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [] };
50
+ return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [], extractionMode, messagesSeen };
12
51
  }
13
52
  const store = new SQLiteStore(options.dbPath);
14
53
  const stored = [];
@@ -22,6 +61,8 @@ export async function processSession(rawTranscript, options) {
22
61
  sessionId: session.sessionId,
23
62
  memoryType: learning.memoryType,
24
63
  level3Keywords: learning.level3Keywords,
64
+ source: options.source ?? 'agent',
65
+ agent: options.agent ?? 'unknown',
25
66
  });
26
67
  stored.push(learning.content.slice(0, 80));
27
68
  }
@@ -34,5 +75,7 @@ export async function processSession(rawTranscript, options) {
34
75
  directory: session.directory,
35
76
  memoriesStored: stored.length,
36
77
  learnings: stored,
78
+ extractionMode,
79
+ messagesSeen,
37
80
  };
38
81
  }
@@ -7,4 +7,6 @@ export interface ExtractedLearning {
7
7
  keywords: string[];
8
8
  level3Keywords: string;
9
9
  }
10
+ /** Fast, network-free baseline used whenever no maintenance model is available. */
11
+ export declare function extractLearningsDeterministic(session: ParsedSession, maxLearnings?: number): ExtractedLearning[];
10
12
  export declare function extractLearnings(session: ParsedSession, client: LLMClient, maxLearnings?: number): Promise<ExtractedLearning[]>;
@@ -1,3 +1,42 @@
1
+ const STOP_WORDS = new Set([
2
+ 'about', 'after', 'again', 'avec', 'cette', 'dans', 'elle', 'from', 'have', 'mais',
3
+ 'pour', 'that', 'this', 'tout', 'une', 'with', 'your', 'être', 'plus', 'then', 'when',
4
+ ]);
5
+ function deterministicKeywords(content) {
6
+ const words = content
7
+ .toLocaleLowerCase()
8
+ .normalize('NFD')
9
+ .replace(/[\u0300-\u036f]/g, '')
10
+ .match(/[a-z0-9_-]{4,}/g) ?? [];
11
+ return [...new Set(words.filter((word) => !STOP_WORDS.has(word)))].slice(0, 8);
12
+ }
13
+ /** Fast, network-free baseline used whenever no maintenance model is available. */
14
+ export function extractLearningsDeterministic(session, maxLearnings = 5) {
15
+ const unique = new Set();
16
+ const candidates = session.messages
17
+ .filter((message) => message.role === 'assistant')
18
+ .map((message) => message.content.trim())
19
+ .filter((content) => content.length >= 40)
20
+ .filter((content) => {
21
+ const key = content.replace(/\s+/g, ' ').toLocaleLowerCase();
22
+ if (unique.has(key))
23
+ return false;
24
+ unique.add(key);
25
+ return true;
26
+ })
27
+ .slice(-maxLearnings);
28
+ return candidates.map((content) => {
29
+ const clipped = content.slice(0, 1_000);
30
+ const keywords = deterministicKeywords(clipped);
31
+ const procedural = /\b(fix(?:ed)?|implement(?:ed)?|add(?:ed)?|use|run|step|corrig|ajout|remplac|configur)/i.test(clipped);
32
+ return {
33
+ content: clipped,
34
+ memoryType: procedural ? 'procedural' : 'episodic',
35
+ keywords,
36
+ level3Keywords: keywords.join(' '),
37
+ };
38
+ });
39
+ }
1
40
  const SYSTEM_PROMPT = `You are a system that extracts mnemonic learnings.
2
41
  Analyse the session and extract the key learnings worth remembering.
3
42
  Write them in the same language as the session itself.
@@ -59,17 +98,7 @@ Format JSON requis:
59
98
  .slice(0, maxLearnings);
60
99
  }
61
100
  catch {
62
- // Fallback: store the last assistant message as single episodic memory
63
- const lastAssistant = session.messages.filter(m => m.role === 'assistant').pop();
64
- if (!lastAssistant)
65
- return [];
66
- return [
67
- {
68
- content: lastAssistant.content.slice(0, 500),
69
- memoryType: 'episodic',
70
- keywords: [],
71
- level3Keywords: '',
72
- },
73
- ];
101
+ return extractLearningsDeterministic(session, 1)
102
+ .map((learning) => ({ ...learning, memoryType: 'episodic' }));
74
103
  }
75
104
  }
@@ -0,0 +1,47 @@
1
+ import type { LLMClient } from '../core/llm-generator.js';
2
+ export interface MaintenanceJob {
3
+ version: 1;
4
+ id: string;
5
+ source: string;
6
+ agent: string;
7
+ sessionId: string;
8
+ directory: string;
9
+ rawTranscript: string;
10
+ maxLearnings: number;
11
+ queuedAt: string;
12
+ attempts: number;
13
+ lastError?: string;
14
+ }
15
+ export interface EnqueueOptions {
16
+ queueDir: string;
17
+ directory?: string;
18
+ source?: string;
19
+ agent?: string;
20
+ maxLearnings?: number;
21
+ now?: () => Date;
22
+ }
23
+ export interface QueueResult {
24
+ job: MaintenanceJob;
25
+ created: boolean;
26
+ path: string;
27
+ }
28
+ export interface WorkerOptions {
29
+ queueDir: string;
30
+ dbPath: string;
31
+ client?: LLMClient;
32
+ llmTimeoutMs?: number;
33
+ maxJobs?: number;
34
+ lockStaleMs?: number;
35
+ maxAttempts?: number;
36
+ now?: () => Date;
37
+ }
38
+ export interface WorkerResult {
39
+ discovered: number;
40
+ processed: number;
41
+ failed: number;
42
+ deadLettered: number;
43
+ memoriesStored: number;
44
+ busy: boolean;
45
+ }
46
+ export declare function enqueueSession(rawTranscript: string, options: EnqueueOptions): Promise<QueueResult>;
47
+ export declare function processMaintenanceQueue(options: WorkerOptions): Promise<WorkerResult>;
@@ -0,0 +1,246 @@
1
+ import { createHash, randomUUID } from 'crypto';
2
+ import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { processSession } from './claude-hook.js';
5
+ import { parseClaudeHookPayload } from './session-parser.js';
6
+ const DEFAULT_LOCK_STALE_MS = 5 * 60 * 1000;
7
+ const DEFAULT_MAX_ATTEMPTS = 5;
8
+ const DEAD_LETTER_SUFFIX = '.dead.json';
9
+ const PROCESSING_SUFFIX = '.processing';
10
+ const CHECKPOINT_DIR = 'checkpoints';
11
+ function jobPath(queueDir, id) {
12
+ return join(queueDir, `${id}.json`);
13
+ }
14
+ function checkpointPath(queueDir, id) {
15
+ return join(queueDir, CHECKPOINT_DIR, `${id}.json`);
16
+ }
17
+ async function readCheckpoint(queueDir, id) {
18
+ try {
19
+ return JSON.parse(await readFile(checkpointPath(queueDir, id), 'utf8'));
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ async function atomicWrite(path, content) {
26
+ const temporary = `${path}.${process.pid}.tmp`;
27
+ await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 });
28
+ try {
29
+ await rename(temporary, path);
30
+ }
31
+ catch (error) {
32
+ if (error?.code !== 'EEXIST' && error?.code !== 'EPERM')
33
+ throw error;
34
+ await rm(path, { force: true });
35
+ await rename(temporary, path);
36
+ }
37
+ }
38
+ export async function enqueueSession(rawTranscript, options) {
39
+ const raw = rawTranscript.trim();
40
+ if (!raw)
41
+ throw new Error('Cannot queue an empty session');
42
+ const directory = options.directory ?? process.cwd();
43
+ const parsed = parseClaudeHookPayload(rawTranscript, directory);
44
+ const source = options.source ?? 'claude-code';
45
+ // Keyed on session, not transcript content: `Stop` fires once per turn and the
46
+ // transcript grows each time, so hashing the raw text would enqueue one job
47
+ // per turn instead of one per session. Re-enqueuing overwrites with the
48
+ // latest (fuller) transcript and resets attempts — new content, new chance.
49
+ const id = createHash('sha256').update(`${source}\0${parsed.sessionId}`).digest('hex');
50
+ const path = jobPath(options.queueDir, id);
51
+ const now = options.now ?? (() => new Date());
52
+ const job = {
53
+ version: 1,
54
+ id,
55
+ source,
56
+ agent: options.agent ?? source,
57
+ sessionId: parsed.sessionId,
58
+ directory: parsed.directory,
59
+ rawTranscript,
60
+ maxLearnings: options.maxLearnings ?? 5,
61
+ queuedAt: now().toISOString(),
62
+ attempts: 0,
63
+ };
64
+ await mkdir(options.queueDir, { recursive: true });
65
+ let created = true;
66
+ try {
67
+ await readFile(path, 'utf8');
68
+ created = false;
69
+ }
70
+ catch (error) {
71
+ if (error?.code !== 'ENOENT')
72
+ throw error;
73
+ }
74
+ await atomicWrite(path, JSON.stringify(job));
75
+ return { job, created, path };
76
+ }
77
+ export async function processMaintenanceQueue(options) {
78
+ await mkdir(options.queueDir, { recursive: true });
79
+ await mkdir(join(options.queueDir, CHECKPOINT_DIR), { recursive: true });
80
+ const now = options.now ?? (() => new Date());
81
+ const lockPath = join(options.queueDir, '.worker.lock');
82
+ const token = `${process.pid}-${randomUUID()}`;
83
+ let lock;
84
+ for (let attempt = 0; attempt < 2; attempt += 1) {
85
+ try {
86
+ lock = await open(lockPath, 'wx', 0o600);
87
+ await lock.writeFile(JSON.stringify({ pid: process.pid, token, startedAt: now().toISOString() }));
88
+ break;
89
+ }
90
+ catch (error) {
91
+ if (error?.code !== 'EEXIST')
92
+ throw error;
93
+ const age = now().getTime() - (await stat(lockPath)).mtimeMs;
94
+ if (attempt === 0 && age > (options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS)) {
95
+ // Atomic takeover: renaming the stale lock away can only succeed once,
96
+ // so two workers seeing the same stale lock cannot both reclaim it. A
97
+ // plain unlink would instead delete a lock the winner just acquired.
98
+ try {
99
+ await rename(lockPath, `${lockPath}.stale.${token}`);
100
+ await rm(`${lockPath}.stale.${token}`, { force: true });
101
+ }
102
+ catch (renameError) {
103
+ if (renameError?.code !== 'ENOENT')
104
+ throw renameError;
105
+ // Another worker won the takeover; the retry below will see its lock.
106
+ }
107
+ continue;
108
+ }
109
+ return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
110
+ }
111
+ }
112
+ if (!lock)
113
+ return { discovered: 0, processed: 0, failed: 0, deadLettered: 0, memoriesStored: 0, busy: true };
114
+ try {
115
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
116
+ // We hold the exclusive lock, so any leftover `.processing` file belongs to
117
+ // a worker that died mid-job. Restore it unless a newer session arrived in
118
+ // the meantime, in which case the newer transcript supersedes it.
119
+ for (const orphan of (await readdir(options.queueDir)).filter((file) => file.endsWith(PROCESSING_SUFFIX))) {
120
+ const orphanPath = join(options.queueDir, orphan);
121
+ const restored = join(options.queueDir, orphan.slice(0, -PROCESSING_SUFFIX.length));
122
+ try {
123
+ await stat(restored);
124
+ await rm(orphanPath, { force: true });
125
+ }
126
+ catch {
127
+ await rename(orphanPath, restored).catch(() => undefined);
128
+ }
129
+ }
130
+ const candidates = (await readdir(options.queueDir)).filter((file) => file.endsWith('.json') && !file.endsWith(DEAD_LETTER_SUFFIX));
131
+ const withMeta = await Promise.all(candidates.map(async (file) => {
132
+ const path = join(options.queueDir, file);
133
+ try {
134
+ const job = JSON.parse(await readFile(path, 'utf8'));
135
+ return { file, path, queuedAt: job.queuedAt ?? '' };
136
+ }
137
+ catch {
138
+ return { file, path, queuedAt: '' };
139
+ }
140
+ }));
141
+ // Oldest-first: queuedAt is the enqueue timestamp, not the filename (a
142
+ // sha256 id sorts arbitrarily and would starve unlucky hashes forever).
143
+ const files = withMeta
144
+ .sort((a, b) => a.queuedAt.localeCompare(b.queuedAt))
145
+ .slice(0, options.maxJobs ?? 20)
146
+ .map((entry) => entry.file);
147
+ const result = {
148
+ discovered: files.length,
149
+ processed: 0,
150
+ failed: 0,
151
+ deadLettered: 0,
152
+ memoriesStored: 0,
153
+ busy: false,
154
+ };
155
+ for (const file of files) {
156
+ const path = join(options.queueDir, file);
157
+ // Claim the job by moving it aside. The hook may enqueue a newer, longer
158
+ // transcript for the same session while we work; it lands on the now-free
159
+ // job path and survives, instead of being deleted by our own cleanup.
160
+ const claimed = `${path}${PROCESSING_SUFFIX}`;
161
+ try {
162
+ await rename(path, claimed);
163
+ }
164
+ catch {
165
+ continue; // Vanished between listing and claiming — nothing to do.
166
+ }
167
+ let job;
168
+ try {
169
+ job = JSON.parse(await readFile(claimed, 'utf8'));
170
+ if (job.version !== 1 || !job.rawTranscript)
171
+ throw new Error('Unsupported maintenance job');
172
+ const checkpoint = await readCheckpoint(options.queueDir, job.id);
173
+ const processed = await processSession(job.rawTranscript, {
174
+ dbPath: options.dbPath,
175
+ directory: job.directory,
176
+ maxLearnings: job.maxLearnings,
177
+ client: options.client,
178
+ llmTimeoutMs: options.llmTimeoutMs,
179
+ source: 'hook',
180
+ agent: job.agent,
181
+ sinceMessage: checkpoint?.messagesSeen ?? 0,
182
+ });
183
+ // Record how far this session has been encoded before dropping the job,
184
+ // so a later `Stop` resending the full transcript only adds the delta.
185
+ await atomicWrite(checkpointPath(options.queueDir, job.id), JSON.stringify({ sessionId: job.sessionId, messagesSeen: processed.messagesSeen, updatedAt: now().toISOString() }));
186
+ await rm(claimed, { force: true });
187
+ result.processed += 1;
188
+ result.memoriesStored += processed.memoriesStored;
189
+ }
190
+ catch (error) {
191
+ result.failed += 1;
192
+ const lastError = error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
193
+ try {
194
+ if (!job) {
195
+ // Unparseable on disk: no attempt counter can live in it, so retrying
196
+ // is pointless. Dead-letter the raw bytes immediately rather than
197
+ // failing this file on every future pass.
198
+ await rename(claimed, join(options.queueDir, `${file.replace(/\.json$/, '')}${DEAD_LETTER_SUFFIX}`));
199
+ result.deadLettered += 1;
200
+ continue;
201
+ }
202
+ job.attempts = (job.attempts ?? 0) + 1;
203
+ job.lastError = lastError;
204
+ if (job.attempts >= maxAttempts) {
205
+ // Exhausted retries: move out of the active queue so it stops being
206
+ // picked up and stops inflating `failed` on every future pass, but
207
+ // keep the raw transcript on disk for manual inspection.
208
+ await atomicWrite(join(options.queueDir, `${job.id}${DEAD_LETTER_SUFFIX}`), JSON.stringify(job));
209
+ await rm(claimed, { force: true });
210
+ result.deadLettered += 1;
211
+ }
212
+ else {
213
+ // Restore for a later pass — unless a newer transcript already took
214
+ // the slot, which supersedes this one.
215
+ try {
216
+ await stat(path);
217
+ await rm(claimed, { force: true });
218
+ }
219
+ catch {
220
+ await atomicWrite(path, JSON.stringify(job));
221
+ await rm(claimed, { force: true });
222
+ }
223
+ }
224
+ }
225
+ catch {
226
+ // Never erase evidence: the claimed file stays for manual inspection
227
+ // and the orphan sweep restores it on the next pass.
228
+ }
229
+ }
230
+ }
231
+ return result;
232
+ }
233
+ finally {
234
+ await lock.close();
235
+ // Only release a lock still held by this worker: if ours went stale and was
236
+ // reclaimed, the file now belongs to whoever took over.
237
+ try {
238
+ const held = JSON.parse(await readFile(lockPath, 'utf8'));
239
+ if (held?.token === token)
240
+ await rm(lockPath, { force: true });
241
+ }
242
+ catch {
243
+ // Already gone or unreadable — nothing of ours left to release.
244
+ }
245
+ }
246
+ }
@@ -0,0 +1,34 @@
1
+ export type AgentSourceId = 'claude-code' | 'codex' | 'kimi-code' | 'kimi-desktop' | 'opencode' | 'qwen-code' | 'mistral-vibe' | 'gemini-cli' | 'github-copilot-cli' | 'aider' | 'cursor' | 'windsurf';
2
+ export interface AgentSourceDefinition {
3
+ id: AgentSourceId;
4
+ name: string;
5
+ vendor: string;
6
+ commands: string[];
7
+ /** Known local roots. Discovery only: no file below these roots is read. */
8
+ roots: RootCandidate[];
9
+ }
10
+ type RootCandidate = {
11
+ base: 'home' | 'appData' | 'localAppData';
12
+ parts: string[];
13
+ } | {
14
+ base: 'env';
15
+ variable: string;
16
+ parts?: string[];
17
+ };
18
+ export interface DiscoveredAgentSource extends AgentSourceDefinition {
19
+ installed: boolean;
20
+ evidence: string[];
21
+ }
22
+ export interface DiscoveryOptions {
23
+ homeDir?: string;
24
+ env?: Record<string, string | undefined>;
25
+ platform?: NodeJS.Platform;
26
+ exists?: (path: string) => boolean;
27
+ }
28
+ /**
29
+ * Non-exhaustive catalog of local AI agent runtimes. A catalog entry means
30
+ * "discoverable", not "its private session format is already importable".
31
+ */
32
+ export declare const KNOWN_AGENT_SOURCES: readonly AgentSourceDefinition[];
33
+ export declare function discoverLocalAgentSources(options?: DiscoveryOptions): DiscoveredAgentSource[];
34
+ export {};
@@ -0,0 +1,89 @@
1
+ import { existsSync } from 'fs';
2
+ import { posix, win32 } from 'path';
3
+ const home = (...parts) => ({ base: 'home', parts });
4
+ const appData = (...parts) => ({ base: 'appData', parts });
5
+ const localAppData = (...parts) => ({ base: 'localAppData', parts });
6
+ const envRoot = (variable, ...parts) => ({ base: 'env', variable, parts });
7
+ /**
8
+ * Non-exhaustive catalog of local AI agent runtimes. A catalog entry means
9
+ * "discoverable", not "its private session format is already importable".
10
+ */
11
+ export const KNOWN_AGENT_SOURCES = [
12
+ { id: 'claude-code', name: 'Claude Code', vendor: 'Anthropic', commands: ['claude'], roots: [home('.claude')] },
13
+ { id: 'codex', name: 'Codex', vendor: 'OpenAI', commands: ['codex'], roots: [home('.codex')] },
14
+ {
15
+ id: 'kimi-code', name: 'Kimi Code', vendor: 'Moonshot AI', commands: ['kimi'],
16
+ roots: [home('.kimi-code'), home('.kimi-work'), localAppData('kimi-code')],
17
+ },
18
+ {
19
+ id: 'kimi-desktop', name: 'Kimi Desktop', vendor: 'Moonshot AI', commands: [],
20
+ roots: [appData('kimi-desktop'), localAppData('kimi-desktop-updater')],
21
+ },
22
+ {
23
+ id: 'opencode', name: 'OpenCode', vendor: 'SST', commands: ['opencode'],
24
+ roots: [home('.opencode'), appData('opencode'), localAppData('opencode')],
25
+ },
26
+ {
27
+ id: 'qwen-code', name: 'Qwen Code', vendor: 'Alibaba Cloud', commands: ['qwen'],
28
+ roots: [envRoot('QWEN_RUNTIME_DIR'), envRoot('QWEN_HOME'), home('.qwen')],
29
+ },
30
+ {
31
+ id: 'mistral-vibe', name: 'Mistral Vibe', vendor: 'Mistral AI', commands: ['vibe'],
32
+ roots: [envRoot('VIBE_HOME'), home('.vibe')],
33
+ },
34
+ {
35
+ id: 'gemini-cli', name: 'Gemini CLI', vendor: 'Google', commands: ['gemini'],
36
+ roots: [envRoot('GEMINI_CLI_HOME', '.gemini'), home('.gemini')],
37
+ },
38
+ {
39
+ id: 'github-copilot-cli', name: 'GitHub Copilot CLI', vendor: 'GitHub', commands: ['copilot'],
40
+ roots: [home('.copilot')],
41
+ },
42
+ { id: 'aider', name: 'Aider', vendor: 'Aider-AI', commands: ['aider'], roots: [home('.aider.conf.yml')] },
43
+ { id: 'cursor', name: 'Cursor', vendor: 'Anysphere', commands: ['cursor'], roots: [appData('Cursor')] },
44
+ { id: 'windsurf', name: 'Windsurf', vendor: 'Cognition', commands: ['windsurf'], roots: [appData('Windsurf')] },
45
+ ];
46
+ function resolveRoot(candidate, context) {
47
+ let base;
48
+ if (candidate.base === 'home')
49
+ base = context.homeDir;
50
+ else if (candidate.base === 'appData')
51
+ base = context.env.APPDATA;
52
+ else if (candidate.base === 'localAppData')
53
+ base = context.env.LOCALAPPDATA;
54
+ else if (candidate.base === 'env')
55
+ base = context.env[candidate.variable];
56
+ if (!base)
57
+ return null;
58
+ return context.join(base, ...(candidate.parts ?? []));
59
+ }
60
+ function executableCandidates(command, env, platform, join) {
61
+ const separator = platform === 'win32' ? ';' : ':';
62
+ const pathEntries = (env.PATH ?? env.Path ?? '').split(separator).filter(Boolean);
63
+ const extensions = platform === 'win32'
64
+ ? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
65
+ : [''];
66
+ return pathEntries.flatMap((entry) => extensions.map((extension) => join(entry, `${command}${extension.toLowerCase()}`)));
67
+ }
68
+ export function discoverLocalAgentSources(options = {}) {
69
+ const env = options.env ?? process.env;
70
+ const platform = options.platform ?? process.platform;
71
+ const pathApi = platform === 'win32' ? win32 : posix;
72
+ const homeDir = options.homeDir ?? env.USERPROFILE ?? env.HOME ?? '';
73
+ const exists = options.exists ?? existsSync;
74
+ const join = pathApi.join;
75
+ return KNOWN_AGENT_SOURCES.map((source) => {
76
+ const evidence = new Set();
77
+ for (const root of source.roots) {
78
+ const resolved = resolveRoot(root, { homeDir, env, join });
79
+ if (resolved && exists(resolved))
80
+ evidence.add(resolved);
81
+ }
82
+ for (const command of source.commands) {
83
+ const executable = executableCandidates(command, env, platform, join).find(exists);
84
+ if (executable)
85
+ evidence.add(executable);
86
+ }
87
+ return { ...source, installed: evidence.size > 0, evidence: [...evidence] };
88
+ });
89
+ }
package/dist/cli/index.js CHANGED
@@ -6,6 +6,7 @@ import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
6
6
  import { join, dirname, resolve } from 'path';
7
7
  import { fileURLToPath } from 'url';
8
8
  import { readFileSync } from 'fs';
9
+ import { discoverLocalAgentSources } from '../agent/source-registry.js';
9
10
  const __filename = fileURLToPath(import.meta.url);
10
11
  const __dirname = dirname(__filename);
11
12
  // Shared store. HUMEMORY_DB points at another database — same convention as the
@@ -37,7 +38,7 @@ program
37
38
  .option('-l2, --level2 <essential>', 'Gist for consolidation level 2')
38
39
  .option('-l3, --level3 <keywords>', 'Keywords for fast level 3 retrieval')
39
40
  .option('-t, --type <type>', 'Memory type (episodic/semantic/procedural)', 'semantic')
40
- .option('--auto', 'Auto-generate levels 1-3 through the LLM (needs ANTHROPIC_API_KEY)')
41
+ .option('--auto', 'Auto-generate levels 1-3 locally (an injected LLM may enhance them)')
41
42
  .option('--photographic', 'Photographic mode — disable decay')
42
43
  .option('--agent <name>', 'Who is encoding (claude/codex/kimi/…)', 'cli')
43
44
  .action(async (content, options) => {
@@ -789,6 +790,24 @@ for (const verb of ['approve', 'reject']) {
789
790
  }
790
791
  });
791
792
  }
793
+ // === LOCAL AGENT SOURCES ===
794
+ const sources = program
795
+ .command('sources')
796
+ .description('Discover local AI agent runtimes without reading their sessions');
797
+ sources
798
+ .command('discover', { isDefault: true })
799
+ .description('Show known runtimes and the local evidence found for each one')
800
+ .option('--installed-only', 'Hide known runtimes that were not found')
801
+ .action((options) => {
802
+ const discovered = discoverLocalAgentSources()
803
+ .filter((source) => !options.installedOnly || source.installed);
804
+ console.log('\nLocal AI sources (discovery only — no session was read):\n');
805
+ for (const source of discovered) {
806
+ console.log(`${source.installed ? '✓' : '·'} ${source.name} — ${source.vendor}`);
807
+ for (const evidence of source.evidence)
808
+ console.log(` ${evidence}`);
809
+ }
810
+ });
792
811
  // Parse and run
793
812
  program.parse();
794
813
  // Cleanup
@@ -14,5 +14,6 @@ export interface LLMClient {
14
14
  }>;
15
15
  };
16
16
  }
17
- export declare function setLLMClient(client: LLMClient): void;
17
+ export declare function setLLMClient(client: LLMClient | null): void;
18
+ export declare function generateMemoryLevelsDeterministic(content: string): GeneratedLevels;
18
19
  export declare function generateMemoryLevels(content: string, memoryType?: MemoryType, client?: LLMClient): Promise<GeneratedLevels>;
@@ -1,39 +1,46 @@
1
- import Anthropic from '@anthropic-ai/sdk';
2
1
  const SYSTEM_PROMPT = `You are a memory consolidation system.
3
2
  For each trace, produce 3 decay levels as strict JSON.
4
3
  Write the levels in the same language as the trace itself.
5
4
  Answer with a JSON object ONLY — no markdown, no explanation.`;
6
5
  let _client = null;
7
- function getClient() {
8
- if (!_client) {
9
- _client = new Anthropic();
10
- }
11
- return _client;
12
- }
13
6
  export function setLLMClient(client) {
14
7
  _client = client;
15
8
  }
9
+ export function generateMemoryLevelsDeterministic(content) {
10
+ const compact = content.trim().replace(/\s+/g, ' ');
11
+ const keywords = [...new Set(compact.toLocaleLowerCase().match(/[\p{L}\p{N}_-]{3,}/gu) ?? [])]
12
+ .slice(0, 12)
13
+ .join(' ');
14
+ return {
15
+ level1Summary: compact.slice(0, 300),
16
+ level2Essential: compact.slice(0, 100),
17
+ level3Keywords: keywords || compact.split(/\s+/).slice(0, 10).join(' '),
18
+ };
19
+ }
16
20
  export async function generateMemoryLevels(content, memoryType = 'semantic', client) {
17
- const llm = client ?? getClient();
21
+ const llm = client ?? _client;
22
+ if (!llm)
23
+ return generateMemoryLevelsDeterministic(content);
18
24
  const typeHints = {
19
25
  episodic: 'a lived event, with its temporal and spatial context',
20
26
  semantic: 'a fact or a concept',
21
27
  procedural: 'know-how or a procedure',
22
28
  };
23
- const response = await llm.messages.create({
24
- model: 'claude-haiku-4-5-20251001',
25
- max_tokens: 512,
26
- system: [
27
- {
28
- type: 'text',
29
- text: SYSTEM_PROMPT,
30
- cache_control: { type: 'ephemeral' },
31
- },
32
- ],
33
- messages: [
34
- {
35
- role: 'user',
36
- content: `Memory type: ${typeHints[memoryType]}
29
+ try {
30
+ const response = await llm.messages.create({
31
+ model: process.env.HUMEMORY_LLM_MODEL ?? 'claude-haiku-4-5-20251001',
32
+ max_tokens: 512,
33
+ system: [
34
+ {
35
+ type: 'text',
36
+ text: SYSTEM_PROMPT,
37
+ cache_control: { type: 'ephemeral' },
38
+ },
39
+ ],
40
+ messages: [
41
+ {
42
+ role: 'user',
43
+ content: `Memory type: ${typeHints[memoryType]}
37
44
 
38
45
  Trace to consolidate:
39
46
  """
@@ -46,11 +53,10 @@ Produce exactly this JSON:
46
53
  "level2Essential": "<1 sentence, the irreducible information>",
47
54
  "level3Keywords": "<8-12 BM25 keywords separated by spaces>"
48
55
  }`,
49
- },
50
- ],
51
- });
52
- const text = response.content[0].type === 'text' ? (response.content[0].text ?? '') : '';
53
- try {
56
+ },
57
+ ],
58
+ });
59
+ const text = response.content[0].type === 'text' ? (response.content[0].text ?? '') : '';
54
60
  const parsed = JSON.parse(text.trim());
55
61
  if (!parsed.level1Summary || !parsed.level2Essential || !parsed.level3Keywords) {
56
62
  throw new Error('Missing fields in LLM response');
@@ -58,12 +64,7 @@ Produce exactly this JSON:
58
64
  return parsed;
59
65
  }
60
66
  catch {
61
- // Fallback: extract from content if JSON parse fails
62
- const words = content.split(/\s+/).slice(0, 10).join(' ');
63
- return {
64
- level1Summary: content.slice(0, 300),
65
- level2Essential: content.slice(0, 100),
66
- level3Keywords: words,
67
- };
67
+ // Invalid output, quota, timeout, or network loss: consolidation still proceeds locally.
68
+ return generateMemoryLevelsDeterministic(content);
68
69
  }
69
70
  }
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  export { SQLiteStore } from './store/sqlite.js';
8
8
  export { InverseSearchEngine } from './core/search.js';
9
9
  export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
10
- export { generateMemoryLevels, setLLMClient } from './core/llm-generator.js';
10
+ export { generateMemoryLevels, generateMemoryLevelsDeterministic, setLLMClient } from './core/llm-generator.js';
11
11
  export { systemClock, FakeClock } from './core/clock.js';
12
12
  export { InMemoryEventBus } from './core/event-bus.js';
13
13
  export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
@@ -15,7 +15,9 @@ 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 { extractLearnings } from './agent/learning-extractor.js';
18
+ export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
19
+ export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
20
+ export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
19
21
  export type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MergeResult, Intention, Cue, IntentionStatus, CueStatus, CueKind, TriggerSpec, TimeTriggerSpec, EventTriggerSpec, NewIntention, NewCue, IntentionStore } from './core/types.js';
20
22
  export type { StoreOptions } from './store/sqlite.js';
21
23
  export type { Clock } from './core/clock.js';
@@ -26,3 +28,5 @@ export type { GeneratedLevels, LLMClient } from './core/llm-generator.js';
26
28
  export type { ParsedSession, SessionMessage } from './agent/session-parser.js';
27
29
  export type { ExtractedLearning } from './agent/learning-extractor.js';
28
30
  export type { HookOptions, HookResult } from './agent/claude-hook.js';
31
+ export type { MaintenanceJob, EnqueueOptions, QueueResult, WorkerOptions, WorkerResult } from './agent/maintenance-queue.js';
32
+ export type { AgentSourceDefinition, AgentSourceId, DiscoveredAgentSource, DiscoveryOptions } from './agent/source-registry.js';
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  export { SQLiteStore } from './store/sqlite.js';
8
8
  export { InverseSearchEngine } from './core/search.js';
9
9
  export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
10
- export { generateMemoryLevels, setLLMClient } from './core/llm-generator.js';
10
+ export { generateMemoryLevels, generateMemoryLevelsDeterministic, setLLMClient } from './core/llm-generator.js';
11
11
  export { systemClock, FakeClock } from './core/clock.js';
12
12
  export { InMemoryEventBus } from './core/event-bus.js';
13
13
  export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
@@ -15,4 +15,6 @@ 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 { extractLearnings } from './agent/learning-extractor.js';
18
+ export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
19
+ export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
20
+ export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
package/docs/TESTING.md CHANGED
@@ -236,8 +236,9 @@ top and trusted.
236
236
 
237
237
  All suites are now hermetic in this sense (BUG-05 closed): `humemory.test.ts` runs
238
238
  on `freshStore()` with a frozen clock, `agent.test.ts` drives `processSession`
239
- against `':memory:'`, and `llm-generator.test.ts` never touched a database. No
240
- test writes a file, so nothing is left behind when one fails.
239
+ against `':memory:'`, and `llm-generator.test.ts` never touched a database.
240
+ Filesystem behavior such as the maintenance queue uses a unique temporary root
241
+ per test and removes it after each run; production data is never touched.
241
242
 
242
243
  Inline literals are still fine where the test *is about* that specific content —
243
244
  a photographic-mode test needs its own trace. Fixtures are for shared corpora and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
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",
@@ -16,6 +16,7 @@
16
16
  "scripts/hook-session.ts",
17
17
  "scripts/hook-session-start.ts",
18
18
  "scripts/hook-post-commit.ts",
19
+ "scripts/maintenance-worker.ts",
19
20
  "scripts/consolidate.js",
20
21
  "README.md",
21
22
  "AGENTS.md",
@@ -85,6 +86,7 @@
85
86
  "start:api": "bun run src/api/server.ts",
86
87
  "cli": "bun run src/cli/index.ts",
87
88
  "consolidate": "bun run scripts/consolidate.js",
89
+ "maintenance": "bun run scripts/maintenance-worker.ts",
88
90
  "dream": "bun run src/cli/index.ts dream",
89
91
  "mcp": "bun run src/mcp/server.ts",
90
92
  "build:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\" && bun build web/index.html --outdir public/app --production --splitting",
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * Claude Code Stop hook — reads the transcript from stdin and stores the learnings.
3
+ * Claude Code Stop hook — durably queues the transcript and exits without an LLM call.
4
4
  *
5
5
  * Usage dans Claude Code settings.json:
6
6
  * {
@@ -10,19 +10,19 @@
10
10
  * }
11
11
  *
12
12
  * Environment variables:
13
- * HUMEMORY_DB — database path (default: data/humemory.db, relative to this script)
13
+ * HUMEMORY_QUEUE — durable inbox (default: data/maintenance-queue)
14
14
  * HUMEMORY_DIR — project directory (default: cwd)
15
15
  * HUMEMORY_MAX — max learnings per session (default: 5)
16
16
  */
17
17
 
18
18
  import { join, dirname } from 'path';
19
19
  import { fileURLToPath } from 'url';
20
- import { processSession } from '../src/agent/claude-hook.js';
20
+ import { enqueueSession } from '../src/agent/maintenance-queue.js';
21
21
 
22
22
  const __filename = fileURLToPath(import.meta.url);
23
23
  const __dirname = dirname(__filename);
24
24
 
25
- const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
25
+ const QUEUE_DIR = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../data/maintenance-queue');
26
26
  const DIRECTORY = process.env.HUMEMORY_DIR ?? process.cwd();
27
27
  const MAX_LEARNINGS = parseInt(process.env.HUMEMORY_MAX ?? '5');
28
28
 
@@ -39,18 +39,19 @@ async function main() {
39
39
  }
40
40
 
41
41
  try {
42
- const result = await processSession(rawInput, {
43
- dbPath: DB_PATH,
42
+ const result = await enqueueSession(rawInput, {
43
+ queueDir: QUEUE_DIR,
44
44
  directory: DIRECTORY,
45
45
  maxLearnings: MAX_LEARNINGS,
46
- verbose: process.env.HUMEMORY_VERBOSE === '1',
46
+ source: 'claude-code',
47
+ agent: process.env.HUMEMORY_AGENT ?? 'claude',
47
48
  });
48
49
 
49
- if (result.memoriesStored > 0) {
50
- console.error(`[humemory] ${result.memoriesStored} learning(s) stored — session ${result.sessionId}`);
50
+ if (process.env.HUMEMORY_VERBOSE === '1') {
51
+ console.error(`[humemory] session ${result.created ? 'queued' : 'already queued'} — ${result.job.sessionId}`);
51
52
  }
52
53
  } catch (err) {
53
- // Never block Claude Code — log to stderr only
54
+ // Never block Claude Code — the raw transcript remains with the source on failure.
54
55
  console.error(`[humemory] hook error: ${err}`);
55
56
  }
56
57
 
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env bun
2
+ /** One non-blocking maintenance pass over sessions queued by local agent hooks. */
3
+
4
+ import Anthropic from '@anthropic-ai/sdk';
5
+ import { dirname, join } from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import type { LLMClient } from '../src/core/llm-generator.js';
8
+ import { processMaintenanceQueue } from '../src/agent/maintenance-queue.js';
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+ const queueDir = process.env.HUMEMORY_QUEUE ?? join(__dirname, '../data/maintenance-queue');
12
+ const dbPath = process.env.HUMEMORY_DB ?? join(__dirname, '../data/humemory.db');
13
+ const provider = process.env.HUMEMORY_MAINTENANCE_LLM ?? 'none';
14
+
15
+ let client: LLMClient | undefined;
16
+ if (provider === 'anthropic' && process.env.ANTHROPIC_API_KEY) {
17
+ client = new Anthropic() as unknown as LLMClient;
18
+ }
19
+
20
+ const result = await processMaintenanceQueue({
21
+ queueDir,
22
+ dbPath,
23
+ client,
24
+ llmTimeoutMs: Number(process.env.HUMEMORY_MAINTENANCE_TIMEOUT_MS ?? 8_000),
25
+ maxJobs: Number(process.env.HUMEMORY_MAINTENANCE_BATCH ?? 20),
26
+ });
27
+
28
+ if (result.busy) {
29
+ if (process.env.HUMEMORY_VERBOSE === '1') console.error('[humemory] maintenance: another worker is active');
30
+ } else if (process.env.HUMEMORY_VERBOSE === '1' || result.failed > 0) {
31
+ console.error(
32
+ `[humemory] maintenance: ${result.processed}/${result.discovered} jobs, ` +
33
+ `${result.memoriesStored} memories, ${result.failed} retained, ${result.deadLettered} dead-lettered`,
34
+ );
35
+ }
36
+
37
+ if (result.failed > 0) process.exitCode = 1;