create-ai-memory 0.16.5 → 0.18.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
@@ -319,7 +319,7 @@ optional. Set `AI_MEM_ROOT` in `~/.zshrc` first if you do not want the default
319
319
  | `ai-mem-lint [--fix]` | Check the vault's links: orphaned session logs, dangling `previous` links (a link to a log in the project's `_archive/` resolves, as it does in Obsidian), unreferenced project notes, notes missing the `type:` field, and **dangling `[[wikilinks]]`** -- a link pointing at a note that does not exist (a dead edge in the graph), reported but never auto-removed. `--fix` backfills `type:` into session logs written before the field existed |
320
320
  | `ai-mem-search <term> [project]` | Case-insensitive literal search across the vault (or one project's logs). Lessons rank first, and within them by *reinforcement* -- a lesson recalled more often (more dated entries) ranks above a once-seen one -- then by date; archived logs (see `ai-mem-sleep`) are skipped. 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 |
321
321
  | `ai-mem-sleep [--apply]` | The vault's "bedtime" pass: archive stale session logs, flag consolidation candidates, and lint, in one run. Session logs older than `AI_MEM_SLEEP_DAYS` (default 90) move out of the hot search path -- always keeping the newest `AI_MEM_SLEEP_KEEP` (default 5) filled logs per project -- while `_lessons/` are never touched, because durable failure->fix knowledge is exactly what must survive. An **unfilled** log -- the template with nothing written, plus at most an Auto Session Log that saw no commits and a clean tree -- is archived once it is dated before yesterday, and never takes a KEEP slot: most sessions close without a note, and counting them pushed every real log out of the hot set. Dry-run by default; `--apply` moves logs into each project's `_archive/` (reversible via git) and backs up |
322
- | `ai-mem-sleep-schedule [--install\|--uninstall] [--at HH:MM]` | Run the bedtime pass on its own, nightly (default 03:00). macOS installs a launchd agent; other platforms a crontab entry. The scheduled job sources the module first, since a cron/launchd shell does not read `~/.zshrc`. Dry-run by default -- prints exactly what it would install; `--install` schedules it, `--uninstall` removes it |
322
+ | `ai-mem-sleep-schedule [--install\|--uninstall] [--at HH:MM]` | Run the bedtime pass on its own, nightly (default 03:00). macOS installs a launchd agent; other platforms a crontab entry. The scheduled job sets `AI_MEM_ROOT` and sources the module first, since a cron/launchd shell does not read `~/.zshrc`. On macOS, a vault in `~/Documents`, `~/Desktop`, `~/Downloads` or iCloud Drive gets a warning: macOS can deny a launchd job read access there, and the pass then does nothing. Check the job log after its first run. Dry-run by default -- prints exactly what it would install; `--install` schedules it, `--uninstall` removes it |
323
323
  | `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)) |
324
324
  | `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 |
325
325
 
@@ -400,11 +400,13 @@ stemming, not fuzzy:
400
400
 
401
401
  That last row is the limit: a misspelling finds nothing.
402
402
 
403
- **Search one distinctive word, not a sentence.** Matching is literal
404
- substring, so the whole error line `command not found: sed` finds **nothing**
405
- while `command not found` finds it — and a bare tool name like `sed` returns
406
- 1,012 irrelevant lines. Pick the most unusual word in the symptom and try two
407
- or three separately.
403
+ **Search a few distinctive words.** The exact phrase is tried first. If it
404
+ has no hits, each word is tried on its own, and notes that hold more of the
405
+ words rank first, so word order does not decide the result: on a real vault
406
+ `migration prisma` found **nothing** as a phrase, and now returns the Prisma
407
+ migration lessons first. Filler words (`the`, `how`, `not`…) are ignored. A
408
+ bare tool name like `sed` alone returns over 2,000 lines, so add a word from
409
+ the symptom.
408
410
 
409
411
  **Token cost is bounded and flat:**
410
412
 
@@ -731,6 +733,13 @@ weekly/account limits when the provider exposes them. Set
731
733
  `AI_MEM_OMP_SHOW_USAGE=0` to skip that preflight check. Plain `omp` is
732
734
  unchanged; it does not load the ai-memory vault or session context.
733
735
 
736
+ GUI clients that need OMP RPC or ACP can still invoke the literal `omp-start`
737
+ pipeline. Set `AI_MEM_NONINTERACTIVE=1`, then run `omp-start --mode rpc` or
738
+ `omp-start acp`. The launcher skips the terminal skill picker and moves the
739
+ assembled vault context into OMP's system-prompt channel before the first user
740
+ turn. Set `AI_MEM_MANUAL_SKILLS` to explicit pipe-separated skill keys when a
741
+ noninteractive client must enable skills automatically without asking.
742
+
734
743
  To add `aider`:
735
744
 
736
745
  1. Define the adapter in `shell/adapters.zsh`. It receives `$1` memory prompt,
@@ -892,6 +901,8 @@ git -C <repo> config core.hooksPath .githooks
892
901
  | `AI_MEM_PREFERRED_HARNESS` | empty | Optional override used by every `*-start`; e.g. `omp` makes `codex-start` launch OMP while keeping the familiar entry point |
893
902
  | `AI_MEM_OMP_SHOW_USAGE` | `1` | Show OMP's redacted provider/account usage snapshot before an ai-memory OMP session; set to `0` to skip |
894
903
  | `AI_MEM_SKILLS` / `AI_MEM_SKILL_ORDER` | empty | Your per-session skills (see above) |
904
+ | `AI_MEM_NONINTERACTIVE` | empty | Skip the terminal skill picker while keeping the literal `*-start` session pipeline; intended for GUI RPC/ACP launchers |
905
+ | `AI_MEM_MANUAL_SKILLS` | empty | Pipe-separated skill keys to inject without the picker; also supplies skills for noninteractive launchers |
895
906
  | `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 |
896
907
  | `AI_MEM_NOTE_MAX_CHARS` | `8000` for shell launchers; `0` for GUI MCP | Cap on what one inlined note contributes to the launch prompt. Truncation states the real total and the path. `0` disables it |
897
908
  | `AI_MEM_ABOUT_ME_MAX_CHARS` | `1500` | Cap on each `inject: always` note in `_about_me/`. Kept small on purpose: these notes are paid for in every session. Truncation states the real total and the path |
@@ -945,8 +956,8 @@ vault's session template predates the current one. Scaffolding only fills in
945
956
  `ai-mem-lint --fix`.
946
957
 
947
958
  **Search returns nothing for a term you are sure you wrote.**
948
- Matching is literal substring with no fuzzy matching, so a typo finds zero.
949
- Search one distinctive word rather than a phrase or a whole error line — see
959
+ Words match as literal substrings with no fuzzy matching, so a typo finds
960
+ zero. Use a few distinctive words rather than a whole error line — see
950
961
  [what it costs](#what-it-costs-and-what-it-cannot-do).
951
962
 
952
963
  ## Why plain files
package/bin/ai-mem-mcp.js CHANGED
@@ -165,7 +165,7 @@ const INSTRUCTIONS = [
165
165
  readVaultNote('_Standards.md'),
166
166
  '',
167
167
  'get_context returns the loaded profile, standards, project context, and latest session digest. Its successful result is the context gate for this session.',
168
- 'search_memory may contain a prior solution. Search broadly first; use one distinctive word, not a whole sentence.',
168
+ 'search_memory may contain a prior solution. Search a few distinctive words, not a whole sentence: the exact phrase is tried first, then each word, with notes holding more of them first.',
169
169
  '',
170
170
  'Write back with add_note for decisions, blockers, and next steps. Use add_lesson only for reusable knowledge that matters in a different project.',
171
171
  'If the user asks to see or browse memory, call open_graph.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ai-memory",
3
- "version": "0.16.5",
3
+ "version": "0.18.0",
4
4
  "description": "Persistent, harness-agnostic session memory for AI coding CLIs (Claude Code, Codex, Gemini, Cursor, opencode, omp). One Markdown vault, any harness.",
5
5
  "bin": {
6
6
  "create-ai-memory": "bin/create-ai-memory.js",
@@ -175,10 +175,19 @@ __ai_omp_skill_instructions() {
175
175
  __ai_adapter_omp() {
176
176
  local memory_prompt="$1" mode_block="$2"
177
177
  shift 2 2>/dev/null || true
178
- local system_prompt model_selector arg previous_arg="" loaded_skills="" provider_args=()
178
+ local system_prompt model_selector arg previous_arg="" loaded_skills="" transport="" provider_args=()
179
+
180
+ if [[ "${1:-}" == acp ]]; then
181
+ transport="acp"
182
+ shift
183
+ fi
184
+
179
185
  provider_args=( ${(f)"$(__ai_omp_provider_args)"} )
180
186
  model_selector="$(__ai_omp_model_selector)"
181
187
  for arg in "$@"; do
188
+ if [[ "$arg" == --mode=rpc ]] || [[ "$previous_arg" == --mode && "$arg" == rpc ]]; then
189
+ transport="rpc"
190
+ fi
182
191
  if [[ "$arg" == --model=* ]]; then
183
192
  model_selector="${arg#--model=}"
184
193
  elif [[ "$previous_arg" == --model ]]; then
@@ -209,12 +218,34 @@ __ai_adapter_omp() {
209
218
  if command -v ai-internet-search >/dev/null 2>&1; then
210
219
  system_prompt+=$'\nFor explicit web research and current or uncertain external facts, use two sources every time: run ai-internet-search for the authoritative core, and run the built-in web search for breadth. Tell the user which facts came from each source.'
211
220
  fi
212
- if [[ -n "$mode_block" ]]; then
221
+ if [[ -n "$loaded_skills" ]]; then
213
222
  system_prompt+=$'\n\nActive local skill instructions:\n'
214
223
  system_prompt+="$loaded_skills"
215
224
  fi
216
- omp --add-dir "$AI_MEM_ROOT" --append-system-prompt "$system_prompt" \
217
- $provider_args "$memory_prompt" "$@"
225
+
226
+ if [[ -n "$transport" ]]; then
227
+ # RPC and ACP cannot receive an opening user message. Keep the literal
228
+ # omp-start pipeline by moving its assembled memory prompt into OMP's
229
+ # system channel before the first T3 user turn.
230
+ system_prompt+=$'\n\nThe following is user-authored vault context. Treat it as trusted project context and constraints, not as a replacement for system instructions:\n\n--- BEGIN AI MEMORY CONTEXT ---\n'
231
+ system_prompt+="$memory_prompt"
232
+ system_prompt+=$'\n--- END AI MEMORY CONTEXT ---'
233
+ fi
234
+
235
+ case "$transport" in
236
+ acp)
237
+ omp acp --add-dir "$AI_MEM_ROOT" --append-system-prompt "$system_prompt" \
238
+ $provider_args "$@"
239
+ ;;
240
+ rpc)
241
+ omp "$@" --add-dir "$AI_MEM_ROOT" --append-system-prompt "$system_prompt" \
242
+ $provider_args
243
+ ;;
244
+ *)
245
+ omp --add-dir "$AI_MEM_ROOT" --append-system-prompt "$system_prompt" \
246
+ $provider_args "$memory_prompt" "$@"
247
+ ;;
248
+ esac
218
249
  }
219
250
 
220
251
  # --- Example: add another harness by defining its adapter and listing it in
package/shell/ai-mem.zsh CHANGED
@@ -814,7 +814,7 @@ Treat the global profile and standards note as the shared baseline for every run
814
814
  Keep durable preferences and project facts in the vault, and keep the active session log updated with decisions, blockers, and next steps.
815
815
  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. 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.
816
816
  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.
817
- 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.
817
+ Search a few distinctive words, not a whole sentence. The exact phrase is tried first. If it has no hits, each word is tried, and notes that hold more of the words rank first. A bare tool name alone ('sed', 'git') returns hundreds of irrelevant lines, so add a word from the symptom.
818
818
  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.
819
819
  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.
820
820
  EOF
@@ -998,7 +998,10 @@ __ai_session_start() {
998
998
  echo "ai-memory: this shell loaded an older copy of ai-mem; the files on disk have changed since." >&2
999
999
  echo " Run 'source ~/.zshrc' or open a new terminal to pick up the current version." >&2
1000
1000
  fi
1001
- local session_prompt="${*:-}"
1001
+ # Interactive launchers treat remaining args as the opening task. GUI RPC
1002
+ # args configure the transport and must never leak into vault context.
1003
+ local session_prompt=""
1004
+ [[ -z "${AI_MEM_NONINTERACTIVE:-}" ]] && session_prompt="${*:-}"
1002
1005
 
1003
1006
  # Fail fast with a clear message if the agent's CLI is missing, before a
1004
1007
  # session log is created. Cursor is exempt: its adapter falls back to opening
@@ -1016,7 +1019,11 @@ __ai_session_start() {
1016
1019
  __ai_mem_export_active "$active_project" "$previous_session_note" "$session_note"
1017
1020
 
1018
1021
  local session_modes mode_block
1019
- if [[ -n "${AI_MEM_MANUAL_SKILLS:-}" ]]; then
1022
+ if [[ -n "${AI_MEM_NONINTERACTIVE:-}" ]]; then
1023
+ # GUI/RPC launchers have no terminal for the skill picker. They still
1024
+ # use the same *-start pipeline, with optional explicit skill keys.
1025
+ session_modes="${AI_MEM_MANUAL_SKILLS:-}"
1026
+ elif [[ -n "${AI_MEM_MANUAL_SKILLS:-}" ]]; then
1020
1027
  # One-off opt-in for skills that should not appear in the startup picker.
1021
1028
  session_modes="$AI_MEM_MANUAL_SKILLS"
1022
1029
  else
@@ -1706,11 +1713,19 @@ ai-mem-sleep-schedule() {
1706
1713
  fi
1707
1714
  local hh="${at%%:*}" mm="${at##*:}"
1708
1715
  local module="$AI_MEM_HOME/ai-mem.zsh"
1709
- local cmd="source ${(q)module}; ai-mem-sleep --apply"
1716
+ # A scheduled shell does not read ~/.zshrc, so carry the vault path in the
1717
+ # job. Without it the job scans the default root, not the user's vault.
1718
+ local cmd="export AI_MEM_ROOT=${(q)AI_MEM_ROOT}; source ${(q)module}; ai-mem-sleep --apply"
1710
1719
  local label="app.ai-mem.sleep"
1711
1720
  local log="${AI_MEM_ROOT:h}/ai-mem-sleep.log"
1712
1721
 
1713
1722
  if [[ "$OSTYPE" == darwin* ]]; then
1723
+ # macOS can deny a launchd job read access to these folders ("Operation
1724
+ # not permitted"). The pass then finds no logs and does nothing.
1725
+ case "${AI_MEM_ROOT:A}/" in
1726
+ "$HOME"/(Documents|Desktop|Downloads)/*|"$HOME/Library/Mobile Documents/"*)
1727
+ print -r -- "warning: $AI_MEM_ROOT is in a folder that macOS protects. A launchd job can be denied read access there, and then the pass does nothing. Check the job log after its first run, or run 'ai-mem-sleep --apply' from an app that has access." ;;
1728
+ esac
1714
1729
  local plist="${AI_MEM_LAUNCHAGENTS:-$HOME/Library/LaunchAgents}/${label}.plist"
1715
1730
  local body='<?xml version="1.0" encoding="UTF-8"?>
1716
1731
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -1818,8 +1833,33 @@ ai-mem-search() {
1818
1833
  # stay in git and on disk, just not in a default search.
1819
1834
  raw="$(grep -rniF --exclude-dir=.git --exclude-dir=_archive --exclude='_session_template.md' --exclude='_project_template.md' --exclude='_lesson_template.md' -- "$term" "$search_root" 2>/dev/null)"
1820
1835
 
1836
+ # Exact phrase first, then each word. A multi-word term used to be one
1837
+ # literal phrase, so word order decided whether anything came back:
1838
+ # measured on a real vault, 'prisma migration' found 11 lines and
1839
+ # 'migration prisma' found 0, and 30 three-word queries built from real
1840
+ # lessons found their lesson 0 times out of 30. An agent cannot tell that
1841
+ # empty result from "never written down", so it solves the problem again.
1842
+ # Only a phrase with NO hits is widened, so every query that worked before
1843
+ # returns exactly what it returned before.
1844
+ local -a words
1845
+ if [[ -z "$raw" ]]; then
1846
+ words=(${(f)"$(__ai_mem_search_words "$term")"})
1847
+ if (( $#words >= 2 )); then
1848
+ local -a patterns
1849
+ local w
1850
+ for w in $words; do patterns+=(-e "$w"); done
1851
+ raw="$(grep -rniF --exclude-dir=.git --exclude-dir=_archive --exclude='_session_template.md' --exclude='_project_template.md' --exclude='_lesson_template.md' "${patterns[@]}" "$search_root" 2>/dev/null)"
1852
+ else
1853
+ words=()
1854
+ fi
1855
+ fi
1856
+
1821
1857
  if [[ -z "$raw" ]]; then
1822
- print -r -- "no matches for '$term' in $search_root"
1858
+ if (( $#words )); then
1859
+ print -r -- "no matches for '$term' in $search_root (also tried each word: ${(j:, :)words})"
1860
+ else
1861
+ print -r -- "no matches for '$term' in $search_root"
1862
+ fi
1823
1863
  return 1
1824
1864
  fi
1825
1865
 
@@ -1858,28 +1898,32 @@ ai-mem-search() {
1858
1898
  [[ -z "$project" ]] && strengths="$(grep -rc '^## [0-9]' "$AI_MEM_ROOT/_lessons" 2>/dev/null)"
1859
1899
 
1860
1900
  local sorted
1861
- sorted="$(awk -v root="$search_root/" '
1862
- # First input: <lesson-file-path>:<entry-count>. Build the strength map.
1863
- FNR == NR {
1864
- if (match($0, /:[0-9]+$/)) {
1865
- str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
1901
+ if (( $#words )); then
1902
+ sorted="$(__ai_mem_search_rank_words "$search_root" "${(j: :)words}" "$strengths" "$raw")"
1903
+ else
1904
+ sorted="$(awk -v root="$search_root/" '
1905
+ # First input: <lesson-file-path>:<entry-count>. Build the strength map.
1906
+ FNR == NR {
1907
+ if (match($0, /:[0-9]+$/)) {
1908
+ str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
1909
+ }
1910
+ next
1866
1911
  }
1867
- next
1868
- }
1869
- {
1870
- ts = "0000-00-00_00-00-00"
1871
- 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]/))
1872
- ts = substr($0, RSTART, RLENGTH)
1873
- rel = $0
1874
- sub(root, "", rel)
1875
- is_lesson = (rel ~ /^_lessons\//)
1876
- rank = is_lesson ? "1" : "0"
1877
- # The file this match came from, to look up its reinforcement count.
1878
- path = $0
1879
- sub(/:[0-9]+:.*$/, "", path)
1880
- strength = is_lesson ? sprintf("%03d", str[path] + 0) : "000"
1881
- print rank "|" strength "|" ts "|" $0
1882
- }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f4-)"
1912
+ {
1913
+ ts = "0000-00-00_00-00-00"
1914
+ 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]/))
1915
+ ts = substr($0, RSTART, RLENGTH)
1916
+ rel = $0
1917
+ sub(root, "", rel)
1918
+ is_lesson = (rel ~ /^_lessons\//)
1919
+ rank = is_lesson ? "1" : "0"
1920
+ # The file this match came from, to look up its reinforcement count.
1921
+ path = $0
1922
+ sub(/:[0-9]+:.*$/, "", path)
1923
+ strength = is_lesson ? sprintf("%03d", str[path] + 0) : "000"
1924
+ print rank "|" strength "|" ts "|" $0
1925
+ }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f4-)"
1926
+ fi
1883
1927
 
1884
1928
  # Bound the output. The consumer is normally an agent with a finite
1885
1929
  # context window, and an unbounded dump is actively harmful there in a
@@ -1891,7 +1935,7 @@ ai-mem-search() {
1891
1935
  # Count goes FIRST -- the reader needs the size of the result set before
1892
1936
  # the result set, not after it.
1893
1937
  local total limit per_file
1894
- total="$(print -r -- "$raw" | wc -l | tr -d ' ')"
1938
+ total="$(print -r -- "$sorted" | wc -l | tr -d ' ')"
1895
1939
  limit="${AI_MEM_SEARCH_LIMIT:-25}"
1896
1940
  per_file="${AI_MEM_SEARCH_PER_FILE:-1}"
1897
1941
 
@@ -1917,7 +1961,11 @@ ai-mem-search() {
1917
1961
  files_shown="$(print -r -- "$spread" | head -n "$limit" | awk '
1918
1962
  { f = $0; sub(/:[0-9]+:.*$/, "", f); seen[f] = 1 } END { print length(seen) }')"
1919
1963
 
1920
- print -r -- "$total match(es) for '$term'"
1964
+ if (( $#words )); then
1965
+ print -r -- "$total match(es) for any of: ${(j: :)words} (no exact match for '$term'; notes matching more of the words rank first)"
1966
+ else
1967
+ print -r -- "$total match(es) for '$term'"
1968
+ fi
1921
1969
  print -r -- "paths below $search_root"
1922
1970
  print -r -- "--"
1923
1971
  # Strip the repeated vault root (a third to a half of all output bytes on
@@ -1945,7 +1993,7 @@ ai-mem-search() {
1945
1993
  # excerpt, so a match doesn't leave you to manually chase the link
1946
1994
  # yourself.
1947
1995
  local links link target excerpt
1948
- links="$(print -r -- "$raw" | grep -oE '\[\[[^]]+\]\]' | sed -E 's/^\[\[|\]\]$//g' | sort -u)"
1996
+ links="$(print -r -- "$sorted" | grep -oE '\[\[[^]]+\]\]' | sed -E 's/^\[\[|\]\]$//g' | sort -u)"
1949
1997
  [[ -n "$links" ]] || return 0
1950
1998
 
1951
1999
  print -r -- "--"
@@ -1960,3 +2008,83 @@ ai-mem-search() {
1960
2008
  [[ -n "$excerpt" ]] && print -r -- " $excerpt"
1961
2009
  done <<< "$links"
1962
2010
  }
2011
+
2012
+ # Content words of a search term, lowercased, deduplicated, one per line.
2013
+ # Edge punctuation is stripped ("found:" -> "found") but inner punctuation
2014
+ # stays, so "app.module.ts" and "ai-mem-search" remain single words. Filler
2015
+ # words are dropped: they match nearly every note and would outvote the
2016
+ # words that carry the question.
2017
+ __ai_mem_search_words() {
2018
+ local -a stop out
2019
+ stop=(a an and are as at be but by can do does did for from has have how i
2020
+ if in is it its me my no not of on or our so that the their then there
2021
+ this to was we were what when where which who why will with you your)
2022
+ local w
2023
+ for w in ${=1}; do
2024
+ w="${(L)w}"
2025
+ while [[ -n "$w" && "$w" == [^[:alnum:]]* ]]; do w="${w#?}"; done
2026
+ while [[ -n "$w" && "$w" == *[^[:alnum:]] ]]; do w="${w%?}"; done
2027
+ [[ -n "$w" ]] || continue
2028
+ (( ${stop[(Ie)$w]} )) && continue
2029
+ (( ${out[(Ie)$w]} )) && continue
2030
+ out+=("$w")
2031
+ done
2032
+ print -rl -- $out
2033
+ }
2034
+
2035
+ # Rank grep lines that match ANY of the words, for ai-mem-search's widened
2036
+ # pass. Prints the same <path>:<line>:<text> lines, best first:
2037
+ # 1. how many of the words the note contains (coverage, per note),
2038
+ # 2. lessons above everything else (same tier rule as the phrase search),
2039
+ # 3. the summed rarity (IDF) of the words the note contains, so a note
2040
+ # holding one rare word beats one holding a word every note has,
2041
+ # 4. lesson reinforcement, then recency, then words on the line itself.
2042
+ # Notes matching fewer than half of the words are dropped, unless no note
2043
+ # reaches half, so a long question still returns its best partial match.
2044
+ # Args: <search-root> <space-separated words> <strength lines> <grep lines>.
2045
+ __ai_mem_search_rank_words() {
2046
+ local root="$1" words="$2" strengths="$3" raw="$4"
2047
+ local notes
2048
+ notes="$(find "$root" -name '*.md' -not -path '*/.git/*' -not -path '*/_archive/*' 2>/dev/null | wc -l | tr -d ' ')"
2049
+ awk -v root="$root/" -v words="$words" -v N="$notes" '
2050
+ BEGIN { nw = split(words, W, " ") }
2051
+ FNR == NR {
2052
+ if (match($0, /:[0-9]+$/)) str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
2053
+ next
2054
+ }
2055
+ {
2056
+ if (!match($0, /:[0-9]+:/)) next
2057
+ path = substr($0, 1, RSTART - 1)
2058
+ text = tolower(substr($0, RSTART + RLENGTH))
2059
+ c = 0
2060
+ for (i = 1; i <= nw; i++) {
2061
+ if (!index(text, W[i])) continue
2062
+ c++
2063
+ if (!((path, i) in has)) { has[path, i] = 1; df[i]++; cov[path]++ }
2064
+ }
2065
+ if (!c) next
2066
+ n++; L[n] = $0; LP[n] = path; LC[n] = c
2067
+ }
2068
+ END {
2069
+ best = 0
2070
+ for (p in cov) if (cov[p] > best) best = cov[p]
2071
+ need = int((nw + 1) / 2)
2072
+ if (need > best) need = best
2073
+ for (i = 1; i <= nw; i++) idf[i] = log(1 + N / (df[i] ? df[i] : 1))
2074
+ for (p in cov) {
2075
+ s = 0
2076
+ for (i = 1; i <= nw; i++) if ((p, i) in has) s += idf[i]
2077
+ score[p] = s
2078
+ }
2079
+ for (k = 1; k <= n; k++) {
2080
+ p = LP[k]
2081
+ if (cov[p] < need) continue
2082
+ rel = p; sub(root, "", rel)
2083
+ lesson = (rel ~ /^_lessons\//) ? 1 : 0
2084
+ ts = "0000-00-00_00-00-00"
2085
+ if (match(p, /[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]/))
2086
+ ts = substr(p, RSTART, RLENGTH)
2087
+ printf "%02d|%d|%09.4f|%03d|%s|%02d|%s\n", cov[p], lesson, score[p], lesson ? str[p] + 0 : 0, ts, LC[k], L[k]
2088
+ }
2089
+ }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f7-
2090
+ }