create-ai-memory 0.12.0 → 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.12.0",
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}"
@@ -19,11 +33,11 @@ AI_MEM_TEMPLATE_SRC="${AI_MEM_HOME:h}/vault-template"
19
33
  # uses whatever behaviour was current whenever this terminal was opened,
20
34
  # which can be months. Comparing the two makes the staleness visible.
21
35
  # cksum is POSIX, so this needs no macOS/Linux branch.
22
- _ai_mem_fingerprint() {
36
+ __ai_mem_fingerprint() {
23
37
  cksum "$AI_MEM_HOME/ai-mem.zsh" "$AI_MEM_HOME/adapters.zsh" 2>/dev/null \
24
38
  | awk '{ printf "%s-", $1 }'
25
39
  }
26
- export AI_MEM_SOURCED_FINGERPRINT="$(_ai_mem_fingerprint)"
40
+ export AI_MEM_SOURCED_FINGERPRINT="$(__ai_mem_fingerprint)"
27
41
  # Vault root. Override in ~/.zshrc; defaults to a hidden dir under $HOME.
28
42
  : "${AI_MEM_ROOT:=$HOME/.ai-memory/_Ai_Memory}"
29
43
  if [[ -d "$AI_MEM_ROOT" ]]; then
@@ -35,12 +49,17 @@ export AI_MEM_STANDARDS="$AI_MEM_ROOT/_Standards.md"
35
49
  export AI_MEM_PROJECT_DIR="$AI_MEM_ROOT/_projects"
36
50
  export AI_MEM_SESSION_DIR="$AI_MEM_ROOT/_session_logs"
37
51
 
38
- _ai_mem_guard() {
39
- local path="${1:-}"
40
- 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
41
60
  "$AI_MEM_ROOT"|"$AI_MEM_ROOT"/*) return 0 ;;
42
61
  *)
43
- echo "Refusing to touch non-memory path: $path"
62
+ echo "Refusing to touch non-memory path: $note_path"
44
63
  return 1
45
64
  ;;
46
65
  esac
@@ -53,7 +72,7 @@ _ai_mem_guard() {
53
72
  # outside this sourced shell, so it can't call this function directly).
54
73
  # No-ops silently if AI_MEM_ROOT isn't its own git repo; never fails the
55
74
  # caller on a push error (no network, no remote configured, etc).
56
- _ai_mem_vault_backup() {
75
+ __ai_mem_vault_backup() {
57
76
  local vault_git_root
58
77
  vault_git_root="$(git -C "${AI_MEM_ROOT:-}" rev-parse --show-toplevel 2>/dev/null || true)"
59
78
  [[ -n "$vault_git_root" ]] || return 0
@@ -73,7 +92,6 @@ _ai_mem_vault_backup() {
73
92
  rmdir "$lock_dir" 2>/dev/null
74
93
  fi
75
94
  return 0
76
- return 0
77
95
  }
78
96
 
79
97
  # Public entry point for anything that writes to the vault outside
@@ -81,9 +99,19 @@ _ai_mem_vault_backup() {
81
99
  # Session Outcome section directly and has no other reason to know this
82
100
  # function exists.
83
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
+
84
112
  local before after
85
113
  before="$(git -C "${AI_MEM_ROOT:-}" rev-parse HEAD 2>/dev/null || true)"
86
- _ai_mem_vault_backup
114
+ __ai_mem_vault_backup
87
115
  after="$(git -C "${AI_MEM_ROOT:-}" rev-parse HEAD 2>/dev/null || true)"
88
116
  if [[ -z "$before" && -z "$after" ]]; then
89
117
  echo "ai-mem-vault-backup: vault isn't git-backed, nothing to do"
@@ -94,17 +122,62 @@ ai-mem-vault-backup() {
94
122
  fi
95
123
  }
96
124
  # Read a vault note only when it exists inside the memory root.
97
- _ai_mem_note_contents() {
98
- local path="${1:-}"
99
- 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)"
100
173
  return 0
101
174
  fi
102
175
 
103
- _ai_mem_guard "$path" || return 1
104
- 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"
105
178
  }
106
179
 
107
- _ai_mem_resolve_project() {
180
+ __ai_mem_resolve_project() {
108
181
  # Prefer the git repo we are actually standing in. Otherwise `cd`-ing between
109
182
  # projects in one shell keeps a stale AI_MEM_ACTIVE_PROJECT pinned, so a later
110
183
  # claude-start writes its log under the wrong project's folder.
@@ -124,16 +197,16 @@ _ai_mem_resolve_project() {
124
197
  basename "$PWD"
125
198
  }
126
199
 
127
- _ai_mem_project_session_dir() {
200
+ __ai_mem_project_session_dir() {
128
201
  local project_name="${1:-}"
129
202
  if [[ -z "$project_name" ]]; then
130
- project_name="$(_ai_mem_resolve_project)"
203
+ project_name="$(__ai_mem_resolve_project)"
131
204
  fi
132
205
 
133
206
  print -r -- "$AI_MEM_SESSION_DIR/$project_name"
134
207
  }
135
208
 
136
- _ai_mem_graphify_repo_root() {
209
+ __ai_mem_graphify_repo_root() {
137
210
  local git_root=""
138
211
  git_root="$(git rev-parse --show-toplevel 2>/dev/null)" || true
139
212
  if [[ -n "$git_root" ]]; then
@@ -143,8 +216,8 @@ _ai_mem_graphify_repo_root() {
143
216
  fi
144
217
  }
145
218
 
146
- _ai_mem_graphify_context() {
147
- local repo_root="$(_ai_mem_graphify_repo_root)"
219
+ __ai_mem_graphify_context() {
220
+ local repo_root="$(__ai_mem_graphify_repo_root)"
148
221
  local graph_root="$repo_root/graphify-out"
149
222
  local graph_json="$graph_root/graph.json"
150
223
  local graph_report="$graph_root/GRAPH_REPORT.md"
@@ -170,22 +243,22 @@ _ai_mem_graphify_context() {
170
243
 
171
244
  # Returns the newest saved session log for the current project.
172
245
  # The active run gets a fresh log, so this only feeds carryover context.
173
- _ai_mem_latest_session_log() {
246
+ __ai_mem_latest_session_log() {
174
247
  local project_name="${1:-}"
175
248
  if [[ -z "$project_name" ]]; then
176
- project_name="$(_ai_mem_resolve_project)"
249
+ project_name="$(__ai_mem_resolve_project)"
177
250
  fi
178
251
 
179
252
  local latest=""
180
253
  local project_session_dir
181
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
254
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
182
255
 
183
256
  latest="$(find "$project_session_dir" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
184
257
  if [[ -z "$latest" ]]; then
185
258
  latest="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
186
259
  fi
187
260
  if [[ -n "$latest" ]]; then
188
- _ai_mem_guard "$latest" || return 1
261
+ __ai_mem_guard "$latest" || return 1
189
262
  print -r -- "$latest"
190
263
  fi
191
264
  }
@@ -193,7 +266,7 @@ _ai_mem_latest_session_log() {
193
266
  # Copy the shipped profile, standards, and templates into the vault on first use.
194
267
  # Idempotent and additive: it never overwrites a file the user already has, so a
195
268
  # plugin-manager install (source only, no install.sh) still gets a working vault.
196
- _ai_mem_ensure_vault() {
269
+ __ai_mem_ensure_vault() {
197
270
  [[ -d "$AI_MEM_TEMPLATE_SRC" ]] || return 0
198
271
  mkdir -p "$AI_MEM_PROJECT_DIR" "$AI_MEM_SESSION_DIR" "$AI_MEM_ROOT/_lessons"
199
272
  local rel
@@ -202,29 +275,29 @@ _ai_mem_ensure_vault() {
202
275
  _lessons/_lesson_template.md; do
203
276
  local src="$AI_MEM_TEMPLATE_SRC/$rel" dst="$AI_MEM_ROOT/$rel"
204
277
  if [[ -f "$src" && ! -f "$dst" ]]; then
205
- _ai_mem_guard "$dst" || return 1
278
+ __ai_mem_guard "$dst" || return 1
206
279
  cp "$src" "$dst"
207
280
  fi
208
281
  done
209
282
  }
210
283
 
211
- _ai_mem_prepare_session() {
284
+ __ai_mem_prepare_session() {
212
285
  local project_name="${1:-}"
213
286
  if [[ -z "$project_name" ]]; then
214
- project_name="$(_ai_mem_resolve_project)"
287
+ project_name="$(__ai_mem_resolve_project)"
215
288
  fi
216
289
 
217
- _ai_mem_ensure_vault || return 1
290
+ __ai_mem_ensure_vault || return 1
218
291
 
219
292
  local project_note="$AI_MEM_PROJECT_DIR/${project_name}.md"
220
293
  local project_session_dir
221
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
294
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
222
295
  local previous_session_note=""
223
- 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
224
297
  local session_note="$project_session_dir/${project_name}-$(date +%Y-%m-%d_%H-%M-%S).md"
225
298
 
226
- _ai_mem_guard "$project_note" || return 1
227
- _ai_mem_guard "$session_note" || return 1
299
+ __ai_mem_guard "$project_note" || return 1
300
+ __ai_mem_guard "$session_note" || return 1
228
301
 
229
302
  mkdir -p "$AI_MEM_PROJECT_DIR" "$AI_MEM_SESSION_DIR" "$project_session_dir"
230
303
 
@@ -251,7 +324,7 @@ _ai_mem_prepare_session() {
251
324
  # Pull one "* **Label:** value" bullet out of a session log's fixed
252
325
  # "# Session Outcome" section. Reads the log directly — no separate file is
253
326
  # ever written, so there is nothing extra sitting in the vault.
254
- _ai_mem_session_field() {
327
+ __ai_mem_session_field() {
255
328
  local file="$1" label="$2" value
256
329
  [[ -f "$file" ]] || return 0
257
330
  value="$(grep -m1 -E "^\* \*\*${label}:\*\*" "$file" | sed -E "s|^\* \*\*${label}:\*\*[[:space:]]*||")"
@@ -263,7 +336,7 @@ _ai_mem_session_field() {
263
336
 
264
337
  # Defensive cap so one unusually long freeform bullet can't blow up the
265
338
  # prompt. Never triggers for the template's intended single-line bullets.
266
- _ai_mem_cap_field() {
339
+ __ai_mem_cap_field() {
267
340
  local text="$1" cap="${2:-500}" source_ref="$3"
268
341
  if (( ${#text} > cap )); then
269
342
  print -r -- "${text[1,$cap]}… (truncated, ${#text} chars total — see $source_ref)"
@@ -272,7 +345,44 @@ _ai_mem_cap_field() {
272
345
  fi
273
346
  }
274
347
 
275
- _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() {
276
386
  local project_note="${1:-}"
277
387
  local previous_session_note="${2:-}"
278
388
  local session_note="${3:-}"
@@ -283,10 +393,10 @@ _ai_mem_context_prompt() {
283
393
  previous_session_label="$previous_session_note"
284
394
 
285
395
  local summary decisions blockers next
286
- summary="$(_ai_mem_session_field "$previous_session_note" 'High-Level Summary')"
287
- decisions="$(_ai_mem_session_field "$previous_session_note" 'Important Decisions')"
288
- blockers="$(_ai_mem_session_field "$previous_session_note" 'Constraints / Blockers')"
289
- 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')"
290
400
 
291
401
  if [[ -z "${AI_MEM_NO_DIGEST:-}" && ( -n "$summary" || -n "$decisions" || -n "$blockers" || -n "$next" ) ]]; then
292
402
  [[ -n "$summary" ]] || summary="—"
@@ -295,10 +405,10 @@ _ai_mem_context_prompt() {
295
405
  [[ -n "$next" ]] || next="—"
296
406
 
297
407
  previous_session_block="- Latest prior session ($previous_session_note), summarized below:"
298
- previous_session_block+=$'\n'"* **Summary:** $(_ai_mem_cap_field "$summary" 500 "$previous_session_note")"
299
- previous_session_block+=$'\n'"* **Decisions:** $(_ai_mem_cap_field "$decisions" 500 "$previous_session_note")"
300
- previous_session_block+=$'\n'"* **Blockers:** $(_ai_mem_cap_field "$blockers" 500 "$previous_session_note")"
301
- 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")"
302
412
  else
303
413
  previous_session_block="- Latest prior session log: $previous_session_label"
304
414
  previous_session_block+=$'\n'
@@ -309,14 +419,15 @@ _ai_mem_context_prompt() {
309
419
  cat <<EOF
310
420
  Read these notes before doing anything else:
311
421
  - Global profile:
312
- $(_ai_mem_note_contents "$AI_MEM_GLOBAL")
422
+ $(__ai_mem_note_contents "$AI_MEM_GLOBAL")
313
423
 
314
424
  - Standards:
315
- $(_ai_mem_note_contents "$AI_MEM_STANDARDS")
425
+ $(__ai_mem_note_contents "$AI_MEM_STANDARDS")
316
426
 
317
427
  - Project context: $project_note
318
428
  $previous_session_block
319
429
  - Active session log: $session_note
430
+ $(__ai_mem_lesson_index)
320
431
 
321
432
  Use the Obsidian vault as the persistent memory layer.
322
433
  Treat the global profile and standards note as the shared baseline for every run.
@@ -327,7 +438,7 @@ EOF
327
438
  }
328
439
 
329
440
  # Mark the current shell as having loaded AI vault context for the active repo.
330
- _ai_mem_mark_commit_ready() {
441
+ __ai_mem_mark_commit_ready() {
331
442
  local project_name="${1:-}"
332
443
  local source="${2:-ai-context}"
333
444
  local ready_dir="$AI_MEM_SESSION_DIR/.context-ready"
@@ -335,11 +446,11 @@ _ai_mem_mark_commit_ready() {
335
446
  local token
336
447
 
337
448
  if [[ -z "$project_name" ]]; then
338
- project_name="$(_ai_mem_resolve_project)"
449
+ project_name="$(__ai_mem_resolve_project)"
339
450
  fi
340
451
 
341
452
  ready_file="$ready_dir/${project_name}.token"
342
- _ai_mem_guard "$ready_file" || return 1
453
+ __ai_mem_guard "$ready_file" || return 1
343
454
 
344
455
  mkdir -p "$ready_dir"
345
456
 
@@ -358,11 +469,11 @@ _ai_mem_mark_commit_ready() {
358
469
  export AI_MEM_CONTEXT_PROJECT="$project_name"
359
470
  }
360
471
 
361
- # 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
362
473
  # exports them too, but it is always invoked inside $(...) command substitution, so
363
474
  # those exports die in the subshell and never reach the launched client or its hooks
364
475
  # (Claude's SessionStart/Stop hooks gate on AI_MEM_ACTIVE_SESSION_LOG).
365
- _ai_mem_export_active() {
476
+ __ai_mem_export_active() {
366
477
  export AI_MEM_ACTIVE_PROJECT="${1:-}"
367
478
  export AI_MEM_PREVIOUS_SESSION_LOG="${2:-}"
368
479
  export AI_MEM_ACTIVE_SESSION_LOG="${3:-}"
@@ -373,11 +484,11 @@ ai-start() {
373
484
  shift || true
374
485
 
375
486
  local resolved
376
- resolved="$(_ai_mem_prepare_session "$project_name")" || return 1
487
+ resolved="$(__ai_mem_prepare_session "$project_name")" || return 1
377
488
 
378
489
  local active_project project_note previous_session_note session_note
379
490
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
380
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
491
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
381
492
 
382
493
  local previous_session_label="(none yet)"
383
494
  if [[ -n "$previous_session_note" ]]; then
@@ -397,18 +508,18 @@ EOF
397
508
  ai-context() {
398
509
  local project_name="${1:-}"
399
510
  local resolved project_note previous_session_note session_note
400
- resolved="$(_ai_mem_prepare_session "$project_name")" || return 1
511
+ resolved="$(__ai_mem_prepare_session "$project_name")" || return 1
401
512
 
402
513
  local active_project
403
514
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
404
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
515
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
405
516
 
406
- _ai_mem_mark_commit_ready "$active_project" "ai-context" || return 1
407
- _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"
408
519
  }
409
520
 
410
521
  # Yes/no helper used by the session-mode prompts. Empty answer counts as no.
411
- _ai_yesno() {
522
+ __ai_yesno() {
412
523
  local prompt="$1" reply
413
524
  while true; do
414
525
  read -r "reply?${prompt} [y/N] "
@@ -436,18 +547,18 @@ typeset -ga AI_MEM_SKILL_ORDER
436
547
 
437
548
  # Ask which optional skills to enable. Each is independent; answer y/n per skill.
438
549
  # Echoes a pipe-joined list of chosen keys; empty means a plain session.
439
- _ai_session_modes_pick() {
550
+ __ai_session_modes_pick() {
440
551
  local modes=() key prompt
441
552
  for key in "${AI_MEM_SKILL_ORDER[@]}"; do
442
553
  prompt="${AI_MEM_SKILLS[$key]%%::*}"
443
554
  [[ -n "$prompt" ]] || continue
444
- _ai_yesno "$prompt" && modes+=("$key")
555
+ __ai_yesno "$prompt" && modes+=("$key")
445
556
  done
446
557
  print -r -- "${(j:|:)modes}"
447
558
  }
448
559
 
449
560
  # Build the instruction block to inject from the chosen skill keys.
450
- _ai_session_modes_instructions() {
561
+ __ai_session_modes_instructions() {
451
562
  local modes="$1" block="" m text
452
563
  for m in ${(s:|:)modes}; do
453
564
  text="${AI_MEM_SKILLS[$m]#*::}"
@@ -457,7 +568,7 @@ _ai_session_modes_instructions() {
457
568
  }
458
569
 
459
570
  # Start an AI client with the shared memory block and the chosen session mode.
460
- _ai_session_start() {
571
+ __ai_session_start() {
461
572
  local launcher="${1:-}"
462
573
  if (( $# > 0 )); then
463
574
  shift
@@ -467,7 +578,7 @@ _ai_session_start() {
467
578
  # below would otherwise succeed quietly using the old behaviour, and the
468
579
  # only symptom is a fix that appears not to have worked.
469
580
  local _fp_now
470
- _fp_now="$(_ai_mem_fingerprint)"
581
+ _fp_now="$(__ai_mem_fingerprint)"
471
582
  if [[ -n "$AI_MEM_SOURCED_FINGERPRINT" && -n "$_fp_now" \
472
583
  && "$_fp_now" != "$AI_MEM_SOURCED_FINGERPRINT" ]]; then
473
584
  echo "ai-memory: this shell loaded an older copy of ai-mem; the files on disk have changed since." >&2
@@ -484,15 +595,15 @@ _ai_session_start() {
484
595
  fi
485
596
 
486
597
  local resolved
487
- resolved="$(_ai_mem_prepare_session)" || return 1
598
+ resolved="$(__ai_mem_prepare_session)" || return 1
488
599
 
489
600
  local active_project project_note previous_session_note session_note
490
601
  IFS='|' read -r active_project project_note previous_session_note session_note <<< "$resolved"
491
- _ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
602
+ __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
492
603
 
493
604
  local session_modes mode_block
494
- session_modes="$(_ai_session_modes_pick)" || return 1
495
- 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")"
496
607
 
497
608
  # AI_SESSION_MODES carries the chosen skill keys; AI_SESSION_STYLE_LABEL
498
609
  # carries the assembled instruction block for launchers to inject.
@@ -500,10 +611,10 @@ _ai_session_start() {
500
611
  export AI_SESSION_STYLE_LABEL="$mode_block"
501
612
 
502
613
  local memory_prompt
503
- 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")"
504
615
 
505
616
  local graphify_context=""
506
- graphify_context="$(_ai_mem_graphify_context)" || return 1
617
+ graphify_context="$(__ai_mem_graphify_context)" || return 1
507
618
  if [[ -n "$graphify_context" ]]; then
508
619
  memory_prompt+=$'\n\n'
509
620
  memory_prompt+="$graphify_context"
@@ -518,51 +629,51 @@ _ai_session_start() {
518
629
  memory_prompt+="$session_prompt"
519
630
  fi
520
631
 
521
- _ai_mem_mark_commit_ready "$active_project" "$launcher-start" || return 1
632
+ __ai_mem_mark_commit_ready "$active_project" "$launcher-start" || return 1
522
633
 
523
634
  # Dispatch to the agent adapter. Each adapter is passed the assembled
524
635
  # memory prompt, the mode block, and any remaining CLI args (e.g. files to
525
636
  # open). Adapters live in adapters.zsh; add one to support a new agent.
526
- if ! typeset -f "_ai_adapter_$launcher" >/dev/null; then
527
- 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
528
639
  return 1
529
640
  fi
530
- "_ai_adapter_$launcher" "$memory_prompt" "$mode_block" "$@"
641
+ "__ai_adapter_$launcher" "$memory_prompt" "$mode_block" "$@"
531
642
  }
532
643
 
533
644
  # Load the agent adapters, then generate a <name>-start launcher for every
534
645
  # registered agent that has a matching adapter. Users extend by appending to
535
- # AI_MEM_AGENTS (space-separated) and defining _ai_adapter_<name>.
646
+ # AI_MEM_AGENTS (space-separated) and defining __ai_adapter_<name>.
536
647
  source "$AI_MEM_HOME/adapters.zsh"
537
648
  : "${AI_MEM_AGENTS:=claude codex gemini cursor opencode}"
538
649
  for _ai_agent in ${(z)AI_MEM_AGENTS}; do
539
- if typeset -f "_ai_adapter_$_ai_agent" >/dev/null; then
650
+ if typeset -f "__ai_adapter_$_ai_agent" >/dev/null; then
540
651
  # A same-named alias (e.g. from another plugin) makes zsh refuse to
541
652
  # `eval` a function definition of that name at all -- "defining
542
653
  # function based on alias", parse error near '()'. Clear it first;
543
654
  # the function this defines is what should win.
544
655
  unalias "${_ai_agent}-start" 2>/dev/null
545
- eval "${_ai_agent}-start() { _ai_session_start ${_ai_agent} \"\$@\"; }"
656
+ eval "${_ai_agent}-start() { __ai_session_start ${_ai_agent} \"\$@\"; }"
546
657
  fi
547
658
  done
548
659
  unset _ai_agent
549
660
 
550
- _ai_mem_current_project() {
551
- _ai_mem_resolve_project
661
+ __ai_mem_current_project() {
662
+ __ai_mem_resolve_project
552
663
  }
553
664
 
554
- _ai_mem_today_session_log() {
665
+ __ai_mem_today_session_log() {
555
666
  local project_name="${1:-}"
556
667
  if [[ -z "$project_name" ]]; then
557
- project_name="$(_ai_mem_resolve_project)"
668
+ project_name="$(__ai_mem_resolve_project)"
558
669
  fi
559
670
 
560
- _ai_mem_ensure_vault || return 1
671
+ __ai_mem_ensure_vault || return 1
561
672
 
562
673
  local today
563
674
  today="$(date +%Y-%m-%d)"
564
675
  local project_session_dir
565
- project_session_dir="$(_ai_mem_project_session_dir "$project_name")"
676
+ project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
566
677
 
567
678
  if [[ -n "${AI_MEM_ACTIVE_SESSION_LOG:-}" && -f "$AI_MEM_ACTIVE_SESSION_LOG" ]]; then
568
679
  case "$AI_MEM_ACTIVE_SESSION_LOG" in
@@ -581,13 +692,13 @@ _ai_mem_today_session_log() {
581
692
  latest="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-${today}_*.md" 2>/dev/null | sort | tail -n 1)" || true
582
693
  fi
583
694
  if [[ -n "$latest" ]]; then
584
- _ai_mem_guard "$latest" || return 1
695
+ __ai_mem_guard "$latest" || return 1
585
696
  print -r -- "$latest"
586
697
  return 0
587
698
  fi
588
699
 
589
700
  local session_note="$project_session_dir/${project_name}-${today}_$(date +%H-%M-%S).md"
590
- _ai_mem_guard "$session_note" || return 1
701
+ __ai_mem_guard "$session_note" || return 1
591
702
  mkdir -p "$project_session_dir"
592
703
  SESSION_DATE="$today" PROJECT_NAME="$project_name" perl -0pe 's/\{\{date\}\}/$ENV{SESSION_DATE}/g; s/\{\{project_name\}\}/$ENV{PROJECT_NAME}/g' \
593
704
  "$AI_MEM_SESSION_DIR/_session_template.md" > "$session_note"
@@ -606,18 +717,18 @@ ai-note() {
606
717
  fi
607
718
 
608
719
  local project_name session_note timestamp
609
- project_name="$(_ai_mem_current_project)" || return 1
610
- 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
611
722
  timestamp="$(date +%H:%M)"
612
723
 
613
- _ai_mem_guard "$session_note" || return 1
724
+ __ai_mem_guard "$session_note" || return 1
614
725
 
615
726
  if ! grep -q '^### Live Notes' "$session_note" 2>/dev/null; then
616
727
  printf '\n### Live Notes\n' >> "$session_note"
617
728
  fi
618
729
 
619
730
  printf '\n- %s %s\n' "$timestamp" "$note_text" >> "$session_note"
620
- _ai_mem_vault_backup
731
+ __ai_mem_vault_backup
621
732
  printf 'Appended to %s\n' "$session_note"
622
733
  }
623
734
 
@@ -644,11 +755,11 @@ ai-lesson() {
644
755
  fi
645
756
 
646
757
  local project_name lesson_file timestamp
647
- project_name="$(_ai_mem_current_project)" || return 1
758
+ project_name="$(__ai_mem_current_project)" || return 1
648
759
  lesson_file="$AI_MEM_ROOT/_lessons/${slug}.md"
649
760
  timestamp="$(date '+%Y-%m-%d %H:%M')"
650
761
 
651
- _ai_mem_guard "$lesson_file" || return 1
762
+ __ai_mem_guard "$lesson_file" || return 1
652
763
 
653
764
  if [[ ! -f "$lesson_file" ]]; then
654
765
  mkdir -p "$AI_MEM_ROOT/_lessons"
@@ -663,7 +774,7 @@ ai-lesson() {
663
774
 
664
775
  printf -- '\n## %s [[%s]]\n\n### Problem\n%s\n\n### Solution\n%s\n' \
665
776
  "$timestamp" "$project_name" "$problem" "$solution" >> "$lesson_file"
666
- _ai_mem_vault_backup
777
+ __ai_mem_vault_backup
667
778
  printf 'Appended to %s\n' "$lesson_file"
668
779
  }
669
780
  # Lints the vault's links: session logs missing a project wikilink, previous
@@ -672,11 +783,21 @@ ai-lesson() {
672
783
  # "isolated dots in Graph View" class of problem before you have to notice it
673
784
  # by eye.
674
785
  ai-mem-lint() {
786
+ local fix=0
787
+ [[ "${1:-}" == "--fix" ]] && fix=1
675
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
676
795
 
677
796
  while IFS= read -r -d '' f; do
678
797
  [[ "${f:t}" == "_session_template.md" ]] && continue
679
798
 
799
+ grep -qm1 '^type: ' "$f" 2>/dev/null || untyped_files+=("$f")
800
+
680
801
  if ! grep -qm1 -E '^project:.*\[\[.*\]\]' "$f" 2>/dev/null; then
681
802
  print -r -- "orphaned session log (no project link): $f"
682
803
  (( issues++ ))
@@ -703,6 +824,29 @@ ai-mem-lint() {
703
824
  fi
704
825
  done < <(find "$AI_MEM_PROJECT_DIR" -maxdepth 1 -name "*.md" -print0 2>/dev/null)
705
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
+
706
850
  if (( issues == 0 )); then
707
851
  print -r -- "ok: vault links are clean"
708
852
  else
@@ -727,7 +871,7 @@ ai-mem-search() {
727
871
 
728
872
  local search_root="$AI_MEM_ROOT"
729
873
  if [[ -n "$project" ]]; then
730
- search_root="$(_ai_mem_project_session_dir "$project")"
874
+ search_root="$(__ai_mem_project_session_dir "$project")"
731
875
  if [[ ! -d "$search_root" ]]; then
732
876
  print -r -- "ai-mem-search: no session logs for project '$project'"
733
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}}"