humemory 0.2.11 → 0.2.13

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/dist/index.js CHANGED
@@ -14,6 +14,8 @@ export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron,
14
14
  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
+ export { adviseInShadow, sanitizeMemoryCandidate, salienceForBand, jsonlShadowReporter } from './agent/memory-advisor.js';
18
+ export { JevMemoryAdvisor, resolveConfiguredJevAdvisor } from './agent/jev-advisor.js';
17
19
  export { parseClaudeHookPayload } from './agent/session-parser.js';
18
20
  export { parseKimiSession } from './agent/kimi-session-parser.js';
19
21
  export { importKimiSessions, defaultKimiHome, KIMI_SOURCE } from './agent/kimi-import.js';
@@ -0,0 +1,9 @@
1
+ # Kimi experiment resolution
2
+
3
+ Resolved on 2026-09-20 before Jev implementation began.
4
+
5
+ - Outcome: accepted and integrated in commit `08bc703` (`feat(maintenance): guard Kimi subscription consolidation`).
6
+ - Owned files: the guarded Kimi client, its maintenance-runner seam, network-free tests, and the bounded historical/trial scripts named in that commit.
7
+ - Evidence: `bun test tests/kimi-llm-client.test.ts` — 7 passed, 0 failed; `pnpm build` passed; the full `pnpm test` suite passed before the commit.
8
+ - Isolation: `AGENTS.md`, `CLAUDE.md`, `README.md`, `docs/TESTING.md`, `JEV_INTEGRATION.md`, `SCENARIOS.md`, and `docs/architecture/` were deliberately excluded because they contain broader user work.
9
+ - Remaining debt: the historical and provider trial scripts stay explicit opt-in tools; their live provider paths are not part of the hermetic test suite. Kimi activation remains disabled unless the local maintenance configuration or environment explicitly selects it.
package/docs/TESTING.md CHANGED
@@ -24,11 +24,12 @@ LLM. Every run must be:
24
24
 
25
25
  ### 1. Isolated database — done
26
26
 
27
- Today `tests/humemory.test.ts` uses a temp file `test-humemory.db` with
28
- `beforeEach`/`afterEach` cleanup. Good enough but file-bound and serial.
27
+ `tests/humemory.test.ts` uses `freshStore()` with a frozen `FakeClock` and a
28
+ fresh `:memory:` database in `beforeEach`, closed in `afterEach`. Suites testing
29
+ cross-process persistence use isolated temporary files.
29
30
 
30
- **Target:** every suite gets its own `bun:sqlite` instance. `SQLiteStore`'s
31
- constructor already accepts a path → pass `':memory:'`.
31
+ Every suite gets its own `bun:sqlite` instance; pass `':memory:'` unless the
32
+ scenario specifically needs on-disk persistence.
32
33
 
33
34
  ```ts
34
35
  import { freshStore } from './helpers/store.js';
@@ -57,7 +58,8 @@ Threaded through `SQLiteStore` (`add`, `recall`, `updateDecay`) and
57
58
  took `now` as a parameter. Anything still calling `new Date()` in a hot path is a
58
59
  regression.
59
60
 
60
- Then decay tests assert the full curve without waiting:
61
+ Decay tests assert the automatic L0→L3 curve without waiting; L4 is covered
62
+ as an explicit merge state, because automatic aging currently stops at L3:
61
63
 
62
64
  ```ts
63
65
  const clock = new FakeClock(new Date('2026-01-01'));
@@ -68,9 +70,9 @@ await store.updateDecay();
68
70
  expect((await store.getById(m.id)).currentLevel).toBe(1); // L0→L1
69
71
  ```
70
72
 
71
- Remaining: `scripts/consolidate.js` and the CLI/API still stamp `day` with
72
- `new Date()` at the edges. Harmless for decay assertions, worth threading when the
73
- prospective hooks land (S5-03a/b).
73
+ `scripts/consolidate.js` and some CLI/API entry points still stamp `day` with
74
+ `new Date()` at the edges. Behavioral tests exercise the injected store clock;
75
+ SessionStart and the prospective resolver also accept an injected clock.
74
76
 
75
77
  ### 3. Mocked LLM — seam already exists
76
78
 
@@ -82,8 +84,14 @@ prospective hooks land (S5-03a/b).
82
84
  import { setLLMClient } from '../src/core/llm-generator.js';
83
85
 
84
86
  setLLMClient({
85
- async generate() {
86
- return { level1: 'fixed summary', level2: 'fixed gist', level3: 'k1 k2 k3' };
87
+ messages: {
88
+ async create() {
89
+ return { content: [{ type: 'text', text: JSON.stringify({
90
+ level1Summary: 'fixed summary',
91
+ level2Essential: 'fixed gist',
92
+ level3Keywords: 'keyword-one keyword-two keyword-three',
93
+ }) }] };
94
+ },
87
95
  },
88
96
  });
89
97
  ```
@@ -116,9 +124,10 @@ handler unsubscribing mid-broadcast cannot corrupt the iteration. `published()`
116
124
  `publishedOf(type)` expose the log for assertions without subscribing; `reset()`
117
125
  clears both handlers and log.
118
126
 
119
- `FileSystemEventBus` (fs.watch / chokidar + git hooks) is deliberately **not**
120
- implemented yet — there is nothing to feed until the `intentions`/`cues` tables and
121
- the resolver exist. It lands with Phase 5.2 (S5-02).
127
+ `FileSystemEventBus` (fs.watch / chokidar) is **not implemented**. The shipped
128
+ resolver accepts events through the injected bus or `POST /events`; callers must
129
+ supply file-open, branch-switch and error events. SessionStart additionally
130
+ resolves branch cues for scripts, not for intentions.
122
131
 
123
132
  ### 5. React components — same runner, no second stack
124
133
 
@@ -0,0 +1,230 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>humemory — Internal architecture and execution</title>
7
+ <style>
8
+ :root{--ink:#172b35;--muted:#52636d;--paper:#f4f6f8;--line:#d3dce1;--accent:#146b88;--dark:#132936;--code:#e9eff3;--warm:#fff1d8}*{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:24px}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.65 system-ui,-apple-system,Segoe UI,sans-serif}a{color:var(--accent);text-underline-offset:3px}button,input,select{font:inherit}button{cursor:pointer}architecture-component{display:grid;grid-template-columns:255px minmax(0,1fr);min-height:100vh}architecture-navigation-zone{display:block;background:var(--dark);color:#e3edf2;padding:26px 20px;position:sticky;top:0;height:100vh;overflow:auto}architecture-content-zone{display:block;min-width:0;padding:48px clamp(24px,5vw,76px) 90px;max-width:1550px}architecture-navigation-zone a{display:block;color:#cadce6;text-decoration:none;padding:9px 10px;border-radius:5px;font-size:14px;line-height:1.35}architecture-navigation-zone a:hover,architecture-navigation-zone a[aria-current="location"]{background:#254454;color:white}architecture-navigation-zone strong{display:block;font-size:21px;letter-spacing:.02em}architecture-navigation-zone p{font-size:12px;color:#9bb5c3;margin:5px 0 25px}h1{font-size:clamp(32px,4vw,52px);line-height:1.12;letter-spacing:-.035em;max-width:900px;margin:12px 0 20px}h2{font-size:29px;line-height:1.2;letter-spacing:-.02em;margin:0 0 22px}h3{font-size:20px;line-height:1.3;margin:28px 0 12px}h4{font-size:16px;margin:20px 0 8px}p{margin:12px 0;max-width:94ch}section{border-top:1px solid var(--line);padding:40px 0 12px;margin-top:38px}section:first-of-type{margin-top:30px}.eyebrow{font:12px/1.5 ui-monospace,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:var(--accent)}.lead{font-size:20px;line-height:1.55;max-width:80ch}.note{background:#e4eef3;border-left:4px solid var(--accent);padding:15px 19px;margin:20px 0}.warning{background:var(--warm);border-left:4px solid #b78028;padding:15px 19px;margin:20px 0}.small{font-size:13px;color:var(--muted)}code{font:13px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:var(--code);padding:2px 5px;border-radius:3px;overflow-wrap:anywhere}pre{background:var(--dark);color:#e2edf4;padding:20px;border-radius:6px;overflow:auto;font:13px/1.65 ui-monospace,Consolas,monospace;tab-size:2}pre code{background:none;color:inherit;padding:0;overflow-wrap:normal}table{width:100%;border-collapse:collapse;font-size:14px;line-height:1.55;background:white}th{text-align:left;background:#e5edf2;font-weight:650}th,td{padding:12px 14px;border:1px solid var(--line);vertical-align:top}td:first-child{min-width:135px}table-wrap-component{display:block;overflow:auto;margin:16px 0}process-map-component{display:block;background:white;border:1px solid var(--line);border-radius:8px;padding:24px;margin:24px 0}process-map-controls-zone{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:22px}process-map-controls-zone button{background:#eaf0f4;border:1px solid var(--line);border-radius:4px;padding:7px 12px;font-size:13px}process-map-controls-zone button[aria-pressed="true"]{background:var(--accent);color:white;border-color:var(--accent)}process-map-topology-zone{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px}process-map-topology-zone button{text-align:left;background:#f6f8fa;color:var(--ink);border:1px solid var(--line);border-radius:6px;padding:16px;min-height:132px;line-height:1.5}process-map-topology-zone button strong{display:block;font-size:16px}process-map-topology-zone button span{display:block;font-size:12px;color:var(--muted);margin-top:5px}process-map-topology-zone button[aria-pressed="true"]{border:2px solid var(--accent);padding:15px;background:#eaf5fa}process-map-topology-zone button[data-dimmed="true"]{opacity:.45}process-map-inspector-zone{display:block;border-top:1px solid var(--line);padding-top:18px;margin-top:22px}process-map-inspector-zone dl{display:grid;grid-template-columns:115px 1fr;gap:7px 20px;margin:16px 0}dt{font-weight:650}dd{margin:0}pipeline-component{display:block;border:1px solid var(--line);border-radius:6px;margin:20px 0;background:white}pipeline-component ol{list-style:none;margin:0;padding:0;counter-reset:steps}pipeline-component li{position:relative;padding:16px 20px 16px 63px;border-bottom:1px solid var(--line);counter-increment:steps}pipeline-component li:last-child{border:0}pipeline-component li:before{content:counter(steps);position:absolute;left:20px;top:18px;width:26px;height:26px;border-radius:50%;background:#dfebf1;color:var(--accent);text-align:center;line-height:26px;font-size:13px;font-weight:700}pipeline-component li strong{display:block}details{background:white;border:1px solid var(--line);border-radius:5px;margin:12px 0;padding:0 20px}summary{cursor:pointer;font-weight:650;padding:15px 0}details>p:last-child,details>table-wrap-component:last-child,details>pre:last-child{margin-bottom:20px}.flow{font:14px/1.8 ui-monospace,Consolas,monospace;white-space:pre-wrap;background:#e7eef3;padding:20px;border-radius:6px;overflow-wrap:anywhere}.tag{display:inline-block;font:12px/1.4 ui-monospace,Consolas,monospace;color:var(--accent);border:1px solid #9cc0cf;border-radius:3px;padding:3px 6px;margin:3px 5px 3px 0}ul,ol{padding-left:23px}li{margin:7px 0}.sources{font-size:13px;color:var(--muted);margin-top:19px}.sources a{margin-right:12px}footer{margin-top:45px;border-top:1px solid var(--line);padding-top:20px;color:var(--muted);font-size:13px}noscript p{padding:12px;background:var(--warm)}@media(max-width:1000px){architecture-component{grid-template-columns:205px minmax(0,1fr)}architecture-content-zone{padding:32px 24px}process-map-topology-zone{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:700px){architecture-component{display:block}architecture-navigation-zone{position:relative;height:auto;padding:18px}architecture-navigation-zone nav{display:flex;gap:5px;flex-wrap:wrap}architecture-navigation-zone a{padding:6px 8px;font-size:12px}architecture-navigation-zone p{margin-bottom:12px}architecture-content-zone{padding:28px 18px 60px}process-map-component{padding:15px}process-map-topology-zone{grid-template-columns:1fr}process-map-inspector-zone dl{grid-template-columns:1fr;gap:3px}dd{margin-bottom:9px}h2{font-size:25px}th,td{padding:10px}section{padding-top:28px}}
9
+ </style>
10
+ </head>
11
+ <body>
12
+ <architecture-component>
13
+ <architecture-navigation-zone>
14
+ <strong>humemory</strong><p>Developer reference · v0.2.10<br>Source-aligned · 12 September 2026</p>
15
+ <nav aria-label="Architecture chapters">
16
+ <a href="#overview">01 · Execution map</a><a href="#installation">02 · Installation and processes</a><a href="#configuration">03 · Configuration and models</a><a href="#storage">04 · Files and database</a><a href="#encoding">05 · Session ingestion</a><a href="#retrieval">06 · Search and recall</a><a href="#decay">07 · Derived levels and decay</a><a href="#prospective">08 · Intentions, cues and scripts</a><a href="#dreamer">09 · Dreamer: start to finish</a><a href="#trust">10 · Trust and corrections</a><a href="#operations">11 · Commands and failure handling</a><a href="#source-map">12 · Source reference</a>
17
+ </nav>
18
+ </architecture-navigation-zone>
19
+ <architecture-content-zone>
20
+ <header><div class="eyebrow">Internal architecture / actual execution paths</div><h1>What runs, what it reads,<br>and what it writes.</h1><p class="lead">A technical description of humemory: entry points, process lifetimes, configuration, SQLite tables, ingestion, retrieval, scheduled cues, decay and cross-session proposals.</p><p>The numbered chapters below describe runtime operations. “Phase 5”, “Phase 6”, “Phase 7” and “Phase 8” in the project plans are development milestones; they are not stages that every request executes.</p><div class="note"><strong>Three separate mechanisms.</strong> SQLite stores the data. FlexSearch provides lexical retrieval in each process. Optional ONNX embeddings provide a second retrieval and clustering path. A generative LLM is optional for session extraction; it is not involved in ordinary search.</div></header>
21
+
22
+ <section id="overview"><div class="eyebrow">01 / Topology</div><h2>Execution map</h2><p>The client starts hooks or an MCP process. The CLI and HTTP API open the same database through <code>SQLiteStore</code>. A maintenance pass consumes the disk queue. Decay and the dreamer are separate operations.</p>
23
+ <div class="flow">AI client ── Stop hook ──► queue files ── maintenance pass ──► SQLite
24
+ AI client ◄─ SessionStart hook ◄── cues + intentions + scripts + memories
25
+ AI client ◄─► MCP stdio process ◄─► SQLiteStore
26
+ Browser ◄─► HTTP API (:3456) ◄─► SQLiteStore
27
+ Developer ──► CLI ──► search / encode / decay / dream / scripts / intentions
28
+
29
+ SQLiteStore ──► FlexSearch index in process memory
30
+ SQLiteStore ──► memory_embeddings in the same SQLite file
31
+ Semantic CLI / vector dreamer ──► local ONNX model + cosine calculations</div>
32
+ <process-map-component>
33
+ <process-map-controls-zone aria-label="Highlight an execution path"><button type="button" data-path="all" aria-pressed="true">All components</button><button type="button" data-path="ingest" aria-pressed="false">Session → database</button><button type="button" data-path="context" aria-pressed="false">Session context</button><button type="button" data-path="search" aria-pressed="false">Retrieval</button><button type="button" data-path="dream" aria-pressed="false">Dreamer</button></process-map-controls-zone>
34
+ <process-map-topology-zone aria-label="Select a component for implementation details">
35
+ <button type="button" data-node="hooks" aria-pressed="true"><strong>Client hooks</strong><span>Short-lived Bun processes<br>Queue a transcript or render context</span></button>
36
+ <button type="button" data-node="queue" aria-pressed="false"><strong>Maintenance queue</strong><span>JSON jobs and checkpoints on disk<br>Claim → extract → write → finish</span></button>
37
+ <button type="button" data-node="worker" aria-pressed="false"><strong>Maintenance runner</strong><span>One pass, or API interval loop<br>Deterministic / Anthropic / Codex</span></button>
38
+ <button type="button" data-node="api" aria-pressed="false"><strong>HTTP API + dashboard</strong><span>Resident Hono process<br>Also owns the optional maintenance timer</span></button>
39
+ <button type="button" data-node="mcp" aria-pressed="false"><strong>MCP server</strong><span>One stdio process per client<br>Six tools, shared database</span></button>
40
+ <button type="button" data-node="cli" aria-pressed="false"><strong>CLI</strong><span>Commander entry point<br>Runs an operation and exits</span></button>
41
+ <button type="button" data-node="store" aria-pressed="false"><strong>SQLiteStore</strong><span>Relational data + embedding BLOBs<br>WAL, write queue, advisory lock</span></button>
42
+ <button type="button" data-node="retrieval" aria-pressed="false"><strong>Retrieval engines</strong><span>FlexSearch / optional hybrid RRF<br>No generative model</span></button>
43
+ <button type="button" data-node="dream" aria-pressed="false"><strong>Dreamer</strong><span>Explicit batch operation<br>Clusters → proposals → review</span></button>
44
+ </process-map-topology-zone>
45
+ <process-map-inspector-zone aria-live="polite"><h3 id="inspector-title">Client hooks</h3><dl id="inspector-details"><dt>Program</dt><dd><a href="../../scripts/hook-session.ts">hook-session.ts</a> and <a href="../../scripts/hook-session-start.ts">hook-session-start.ts</a></dd><dt>Lifetime</dt><dd>Started by the AI client at Stop or SessionStart; exits after enqueueing or rendering.</dd><dt>Reads</dt><dd>Stop: the session transcript. Start: SQLite, current working directory and Git branch.</dd><dt>Writes</dt><dd>Stop: a durable JSON job. Start: cue firing state and a Markdown context block on stdout.</dd><dt>Model</dt><dd>None inside these hooks. Extraction occurs later in maintenance.</dd></dl></process-map-inspector-zone>
46
+ <noscript><p>The map inspector needs JavaScript. All operational explanations and source references below remain available.</p></noscript>
47
+ </process-map-component>
48
+ <p class="sources">Implementation: <a href="../../src/cli/index.ts">CLI</a><a href="../../src/api/server.ts">API</a><a href="../../src/mcp/server.ts">MCP</a><a href="../../src/agent/maintenance-runner.ts">maintenance runner</a></p></section>
49
+
50
+ <section id="installation"><div class="eyebrow">02 / Deployment</div><h2>Installation and process lifetimes</h2><h3>Working from this checkout</h3><p>The backend requires Bun ≥ 1.3.14 because the store imports <code>bun:sqlite</code>. The package uses pnpm 10.33.2. The build compiles TypeScript into <code>dist/</code>, type-checks the React frontend and bundles it into <code>public/app/</code>.</p><pre><code>pnpm install
51
+ pnpm build
52
+ pnpm cli doctor
53
+ pnpm start:api
54
+ # Open http://127.0.0.1:3456/app</code></pre><p><code>pnpm cli …</code> runs <code>src/cli/index.ts</code> with Bun. The installed <code>humemory</code> executable runs <code>bin/humemory.js</code>, which imports <code>dist/cli/index.js</code>. Auxiliary hook, API and maintenance scripts are separate entry points. The first store construction creates the database directory, tables and schema migrations.</p>
55
+ <table-wrap-component><table><thead><tr><th>Process</th><th>Start</th><th>Lifetime and work</th></tr></thead><tbody>
56
+ <tr><td>CLI</td><td><code>pnpm cli &lt;command&gt;</code></td><td>One invocation. Opens a store when required, executes the command and exits.</td></tr>
57
+ <tr><td>HTTP API</td><td><code>pnpm start:api</code></td><td>Resident. Serves HTTP and built dashboard assets; starts a maintenance interval unless disabled.</td></tr>
58
+ <tr><td>MCP</td><td><code>pnpm mcp</code></td><td>Resident for the client's stdio connection. Each client can launch its own process, with its own agent identity and in-memory search index.</td></tr>
59
+ <tr><td>Maintenance worker</td><td><code>pnpm maintenance</code></td><td>One import-and-drain pass. It does not become a daemon.</td></tr>
60
+ <tr><td>Decay pass</td><td><code>pnpm consolidate</code></td><td>One pass through <code>scripts/consolidate.js</code>. Requires an external scheduler for recurrence.</td></tr>
61
+ <tr><td>Dreamer</td><td><code>pnpm cli dream run</code></td><td>One proposal-generation pass. No built-in recurring dream timer.</td></tr>
62
+ <tr><td>Hooks</td><td>Client or Git event</td><td>Stop queues input; SessionStart renders context; post-commit checks explicit loop-closing markers.</td></tr>
63
+ </tbody></table></table-wrap-component>
64
+ <h3>Windows startup and watchdog</h3><pre><code>pnpm win:install
65
+ # Equivalent:
66
+ pwsh -File scripts/windows/install.ps1 -WatchdogMinutes 5
67
+
68
+ # Remove the startup registration and scheduled task:
69
+ pwsh -File scripts/windows/install.ps1 -Uninstall</code></pre><pipeline-component><ol><li><strong>Installer creates a Startup shim.</strong>A generated <code>humemory-api.vbs</code> in the Windows Startup folder delegates to this checkout's <code>scripts/windows/humemory-api.vbs</code>.</li><li><strong>Installer registers a scheduled task.</strong><code>humemory-watchdog</code> runs <code>humemory-watchdog.vbs</code> every five minutes by default. Installing creates the registrations; the launcher runs at login or through a subsequent watchdog check.</li><li><strong>Launcher starts Bun in the background.</strong>The VBS launcher uses the checkout as its working directory and runs <code>bun run src/api/server.ts</code> hidden. It tries the WinGet Bun link, then <code>bun.exe</code> on PATH.</li><li><strong>Watchdog probes HTTP health.</strong>A 200 response from <code>http://127.0.0.1:&lt;port&gt;/health</code> counts as alive. Failure starts another launcher invocation. It does not terminate an old hung process.</li></ol></pipeline-component><p>These are a Startup script and a Windows scheduled task. There is no Windows Service Control Manager service. The registration references the checkout by absolute path; moving it requires reinstalling the registration. Uninstalling leaves stored data and any already-running API process in place.</p><div class="warning"><strong>Two port variables in the Windows path.</strong> The API reads <code>PORT</code>. The watchdog reads <code>HUMEMORY_PORT</code>. Set both consistently when changing the port. Windows launcher logs are under <code>&lt;checkout&gt;/data/logs/</code>, even when the database uses an OS data directory.</div>
70
+ <h3>Client registration and attribution</h3><p>The project ships <code>.mcp.json</code> for Claude Code. <code>pnpm cli sources setup</code> merges server registration into detected supported client configurations. Give every client its own <code>HUMEMORY_AGENT</code>, for example <code>claude</code>, <code>codex</code>, <code>kimi</code> or <code>opencode</code>. Separate MCP processes share one store when they resolve the same database path.</p><p>The Claude Stop and SessionStart scripts must also be registered in the client's hook configuration. A Git post-commit hook must be installed in each project that should close loops; that hook uses <code>HUMEMORY_HOME</code> to find the humemory checkout. MCP registration does not itself create a transcript hook.</p><p class="sources">Source: <a href="../../package.json">package scripts</a><a href="../../bin/humemory.js">installed CLI wrapper</a><a href="../../scripts/windows/install.ps1">Windows installer</a><a href="../../scripts/windows/humemory-api.vbs">launcher</a><a href="../../scripts/windows/humemory-watchdog.vbs">watchdog</a><a href="../../src/agent/mcp-client-setup.ts">client registration</a></p></section>
71
+
72
+ <section id="configuration"><div class="eyebrow">03 / Parameters</div><h2>Configuration and model selection</h2><p>There is no central <code>humemory.json</code> model router. Runtime settings come from environment variables, command options and constructor arguments. Client MCP and hook configuration tells the client which humemory program to launch. Algorithm constants live in TypeScript configuration objects.</p><p>Set environment variables in the process that launches the API, worker or MCP server. Values set in one terminal do not change an already-running process. API settings such as port and maintenance interval take effect at startup.</p>
73
+ <table-wrap-component><table><thead><tr><th>Variable</th><th>Default</th><th>Scope / effect</th></tr></thead><tbody>
74
+ <tr><td><code>HUMEMORY_DATA_DIR</code></td><td>Resolved OS data directory, with legacy checkout fallback</td><td>Base directory for database, queue and model cache when individual paths are not overridden.</td></tr>
75
+ <tr><td><code>HUMEMORY_DB</code></td><td><code>&lt;dataDir&gt;/humemory.db</code></td><td>SQLite file used by store entry points. The same absolute path means the same store.</td></tr>
76
+ <tr><td><code>HUMEMORY_QUEUE</code></td><td><code>&lt;dataDir&gt;/maintenance-queue</code></td><td>Stop hook and maintenance inbox. Health state is next to this queue directory.</td></tr>
77
+ <tr><td><code>HUMEMORY_MODEL_CACHE</code></td><td><code>&lt;dataDir&gt;/models</code></td><td>ONNX / tokenizer cache.</td></tr>
78
+ <tr><td><code>PORT</code></td><td><code>3456</code></td><td>HTTP API listener port.</td></tr>
79
+ <tr><td><code>HUMEMORY_HOST</code></td><td><code>127.0.0.1</code></td><td>Listener address. A non-loopback bind requires an API token.</td></tr>
80
+ <tr><td><code>HUMEMORY_API_TOKEN</code></td><td>Unset</td><td>Bearer authentication for data routes when configured. Health and static assets remain public.</td></tr>
81
+ <tr><td><code>CORS_ORIGINS</code></td><td>Production: <code>http://localhost:3456</code></td><td>Comma-separated allowed origins. Development accepts local browser origins.</td></tr>
82
+ <tr><td><code>HUMEMORY_AGENT</code></td><td>MCP: <code>unknown</code> if omitted</td><td>Process attribution. Set a distinct value per client.</td></tr>
83
+ <tr><td><code>HUMEMORY_DEVICE</code></td><td>Hostname</td><td>Stored provenance; it does not enable device synchronization.</td></tr>
84
+ <tr><td><code>HUMEMORY_MAINTENANCE_INTERVAL_MS</code></td><td><code>900000</code> (15 minutes)</td><td>API maintenance timer. <code>0</code> disables it. First pass is after the interval, not immediately at startup.</td></tr>
85
+ <tr><td><code>HUMEMORY_MAINTENANCE_BATCH</code></td><td><code>20</code></td><td>Maximum queue jobs handled in one maintenance pass.</td></tr>
86
+ <tr><td><code>HUMEMORY_MAINTENANCE_LLM</code></td><td><code>none</code></td><td>Optional extraction provider: <code>anthropic</code> or <code>codex</code>; other values leave deterministic extraction.</td></tr>
87
+ <tr><td><code>ANTHROPIC_API_KEY</code></td><td>Unset</td><td>Required to construct the Anthropic extraction client. Never needed for deterministic maintenance.</td></tr>
88
+ <tr><td><code>HUMEMORY_MAINTENANCE_TIMEOUT_MS</code></td><td><code>8000</code></td><td>Optional extraction deadline; also passed to the maintenance Codex adapter. On failure, deterministic extraction is retained.</td></tr>
89
+ <tr><td><code>HUMEMORY_MAINTENANCE_CODEX_DAYS</code></td><td><code>1</code></td><td>Codex discovery window in the standalone worker. The API runner defaults independently to one day through its options.</td></tr>
90
+ <tr><td><code>HUMEMORY_LLM_MODEL</code></td><td>See model table below</td><td>Codex subprocess model and optional library level generator. Does not override the Anthropic extraction model.</td></tr>
91
+ <tr><td><code>HUMEMORY_SESSION_BUDGET</code></td><td>10 items per section</td><td>SessionStart context budget; separate from maintenance batch size and model token limits.</td></tr>
92
+ <tr><td><code>HUMEMORY_HOME</code></td><td>Hook installation dependent</td><td>Location of humemory code for a post-commit hook installed in another project.</td></tr>
93
+ </tbody></table></table-wrap-component>
94
+ <h3>Which model performs which operation?</h3><table-wrap-component><table><thead><tr><th>Operation</th><th>Actual implementation</th><th>Selection and limits</th></tr></thead><tbody>
95
+ <tr><td>Default session extraction</td><td><code>extractLearningsDeterministic()</code></td><td>No model or network. Rule-based extraction of session learnings; default maximum five learnings per processed job.</td></tr>
96
+ <tr><td>Anthropic session extraction</td><td><code>learning-extractor.ts</code>, <code>client.messages.create()</code></td><td>Hardcoded <code>claude-haiku-4-5-20251001</code>, output <code>max_tokens: 1024</code>, final 3,000 characters of assembled session text. Timeout, provider failure or invalid output falls back to deterministic extraction.</td></tr>
97
+ <tr><td>Codex session extraction</td><td><code>createCodexClient()</code> adapts a CLI subprocess to the same messages interface</td><td><code>HUMEMORY_LLM_MODEL</code> becomes <code>codex exec -m …</code>; otherwise Codex selects its default model. Requires the installed, authenticated CLI.</td></tr>
98
+ <tr><td>L1/L2/L3 generation</td><td><code>generateMemoryLevels()</code></td><td>Deterministic by default. An injected library <code>LLMClient</code> uses <code>HUMEMORY_LLM_MODEL</code> or the Haiku default, <code>max_tokens: 512</code>. Maintenance provider selection does not globally inject this client.</td></tr>
99
+ <tr><td>Lexical search / session context</td><td>FlexSearch / database reads / cue resolver</td><td>No model. Fetching context does not launch a generative consultation phase.</td></tr>
100
+ <tr><td>Semantic search / vector clustering</td><td><code>OnnxEmbedder</code>, Transformers feature extraction</td><td>Default <code>Xenova/bge-m3@q8</code>, 1,024 dimensions. Embeddings run locally after model files are cached; initial model download needs network access.</td></tr>
101
+ <tr><td>Dream proposal drafting</td><td>Deterministic proposal construction; optional <code>runDreamer({ draft })</code> callback</td><td>CLI and HTTP do not wire a generative drafting client. The library extension exists, capped at ten drafts per run.</td></tr>
102
+ </tbody></table></table-wrap-component>
103
+ <details><summary>Codex adapter: exact subprocess boundary</summary><p>The adapter runs <code>codex exec</code> with <code>--ephemeral --ignore-user-config --ignore-rules --skip-git-repo-check -s read-only</code>, low reasoning effort, low verbosity and <code>--color never</code>. It sends the prompt on stdin and reads the final answer through <code>-o &lt;temporary-file&gt;</code>. The temporary <code>humemory-codex-*</code> directory is removed in <code>finally</code>; a timeout kills the child process. This is an extraction subprocess, not the client's normal coding session.</p></details>
104
+ <h3>Example: explicit local paths and optional extraction</h3><pre><code># PowerShell, before starting the process:
105
+ $env:HUMEMORY_DATA_DIR = 'D:\humemory-data'
106
+ $env:HUMEMORY_AGENT = 'codex'
107
+ $env:HUMEMORY_MAINTENANCE_LLM = 'codex'
108
+ $env:HUMEMORY_MAINTENANCE_TIMEOUT_MS = '60000'
109
+ pnpm maintenance
110
+
111
+ # Network-free extraction:
112
+ $env:HUMEMORY_MAINTENANCE_LLM = 'none'
113
+ pnpm maintenance</code></pre><p class="sources">Source: <a href="../../src/core/paths.ts">path resolver</a><a href="../../src/agent/maintenance-runner.ts">runtime maintenance settings</a><a href="../../src/agent/learning-extractor.ts">extraction request</a><a href="../../src/core/llm-generator.ts">level generator</a><a href="../../src/core/llm-cli-client.ts">Codex adapter</a><a href="../../src/core/embeddings.ts">ONNX embedder</a></p></section>
114
+
115
+ <section id="storage"><div class="eyebrow">04 / Persistence</div><h2>Files, paths and database responsibilities</h2><p><code>src/core/paths.ts</code> resolves the installation root separately from the data root. Path priority is explicit override, then default resolution. With no <code>HUMEMORY_DATA_DIR</code>, an existing <code>&lt;installationRoot&gt;/data/humemory.db</code> preserves the legacy checkout location.</p><table-wrap-component><table><thead><tr><th>Location</th><th>Default / purpose</th></tr></thead><tbody><tr><td>Windows data root</td><td><code>%LOCALAPPDATA%\humemory</code>, with a user AppData/Local fallback.</td></tr><tr><td>macOS data root</td><td><code>~/Library/Application Support/humemory</code></td></tr><tr><td>Linux data root</td><td><code>$XDG_DATA_HOME/humemory</code>, otherwise <code>~/.local/share/humemory</code></td></tr><tr><td><code>humemory.db</code></td><td>All relational entities and embedding BLOBs. WAL operation also creates SQLite <code>-wal</code> and <code>-shm</code> sidecars.</td></tr><tr><td><code>humemory.db.lock</code></td><td>Cross-process advisory write coordination; separate from SQLite's main data file.</td></tr><tr><td><code>maintenance-queue/&lt;id&gt;.json</code></td><td>Pending raw session job; source and session identity determine its hash.</td></tr><tr><td><code>&lt;id&gt;.json.processing</code></td><td>Claimed job. The worker recovers abandoned claims after acquiring exclusive worker ownership.</td></tr><tr><td><code>&lt;id&gt;.dead.json</code></td><td>Exhausted job retaining its raw transcript for review and requeue.</td></tr><tr><td><code>maintenance-queue/checkpoints/&lt;id&gt;.json</code></td><td>Processed message count for incremental session extraction.</td></tr><tr><td><code>maintenance-queue/.worker-lock</code></td><td>OS-backed advisory ownership lock for queue draining; no wall-clock expiry that could steal a slow live worker's job.</td></tr><tr><td><code>maintenance-state.json</code></td><td>Health record next to the queue directory: last run, success, duration, errors and result counts. Independent of SQLite.</td></tr><tr><td><code>models/</code></td><td>Downloaded ONNX model and tokenizer assets; not session content.</td></tr><tr><td><code>&lt;checkout&gt;/data/logs/api.log</code><br><code>watchdog.log</code></td><td>Windows VBS launcher logs. These paths are fixed by the launcher, not by the core data resolver.</td></tr><tr><td><code>dist/</code></td><td>Compiled TypeScript backend used by the packaged CLI wrapper.</td></tr><tr><td><code>web/ → public/app/</code></td><td>React sources → built dashboard assets served by the HTTP API.</td></tr></tbody></table></table-wrap-component>
116
+ <h3>The SQLite schema</h3><table-wrap-component><table><thead><tr><th>Table</th><th>Contents</th><th>Who uses it</th></tr></thead><tbody>
117
+ <tr><td><code>memories</code></td><td>Original <code>content</code>; optional L1 summary, L2 essential text, L3 keywords; <code>current_level</code>; project directory, session, type, creation/recall timestamps, saillance, photographic flag, merge link and provenance.</td><td>Encoding, search, decay, context injection, trust and dreamer.</td></tr>
118
+ <tr><td><code>intentions</code></td><td>Future task, status, expiry, fired/closed state, linked memory and provenance.</td><td>Cue resolution, SessionStart, explicit loop closure and stale-loop proposals.</td></tr>
119
+ <tr><td><code>cues</code></td><td><code>target_kind</code>/<code>target_id</code> points to an intention or script; typed trigger specification and armed/fired/cancelled state.</td><td>Time and event resolver. One target can have multiple cues.</td></tr>
120
+ <tr><td><code>scripts</code></td><td>Name, description, ordered steps, version, draft/active/archived status, saillance, pinning, fire count, last firing and provenance.</td><td>Script authoring, cue-driven context injection, disuse and correction handling.</td></tr>
121
+ <tr><td><code>contradictions</code></td><td>Winner memory, loser memory or script, rationale and revocation state.</td><td>Trust ranking, context exclusion, script archival and dreamer correction mining.</td></tr>
122
+ <tr><td><code>level_revisions</code></td><td>Snapshots of derived levels before merge overwrites; retained to five revisions per memory.</td><td>Merge and unmerge.</td></tr>
123
+ <tr><td><code>dream_proposals</code></td><td>Kind, member IDs, payload, confidence, payload hash, expiry and review status.</td><td>Dream generation, deduplication, review, approval and rejection.</td></tr>
124
+ <tr><td><code>memory_embeddings</code></td><td><code>memory_id</code> primary key, <code>model_id</code>, Float32 vector BLOB and embedding timestamp.</td><td>Semantic search and vector clustering. One stored embedding per memory; backfilling another model replaces its previous vector.</td></tr>
125
+ </tbody></table></table-wrap-component>
126
+ <div class="note"><strong>SQLite and vectors are not alternative storage levels.</strong> This implementation uses one SQLite database. Vectors are rows in <code>memory_embeddings</code>. Similarity is calculated in JavaScript over stored vectors; there is no separate vector database or ANN service.</div>
127
+ <h3>Store initialization and concurrency</h3><pipeline-component><ol><li><strong>Open and initialize.</strong><code>new SQLiteStore(path)</code> creates the directory, opens Bun SQLite, sets WAL, a 5-second busy timeout, <code>synchronous=NORMAL</code>, foreign keys and a 16 MB cache budget.</li><li><strong>Apply schema changes.</strong><code>initSchema()</code> creates or migrates tables. Some script-era changes rebuild a table by creating a replacement, copying data, dropping and renaming.</li><li><strong>Build the local search index.</strong><code>loadIntoMemory()</code> loads the memory corpus into a Map and FlexSearch. Each process has its own copy. Search checks SQLite <code>PRAGMA data_version</code> and reloads after another connection changes the database.</li><li><strong>Serialize writes.</strong>An in-process promise queue and cross-process advisory lock protect store writes. WAL supports concurrent readers; coordination does not turn multi-operation workflows into a single transaction.</li></ol></pipeline-component><p>Opening many short-lived stores rebuilds the full lexical index repeatedly. Semantic similarity also scans vectors in process memory. Those are concrete corpus-size costs to account for; the scale benchmark is <code>scripts/bench-scale.ts</code>.</p><p class="sources">Source: <a href="../../src/store/sqlite.ts">schema and store</a><a href="../../src/core/paths.ts">paths</a><a href="../../src/agent/maintenance-queue.ts">queue files</a><a href="../../src/agent/maintenance-state.ts">health state</a><a href="../../scripts/bench-scale.ts">scale benchmark</a></p></section>
128
+
129
+ <section id="encoding"><div class="eyebrow">05 / Input pipeline</div><h2>Session → queue → extracted memories</h2><p>Stop-hook work is deliberately short. It queues a raw session; extraction is performed later. Codex, Kimi and OpenCode imports feed the same durable queue from their supported local session formats.</p><pipeline-component><ol>
130
+ <li><strong>Capture or discover input.</strong><code>scripts/hook-session.ts</code> receives the Claude Stop event and enqueues the session. A maintenance pass also discovers recent Codex/Kimi/OpenCode sessions unless the corresponding import is skipped.</li>
131
+ <li><strong>Deduplicate the queue slot.</strong><code>enqueueMaintenanceSession()</code> hashes source + session ID. A newer transcript for the same session updates its pending slot. Raw transcript data stays in the queue file until successful processing or dead-letter handling.</li>
132
+ <li><strong>Acquire queue ownership and claim a job.</strong><code>drainMaintenanceQueue()</code> takes <code>.worker-lock</code>, recovers abandoned processing files and claims a pending file by rename. A pass handles at most the configured batch.</li>
133
+ <li><strong>Parse and scope the session.</strong><code>processSession()</code> uses the stored checkpoint's <code>messagesSeen</code>. Parser/import modules normalize each client's transcript; extraction focuses on messages not already covered by the checkpoint.</li>
134
+ <li><strong>Prepare a deterministic result, then optionally use a provider.</strong>The worker computes rule-based learnings first. If a configured client exists, it attempts LLM extraction under the deadline. The default per-job learning limit is five.</li>
135
+ <li><strong>Write each extracted learning.</strong><code>SQLiteStore.add()</code> receives content, keywords, L3 keywords, memory type, directory, session ID, occurrence time, source and agent. The worker does <em>not</em> pass <code>autoGenerate</code>; it does not automatically generate L1 and L2.</li>
136
+ <li><strong>Checkpoint and finish.</strong>After successful job processing, the queue stores the processed message count and removes the completed claim. The opened store is closed. On failure, retry classification decides whether to retain, retry or park the job.</li>
137
+ <li><strong>Record pass health.</strong><code>runMaintenancePass()</code> persists summary counts and duration in <code>maintenance-state.json</code>, then returns. A standalone process ends; the API loop waits for its next interval.</li>
138
+ </ol></pipeline-component><div class="warning"><strong>What this pass does not do.</strong> Ingestion does not run decay, vector backfill or the dreamer. New rows start at L0, including backdated imported rows; a later decay pass recomputes their age-based state. Checkpoint storage and individual memory writes are separate operations, so this pipeline should not be described as an exactly-once transaction.</div>
139
+ <h3>Two ways to run the same maintenance operation</h3><pre><code>pnpm maintenance
140
+ pnpm cli maintenance run --skip-imports
141
+ pnpm cli maintenance run --skip-codex --skip-kimi --skip-opencode
142
+ pnpm cli maintenance status</code></pre><p>The API interval prevents overlapping passes within that loop. Queue ownership also prevents two drainers from consuming the same job simultaneously. Import discovery defaults to the last day; it is not an unrestricted replay of every historical session.</p><p class="sources">Source: <a href="../../scripts/hook-session.ts">Stop hook</a><a href="../../scripts/maintenance-worker.ts">standalone worker</a><a href="../../src/agent/maintenance-runner.ts">pass and interval</a><a href="../../src/agent/claude-hook.ts">processSession</a><a href="../../src/agent/learning-extractor.ts">learning extraction</a><a href="../../src/agent/maintenance-queue.ts">queue protocol</a></p></section>
143
+
144
+ <section id="retrieval"><div class="eyebrow">06 / Query paths</div><h2>Lexical search, semantic search and explicit recall</h2><h3>Ordinary search: no LLM</h3><pipeline-component><ol><li><strong>Receive a query.</strong>CLI <code>search</code>, HTTP <code>GET /search?q=…</code> and MCP <code>humemory_search</code> call the lexical store search path.</li><li><strong>Refresh the index if needed.</strong>The store checks for writes from another SQLite connection before using its process-local FlexSearch index.</li><li><strong>Search fields in order.</strong><code>InverseSearchEngine</code> tries L3 keywords → L2 essential text → L1 summary → original content. <code>maxLevel</code> limits indexed fields, not the memory's current age state.</li><li><strong>Rank candidates.</strong>Strict matching requires query terms within one indexed field. When no strict result exists anywhere, a partial-match pass produces lower-scored candidates. Ranking uses field depth, recalls, saillance, recency, trust and query filters.</li><li><strong>Return results.</strong>Search does not call <code>recall()</code> and does not regenerate text. Original content remains searchable even when the memory's stored state is L3.</li></ol></pipeline-component>
145
+ <h3>Semantic CLI search: embeddings + rank fusion</h3><pre><code># First backfill the default model's embeddings:
146
+ pnpm cli embed backfill --model bge-m3 --dtype q8
147
+ pnpm cli search "concurrent database writes" --semantic
148
+
149
+ # Alternate backfill models exist:
150
+ pnpm cli embed backfill --model small
151
+ pnpm cli embed backfill --model base</code></pre><table-wrap-component><table><thead><tr><th>Stage</th><th>Implementation detail</th></tr></thead><tbody><tr><td>Text to embed</td><td>L3 keywords first, followed by original content. The input is not selected solely from <code>currentLevel</code>.</td></tr><tr><td>Embedding</td><td>Transformers feature-extraction pipeline, mean pooling, normalization and ONNX quantization. Default bge-m3 q8 has 1,024 dimensions; e5-small has 384, e5-base 768. E5 adds query/passage prefixes.</td></tr><tr><td>Storage</td><td>Float32 BLOB in SQLite, tagged with the model ID. CLI backfill defaults to a 500-row limit and embedding batches of 32.</td></tr><tr><td>Query</td><td>The semantic CLI constructs the default bge-m3 embedder. The search command has no matching <code>--model</code> switch; alternate-model backfill alone does not change its query model.</td></tr><tr><td>Candidate lanes</td><td>Lexical candidates and cosine-ranked vectors are collected at up to three times the requested result limit.</td></tr><tr><td>Fusion</td><td><code>hybrid.ts</code> sums reciprocal ranks with <code>RRF_K = 60</code>, then sorts. Directory filtering occurs after the fused limit and can underfill results.</td></tr><tr><td>Missing vectors / load errors</td><td>No vectors for the requested model → lexical results without model loading. With matching vectors present, model-loading failure propagates; it is not a universal silent fallback.</td></tr></tbody></table></table-wrap-component><p>HTTP <code>/search</code> and the current MCP search tool expose lexical search. The semantic path is surfaced by CLI <code>--semantic</code>. Vector rows are invalidated by decay state changes and relevant merge/unmerge/delete operations; run backfill again when needed.</p>
152
+ <h3>Recall is a separate write</h3><p><code>recall(id, agent)</code> increments the recall count, sets the last-recall timestamp and sets saillance to 100. It does not immediately rewrite <code>currentLevel</code>. A later decay calculation uses the more recent recall as its age anchor, so an eligible unmerged trace can return to a more detailed state.</p><p>Trusted cross-agent reuse can earn <code>reused</code> verification. A self-declared HTTP agent header is not treated as equivalent to a trusted client identity.</p><pre><code>pnpm cli recall &lt;memory-id&gt;
153
+ # HTTP: POST /memories/:id/recall
154
+ # MCP: humemory_recall</code></pre><p class="sources">Source: <a href="../../src/core/search.ts">lexical algorithm</a><a href="../../src/core/hybrid.ts">hybrid fusion</a><a href="../../src/core/embeddings.ts">embedding types and thresholds</a><a href="../../src/core/embeddings.ts">model pipeline</a><a href="../../src/store/sqlite.ts">recall and vector storage</a></p></section>
155
+
156
+ <section id="decay"><div class="eyebrow">07 / State and representation</div><h2>Derived text levels and age-based decay</h2><p>Two distinct concepts share the level names: text representations stored on a row, and <code>currentLevel</code>, the row's age-based state. A decay pass updates state and saillance; it does not progressively destroy the original content or call a summarization model.</p><table-wrap-component><table><thead><tr><th>Level</th><th>Representation</th><th>Age calculation</th></tr></thead><tbody><tr><td>L0</td><td><code>content</code>: original text</td><td>Effective age below 24 hours.</td></tr><tr><td>L1</td><td><code>level1Summary</code>: optional summary</td><td>From 24 effective hours.</td></tr><tr><td>L2</td><td><code>level2Essential</code>: optional essential text</td><td>From 168 effective hours (7 days).</td></tr><tr><td>L3</td><td><code>level3Keywords</code>: optional keywords</td><td>From 720 effective hours (30 days); automatic aging stops here.</td></tr><tr><td>L4</td><td>Lost/merged state, linked by <code>mergedIntoId</code> when merged</td><td>The thresholds array contains 2,160 hours, but the age loop checks only L3 through L0. Time alone does not transition a row to L4.</td></tr></tbody></table></table-wrap-component>
157
+ <h3>Exact state calculation</h3><div class="flow">if photographic: level = 0
158
+ else if already L4 or merged: level = 4
159
+ else:
160
+ effectiveAge = min(age since creation, age since last recall)
161
+ slowdown = min(
162
+ (1 + recallCount × 0.3)
163
+ × (saillance ≥ 70 ? 1.5 : 1)
164
+ × (verified ? 1.5 : 1),
165
+ 2.5
166
+ )
167
+ finalAge = effectiveAge / slowdown
168
+ level = highest matching threshold among L0…L3</div><p><code>decayRate</code> is calculated and persisted, but the current level calculation does not use it. Content length and keyword count are not additional level slowdown factors in this implementation. The 2.5× cap applies to the product of all level slowdown factors.</p><h3>When derived text is generated</h3><p><code>generateMemoryLevels()</code> is called when an add requests <code>autoGenerate</code>, and by relevant automatic merge operations. Without an injected LLM, whitespace is compacted, L1 is truncated to 300 characters, L2 to 100 characters, and L3 is a capped list of unique words. CLI <code>encode --auto</code> enables this generation path; it does not automatically install the maintenance LLM client.</p><pre><code>pnpm cli encode "A reusable technical learning" --auto
169
+ pnpm consolidate
170
+ # HTTP: POST /decay</code></pre><p><code>SQLiteStore.updateDecay()</code> writes <code>current_level</code> and saillance and invalidates changed-level vectors. The consolidate script also handles script disuse. <code>decayCycleHours: 24</code> is an algorithm constant, not an automatically installed scheduler. Configure a scheduler explicitly for repeated consolidation.</p><p class="sources">Source: <a href="../../src/core/decay.ts">state calculation</a><a href="../../src/core/llm-generator.ts">derived levels</a><a href="../../scripts/consolidate.js">consolidation entry</a><a href="../../src/store/sqlite.ts">state writes and merge revisions</a></p></section>
171
+
172
+ <section id="prospective"><div class="eyebrow">08 / Event and time execution</div><h2>Intentions, cues, scripts and SessionStart</h2><p>An intention is a future task. A script is an ordered procedure. A cue is a trigger targeting either one. These are separate tables and lifecycles; intentions and scripts are not retrospective <code>MemoryType</code> values.</p><h3>Intention lifecycle</h3><div class="flow">add → armed (saillance 100, no decay)
173
+ trigger → fired (saillance loses 10 per elapsed day, floor 0)
174
+ explicit close → closed (saillance 0, cues cancelled)
175
+ expiry of eligible armed intention → expired (saillance 0)</div><p>A commit closes a loop only through an explicit <code>Closes loop-&lt;id&gt;</code> marker. File-overlap scoring can suggest related loops; it never closes them. <code>commit-closer.ts</code> owns this behavior.</p><h3>Trigger behavior and recurrence</h3><table-wrap-component><table><thead><tr><th>Cue</th><th>Input</th><th>When it fires / what repeats</th></tr></thead><tbody><tr><td>ISO timestamp</td><td><code>time:&lt;ISO timestamp&gt;</code></td><td>Time resolver fires when due. One-shot cue becomes fired.</td></tr><tr><td>Cron</td><td><code>cron:0 9 * * 1</code></td><td>Resolver checks due occurrences since the last firing or arming, with catch-up bounded to seven days. Cron uses local time. Cue is rearmed after firing; repeated invocations can fire subsequent occurrences.</td></tr><tr><td>File open</td><td><code>event:file_open:src/a.ts</code></td><td>Requires an explicit matching event. No automatic filesystem watcher is created. One-shot cue becomes fired.</td></tr><tr><td>Branch switch</td><td><code>event:branch_switch:main</code></td><td>Matching event; SessionStart also uses the current Git branch in its script context path. One-shot cue becomes fired.</td></tr><tr><td>Error pattern</td><td><code>event:error_pattern:&lt;pattern&gt;</code></td><td>Requires a submitted matching event. No background stderr watcher.</td></tr></tbody></table></table-wrap-component><p>Time triggers run when the resolver is invoked, such as at SessionStart, through CLI resolve or HTTP resolve. A cron specification does not create its own OS cron job. The API maintenance interval imports and extracts sessions; it is not the cue scheduler.</p>
176
+ <h3>Script lifecycle and execution meaning</h3><div class="flow">human authoring → active
177
+ agent/API or approved script_candidate → draft → human activate → active
178
+ active + matching cue → context block with ordered steps
179
+ disuse or contradiction → archived
180
+
181
+ On firing: fire_count += 1; last_fired_at = now; saillance += 5 (cap 100)</div><p>“Run a script” means render its steps into the AI client's context. humemory does not execute shell commands from those steps. Draft and archived scripts do not fire. A non-cron cue is consumed even though the script remains active; recurrence needs a cron cue or deliberate rearming/new cues.</p><p>Unpinned active scripts get a 60-day disuse grace period, then lose 10 saillance per month of disuse. Below 20, consolidation archives the script and writes a <code>script_archived</code> notice. Firing resets the disuse anchor. A winning contradiction against a script archives it immediately. Revoking the contradiction restores active status but leaves its cues cancelled.</p>
182
+ <h3>SessionStart, from invocation to output</h3><pipeline-component><ol><li><strong>Collect context.</strong><code>hook-session-start.ts</code> obtains the project working directory and current Git branch, then calls <code>buildSessionContext()</code>.</li><li><strong>Resolve due cues.</strong>The context builder resolves time cues and its supported context events. This can change intention/cue state or mark a script as fired. Resolving time cues can affect targets outside the currently rendered project.</li><li><strong>Select local context.</strong>It collects relevant open loops, eligible traces and one script at most. Trace selection includes L2/L3 state and a saillance threshold of 60; script ties use effective saillance including disuse.</li><li><strong>Render bounded Markdown.</strong>Sections contain loop identifiers, trace excerpts and up to eight rendered script steps. The default item budget is ten per section. Budgets and sanitization limit output size. Non-human or insufficiently verified data is wrapped in <code>&lt;humemory-untrusted&gt;</code>.</li><li><strong>Emit on stdout and exit.</strong>The AI client receives the block through its hook mechanism. This operation does not perform a decay sweep, a generative LLM call or automatic trace recall.</li></ol></pipeline-component><pre><code>pnpm cli intent add "Review the storage change" -d &lt;project&gt; -c "cron:0 9 * * 1"
183
+ pnpm cli intent resolve
184
+ pnpm cli intent close &lt;intention-id&gt;
185
+ pnpm cli script list
186
+ pnpm cli script activate &lt;script-id&gt;
187
+ # Submit external events through POST /events.</code></pre><p class="sources">Source: <a href="../../src/core/cues.ts">cue resolver and cron</a><a href="../../src/core/cue-arg.ts">trigger argument parser</a><a href="../../src/agent/session-context.ts">context builder</a><a href="../../scripts/hook-session-start.ts">SessionStart entry</a><a href="../../src/agent/commit-closer.ts">commit closure</a><a href="../../src/core/scripts.ts">script disuse</a></p></section>
188
+
189
+ <section id="dreamer"><div class="eyebrow">09 / Cross-session batch</div><h2>Dreamer: collection, clustering, proposals and review</h2><p>The dreamer is an explicit batch function, <code>runDreamer()</code>. It has a start, a bounded collection phase, a proposal phase and a returned report. It does not run continuously. The current CLI and HTTP paths do not configure a generative model for it.</p><pre><code>pnpm cli dream run
190
+ pnpm cli dream run --window 30 --clusterer vector
191
+ pnpm cli dream review
192
+ pnpm cli dream approve &lt;proposal-id&gt;
193
+ pnpm cli dream reject &lt;proposal-id&gt;</code></pre><pipeline-component><ol><li><strong>Start and expire old proposals.</strong>The CLI constructs a store and selects the keyword clusterer by default. <code>runDreamer()</code> expires pending proposals past their TTL.</li><li><strong>Collect a bounded memory set.</strong>It reads up to 500 memories and applies the default 30-day creation window. L4, merged memories and active contradiction losers are excluded from the clustering set.</li><li><strong>Cluster.</strong>Keyword mode uses Jaccard similarity with threshold 0.34. Vector mode obtains embeddings for its model, computes missing ones and builds cosine-based connected components. Default bge-m3 clustering threshold is 0.740; e5-small is 0.855 and e5-base 0.825.</li><li><strong>Qualify recurrence.</strong>A cluster qualifies with at least three traces from two sessions, <em>or</em> at least two distinct agents. Confidence uses base provenance trust, without feeding existing verification bonuses back into clustering.</li><li><strong>Apply the corroboration rule separately.</strong>Keyword recurrence can earn verification when it also spans two agents, two sessions and two directories. The vector path additionally has a 0.99 similarity guard, documented in code as the disabled-auto-corroboration sentinel.</li><li><strong>File semantic proposals.</strong>Qualifying clusters produce <code>promote_semantic</code> proposals. A hash of kind + sorted member IDs prevents duplicate filing. Normal proposals expire after 14 days.</li><li><strong>Mine other current proposal paths.</strong>Eligible armed/fired loops open for at least 30 days can yield <code>close_stale_loop</code>. At least two correction-winning memories in one directory can yield <code>script_candidate</code>, with up to six ordered steps (200 characters each), using L2 essential text or original content, and no LLM.</li><li><strong>Return and end.</strong>The report includes considered memories, clusters, filed/expired proposals, stale loops, corroborations and script candidates. The command ends. Approval or rejection is a later, separate operation.</li></ol></pipeline-component>
194
+ <div class="warning"><strong>Proposal generation and approval are different.</strong> Running the dreamer normally creates review rows. It can also write corroboration metadata during the run; it does not require proposal approval for that metadata rule. CLI/HTTP approval applies proposal effects and then marks the proposal approved as separate operations.</div><h3>What approval actually does</h3><table-wrap-component><table><thead><tr><th>Kind</th><th>Approval effect</th><th>Current producer</th></tr></thead><tbody><tr><td><code>promote_semantic</code></td><td>Adds a semantic memory from the proposal/member content with dream provenance.</td><td>Recurring qualified clusters.</td></tr><tr><td><code>close_stale_loop</code></td><td>Closes the targeted intention.</td><td>Stale-loop scan.</td></tr><tr><td><code>script_candidate</code></td><td>Adds a <strong>draft</strong> script; human activation is still required after reviewing its steps.</td><td>Correction mining.</td></tr><tr><td><code>script_archived</code></td><td>Acknowledges a notice; archival has already happened.</td><td>Script disuse / correction handling.</td></tr><tr><td><code>merge_cluster</code></td><td>Merges the listed source traces into a target.</td><td>Application handler exists; current recurring-cluster scan files semantic proposals instead.</td></tr><tr><td><code>contradiction</code></td><td>Records a contradiction between the referenced targets.</td><td>Application handler exists; not an automatic pairwise LLM detector in the current run path.</td></tr><tr><td><code>update_agents_md</code></td><td>Returns suggested content. Does not edit <code>AGENTS.md</code>.</td><td>Suggestion/application support exists; no automatic file-write path.</td></tr></tbody></table></table-wrap-component><p>Rejection changes review status without applying the proposal. There is no automatic approval loop. There is also no persisted “dream job” queue with the maintenance retry policy: an exception from a dream run propagates to its caller.</p><p class="sources">Source: <a href="../../src/core/dreamer.ts">runDreamer and applyDreamProposal</a><a href="../../src/core/vector-clusterer.ts">vector clustering</a><a href="../../src/api/dream-routes.ts">HTTP dream routes</a><a href="../../src/cli/index.ts">CLI review commands</a></p></section>
195
+
196
+ <section id="trust"><div class="eyebrow">10 / Evidence and corrections</div><h2>Trust, provenance and context protection</h2><p>Saillance controls prominence. Trust scores evidence and source authority separately. A frequently recalled memory is not automatically a human-verified fact.</p><table-wrap-component><table><thead><tr><th>Component</th><th>Current values / rule</th></tr></thead><tbody><tr><td>Base provenance</td><td>human 60; hook 45; agent 35; llm_generated 25; dream_proposal 20.</td></tr><tr><td>Verification bonus</td><td>human +25; grounded +20; reused +15; corroborated +8.</td></tr><tr><td>Refutation penalty</td><td>−15 per refutation, capped at three. Final trust score is clamped to 0–100.</td></tr><tr><td>Verification evidence</td><td>Explicit human verification, grounding in a closed loop, trusted cross-agent reuse or eligible corroboration. A source label alone is not sufficient.</td></tr><tr><td>Contradiction against memory</td><td>Authority rules choose the supported winner. Loser saillance is reduced with a floor of 5; active losers stay searchable but are excluded from normal injected context.</td></tr><tr><td>Contradiction against script</td><td>Archives the script and cancels its cues. Revocation restores active status but does not rearm cues.</td></tr><tr><td>Injected context</td><td>Length limits, marker escaping and <code>&lt;humemory-untrusted&gt;</code> boundaries distinguish stored suggestions from trusted instructions. Human-authored scripts can render bare.</td></tr><tr><td>Merge reversibility</td><td>Derived-level revisions are captured before overwrite; unmerge restores the previous representation. Original trace content remains a separate stored field.</td></tr></tbody></table></table-wrap-component><pre><code>pnpm cli contradict &lt;winner-memory-id&gt; &lt;loser-memory-or-script-id&gt;
197
+ pnpm cli unmerge &lt;memory-id&gt;</code></pre><p class="sources">Source: <a href="../../src/core/trust.ts">trust formula</a><a href="../../src/core/sanitize.ts">context boundaries</a><a href="../../src/store/sqlite.ts">verification, contradictions and revisions</a></p></section>
198
+
199
+ <section id="operations"><div class="eyebrow">11 / Operating the system</div><h2>Commands, recurrence and failure handling</h2><h3>What repeats, and what starts it?</h3><table-wrap-component><table><thead><tr><th>Activity</th><th>Recurring mechanism</th><th>Termination / completion</th></tr></thead><tbody><tr><td>API maintenance</td><td>15-minute interval by default while API is alive; no overlapping interval passes.</td><td>Each pass returns; shutdown stops the interval.</td></tr><tr><td>Windows liveness check</td><td>Scheduled task every five minutes by default.</td><td>HTTP 200 ends the check; otherwise launch attempt and exit.</td></tr><tr><td>Session learning</td><td>Client Stop hook, then import/drain passes.</td><td>Successful job checkpoint and queue removal; retry or dead-letter on job failure.</td></tr><tr><td>Context injection</td><td>Client SessionStart hook.</td><td>Bounded Markdown emitted; process exits.</td></tr><tr><td>Cron cue</td><td>Cron specification evaluated by resolver invocations.</td><td>Firing records timestamp and rearms cue for a later due occurrence.</td></tr><tr><td>Decay / script disuse</td><td>Explicit consolidate command or externally configured scheduler.</td><td>One state-update pass.</td></tr><tr><td>Dreamer</td><td>Explicit CLI / HTTP run or external scheduler.</td><td>Report returned; pending proposals wait for review.</td></tr><tr><td>Embedding backfill</td><td>Explicit bounded CLI command; vector dreamer also fills missing embeddings.</td><td>Requested batch set processed and command exits.</td></tr></tbody></table></table-wrap-component>
200
+ <h3>Maintenance retries preserve sessions during outages</h3><pipeline-component><ol><li><strong>Classify the failure.</strong>Database-open/locked errors, disk-full, read-only filesystem and non-constraint SQLite failures are infrastructure failures. They do not spend the job's retry budget.</li><li><strong>Stop an outage-shaped pass.</strong>A circuit breaker aborts after three consecutive failures by default. Untouched jobs are not claimed.</li><li><strong>Finalize retry accounting.</strong>If an aborted pass processed zero jobs, retries charged during that pass are refunded. A successful job proves the machine can work and removes that amnesty.</li><li><strong>Park exhausted job failures.</strong>A genuine job failure can spend five attempts, then retains the transcript in a dead-letter file. Requeue resets attempts without overwriting a newer live job for the same session.</li></ol></pipeline-component><pre><code>pnpm cli maintenance status
201
+ pnpm cli maintenance dead-letters
202
+ pnpm cli maintenance requeue --all
203
+ pnpm cli maintenance run --skip-imports</code></pre><p><code>maintenance-state.json</code> records failed zero-output passes as failures. Status considers the loop stale after 60 minutes by default. <code>/health</code> proves HTTP liveness; it does not prove that queue extraction is progressing.</p>
204
+ <h3>HTTP and MCP surface</h3><table-wrap-component><table><thead><tr><th>Surface</th><th>Operations</th></tr></thead><tbody><tr><td>HTTP memories</td><td><code>POST/GET /memories</code>; <code>GET/DELETE /memories/:id</code>; <code>POST /memories/:id/recall</code>; <code>GET /memories/:id/similar</code>; <code>POST /memories/:id/merge</code>; <code>POST /memories/:id/photo</code>.</td></tr><tr><td>HTTP retrieval / state</td><td><code>GET /search?q=…</code>; <code>POST /decay</code>; <code>GET /status</code>; <code>GET /health</code>.</td></tr><tr><td>HTTP prospective</td><td><code>POST/GET /intentions</code>; close/fire actions; <code>POST /cues</code>, <code>POST /events</code>, <code>POST /cues/resolve</code>; <code>POST/GET /scripts</code> and activate/archive/fire actions.</td></tr><tr><td>HTTP dreams</td><td><code>GET /dreams</code>; <code>POST /dreams/run</code>; <code>POST /dreams/:id/approve</code> or <code>/reject</code>.</td></tr><tr><td>MCP tools</td><td><code>humemory_add</code>, <code>humemory_search</code>, <code>humemory_recall</code>, <code>humemory_intent_add</code>, <code>humemory_intent_close</code>, <code>humemory_dreams</code>. These are not a mirror of every CLI and HTTP feature.</td></tr></tbody></table></table-wrap-component>
205
+ <h3>Safe developer verification</h3><p><code>pnpm cli doctor</code> inspects installation/runtime configuration without reading session contents. Tests must use isolated SQLite, fake clocks, fixtures and mocked clients; never point test runs at the shared data store. <code>pnpm test</code> is a single Bun test pass.</p><p class="sources">Source: <a href="../../src/agent/maintenance-queue.ts">retry classification</a><a href="../../src/agent/maintenance-state.ts">health semantics</a><a href="../../src/api/server.ts">HTTP routes</a><a href="../../src/mcp/server.ts">MCP tools</a><a href="../TESTING.md">testing requirements</a></p></section>
206
+
207
+ <section id="source-map"><div class="eyebrow">12 / Implementation index</div><h2>Where to change each behavior</h2><table-wrap-component><table><thead><tr><th>Responsibility</th><th>File</th></tr></thead><tbody><tr><td>CLI options and invocation wiring</td><td><a href="../../src/cli/index.ts">src/cli/index.ts</a></td></tr><tr><td>API binding, auth, static assets and maintenance startup</td><td><a href="../../src/api/server.ts">src/api/server.ts</a></td></tr><tr><td>MCP tools and stdio lifetime</td><td><a href="../../src/mcp/server.ts">src/mcp/server.ts</a></td></tr><tr><td>Interfaces, record shapes and statuses</td><td><a href="../../src/core/types.ts">src/core/types.ts</a></td></tr><tr><td>Data path resolution</td><td><a href="../../src/core/paths.ts">src/core/paths.ts</a></td></tr><tr><td>Schema, locking, persistence and recalls</td><td><a href="../../src/store/sqlite.ts">src/store/sqlite.ts</a></td></tr><tr><td>Lexical retrieval and ranking</td><td><a href="../../src/core/search.ts">src/core/search.ts</a></td></tr><tr><td>Hybrid retrieval and ONNX model loading</td><td><a href="../../src/core/hybrid.ts">src/core/hybrid.ts</a> · <a href="../../src/core/embeddings.ts">src/core/embeddings.ts</a></td></tr><tr><td>Derived level generation</td><td><a href="../../src/core/llm-generator.ts">src/core/llm-generator.ts</a></td></tr><tr><td>Age-based state and script disuse</td><td><a href="../../src/core/decay.ts">src/core/decay.ts</a> · <a href="../../src/core/scripts.ts">src/core/scripts.ts</a></td></tr><tr><td>Maintenance passes, provider wiring and timer</td><td><a href="../../src/agent/maintenance-runner.ts">src/agent/maintenance-runner.ts</a></td></tr><tr><td>Durable queue and retry policy</td><td><a href="../../src/agent/maintenance-queue.ts">src/agent/maintenance-queue.ts</a></td></tr><tr><td>Parsing and extraction boundary</td><td><a href="../../src/agent/claude-hook.ts">src/agent/claude-hook.ts</a> · <a href="../../src/agent/learning-extractor.ts">src/agent/learning-extractor.ts</a></td></tr><tr><td>Local client discovery</td><td><a href="../../src/agent/source-registry.ts">src/agent/source-registry.ts</a></td></tr><tr><td>Time/event resolution and context output</td><td><a href="../../src/core/cues.ts">src/core/cues.ts</a> · <a href="../../src/agent/session-context.ts">src/agent/session-context.ts</a></td></tr><tr><td>Dream collection, proposals and effects</td><td><a href="../../src/core/dreamer.ts">src/core/dreamer.ts</a> · <a href="../../src/core/vector-clusterer.ts">src/core/vector-clusterer.ts</a></td></tr><tr><td>Trust formula and output sanitization</td><td><a href="../../src/core/trust.ts">src/core/trust.ts</a> · <a href="../../src/core/sanitize.ts">src/core/sanitize.ts</a></td></tr></tbody></table></table-wrap-component></section>
208
+ <footer>This document describes the source paths shipped in this checkout, not proposed architecture. Source links open the implementation. The page is self-contained: no CDN, model invocation or external visualization dependency.</footer>
209
+ </architecture-content-zone>
210
+ </architecture-component>
211
+ <script>
212
+ const nodes={
213
+ hooks:{title:'Client hooks',program:'scripts/hook-session.ts; scripts/hook-session-start.ts',lifetime:'Client starts a short-lived Bun process at Stop or SessionStart.',reads:'Stop: transcript. Start: current directory, Git branch and SQLite records.',writes:'Stop: queue JSON. Start: cue/target firing state and bounded Markdown on stdout.',model:'None in the hook; optional extraction is deferred to maintenance.',config:'HUMEMORY_QUEUE, HUMEMORY_DB, HUMEMORY_SESSION_BUDGET',source:'../../src/agent/session-context.ts'},
214
+ queue:{title:'Maintenance queue',program:'src/agent/maintenance-queue.ts',lifetime:'Disk state survives processes; one drainer holds an advisory ownership lock.',reads:'Pending job JSON, processing claims and per-session checkpoints.',writes:'Claim renames, checkpoints, retry state, retained dead letters.',model:'No model. The processing callback owns extraction.',config:'Queue path; maxAttempts 5; consecutive-failure threshold 3 by default.',source:'../../src/agent/maintenance-queue.ts'},
215
+ worker:{title:'Maintenance runner',program:'runMaintenancePass(); processSession()',lifetime:'One pass from CLI/worker, or repeated non-overlapping passes in the API loop.',reads:'Recent local client sessions, queue jobs and checkpoints.',writes:'Extracted memory rows and maintenance-state.json; no decay or dream pass.',model:'Deterministic first; optional Anthropic messages API or Codex CLI extraction.',config:'HUMEMORY_MAINTENANCE_LLM, TIMEOUT_MS, BATCH and INTERVAL_MS (full names in chapter 03).',source:'../../src/agent/maintenance-runner.ts'},
216
+ api:{title:'HTTP API and dashboard',program:'src/api/server.ts; Hono + @hono/node-server',lifetime:'Resident HTTP process; also owns the maintenance interval.',reads:'SQLite records; built public/app assets.',writes:'Route-dependent entity changes and maintenance results.',model:'Ordinary HTTP search uses no model. Maintenance can use its separately configured provider.',config:'PORT, HUMEMORY_HOST, HUMEMORY_API_TOKEN, CORS_ORIGINS; maintenance settings.',source:'../../src/api/server.ts'},
217
+ mcp:{title:'MCP server',program:'src/mcp/server.ts',lifetime:'Stdio server launched by a client; one process per connection/configuration.',reads:'Shared SQLite store for six tools.',writes:'Add, recall and intention actions; agent attribution on writes.',model:'No generative model or semantic lane in the current search tool.',config:'HUMEMORY_AGENT and the shared HUMEMORY_DB/path resolution.',source:'../../src/mcp/server.ts'},
218
+ cli:{title:'CLI',program:'src/cli/index.ts; packaged entry bin/humemory.js → dist/cli/index.js',lifetime:'One command invocation.',reads:'Command-specific store state, paths, source registry or queue.',writes:'Command-specific changes; operations such as dream run and decay are explicit.',model:'Only the selected operation uses a model; --semantic loads ONNX when vectors exist.',config:'Command flags plus applicable environment variables.',source:'../../src/cli/index.ts'},
219
+ store:{title:'SQLiteStore',program:'src/store/sqlite.ts',lifetime:'Owned by the caller; per-process memory Map and lexical index.',reads:'Relational tables; full memory corpus on index load; PRAGMA data_version.',writes:'Serialized writes through a promise queue and advisory lock. Schema initialization at open.',model:'Storage itself has no provider; auto-generation can call the optional level generator.',config:'Resolved database path and injected Clock/LLM interfaces where supported.',source:'../../src/store/sqlite.ts'},
220
+ retrieval:{title:'Retrieval engines',program:'InverseSearchEngine; hybrid search; OnnxEmbedder',lifetime:'Index lives with store; query operation returns ranked results.',reads:'L3/L2/L1/content fields; optional matching-model vector BLOBs.',writes:'Search itself does not recall. Embedding backfill is a separate write operation.',model:'Lexical: none. Semantic: ONNX feature extraction, default bge-m3 q8.',config:'Query filters; --semantic; model cache; backfill model/dtype options.',source:'../../src/core/hybrid.ts'},
221
+ dream:{title:'Dreamer',program:'runDreamer(); applyDreamProposal()',lifetime:'Explicit bounded batch; returns report. Approval/rejection happens later.',reads:'Up to 500 traces, creation window, provenance, loops and active contradictions.',writes:'Review proposals; eligible corroboration metadata; proposal effects on approval.',model:'Keyword clustering by default. Optional vector clusterer. No drafting LLM wired by CLI/HTTP.',config:'--window, --clusterer; DREAM_CONFIG constants; optional library draft callback.',source:'../../src/core/dreamer.ts'}
222
+ };
223
+ const paths={all:Object.keys(nodes),ingest:['hooks','queue','worker','store'],context:['hooks','store'],search:['cli','api','mcp','store','retrieval'],dream:['cli','api','store','retrieval','dream']};
224
+ function inspect(key){const node=nodes[key];document.getElementById('inspector-title').textContent=node.title;const dl=document.getElementById('inspector-details');dl.replaceChildren();for(const [label,value]of [['Program',node.program],['Lifetime',node.lifetime],['Reads',node.reads],['Writes',node.writes],['Model',node.model],['Configuration',node.config]]){const dt=document.createElement('dt');dt.textContent=label;const dd=document.createElement('dd');dd.textContent=value;dl.append(dt,dd)}const dt=document.createElement('dt');dt.textContent='Source';const dd=document.createElement('dd');const a=document.createElement('a');a.href=node.source;a.textContent=node.source.replace('../../','');dd.append(a);dl.append(dt,dd);document.querySelectorAll('[data-node]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.node===key)))}
225
+ document.querySelectorAll('[data-node]').forEach(b=>b.addEventListener('click',()=>inspect(b.dataset.node)));
226
+ document.querySelectorAll('[data-path]').forEach(b=>b.addEventListener('click',()=>{const path=b.dataset.path;document.querySelectorAll('[data-path]').forEach(c=>c.setAttribute('aria-pressed',String(c===b)));document.querySelectorAll('[data-node]').forEach(c=>c.dataset.dimmed=String(!paths[path].includes(c.dataset.node)));inspect(paths[path][0])}));
227
+ const navlinks=[...document.querySelectorAll('nav a')];const observer=new IntersectionObserver(entries=>{for(const entry of entries){if(entry.isIntersecting){navlinks.forEach(a=>{if(a.hash==='#'+entry.target.id)a.setAttribute('aria-current','location');else a.removeAttribute('aria-current')})}}},{rootMargin:'-10% 0px -70% 0px'});document.querySelectorAll('section[id]').forEach(s=>observer.observe(s));
228
+ </script>
229
+ </body>
230
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
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",
@@ -99,6 +99,7 @@
99
99
  "verify:package": "bun run scripts/verify-package.ts",
100
100
  "measure:recall": "bun run scripts/measure-recall.ts",
101
101
  "bench:scale": "bun run scripts/bench-scale.ts",
102
+ "probe:jev": "bun run scripts/probe-jev.ts --run",
102
103
  "clean:web": "node -e \"require('fs').rmSync('public/app',{recursive:true,force:true})\""
103
104
  }
104
105
  }
@@ -7,10 +7,16 @@
7
7
  * (`pnpm maintenance`) and for a machine that does not keep the API resident.
8
8
  */
9
9
 
10
- import { runMaintenancePass, resolveMaintenanceClient, defaultLlmTimeoutMs } from '../src/agent/maintenance-runner.js';
10
+ import {
11
+ runMaintenancePass,
12
+ resolveMaintenanceClient,
13
+ resolveMaintenanceAdvisor,
14
+ defaultLlmTimeoutMs,
15
+ } from '../src/agent/maintenance-runner.js';
11
16
 
12
17
  const llmTimeoutMs = defaultLlmTimeoutMs();
13
18
  const client = await resolveMaintenanceClient(llmTimeoutMs);
19
+ const advisor = resolveMaintenanceAdvisor();
14
20
 
15
21
  // --skip-codex for a machine where the rollouts are imported some other way.
16
22
  const skipImports = process.argv.includes('--skip-imports');
@@ -19,7 +25,7 @@ const codexSinceDays = skipImports || process.argv.includes('--skip-codex')
19
25
  : Number(process.env.HUMEMORY_MAINTENANCE_CODEX_DAYS ?? 1);
20
26
 
21
27
  const { worker: result } = await runMaintenancePass({
22
- client, llmTimeoutMs, codexSinceDays,
28
+ client, ...advisor, llmTimeoutMs, codexSinceDays,
23
29
  kimiSinceDays: skipImports ? false : undefined,
24
30
  opencodeSinceDays: skipImports ? false : undefined,
25
31
  });
@@ -3,6 +3,11 @@ import { lastMessageTime, parseAgentSession, type ParsedSession } from './sessio
3
3
  import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
4
4
  import type { LLMClient } from '../core/llm-generator.js';
5
5
  import type { TraceSource } from '../core/types.js';
6
+ import {
7
+ adviseInShadow,
8
+ type MemoryAdvisor,
9
+ type ShadowDecisionReporter,
10
+ } from './memory-advisor.js';
6
11
 
7
12
  export interface HookOptions {
8
13
  dbPath: string;
@@ -12,6 +17,10 @@ export interface HookOptions {
12
17
  llmTimeoutMs?: number;
13
18
  source?: TraceSource;
14
19
  agent?: string;
20
+ /** Optional automatic-candidate advisor. It is observational in this release. */
21
+ memoryAdvisor?: MemoryAdvisor;
22
+ /** Receives content-free comparisons; reporter failures never block storage. */
23
+ advisorReporter?: ShadowDecisionReporter;
15
24
  /**
16
25
  * Number of leading transcript messages already encoded for this session.
17
26
  * `Stop` fires once per turn and resends the whole transcript, so without a
@@ -27,6 +36,8 @@ export interface HookResult {
27
36
  memoriesStored: number;
28
37
  learnings: string[];
29
38
  extractionMode: 'llm' | 'deterministic';
39
+ /** Candidates inspected in shadow mode, including local privacy rejections. */
40
+ advisorComparisons: number;
30
41
  /** Total messages in the transcript — the checkpoint to persist after success. */
31
42
  messagesSeen: number;
32
43
  }
@@ -60,7 +71,7 @@ export async function processSession(
60
71
  if (pending.length === 0) {
61
72
  return {
62
73
  sessionId: session.sessionId, directory: session.directory,
63
- memoriesStored: 0, learnings: [], extractionMode: 'deterministic', messagesSeen,
74
+ memoriesStored: 0, learnings: [], extractionMode: 'deterministic', advisorComparisons: 0, messagesSeen,
64
75
  };
65
76
  }
66
77
  const scoped: ParsedSession = {
@@ -84,7 +95,26 @@ export async function processSession(
84
95
  }
85
96
 
86
97
  if (learnings.length === 0) {
87
- return { sessionId: session.sessionId, directory: session.directory, memoriesStored: 0, learnings: [], extractionMode, messagesSeen };
98
+ return {
99
+ sessionId: session.sessionId, directory: session.directory, memoriesStored: 0,
100
+ learnings: [], extractionMode, advisorComparisons: 0, messagesSeen,
101
+ };
102
+ }
103
+
104
+ const source = options.source ?? 'agent';
105
+ let advisorComparisons = 0;
106
+ if (options.memoryAdvisor) {
107
+ // Advice is recorded before storage, but its value is intentionally ignored.
108
+ // `adviseInShadow` contains provider and reporter failures, so every learning
109
+ // below follows the same storage path it used before Jev existed.
110
+ for (const learning of learnings) {
111
+ await adviseInShadow({
112
+ content: learning.content,
113
+ currentMemoryType: learning.memoryType,
114
+ source,
115
+ }, options.memoryAdvisor, options.advisorReporter);
116
+ advisorComparisons += 1;
117
+ }
88
118
  }
89
119
 
90
120
  // What is encoded belongs to the day the session ran, not the day it was
@@ -106,7 +136,7 @@ export async function processSession(
106
136
  sessionId: session.sessionId,
107
137
  memoryType: learning.memoryType,
108
138
  level3Keywords: learning.level3Keywords,
109
- source: options.source ?? 'agent',
139
+ source,
110
140
  agent: options.agent ?? 'unknown',
111
141
  });
112
142
  stored.push(learning.content.slice(0, 80));
@@ -121,6 +151,7 @@ export async function processSession(
121
151
  memoriesStored: stored.length,
122
152
  learnings: stored,
123
153
  extractionMode,
154
+ advisorComparisons,
124
155
  messagesSeen,
125
156
  };
126
157
  }