create-ai-memory 0.14.1 → 0.14.3

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
@@ -33,69 +33,33 @@ npm create ai-memory@latest
33
33
 
34
34
  ## The problem
35
35
 
36
- Every AI coding session starts from zero.
36
+ Every AI coding session starts from zero. The moment a thread ends, the agent
37
+ forgets what was built, why each choice was made, and where you left off.
37
38
 
38
- Claude Code, Codex, Gemini CLI. The moment a session ends, the agent forgets what
39
- was built, the decisions that were made, the PRD, every architectural and codebase
40
- choice. The context that mattered most evaporates with the chat thread, and the
41
- next run begins blind.
42
-
43
- You pay the same tax on every run:
44
-
45
- - **Agent amnesia.** Accumulated project knowledge vanishes when the thread closes.
46
- - **Lost decisions.** Why a choice was made is nowhere; the next run re-litigates it.
47
- - **Reload overhead.** You re-explain the stack, constraints, and conventions from scratch.
48
- - **No continuity.** Nothing carries "where I left off" into the next session.
49
-
50
- Switching agents makes it worse. Each CLI is its own island with its own memory,
51
- or none. Knowledge earned in Claude doesn't reach Codex.
39
+ You pay it again on the next run: re-explaining the stack, re-litigating
40
+ settled decisions, losing "where I was". Switching agents makes it worse —
41
+ each CLI is its own island, so what Claude learned never reaches Codex.
52
42
 
53
43
  ## How it works
54
44
 
55
- Keep the memory outside the chat, in plain Markdown on disk, and inject it into
56
- whichever agent you launch. A chat thread is disposable; the vault is permanent.
57
- Because it is just files, the same vault opens as an
58
- [Obsidian](https://obsidian.md) second brain with graph view, backlinks, and
59
- search. Nothing here requires Obsidian; it is Markdown either way.
45
+ Keep the memory outside the chat, in plain Markdown on disk, and inject it
46
+ into whichever agent you launch. A thread is disposable; the vault is
47
+ permanent. Because it is just files, the same vault opens in
48
+ [Obsidian](https://obsidian.md) with graph view and backlinks — though
49
+ nothing here requires it.
60
50
 
61
- Memory sits in three layers, each injected at the right scope:
51
+ Three layers, each injected at the right scope:
62
52
 
63
53
  | Layer | Lives in | Injected | Holds |
64
54
  |---|---|---|---|
65
- | **Global** | `_Global_Profile.md`, `_Standards.md` | every session, every project | who you are, your rules, coding standards, commit policy |
66
- | **Project** | `_projects/<repo>.md` | sessions in that repo | purpose, architecture, constraints, active decisions |
55
+ | **Global** | `_Global_Profile.md`, `_Standards.md` | every session | who you are, your rules, commit policy |
56
+ | **Project** | `_projects/<repo>.md` | sessions in that repo | purpose, architecture, constraints, decisions |
67
57
  | **Session** | `_session_logs/<repo>/<timestamp>.md` | next session as carryover | what changed, blockers, next steps |
68
58
 
69
- When you run a launcher, create-ai-memory assembles those layers into one prompt and
70
- hands it to the agent as its opening message:
71
-
72
- ```
73
- $ claude-start
74
- │
75
- ├─ resolve the project from the current git repo
76
- ├─ create a fresh session log from the template
77
- ├─ gather: Global Profile + Standards (who you are)
78
- │ Project note (this repo)
79
- │ prior session's outcome (where you left off, inlined)
80
- ├─ ask which session skills to enable (optional)
81
- └─ launch the agent with all of it as the first prompt
82
- │
83
- ▼
84
- …you work…
85
- │
86
- ▼
87
- on exit, a hook writes an auto session log
88
- (branch, commits made, uncommitted changes)
89
- → the NEXT session inherits it as carryover
90
- ```
91
-
92
- The prior session's outcome is extracted from the log and inlined into the opening
93
- prompt directly — not just a path the agent is told to go read. No separate file,
94
- no index, nothing new in the vault: it's read straight out of the session log you
95
- already have, every launch.
96
-
97
- One environment variable, `AI_MEM_ROOT`, points at the vault, so the whole system
98
- moves between machines by pointing at the same folder.
59
+ The prior session's outcome is **inlined into the opening prompt**, not left
60
+ as a path the agent is told to go read. One environment variable,
61
+ `AI_MEM_ROOT`, points at the vault, so the whole system moves between
62
+ machines by pointing at the same folder.
99
63
 
100
64
  ## The full loop
101
65
 
@@ -193,6 +157,7 @@ off last time.
193
157
  - [Install](#install)
194
158
  - [Commands](#commands)
195
159
  - [How search works](#how-search-works)
160
+ - [What it costs](#what-it-costs-and-what-it-cannot-do)
196
161
 
197
162
  </td>
198
163
  <td valign="top" width="33%">
@@ -263,7 +228,8 @@ AI_MEM_SEARCH_LIMIT=999999 ai-mem-search postgres | wc -c
263
228
 
264
229
  | | |
265
230
  |---|---|
266
- | Search, common term, 238 hits | **0.07 s** |
231
+ | Search, common term, 501-note vault | **0.07 s** |
232
+ | Search at 2,000 / 10,000 notes | 1.3 s / 7.2 s — linear, see [limits](#what-it-costs-and-what-it-cannot-do) |
267
233
  | Shell startup cost of the module | **< 0.01 s** |
268
234
  | Recency sort, v0.11.0 regression fix | 25.4 s → **0.54 s** (47×) |
269
235
 
@@ -335,7 +301,7 @@ optional. Set `AI_MEM_ROOT` in `~/.zshrc` first if you do not want the default
335
301
  | `ai-note <text>` | Append a timestamped note to today's session log while you work |
336
302
  | `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 |
337
303
  | `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 |
338
- | `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 |
304
+ | `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 25) 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 |
339
305
  | `ai-mem-serve [port] [--no-open]` | Open the vault as a browsable graph on `127.0.0.1`. Agents run this for you when you ask to see your memory (see [Graph view](#graph-view)) |
340
306
  | `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 |
341
307
 
@@ -343,10 +309,9 @@ Project is auto-resolved from the current git repo; pass a name to override.
343
309
 
344
310
  ## How search works
345
311
 
346
- Searching the vault reads your notes directly, every time. Nothing is
347
- prepared in advance: no index to rebuild, no background service, no
348
- embeddings to regenerate, nothing that can quietly fall out of date. A note
349
- is findable the second you write it.
312
+ Reads your notes directly, every time. No index, no daemon, no embeddings —
313
+ nothing to rebuild and nothing that can go stale. A note is findable the
314
+ second you write it.
350
315
 
351
316
  ```mermaid
352
317
  flowchart TD
@@ -357,7 +322,7 @@ flowchart TD
357
322
  D --> E
358
323
  E -->|"found nothing"| F["<b>Says so, plainly.</b><br/>Never a blank screen you<br/>could mistake for 'none exist'"]
359
324
  E -->|"found something"| G["Newest first"]
360
- G --> H["Show the first 40<br/>and say how many more there are"]
325
+ G --> H["Show a few from each note<br/>and say how many more there are"]
361
326
  H --> I["Follow any linked note one step,<br/>with a one-line summary of it"]
362
327
  I --> J(["What you read"])
363
328
 
@@ -369,152 +334,132 @@ flowchart TD
369
334
  class J done
370
335
  ```
371
336
 
372
- Two boxes are shaded because they are the ones that matter: an empty result
373
- that **says** it is empty, and an output short enough to read to the end.
374
-
375
- That is the whole idea. The rest of this section is the mechanism -- one
376
- `grep -rniF`, then a sort, then a cap -- and why each piece is the way it is.
377
- Every flag exists because the alternative produced a wrong answer on a real
378
- vault. Skip it unless you are changing the code.
337
+ The shaded boxes are the two that matter: an empty result that **says** it is
338
+ empty, and an output short enough to read to the end.
379
339
 
380
340
  ```console
381
341
  $ ai-mem-search prisma
382
- 238 match(es) for 'prisma'
342
+ 240 match(es) for 'prisma'
383
343
  paths below /Users/you/_Ai_Memory
384
344
  --
385
345
  _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`.
386
- _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 [...]
387
346
  ...
388
347
  --
389
- showing 40 of 238 (198 hidden) -- narrow with: ai-mem-search 'prisma' <project>, or raise AI_MEM_SEARCH_LIMIT
348
+ showing 25 of 240 (215 hidden), across 25 file(s), at most 1 line(s) each -- for more lines per file raise AI_MEM_SEARCH_PER_FILE, or narrow with: ai-mem-search 'prisma' <project>
390
349
  ```
391
350
 
392
- **Case-insensitive (`-i`).** A false empty state is the worst answer a memory
393
- tool can give, because it is indistinguishable from the truth -- and the
394
- explicit `no matches` message is exactly what makes it look authoritative.
395
- Measured on a real vault: `precompact` found 0 matches case-sensitively and 3
396
- with `-i`; `Postgres` found 56 versus 90.
397
-
398
- **Literal, not regex (`-F`).** The caller is usually an agent passing free
399
- text, where a stray `.`, `(` or `|` must match itself. `ai-mem-search .env`
400
- finds `.env`, not every four-character string ending in `env`.
401
-
402
- **Newest first.** The sort key is the `YYYY-MM-DD_HH-MM-SS` embedded in the
403
- log filename. For a time series the most recent match is usually the relevant
404
- one, so a large result set stays useful at a glance without any relevance
405
- ranking. Files with no timestamp in the name (`_Global_Profile.md`, project
406
- notes) sort last.
407
-
408
- **Bounded output.** The count comes first, before the results -- you need the
409
- size of the result set to interpret it. Then at most `AI_MEM_SEARCH_LIMIT`
410
- lines (default 40), and if anything was withheld, an explicit `N hidden` line
411
- with the command to narrow. This is for the agent, not for you: an unbounded
412
- dump of a common term ran ~29k tokens, overflowed the host's tool-response
413
- cap, and got silently truncated -- leaving the agent unable to tell "hidden"
414
- from "absent". Near-miss padding is also the most damaging kind of distractor
415
- for a model, so fewer clean hits beat more of them.
416
-
417
- **Compact lines.** The vault root is printed once in the header and stripped
418
- from every result path (a third to a half of all output bytes on a real
419
- vault, no information lost). Lines longer than 200 characters are clamped
420
- with `[...]`, since prose notes routinely run long.
421
-
422
- **One hop out.** Any `[[wikilink]]` on a matched line is resolved to its
423
- project note and shown with a one-line excerpt under `one hop out:`. A
424
- `_lessons` entry names the projects it came from, so a hit there tells you
425
- where it happened without a second search. Always on, not a flag to remember.
351
+ Under the hood it is one `grep -rniF`, a sort, and a cap. Each choice exists
352
+ because the alternative gave a wrong answer on a real vault:
426
353
 
427
- ```console
428
- $ ai-mem-search '[[create-ai-memory]]'
429
- 11 match(es) for '[[create-ai-memory]]'
430
- ...
431
- --
432
- one hop out:
433
- [[create-ai-memory]] -> /Users/you/_Ai_Memory/_projects/create-ai-memory.md
434
- * **Current Objective:** ship the vault-backup fix
435
- ```
354
+ | choice | why |
355
+ |---|---|
356
+ | **Case-insensitive** | A false empty is the worst answer a memory tool can give. `precompact` found 0 case-sensitively and 3 with `-i`; `Postgres` 56 vs 90. |
357
+ | **Literal, not regex** | The caller is usually an agent passing free text, where a stray `.` or `(` must match itself. |
358
+ | **Lessons first, then newest** | Session logs outnumber lessons ~4:1 and are always newer, so recency alone buried them — searching `snapshot` returned 25 logs and none of the 3 lessons answering it. A lesson now outranks newer chatter. |
359
+ | **Bounded output** | Unbounded, a common term ran ~29k tokens and was silently truncated by the host — leaving the agent unable to tell *hidden* from *absent*. |
360
+ | **One line per file** | Until the budget binds. Spends it on distinct notes rather than the chattiest one. |
361
+ | **Compact lines** | Vault root printed once and stripped from every path; lines over 200 chars clamped. |
362
+ | **One hop out** | Any `[[wikilink]]` on a hit resolves to its project note with a one-line excerpt, so a lesson tells you where it happened without a second search. |
436
363
 
437
- (That query is also `-F` earning its keep: `[[` is matched literally, not as
438
- a character class.)
364
+ ### What it costs, and what it cannot do
439
365
 
440
- **Scoping.** A second argument restricts the search to one project's session
441
- logs -- `ai-mem-search postgres checkout-api`. Unknown project names fail
442
- explicitly rather than silently searching everything.
366
+ Measured, not estimated. Reproduce with `ai-mem-search <term>`.
443
367
 
444
- ### Mirrored notes are not injected twice
368
+ **Matching is substring, case-insensitive, literal** — not word matching, not
369
+ stemming, not fuzzy:
445
370
 
446
- `_Standards.md` ships declaring `mirror_of: _Global_Profile.md` in its
447
- frontmatter. The mirror exists so the shared rules stay visible wherever only
448
- one of the two notes is read -- but the launch prompt reads *both*, so
449
- injecting both in full restates text the model has just finished reading.
371
+ | query | matches | |
372
+ |---|---|---|
373
+ | `git` | 765 | substring — also hits `github` |
374
+ | `github` | 255 | a subset of the above |
375
+ | `Postgres` / `POSTGRES` / `postgre` | 93 each | case ignored, prefix matches |
376
+ | `.env` | 131 | the dot is literal |
377
+ | `env` | 307 | more — `.env` is narrower |
378
+ | `postgress` *(typo)* | **0** | **no fuzzy matching** |
450
379
 
451
- When a note declares `mirror_of: <sibling note>`, only the lines that
452
- actually differ from that source are injected, under a one-line marker
453
- naming what was elided:
380
+ That last row is the limit: a misspelling finds nothing.
454
381
 
455
- ```text
456
- - Standards:
457
- (mirror of _Global_Profile.md, shown above -- only the lines that differ from it are repeated here)
458
- ## Standards Addendum
459
- * Keep `_Standards.md` and `_Global_Profile.md` in lockstep when shared rules change.
460
- ...
461
- ```
382
+ **Search one distinctive word, not a sentence.** Matching is literal
383
+ substring, so the whole error line `command not found: sed` finds **nothing**
384
+ while `command not found` finds it — and a bare tool name like `sed` returns
385
+ 1,012 irrelevant lines. Pick the most unusual word in the symptom and try two
386
+ or three separately.
462
387
 
463
- Measured on a real vault: 72 of the mirror's 80 unique lines were already
464
- verbatim in its source, and the launch prompt went from **~7,200 to ~4,300
465
- tokens -- a 40% cut with nothing lost**, paid once per session per agent.
388
+ **Token cost is bounded and flat:**
466
389
 
467
- Matching is exact, line by line, so anything reworded is kept -- a near-match
468
- is a real edit. The comparison fails **open** in every uncertain case: no
469
- frontmatter, a missing source, a `mirror_of` containing a path separator, or
470
- a diff that would leave nothing all inject the note in full. Injecting a note
471
- twice costs tokens; dropping one costs the agent context it was promised, and
472
- those are not the same kind of mistake.
390
+ | matches | tokens |
391
+ |---|---|
392
+ | 0 | ~23 |
393
+ | 240 | ~1,224 |
394
+ | 10,198 | ~1,270 |
473
395
 
474
- ### Lessons are indexed, not injected
396
+ Forty times the matches for the same cost.
475
397
 
476
- `ai-lesson` writes to `_lessons/<topic-slug>.md`, and those entries are the
477
- most reusable thing in the vault -- they are the only notes that are true
478
- across projects. They are also the hardest for an agent to find, because
479
- finding one by search means guessing a term for knowledge it does not know
480
- it has.
398
+ **Speed is linear in vault size**, dominated by how many lines match:
481
399
 
482
- So the launch prompt lists **every lesson slug and no lesson bodies**:
400
+ | vault | rare term | common term |
401
+ |---|---|---|
402
+ | 501 notes *(real)* | — | **0.07 s** |
403
+ | 2,000 *(synthetic)* | 0.35 s | 1.29 s |
404
+ | 10,000 | 1.74 s | 7.20 s |
483
405
 
484
- ```text
485
- - Lessons already recorded (96), listed by topic slug only -- the bodies are NOT
486
- included here. If one looks relevant to the task at hand, read it with
487
- `ai-mem-search <slug>` before solving the problem again from scratch.
488
- prisma-connection-pool-exhaustion, decimal-money-precision-js, react-hydration-mismatch, ...
489
- ```
406
+ Comfortable to a few thousand notes — years of daily logs. Past ~10k, scope
407
+ it: `ai-mem-search <term> <project>`. If that is not enough, this is the wrong
408
+ tool and you want a real index.
409
+
410
+ ### Is it used while you code, or only at launch?
490
411
 
491
- A slug is the lesson already compressed: `prisma-connection-pool-exhaustion`
492
- tells you whether to open it without opening it. That is the trade -- roughly
493
- 8 tokens per lesson to convert a blind guess into a precise search. 96
494
- lessons cost about 830 tokens.
412
+ **Pushed once at launch** (~4,300 tokens): your profile, standards, the
413
+ project note's path, a digest of the last session, and the lesson topics.
495
414
 
496
- Newest first, capped at `AI_MEM_LESSON_INDEX_LIMIT` (200), with a `+N older`
497
- note when it truncates. The cap is not decoration: past a few hundred
498
- entries, most titles are irrelevant to any given session, and a long tail of
499
- near-miss titles is the most damaging kind of distractor for a model -- the
500
- same reason `ai-mem-search` bounds its own output. A vault with no lessons
501
- adds nothing to the prompt at all.
415
+ **Pulled on demand after that.** Nothing re-injects. The agent reaches the
416
+ vault mid-session only by running `ai-mem-search` itself — which the launch
417
+ prompt tells it to do before solving anything, and again whenever it hits a
418
+ blocker.
419
+
420
+ So: a reference library the agent is told to consult, not a memory it thinks
421
+ with. Two consequences — launch a bare `claude` instead of `claude-start` and
422
+ you get **no vault context at all**, and whether it helps mid-build depends on
423
+ the agent actually searching.
424
+
425
+ ### Mirrored notes are not injected twice
502
426
 
503
- ### What it deliberately is not
427
+ `_Standards.md` ships declaring `mirror_of: _Global_Profile.md`. The launch
428
+ prompt reads both, so injecting both in full restates text the model just
429
+ read.
504
430
 
505
- Substring matching, not word matching: `git` also hits `github` and
506
- `gitignore`. No stemming, no fuzzy matching, no synonyms, no relevance
507
- ranking, no vector search. A term you half-remember will miss.
431
+ When a note declares `mirror_of:`, only the differing lines are injected,
432
+ under a marker naming what was elided. On a real vault, 72 of the mirror's 80
433
+ unique lines were verbatim duplicates: **launch prompt 7,200 → 4,300 tokens,
434
+ nothing lost.**
508
435
 
509
- That is a real limit, and the way around it is the search strategy rather
510
- than the search engine: **start broad and narrow down.** A first query that is
511
- too specific is the usual way to miss what you were looking for. Search
512
- `postgres` before `postgres connection pool timeout`, then add the project
513
- argument once you can see roughly where the answer lives.
436
+ Matching is exact and line-by-line, so anything reworded survives. It fails
437
+ **open** — no frontmatter, a missing source, or an empty diff all inject the
438
+ note in full. Injecting twice costs tokens; dropping a note costs the agent
439
+ context it was promised.
514
440
 
515
- Returns non-zero on no matches, a missing term, or an unknown project, so it
516
- composes in a script.
441
+ ### Lessons are indexed, not injected
442
+
443
+ `_lessons/` entries are the only notes true across projects, and the hardest
444
+ to find — searching for one means guessing a term for knowledge you don't
445
+ know you have. So the launch prompt lists **every lesson slug and no bodies**:
446
+
447
+ ```text
448
+ - Lessons already recorded (96), listed by topic slug only. If one looks
449
+ relevant, read it with `ai-mem-search <slug>` before solving again.
450
+ prisma-connection-pool-exhaustion, decimal-money-precision-js, ...
451
+ ```
517
452
 
453
+ A slug is the lesson compressed: `prisma-connection-pool-exhaustion` tells
454
+ you whether to open it without opening it. ~8 tokens each; 96 lessons cost
455
+ ~830.
456
+
457
+ Newest first, capped at `AI_MEM_LESSON_INDEX_LIMIT` (200). The cap matters —
458
+ past a few hundred, most titles are irrelevant to any given session, and a
459
+ long tail of near-misses is the most damaging kind of distractor for a model.
460
+
461
+ Returns non-zero on no matches, a missing term, or an unknown project, so
462
+ it composes in a script.
518
463
 
519
464
  ## Session skills (optional)
520
465
 
@@ -605,58 +550,40 @@ are sanitized placeholders.
605
550
 
606
551
  ## Open Knowledge Format
607
552
 
608
- [Open Knowledge Format](https://github.com/GoogleCloudPlatform/open-knowledge-format)
609
- (OKF) is Google's vendor-neutral spec for portable, agent-readable knowledge.
610
- An OKF *bundle* is simply a directory tree of markdown files — the unit of
611
- distribution, shippable as a git repo, tarball, or zip, and readable by any
612
- agent, static file server, Obsidian, MkDocs, or graph viewer without a
553
+ [OKF](https://github.com/GoogleCloudPlatform/open-knowledge-format) is
554
+ Google's vendor-neutral spec for portable, agent-readable knowledge. A bundle
555
+ is just a directory tree of markdown files — shippable as a repo, tarball or
556
+ zip, readable by any agent, Obsidian, MkDocs or graph viewer without a
613
557
  translation layer.
614
558
 
615
- Your vault is one. That is convergence rather than adoption: both bet on
616
- plain Markdown in a directory tree, in git, with no runtime.
617
-
618
- The spec is deliberately small. [It requires no file at the bundle
619
- root](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
620
- — `index.md` and `log.md` are optional — and names exactly one required
621
- frontmatter key: *"`type` is the only always-required key; a concept carrying
622
- just `type` is fully conformant."*
559
+ Your vault is one, by convergence rather than adoption. The
560
+ [spec](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)
561
+ requires no file at the bundle root and exactly one frontmatter key:
562
+ *"`type` is the only always-required key."*
623
563
 
624
564
  | OKF | Here |
625
565
  |---|---|
626
- | Markdown files in a directory hierarchy | ✅ `_projects/`, `_lessons/`, `_session_logs/`, `_proposals/` |
566
+ | Markdown in a directory hierarchy | ✅ |
627
567
  | YAML frontmatter | ✅ every note |
628
- | **`type` — the only required key** | ✅ `ai-project-context`, `ai-lesson`, `ai-session-log`, `ai-global-profile`, `ai-standards` |
629
- | Recommended: `title`, `description`, `resource`, `tags` | ⚠️ partial — notes carry their own fields instead |
630
- | Cross-links as standard markdown links | ⚠️ `[[wikilink]]` instead |
631
- | `index.md` / `log.md` | optional in the spec; not generated here |
568
+ | **`type` — the only required key** | ✅ `ai-project-context`, `ai-lesson`, `ai-session-log`, … |
569
+ | Recommended `title` / `description` / `tags` | ⚠️ partial |
570
+ | Cross-links as markdown links | ⚠️ `[[wikilink]]` instead |
571
+ | `index.md` / `log.md` | optional in the spec; not generated |
632
572
  | No SDK, no account, git-versionable | ✅ |
633
573
 
634
- One real deviation: **links stay Obsidian-style.** The vault is meant to be
635
- opened in Obsidian, where the graph view and backlinks are much of why anyone
636
- keeps one, and `ai-mem-search` resolves `[[wikilinks]]` itself. A strict OKF
637
- consumer would not follow them — though the spec already requires consumers
638
- to tolerate links that do not resolve.
574
+ One real deviation: **links stay Obsidian-style**, because the graph view and
575
+ backlinks are much of why anyone keeps a vault. No `index.md` is generated —
576
+ `grep` never reads one and a materialized index goes stale on rename.
639
577
 
640
- No `index.md` is generated, and that is a choice rather than a gap: nothing
641
- here reads one, `grep` does not consult it, and a materialized index is
642
- exactly the thing that goes stale when a file is renamed. The lesson index is
643
- built at launch from the directory itself for the same reason.
644
-
645
- Session logs predate the `type` field, so a vault that has been in use holds
646
- notes without it. `ai-mem-lint` counts them, and `ai-mem-lint --fix`
647
- backfills:
578
+ Session logs predate the `type` field, so a vault in use holds notes without
579
+ it:
648
580
 
649
581
  ```console
650
- $ ai-mem-lint
651
- 350 session log(s) missing the `type:` frontmatter field (Open Knowledge Format requires it). Fix with: ai-mem-lint --fix
652
-
653
582
  $ ai-mem-lint --fix
654
583
  backfilled `type: ai-session-log` into 350 session log(s)
655
584
  ```
656
585
 
657
- It edits in place, preserves existing frontmatter and body, opens a
658
- frontmatter block for a note that had none, and is idempotent — running it
659
- twice does not stack a second field.
586
+ Edits in place, preserves frontmatter and body, idempotent.
660
587
 
661
588
  ## Add another agent
662
589
 
@@ -694,56 +621,35 @@ an agent-run command.
694
621
 
695
622
  ### Graph view
696
623
 
697
- `ai-mem-search` answers a question you already knew to ask. This is for the
698
- other one — what is in there at all, and which notes turned out to be
699
- connected.
624
+ `ai-mem-search` answers a question you already knew to ask. This answers the
625
+ other one — what is in there, and what turned out to be connected.
700
626
 
701
- You should not usually have to run this. **Ask the agent** — "open my memory",
702
- "show me my context" — and it will: the launch prompt tells terminal agents
703
- the viewer exists, and GUI clients get an `open_graph` tool over MCP. Running
704
- it by hand stays available:
627
+ Ask the agent ("open my memory") or run it:
705
628
 
706
629
  ```sh
707
630
  ai-mem-serve # opens a browser at http://127.0.0.1:7777
708
- ai-mem-serve 8080 --no-open
709
631
  ```
710
632
 
711
- Asked twice, the second call finds the first still listening and just opens
712
- the tab. An agent should not have to check whether it is already running, and
713
- a port collision with **its own** server is not a failure worth reporting —
714
- though a port held by something else still is.
715
-
716
633
  ![The vault as a graph: notes coloured by type, a lesson selected, its linked project highlighted](assets/graph-view.png)
717
634
 
718
- Nothing here is a separate database. The vault is already a graph — notes
719
- carrying a `type` in frontmatter with `[[wikilinks]]` between them — so this
720
- only draws what is on disk.
721
-
722
- - **Nodes are coloured by `type`** and sized by how many notes link to them, so
723
- a project that has accumulated forty sessions looks like the hub it is.
724
- - **Selecting a note** dims everything it is not connected to, shows the note
725
- rendered beside the graph, and lists what it links to.
726
- - **Durable knowledge** is the default view. Session logs usually outnumber
727
- everything else several times over and all point at their project, which
728
- buries the projects and lessons inside a hairball. Switch to *Everything* to
729
- see them.
730
- - **Search** and the legend both filter; `/` focuses the search box.
731
-
732
- Bound to `127.0.0.1` only, deliberately. The vault holds project history and
733
- operational detail, and a viewer for it has no business being reachable from
734
- the network. Zero dependencies — the layout is a small force simulation rather
735
- than a charting library, so it works with no network at all.
635
+ Nodes are coloured by `type` and sized by how many notes link to them.
636
+ Selecting one dims everything unconnected and renders the note beside the
637
+ graph. *Durable knowledge* is the default view — session logs usually
638
+ outnumber everything else and bury the rest.
736
639
 
737
- ### GUI clients (MCP)
640
+ Loopback only, deliberately: the vault holds project history. Zero
641
+ dependencies — the layout is a small force simulation, not a charting
642
+ library, so it works offline. Run it twice and the second call just opens the
643
+ tab, unless another vault holds the port.
738
644
 
739
- The `*-start` launchers reach an agent by injecting the vault into its opening
740
- prompt. **A GUI opened from the Dock never runs one** — there is no daemon and
741
- no background service, so Claude Desktop and the Cursor GUI would otherwise
742
- see nothing.
645
+ ### GUI clients (MCP)
743
646
 
744
- `ai-mem-mcp` is the channel for those. Register it once:
647
+ The launchers reach an agent through its opening prompt. **A GUI opened from
648
+ the Dock never runs one**, so Claude Desktop and the Cursor GUI would see
649
+ nothing. `ai-mem-mcp` is their channel.
745
650
 
746
651
  **Claude Desktop** — `~/Library/Application Support/Claude/claude_desktop_config.json`
652
+ (**Cursor** — `~/.cursor/mcp.json`, same shape):
747
653
 
748
654
  ```json
749
655
  {
@@ -756,37 +662,19 @@ see nothing.
756
662
  }
757
663
  ```
758
664
 
759
- **Cursor** — `~/.cursor/mcp.json`, same shape.
760
-
761
665
  Six tools, read **and** write, so a GUI session is not a dead end:
762
- `search_memory`, `get_context`, `read_note`, `add_note`, `add_lesson`, and
763
- `open_graph` (which launches the [graph view](#graph-view) for them). Each
764
- shells out to the same zsh functions the CLI uses, so there is one
765
- implementation of the rules rather than a copy that drifts -- a note written
766
- from Claude Desktop is committed and pushed exactly like one written in a
767
- terminal, and is findable by the next session either way.
768
-
769
- `read_note` compares resolved real paths and refuses anything outside the
770
- vault.
771
-
772
- **Making a GUI behave like a launcher.** In a terminal the vault is pushed
773
- into the agent's opening prompt. Over MCP nothing is pushed, and a model with
774
- no reason to suspect a memory exists will simply never call a tool. The server
775
- returns MCP's `instructions` field at startup -- a short standing brief to read
776
- context first, search before solving, and write back afterwards. That one
777
- field is the difference between a vault the GUI *could* reach and one it
778
- actually uses.
779
-
780
- **On cost.** Tool schemas are re-sent every turn, so their prose is a
781
- recurring tax; the `instructions` brief is sent once. Behaviour guidance
782
- therefore lives in `instructions` and the descriptions stay terse. Adding the
783
- write tools cost nothing per turn as a result: six tools now total ~429
784
- tokens against ~380 for the original four, with a one-time ~227 for the brief.
666
+ `search_memory`, `get_context`, `read_note`, `add_note`, `add_lesson`,
667
+ `open_graph`. Each shells out to the same zsh functions the CLI uses — one
668
+ implementation, not a copy that drifts. A note written from Claude Desktop is
669
+ committed and pushed exactly like one written in a terminal.
670
+
671
+ MCP's `instructions` field carries a standing brief (read context first,
672
+ search before solving, write back after) — without it a model has no reason
673
+ to suspect a memory exists. Tool descriptions stay terse because schemas are
674
+ re-sent every turn: six tools cost ~429 tokens/turn, the brief ~290 once.
785
675
 
786
676
  **Do not register this for a terminal agent.** Claude Code, Codex, Gemini and
787
- opencode all have a shell and should call `ai-mem-search` directly; wrapping a
788
- CLI the agent can already run just adds a layer that can go out of date. MCP
789
- earns its place only where the client has no shell.
677
+ opencode have a shell and should call `ai-mem-search` directly.
790
678
 
791
679
  ### Claude Code hooks
792
680
  The files live in `hooks/claude/`. Record repo `HEAD` at session start, then on
@@ -827,7 +715,8 @@ git -C <repo> config core.hooksPath .githooks
827
715
  | `AI_MEM_AGENTS` | `claude codex gemini cursor opencode` | Space-separated agents to generate `-start` functions for |
828
716
  | `AI_MEM_SKILLS` / `AI_MEM_SKILL_ORDER` | empty | Your per-session skills (see above) |
829
717
  | `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 |
830
- | `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)) |
718
+ | `AI_MEM_SEARCH_LIMIT` | `25` | 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)) |
719
+ | `AI_MEM_SEARCH_PER_FILE` | `1` | Lines shown per file once the cap binds. Spreads results across notes instead of on the chattiest one; ignored when every match already fits |
831
720
 
832
721
  ## Why plain files
833
722
 
package/bin/ai-mem-mcp.js CHANGED
@@ -109,6 +109,8 @@ const INSTRUCTIONS = [
109
109
  '',
110
110
  'Before answering anything about their work, call get_context. It returns their profile, standards, the current project note, and what the last session concluded.',
111
111
  'Before solving a problem, call search_memory -- they may have solved it already, and repeating a solved mistake is the failure this vault exists to prevent. Search broadly first; too specific a first query is the usual way to miss something.',
112
+ 'When you hit a blocker -- an error you do not understand, an unclear failure, or a second failed attempt at the same thing -- search again before guessing. Lessons rank above session logs, so a hit under _lessons/ is the recorded fix.',
113
+ 'Search ONE distinctive word, not a sentence. Matching is literal substring: a whole error line finds nothing, and a bare tool name returns hundreds of irrelevant lines. Pick the most unusual word in the symptom and try two or three separately.',
112
114
  '',
113
115
  'Write back. A session that only reads leaves nothing behind, and the next one starts cold:',
114
116
  '- add_note for what happened, decided, or broke during this session.',
@@ -82,10 +82,45 @@ function frontmatter(text) {
82
82
  return out;
83
83
  }
84
84
 
85
- /** First H1, else the filename -- what a human would call this note. */
86
- function titleOf(text, path) {
87
- const h1 = text.match(/^#\s+(.+)$/m);
88
- return (h1 && h1[1].trim()) || basename(path, '.md');
85
+ /** The note's first H1, or null. */
86
+ function h1Of(text) {
87
+ const m = text.match(/^#\s+(.+)$/m);
88
+ return m ? m[1].trim() : null;
89
+ }
90
+
91
+ /**
92
+ * What to call a note on the graph.
93
+ *
94
+ * The obvious answer -- its first H1 -- is wrong here, because notes are
95
+ * created from templates and inherit the template's heading. On a real vault
96
+ * that made 354 notes read "Session Outcome" and 34 read "Project Snapshot":
97
+ * every project and every log sharing two labels between them, which is worse
98
+ * than no labels at all.
99
+ *
100
+ * So an H1 is only a title if it is *this note's* H1. One shared by several
101
+ * notes is boilerplate by definition, and the rule needs no list of known
102
+ * template headings to maintain -- it corrects itself for any template,
103
+ * including ones a user writes.
104
+ *
105
+ * @param {string} text the note
106
+ * @param {string} path its path
107
+ * @param {object} fm parsed frontmatter
108
+ * @param {Map} h1Counts how many notes share each H1
109
+ */
110
+ function titleOf(text, path, fm, h1Counts) {
111
+ if (fm.title) return fm.title;
112
+ if (fm.project_name) return fm.project_name;
113
+
114
+ const h1 = h1Of(text);
115
+ if (h1 && h1Counts.get(h1) === 1) return h1;
116
+
117
+ // Fall back to the filename, which is always specific. A session log's name
118
+ // is <project>-<date>_<time>, and the project is already obvious from the
119
+ // node it is attached to -- so show the moment, which is the part that
120
+ // distinguishes it from its forty siblings.
121
+ const name = basename(path, '.md');
122
+ const stamp = name.match(/(\d{4}-\d{2}-\d{2})_(\d{2})-(\d{2})-\d{2}$/);
123
+ return stamp ? stamp[1] + ' ' + stamp[2] + ':' + stamp[3] : name;
89
124
  }
90
125
 
91
126
  const LINK_RE = /\[\[([^\]|#]+)/g;
@@ -103,6 +138,11 @@ function buildGraph() {
103
138
  const nodes = [];
104
139
  const byBasename = new Map();
105
140
 
141
+ // Read once, keep the text: the vault is a few megabytes of markdown, and
142
+ // reading every file twice to count headings first would double the work
143
+ // for no reason.
144
+ const read = [];
145
+ const h1Counts = new Map();
106
146
  for (const f of files) {
107
147
  let text;
108
148
  try {
@@ -110,10 +150,16 @@ function buildGraph() {
110
150
  } catch {
111
151
  continue;
112
152
  }
153
+ read.push([f, text]);
154
+ const h = h1Of(text);
155
+ if (h) h1Counts.set(h, (h1Counts.get(h) || 0) + 1);
156
+ }
157
+
158
+ for (const [f, text] of read) {
113
159
  const fm = frontmatter(text);
114
160
  const node = {
115
161
  id: relative(VAULT, f),
116
- title: fm.title || titleOf(text, f),
162
+ title: titleOf(text, f, fm, h1Counts),
117
163
  type: fm.type || 'untyped',
118
164
  tags: Array.isArray(fm.tags) ? fm.tags : fm.tags ? [fm.tags] : [],
119
165
  description: fm.description || '',
@@ -225,16 +271,38 @@ server.on('error', (err) => {
225
271
  }
226
272
  const url = 'http://127.0.0.1:' + PORT;
227
273
  http.get(url + '/api/graph', (res) => {
228
- if (res.statusCode !== 200) return bail();
229
- res.resume();
230
- console.log('ai-mem-serve: already running');
231
- console.log(' ' + url);
232
- openBrowser(url);
233
- process.exit(0);
234
- }).on('error', bail);
235
-
236
- function bail() {
237
- console.error('ai-mem-serve: port ' + PORT + ' is in use by something else. Pass a different port.');
274
+ if (res.statusCode !== 200) return bail('something else');
275
+ let body = '';
276
+ res.setEncoding('utf8');
277
+ res.on('data', (c) => { body += c; });
278
+ res.on('end', () => {
279
+ // Being an ai-mem-serve is not enough -- it has to be serving THIS
280
+ // vault. A leftover server from a test run or another vault answers
281
+ // /api/graph perfectly well, and attaching to it silently shows the
282
+ // wrong notes while reporting success. That is the failure this whole
283
+ // tool exists to avoid, so compare the vault it names.
284
+ let serving;
285
+ try {
286
+ serving = JSON.parse(body).vault;
287
+ } catch {
288
+ return bail('something else');
289
+ }
290
+ if (serving !== VAULT) {
291
+ console.error('ai-mem-serve: port ' + PORT + ' is already serving a different vault:');
292
+ console.error(' running: ' + serving);
293
+ console.error(' wanted: ' + VAULT);
294
+ console.error('Stop that server, or pass another port: ai-mem-serve ' + (PORT + 1));
295
+ process.exit(1);
296
+ }
297
+ console.log('ai-mem-serve: already running');
298
+ console.log(' ' + url);
299
+ openBrowser(url);
300
+ process.exit(0);
301
+ });
302
+ }).on('error', () => bail('something else'));
303
+
304
+ function bail(what) {
305
+ console.error('ai-mem-serve: port ' + PORT + ' is in use by ' + what + '. Pass a different port.');
238
306
  process.exit(1);
239
307
  }
240
308
  });
@@ -22,7 +22,17 @@ const pkgRoot = resolve(__dirname, '..'); // bundled tool
22
22
  const dest = resolve(process.argv[2] || join(homedir(), 'ai-memory'));
23
23
 
24
24
  // Files that make up the tool; copied verbatim from the package into dest.
25
- const ITEMS = ['shell', 'hooks', 'vault-template', 'install.sh', 'create-ai-memory.plugin.zsh', 'LICENSE'];
25
+ //
26
+ // `bin` and `web` are as load-bearing as `shell`: ai-mem-serve is the graph
27
+ // viewer and ai-mem-mcp is how GUI clients reach the vault at all. Both were
28
+ // added to package.json's `files` when they were written, so they shipped in
29
+ // the tarball -- and stopped there, because this list was never updated. A
30
+ // user who installed the documented way got neither, while the README told
31
+ // them to run both.
32
+ //
33
+ // package.json comes along because ai-mem-mcp reports its own version from it;
34
+ // without it the server introduced itself to every client as 0.0.0.
35
+ const ITEMS = ['shell', 'bin', 'web', 'hooks', 'vault-template', 'install.sh', 'create-ai-memory.plugin.zsh', 'package.json', 'LICENSE'];
26
36
 
27
37
  console.log(`create-ai-memory: installing into ${dest}`);
28
38
  mkdirSync(dest, { recursive: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ai-memory",
3
- "version": "0.14.1",
3
+ "version": "0.14.3",
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",
package/shell/ai-mem.zsh CHANGED
@@ -98,6 +98,30 @@ __ai_mem_vault_backup() {
98
98
  # ai-note/ai-lesson -- e.g. the update-session-log skill, which edits the
99
99
  # Session Outcome section directly and has no other reason to know this
100
100
  # function exists.
101
+ # The graph viewer and the MCP server are Node scripts shipped beside this
102
+ # module. They are declared as npm `bin` entries too, but `npm create` copies
103
+ # the tool into a folder rather than installing it globally, so nothing puts
104
+ # them on PATH -- exposing them as functions is what makes the documented
105
+ # commands work for everyone, however they installed.
106
+ #
107
+ # The bundled copy wins over anything on PATH: it is guaranteed to match the
108
+ # module the shell just sourced, which a separately-installed global may not.
109
+ __ai_mem_node_bin() {
110
+ local script="$AI_MEM_HOME/../bin/$1"
111
+ shift
112
+ if [[ -f "$script" ]]; then
113
+ command node "$script" "$@"
114
+ elif command -v "${1:-}" >/dev/null 2>&1; then
115
+ command "$@"
116
+ else
117
+ print -r -- "$script is missing -- reinstall with: npm create ai-memory@latest" >&2
118
+ return 1
119
+ fi
120
+ }
121
+
122
+ ai-mem-serve() { __ai_mem_node_bin ai-mem-serve.js "$@" }
123
+ ai-mem-mcp() { __ai_mem_node_bin ai-mem-mcp.js "$@" }
124
+
101
125
  ai-mem-vault-backup() {
102
126
  # Fail loudly if the helper is absent. Without this the function still
103
127
  # "works": HEAD does not move, so it prints "nothing to commit" and exits
@@ -458,6 +482,8 @@ Use the Obsidian vault as the persistent memory layer.
458
482
  Treat the global profile and standards note as the shared baseline for every run.
459
483
  Keep durable preferences and project facts in the vault, and keep the active session log updated with decisions, blockers, and next steps.
460
484
  For anything not covered above -- a decision from further back, a different project, a health check on the vault's links -- run \`ai-mem-search <term> [project]\` or \`ai-mem-lint\` yourself; both are plain shell commands already on PATH. Search is case-insensitive and matches literally, and its output is capped: if it reports results hidden, narrow with a project argument or a more specific term rather than assuming you have seen everything. Start broad and narrow from there -- a first query that is too specific is the usual way to miss what you were looking for.
485
+ When you hit a blocker -- an error you do not immediately understand, a test failing for an unclear reason, a decision you cannot settle from the code in front of you, or a second failed attempt at the same thing -- search the vault BEFORE guessing again. You have likely been here before, and \`_lessons/\` exists because the answer usually was written down; lessons are ranked above session logs in the results, so a hit under \`_lessons/\` is the recorded fix.
486
+ Search ONE distinctive word, not a sentence. Matching is literal substring, so a whole error line ('command not found: sed') finds nothing while 'command not found' finds it, and a bare tool name ('sed', 'git') returns hundreds of irrelevant lines. Pick the most unusual word in the symptom and try two or three of them separately.
461
487
  If the user asks to see, open or browse their memory rather than search it, run \`ai-mem-serve\` -- it opens the vault as a graph in their browser, and is safe to run again if it is already up.
462
488
  When you hit a mistake, decision, or solution worth remembering across projects (not just this one), run \`ai-lesson <topic-slug> <problem> <solution>\` -- e.g. \`ai-lesson rate-limiting "a fixed-window limiter kept losing bursts of legitimate traffic" "switched to a token bucket, which absorbs bursts correctly"\`. It appends a dated Problem/Solution entry to a cross-project note at _lessons/<topic-slug>.md; ai-mem-search already covers it.
463
489
  EOF
@@ -955,14 +981,28 @@ ai-mem-search() {
955
981
  # -- while the grep that actually searched it took 0.16s. Measuring grep
956
982
  # alone said this command was fast; measuring the command said otherwise.
957
983
  # Interval syntax like {4} is avoided so this works on a stock BSD awk.
984
+ # Lessons outrank everything else, then newest-first within each group.
985
+ #
986
+ # Recency alone was wrong for the case that matters most: hitting a blocker
987
+ # you have hit before. Session logs outnumber lessons roughly four to one
988
+ # and are always newer, so they swept the result set -- searching
989
+ # "snapshot" on a real vault returned 25 session logs and none of the
990
+ # THREE lessons that answer it exactly. The durable answer was in the
991
+ # vault and unreachable.
992
+ #
993
+ # Sort key is rank + timestamp: "0" for _lessons/, "1" for everything
994
+ # else, so a lesson with an old date still beats today's chatter.
958
995
  local sorted
959
- sorted="$(print -r -- "$raw" | awk '
996
+ sorted="$(print -r -- "$raw" | awk -v root="$search_root/" '
960
997
  {
961
998
  ts = "0000-00-00_00-00-00"
962
999
  if (match($0, /[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]-[0-9][0-9]-[0-9][0-9]/))
963
1000
  ts = substr($0, RSTART, RLENGTH)
964
- print ts "|" $0
965
- }' | sort -r | cut -d'|' -f2-)"
1001
+ rel = $0
1002
+ sub(root, "", rel)
1003
+ rank = (rel ~ /^_lessons\//) ? "1" : "0"
1004
+ print rank "|" ts "|" $0
1005
+ }' | sort -r | cut -d'|' -f3-)"
966
1006
 
967
1007
  # Bound the output. The consumer is normally an agent with a finite
968
1008
  # context window, and an unbounded dump is actively harmful there in a
@@ -973,9 +1013,32 @@ ai-mem-search() {
973
1013
  # distractor for a model, so fewer, cleaner hits beat more of them.
974
1014
  # Count goes FIRST -- the reader needs the size of the result set before
975
1015
  # the result set, not after it.
976
- local total limit
1016
+ local total limit per_file
977
1017
  total="$(print -r -- "$raw" | wc -l | tr -d ' ')"
978
- limit="${AI_MEM_SEARCH_LIMIT:-40}"
1018
+ limit="${AI_MEM_SEARCH_LIMIT:-25}"
1019
+ per_file="${AI_MEM_SEARCH_PER_FILE:-1}"
1020
+
1021
+ # Spend the line budget on distinct sources rather than on whichever note
1022
+ # happens to be chattiest. Measured on a real vault: 'prisma' matched 82
1023
+ # files, but one long session log took 9 of the 40 slots and the output
1024
+ # reached only 14 of them. Capping lines per file reaches roughly three
1025
+ # times as many notes for the same tokens, which is the number that
1026
+ # actually decides whether the answer is in there.
1027
+ #
1028
+ # Applied after the sort, so the lines kept from each file are its newest.
1029
+ # Only engage when the budget actually binds. If every match fits, showing
1030
+ # all of them beats withholding lines from a note that had three -- the
1031
+ # cap exists to allocate a scarce budget, and nothing is scarce here.
1032
+ local spread
1033
+ if (( total > limit )); then
1034
+ spread="$(print -r -- "$sorted" | awk -v cap="$per_file" '
1035
+ { f = $0; sub(/:[0-9]+:.*$/, "", f); if (++seen[f] <= cap) print }')"
1036
+ else
1037
+ spread="$sorted"
1038
+ fi
1039
+ local files_shown
1040
+ files_shown="$(print -r -- "$spread" | head -n "$limit" | awk '
1041
+ { f = $0; sub(/:[0-9]+:.*$/, "", f); seen[f] = 1 } END { print length(seen) }')"
979
1042
 
980
1043
  print -r -- "$total match(es) for '$term'"
981
1044
  print -r -- "paths below $search_root"
@@ -983,13 +1046,21 @@ ai-mem-search() {
983
1046
  # Strip the repeated vault root (a third to a half of all output bytes on
984
1047
  # a real vault, with zero information lost -- it is printed once above)
985
1048
  # and clamp very long lines, which are common in prose notes.
986
- print -r -- "$sorted" | head -n "$limit" \
1049
+ local shown
1050
+ shown="$(print -r -- "$spread" | head -n "$limit")"
1051
+ print -r -- "$shown" \
987
1052
  | sed "s|^${search_root}/||" \
988
1053
  | awk '{ if (length($0) > 200) print substr($0, 1, 200) " [...]"; else print }'
989
1054
 
990
- if (( total > limit )); then
1055
+ local shown_n
1056
+ shown_n="$(print -r -- "$shown" | wc -l | tr -d ' ')"
1057
+ if (( total > shown_n )); then
991
1058
  print -r -- "--"
992
- print -r -- "showing $limit of $total ($(( total - limit )) hidden) -- narrow with: ai-mem-search '$term' <project>, or raise AI_MEM_SEARCH_LIMIT"
1059
+ # The withheld count stays explicit. "showing 25 of 240" implies it,
1060
+ # but the reader has to be able to tell "hidden" from "absent" without
1061
+ # doing arithmetic -- that distinction is the whole reason this line
1062
+ # exists.
1063
+ print -r -- "showing $shown_n of $total ($(( total - shown_n )) hidden), across $files_shown file(s), at most $per_file line(s) each -- for more lines per file raise AI_MEM_SEARCH_PER_FILE, or narrow with: ai-mem-search '$term' <project>"
993
1064
  fi
994
1065
  # One hop out: resolve [[wikilinks]] found on matched lines to their
995
1066
  # target note (currently: project notes only -- the confirmed use case