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/AGENTS.md +43 -25
- package/CHANGELOG.md +16 -0
- package/README.md +31 -16
- package/dist/agent/claude-hook.d.ts +7 -0
- package/dist/agent/claude-hook.js +23 -3
- package/dist/agent/jev-advisor.d.ts +37 -0
- package/dist/agent/jev-advisor.js +139 -0
- package/dist/agent/maintenance-queue.d.ts +3 -0
- package/dist/agent/maintenance-queue.js +2 -0
- package/dist/agent/maintenance-runner.d.ts +13 -3
- package/dist/agent/maintenance-runner.js +60 -10
- package/dist/agent/memory-advisor.d.ts +86 -0
- package/dist/agent/memory-advisor.js +162 -0
- package/dist/cli/index.js +3 -1
- package/dist/core/kimi-llm-client.d.ts +30 -0
- package/dist/core/kimi-llm-client.js +228 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/docs/KIMI_EXPERIMENT_RESOLUTION.md +9 -0
- package/docs/TESTING.md +22 -13
- package/docs/architecture/architecture.html +230 -0
- package/package.json +2 -1
- package/scripts/maintenance-worker.ts +8 -2
- package/src/agent/claude-hook.ts +34 -3
- package/src/agent/jev-advisor.ts +191 -0
- package/src/agent/maintenance-queue.ts +5 -0
- package/src/agent/maintenance-runner.ts +66 -9
- package/src/agent/memory-advisor.ts +237 -0
- package/src/cli/index.ts +3 -1
- package/src/core/kimi-llm-client.ts +180 -0
- package/src/index.ts +7 -0
package/AGENTS.md
CHANGED
|
@@ -12,9 +12,10 @@ For the project's identity and "why", read [README.md](./README.md) first.
|
|
|
12
12
|
humemory has two halves, both built as of Phase 8 (2026-08-08). The direction
|
|
13
13
|
was **Direction 1**, chosen 2026-06-17; everything below is the shipped result.
|
|
14
14
|
|
|
15
|
-
1. **Retrospective** ✅ —
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
1. **Retrospective** ✅ — a five-state model (detail → summary → essential →
|
|
16
|
+
keywords → lost/merged). Automatic aging currently stops at L3; explicit merge
|
|
17
|
+
sets L4. Original content stays in SQLite. Recall reinforces; inverse search
|
|
18
|
+
visits the degraded fields first, then ranks matches across fields.
|
|
18
19
|
2. **Prospective** ✅ — intentions that fire on a **cue** (time/event), **Zeigarnik**
|
|
19
20
|
open loops that stay salient until a `commit` closes them, and context-triggered
|
|
20
21
|
**scripts** that fade on disuse rather than time. A memory that resurfaces
|
|
@@ -35,7 +36,7 @@ prospective, scripts cognitifs, effet Zeigarnik).
|
|
|
35
36
|
|
|
36
37
|
```bash
|
|
37
38
|
pnpm install
|
|
38
|
-
pnpm build # tsc
|
|
39
|
+
pnpm build # backend tsc → dist/ + web typecheck + web bundle → public/app/
|
|
39
40
|
pnpm dev # watch src/cli/index.ts (bun)
|
|
40
41
|
pnpm start:api # HTTP API + dashboard on :3456
|
|
41
42
|
pnpm cli <cmd> # run CLI directly
|
|
@@ -62,12 +63,23 @@ src/
|
|
|
62
63
|
│ ├── types.ts # Memory, DecayLevel, SearchQuery, MemoryStore iface
|
|
63
64
|
│ ├── decay.ts # degradation curve + thresholds
|
|
64
65
|
│ ├── search.ts # inverse search (lexical, degraded-first)
|
|
65
|
-
│
|
|
66
|
+
│ ├── llm-generator.ts # deterministic L1/L2/L3; optional injected LLM
|
|
67
|
+
│ ├── clock.ts # Clock seam (systemClock / FakeClock)
|
|
68
|
+
│ ├── event-bus.ts # AppEvent + InMemoryEventBus
|
|
69
|
+
│ ├── cue-arg.ts # cue syntax shared by CLI and React form
|
|
70
|
+
│ ├── cues.ts # cue resolver, cron matcher, loop ids
|
|
71
|
+
│ ├── scripts.ts # script disuse calculation + archival sweep
|
|
72
|
+
│ ├── trust.ts / sanitize.ts # authority scoring + context hardening
|
|
73
|
+
│ ├── dreamer.ts # clusters, corroboration metadata, reviewed proposals
|
|
74
|
+
│ ├── embeddings.ts / hybrid.ts / vector-clusterer.ts # optional semantic lane
|
|
75
|
+
│ ├── paths.ts # data/db/queue/model-cache/install root resolver
|
|
76
|
+
│ └── doctor.ts # install diagnostic (no memory content read)
|
|
66
77
|
├── store/
|
|
67
78
|
│ └── sqlite.ts # bun:sqlite store (WAL), findSimilar/merge/setPhotographic
|
|
68
79
|
├── agent/
|
|
69
80
|
│ ├── session-parser.ts # parse Claude Code session transcripts
|
|
70
81
|
│ ├── source-registry.ts # discover local AI runtimes without reading sessions
|
|
82
|
+
│ ├── codex-rollout-parser.ts / codex-import.ts # Codex rollout → queue
|
|
71
83
|
│ ├── kimi-session-parser.ts / kimi-import.ts # Kimi wire → maintenance queue
|
|
72
84
|
│ ├── opencode-session-parser.ts / opencode-import.ts # public OpenCode export → queue
|
|
73
85
|
│ ├── mcp-client-setup.ts # merge humemory into Kimi/OpenCode MCP configs
|
|
@@ -77,15 +89,9 @@ src/
|
|
|
77
89
|
│ ├── maintenance-state.ts # durable health record of the loop (data/maintenance-state.json)
|
|
78
90
|
│ ├── claude-hook.ts # worker-side session learning encoder
|
|
79
91
|
│ └── session-context.ts # SessionStart → markdown block (open loops + traces)
|
|
80
|
-
├── core/
|
|
81
|
-
│ ├── clock.ts # Clock seam (systemClock / FakeClock)
|
|
82
|
-
│ ├── event-bus.ts # AppEvent + InMemoryEventBus
|
|
83
|
-
│ ├── cue-arg.ts # cue syntax, shared by the CLI and the React form
|
|
84
|
-
│ ├── paths.ts # single resolver for data/db/queue/model-cache/install root
|
|
85
|
-
│ ├── doctor.ts # install diagnostic behind `humemory doctor` (no content read)
|
|
86
|
-
│ └── cues.ts # cue resolver, cron matcher, loop ids
|
|
87
92
|
├── api/server.ts # Hono HTTP API + serves public/ dashboard
|
|
88
93
|
├── cli/index.ts # commander CLI
|
|
94
|
+
├── mcp/server.ts # shared-store tools over stdio, process agent identity
|
|
89
95
|
└── index.ts # library exports
|
|
90
96
|
web/ # React front (bun bundler → public/app, served at /app)
|
|
91
97
|
scripts/hook-session.ts # Claude Code Stop hook → queue raw session only
|
|
@@ -115,9 +121,13 @@ data/humemory.db # legacy in-checkout DB; new installs use the OS data
|
|
|
115
121
|
| `keywords` | Indices de récupération | retrieval cues |
|
|
116
122
|
| `memoryType` | Type | episodic / semantic / procedural |
|
|
117
123
|
|
|
118
|
-
**
|
|
119
|
-
|
|
120
|
-
|
|
124
|
+
**Automatic decay thresholds:** L0→L1 24h · L1→L2 168h · L2→L3 720h,
|
|
125
|
+
before slowdown. The configured L4 threshold (2160h) is not visited by the
|
|
126
|
+
calculator. Slowdown is the product of `(1 + recallCount * 0.3)`, 1.5 when
|
|
127
|
+
saillance >=70, and 1.5 when verified, capped at 2.5×. The more recent creation
|
|
128
|
+
or recall determines age. Content length and keyword count affect stored
|
|
129
|
+
`decayRate`, which does not currently affect the calculated level.
|
|
130
|
+
`photographic: true` returns L0. See the [architecture guide](docs/architecture/architecture.html).
|
|
121
131
|
|
|
122
132
|
**Memory types:** `episodic` (events), `semantic` (facts), `procedural` (skills).
|
|
123
133
|
|
|
@@ -131,11 +141,11 @@ keywords >5. `photographic: true` disables decay entirely.
|
|
|
131
141
|
| GET | `/memories` | list (limit, level, type) |
|
|
132
142
|
| GET | `/memories/:id` | fetch one |
|
|
133
143
|
| POST | `/memories/:id/recall` | bump recall + saillance |
|
|
134
|
-
|
|
|
144
|
+
| GET | `/memories/:id/similar` | find similar |
|
|
135
145
|
| POST | `/memories/:id/merge` | merge (L4) |
|
|
136
146
|
| POST | `/memories/:id/photo` | toggle photographic |
|
|
137
147
|
| DELETE | `/memories/:id` | forget |
|
|
138
|
-
| GET | `/search?
|
|
148
|
+
| GET | `/search?q=X` | inverse search |
|
|
139
149
|
| POST | `/decay` | run consolidation |
|
|
140
150
|
| GET | `/status` | pool stats |
|
|
141
151
|
|
|
@@ -184,7 +194,8 @@ Core rules:
|
|
|
184
194
|
- **Isolated DB per run** — never touch `data/humemory.db`; use an in-memory or
|
|
185
195
|
temp-file `bun:sqlite` instance, torn down after each suite.
|
|
186
196
|
- **Injectable clock** — decay is time-driven, so time must be a parameter, not
|
|
187
|
-
`Date.now()`. Tests fast-forward a fake clock
|
|
197
|
+
`Date.now()`. Tests fast-forward a fake clock through automatic L0→L3;
|
|
198
|
+
L4 is tested as an explicit merge state.
|
|
188
199
|
- **Mocked LLM** — no calls to Anthropic in tests; `LLMClient` is stubbed with
|
|
189
200
|
deterministic fixtures. CI runs with no `ANTHROPIC_API_KEY`.
|
|
190
201
|
- **Fixtures, not live data** — seed memories from `tests/fixtures/`.
|
|
@@ -201,7 +212,8 @@ clock- and event-driven and cannot be trusted without it.
|
|
|
201
212
|
### ✅ Done — Sprints 1–4
|
|
202
213
|
- Core decay + inverse search; `bun:sqlite` store (WAL, write-queue serialization)
|
|
203
214
|
- CLI + Hono API + web dashboard ("palais de mémoire")
|
|
204
|
-
-
|
|
215
|
+
- Consolidation entry point for an external scheduler (`0 3 * * *` is an example,
|
|
216
|
+
not installed automatically); API maintenance imports/encodes sessions every 15 min
|
|
205
217
|
- Deterministic L1/L2/L3 generation; optional injected LLM enhancement
|
|
206
218
|
- Similar-detection + merge (L4); enriched search (type/period/saillance/recalls)
|
|
207
219
|
- Photographic mode; Claude Code `Stop` hook → durable async maintenance queue
|
|
@@ -220,7 +232,8 @@ branch_switch / error_pattern). One intention → N cues.
|
|
|
220
232
|
|
|
221
233
|
**Cue resolver (5.2): ✅ shipped (S5-02), `src/core/cues.ts`.** `resolveTimeCues(now)` + `resolveEventCues(event)` + expiry.
|
|
222
234
|
Decay × intention rule: `armed` → saillance pinned at 100, no decay (open loop stays
|
|
223
|
-
salient); `fired` not `closed` →
|
|
235
|
+
salient); `fired` not `closed` → intention-specific fade (−10 points/day from
|
|
236
|
+
`firedAt`, not the retrospective L0→L3 curve); `closed`
|
|
224
237
|
→ archived.
|
|
225
238
|
|
|
226
239
|
**Hooks (5.3): ✅ shipped (S5-03a, S5-03b).**
|
|
@@ -269,14 +282,18 @@ recurring traces across sessions/agents (KeywordClusterer behind a `Clusterer`
|
|
|
269
282
|
interface — vectors are Phase 7), scores clusters on `base(source)` only,
|
|
270
283
|
writes **idempotent** `dream_proposals` (14-day expiry) reviewed via
|
|
271
284
|
`pnpm cli dream review` / `approve` / `reject`; API `GET /dreams`,
|
|
272
|
-
`POST /dreams/:id/approve|reject`.
|
|
273
|
-
|
|
285
|
+
`POST /dreams/:id/approve|reject`. Content-changing proposals require approval;
|
|
286
|
+
keyword corroboration can automatically update verification metadata on existing
|
|
287
|
+
memories. `update_agents_md` returns a suggestion and never edits the file.
|
|
288
|
+
Dream kinds: `promote_semantic`, `merge_cluster`,
|
|
274
289
|
`contradiction`, `close_stale_loop`, `update_agents_md` (suggestion only).
|
|
275
290
|
|
|
276
291
|
**6.2 — MCP server: ✅ shipped** (`pnpm mcp`, `src/mcp/server.ts`, stdio).
|
|
277
292
|
Tools `humemory_add / search / recall / intent_add / intent_close / dreams` —
|
|
278
293
|
Claude, Codex, Kimi, OpenCode share one store with agent attribution on every
|
|
279
|
-
write (
|
|
294
|
+
write (identity from `$HUMEMORY_AGENT` in the server process, not a tool argument;
|
|
295
|
+
`HUMEMORY_DB` override for tests). Cross-agent reuse earns verification only
|
|
296
|
+
through a caller that supplies a trusted process identity, not an HTTP attribution header.
|
|
280
297
|
|
|
281
298
|
**Client registration** — the repo ships `.mcp.json` (Claude Code project
|
|
282
299
|
scope, `HUMEMORY_AGENT=claude`). `pnpm cli sources setup` merge-registers the
|
|
@@ -319,7 +336,7 @@ bundle (scripts are markdown any CLI agent reads, humemory stays agent-agnostic)
|
|
|
319
336
|
human-authored renders bare, everything else wrapped in
|
|
320
337
|
`<humemory-untrusted>`, escape-attempt telemetry on every render path.
|
|
321
338
|
- **8.3 — authoring & trust.** Three paths: human (`script add` → active
|
|
322
|
-
directly), agent (
|
|
339
|
+
directly), agent (API/library authoring → draft, human activates), dreamer-mined
|
|
323
340
|
(→ draft, see 8.5). Draft scripts never fire.
|
|
324
341
|
- **8.4 — disuse decay, the inverse Zeigarnik.** Scripts fade on *disuse*, not
|
|
325
342
|
time: active + unfired 60 days → −10 saillance/month past the grace period;
|
|
@@ -376,7 +393,8 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
|
|
|
376
393
|
- `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
|
|
377
394
|
|
|
378
395
|
## 📝 Notes
|
|
379
|
-
- Shared DB: `
|
|
396
|
+
- Shared DB: `src/core/paths.ts` resolves environment overrides, a legacy checkout
|
|
397
|
+
DB or the OS user data directory · API port `3456` (`PORT` env)
|
|
380
398
|
- Stack: TypeScript · `bun:sqlite` · `flexsearch` · `hono` · `commander` · `@anthropic-ai/sdk`
|
|
381
399
|
- `CLAUDE.md` is a thin quick-start companion that points back to this file; this
|
|
382
400
|
AGENTS.md remains the canonical source of truth for project vision and concepts.
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.13] - 2026-09-20
|
|
4
|
+
**Documentation:**
|
|
5
|
+
- update project guidance and architecture
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
## [0.2.12] - 2026-09-20
|
|
10
|
+
**Features:**
|
|
11
|
+
- add Jev shadow qualification
|
|
12
|
+
- guard Kimi subscription consolidation
|
|
13
|
+
|
|
14
|
+
**Documentation:**
|
|
15
|
+
- clarify Jev shadow invariants
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
3
19
|
## [0.2.11] - 2026-09-08
|
|
4
20
|
**Features:**
|
|
5
21
|
- measure what the index rebuild actually costs
|
package/README.md
CHANGED
|
@@ -26,17 +26,24 @@ Past learnings are **encoded**, then **degraded** over time on a human curve:
|
|
|
26
26
|
| Level | Name | Lifespan | Holds |
|
|
27
27
|
|-------|------|----------|-------|
|
|
28
28
|
| L0 | full detail | fresh (<24h) | complete content |
|
|
29
|
-
| L1 | summary | days | LLM
|
|
29
|
+
| L1 | summary | days | deterministic summary; optional LLM enhancement |
|
|
30
30
|
| L2 | essential | weeks | the gist |
|
|
31
31
|
| L3 | keywords | months | lexical retrieval tokens |
|
|
32
|
-
| L4 | lost / merged |
|
|
32
|
+
| L4 | lost / merged | explicit merge | source linked to a sibling trace |
|
|
33
33
|
|
|
34
34
|
Recall resists decay. Saillance (mnemonic strength, 0–100) and recall count slow
|
|
35
35
|
the curve. A **photographic** flag pins critical traces so they never fade.
|
|
36
36
|
|
|
37
|
-
**Inverse search**
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
**Inverse search** visits indexed fields in order: L3 keywords → L2 essentials →
|
|
38
|
+
L1 summary → full content. It collects matches across these fields, then ranks and
|
|
39
|
+
limits the results. A relaxed pass runs only if the strict pass found nothing.
|
|
40
|
+
Search does not itself reinforce a trace; use `recall` for that.
|
|
41
|
+
|
|
42
|
+
The model has five states, but automatic aging currently stops at L3: the decay
|
|
43
|
+
calculator does not visit the configured L4 threshold. Aging preserves the original
|
|
44
|
+
content and derived fields in SQLite, so detailed content remains searchable.
|
|
45
|
+
See the [interactive architecture guide](docs/architecture/architecture.html)
|
|
46
|
+
for the overall system and the detailed rules.
|
|
40
47
|
|
|
41
48
|
A Claude Code `Stop` hook can queue each completed session instantly; maintenance
|
|
42
49
|
extracts and stores its learnings afterward, outside the agent's critical path.
|
|
@@ -396,7 +403,7 @@ The CLI provides several commands to interact with humemory:
|
|
|
396
403
|
Options:
|
|
397
404
|
- `-d, --directory <dir>`: Filter by mental space
|
|
398
405
|
- `-s, --session <id>`: Filter by context
|
|
399
|
-
- `-l, --level <max>`:
|
|
406
|
+
- `-l, --level <max>`: Highest indexed field to search (0-4); not a filter on a trace's current state
|
|
400
407
|
- `-n, --limit <n>`: Number of traces
|
|
401
408
|
- `-t, --type <type>`: Filter by type (episodic/semantic/procedural)
|
|
402
409
|
- `--from <date>`: Start date YYYY-MM-DD
|
|
@@ -443,7 +450,7 @@ The CLI provides several commands to interact with humemory:
|
|
|
443
450
|
pnpm cli merge <sourceId> <targetId>
|
|
444
451
|
```
|
|
445
452
|
Options:
|
|
446
|
-
- `--auto`:
|
|
453
|
+
- `--auto`: Regenerate merged derived levels locally; an injected LLM may enhance them
|
|
447
454
|
|
|
448
455
|
- **Delete a memory trace**:
|
|
449
456
|
```bash
|
|
@@ -489,11 +496,11 @@ The API will be available at `http://localhost:3456`. You can interact with it u
|
|
|
489
496
|
- `GET /memories`: List memories
|
|
490
497
|
- `GET /memories/:id`: Fetch a specific memory
|
|
491
498
|
- `POST /memories/:id/recall`: Bump recall and saillance
|
|
492
|
-
- `
|
|
499
|
+
- `GET /memories/:id/similar`: Find similar memories
|
|
493
500
|
- `POST /memories/:id/merge`: Merge memories
|
|
494
501
|
- `POST /memories/:id/photo`: Toggle photographic mode
|
|
495
502
|
- `DELETE /memories/:id`: Forget a memory
|
|
496
|
-
- `GET /search?
|
|
503
|
+
- `GET /search?q=X`: Inverse search
|
|
497
504
|
- `POST /decay`: Run consolidation
|
|
498
505
|
- `GET /status`: Pool stats
|
|
499
506
|
|
|
@@ -670,9 +677,12 @@ days later on a user's machine. Runs on Linux, macOS and Windows in CI.
|
|
|
670
677
|
| `keywords` | Indices de récupération | retrieval cues |
|
|
671
678
|
| `memoryType` | Type | episodic / semantic / procedural |
|
|
672
679
|
|
|
673
|
-
**
|
|
674
|
-
|
|
675
|
-
|
|
680
|
+
**Automatic decay thresholds:** L0→L1 24h · L1→L2 168h · L2→L3 720h,
|
|
681
|
+
before slowdown. L4 is configured at 2160h but is not reached by automatic aging.
|
|
682
|
+
Age is measured from the more recent creation or recall. Slowdown is
|
|
683
|
+
`min((1 + recallCount * 0.3) × (saillance >= 70 ? 1.5 : 1) × (verified ? 1.5 : 1), 2.5)`.
|
|
684
|
+
Content length and keyword count affect the stored `decayRate`, which the level
|
|
685
|
+
calculator currently does not use. `photographic: true` returns L0.
|
|
676
686
|
|
|
677
687
|
**Memory types:** `episodic` (events), `semantic` (facts), `procedural` (skills).
|
|
678
688
|
|
|
@@ -683,7 +693,8 @@ keywords >5. `photographic: true` disables decay entirely.
|
|
|
683
693
|
### ✅ Done — Sprints 1–4
|
|
684
694
|
- Core decay + inverse search; `bun:sqlite` store (WAL, write-queue serialization)
|
|
685
695
|
- CLI + Hono API + web dashboard ("palais de mémoire")
|
|
686
|
-
-
|
|
696
|
+
- Consolidation entry point for an external scheduler (example: `0 3 * * *`);
|
|
697
|
+
the API's 15-minute maintenance loop imports and encodes sessions, not trace decay
|
|
687
698
|
- Deterministic L1/L2/L3 generation; optional injected LLM enhancement
|
|
688
699
|
- Similar-detection + merge (L4); enriched search (type/period/saillance/recalls)
|
|
689
700
|
- Photographic mode; Claude Code `Stop` hook → durable async maintenance queue
|
|
@@ -698,14 +709,17 @@ keywords >5. `photographic: true` disables decay entirely.
|
|
|
698
709
|
typed `trigger_spec`. One intention → N cues.
|
|
699
710
|
- [x] **5.2 Cue resolver** — time cues (ISO/cron) and event cues (file_open,
|
|
700
711
|
branch_switch, error_pattern). Decay rule: `armed` → saillance pinned at 100;
|
|
701
|
-
`fired` not `closed` →
|
|
712
|
+
`fired` not `closed` → −10 saillance points/day from `firedAt`;
|
|
713
|
+
`closed` → archived. This is separate from retrospective trace aging.
|
|
702
714
|
- [x] **5.3 Hooks** — `SessionStart` injects context (`scripts/hook-session-start.ts`,
|
|
703
715
|
budget via `HUMEMORY_SESSION_BUDGET`); git `post-commit` closes loops via the
|
|
704
716
|
explicit `Closes loop-<id>` marker, and only *suggests* on file-overlap.
|
|
705
717
|
- [x] **5.4 CLI/API** — `pnpm cli intent {add,list,close,fire,resolve}`,
|
|
706
718
|
`POST /intentions`, `POST /cues`, `POST /events`, `POST /cues/resolve`.
|
|
707
719
|
|
|
708
|
-
**
|
|
720
|
+
**Phases 6–8 shipped** — trust and contradictions, reviewed dream proposals, MCP,
|
|
721
|
+
optional vector search, and cognitive scripts. See the detailed shipped status in
|
|
722
|
+
[AGENTS.md](AGENTS.md). Cognitive scripts are Phase 8, not deferred work.
|
|
709
723
|
|
|
710
724
|
### 🛣️ Beyond
|
|
711
725
|
- Shared multi-project DB with concurrency lock (WAL + advisory) — done (Sprint 5 / S5-00a)
|
|
@@ -721,7 +735,8 @@ keywords >5. `photographic: true` disables decay entirely.
|
|
|
721
735
|
- `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
|
|
722
736
|
|
|
723
737
|
## Notes
|
|
724
|
-
- Shared DB: `
|
|
738
|
+
- Shared DB: resolved by `src/core/paths.ts` (legacy checkout `data/humemory.db`,
|
|
739
|
+
otherwise the OS user data directory, with environment overrides) · API port `3456` (`PORT` env)
|
|
725
740
|
- Stack: TypeScript · `bun:sqlite` · `flexsearch` · `hono` · `commander` · `@anthropic-ai/sdk`
|
|
726
741
|
- `CLAUDE.md` is a thin Claude-Code-specific quick-start that delegates to
|
|
727
742
|
`AGENTS.md`; `AGENTS.md` remains the canonical source of truth.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { LLMClient } from '../core/llm-generator.js';
|
|
2
2
|
import type { TraceSource } from '../core/types.js';
|
|
3
|
+
import { type MemoryAdvisor, type ShadowDecisionReporter } from './memory-advisor.js';
|
|
3
4
|
export interface HookOptions {
|
|
4
5
|
dbPath: string;
|
|
5
6
|
directory?: string;
|
|
@@ -8,6 +9,10 @@ export interface HookOptions {
|
|
|
8
9
|
llmTimeoutMs?: number;
|
|
9
10
|
source?: TraceSource;
|
|
10
11
|
agent?: string;
|
|
12
|
+
/** Optional automatic-candidate advisor. It is observational in this release. */
|
|
13
|
+
memoryAdvisor?: MemoryAdvisor;
|
|
14
|
+
/** Receives content-free comparisons; reporter failures never block storage. */
|
|
15
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
11
16
|
/**
|
|
12
17
|
* Number of leading transcript messages already encoded for this session.
|
|
13
18
|
* `Stop` fires once per turn and resends the whole transcript, so without a
|
|
@@ -22,6 +27,8 @@ export interface HookResult {
|
|
|
22
27
|
memoriesStored: number;
|
|
23
28
|
learnings: string[];
|
|
24
29
|
extractionMode: 'llm' | 'deterministic';
|
|
30
|
+
/** Candidates inspected in shadow mode, including local privacy rejections. */
|
|
31
|
+
advisorComparisons: number;
|
|
25
32
|
/** Total messages in the transcript — the checkpoint to persist after success. */
|
|
26
33
|
messagesSeen: number;
|
|
27
34
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SQLiteStore } from '../store/sqlite.js';
|
|
2
2
|
import { lastMessageTime, parseAgentSession } from './session-parser.js';
|
|
3
3
|
import { extractLearnings, extractLearningsDeterministic } from './learning-extractor.js';
|
|
4
|
+
import { adviseInShadow, } from './memory-advisor.js';
|
|
4
5
|
async function withTimeout(promise, timeoutMs) {
|
|
5
6
|
let timer;
|
|
6
7
|
try {
|
|
@@ -27,7 +28,7 @@ export async function processSession(rawTranscript, options) {
|
|
|
27
28
|
if (pending.length === 0) {
|
|
28
29
|
return {
|
|
29
30
|
sessionId: session.sessionId, directory: session.directory,
|
|
30
|
-
memoriesStored: 0, learnings: [], extractionMode: 'deterministic', messagesSeen,
|
|
31
|
+
memoriesStored: 0, learnings: [], extractionMode: 'deterministic', advisorComparisons: 0, messagesSeen,
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
const scoped = {
|
|
@@ -47,7 +48,25 @@ export async function processSession(rawTranscript, options) {
|
|
|
47
48
|
}
|
|
48
49
|
}
|
|
49
50
|
if (learnings.length === 0) {
|
|
50
|
-
return {
|
|
51
|
+
return {
|
|
52
|
+
sessionId: session.sessionId, directory: session.directory, memoriesStored: 0,
|
|
53
|
+
learnings: [], extractionMode, advisorComparisons: 0, messagesSeen,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const source = options.source ?? 'agent';
|
|
57
|
+
let advisorComparisons = 0;
|
|
58
|
+
if (options.memoryAdvisor) {
|
|
59
|
+
// Advice is recorded before storage, but its value is intentionally ignored.
|
|
60
|
+
// `adviseInShadow` contains provider and reporter failures, so every learning
|
|
61
|
+
// below follows the same storage path it used before Jev existed.
|
|
62
|
+
for (const learning of learnings) {
|
|
63
|
+
await adviseInShadow({
|
|
64
|
+
content: learning.content,
|
|
65
|
+
currentMemoryType: learning.memoryType,
|
|
66
|
+
source,
|
|
67
|
+
}, options.memoryAdvisor, options.advisorReporter);
|
|
68
|
+
advisorComparisons += 1;
|
|
69
|
+
}
|
|
51
70
|
}
|
|
52
71
|
// What is encoded belongs to the day the session ran, not the day it was
|
|
53
72
|
// read: a rollout sweep runs long after the fact, and dating every trace on
|
|
@@ -66,7 +85,7 @@ export async function processSession(rawTranscript, options) {
|
|
|
66
85
|
sessionId: session.sessionId,
|
|
67
86
|
memoryType: learning.memoryType,
|
|
68
87
|
level3Keywords: learning.level3Keywords,
|
|
69
|
-
source
|
|
88
|
+
source,
|
|
70
89
|
agent: options.agent ?? 'unknown',
|
|
71
90
|
});
|
|
72
91
|
stored.push(learning.content.slice(0, 80));
|
|
@@ -81,6 +100,7 @@ export async function processSession(rawTranscript, options) {
|
|
|
81
100
|
memoriesStored: stored.length,
|
|
82
101
|
learnings: stored,
|
|
83
102
|
extractionMode,
|
|
103
|
+
advisorComparisons,
|
|
84
104
|
messagesSeen,
|
|
85
105
|
};
|
|
86
106
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type MemoryAdvice, type MemoryAdvisor, type SanitizedMemoryCandidate } from './memory-advisor.js';
|
|
2
|
+
/**
|
|
3
|
+
* TypeSafe System One adapter for automatic-memory qualification.
|
|
4
|
+
* Acquisition rules and privacy checks stay in `memory-advisor.ts`; this file
|
|
5
|
+
* only translates a sanitized candidate to and from the provider schema.
|
|
6
|
+
*/
|
|
7
|
+
export type JevMode = 'off' | 'shadow' | 'advisory';
|
|
8
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
9
|
+
export interface JevAdvisorOptions {
|
|
10
|
+
apiKey: string;
|
|
11
|
+
endpoint?: string;
|
|
12
|
+
model?: string;
|
|
13
|
+
/** Per-request deadline. Native fetch observes the AbortSignal below. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
/** Test seam; production uses the runtime's native fetch. */
|
|
16
|
+
fetch?: FetchLike;
|
|
17
|
+
}
|
|
18
|
+
/** HTTP implementation of the provider-neutral `MemoryAdvisor` seam. */
|
|
19
|
+
export declare class JevMemoryAdvisor implements MemoryAdvisor {
|
|
20
|
+
private readonly apiKey;
|
|
21
|
+
private readonly endpoint;
|
|
22
|
+
private readonly model;
|
|
23
|
+
private readonly timeoutMs;
|
|
24
|
+
private readonly fetchImpl;
|
|
25
|
+
constructor(options: JevAdvisorOptions);
|
|
26
|
+
advise(candidate: SanitizedMemoryCandidate): Promise<MemoryAdvice>;
|
|
27
|
+
}
|
|
28
|
+
/** Requested mode and the narrower mode this release is allowed to execute. */
|
|
29
|
+
export interface ConfiguredJevAdvisor {
|
|
30
|
+
requestedMode: JevMode;
|
|
31
|
+
effectiveMode: 'off' | 'shadow';
|
|
32
|
+
advisor?: MemoryAdvisor;
|
|
33
|
+
unavailableReason?: 'missing_api_key';
|
|
34
|
+
}
|
|
35
|
+
/** API-key presence alone is inert. Advisory is deliberately capped to shadow. */
|
|
36
|
+
export declare function resolveConfiguredJevAdvisor(env?: NodeJS.ProcessEnv, fetchImpl?: FetchLike): ConfiguredJevAdvisor;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { SALIENCE_BANDS, } from './memory-advisor.js';
|
|
2
|
+
function finiteProbability(value, name) {
|
|
3
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
4
|
+
throw new Error(`Malformed Jev ${name}`);
|
|
5
|
+
}
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
function memoryType(value) {
|
|
9
|
+
if (value === 'episodic' || value === 'semantic' || value === 'procedural')
|
|
10
|
+
return value;
|
|
11
|
+
throw new Error('Malformed Jev memory_type');
|
|
12
|
+
}
|
|
13
|
+
function salienceBand(value) {
|
|
14
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > SALIENCE_BANDS.length - 1) {
|
|
15
|
+
throw new Error('Malformed Jev salience_band');
|
|
16
|
+
}
|
|
17
|
+
return SALIENCE_BANDS[Math.round(value)];
|
|
18
|
+
}
|
|
19
|
+
/** HTTP implementation of the provider-neutral `MemoryAdvisor` seam. */
|
|
20
|
+
export class JevMemoryAdvisor {
|
|
21
|
+
apiKey;
|
|
22
|
+
endpoint;
|
|
23
|
+
model;
|
|
24
|
+
timeoutMs;
|
|
25
|
+
fetchImpl;
|
|
26
|
+
constructor(options) {
|
|
27
|
+
if (!options.apiKey.trim())
|
|
28
|
+
throw new Error('TYPESAFE_API_KEY is required for Jev shadow mode');
|
|
29
|
+
this.apiKey = options.apiKey.trim();
|
|
30
|
+
this.endpoint = options.endpoint ?? 'https://api.typesafe.ai/v1/systemone';
|
|
31
|
+
this.model = options.model ?? 'jev-latest';
|
|
32
|
+
this.timeoutMs = options.timeoutMs ?? 3_000;
|
|
33
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
34
|
+
}
|
|
35
|
+
async advise(candidate) {
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
38
|
+
try {
|
|
39
|
+
const response = await this.fetchImpl(this.endpoint, {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: {
|
|
42
|
+
authorization: `Bearer ${this.apiKey}`,
|
|
43
|
+
'content-type': 'application/json',
|
|
44
|
+
},
|
|
45
|
+
signal: controller.signal,
|
|
46
|
+
body: JSON.stringify({
|
|
47
|
+
state: {
|
|
48
|
+
candidate: candidate.content,
|
|
49
|
+
current_memory_type: candidate.currentMemoryType,
|
|
50
|
+
},
|
|
51
|
+
model: this.model,
|
|
52
|
+
questions: {
|
|
53
|
+
should_store: {
|
|
54
|
+
type: 'noul',
|
|
55
|
+
instructions: 'Should this candidate become durable memory for a future AI agent working on the same project?',
|
|
56
|
+
criteria: {
|
|
57
|
+
true: 'Durable decision, solved problem, reusable procedure, or stable project fact',
|
|
58
|
+
false: 'Transient output, conversational filler, unverified plan, repetition, or one-off observation',
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
memory_type: {
|
|
62
|
+
type: 'choice',
|
|
63
|
+
instructions: 'Which cognitive memory type best describes this candidate?',
|
|
64
|
+
criteria: {
|
|
65
|
+
episodic: 'A particular event or session-bound occurrence',
|
|
66
|
+
semantic: 'A stable fact, rule, or concept',
|
|
67
|
+
procedural: 'A reusable method, skill, or sequence of actions',
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
salience_band: {
|
|
71
|
+
type: 'score',
|
|
72
|
+
instructions: 'How important is this candidate to future work on the same project?',
|
|
73
|
+
criteria: [
|
|
74
|
+
'Discard: no durable value',
|
|
75
|
+
'Low: occasionally useful context',
|
|
76
|
+
'Normal: useful project memory',
|
|
77
|
+
'High: important decision or reliable procedure',
|
|
78
|
+
'Exceptional: critical safety rule or foundational invariant',
|
|
79
|
+
],
|
|
80
|
+
},
|
|
81
|
+
contains_sensitive_material: {
|
|
82
|
+
type: 'noul',
|
|
83
|
+
instructions: 'Does the already-redacted candidate still appear to contain private credentials, personal identity, or confidential machine details?',
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
}),
|
|
87
|
+
});
|
|
88
|
+
if (!response.ok)
|
|
89
|
+
throw new Error(`Jev request failed with status ${response.status}`);
|
|
90
|
+
const payload = await response.json();
|
|
91
|
+
const answers = payload.answers;
|
|
92
|
+
// Do not coerce partial provider output. Throwing here becomes a
|
|
93
|
+
// content-free `provider_failure` record at the shadow boundary.
|
|
94
|
+
if (!answers || answers.should_store?.type !== 'noul' || answers.memory_type?.type !== 'choice'
|
|
95
|
+
|| answers.salience_band?.type !== 'score' || answers.contains_sensitive_material?.type !== 'noul') {
|
|
96
|
+
throw new Error('Malformed Jev response');
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
shouldStore: finiteProbability(answers.should_store.noul, 'should_store'),
|
|
100
|
+
memoryType: memoryType(answers.memory_type.choice),
|
|
101
|
+
memoryTypeConfidence: finiteProbability(answers.memory_type.confidence, 'memory_type confidence'),
|
|
102
|
+
salienceBand: salienceBand(answers.salience_band.score),
|
|
103
|
+
provider: 'jev',
|
|
104
|
+
containsSensitiveMaterial: finiteProbability(answers.contains_sensitive_material.noul, 'contains_sensitive_material'),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function requestedMode(env) {
|
|
113
|
+
const value = env.HUMEMORY_JEV_MODE?.trim().toLowerCase();
|
|
114
|
+
return value === 'shadow' || value === 'advisory' ? value : 'off';
|
|
115
|
+
}
|
|
116
|
+
/** API-key presence alone is inert. Advisory is deliberately capped to shadow. */
|
|
117
|
+
export function resolveConfiguredJevAdvisor(env = process.env, fetchImpl) {
|
|
118
|
+
const requested = requestedMode(env);
|
|
119
|
+
if (requested === 'off')
|
|
120
|
+
return { requestedMode: requested, effectiveMode: 'off' };
|
|
121
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim();
|
|
122
|
+
if (!apiKey) {
|
|
123
|
+
return {
|
|
124
|
+
requestedMode: requested,
|
|
125
|
+
effectiveMode: 'shadow',
|
|
126
|
+
unavailableReason: 'missing_api_key',
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
requestedMode: requested,
|
|
131
|
+
effectiveMode: 'shadow',
|
|
132
|
+
advisor: new JevMemoryAdvisor({
|
|
133
|
+
apiKey,
|
|
134
|
+
model: env.HUMEMORY_JEV_MODEL?.trim() || 'jev-latest',
|
|
135
|
+
timeoutMs: Number(env.HUMEMORY_JEV_TIMEOUT_MS ?? 3_000),
|
|
136
|
+
fetch: fetchImpl,
|
|
137
|
+
}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { rename } from 'fs/promises';
|
|
2
2
|
import type { LLMClient } from '../core/llm-generator.js';
|
|
3
|
+
import type { MemoryAdvisor, ShadowDecisionReporter } from './memory-advisor.js';
|
|
3
4
|
export interface MaintenanceJob {
|
|
4
5
|
version: 1;
|
|
5
6
|
id: string;
|
|
@@ -34,6 +35,8 @@ export interface WorkerOptions {
|
|
|
34
35
|
queueDir: string;
|
|
35
36
|
dbPath: string;
|
|
36
37
|
client?: LLMClient;
|
|
38
|
+
memoryAdvisor?: MemoryAdvisor;
|
|
39
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
37
40
|
llmTimeoutMs?: number;
|
|
38
41
|
maxJobs?: number;
|
|
39
42
|
maxAttempts?: number;
|
|
@@ -221,6 +221,8 @@ export async function processMaintenanceQueue(options) {
|
|
|
221
221
|
directory: job.directory,
|
|
222
222
|
maxLearnings: job.maxLearnings,
|
|
223
223
|
client: options.client,
|
|
224
|
+
memoryAdvisor: options.memoryAdvisor,
|
|
225
|
+
advisorReporter: options.advisorReporter,
|
|
224
226
|
llmTimeoutMs: options.llmTimeoutMs,
|
|
225
227
|
source: 'hook',
|
|
226
228
|
agent: job.agent,
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import type { LLMClient } from '../core/llm-generator.js';
|
|
17
17
|
import type { Clock } from '../core/clock.js';
|
|
18
|
+
import { type MemoryAdvisor, type ShadowDecisionReporter } from './memory-advisor.js';
|
|
18
19
|
import { type WorkerResult } from './maintenance-queue.js';
|
|
19
20
|
import { type CodexImportResult } from './codex-import.js';
|
|
20
21
|
import { type KimiImportResult } from './kimi-import.js';
|
|
@@ -38,6 +39,9 @@ export interface MaintenancePassOptions {
|
|
|
38
39
|
opencodeRun?: OpenCodeCommandRunner;
|
|
39
40
|
opencodeCommand?: string;
|
|
40
41
|
client?: LLMClient;
|
|
42
|
+
/** `false` is an explicit test/operator override even when env selects shadow mode. */
|
|
43
|
+
memoryAdvisor?: MemoryAdvisor | false;
|
|
44
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
41
45
|
llmTimeoutMs?: number;
|
|
42
46
|
maxJobs?: number;
|
|
43
47
|
clock?: Clock;
|
|
@@ -55,14 +59,20 @@ export interface MaintenancePassResult {
|
|
|
55
59
|
}
|
|
56
60
|
export declare function defaultQueueDir(): string;
|
|
57
61
|
export declare function defaultDbPath(): string;
|
|
58
|
-
export declare function defaultLlmTimeoutMs(): number;
|
|
62
|
+
export declare function defaultLlmTimeoutMs(dbPath?: string): number;
|
|
59
63
|
export declare function configuredIntervalMs(): number;
|
|
60
64
|
/**
|
|
61
65
|
* The LLM the pass consolidates with. 'none' (the default) keeps consolidation
|
|
62
66
|
* deterministic and network-free; there is no API key on the production machine
|
|
63
|
-
* and none wanted, so
|
|
67
|
+
* and none wanted, so CLI providers use the logged-in subscription instead.
|
|
68
|
+
* Local provider settings require enabled=true; an environment override remains explicit.
|
|
64
69
|
*/
|
|
65
|
-
export declare function resolveMaintenanceClient(timeoutMs?: number): Promise<LLMClient | undefined>;
|
|
70
|
+
export declare function resolveMaintenanceClient(timeoutMs?: number | undefined, dbPath?: string, queueDir?: string): Promise<LLMClient | undefined>;
|
|
71
|
+
/** Resolve Jev only at executable entry points, never inside the hermetic pass. */
|
|
72
|
+
export declare function resolveMaintenanceAdvisor(dbPath?: string): {
|
|
73
|
+
memoryAdvisor?: MemoryAdvisor;
|
|
74
|
+
advisorReporter?: ShadowDecisionReporter;
|
|
75
|
+
};
|
|
66
76
|
/**
|
|
67
77
|
* Import, then drain, then record. Every producer is isolated: a missing or
|
|
68
78
|
* unreadable runtime must never stall the queue or another producer.
|