create-ai-memory 0.17.0 → 0.18.1

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
@@ -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
 
@@ -954,8 +956,8 @@ vault's session template predates the current one. Scaffolding only fills in
954
956
  `ai-mem-lint --fix`.
955
957
 
956
958
  **Search returns nothing for a term you are sure you wrote.**
957
- Matching is literal substring with no fuzzy matching, so a typo finds zero.
958
- 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
959
961
  [what it costs](#what-it-costs-and-what-it-cannot-do).
960
962
 
961
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.',
@@ -124,6 +124,10 @@ function titleOf(text, path, fm, h1Counts) {
124
124
  }
125
125
 
126
126
  const LINK_RE = /\[\[([^\]|#]+)/g;
127
+ // Code is not prose: a shell test such as [[ -n $X ]] inside `inline code` or
128
+ // a fenced block looks like a wikilink. Same rule as ai-mem-lint, including a
129
+ // fence that never closes, which runs to the end of the note (as in Obsidian).
130
+ const CODE_RE = /^[ \t]*(```|~~~)[^\n]*(?:\n[\s\S]*?^[ \t]*\1[^\n]*$|[\s\S]*$(?![\s\S]))|`[^`\n]*`/gm;
127
131
 
128
132
  /**
129
133
  * Build the graph.
@@ -171,7 +175,9 @@ function buildGraph() {
171
175
  return 0;
172
176
  }
173
177
  })(),
174
- links: [...text.matchAll(LINK_RE)].map((m) => m[1].trim()),
178
+ links: [...text.replace(CODE_RE, '').matchAll(LINK_RE)]
179
+ .map((m) => m[1].trim())
180
+ .filter((l) => !l.includes('{{')),
175
181
  };
176
182
  nodes.push(node);
177
183
  // First writer wins: a duplicate basename is ambiguous in Obsidian too.
@@ -187,7 +193,8 @@ function buildGraph() {
187
193
  // mark which notes carry a broken link without inventing targets for them.
188
194
  const danglingSeen = new Set();
189
195
  for (const link of n.links) {
190
- const target = byBasename.get(link);
196
+ // A folder path ([[_idea/x]], [[../dir/x]]) resolves by its last segment.
197
+ const target = byBasename.get(link) || byBasename.get(link.split('/').pop());
191
198
  if (!target) {
192
199
  if (link && link !== basename(n.id, '.md')) danglingSeen.add(link);
193
200
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-ai-memory",
3
- "version": "0.17.0",
3
+ "version": "0.18.1",
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",
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
@@ -1098,6 +1098,8 @@ __ai_mem_current_project() {
1098
1098
  # Create a global (GUI/MCP) session log at $1 if it does not exist yet. Global
1099
1099
  # logs are created lazily, on the first write, so a read-only conversation
1100
1100
  # leaves no empty note behind. `previous:` links the newest log with content.
1101
+ # `project:` links the project note, as in a terminal session log: without it
1102
+ # ai-mem-lint reports the log as orphaned and the graph shows it unconnected.
1101
1103
  __ai_mem_create_global_log() {
1102
1104
  local session_note="$1" project_name="$2" previous prev_link=""
1103
1105
  [[ -f "$session_note" ]] && return 0
@@ -1105,7 +1107,8 @@ __ai_mem_create_global_log() {
1105
1107
  previous="$(__ai_mem_latest_session_log "$project_name")" || return 1
1106
1108
  [[ -n "$previous" ]] && prev_link="[[${previous:t:r}]]"
1107
1109
  mkdir -p "${session_note:h}"
1108
- print -rl -- "---" "type: ai-global-session" "date: $(date +%Y-%m-%d)" "previous: \"$prev_link\"" "---" "" "# Global Session Notes" > "$session_note"
1110
+ print -rl -- "---" "type: ai-global-session" "date: $(date +%Y-%m-%d)" "project: \"[[$project_name]]\"" \
1111
+ "previous: \"$prev_link\"" "---" "" "# Global Session Notes" > "$session_note"
1109
1112
  }
1110
1113
 
1111
1114
  __ai_mem_today_session_log() {
@@ -1388,7 +1391,9 @@ ai-mem-lint() {
1388
1391
  __ai_mem_paths
1389
1392
  local fix=0
1390
1393
  [[ "${1:-}" == "--fix" ]] && fix=1
1391
- local issues=0 f label target
1394
+ # Declared once here: re-declaring a set local (`local pname` inside a
1395
+ # loop or a later block) makes zsh print "pname=value" to stdout.
1396
+ local issues=0 f label target pname otmp
1392
1397
  # Open Knowledge Format names exactly one required frontmatter field:
1393
1398
  # `type`. Every note the vault ships already declares one except session
1394
1399
  # logs, which predate the field -- so a vault that has been in use carries
@@ -1413,7 +1418,11 @@ ai-mem-lint() {
1413
1418
  # ai-mem-sleep moves older logs into the project's _archive/, and
1414
1419
  # Obsidian resolves a link by basename anywhere in the vault. A
1415
1420
  # link to an archived log still opens, so it is not dangling.
1416
- if [[ ! -f "${f:h}/${target}.md" && ! -f "${f:h}/_archive/${target}.md" ]]; then
1421
+ # A project renamed mid-history links its first log to a log in
1422
+ # the old project's folder; Obsidian resolves that by basename,
1423
+ # so look vault-wide before calling it dangling (rare, so cheap).
1424
+ if [[ ! -f "${f:h}/${target}.md" && ! -f "${f:h}/_archive/${target}.md" \
1425
+ && -z "$(find "$AI_MEM_SESSION_DIR" -name "${target}.md" -print -quit 2>/dev/null)" ]]; then
1417
1426
  print -r -- "dangling previous link: $f -> [[${target}]] (not found)"
1418
1427
  (( issues++ ))
1419
1428
  fi
@@ -1422,7 +1431,7 @@ ai-mem-lint() {
1422
1431
 
1423
1432
  while IFS= read -r -d '' f; do
1424
1433
  [[ "${f:t}" == "_project_template.md" ]] && continue
1425
- local pname="${f:t:r}"
1434
+ pname="${f:t:r}"
1426
1435
  if ! grep -rq -- "\[\[${pname}\]\]" "$AI_MEM_SESSION_DIR" 2>/dev/null; then
1427
1436
  print -r -- "unreferenced project note (no session log links to it): $f"
1428
1437
  (( issues++ ))
@@ -1464,7 +1473,6 @@ ai-mem-lint() {
1464
1473
  done < <(find "$AI_MEM_SESSION_DIR" -maxdepth 2 -name "*.md" -print0 2>/dev/null)
1465
1474
 
1466
1475
  if (( $#orphan_files && fix )); then
1467
- local pname otmp
1468
1476
  for f in $orphan_files; do
1469
1477
  __ai_mem_guard "$f" >/dev/null || continue
1470
1478
  pname="$(grep -m1 '^project: ' "$f" | sed 's/^project: *//; s/^"//; s/"$//')"
@@ -1503,29 +1511,46 @@ ai-mem-lint() {
1503
1511
  # a dead edge in the graph. Detection only: the dead link is surfaced, never
1504
1512
  # auto-removed, because the intended target is unknowable and a note's own
1505
1513
  # prose is the author's to edit. Wikilinks resolve by basename (the same way
1506
- # ai-mem-serve draws them), so the node set is every note's basename.
1514
+ # ai-mem-serve draws them), so the node set is every note's basename. A
1515
+ # folder path ([[_idea/x]], [[../dir/x]]) resolves by its last segment.
1507
1516
  #
1508
- # One grep over the vault, never a grep per file -- a per-file scan is the
1509
- # 25s antipattern ai-mem-search documents. Scope is the vault root derived
1510
- # from AI_MEM_SESSION_DIR (its parent), the same subtree the rest of this
1511
- # linter walks, so a caller that redirects the session dir redirects this too.
1517
+ # Not links, so never reported (28 of 280 findings on a real vault were
1518
+ # these): text inside `inline code` or a fenced code block, where a shell
1519
+ # test such as [[ -n $X ]] looks like a wikilink, and {{placeholder}}
1520
+ # targets in the note templates.
1521
+ #
1522
+ # One awk pass over the vault, never a process per file -- a per-file scan
1523
+ # is the 25s antipattern ai-mem-search documents. Scope is the vault root
1524
+ # derived from AI_MEM_SESSION_DIR (its parent), the same subtree the rest
1525
+ # of this linter walks, so a caller that redirects the session dir
1526
+ # redirects this too.
1512
1527
  local vault="${AI_MEM_SESSION_DIR:h}"
1513
- typeset -A _known
1514
- local nf
1515
- for nf in ${(f)"$(find "$vault" -name '*.md' -not -path '*/.git/*' 2>/dev/null)"}; do
1516
- _known[${nf:t:r}]=1
1517
- done
1528
+ local known_file
1529
+ known_file="$(mktemp)"
1530
+ find "$vault" -name '*.md' -not -path '*/.git/*' 2>/dev/null \
1531
+ | awk '{ sub(/.*\//, ""); sub(/\.md$/, ""); print }' > "$known_file"
1518
1532
  local -a dangling
1519
- local line src tgt
1520
- for line in ${(f)"$(grep -rHoE --include='*.md' --exclude-dir=.git -- '\[\[[^]]+\]\]' "$vault" 2>/dev/null)"}; do
1521
- src="${line%%:\[\[*}" # path, before the ':[[' grep separator
1522
- tgt="${line##*:\[\[}"; tgt="${tgt%\]\]}" # inside the brackets
1523
- tgt="${tgt%%\|*}"; tgt="${tgt%%#*}" # drop |alias and #heading
1524
- tgt="${tgt## }"; tgt="${tgt%% }"
1525
- [[ -z "$tgt" ]] && continue
1526
- [[ -n "${_known[$tgt]-}" ]] && continue
1527
- dangling+=( "${src:t} -> [[${tgt}]]" )
1528
- done
1533
+ dangling=( ${(f)"$(find "$vault" -name '*.md' -not -path '*/.git/*' -exec awk -v kf="$known_file" '
1534
+ FILENAME == kf { known[$0] = 1; next }
1535
+ FNR == 1 { fence = 0; src = FILENAME; sub(/.*\//, "", src) }
1536
+ /^[ \t]*(```|~~~)/ { fence = !fence; next }
1537
+ fence { next }
1538
+ {
1539
+ line = $0
1540
+ gsub(/`[^`]*`/, "", line)
1541
+ while (match(line, /\[\[[^\]]+\]\]/)) {
1542
+ t = substr(line, RSTART + 2, RLENGTH - 4)
1543
+ line = substr(line, RSTART + RLENGTH)
1544
+ sub(/\|.*/, "", t); sub(/#.*/, "", t)
1545
+ sub(/^ +/, "", t); sub(/ +$/, "", t)
1546
+ if (t == "" || index(t, "{{")) continue
1547
+ b = t; sub(/.*\//, "", b)
1548
+ if ((t in known) || (b in known)) continue
1549
+ print src " -> [[" t "]]"
1550
+ }
1551
+ }' "$known_file" {} + 2>/dev/null)"} )
1552
+ rm -f "$known_file"
1553
+ local line
1529
1554
  if (( $#dangling )); then
1530
1555
  print -r -- "$#dangling dangling wikilink(s) -- a [[link]] that resolves to no note:"
1531
1556
  for line in $dangling; do print -r -- " $line"; done
@@ -1833,8 +1858,33 @@ ai-mem-search() {
1833
1858
  # stay in git and on disk, just not in a default search.
1834
1859
  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)"
1835
1860
 
1861
+ # Exact phrase first, then each word. A multi-word term used to be one
1862
+ # literal phrase, so word order decided whether anything came back:
1863
+ # measured on a real vault, 'prisma migration' found 11 lines and
1864
+ # 'migration prisma' found 0, and 30 three-word queries built from real
1865
+ # lessons found their lesson 0 times out of 30. An agent cannot tell that
1866
+ # empty result from "never written down", so it solves the problem again.
1867
+ # Only a phrase with NO hits is widened, so every query that worked before
1868
+ # returns exactly what it returned before.
1869
+ local -a words
1836
1870
  if [[ -z "$raw" ]]; then
1837
- print -r -- "no matches for '$term' in $search_root"
1871
+ words=(${(f)"$(__ai_mem_search_words "$term")"})
1872
+ if (( $#words >= 2 )); then
1873
+ local -a patterns
1874
+ local w
1875
+ for w in $words; do patterns+=(-e "$w"); done
1876
+ 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)"
1877
+ else
1878
+ words=()
1879
+ fi
1880
+ fi
1881
+
1882
+ if [[ -z "$raw" ]]; then
1883
+ if (( $#words )); then
1884
+ print -r -- "no matches for '$term' in $search_root (also tried each word: ${(j:, :)words})"
1885
+ else
1886
+ print -r -- "no matches for '$term' in $search_root"
1887
+ fi
1838
1888
  return 1
1839
1889
  fi
1840
1890
 
@@ -1873,28 +1923,32 @@ ai-mem-search() {
1873
1923
  [[ -z "$project" ]] && strengths="$(grep -rc '^## [0-9]' "$AI_MEM_ROOT/_lessons" 2>/dev/null)"
1874
1924
 
1875
1925
  local sorted
1876
- sorted="$(awk -v root="$search_root/" '
1877
- # First input: <lesson-file-path>:<entry-count>. Build the strength map.
1878
- FNR == NR {
1879
- if (match($0, /:[0-9]+$/)) {
1880
- str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
1926
+ if (( $#words )); then
1927
+ sorted="$(__ai_mem_search_rank_words "$search_root" "${(j: :)words}" "$strengths" "$raw")"
1928
+ else
1929
+ sorted="$(awk -v root="$search_root/" '
1930
+ # First input: <lesson-file-path>:<entry-count>. Build the strength map.
1931
+ FNR == NR {
1932
+ if (match($0, /:[0-9]+$/)) {
1933
+ str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
1934
+ }
1935
+ next
1881
1936
  }
1882
- next
1883
- }
1884
- {
1885
- ts = "0000-00-00_00-00-00"
1886
- 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]/))
1887
- ts = substr($0, RSTART, RLENGTH)
1888
- rel = $0
1889
- sub(root, "", rel)
1890
- is_lesson = (rel ~ /^_lessons\//)
1891
- rank = is_lesson ? "1" : "0"
1892
- # The file this match came from, to look up its reinforcement count.
1893
- path = $0
1894
- sub(/:[0-9]+:.*$/, "", path)
1895
- strength = is_lesson ? sprintf("%03d", str[path] + 0) : "000"
1896
- print rank "|" strength "|" ts "|" $0
1897
- }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f4-)"
1937
+ {
1938
+ ts = "0000-00-00_00-00-00"
1939
+ 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]/))
1940
+ ts = substr($0, RSTART, RLENGTH)
1941
+ rel = $0
1942
+ sub(root, "", rel)
1943
+ is_lesson = (rel ~ /^_lessons\//)
1944
+ rank = is_lesson ? "1" : "0"
1945
+ # The file this match came from, to look up its reinforcement count.
1946
+ path = $0
1947
+ sub(/:[0-9]+:.*$/, "", path)
1948
+ strength = is_lesson ? sprintf("%03d", str[path] + 0) : "000"
1949
+ print rank "|" strength "|" ts "|" $0
1950
+ }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f4-)"
1951
+ fi
1898
1952
 
1899
1953
  # Bound the output. The consumer is normally an agent with a finite
1900
1954
  # context window, and an unbounded dump is actively harmful there in a
@@ -1906,7 +1960,7 @@ ai-mem-search() {
1906
1960
  # Count goes FIRST -- the reader needs the size of the result set before
1907
1961
  # the result set, not after it.
1908
1962
  local total limit per_file
1909
- total="$(print -r -- "$raw" | wc -l | tr -d ' ')"
1963
+ total="$(print -r -- "$sorted" | wc -l | tr -d ' ')"
1910
1964
  limit="${AI_MEM_SEARCH_LIMIT:-25}"
1911
1965
  per_file="${AI_MEM_SEARCH_PER_FILE:-1}"
1912
1966
 
@@ -1932,7 +1986,11 @@ ai-mem-search() {
1932
1986
  files_shown="$(print -r -- "$spread" | head -n "$limit" | awk '
1933
1987
  { f = $0; sub(/:[0-9]+:.*$/, "", f); seen[f] = 1 } END { print length(seen) }')"
1934
1988
 
1935
- print -r -- "$total match(es) for '$term'"
1989
+ if (( $#words )); then
1990
+ print -r -- "$total match(es) for any of: ${(j: :)words} (no exact match for '$term'; notes matching more of the words rank first)"
1991
+ else
1992
+ print -r -- "$total match(es) for '$term'"
1993
+ fi
1936
1994
  print -r -- "paths below $search_root"
1937
1995
  print -r -- "--"
1938
1996
  # Strip the repeated vault root (a third to a half of all output bytes on
@@ -1960,7 +2018,7 @@ ai-mem-search() {
1960
2018
  # excerpt, so a match doesn't leave you to manually chase the link
1961
2019
  # yourself.
1962
2020
  local links link target excerpt
1963
- links="$(print -r -- "$raw" | grep -oE '\[\[[^]]+\]\]' | sed -E 's/^\[\[|\]\]$//g' | sort -u)"
2021
+ links="$(print -r -- "$sorted" | grep -oE '\[\[[^]]+\]\]' | sed -E 's/^\[\[|\]\]$//g' | sort -u)"
1964
2022
  [[ -n "$links" ]] || return 0
1965
2023
 
1966
2024
  print -r -- "--"
@@ -1975,3 +2033,83 @@ ai-mem-search() {
1975
2033
  [[ -n "$excerpt" ]] && print -r -- " $excerpt"
1976
2034
  done <<< "$links"
1977
2035
  }
2036
+
2037
+ # Content words of a search term, lowercased, deduplicated, one per line.
2038
+ # Edge punctuation is stripped ("found:" -> "found") but inner punctuation
2039
+ # stays, so "app.module.ts" and "ai-mem-search" remain single words. Filler
2040
+ # words are dropped: they match nearly every note and would outvote the
2041
+ # words that carry the question.
2042
+ __ai_mem_search_words() {
2043
+ local -a stop out
2044
+ stop=(a an and are as at be but by can do does did for from has have how i
2045
+ if in is it its me my no not of on or our so that the their then there
2046
+ this to was we were what when where which who why will with you your)
2047
+ local w
2048
+ for w in ${=1}; do
2049
+ w="${(L)w}"
2050
+ while [[ -n "$w" && "$w" == [^[:alnum:]]* ]]; do w="${w#?}"; done
2051
+ while [[ -n "$w" && "$w" == *[^[:alnum:]] ]]; do w="${w%?}"; done
2052
+ [[ -n "$w" ]] || continue
2053
+ (( ${stop[(Ie)$w]} )) && continue
2054
+ (( ${out[(Ie)$w]} )) && continue
2055
+ out+=("$w")
2056
+ done
2057
+ print -rl -- $out
2058
+ }
2059
+
2060
+ # Rank grep lines that match ANY of the words, for ai-mem-search's widened
2061
+ # pass. Prints the same <path>:<line>:<text> lines, best first:
2062
+ # 1. how many of the words the note contains (coverage, per note),
2063
+ # 2. lessons above everything else (same tier rule as the phrase search),
2064
+ # 3. the summed rarity (IDF) of the words the note contains, so a note
2065
+ # holding one rare word beats one holding a word every note has,
2066
+ # 4. lesson reinforcement, then recency, then words on the line itself.
2067
+ # Notes matching fewer than half of the words are dropped, unless no note
2068
+ # reaches half, so a long question still returns its best partial match.
2069
+ # Args: <search-root> <space-separated words> <strength lines> <grep lines>.
2070
+ __ai_mem_search_rank_words() {
2071
+ local root="$1" words="$2" strengths="$3" raw="$4"
2072
+ local notes
2073
+ notes="$(find "$root" -name '*.md' -not -path '*/.git/*' -not -path '*/_archive/*' 2>/dev/null | wc -l | tr -d ' ')"
2074
+ awk -v root="$root/" -v words="$words" -v N="$notes" '
2075
+ BEGIN { nw = split(words, W, " ") }
2076
+ FNR == NR {
2077
+ if (match($0, /:[0-9]+$/)) str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
2078
+ next
2079
+ }
2080
+ {
2081
+ if (!match($0, /:[0-9]+:/)) next
2082
+ path = substr($0, 1, RSTART - 1)
2083
+ text = tolower(substr($0, RSTART + RLENGTH))
2084
+ c = 0
2085
+ for (i = 1; i <= nw; i++) {
2086
+ if (!index(text, W[i])) continue
2087
+ c++
2088
+ if (!((path, i) in has)) { has[path, i] = 1; df[i]++; cov[path]++ }
2089
+ }
2090
+ if (!c) next
2091
+ n++; L[n] = $0; LP[n] = path; LC[n] = c
2092
+ }
2093
+ END {
2094
+ best = 0
2095
+ for (p in cov) if (cov[p] > best) best = cov[p]
2096
+ need = int((nw + 1) / 2)
2097
+ if (need > best) need = best
2098
+ for (i = 1; i <= nw; i++) idf[i] = log(1 + N / (df[i] ? df[i] : 1))
2099
+ for (p in cov) {
2100
+ s = 0
2101
+ for (i = 1; i <= nw; i++) if ((p, i) in has) s += idf[i]
2102
+ score[p] = s
2103
+ }
2104
+ for (k = 1; k <= n; k++) {
2105
+ p = LP[k]
2106
+ if (cov[p] < need) continue
2107
+ rel = p; sub(root, "", rel)
2108
+ lesson = (rel ~ /^_lessons\//) ? 1 : 0
2109
+ ts = "0000-00-00_00-00-00"
2110
+ 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]/))
2111
+ ts = substr(p, RSTART, RLENGTH)
2112
+ 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]
2113
+ }
2114
+ }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f7-
2115
+ }