create-ai-memory 0.14.3 → 0.15.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/shell/ai-mem.zsh CHANGED
@@ -18,8 +18,11 @@
18
18
  # an agent then reports as success. Do not "tidy" these back to one
19
19
  # underscore -- tests/run.sh asserts the naming for exactly this reason.
20
20
 
21
- # Directory holding this module, used to source sibling files.
22
- AI_MEM_HOME="${0:A:h}"
21
+ # Directory holding this module, used to source sibling files. Exported so a
22
+ # non-interactive child shell can re-source the module by absolute path
23
+ # (`zsh -c 'source "$AI_MEM_HOME/ai-mem.zsh"; ...'`) without a hard-coded path
24
+ # and without the cost of a full interactive shell (`zsh -ic`).
25
+ export AI_MEM_HOME="${0:A:h}"
23
26
 
24
27
  # Where the shipped example notes and templates live, used to auto-scaffold a
25
28
  # vault on first use so install.sh is optional (plugin-manager installs work).
@@ -139,11 +142,46 @@ ai-mem-vault-backup() {
139
142
  after="$(git -C "${AI_MEM_ROOT:-}" rev-parse HEAD 2>/dev/null || true)"
140
143
  if [[ -z "$before" && -z "$after" ]]; then
141
144
  echo "ai-mem-vault-backup: vault isn't git-backed, nothing to do"
142
- elif [[ "$before" != "$after" ]]; then
143
- echo "ai-mem-vault-backup: pushed"
144
- else
145
- echo "ai-mem-vault-backup: nothing to commit"
145
+ return 0
146
+ fi
147
+
148
+ # "pushed" used to mean "HEAD moved", which is what a COMMIT does. The push
149
+ # is best-effort and swallows its own errors, so a commit that never left
150
+ # the machine still reported success -- observed for real: three commits
151
+ # sat unpushed for an hour while every backup said "pushed", because the
152
+ # credential in use had lost access to the vault repo.
153
+ #
154
+ # Ask the only question that matters: does the remote have what we have.
155
+ local upstream local_sha remote_sha
156
+ upstream="$(git -C "$AI_MEM_ROOT" rev-parse --abbrev-ref '@{u}' 2>/dev/null || true)"
157
+ if [[ -z "$upstream" ]]; then
158
+ if [[ "$before" != "$after" ]]; then
159
+ echo "ai-mem-vault-backup: committed, but this branch has no upstream -- nothing was pushed"
160
+ return 1
161
+ fi
162
+ echo "ai-mem-vault-backup: nothing to commit (no upstream configured)"
163
+ return 0
146
164
  fi
165
+
166
+ git -C "$AI_MEM_ROOT" fetch -q origin 2>/dev/null
167
+ local_sha="$(git -C "$AI_MEM_ROOT" rev-parse HEAD 2>/dev/null || true)"
168
+ remote_sha="$(git -C "$AI_MEM_ROOT" rev-parse '@{u}' 2>/dev/null || true)"
169
+
170
+ if [[ -n "$local_sha" && "$local_sha" == "$remote_sha" ]]; then
171
+ if [[ "$before" != "$after" ]]; then
172
+ echo "ai-mem-vault-backup: pushed"
173
+ else
174
+ echo "ai-mem-vault-backup: nothing to commit"
175
+ fi
176
+ return 0
177
+ fi
178
+
179
+ local ahead
180
+ ahead="$(git -C "$AI_MEM_ROOT" rev-list --count '@{u}..HEAD' 2>/dev/null || echo '?')"
181
+ print -r -- "ai-mem-vault-backup: NOT PUSHED -- $ahead commit(s) exist only on this machine." >&2
182
+ print -r -- " The vault is committed locally but the remote does not have it. Check credentials and push by hand:" >&2
183
+ print -r -- " git -C \"$AI_MEM_ROOT\" push" >&2
184
+ return 1
147
185
  }
148
186
  # Read a vault note only when it exists inside the memory root.
149
187
  #
@@ -160,6 +198,38 @@ ai-mem-vault-backup() {
160
198
  # target, a target outside the vault, or a diff that would leave nothing --
161
199
  # because injecting a note twice merely costs tokens, while dropping one
162
200
  # costs the agent context it was promised.
201
+ # Bound what a single note can contribute to the launch prompt.
202
+ #
203
+ # Every other path into the prompt is already bounded: session-log fields at
204
+ # 500 chars each, the lesson index at 200 slugs, search output at a flat cap,
205
+ # and the project note is a path rather than its contents. The inlined notes
206
+ # were the one exception, so a profile that grows makes EVERY session in
207
+ # EVERY project more expensive, forever, and nothing reports it.
208
+ #
209
+ # Truncation states the real total and where to read the rest, because a
210
+ # truncated note the agent cannot tell from a complete one is worse than a
211
+ # long one -- it would answer from half a profile believing it had all of it.
212
+ #
213
+ # The cut lands on a line boundary. Markdown cut mid-line can leave an
214
+ # unterminated code fence or half a heading, which reads as content rather
215
+ # than as damage.
216
+ __ai_mem_cap_note() {
217
+ local text="$1" source_ref="${2:-the note}"
218
+ local cap="${AI_MEM_NOTE_MAX_CHARS:-8000}"
219
+ # 0 disables the cap outright, for anyone who wants the old behaviour.
220
+ if (( cap <= 0 )) || (( ${#text} <= cap )); then
221
+ print -r -- "$text"
222
+ return 0
223
+ fi
224
+ local head_text="${text[1,$cap]}"
225
+ local trimmed="${head_text%$'\n'*}"
226
+ # A single line longer than the whole cap leaves nothing after trimming;
227
+ # keep the hard cut rather than emitting an empty note.
228
+ [[ -n "${trimmed//[[:space:]]/}" ]] && head_text="$trimmed"
229
+ print -r -- "$head_text"
230
+ print -r -- "[truncated at ${cap} of ${#text} chars -- read the rest with: cat \"$source_ref\"]"
231
+ }
232
+
163
233
  __ai_mem_note_contents() {
164
234
  local note_path="${1:-}"
165
235
  if [[ -z "$note_path" || ! -f "$note_path" ]]; then
@@ -173,7 +243,7 @@ __ai_mem_note_contents() {
173
243
  local mirror
174
244
  mirror="$(sed -n '2,/^---$/p' "$note_path" 2>/dev/null | sed -n 's/^mirror_of:[[:space:]]*//p' | head -1)"
175
245
  if [[ -z "$mirror" ]]; then
176
- print -r -- "$(<"$note_path")"
246
+ __ai_mem_cap_note "$(<"$note_path")" "$note_path"
177
247
  return 0
178
248
  fi
179
249
 
@@ -184,7 +254,7 @@ __ai_mem_note_contents() {
184
254
  # every separator outright is both the safer rule and the simpler one.
185
255
  local target="$AI_MEM_ROOT/$mirror"
186
256
  if [[ "$mirror" == */* || ! -f "$target" ]]; then
187
- print -r -- "$(<"$note_path")"
257
+ __ai_mem_cap_note "$(<"$note_path")" "$note_path"
188
258
  return 0
189
259
  fi
190
260
 
@@ -198,7 +268,7 @@ __ai_mem_note_contents() {
198
268
  fi
199
269
 
200
270
  print -r -- "(mirror of ${mirror}, shown above -- only the lines that differ from it are repeated here)"
201
- print -r -- "$unique"
271
+ __ai_mem_cap_note "$unique" "$note_path"
202
272
  }
203
273
 
204
274
  __ai_mem_resolve_project() {
@@ -273,14 +343,30 @@ __ai_mem_latest_session_log() {
273
343
  project_name="$(__ai_mem_resolve_project)"
274
344
  fi
275
345
 
276
- local latest=""
346
+ local logs="" latest=""
277
347
  local project_session_dir
278
348
  project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
279
349
 
280
- latest="$(find "$project_session_dir" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
281
- if [[ -z "$latest" ]]; then
282
- latest="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort | tail -n 1)" || true
350
+ logs="$(find "$project_session_dir" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort -r)" || true
351
+ if [[ -z "$logs" ]]; then
352
+ logs="$(find "$AI_MEM_SESSION_DIR" -maxdepth 1 -type f -name "${project_name}-*.md" 2>/dev/null | sort -r)" || true
283
353
  fi
354
+ [[ -n "$logs" ]] || return 0
355
+
356
+ # The newest file is often an untouched template: a session that was
357
+ # opened and closed, or one still running in another terminal. Pointing
358
+ # the next session at it hands over nothing, while real context sits one
359
+ # file back. So take the newest log with any line that is not template
360
+ # scaffolding (frontmatter, blanks, the heading, [placeholder] bullets).
361
+ # One awk pass over newest-first files, stopping at the first hit. When
362
+ # every log is unfilled, keep the newest, as before.
363
+ latest="$(awk '
364
+ FNR == 1 { fm = ($0 == "---"); if (fm) next }
365
+ fm { if ($0 == "---") fm = 0; next }
366
+ /^[[:space:]]*$/ || $0 == "# Session Outcome" || /^\* \*\*[^*]+:\*\*[[:space:]]*\[.*\]$/ { next }
367
+ { print FILENAME; exit }
368
+ ' "${(@f)logs}" 2>/dev/null)" || true
369
+ [[ -n "$latest" ]] || latest="${logs%%$'\n'*}"
284
370
  if [[ -n "$latest" ]]; then
285
371
  __ai_mem_guard "$latest" || return 1
286
372
  print -r -- "$latest"
@@ -317,7 +403,22 @@ __ai_mem_ensure_vault() {
317
403
  # in the file alone. This runs on session prep, so an existing install
318
404
  # heals on its next launch rather than waiting for someone to think to run
319
405
  # ai-mem-lint --fix.
406
+ # The `project:` line must be a [[wikilink]] or every log created from this
407
+ # template is orphaned from its project note -- which is what the graph
408
+ # edges and ai-mem-lint both key on. A vault whose template predates that
409
+ # produced disconnected logs silently, one per session.
320
410
  local tmpl="$AI_MEM_SESSION_DIR/_session_template.md"
411
+ if [[ -f "$tmpl" ]] && grep -qm1 '^project: {{project_name}}$' "$tmpl"; then
412
+ __ai_mem_guard "$tmpl" || return 1
413
+ local ptmp="$tmpl.aimem-upgrade"
414
+ sed 's|^project: {{project_name}}$|project: "[[{{project_name}}]]"|' "$tmpl" > "$ptmp" && mv "$ptmp" "$tmpl"
415
+ fi
416
+ if [[ -f "$tmpl" ]] && ! grep -qm1 '^previous:' "$tmpl"; then
417
+ __ai_mem_guard "$tmpl" || return 1
418
+ local vtmp="$tmpl.aimem-upgrade"
419
+ awk '/^project:/ { print; print "previous: \"{{previous_session_link}}\""; next } { print }' "$tmpl" > "$vtmp" && mv "$vtmp" "$tmpl"
420
+ fi
421
+
321
422
  if [[ -f "$tmpl" ]] && ! grep -qm1 '^type: ' "$tmpl"; then
322
423
  __ai_mem_guard "$tmpl" || return 1
323
424
  local tmp="$tmpl.aimem-upgrade"
@@ -343,7 +444,8 @@ __ai_mem_prepare_session() {
343
444
  project_session_dir="$(__ai_mem_project_session_dir "$project_name")"
344
445
  local previous_session_note=""
345
446
  previous_session_note="$(__ai_mem_latest_session_log "$project_name")" || return 1
346
- local session_note="$project_session_dir/${project_name}-$(date +%Y-%m-%d_%H-%M-%S).md"
447
+ local session_stamp="$(date +%Y-%m-%d_%H-%M-%S)"
448
+ local session_note="$project_session_dir/${project_name}-${session_stamp}.md"
347
449
 
348
450
  __ai_mem_guard "$project_note" || return 1
349
451
  __ai_mem_guard "$session_note" || return 1
@@ -355,13 +457,29 @@ __ai_mem_prepare_session() {
355
457
  "$AI_MEM_PROJECT_DIR/_project_template.md" > "$project_note"
356
458
  fi
357
459
 
460
+ # A blank note with this second's timestamp belongs to a separate session.
461
+ # Wait for the next timestamp instead of overwriting its previous-session
462
+ # link. A note with Live Notes is the active GUI/CLI session and must be
463
+ # reused.
464
+ if [[ -f "$session_note" ]] && ! grep -q '^### Live Notes' "$session_note" 2>/dev/null; then
465
+ while [[ -f "$session_note" ]]; do
466
+ sleep 1
467
+ session_stamp="$(date +%Y-%m-%d_%H-%M-%S)"
468
+ session_note="$project_session_dir/${project_name}-${session_stamp}.md"
469
+ done
470
+ fi
471
+
358
472
  local prev_link=""
359
473
  if [[ -n "$previous_session_note" ]]; then
360
474
  prev_link="[[${previous_session_note:t:r}]]"
361
475
  fi
362
476
 
363
- SESSION_DATE="$(date +%Y-%m-%d)" PROJECT_NAME="$project_name" PREV_LINK="$prev_link" perl -0pe 's/\{\{date\}\}/$ENV{SESSION_DATE}/g; s/\{\{project_name\}\}/$ENV{PROJECT_NAME}/g; s/\{\{previous_session_link\}\}/$ENV{PREV_LINK}/g' \
364
- "$AI_MEM_SESSION_DIR/_session_template.md" > "$session_note"
477
+ # Context reads can follow a GUI write in the same second. Reusing an
478
+ # existing timestamped note preserves Live Notes and any other append.
479
+ if [[ ! -f "$session_note" ]]; then
480
+ SESSION_DATE="$(date +%Y-%m-%d)" PROJECT_NAME="$project_name" PREV_LINK="$prev_link" perl -0pe 's/\{\{date\}\}/$ENV{SESSION_DATE}/g; s/\{\{project_name\}\}/$ENV{PROJECT_NAME}/g; s/\{\{previous_session_link\}\}/$ENV{PREV_LINK}/g' \
481
+ "$AI_MEM_SESSION_DIR/_session_template.md" > "$session_note"
482
+ fi
365
483
 
366
484
  export AI_MEM_ACTIVE_PROJECT="$project_name"
367
485
  export AI_MEM_PREVIOUS_SESSION_LOG="$previous_session_note"
@@ -465,6 +583,16 @@ __ai_mem_context_prompt() {
465
583
  fi
466
584
  fi
467
585
 
586
+ # A project note straight from the template is worse than no note: the
587
+ # prompt points at it as "Project context", the agent opens it, and finds
588
+ # "[What problem this repository solves]". That reads as context and
589
+ # carries none -- the same present-but-empty failure as a search that
590
+ # returns nothing while looking authoritative. Say so, and say what to do.
591
+ local project_state=""
592
+ if [[ -f "$project_note" ]] && grep -q '\[What problem this repository solves\]' "$project_note" 2>/dev/null; then
593
+ project_state=" -- NOT YET FILLED IN: it is still the blank template, so it holds no context. Read the repo (README, package manifest, AGENTS.md/CLAUDE.md, recent git log) and fill it in early in this session; every future session on this repo starts from it."
594
+ fi
595
+
468
596
  cat <<EOF
469
597
  Read these notes before doing anything else:
470
598
  - Global profile:
@@ -473,7 +601,7 @@ $(__ai_mem_note_contents "$AI_MEM_GLOBAL")
473
601
  - Standards:
474
602
  $(__ai_mem_note_contents "$AI_MEM_STANDARDS")
475
603
 
476
- - Project context: $project_note
604
+ - Project context: $project_note$project_state
477
605
  $previous_session_block
478
606
  - Active session log: $session_note
479
607
  $(__ai_mem_lesson_index)
@@ -481,7 +609,7 @@ $(__ai_mem_lesson_index)
481
609
  Use the Obsidian vault as the persistent memory layer.
482
610
  Treat the global profile and standards note as the shared baseline for every run.
483
611
  Keep durable preferences and project facts in the vault, and keep the active session log updated with decisions, blockers, and next steps.
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.
612
+ 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 zsh functions from the sourced module, so \`command -v\` finds them but \`which\` under bash will not. 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
613
  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
614
  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.
487
615
  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.
@@ -529,6 +657,13 @@ __ai_mem_export_active() {
529
657
  export AI_MEM_ACTIVE_PROJECT="${1:-}"
530
658
  export AI_MEM_PREVIOUS_SESSION_LOG="${2:-}"
531
659
  export AI_MEM_ACTIVE_SESSION_LOG="${3:-}"
660
+ # These exports outlive the agent in the user's shell. The Claude hooks
661
+ # compare this against the repo they run in, so a later plain `claude` in a
662
+ # different repo does not write that repo's commits into this project's log.
663
+ # The common dir, not the toplevel, so every worktree of one repo matches.
664
+ local git_dir
665
+ git_dir="$(git rev-parse --git-common-dir 2>/dev/null)" || git_dir=""
666
+ export AI_MEM_ACTIVE_GIT_DIR="${git_dir:+${git_dir:A}}"
532
667
  }
533
668
 
534
669
  ai-start() {
@@ -697,7 +832,7 @@ __ai_session_start() {
697
832
  # registered agent that has a matching adapter. Users extend by appending to
698
833
  # AI_MEM_AGENTS (space-separated) and defining __ai_adapter_<name>.
699
834
  source "$AI_MEM_HOME/adapters.zsh"
700
- : "${AI_MEM_AGENTS:=claude codex gemini cursor opencode}"
835
+ : "${AI_MEM_AGENTS:=claude codex agy gemini cursor opencode}"
701
836
  for _ai_agent in ${(z)AI_MEM_AGENTS}; do
702
837
  if typeset -f "__ai_adapter_$_ai_agent" >/dev/null; then
703
838
  # A same-named alias (e.g. from another plugin) makes zsh refuse to
@@ -827,7 +962,149 @@ ai-lesson() {
827
962
  printf -- '\n## %s [[%s]]\n\n### Problem\n%s\n\n### Solution\n%s\n' \
828
963
  "$timestamp" "$project_name" "$problem" "$solution" >> "$lesson_file"
829
964
  __ai_mem_vault_backup
830
- printf 'Appended to %s\n' "$lesson_file"
965
+ # Make the reinforcement visible: a second-or-later entry is the same
966
+ # lesson firing again, which ai-mem-search now ranks higher. Derived from
967
+ # the entries themselves, so nothing is stored twice.
968
+ local recalls
969
+ recalls="$(grep -c '^## [0-9]' "$lesson_file" 2>/dev/null)"
970
+ if (( recalls > 1 )); then
971
+ printf 'Reinforced %s -- %d recalls now, so it ranks higher in ai-mem-search\n' "$lesson_file" "$recalls"
972
+ else
973
+ printf 'Appended to %s\n' "$lesson_file"
974
+ fi
975
+ }
976
+
977
+ # Ingests a distilled record of an external artifact (meeting, video, voice
978
+ # note, ...) into the vault as ONE flat note per source_id under _transcripts/.
979
+ # The heavy lifting -- transcription and distillation -- happens upstream
980
+ # (fimbria); this only takes the already-distilled metadata as flags and files
981
+ # it in reversible Markdown. Deliberately NOT a raw-transcript store: there is
982
+ # no --text flag, the note LINKS to --transcript-path instead of embedding it
983
+ # (distill, don't dump). Mirrors ai-lesson's one-file-per-slug create-or-update
984
+ # shape so ai-mem-search covers it for free -- no new search path.
985
+ #
986
+ # Metadata arrives as flags, not JSON: parsing arbitrary JSON in pure zsh would
987
+ # need jq, and a new external dependency is exactly what this project refuses.
988
+ ai-mem-ingest() {
989
+ local source_id="" title="" date="" kind="" source_uri="" transcript_path=""
990
+ local project="" summary=""
991
+ local -a persons decisions actions
992
+ persons=(); decisions=(); actions=()
993
+
994
+ while (( $# )); do
995
+ case "$1" in
996
+ --source-id) source_id="${2:-}"; shift 2 ;;
997
+ --title) title="${2:-}"; shift 2 ;;
998
+ --date) date="${2:-}"; shift 2 ;;
999
+ --kind) kind="${2:-}"; shift 2 ;;
1000
+ --source-uri) source_uri="${2:-}"; shift 2 ;;
1001
+ --transcript-path) transcript_path="${2:-}"; shift 2 ;;
1002
+ --project) project="${2:-}"; shift 2 ;;
1003
+ --summary) summary="${2:-}"; shift 2 ;;
1004
+ --person) persons+=("${2:-}"); shift 2 ;;
1005
+ --decision) decisions+=("${2:-}"); shift 2 ;;
1006
+ --action) actions+=("${2:-}"); shift 2 ;;
1007
+ *) print -r -- "ai-mem-ingest: unknown flag: $1" >&2; return 1 ;;
1008
+ esac
1009
+ done
1010
+
1011
+ if [[ -z "$source_id" || -z "$title" || -z "$date" ]]; then
1012
+ print -r -- "Usage: ai-mem-ingest --source-id <id> --title <t> --date <ISO> [--kind <meeting|video|voice-note|other>] [--source-uri <path/url>] [--transcript-path <path>] [--project <name>] [--person <name> ...] [--summary <text>] [--decision <text> ...] [--action <text> ...]" >&2
1013
+ print -r -- "ai-mem-ingest: --source-id, --title, and --date are required" >&2
1014
+ return 1
1015
+ fi
1016
+
1017
+ # Dedup key: the filename is slug(source_id), slugified flat exactly like
1018
+ # ai-lesson so a crafted source_id cannot path-traverse out of _transcripts/,
1019
+ # and a re-ingest of the same source_id lands on the same file (update, not
1020
+ # a duplicate).
1021
+ local slug
1022
+ slug="$(print -r -- "$source_id" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g')"
1023
+ if [[ -z "$slug" ]]; then
1024
+ print -r -- "ai-mem-ingest: --source-id must contain at least one letter or digit" >&2
1025
+ return 1
1026
+ fi
1027
+
1028
+ local transcript_file="$AI_MEM_ROOT/_transcripts/${slug}.md"
1029
+ __ai_mem_guard "$transcript_file" || return 1
1030
+
1031
+ # Optional project wikilink: an explicit --project wins, else the pinned
1032
+ # active session's project. Unlike ai-lesson this does NOT fall back to the
1033
+ # cwd basename -- an ingested artifact may belong to no project at all.
1034
+ local project_name="$project"
1035
+ [[ -z "$project_name" && -n "${AI_MEM_ACTIVE_PROJECT:-}" ]] && project_name="$AI_MEM_ACTIVE_PROJECT"
1036
+
1037
+ mkdir -p "$AI_MEM_ROOT/_transcripts"
1038
+
1039
+ # Build the whole note in a temp file and mv it into place, so a re-ingest
1040
+ # OVERWRITES (updates) the one file rather than appending a second copy.
1041
+ local tmp
1042
+ tmp="$(mktemp)"
1043
+ {
1044
+ print -r -- "---"
1045
+ print -r -- "type: ai-transcript"
1046
+ print -r -- "date: $date"
1047
+ print -r -- "title: $title"
1048
+ [[ -n "$kind" ]] && print -r -- "kind: $kind"
1049
+ print -r -- "source_uri: $source_uri"
1050
+ print -r -- "source_id: $source_id"
1051
+ [[ -n "$project_name" ]] && print -r -- "project: \"[[$project_name]]\""
1052
+ print -r -- "---"
1053
+ print -r -- ""
1054
+ print -r -- "# $title"
1055
+
1056
+ if (( ${#persons} )); then
1057
+ local -a plinks; plinks=()
1058
+ local p
1059
+ for p in "${persons[@]}"; do plinks+=("[[$p]]"); done
1060
+ print -r -- ""
1061
+ print -r -- "Attendees: ${(j: :)plinks}"
1062
+ fi
1063
+
1064
+ if [[ -n "$summary" ]]; then
1065
+ print -r -- ""
1066
+ print -r -- "## Summary"
1067
+ print -r -- ""
1068
+ print -r -- "$summary"
1069
+ fi
1070
+
1071
+ print -r -- ""
1072
+ print -r -- "## Decisions"
1073
+ print -r -- ""
1074
+ if (( ${#decisions} )); then
1075
+ local d
1076
+ for d in "${decisions[@]}"; do print -r -- "- $d"; done
1077
+ fi
1078
+
1079
+ print -r -- ""
1080
+ print -r -- "## Action items"
1081
+ print -r -- ""
1082
+ if (( ${#actions} )); then
1083
+ local a
1084
+ for a in "${actions[@]}"; do print -r -- "- $a"; done
1085
+ fi
1086
+
1087
+ # Distill, don't dump: only a relative link to the source transcript,
1088
+ # never its body. There is no flag that could carry the body.
1089
+ if [[ -n "$transcript_path" ]]; then
1090
+ print -r -- ""
1091
+ print -r -- "## Source"
1092
+ print -r -- ""
1093
+ print -r -- "- Transcript: [$transcript_path]($transcript_path)"
1094
+ fi
1095
+ } > "$tmp"
1096
+
1097
+ local existed=0
1098
+ [[ -f "$transcript_file" ]] && existed=1
1099
+ mv "$tmp" "$transcript_file"
1100
+
1101
+ __ai_mem_vault_backup
1102
+
1103
+ if (( existed )); then
1104
+ printf 'Updated %s\n' "$transcript_file"
1105
+ else
1106
+ printf 'Ingested %s\n' "$transcript_file"
1107
+ fi
831
1108
  }
832
1109
  # Lints the vault's links: session logs missing a project wikilink, previous
833
1110
  # links pointing at a note that no longer exists, and project notes nothing
@@ -900,6 +1177,28 @@ ai-mem-lint() {
900
1177
  fi
901
1178
  fi
902
1179
 
1180
+ # Logs already written from a stale template stay orphaned until repaired.
1181
+ # Reporting them without offering the fix leaves the user to hand-edit
1182
+ # hundreds of files, which nobody does.
1183
+ local -a orphan_files
1184
+ while IFS= read -r -d '' f; do
1185
+ [[ "${f:t}" == "_session_template.md" ]] && continue
1186
+ grep -qm1 -E '^project:.*\[\[.*\]\]' "$f" 2>/dev/null && continue
1187
+ grep -qm1 -E '^project: .+' "$f" 2>/dev/null && orphan_files+=("$f")
1188
+ done < <(find "$AI_MEM_SESSION_DIR" -maxdepth 2 -name "*.md" -print0 2>/dev/null)
1189
+
1190
+ if (( $#orphan_files && fix )); then
1191
+ local pname otmp
1192
+ for f in $orphan_files; do
1193
+ __ai_mem_guard "$f" >/dev/null || continue
1194
+ pname="$(grep -m1 '^project: ' "$f" | sed 's/^project: *//; s/^"//; s/"$//')"
1195
+ [[ -n "$pname" ]] || continue
1196
+ otmp="$f.aimem-link"
1197
+ sed "s|^project: .*$|project: \"[[${pname}]]\"|" "$f" > "$otmp" && mv "$otmp" "$f"
1198
+ done
1199
+ print -r -- "linked $#orphan_files session log(s) back to their project note"
1200
+ fi
1201
+
903
1202
  if (( $#untyped_files )); then
904
1203
  if (( fix )); then
905
1204
  # Written by hand rather than with `sed -i`, whose in-place flag
@@ -923,6 +1222,39 @@ ai-mem-lint() {
923
1222
  fi
924
1223
  fi
925
1224
 
1225
+
1226
+ # Dangling wikilinks: a [[target]] pointing at a note that does not exist --
1227
+ # a dead edge in the graph. Detection only: the dead link is surfaced, never
1228
+ # auto-removed, because the intended target is unknowable and a note's own
1229
+ # prose is the author's to edit. Wikilinks resolve by basename (the same way
1230
+ # ai-mem-serve draws them), so the node set is every note's basename.
1231
+ #
1232
+ # One grep over the vault, never a grep per file -- a per-file scan is the
1233
+ # 25s antipattern ai-mem-search documents. Scope is the vault root derived
1234
+ # from AI_MEM_SESSION_DIR (its parent), the same subtree the rest of this
1235
+ # linter walks, so a caller that redirects the session dir redirects this too.
1236
+ local vault="${AI_MEM_SESSION_DIR:h}"
1237
+ typeset -A _known
1238
+ local nf
1239
+ for nf in ${(f)"$(find "$vault" -name '*.md' -not -path '*/.git/*' 2>/dev/null)"}; do
1240
+ _known[${nf:t:r}]=1
1241
+ done
1242
+ local -a dangling
1243
+ local line src tgt
1244
+ for line in ${(f)"$(grep -rHoE --include='*.md' --exclude-dir=.git -- '\[\[[^]]+\]\]' "$vault" 2>/dev/null)"}; do
1245
+ src="${line%%:\[\[*}" # path, before the ':[[' grep separator
1246
+ tgt="${line##*:\[\[}"; tgt="${tgt%\]\]}" # inside the brackets
1247
+ tgt="${tgt%%\|*}"; tgt="${tgt%%#*}" # drop |alias and #heading
1248
+ tgt="${tgt## }"; tgt="${tgt%% }"
1249
+ [[ -z "$tgt" ]] && continue
1250
+ [[ -n "${_known[$tgt]-}" ]] && continue
1251
+ dangling+=( "${src:t} -> [[${tgt}]]" )
1252
+ done
1253
+ if (( $#dangling )); then
1254
+ print -r -- "$#dangling dangling wikilink(s) -- a [[link]] that resolves to no note:"
1255
+ for line in $dangling; do print -r -- " $line"; done
1256
+ (( issues += $#dangling ))
1257
+ fi
926
1258
  if (( issues == 0 )); then
927
1259
  print -r -- "ok: vault links are clean"
928
1260
  else
@@ -931,6 +1263,211 @@ ai-mem-lint() {
931
1263
  return $(( issues > 0 ? 1 : 0 ))
932
1264
  }
933
1265
 
1266
+
1267
+ # ai-mem-sleep: the vault's "bedtime" pass -- consolidation, decay and lint in
1268
+ # one run, modelled on how a brain sleeps. It NEVER prunes a lesson: the
1269
+ # failure->fix records in _lessons/ are the durable knowledge that must survive,
1270
+ # and reinforcement already strengthens them. Only ephemeral SESSION LOGS decay,
1271
+ # and even they are ARCHIVED (moved under the project's _archive/, which
1272
+ # ai-mem-search skips), never deleted -- git keeps every move reversible.
1273
+ #
1274
+ # Dry run by default: it reports what would move and nothing changes on disk.
1275
+ # --apply performs the archive moves and backs the vault up. Tunables:
1276
+ # AI_MEM_SLEEP_KEEP newest logs per project always kept hot (default 5)
1277
+ # AI_MEM_SLEEP_DAYS archive logs older than this many days (default 90)
1278
+ # AI_MEM_SLEEP_CONSOLIDATE flag a project with this many hot logs (default 8)
1279
+ ai-mem-sleep() {
1280
+ local apply=0
1281
+ [[ "${1:-}" == "--apply" ]] && apply=1
1282
+
1283
+ zmodload zsh/datetime 2>/dev/null
1284
+ local keep="${AI_MEM_SLEEP_KEEP:-5}"
1285
+ local days="${AI_MEM_SLEEP_DAYS:-90}"
1286
+ local ripe="${AI_MEM_SLEEP_CONSOLIDATE:-8}"
1287
+ # Cut-off date as a string. Filenames carry YYYY-MM-DD, which sorts and
1288
+ # compares chronologically as text, so no BSD-vs-GNU `date` parsing is
1289
+ # needed -- strftime on an epoch offset is portable and dependency-free.
1290
+ local cutoff
1291
+ cutoff="$(strftime '%Y-%m-%d' $(( EPOCHSECONDS - days * 86400 )))"
1292
+
1293
+ if (( apply )); then
1294
+ print -r -- "ai-mem-sleep: applying. Keep newest $keep per project; archive session logs dated before $cutoff."
1295
+ else
1296
+ print -r -- "ai-mem-sleep: dry run (nothing moves). Keep newest $keep per project; would archive logs dated before $cutoff."
1297
+ fi
1298
+ print -r -- "Lessons are never touched -- only ephemeral session logs, and they are archived, not deleted."
1299
+ print -r -- "--"
1300
+
1301
+ local sessions_root="$AI_MEM_SESSION_DIR"
1302
+ if [[ ! -d "$sessions_root" ]]; then
1303
+ print -r -- "no session logs at $sessions_root -- nothing to do"
1304
+ return 0
1305
+ fi
1306
+
1307
+ local -i total_archived=0
1308
+ local project pdir log sidecar stem logdate
1309
+ local -a logs stale
1310
+ local -i i hot remaining
1311
+ for pdir in "$sessions_root"/*(/N); do
1312
+ project="${pdir:t}"
1313
+ # Skip the archive dir itself and any bookkeeping dir (leading _ or .).
1314
+ [[ "$project" == [_.]* ]] && continue
1315
+
1316
+ # Newest first: a log's name starts with the project slug, so name order
1317
+ # is date order within one project. (On) sorts by name, descending.
1318
+ logs=( "$pdir"/*.md(N.On) )
1319
+ (( ${#logs} )) || continue
1320
+
1321
+ # The newest KEEP stay hot however old they are, so a dormant project
1322
+ # keeps a readable recent history instead of emptying out.
1323
+ hot=$(( keep < ${#logs} ? keep : ${#logs} ))
1324
+ stale=()
1325
+ for (( i = hot + 1; i <= ${#logs}; i++ )); do
1326
+ log="${logs[i]}"
1327
+ stem="${${log:t:r}%%_*}" # "proj-2026-08-20_10-00-00.md" -> "proj-2026-08-20"
1328
+ logdate="${stem: -10}" # -> "2026-08-20"
1329
+ [[ "$logdate" =~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' ]] || continue # not a dated log
1330
+ [[ "$logdate" < "$cutoff" ]] || continue # not old enough
1331
+ stale+=( "$log" )
1332
+ done
1333
+ remaining=$(( ${#logs} - ${#stale} ))
1334
+
1335
+ if (( ${#stale} )); then
1336
+ print -r -- "$project: ${#stale} log(s) to archive (of ${#logs}, keeping newest $hot)"
1337
+ if (( apply )); then
1338
+ mkdir -p "$pdir/_archive"
1339
+ for log in "${stale[@]}"; do
1340
+ mv -- "$log" "$pdir/_archive/"
1341
+ sidecar="${log:r}.startsha"
1342
+ [[ -f "$sidecar" ]] && mv -- "$sidecar" "$pdir/_archive/"
1343
+ done
1344
+ fi
1345
+ (( total_archived += ${#stale} ))
1346
+ fi
1347
+
1348
+ # Consolidation candidate: many still-hot logs are unconsolidated
1349
+ # knowledge -- a nudge to distil them into a durable lesson.
1350
+ if (( remaining >= ripe )); then
1351
+ print -r -- "$project: $remaining hot logs -- consolidation candidate (distil into a _lessons/ note)"
1352
+ fi
1353
+ done
1354
+
1355
+ print -r -- "--"
1356
+ if (( apply && total_archived > 0 )); then
1357
+ __ai_mem_vault_backup
1358
+ print -r -- "Archived $total_archived session log(s) -- reversible: in each project's _archive/ and in git history."
1359
+ elif (( total_archived > 0 )); then
1360
+ print -r -- "Would archive $total_archived session log(s). Re-run with --apply to move them."
1361
+ else
1362
+ print -r -- "No session logs old enough to archive."
1363
+ fi
1364
+
1365
+ print -r -- "--"
1366
+ print -r -- "lint:"
1367
+ ai-mem-lint
1368
+ }
1369
+
1370
+ # ai-mem-sleep-schedule: run the bedtime pass on its own, nightly. A scheduled
1371
+ # shell does not source ~/.zshrc, so the job sources the module directly
1372
+ # ($AI_MEM_HOME/ai-mem.zsh) before calling ai-mem-sleep --apply. macOS uses a
1373
+ # launchd LaunchAgent; every other platform uses crontab.
1374
+ #
1375
+ # ai-mem-sleep-schedule print what it would install
1376
+ # ai-mem-sleep-schedule --install [--at HH:MM] install it (default 03:00)
1377
+ # ai-mem-sleep-schedule --uninstall remove it
1378
+ #
1379
+ # Dry run by default -- nothing is scheduled until --install. AI_MEM_LAUNCHAGENTS
1380
+ # overrides where the plist is written (used by the tests).
1381
+ ai-mem-sleep-schedule() {
1382
+ local action="print" at="03:00"
1383
+ while (( $# )); do
1384
+ case "$1" in
1385
+ --install) action="install" ;;
1386
+ --uninstall) action="uninstall" ;;
1387
+ --at) at="${2:-}"; shift ;;
1388
+ *) print -r -- "usage: ai-mem-sleep-schedule [--install|--uninstall] [--at HH:MM]"; return 2 ;;
1389
+ esac
1390
+ shift
1391
+ done
1392
+ if [[ ! "$at" =~ '^([01][0-9]|2[0-3]):[0-5][0-9]$' ]]; then
1393
+ print -r -- "ai-mem-sleep-schedule: --at wants HH:MM (24-hour), got '$at'"
1394
+ return 2
1395
+ fi
1396
+ local hh="${at%%:*}" mm="${at##*:}"
1397
+ local module="$AI_MEM_HOME/ai-mem.zsh"
1398
+ local cmd="source ${(q)module}; ai-mem-sleep --apply"
1399
+ local label="app.ai-mem.sleep"
1400
+ local log="${AI_MEM_ROOT:h}/ai-mem-sleep.log"
1401
+
1402
+ if [[ "$OSTYPE" == darwin* ]]; then
1403
+ local plist="${AI_MEM_LAUNCHAGENTS:-$HOME/Library/LaunchAgents}/${label}.plist"
1404
+ local body='<?xml version="1.0" encoding="UTF-8"?>
1405
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1406
+ <plist version="1.0"><dict>
1407
+ <key>Label</key><string>'"$label"'</string>
1408
+ <key>ProgramArguments</key>
1409
+ <array><string>/bin/zsh</string><string>-c</string><string>'"$cmd"'</string></array>
1410
+ <key>StartCalendarInterval</key>
1411
+ <dict><key>Hour</key><integer>'"${hh#0}"'</integer><key>Minute</key><integer>'"${mm#0}"'</integer></dict>
1412
+ <key>StandardOutPath</key><string>'"$log"'</string>
1413
+ <key>StandardErrorPath</key><string>'"$log"'</string>
1414
+ </dict></plist>'
1415
+ case "$action" in
1416
+ print)
1417
+ print -r -- "would install a launchd agent (daily at $at):"
1418
+ print -r -- " $plist"
1419
+ print -r -- "$body"
1420
+ print -r -- "--"
1421
+ print -r -- "install with: ai-mem-sleep-schedule --install --at $at" ;;
1422
+ install)
1423
+ mkdir -p "${plist:h}"
1424
+ print -r -- "$body" > "$plist" || { print -r -- "could not write $plist"; return 1 }
1425
+ if [[ -z "${AI_MEM_SLEEP_NO_LAUNCHCTL-}" ]] && command -v launchctl >/dev/null 2>&1; then
1426
+ launchctl unload "$plist" 2>/dev/null
1427
+ if launchctl load "$plist" 2>/dev/null; then
1428
+ print -r -- "scheduled: $label runs daily at $at"
1429
+ else
1430
+ print -r -- "wrote $plist, but launchctl load failed -- it will load at next login"
1431
+ fi
1432
+ else
1433
+ print -r -- "wrote $plist (launchctl not found; loads at next login)"
1434
+ fi ;;
1435
+ uninstall)
1436
+ [[ -z "${AI_MEM_SLEEP_NO_LAUNCHCTL-}" ]] && command -v launchctl >/dev/null 2>&1 && launchctl unload "$plist" 2>/dev/null
1437
+ if [[ -f "$plist" ]]; then
1438
+ rm -f "$plist" && print -r -- "removed $label"
1439
+ else
1440
+ print -r -- "no schedule at $plist"
1441
+ fi ;;
1442
+ esac
1443
+ return 0
1444
+ fi
1445
+
1446
+ # Linux and other: crontab. The comment marker lets --uninstall find its own
1447
+ # line without disturbing anything else the user has scheduled.
1448
+ local cronline="${mm#0} ${hh#0} * * * /bin/zsh -c '${cmd}' >> ${log} 2>&1 # ${label}"
1449
+ case "$action" in
1450
+ print)
1451
+ print -r -- "would add this crontab line (daily at $at):"
1452
+ print -r -- " $cronline"
1453
+ print -r -- "--"
1454
+ print -r -- "install with: ai-mem-sleep-schedule --install --at $at" ;;
1455
+ install)
1456
+ if ! command -v crontab >/dev/null 2>&1; then
1457
+ print -r -- "crontab not found -- add this to your scheduler yourself:"
1458
+ print -r -- " $cronline"
1459
+ return 1
1460
+ fi
1461
+ if { crontab -l 2>/dev/null | grep -v "# ${label}\$"; print -r -- "$cronline"; } | crontab -; then
1462
+ print -r -- "scheduled: crontab entry $label runs daily at $at"
1463
+ else
1464
+ print -r -- "crontab update failed"; return 1
1465
+ fi ;;
1466
+ uninstall)
1467
+ if ! command -v crontab >/dev/null 2>&1; then print -r -- "crontab not found"; return 1; fi
1468
+ crontab -l 2>/dev/null | grep -v "# ${label}\$" | crontab - && print -r -- "removed $label from crontab" ;;
1469
+ esac
1470
+ }
934
1471
  # Full-text search across the vault. Plain grep -- no new dependency, and at
935
1472
  # vault scale (a personal notes collection, not a codebase) there is no real
936
1473
  # performance reason to reach for anything faster. Always resolves one hop
@@ -964,7 +1501,10 @@ ai-mem-search() {
964
1501
  # -F: the caller is usually an agent passing a free-text term, where a
965
1502
  # stray . ( | must match literally rather than as a regex metacharacter.
966
1503
  local raw
967
- raw="$(grep -rniF --exclude-dir=.git --exclude='_session_template.md' --exclude='_project_template.md' --exclude='_lesson_template.md' -- "$term" "$search_root" 2>/dev/null)"
1504
+ # --exclude-dir=_archive: session logs that ai-mem-sleep has retired are out
1505
+ # of the hot search path (their durable content lives on in a lesson). They
1506
+ # stay in git and on disk, just not in a default search.
1507
+ 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)"
968
1508
 
969
1509
  if [[ -z "$raw" ]]; then
970
1510
  print -r -- "no matches for '$term' in $search_root"
@@ -990,19 +1530,44 @@ ai-mem-search() {
990
1530
  # THREE lessons that answer it exactly. The durable answer was in the
991
1531
  # vault and unreachable.
992
1532
  #
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.
1533
+ # Sort key is rank + reinforcement + timestamp. "1" for _lessons/, "0"
1534
+ # for everything else, so a lesson with an old date still beats today's
1535
+ # chatter. Within the lessons tier, a lesson RECALLED more often ranks
1536
+ # above a once-seen one -- long-term potentiation for the vault: a pathway
1537
+ # that keeps firing is strengthened. Timestamp breaks ties below that.
1538
+ #
1539
+ # Reinforcement is the count of dated entries the lesson already carries.
1540
+ # ai-lesson appends one every time the same problem is hit again, so the
1541
+ # count is already in the data -- no separate counter to keep in sync (a
1542
+ # shadowed derived field is its own class of bug), and it is read in ONE
1543
+ # grep over the lesson headers, never a per-file scan. Only whole-vault
1544
+ # searches consult it; a project-scoped search sees no lessons anyway.
1545
+ local strengths=""
1546
+ [[ -z "$project" ]] && strengths="$(grep -rc '^## [0-9]' "$AI_MEM_ROOT/_lessons" 2>/dev/null)"
1547
+
995
1548
  local sorted
996
- sorted="$(print -r -- "$raw" | awk -v root="$search_root/" '
1549
+ sorted="$(awk -v root="$search_root/" '
1550
+ # First input: <lesson-file-path>:<entry-count>. Build the strength map.
1551
+ FNR == NR {
1552
+ if (match($0, /:[0-9]+$/)) {
1553
+ str[substr($0, 1, RSTART - 1)] = substr($0, RSTART + 1) + 0
1554
+ }
1555
+ next
1556
+ }
997
1557
  {
998
1558
  ts = "0000-00-00_00-00-00"
999
1559
  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]/))
1000
1560
  ts = substr($0, RSTART, RLENGTH)
1001
1561
  rel = $0
1002
1562
  sub(root, "", rel)
1003
- rank = (rel ~ /^_lessons\//) ? "1" : "0"
1004
- print rank "|" ts "|" $0
1005
- }' | sort -r | cut -d'|' -f3-)"
1563
+ is_lesson = (rel ~ /^_lessons\//)
1564
+ rank = is_lesson ? "1" : "0"
1565
+ # The file this match came from, to look up its reinforcement count.
1566
+ path = $0
1567
+ sub(/:[0-9]+:.*$/, "", path)
1568
+ strength = is_lesson ? sprintf("%03d", str[path] + 0) : "000"
1569
+ print rank "|" strength "|" ts "|" $0
1570
+ }' <(print -r -- "$strengths") <(print -r -- "$raw") | sort -r | cut -d'|' -f4-)"
1006
1571
 
1007
1572
  # Bound the output. The consumer is normally an agent with a finite
1008
1573
  # context window, and an unbounded dump is actively harmful there in a