create-ai-memory 0.11.3 → 0.13.0

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/README.md CHANGED
@@ -189,8 +189,10 @@ off last time.
189
189
  **Getting started**
190
190
 
191
191
  - [Quickstart](#quickstart)
192
+ - [Benchmarks](#benchmarks)
192
193
  - [Install](#install)
193
194
  - [Commands](#commands)
195
+ - [How search works](#how-search-works)
194
196
 
195
197
  </td>
196
198
  <td valign="top" width="33%">
@@ -199,6 +201,7 @@ off last time.
199
201
 
200
202
  - [Session skills](#session-skills-optional)
201
203
  - [Your vault](#your-vault)
204
+ - [Open Knowledge Format](#open-knowledge-format)
202
205
  - [Add another agent](#add-another-agent)
203
206
  - [Integrations](#integrations)
204
207
  - [Configuration](#configuration)
@@ -233,6 +236,60 @@ off last time.
233
236
  | **Guardrails built in** | Every write is checked to stay inside the vault, and a commit hook refuses commits made without the vault context loaded. |
234
237
  | **Zero runtime deps** | No daemon, no database, no API key, no server. It runs in your shell. |
235
238
 
239
+ ## Benchmarks
240
+
241
+ Measured on a real 495-note vault (4.9 MB of Markdown), macOS, warm cache.
242
+ Every number below is reproducible with the command beside it.
243
+
244
+ **Tokens** — what the agent pays, every session
245
+
246
+ | | before | after | |
247
+ |---|---|---|---|
248
+ | Launch prompt | 7,207 | **4,321** | −40%, mirrored notes injected once ([why](#mirrored-notes-are-not-injected-twice)) |
249
+ | Search result, common term | 10,234 | **1,752** | −83%, bounded output ([why](#how-search-works)) |
250
+ | Lesson index, 96 lessons | — | **+829** | ~8 tokens per lesson, names only ([why](#lessons-are-indexed-not-injected)) |
251
+
252
+ ```sh
253
+ # launch prompt
254
+ ai-context | wc -c # chars; divide by ~4 for tokens
255
+ # search output, bounded vs not
256
+ ai-mem-search postgres | wc -c
257
+ AI_MEM_SEARCH_LIMIT=999999 ai-mem-search postgres | wc -c
258
+ ```
259
+
260
+ **Speed**
261
+
262
+ | | |
263
+ |---|---|
264
+ | Search, common term, 238 hits | **0.07 s** |
265
+ | Shell startup cost of the module | **< 0.01 s** |
266
+ | Recency sort, v0.11.0 regression fix | 25.4 s → **0.54 s** (47×) |
267
+
268
+ ```sh
269
+ time ai-mem-search postgres >/dev/null
270
+ time zsh -c 'source shell/ai-mem.zsh'
271
+ ```
272
+
273
+ The 47× is worth stating plainly because it was self-inflicted. The sort
274
+ spawned two subprocesses per matched line -- about 18,000 processes for one
275
+ query -- while the `grep` underneath it took 0.16 s. Benchmarking `grep`
276
+ alone said the command was fast; benchmarking the command said otherwise.
277
+ A regression guard now bounds it, with the bound set by measuring both
278
+ implementations rather than guessing.
279
+
280
+ **Footprint**
281
+
282
+ | | |
283
+ |---|---|
284
+ | Runtime dependencies | **0** |
285
+ | Package | **35 kB** (99.7 kB unpacked, 19 files) |
286
+ | Index, daemon, database, embeddings | **none** — a note is searchable the moment it is written |
287
+ | Tests | **153**, no network, no framework |
288
+
289
+ ```sh
290
+ npm pack --dry-run && zsh tests/run.sh
291
+ ```
292
+
236
293
  ## Install
237
294
 
238
295
  Pick whichever fits how you manage your shell. All paths end at the same place.
@@ -275,12 +332,187 @@ optional. Set `AI_MEM_ROOT` in `~/.zshrc` first if you do not want the default
275
332
  | `ai-context [project]` | Print the vault context block for the current repo, and arm the git commit guard |
276
333
  | `ai-note <text>` | Append a timestamped note to today's session log while you work |
277
334
  | `ai-lesson <topic-slug> <problem> <solution>` | Append a dated Problem/Solution entry to a cross-project `_lessons/<topic-slug>.md` -- decisions, mistakes, solutions worth recalling outside the current project |
278
- | `ai-mem-lint` | Check the vault's links: orphaned session logs, dangling `previous` links, unreferenced project notes |
335
+ | `ai-mem-lint [--fix]` | Check the vault's links: orphaned session logs, dangling `previous` links, unreferenced project notes, and notes missing the `type:` field. `--fix` backfills `type:` into session logs written before the field existed |
279
336
  | `ai-mem-search <term> [project]` | Case-insensitive literal search across the vault (or one project's logs), newest match first. Paths print relative to a root stated once in the header. Output is capped (`AI_MEM_SEARCH_LIMIT`, default 40) with an explicit `N hidden` notice, because the usual caller is an agent with a finite context window. Also resolves any `[[wikilink]]` on a matched line to its project note -- one hop out along the graph, always on, not a flag to remember |
280
337
  | `ai-mem-vault-backup` | Commit and push the vault if it's git-backed. `ai-note`/`ai-lesson` already call this; use it directly after editing a session log or project note by hand |
281
338
 
282
339
  Project is auto-resolved from the current git repo; pass a name to override.
283
340
 
341
+ ## How search works
342
+
343
+ Searching the vault reads your notes directly, every time. Nothing is
344
+ prepared in advance: no index to rebuild, no background service, no
345
+ embeddings to regenerate, nothing that can quietly fall out of date. A note
346
+ is findable the second you write it.
347
+
348
+ ```mermaid
349
+ flowchart TD
350
+ A(["You look for a word"]) --> B{"Did you name<br/>a project?"}
351
+ B -->|"no"| C["Look through<br/>every note you have"]
352
+ B -->|"yes"| D["Look only inside<br/>that project"]
353
+ C --> E["Read them all.<br/>Capitals don't matter.<br/>Punctuation means itself."]
354
+ D --> E
355
+ E -->|"found nothing"| F["<b>Says so, plainly.</b><br/>Never a blank screen you<br/>could mistake for 'none exist'"]
356
+ E -->|"found something"| G["Newest first"]
357
+ G --> H["Show the first 40<br/>and say how many more there are"]
358
+ H --> I["Follow any linked note one step,<br/>with a one-line summary of it"]
359
+ I --> J(["What you read"])
360
+
361
+ classDef ask fill:#0d9488,stroke:#0f766e,color:#fff
362
+ classDef care fill:#b45309,stroke:#92400e,color:#fff
363
+ classDef done fill:#1e3a8a,stroke:#1e40af,color:#fff
364
+ class A ask
365
+ class F care
366
+ class J done
367
+ ```
368
+
369
+ Two boxes are shaded because they are the ones that matter: an empty result
370
+ that **says** it is empty, and an output short enough to read to the end.
371
+
372
+ That is the whole idea. The rest of this section is the mechanism -- one
373
+ `grep -rniF`, then a sort, then a cap -- and why each piece is the way it is.
374
+ Every flag exists because the alternative produced a wrong answer on a real
375
+ vault. Skip it unless you are changing the code.
376
+
377
+ ```console
378
+ $ ai-mem-search prisma
379
+ 238 match(es) for 'prisma'
380
+ paths below /Users/you/_Ai_Memory
381
+ --
382
+ _session_logs/checkout-api/checkout-api-2026-08-31_00-00-00.md:56: - **A green deploy log is not evidence a migration ran.** Verify against `_prisma_migrations`.
383
+ _session_logs/checkout-api/checkout-api-2026-08-31_00-00-00.md:55: - **`prisma migrate deploy` cannot see `prisma/migrations/<name>.sql`.** Only `<name>/migration.sql`. It skips loose files silently -- a [...]
384
+ ...
385
+ --
386
+ showing 40 of 238 (198 hidden) -- narrow with: ai-mem-search 'prisma' <project>, or raise AI_MEM_SEARCH_LIMIT
387
+ ```
388
+
389
+ **Case-insensitive (`-i`).** A false empty state is the worst answer a memory
390
+ tool can give, because it is indistinguishable from the truth -- and the
391
+ explicit `no matches` message is exactly what makes it look authoritative.
392
+ Measured on a real vault: `precompact` found 0 matches case-sensitively and 3
393
+ with `-i`; `Postgres` found 56 versus 90.
394
+
395
+ **Literal, not regex (`-F`).** The caller is usually an agent passing free
396
+ text, where a stray `.`, `(` or `|` must match itself. `ai-mem-search .env`
397
+ finds `.env`, not every four-character string ending in `env`.
398
+
399
+ **Newest first.** The sort key is the `YYYY-MM-DD_HH-MM-SS` embedded in the
400
+ log filename. For a time series the most recent match is usually the relevant
401
+ one, so a large result set stays useful at a glance without any relevance
402
+ ranking. Files with no timestamp in the name (`_Global_Profile.md`, project
403
+ notes) sort last.
404
+
405
+ **Bounded output.** The count comes first, before the results -- you need the
406
+ size of the result set to interpret it. Then at most `AI_MEM_SEARCH_LIMIT`
407
+ lines (default 40), and if anything was withheld, an explicit `N hidden` line
408
+ with the command to narrow. This is for the agent, not for you: an unbounded
409
+ dump of a common term ran ~29k tokens, overflowed the host's tool-response
410
+ cap, and got silently truncated -- leaving the agent unable to tell "hidden"
411
+ from "absent". Near-miss padding is also the most damaging kind of distractor
412
+ for a model, so fewer clean hits beat more of them.
413
+
414
+ **Compact lines.** The vault root is printed once in the header and stripped
415
+ from every result path (a third to a half of all output bytes on a real
416
+ vault, no information lost). Lines longer than 200 characters are clamped
417
+ with `[...]`, since prose notes routinely run long.
418
+
419
+ **One hop out.** Any `[[wikilink]]` on a matched line is resolved to its
420
+ project note and shown with a one-line excerpt under `one hop out:`. A
421
+ `_lessons` entry names the projects it came from, so a hit there tells you
422
+ where it happened without a second search. Always on, not a flag to remember.
423
+
424
+ ```console
425
+ $ ai-mem-search '[[create-ai-memory]]'
426
+ 11 match(es) for '[[create-ai-memory]]'
427
+ ...
428
+ --
429
+ one hop out:
430
+ [[create-ai-memory]] -> /Users/you/_Ai_Memory/_projects/create-ai-memory.md
431
+ * **Current Objective:** ship the vault-backup fix
432
+ ```
433
+
434
+ (That query is also `-F` earning its keep: `[[` is matched literally, not as
435
+ a character class.)
436
+
437
+ **Scoping.** A second argument restricts the search to one project's session
438
+ logs -- `ai-mem-search postgres checkout-api`. Unknown project names fail
439
+ explicitly rather than silently searching everything.
440
+
441
+ ### Mirrored notes are not injected twice
442
+
443
+ `_Standards.md` ships declaring `mirror_of: _Global_Profile.md` in its
444
+ frontmatter. The mirror exists so the shared rules stay visible wherever only
445
+ one of the two notes is read -- but the launch prompt reads *both*, so
446
+ injecting both in full restates text the model has just finished reading.
447
+
448
+ When a note declares `mirror_of: <sibling note>`, only the lines that
449
+ actually differ from that source are injected, under a one-line marker
450
+ naming what was elided:
451
+
452
+ ```text
453
+ - Standards:
454
+ (mirror of _Global_Profile.md, shown above -- only the lines that differ from it are repeated here)
455
+ ## Standards Addendum
456
+ * Keep `_Standards.md` and `_Global_Profile.md` in lockstep when shared rules change.
457
+ ...
458
+ ```
459
+
460
+ Measured on a real vault: 72 of the mirror's 80 unique lines were already
461
+ verbatim in its source, and the launch prompt went from **~7,200 to ~4,300
462
+ tokens -- a 40% cut with nothing lost**, paid once per session per agent.
463
+
464
+ Matching is exact, line by line, so anything reworded is kept -- a near-match
465
+ is a real edit. The comparison fails **open** in every uncertain case: no
466
+ frontmatter, a missing source, a `mirror_of` containing a path separator, or
467
+ a diff that would leave nothing all inject the note in full. Injecting a note
468
+ twice costs tokens; dropping one costs the agent context it was promised, and
469
+ those are not the same kind of mistake.
470
+
471
+ ### Lessons are indexed, not injected
472
+
473
+ `ai-lesson` writes to `_lessons/<topic-slug>.md`, and those entries are the
474
+ most reusable thing in the vault -- they are the only notes that are true
475
+ across projects. They are also the hardest for an agent to find, because
476
+ finding one by search means guessing a term for knowledge it does not know
477
+ it has.
478
+
479
+ So the launch prompt lists **every lesson slug and no lesson bodies**:
480
+
481
+ ```text
482
+ - Lessons already recorded (96), listed by topic slug only -- the bodies are NOT
483
+ included here. If one looks relevant to the task at hand, read it with
484
+ `ai-mem-search <slug>` before solving the problem again from scratch.
485
+ prisma-connection-pool-exhaustion, decimal-money-precision-js, react-hydration-mismatch, ...
486
+ ```
487
+
488
+ A slug is the lesson already compressed: `prisma-connection-pool-exhaustion`
489
+ tells you whether to open it without opening it. That is the trade -- roughly
490
+ 8 tokens per lesson to convert a blind guess into a precise search. 96
491
+ lessons cost about 830 tokens.
492
+
493
+ Newest first, capped at `AI_MEM_LESSON_INDEX_LIMIT` (200), with a `+N older`
494
+ note when it truncates. The cap is not decoration: past a few hundred
495
+ entries, most titles are irrelevant to any given session, and a long tail of
496
+ near-miss titles is the most damaging kind of distractor for a model -- the
497
+ same reason `ai-mem-search` bounds its own output. A vault with no lessons
498
+ adds nothing to the prompt at all.
499
+
500
+ ### What it deliberately is not
501
+
502
+ Substring matching, not word matching: `git` also hits `github` and
503
+ `gitignore`. No stemming, no fuzzy matching, no synonyms, no relevance
504
+ ranking, no vector search. A term you half-remember will miss.
505
+
506
+ That is a real limit, and the way around it is the search strategy rather
507
+ than the search engine: **start broad and narrow down.** A first query that is
508
+ too specific is the usual way to miss what you were looking for. Search
509
+ `postgres` before `postgres connection pool timeout`, then add the project
510
+ argument once you can see roughly where the answer lives.
511
+
512
+ Returns non-zero on no matches, a missing term, or an unknown project, so it
513
+ composes in a script.
514
+
515
+
284
516
  ## Session skills (optional)
285
517
 
286
518
  You define your own per-session skills; create-ai-memory ships none. At launch it asks
@@ -368,6 +600,61 @@ Notes are created from templates on first use and never overwritten. Edit
368
600
  `_Global_Profile.md` and `_Standards.md` to make them yours; the shipped versions
369
601
  are sanitized placeholders.
370
602
 
603
+ ## Open Knowledge Format
604
+
605
+ [Open Knowledge Format](https://github.com/GoogleCloudPlatform/open-knowledge-format)
606
+ (OKF) is Google's vendor-neutral spec for portable, agent-readable knowledge.
607
+ An OKF *bundle* is simply a directory tree of markdown files — the unit of
608
+ distribution, shippable as a git repo, tarball, or zip, and readable by any
609
+ agent, static file server, Obsidian, MkDocs, or graph viewer without a
610
+ translation layer.
611
+
612
+ Your vault is one. That is convergence rather than adoption: both bet on
613
+ plain Markdown in a directory tree, in git, with no runtime.
614
+
615
+ The spec is deliberately small. [It requires no file at the bundle
616
+ root](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
617
+ — `index.md` and `log.md` are optional — and names exactly one required
618
+ frontmatter key: *"`type` is the only always-required key; a concept carrying
619
+ just `type` is fully conformant."*
620
+
621
+ | OKF | Here |
622
+ |---|---|
623
+ | Markdown files in a directory hierarchy | ✅ `_projects/`, `_lessons/`, `_session_logs/`, `_proposals/` |
624
+ | YAML frontmatter | ✅ every note |
625
+ | **`type` — the only required key** | ✅ `ai-project-context`, `ai-lesson`, `ai-session-log`, `ai-global-profile`, `ai-standards` |
626
+ | Recommended: `title`, `description`, `resource`, `tags` | ⚠️ partial — notes carry their own fields instead |
627
+ | Cross-links as standard markdown links | ⚠️ `[[wikilink]]` instead |
628
+ | `index.md` / `log.md` | optional in the spec; not generated here |
629
+ | No SDK, no account, git-versionable | ✅ |
630
+
631
+ One real deviation: **links stay Obsidian-style.** The vault is meant to be
632
+ opened in Obsidian, where the graph view and backlinks are much of why anyone
633
+ keeps one, and `ai-mem-search` resolves `[[wikilinks]]` itself. A strict OKF
634
+ consumer would not follow them — though the spec already requires consumers
635
+ to tolerate links that do not resolve.
636
+
637
+ No `index.md` is generated, and that is a choice rather than a gap: nothing
638
+ here reads one, `grep` does not consult it, and a materialized index is
639
+ exactly the thing that goes stale when a file is renamed. The lesson index is
640
+ built at launch from the directory itself for the same reason.
641
+
642
+ Session logs predate the `type` field, so a vault that has been in use holds
643
+ notes without it. `ai-mem-lint` counts them, and `ai-mem-lint --fix`
644
+ backfills:
645
+
646
+ ```console
647
+ $ ai-mem-lint
648
+ 350 session log(s) missing the `type:` frontmatter field (Open Knowledge Format requires it). Fix with: ai-mem-lint --fix
649
+
650
+ $ ai-mem-lint --fix
651
+ backfilled `type: ai-session-log` into 350 session log(s)
652
+ ```
653
+
654
+ It edits in place, preserves existing frontmatter and body, opens a
655
+ frontmatter block for a note that had none, and is idempotent — running it
656
+ twice does not stack a second field.
657
+
371
658
  ## Add another agent
372
659
 
373
660
  Launchers are not hardcoded. Each agent is one small adapter, and the
@@ -377,7 +664,7 @@ Launchers are not hardcoded. Each agent is one small adapter, and the
377
664
  1. Define the adapter in `shell/adapters.zsh`. It receives `$1` memory prompt,
378
665
  `$2` mode block, and `$3` onward extra args:
379
666
  ```zsh
380
- _ai_adapter_aider() {
667
+ __ai_adapter_aider() {
381
668
  local memory_prompt="$1"
382
669
  aider --message "$memory_prompt"
383
670
  }
@@ -388,6 +675,13 @@ Launchers are not hardcoded. Each agent is one small adapter, and the
388
675
  ```
389
676
  3. `aider-start` now exists. No core edits.
390
677
 
678
+ Name private helpers with **two** leading underscores (`__ai_adapter_aider`,
679
+ not `_ai_adapter_aider`). Claude Code replays a snapshot of your interactive
680
+ shell for every command it runs, and that snapshot drops single-underscore
681
+ function names -- the filter targets zsh's completion functions, but it takes
682
+ private helpers with it. A one-underscore helper simply will not exist inside
683
+ an agent-run command.
684
+
391
685
  ## Integrations
392
686
 
393
687
  ### Claude Code hooks
@@ -428,6 +722,8 @@ git -C <repo> config core.hooksPath .githooks
428
722
  | `AI_MEM_ROOT` | `$HOME/.ai-memory/_Ai_Memory` | Vault root. Point at any folder, including an existing Obsidian vault |
429
723
  | `AI_MEM_AGENTS` | `claude codex gemini cursor opencode` | Space-separated agents to generate `-start` functions for |
430
724
  | `AI_MEM_SKILLS` / `AI_MEM_SKILL_ORDER` | empty | Your per-session skills (see above) |
725
+ | `AI_MEM_LESSON_INDEX_LIMIT` | `200` | Lesson slugs listed in the launch prompt before it truncates to the newest. Names only -- bodies are never injected |
726
+ | `AI_MEM_SEARCH_LIMIT` | `40` | Result lines `ai-mem-search` prints before it truncates. The default is sized for an agent's context window; raise it when you are reading the output yourself (see [How search works](#how-search-works)) |
431
727
 
432
728
  ## Why plain files
433
729
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ai-memory",
3
- "version": "0.11.3",
3
+ "version": "0.13.0",
4
4
  "description": "Persistent, agent-agnostic session memory for AI coding CLIs (Claude Code, Codex, Gemini, Cursor, opencode). One Markdown vault, any agent.",
5
5
  "bin": {
6
6
  "create-ai-memory": "bin/create-ai-memory.js"
@@ -1,22 +1,22 @@
1
1
  # Agent launch adapters for ai-mem.
2
2
  #
3
- # One function per agent: _ai_adapter_<name>. It receives:
3
+ # One function per agent: __ai_adapter_<name>. It receives:
4
4
  # $1 memory_prompt — assembled vault context + session-mode block
5
5
  # $2 mode_block — just the session-mode instructions (may be empty)
6
6
  # $3… extra CLI args — anything passed to <name>-start (e.g. files to open)
7
7
  #
8
- # Add a new agent (opencode, aider, …) by defining _ai_adapter_<name> here and
8
+ # Add a new agent (opencode, aider, …) by defining __ai_adapter_<name> here and
9
9
  # listing <name> in AI_MEM_AGENTS (see ai-mem.zsh). No core edits needed.
10
10
 
11
11
  # Codex: --add-dir grants read access to the vault; prompt is positional.
12
- _ai_adapter_codex() {
12
+ __ai_adapter_codex() {
13
13
  local memory_prompt="$1"
14
14
  codex --add-dir "$AI_MEM_ROOT" "$memory_prompt"
15
15
  }
16
16
 
17
17
  # Claude Code: --add-dir is variadic, so the prompt must come FIRST or it gets
18
18
  # swallowed as a bogus directory and Claude starts with no initial prompt.
19
- _ai_adapter_claude() {
19
+ __ai_adapter_claude() {
20
20
  local memory_prompt="$1" mode_block="$2"
21
21
  if [[ -n "$mode_block" ]]; then
22
22
  claude "$memory_prompt" --add-dir "$AI_MEM_ROOT" --append-system-prompt "$mode_block"
@@ -26,7 +26,7 @@ _ai_adapter_claude() {
26
26
  }
27
27
 
28
28
  # Gemini CLI: --include-directories for vault access, -i for the initial prompt.
29
- _ai_adapter_gemini() {
29
+ __ai_adapter_gemini() {
30
30
  local memory_prompt="$1"
31
31
  gemini --include-directories "$AI_MEM_ROOT" -i "$memory_prompt"
32
32
  }
@@ -34,7 +34,7 @@ _ai_adapter_gemini() {
34
34
  # Cursor has no CLI prompt path, so persist the session's skill choices as a
35
35
  # managed always-apply rule that this adapter rewrites each launch (and clears
36
36
  # when nothing is selected).
37
- _ai_adapter_cursor() {
37
+ __ai_adapter_cursor() {
38
38
  local memory_prompt="$1" mode_block="$2"
39
39
  shift 2
40
40
  local cursor_rule="$HOME/.cursor/rules/_ai-session.mdc"
@@ -62,14 +62,14 @@ _ai_adapter_cursor() {
62
62
  # opencode (sst/opencode): the TUI seeds its first message from --prompt. It has
63
63
  # no --add-dir, so vault access rides on the inlined profile/standards in the
64
64
  # prompt plus the absolute note paths the agent can read on demand.
65
- _ai_adapter_opencode() {
65
+ __ai_adapter_opencode() {
66
66
  local memory_prompt="$1"
67
67
  opencode --prompt "$memory_prompt"
68
68
  }
69
69
 
70
70
  # --- Example: add another agent by defining its adapter and listing it in
71
71
  # AI_MEM_AGENTS. aider takes the initial instruction via --message:
72
- # _ai_adapter_aider() {
72
+ # __ai_adapter_aider() {
73
73
  # local memory_prompt="$1"
74
74
  # aider --message "$memory_prompt"
75
75
  # }
package/shell/ai-mem.zsh CHANGED
@@ -1,8 +1,22 @@
1
1
  # === AI CLI + Obsidian memory ===
2
2
  # Portable, agent-agnostic session memory. Source this from ~/.zshrc after
3
3
  # exporting AI_MEM_ROOT to point at your vault. Zsh-only (uses print -r, ${(s)},
4
- # and associative arrays). Add a new agent by defining _ai_adapter_<name> in adapters.zsh and
4
+ # and associative arrays). Add a new agent by defining __ai_adapter_<name> in adapters.zsh and
5
5
  # listing it in AI_MEM_AGENTS; a matching <name>-start function is generated.
6
+ #
7
+ # Private helpers are named __ai_* with TWO leading underscores, deliberately.
8
+ # Claude Code snapshots the interactive shell and replays that snapshot for
9
+ # every agent-run command, and its snapshot drops every function whose name
10
+ # starts with a single underscore -- the filter is aimed at zsh's ~1000
11
+ # completion functions (_git, _ssh, ...), and single-underscore private
12
+ # helpers are collateral. Measured on one real shell: 1018 single-underscore
13
+ # functions defined, 0 survived; all 9 double-underscore ones did.
14
+ #
15
+ # The failure that causes is silent, not loud. A public function survives,
16
+ # calls a helper that no longer exists, and carries on: ai-mem-vault-backup
17
+ # printed "nothing to commit" and exited 0 while backing up nothing, which
18
+ # an agent then reports as success. Do not "tidy" these back to one
19
+ # underscore -- tests/run.sh asserts the naming for exactly this reason.
6
20
 
7
21
  # Directory holding this module, used to source sibling files.
8
22
  AI_MEM_HOME="${0:A:h}"
@@ -11,6 +25,19 @@ AI_MEM_HOME="${0:A:h}"
11
25
  # vault on first use so install.sh is optional (plugin-manager installs work).
12
26
  AI_MEM_TEMPLATE_SRC="${AI_MEM_HOME:h}/vault-template"
13
27
 
28
+ # Fingerprint of the module files, recorded at source time and re-checked at
29
+ # launch. A shell keeps whatever function definitions it loaded at startup:
30
+ # editing these files, or upgrading the package, changes nothing in a
31
+ # terminal that is already open. That is a silent trap rather than an
32
+ # obvious one -- the launcher still runs, still reports success, and quietly
33
+ # uses whatever behaviour was current whenever this terminal was opened,
34
+ # which can be months. Comparing the two makes the staleness visible.
35
+ # cksum is POSIX, so this needs no macOS/Linux branch.
36
+ __ai_mem_fingerprint() {
37
+ cksum "$AI_MEM_HOME/ai-mem.zsh" "$AI_MEM_HOME/adapters.zsh" 2>/dev/null \
38
+ | awk '{ printf "%s-", $1 }'
39
+ }
40
+ export AI_MEM_SOURCED_FINGERPRINT="$(__ai_mem_fingerprint)"
14
41
  # Vault root. Override in ~/.zshrc; defaults to a hidden dir under $HOME.
15
42
  : "${AI_MEM_ROOT:=$HOME/.ai-memory/_Ai_Memory}"
16
43
  if [[ -d "$AI_MEM_ROOT" ]]; then
@@ -22,12 +49,17 @@ export AI_MEM_STANDARDS="$AI_MEM_ROOT/_Standards.md"
22
49
  export AI_MEM_PROJECT_DIR="$AI_MEM_ROOT/_projects"
23
50
  export AI_MEM_SESSION_DIR="$AI_MEM_ROOT/_session_logs"
24
51
 
25
- _ai_mem_guard() {
26
- local path="${1:-}"
27
- case "$path" in
52
+ # `note_path`, not `path`: in zsh `path` is the special array tied to $PATH,
53
+ # so `local path=...` inside a function replaces command lookup with the
54
+ # string being passed in and every external command becomes "command not
55
+ # found". This function only uses builtins, so it survived the mistake -- but
56
+ # the next editor to add a `grep` here would not.
57
+ __ai_mem_guard() {
58
+ local note_path="${1:-}"
59
+ case "$note_path" in
28
60
  "$AI_MEM_ROOT"|"$AI_MEM_ROOT"/*) return 0 ;;
29
61
  *)
30
- echo "Refusing to touch non-memory path: $path"
62
+ echo "Refusing to touch non-memory path: $note_path"
31
63
  return 1
32
64
  ;;
33
65
  esac
@@ -40,7 +72,7 @@ _ai_mem_guard() {
40
72
  # outside this sourced shell, so it can't call this function directly).
41
73
  # No-ops silently if AI_MEM_ROOT isn't its own git repo; never fails the
42
74
  # caller on a push error (no network, no remote configured, etc).
43
- _ai_mem_vault_backup() {
75
+ __ai_mem_vault_backup() {
44
76
  local vault_git_root
45
77
  vault_git_root="$(git -C "${AI_MEM_ROOT:-}" rev-parse --show-toplevel 2>/dev/null || true)"
46
78
  [[ -n "$vault_git_root" ]] || return 0
@@ -60,7 +92,6 @@ _ai_mem_vault_backup() {
60
92
  rmdir "$lock_dir" 2>/dev/null
61
93
  fi
62
94
  return 0
63
- return 0
64
95
  }
65
96
 
66
97
  # Public entry point for anything that writes to the vault outside
@@ -68,9 +99,19 @@ _ai_mem_vault_backup() {
68
99
  # Session Outcome section directly and has no other reason to know this
69
100
  # function exists.
70
101
  ai-mem-vault-backup() {
102
+ # Fail loudly if the helper is absent. Without this the function still
103
+ # "works": HEAD does not move, so it prints "nothing to commit" and exits
104
+ # 0, and the agent reading that reports a successful backup of a vault
105
+ # nothing was written to. A wrong answer that looks like a right one is
106
+ # the worst outcome for a memory tool, so refuse instead of guessing.
107
+ if (( ! $+functions[__ai_mem_vault_backup] )); then
108
+ print -r -- "ai-mem-vault-backup: helper __ai_mem_vault_backup is not defined -- this shell's function table is incomplete (stale or filtered snapshot). Re-run in a fresh terminal, or commit and push \$AI_MEM_ROOT by hand." >&2
109
+ return 1
110
+ fi
111
+
71
112
  local before after
72
113
  before="$(git -C "${AI_MEM_ROOT:-}" rev-parse HEAD 2>/dev/null || true)"
73
- _ai_mem_vault_backup
114
+ __ai_mem_vault_backup
74
115
  after="$(git -C "${AI_MEM_ROOT:-}" rev-parse HEAD 2>/dev/null || true)"
75
116
  if [[ -z "$before" && -z "$after" ]]; then
76
117
  echo "ai-mem-vault-backup: vault isn't git-backed, nothing to do"
@@ -81,17 +122,62 @@ ai-mem-vault-backup() {
81
122
  fi
82
123
  }
83
124
  # Read a vault note only when it exists inside the memory root.
84
- _ai_mem_note_contents() {
85
- local path="${1:-}"
86
- if [[ -z "$path" || ! -f "$path" ]]; then
125
+ #
126
+ # A note may declare `mirror_of: <other-note>` in its frontmatter, as the
127
+ # shipped _Standards.md does for _Global_Profile.md. The mirror exists so the
128
+ # shared rules stay visible wherever only one of the two gets read -- but
129
+ # injecting BOTH in full into the SAME prompt restates text the model just
130
+ # finished reading. Measured on a real vault: 72 of the mirror's 80 unique
131
+ # lines were already verbatim in its source, ~2900 of the launch prompt's
132
+ # ~7200 tokens spent saying the same thing twice.
133
+ #
134
+ # So a mirror contributes only the lines that actually differ. This fails
135
+ # OPEN in every uncertain case -- no frontmatter, an unreadable or missing
136
+ # target, a target outside the vault, or a diff that would leave nothing --
137
+ # because injecting a note twice merely costs tokens, while dropping one
138
+ # costs the agent context it was promised.
139
+ __ai_mem_note_contents() {
140
+ local note_path="${1:-}"
141
+ if [[ -z "$note_path" || ! -f "$note_path" ]]; then
142
+ return 0
143
+ fi
144
+
145
+ __ai_mem_guard "$note_path" || return 1
146
+
147
+ # Read mirror_of from the frontmatter block only (lines 2..next `---`), so
148
+ # the word appearing in a note's prose can never be mistaken for a claim.
149
+ local mirror
150
+ mirror="$(sed -n '2,/^---$/p' "$note_path" 2>/dev/null | sed -n 's/^mirror_of:[[:space:]]*//p' | head -1)"
151
+ if [[ -z "$mirror" ]]; then
152
+ print -r -- "$(<"$note_path")"
153
+ return 0
154
+ fi
155
+
156
+ # A mirror names a sibling note, never a path. __ai_mem_guard matches on
157
+ # the string, so "$AI_MEM_ROOT/../../etc/passwd" would satisfy it -- and
158
+ # this value comes out of a file's frontmatter, so accepting a path here
159
+ # would turn any note into a request to read an arbitrary file. Rejecting
160
+ # every separator outright is both the safer rule and the simpler one.
161
+ local target="$AI_MEM_ROOT/$mirror"
162
+ if [[ "$mirror" == */* || ! -f "$target" ]]; then
163
+ print -r -- "$(<"$note_path")"
164
+ return 0
165
+ fi
166
+
167
+ # -x -F: drop only lines that are byte-for-byte identical to one in the
168
+ # source. Anything reworded stays, because a near-match is a real edit.
169
+ local unique
170
+ unique="$(grep -vxF -f "$target" -- "$note_path" 2>/dev/null)"
171
+ if [[ -z "${unique//[[:space:]]/}" ]]; then
172
+ print -r -- "(identical to ${mirror}; nothing further)"
87
173
  return 0
88
174
  fi
89
175
 
90
- _ai_mem_guard "$path" || return 1
91
- print -r -- "$(<"$path")"
176
+ print -r -- "(mirror of ${mirror}, shown above -- only the lines that differ from it are repeated here)"
177
+ print -r -- "$unique"
92
178
  }
93
179
 
94
- _ai_mem_resolve_project() {
180
+ __ai_mem_resolve_project() {
95
181
  # Prefer the git repo we are actually standing in. Otherwise `cd`-ing between
96
182
  # projects in one shell keeps a stale AI_MEM_ACTIVE_PROJECT pinned, so a later
97
183
  # claude-start writes its log under the wrong project's folder.
@@ -111,16 +197,16 @@ _ai_mem_resolve_project() {
111
197
  basename "$PWD"
112
198
  }
113
199
 
114
- _ai_mem_project_session_dir() {
200
+ __ai_mem_project_session_dir() {
115
201
  local project_name="${1:-}"
116
202
  if [[ -z "$project_name" ]]; then
117
- project_name="$(_ai_mem_resolve_project)"
203
+ project_name="$(__ai_mem_resolve_project)"
118
204
  fi
119
205
 
120
206
  print -r -- "$AI_MEM_SESSION_DIR/$project_name"
121
207
  }
122
208
 
123
- _ai_mem_graphify_repo_root() {
209
+ __ai_mem_graphify_repo_root() {
124
210
  local git_root=""
125
211
  git_root="$(git rev-parse --show-toplevel 2>/dev/null)" || true
126
212
  if [[ -n "$git_root" ]]; then
@@ -130,8 +216,8 @@ _ai_mem_graphify_repo_root() {
130
216
  fi
131
217
  }
132
218
 
133
- _ai_mem_graphify_context() {
134
- local repo_root="$(_ai_mem_graphify_repo_root)"
219
+ __ai_mem_graphify_context() {
220
+ local repo_root="$(__ai_mem_graphify_repo_root)"
135
221
  local graph_root="$repo_root/graphify-out"
136
222
  local graph_json="$graph_root/graph.json"
137
223
  local graph_report="$graph_root/GRAPH_REPORT.md"
@@ -157,22 +243,22 @@ _ai_mem_graphify_context() {
157
243
 
158
244
  # Returns the newest saved session log for the current project.
159
245
  # The active run gets a fresh log, so this only feeds carryover context.
160
- _ai_mem_latest_session_log() {
246
+ __ai_mem_latest_session_log() {
161
247
  local project_name="${1:-}"
162
248
  if [[ -z "$project_name" ]]; then
163
- project_name="$(_ai_mem_resolve_project)"
249
+ project_name="$(__ai_mem_resolve_project)"
164
250
  fi
165
251
 
166
252
  local latest=""
167
253
  local project_session_dir
168
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
254
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
169
255
 
170
256
  latest="$(find "$project_session_dir" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
171
257
  if [[ -z "$latest" ]]; then
172
258
  latest="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
173
259
  fi
174
260
  if [[ -n "$latest" ]]; then
175
- _ai_mem_guard "$latest" || return 1
261
+ __ai_mem_guard "$latest" || return 1
176
262
  print -r -- "$latest"
177
263
  fi
178
264
  }
@@ -180,7 +266,7 @@ _ai_mem_latest_session_log() {
180
266
  # Copy the shipped profile, standards, and templates into the vault on first use.
181
267
  # Idempotent and additive: it never overwrites a file the user already has, so a
182
268
  # plugin-manager install (source only, no install.sh) still gets a working vault.
183
- _ai_mem_ensure_vault() {
269
+ __ai_mem_ensure_vault() {
184
270
  [[ -d "$AI_MEM_TEMPLATE_SRC" ]] || return 0
185
271
  mkdir -p "$AI_MEM_PROJECT_DIR" "$AI_MEM_SESSION_DIR" "$AI_MEM_ROOT/_lessons"
186
272
  local rel
@@ -189,29 +275,29 @@ _ai_mem_ensure_vault() {
189
275
  _lessons/_lesson_template.md; do
190
276
  local src="$AI_MEM_TEMPLATE_SRC/$rel" dst="$AI_MEM_ROOT/$rel"
191
277
  if [[ -f "$src" && ! -f "$dst" ]]; then
192
- _ai_mem_guard "$dst" || return 1
278
+ __ai_mem_guard "$dst" || return 1
193
279
  cp "$src" "$dst"
194
280
  fi
195
281
  done
196
282
  }
197
283
 
198
- _ai_mem_prepare_session() {
284
+ __ai_mem_prepare_session() {
199
285
  local project_name="${1:-}"
200
286
  if [[ -z "$project_name" ]]; then
201
- project_name="$(_ai_mem_resolve_project)"
287
+ project_name="$(__ai_mem_resolve_project)"
202
288
  fi
203
289
 
204
- _ai_mem_ensure_vault || return 1
290
+ __ai_mem_ensure_vault || return 1
205
291
 
206
292
  local project_note="$AI_MEM_PROJECT_DIR/${project_name}.md"
207
293
  local project_session_dir
208
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
294
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
209
295
  local previous_session_note=""
210
- previous_session_note="$(_ai_mem_latest_session_log "$project_name")" || return 1
296
+ previous_session_note="$(__ai_mem_latest_session_log "$project_name")" || return 1
211
297
  local session_note="$project_session_dir/${project_name}-$(date +%Y-%m-%d_%H-%M-%S).md"
212
298
 
213
- _ai_mem_guard "$project_note" || return 1
214
- _ai_mem_guard "$session_note" || return 1
299
+ __ai_mem_guard "$project_note" || return 1
300
+ __ai_mem_guard "$session_note" || return 1
215
301
 
216
302
  mkdir -p "$AI_MEM_PROJECT_DIR" "$AI_MEM_SESSION_DIR" "$project_session_dir"
217
303
 
@@ -238,7 +324,7 @@ _ai_mem_prepare_session() {
238
324
  # Pull one "* **Label:** value" bullet out of a session log's fixed
239
325
  # "# Session Outcome" section. Reads the log directly — no separate file is
240
326
  # ever written, so there is nothing extra sitting in the vault.
241
- _ai_mem_session_field() {
327
+ __ai_mem_session_field() {
242
328
  local file="$1" label="$2" value
243
329
  [[ -f "$file" ]] || return 0
244
330
  value="$(grep -m1 -E "^\* \*\*${label}:\*\*" "$file" | sed -E "s|^\* \*\*${label}:\*\*[[:space:]]*||")"
@@ -250,7 +336,7 @@ _ai_mem_session_field() {
250
336
 
251
337
  # Defensive cap so one unusually long freeform bullet can't blow up the
252
338
  # prompt. Never triggers for the template's intended single-line bullets.
253
- _ai_mem_cap_field() {
339
+ __ai_mem_cap_field() {
254
340
  local text="$1" cap="${2:-500}" source_ref="$3"
255
341
  if (( ${#text} > cap )); then
256
342
  print -r -- "${text[1,$cap]}… (truncated, ${#text} chars total — see $source_ref)"
@@ -259,7 +345,44 @@ _ai_mem_cap_field() {
259
345
  fi
260
346
  }
261
347
 
262
- _ai_mem_context_prompt() {
348
+ # An agent cannot search for knowledge it does not know exists, and the
349
+ # lesson bodies are far too large to inject -- but a slug like
350
+ # prisma-connection-pool-exhaustion is already the lesson compressed to a
351
+ # handful of tokens. Listing the names turns a blind guess into a precise
352
+ # ai-mem-search, at roughly 4 tokens per lesson. Recognition is the point;
353
+ # recall is what the agent is bad at.
354
+ #
355
+ # Names only, never bodies. The cap exists because this stops paying for
356
+ # itself once most entries are irrelevant to the session at hand: a long
357
+ # tail of near-miss titles is the most damaging kind of distractor for a
358
+ # model, which is the same reason ai-mem-search bounds its own output.
359
+ # Newest first, so the cap drops the stalest rather than the alphabetically
360
+ # unlucky.
361
+ __ai_mem_lesson_index() {
362
+ local dir="$AI_MEM_ROOT/_lessons"
363
+ [[ -d "$dir" ]] || return 0
364
+
365
+ # (N) tolerate an empty dir, (.) files only, (om) newest mtime first,
366
+ # (:t:r) basename without the extension. Then drop _lesson_template.
367
+ local -a slugs
368
+ slugs=("$dir"/*.md(N.om:t:r))
369
+ slugs=(${slugs:#_*})
370
+ (( $#slugs )) || return 0
371
+
372
+ local limit="${AI_MEM_LESSON_INDEX_LIMIT:-200}"
373
+ local total=$#slugs extra=0
374
+ if (( total > limit )); then
375
+ extra=$(( total - limit ))
376
+ slugs=(${slugs[1,$limit]})
377
+ fi
378
+
379
+ print -r -- "- Lessons already recorded ($total), listed by topic slug only -- the bodies are NOT included here. If one looks relevant to the task at hand, read it with \`ai-mem-search <slug>\` before solving the problem again from scratch."
380
+ print -r -- " ${(j:, :)slugs}"
381
+ (( extra )) && print -r -- " (+$extra older, not listed; \`ls \$AI_MEM_ROOT/_lessons\` for the rest)"
382
+ return 0
383
+ }
384
+
385
+ __ai_mem_context_prompt() {
263
386
  local project_note="${1:-}"
264
387
  local previous_session_note="${2:-}"
265
388
  local session_note="${3:-}"
@@ -270,10 +393,10 @@ _ai_mem_context_prompt() {
270
393
  previous_session_label="$previous_session_note"
271
394
 
272
395
  local summary decisions blockers next
273
- summary="$(_ai_mem_session_field "$previous_session_note" 'High-Level Summary')"
274
- decisions="$(_ai_mem_session_field "$previous_session_note" 'Important Decisions')"
275
- blockers="$(_ai_mem_session_field "$previous_session_note" 'Constraints / Blockers')"
276
- next="$(_ai_mem_session_field "$previous_session_note" 'Next Step')"
396
+ summary="$(__ai_mem_session_field "$previous_session_note" 'High-Level Summary')"
397
+ decisions="$(__ai_mem_session_field "$previous_session_note" 'Important Decisions')"
398
+ blockers="$(__ai_mem_session_field "$previous_session_note" 'Constraints / Blockers')"
399
+ next="$(__ai_mem_session_field "$previous_session_note" 'Next Step')"
277
400
 
278
401
  if [[ -z "${AI_MEM_NO_DIGEST:-}" && ( -n "$summary" || -n "$decisions" || -n "$blockers" || -n "$next" ) ]]; then
279
402
  [[ -n "$summary" ]] || summary="—"
@@ -282,10 +405,10 @@ _ai_mem_context_prompt() {
282
405
  [[ -n "$next" ]] || next="—"
283
406
 
284
407
  previous_session_block="- Latest prior session ($previous_session_note), summarized below:"
285
- previous_session_block+=$'\n'"* **Summary:** $(_ai_mem_cap_field "$summary" 500 "$previous_session_note")"
286
- previous_session_block+=$'\n'"* **Decisions:** $(_ai_mem_cap_field "$decisions" 500 "$previous_session_note")"
287
- previous_session_block+=$'\n'"* **Blockers:** $(_ai_mem_cap_field "$blockers" 500 "$previous_session_note")"
288
- previous_session_block+=$'\n'"* **Next:** $(_ai_mem_cap_field "$next" 500 "$previous_session_note")"
408
+ previous_session_block+=$'\n'"* **Summary:** $(__ai_mem_cap_field "$summary" 500 "$previous_session_note")"
409
+ previous_session_block+=$'\n'"* **Decisions:** $(__ai_mem_cap_field "$decisions" 500 "$previous_session_note")"
410
+ previous_session_block+=$'\n'"* **Blockers:** $(__ai_mem_cap_field "$blockers" 500 "$previous_session_note")"
411
+ previous_session_block+=$'\n'"* **Next:** $(__ai_mem_cap_field "$next" 500 "$previous_session_note")"
289
412
  else
290
413
  previous_session_block="- Latest prior session log: $previous_session_label"
291
414
  previous_session_block+=$'\n'
@@ -296,14 +419,15 @@ _ai_mem_context_prompt() {
296
419
  cat <<EOF
297
420
  Read these notes before doing anything else:
298
421
  - Global profile:
299
- $(_ai_mem_note_contents "$AI_MEM_GLOBAL")
422
+ $(__ai_mem_note_contents "$AI_MEM_GLOBAL")
300
423
 
301
424
  - Standards:
302
- $(_ai_mem_note_contents "$AI_MEM_STANDARDS")
425
+ $(__ai_mem_note_contents "$AI_MEM_STANDARDS")
303
426
 
304
427
  - Project context: $project_note
305
428
  $previous_session_block
306
429
  - Active session log: $session_note
430
+ $(__ai_mem_lesson_index)
307
431
 
308
432
  Use the Obsidian vault as the persistent memory layer.
309
433
  Treat the global profile and standards note as the shared baseline for every run.
@@ -314,7 +438,7 @@ EOF
314
438
  }
315
439
 
316
440
  # Mark the current shell as having loaded AI vault context for the active repo.
317
- _ai_mem_mark_commit_ready() {
441
+ __ai_mem_mark_commit_ready() {
318
442
  local project_name="${1:-}"
319
443
  local source="${2:-ai-context}"
320
444
  local ready_dir="$AI_MEM_SESSION_DIR/.context-ready"
@@ -322,11 +446,11 @@ _ai_mem_mark_commit_ready() {
322
446
  local token
323
447
 
324
448
  if [[ -z "$project_name" ]]; then
325
- project_name="$(_ai_mem_resolve_project)"
449
+ project_name="$(__ai_mem_resolve_project)"
326
450
  fi
327
451
 
328
452
  ready_file="$ready_dir/${project_name}.token"
329
- _ai_mem_guard "$ready_file" || return 1
453
+ __ai_mem_guard "$ready_file" || return 1
330
454
 
331
455
  mkdir -p "$ready_dir"
332
456
 
@@ -345,11 +469,11 @@ _ai_mem_mark_commit_ready() {
345
469
  export AI_MEM_CONTEXT_PROJECT="$project_name"
346
470
  }
347
471
 
348
- # Re-export the active-session vars in the CALLER's shell. _ai_mem_prepare_session
472
+ # Re-export the active-session vars in the CALLER's shell. __ai_mem_prepare_session
349
473
  # exports them too, but it is always invoked inside $(...) command substitution, so
350
474
  # those exports die in the subshell and never reach the launched client or its hooks
351
475
  # (Claude's SessionStart/Stop hooks gate on AI_MEM_ACTIVE_SESSION_LOG).
352
- _ai_mem_export_active() {
476
+ __ai_mem_export_active() {
353
477
  export AI_MEM_ACTIVE_PROJECT="${1:-}"
354
478
  export AI_MEM_PREVIOUS_SESSION_LOG="${2:-}"
355
479
  export AI_MEM_ACTIVE_SESSION_LOG="${3:-}"
@@ -360,11 +484,11 @@ ai-start() {
360
484
  shift || true
361
485
 
362
486
  local resolved
363
- resolved="$(_ai_mem_prepare_session "$project_name")" || return 1
487
+ resolved="$(__ai_mem_prepare_session "$project_name")" || return 1
364
488
 
365
489
  local active_project project_note previous_session_note session_note
366
490
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
367
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
491
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
368
492
 
369
493
  local previous_session_label="(none yet)"
370
494
  if [[ -n "$previous_session_note" ]]; then
@@ -384,18 +508,18 @@ EOF
384
508
  ai-context() {
385
509
  local project_name="${1:-}"
386
510
  local resolved project_note previous_session_note session_note
387
- resolved="$(_ai_mem_prepare_session "$project_name")" || return 1
511
+ resolved="$(__ai_mem_prepare_session "$project_name")" || return 1
388
512
 
389
513
  local active_project
390
514
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
391
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
515
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
392
516
 
393
- _ai_mem_mark_commit_ready "$active_project" "ai-context" || return 1
394
- _ai_mem_context_prompt "$project_note" "$previous_session_note" "$session_note"
517
+ __ai_mem_mark_commit_ready "$active_project" "ai-context" || return 1
518
+ __ai_mem_context_prompt "$project_note" "$previous_session_note" "$session_note"
395
519
  }
396
520
 
397
521
  # Yes/no helper used by the session-mode prompts. Empty answer counts as no.
398
- _ai_yesno() {
522
+ __ai_yesno() {
399
523
  local prompt="$1" reply
400
524
  while true; do
401
525
  read -r "reply?${prompt} [y/N] "
@@ -423,18 +547,18 @@ typeset -ga AI_MEM_SKILL_ORDER
423
547
 
424
548
  # Ask which optional skills to enable. Each is independent; answer y/n per skill.
425
549
  # Echoes a pipe-joined list of chosen keys; empty means a plain session.
426
- _ai_session_modes_pick() {
550
+ __ai_session_modes_pick() {
427
551
  local modes=() key prompt
428
552
  for key in "${AI_MEM_SKILL_ORDER[@]}"; do
429
553
  prompt="${AI_MEM_SKILLS[$key]%%::*}"
430
554
  [[ -n "$prompt" ]] || continue
431
- _ai_yesno "$prompt" && modes+=("$key")
555
+ __ai_yesno "$prompt" && modes+=("$key")
432
556
  done
433
557
  print -r -- "${(j:|:)modes}"
434
558
  }
435
559
 
436
560
  # Build the instruction block to inject from the chosen skill keys.
437
- _ai_session_modes_instructions() {
561
+ __ai_session_modes_instructions() {
438
562
  local modes="$1" block="" m text
439
563
  for m in ${(s:|:)modes}; do
440
564
  text="${AI_MEM_SKILLS[$m]#*::}"
@@ -444,12 +568,22 @@ _ai_session_modes_instructions() {
444
568
  }
445
569
 
446
570
  # Start an AI client with the shared memory block and the chosen session mode.
447
- _ai_session_start() {
571
+ __ai_session_start() {
448
572
  local launcher="${1:-}"
449
573
  if (( $# > 0 )); then
450
574
  shift
451
575
  fi
452
576
 
577
+ # Warn (never block) if this shell is running a stale copy. Everything
578
+ # below would otherwise succeed quietly using the old behaviour, and the
579
+ # only symptom is a fix that appears not to have worked.
580
+ local _fp_now
581
+ _fp_now="$(__ai_mem_fingerprint)"
582
+ if [[ -n "$AI_MEM_SOURCED_FINGERPRINT" && -n "$_fp_now" \
583
+ && "$_fp_now" != "$AI_MEM_SOURCED_FINGERPRINT" ]]; then
584
+ echo "ai-memory: this shell loaded an older copy of ai-mem; the files on disk have changed since." >&2
585
+ echo " Run 'source ~/.zshrc' or open a new terminal to pick up the current version." >&2
586
+ fi
453
587
  local session_prompt="${*:-}"
454
588
 
455
589
  # Fail fast with a clear message if the agent's CLI is missing, before a
@@ -461,15 +595,15 @@ _ai_session_start() {
461
595
  fi
462
596
 
463
597
  local resolved
464
- resolved="$(_ai_mem_prepare_session)" || return 1
598
+ resolved="$(__ai_mem_prepare_session)" || return 1
465
599
 
466
600
  local active_project project_note previous_session_note session_note
467
601
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
468
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
602
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
469
603
 
470
604
  local session_modes mode_block
471
- session_modes="$(_ai_session_modes_pick)" || return 1
472
- mode_block="$(_ai_session_modes_instructions "$session_modes")"
605
+ session_modes="$(__ai_session_modes_pick)" || return 1
606
+ mode_block="$(__ai_session_modes_instructions "$session_modes")"
473
607
 
474
608
  # AI_SESSION_MODES carries the chosen skill keys; AI_SESSION_STYLE_LABEL
475
609
  # carries the assembled instruction block for launchers to inject.
@@ -477,10 +611,10 @@ _ai_session_start() {
477
611
  export AI_SESSION_STYLE_LABEL="$mode_block"
478
612
 
479
613
  local memory_prompt
480
- memory_prompt="$(_ai_mem_context_prompt "$project_note" "$previous_session_note" "$session_note")"
614
+ memory_prompt="$(__ai_mem_context_prompt "$project_note" "$previous_session_note" "$session_note")"
481
615
 
482
616
  local graphify_context=""
483
- graphify_context="$(_ai_mem_graphify_context)" || return 1
617
+ graphify_context="$(__ai_mem_graphify_context)" || return 1
484
618
  if [[ -n "$graphify_context" ]]; then
485
619
  memory_prompt+=$'\n\n'
486
620
  memory_prompt+="$graphify_context"
@@ -495,51 +629,51 @@ _ai_session_start() {
495
629
  memory_prompt+="$session_prompt"
496
630
  fi
497
631
 
498
- _ai_mem_mark_commit_ready "$active_project" "$launcher-start" || return 1
632
+ __ai_mem_mark_commit_ready "$active_project" "$launcher-start" || return 1
499
633
 
500
634
  # Dispatch to the agent adapter. Each adapter is passed the assembled
501
635
  # memory prompt, the mode block, and any remaining CLI args (e.g. files to
502
636
  # open). Adapters live in adapters.zsh; add one to support a new agent.
503
- if ! typeset -f "_ai_adapter_$launcher" >/dev/null; then
504
- echo "Unknown AI launcher: $launcher (define _ai_adapter_$launcher in adapters.zsh)" >&2
637
+ if ! typeset -f "__ai_adapter_$launcher" >/dev/null; then
638
+ echo "Unknown AI launcher: $launcher (define __ai_adapter_$launcher in adapters.zsh)" >&2
505
639
  return 1
506
640
  fi
507
- "_ai_adapter_$launcher" "$memory_prompt" "$mode_block" "$@"
641
+ "__ai_adapter_$launcher" "$memory_prompt" "$mode_block" "$@"
508
642
  }
509
643
 
510
644
  # Load the agent adapters, then generate a <name>-start launcher for every
511
645
  # registered agent that has a matching adapter. Users extend by appending to
512
- # AI_MEM_AGENTS (space-separated) and defining _ai_adapter_<name>.
646
+ # AI_MEM_AGENTS (space-separated) and defining __ai_adapter_<name>.
513
647
  source "$AI_MEM_HOME/adapters.zsh"
514
648
  : "${AI_MEM_AGENTS:=claude codex gemini cursor opencode}"
515
649
  for _ai_agent in ${(z)AI_MEM_AGENTS}; do
516
- if typeset -f "_ai_adapter_$_ai_agent" >/dev/null; then
650
+ if typeset -f "__ai_adapter_$_ai_agent" >/dev/null; then
517
651
  # A same-named alias (e.g. from another plugin) makes zsh refuse to
518
652
  # `eval` a function definition of that name at all -- "defining
519
653
  # function based on alias", parse error near '()'. Clear it first;
520
654
  # the function this defines is what should win.
521
655
  unalias "${_ai_agent}-start" 2>/dev/null
522
- eval "${_ai_agent}-start() { _ai_session_start ${_ai_agent} \"\$@\"; }"
656
+ eval "${_ai_agent}-start() { __ai_session_start ${_ai_agent} \"\$@\"; }"
523
657
  fi
524
658
  done
525
659
  unset _ai_agent
526
660
 
527
- _ai_mem_current_project() {
528
- _ai_mem_resolve_project
661
+ __ai_mem_current_project() {
662
+ __ai_mem_resolve_project
529
663
  }
530
664
 
531
- _ai_mem_today_session_log() {
665
+ __ai_mem_today_session_log() {
532
666
  local project_name="${1:-}"
533
667
  if [[ -z "$project_name" ]]; then
534
- project_name="$(_ai_mem_resolve_project)"
668
+ project_name="$(__ai_mem_resolve_project)"
535
669
  fi
536
670
 
537
- _ai_mem_ensure_vault || return 1
671
+ __ai_mem_ensure_vault || return 1
538
672
 
539
673
  local today
540
674
  today="$(date +%Y-%m-%d)"
541
675
  local project_session_dir
542
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
676
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
543
677
 
544
678
  if [[ -n "${AI_MEM_ACTIVE_SESSION_LOG:-}" && -f "$AI_MEM_ACTIVE_SESSION_LOG" ]]; then
545
679
  case "$AI_MEM_ACTIVE_SESSION_LOG" in
@@ -558,13 +692,13 @@ _ai_mem_today_session_log() {
558
692
  latest="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-${today}_*.md" 2>/dev/null | sort | tail -n 1)" || true
559
693
  fi
560
694
  if [[ -n "$latest" ]]; then
561
- _ai_mem_guard "$latest" || return 1
695
+ __ai_mem_guard "$latest" || return 1
562
696
  print -r -- "$latest"
563
697
  return 0
564
698
  fi
565
699
 
566
700
  local session_note="$project_session_dir/${project_name}-${today}_$(date +%H-%M-%S).md"
567
- _ai_mem_guard "$session_note" || return 1
701
+ __ai_mem_guard "$session_note" || return 1
568
702
  mkdir -p "$project_session_dir"
569
703
  SESSION_DATE="$today" PROJECT_NAME="$project_name" perl -0pe 's/\{\{date\}\}/$ENV{SESSION_DATE}/g; s/\{\{project_name\}\}/$ENV{PROJECT_NAME}/g' \
570
704
  "$AI_MEM_SESSION_DIR/_session_template.md" > "$session_note"
@@ -583,18 +717,18 @@ ai-note() {
583
717
  fi
584
718
 
585
719
  local project_name session_note timestamp
586
- project_name="$(_ai_mem_current_project)" || return 1
587
- session_note="$(_ai_mem_today_session_log "$project_name")" || return 1
720
+ project_name="$(__ai_mem_current_project)" || return 1
721
+ session_note="$(__ai_mem_today_session_log "$project_name")" || return 1
588
722
  timestamp="$(date +%H:%M)"
589
723
 
590
- _ai_mem_guard "$session_note" || return 1
724
+ __ai_mem_guard "$session_note" || return 1
591
725
 
592
726
  if ! grep -q '^### Live Notes' "$session_note" 2>/dev/null; then
593
727
  printf '\n### Live Notes\n' >> "$session_note"
594
728
  fi
595
729
 
596
730
  printf '\n- %s %s\n' "$timestamp" "$note_text" >> "$session_note"
597
- _ai_mem_vault_backup
731
+ __ai_mem_vault_backup
598
732
  printf 'Appended to %s\n' "$session_note"
599
733
  }
600
734
 
@@ -621,11 +755,11 @@ ai-lesson() {
621
755
  fi
622
756
 
623
757
  local project_name lesson_file timestamp
624
- project_name="$(_ai_mem_current_project)" || return 1
758
+ project_name="$(__ai_mem_current_project)" || return 1
625
759
  lesson_file="$AI_MEM_ROOT/_lessons/${slug}.md"
626
760
  timestamp="$(date '+%Y-%m-%d %H:%M')"
627
761
 
628
- _ai_mem_guard "$lesson_file" || return 1
762
+ __ai_mem_guard "$lesson_file" || return 1
629
763
 
630
764
  if [[ ! -f "$lesson_file" ]]; then
631
765
  mkdir -p "$AI_MEM_ROOT/_lessons"
@@ -640,7 +774,7 @@ ai-lesson() {
640
774
 
641
775
  printf -- '\n## %s [[%s]]\n\n### Problem\n%s\n\n### Solution\n%s\n' \
642
776
  "$timestamp" "$project_name" "$problem" "$solution" >> "$lesson_file"
643
- _ai_mem_vault_backup
777
+ __ai_mem_vault_backup
644
778
  printf 'Appended to %s\n' "$lesson_file"
645
779
  }
646
780
  # Lints the vault's links: session logs missing a project wikilink, previous
@@ -649,11 +783,21 @@ ai-lesson() {
649
783
  # "isolated dots in Graph View" class of problem before you have to notice it
650
784
  # by eye.
651
785
  ai-mem-lint() {
786
+ local fix=0
787
+ [[ "${1:-}" == "--fix" ]] && fix=1
652
788
  local issues=0 f label target found
789
+ # Open Knowledge Format names exactly one required frontmatter field:
790
+ # `type`. Every note the vault ships already declares one except session
791
+ # logs, which predate the field -- so a vault that has been in use carries
792
+ # a backlog of them. Counted rather than listed: one actionable line beats
793
+ # several hundred identical ones, and the fix is a single pass anyway.
794
+ local -a untyped_files
653
795
 
654
796
  while IFS= read -r -d '' f; do
655
797
  [[ "${f:t}" == "_session_template.md" ]] && continue
656
798
 
799
+ grep -qm1 '^type: ' "$f" 2>/dev/null || untyped_files+=("$f")
800
+
657
801
  if ! grep -qm1 -E '^project:.*\[\[.*\]\]' "$f" 2>/dev/null; then
658
802
  print -r -- "orphaned session log (no project link): $f"
659
803
  (( issues++ ))
@@ -680,6 +824,29 @@ ai-mem-lint() {
680
824
  fi
681
825
  done < <(find "$AI_MEM_PROJECT_DIR" -maxdepth 1 -name "*.md" -print0 2>/dev/null)
682
826
 
827
+ if (( $#untyped_files )); then
828
+ if (( fix )); then
829
+ # Written by hand rather than with `sed -i`, whose in-place flag
830
+ # takes an argument on BSD and not on GNU -- a portability trap
831
+ # for a one-liner a user would otherwise paste from the README.
832
+ local tmp
833
+ for f in $untyped_files; do
834
+ __ai_mem_guard "$f" >/dev/null || continue
835
+ tmp="$f.aimem-backfill"
836
+ if [[ "$(head -1 "$f")" == "---" ]]; then
837
+ { head -1 "$f"; print -r -- "type: ai-session-log"; tail -n +2 "$f"; } > "$tmp"
838
+ else
839
+ { print -rl -- "---" "type: ai-session-log" "---" ""; cat "$f"; } > "$tmp"
840
+ fi
841
+ mv "$tmp" "$f"
842
+ done
843
+ print -r -- "backfilled \`type: ai-session-log\` into $#untyped_files session log(s)"
844
+ else
845
+ print -r -- "$#untyped_files session log(s) missing the \`type:\` frontmatter field (Open Knowledge Format requires it). Fix with: ai-mem-lint --fix"
846
+ (( issues++ ))
847
+ fi
848
+ fi
849
+
683
850
  if (( issues == 0 )); then
684
851
  print -r -- "ok: vault links are clean"
685
852
  else
@@ -704,7 +871,7 @@ ai-mem-search() {
704
871
 
705
872
  local search_root="$AI_MEM_ROOT"
706
873
  if [[ -n "$project" ]]; then
707
- search_root="$(_ai_mem_project_session_dir "$project")"
874
+ search_root="$(__ai_mem_project_session_dir "$project")"
708
875
  if [[ ! -d "$search_root" ]]; then
709
876
  print -r -- "ai-mem-search: no session logs for project '$project'"
710
877
  return 1
@@ -1,4 +1,5 @@
1
1
  ---
2
+ type: ai-session-log
2
3
  date: {{date}}
3
4
  project: "[[{{project_name}}]]"
4
5
  previous: "{{previous_session_link}}"