@skedulo/memory-hub-mcp 0.2.6 → 0.2.8

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
@@ -45,8 +45,8 @@ lives here so it updates on the next `yarn build`, not via a manual `cp` into
45
45
  ## Claude Desktop
46
46
 
47
47
  The MCP server is plain stdio, so Claude Desktop can run it. The `memory-hub-hook` package
48
- cannot — Claude Desktop has no hook system — so startup recall and end-of-session auto-save
49
- have no equivalent there. Two consequences, both permanent until Desktop grows hooks:
48
+ cannot — Claude Desktop has no hook system — so startup recall and the optional capture hook
49
+ have no equivalent there, and nothing is saved unless Claude calls `memory_save`. Two consequences, both permanent until Desktop grows hooks:
50
50
 
51
51
  - **Recall** is covered by the `memory_sessionContext` tool plus the server's `instructions`,
52
52
  which ask Claude to call it once at the start of a conversation. Nothing fires it
@@ -4,15 +4,17 @@
4
4
  # start — every call degrades to "no content" on any failure.
5
5
  set -u
6
6
 
7
+ [ -n "${MEMORY_HUB_STOP_HOOK_ACTIVE:-}" ] && exit 0
8
+
7
9
  # The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
8
10
  # be set to override this (e.g. pointing at a local `sked function dev` instance).
9
11
  FUNCTION_URL="${MEMORY_HUB_FUNCTION_URL:-https://dev-api.test.skl.io/function/memory-hub/memory-hub}"
10
- TOKEN="${MEMORY_HUB_MCP_TOKEN:-}"
12
+ TOKEN="${MEMORY_HUB_MCP_TOKEN:-${CLAUDE_PLUGIN_OPTION_TOKEN:-}}"
11
13
 
12
14
  if [ -z "$TOKEN" ]; then
13
15
  # A plugin install has no setup step of its own, so it says how to add the token.
14
16
  if [ -n "${CLAUDE_PLUGIN_ROOT:-}" ]; then
15
- printf '%s\n' '{"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "memory-hub plugin: MEMORY_HUB_MCP_TOKEN is not set, so memory is off this session. Tell the user to run `npx -y @skedulo/memory-hub-mcp setup --code` in a terminal, then restart Claude Code."}}'
17
+ printf '%s\n' '{"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "memory-hub plugin: MEMORY_HUB_MCP_TOKEN is not set, so memory is off this session. Tell the user to run `npx -y @skedulo/memory-hub-mcp setup --code` in a terminal (it logs in with sked and stores a token), or to paste a Skedulo API token with /plugin configure memory-hub@se-ai-memory-hub. Then restart Claude Code."}}'
16
18
  fi
17
19
  exit 0
18
20
  fi
@@ -31,6 +33,8 @@ call() {
31
33
  # real tenant latency.
32
34
  # Test seam: replay canned per-leg responses so budget and assembly logic test offline.
33
35
  if [ -n "${MEMORY_HUB_FIXTURE_DIR:-}" ]; then
36
+ mkdir -p "$MEMORY_HUB_FIXTURE_DIR/requests" 2>/dev/null
37
+ printf '%s' "$body" > "$MEMORY_HUB_FIXTURE_DIR/requests/$(basename "$out_file")" 2>/dev/null
34
38
  cp "$MEMORY_HUB_FIXTURE_DIR/$(basename "$out_file")" "$out_file" 2>/dev/null || true
35
39
  return 0
36
40
  fi
@@ -162,6 +166,9 @@ fi
162
166
  if [ -n "$REPO_UID" ]; then
163
167
  # The repo legs get the larger share — they are first in priority order below.
164
168
  REPO_UID_JSON=$(printf '%s' "$REPO_UID" | jq -Rs .)
169
+ # The unscoped self facts from the first round span every repo; replace them, never fall back to them.
170
+ rm -f "$TMP_DIR/facts_self.json"
171
+ call "/memory/recall" "$(printf '{"scope":"self","repo":%s,"maxTotalChars":%d}' "$REPO_UID_JSON" "$FETCH_FACTS")" "$TMP_DIR/facts_self.json" &
165
172
  call "/memory/recall" "$(printf '{"scope":"team","repo":%s,"maxTotalChars":%d}' "$REPO_UID_JSON" "$FETCH_REPO_FACTS")" "$TMP_DIR/facts_repo.json" &
166
173
  call "/memory/list-skills" "$(printf '{"scope":"team","repo":%s,"maxTotalChars":%d}' "$REPO_UID_JSON" "$FETCH_REPO_REST")" "$TMP_DIR/skills_repo.json" &
167
174
  call "/memory/recall-wiki" "$(printf '{"scope":"team","repo":%s,"maxTotalChars":%d}' "$REPO_UID_JSON" "$FETCH_REPO_REST")" "$TMP_DIR/wiki_repo.json" &
@@ -194,16 +201,38 @@ cut_pointer() {
194
201
  printf '(if .truncated then " [cut at \\(.content | length) of \\(.fullLength) — memory_get type=%s uid=\\(.uid)]" else "" end)' "$1"
195
202
  }
196
203
 
204
+ # Same as user-prompt-submit.sh; change both together.
205
+ EXTRAS_DEF='def extras($under; $text):
206
+ (if (.externalRef | type) == "string" and .externalRef != "" and .externalRef != $under then " · " + (.externalRef | gsub("[[:cntrl:]]"; " ")) else "" end)
207
+ + ((first(($text // "") | gsub("[A-Za-z][A-Za-z0-9+.-]*://[^\\s)]*"; " ") | scan("[A-Za-z0-9_./-]+\\.(?:tsx|ts|jsx|js|mjs|sh|py|json|md|yml|yaml|cls|java|kt|swift|go|rb)\\b") | select(startswith("http") | not)) // null) | if . then " · cites " + . else "" end);'
208
+
209
+ SUPERSEDED_DEF='def superseded: (.externalRef) as $r
210
+ | if ($r | type) == "string" and ($newest[$r] != null) and (.lastModifiedDate | type) == "string" and .lastModifiedDate < $newest[$r].date
211
+ then " · older than " + $newest[$r].uid[0:8] + " for " + ($r | gsub("[[:cntrl:]]"; " ")) + ", may be superseded"
212
+ else "" end;'
213
+
214
+ # Newest fact per externalRef across every fact leg that gets injected, so a marker holds even when the newer fact sits in another section.
215
+ newest_fact_per_ref() {
216
+ local f
217
+ for f in "$@"; do
218
+ jq -c '.facts[]? | select(type == "object")' "$f" 2>/dev/null || true
219
+ done | jq -s -c '
220
+ [.[] | select((.externalRef | type) == "string" and .externalRef != "" and (.lastModifiedDate | type) == "string" and (.uid | type) == "string")]
221
+ | unique_by(.uid) | group_by(.externalRef)
222
+ | map(select(length > 1) | max_by(.lastModifiedDate) | {key: .externalRef, value: {uid: .uid, date: .lastModifiedDate}})
223
+ | from_entries' 2>/dev/null || true
224
+ }
225
+
197
226
  extract_facts() {
198
- jq -c ".facts[]? | (\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
227
+ jq -c --argjson newest "$NEWEST_BY_REF" "$EXTRAS_DEF $SUPERSEDED_DEF .facts[]? | (\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP + extras(\"\"; .content) + superseded) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
199
228
  }
200
229
 
201
230
  extract_skills() {
202
- jq -c ".skills[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
231
+ jq -c "$EXTRAS_DEF .skills[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP + extras(\"\"; .content)) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
203
232
  }
204
233
 
205
234
  extract_wiki() {
206
- jq -c ".pages[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
235
+ jq -c "$EXTRAS_DEF .pages[]? | (\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP + extras(\"\"; .content)) | $CLOSE_FENCE | $INDENT" "$1" 2>/dev/null || true
207
236
  }
208
237
 
209
238
  # Absent on functions deployed before the field existed; fall back to what arrived rather than inventing a number.
@@ -232,14 +261,13 @@ omission_footer() {
232
261
 
233
262
  # Sized for every section being skipped, so the footer can never itself be the thing squeezed out.
234
263
  FOOTER_NAMES="Your memory-hub facts, Team memory-hub facts, Your memory-hub skills, Team memory-hub skills"
235
- [ -n "$REPO_UID" ] && FOOTER_NAMES="Team knowledge for ${REPO_NAME}, ${FOOTER_NAMES}"
264
+ [ -n "$REPO_UID" ] && FOOTER_NAMES="Team knowledge for ${REPO_NAME}, Your memory-hub facts, Your memory-hub skills, Team memory-hub skills"
236
265
  FOOTER_RESERVE=$(($(omission_footer "$FOOTER_NAMES" | wc -m) + 2))
237
266
  REMAINING=$((BUDGET - FOOTER_RESERVE))
238
267
  SKIPPED=""
239
268
 
240
269
  # Even share per section, recomputed: huge facts/repo sections cannot starve skills, and unspent budget flows onward.
241
270
  SECTIONS_LEFT=4
242
- [ -n "$REPO_UID" ] && SECTIONS_LEFT=5
243
271
 
244
272
  # Emits at most $1 chars of $2, whole items only. $3 is what the server holds — its cap has usually dropped items already.
245
273
  clip_to_budget() {
@@ -299,13 +327,21 @@ add_section() {
299
327
  REMAINING=$((REMAINING - ${#clipped} - ${#heading} - 6))
300
328
  }
301
329
 
330
+ # Inside a resolved repo the repo section already carries the team's knowledge; the all-teams facts would leak other clients' work.
331
+ FACT_FILES=("$TMP_DIR/facts_self.json")
332
+ [ -n "$REPO_UID" ] && FACT_FILES+=("$TMP_DIR/facts_repo.json") || FACT_FILES+=("$TMP_DIR/facts_team.json")
333
+ NEWEST_BY_REF=$(newest_fact_per_ref "${FACT_FILES[@]}")
334
+ [ -n "$NEWEST_BY_REF" ] || NEWEST_BY_REF='{}'
335
+
302
336
  FACTS_SELF=$(extract_facts "$TMP_DIR/facts_self.json")
303
- FACTS_TEAM=$(extract_facts "$TMP_DIR/facts_team.json")
337
+ FACTS_TEAM=""
338
+ [ -n "$REPO_UID" ] || FACTS_TEAM=$(extract_facts "$TMP_DIR/facts_team.json")
304
339
  SKILLS_SELF=$(extract_skills "$TMP_DIR/skills_self.json")
305
340
  SKILLS_TEAM=$(extract_skills "$TMP_DIR/skills_team.json")
306
341
 
307
342
  FACTS_SELF_N=$(leg_total "$TMP_DIR/facts_self.json" "$(count_items "$FACTS_SELF")")
308
- FACTS_TEAM_N=$(leg_total "$TMP_DIR/facts_team.json" "$(count_items "$FACTS_TEAM")")
343
+ FACTS_TEAM_N=0
344
+ [ -n "$REPO_UID" ] || FACTS_TEAM_N=$(leg_total "$TMP_DIR/facts_team.json" "$(count_items "$FACTS_TEAM")")
309
345
  SKILLS_SELF_N=$(leg_total "$TMP_DIR/skills_self.json" "$(count_items "$SKILLS_SELF")")
310
346
  SKILLS_TEAM_N=$(leg_total "$TMP_DIR/skills_team.json" "$(count_items "$SKILLS_TEAM")")
311
347
 
@@ -365,13 +401,7 @@ else
365
401
  fi
366
402
  DIAG="${DIAG}_"
367
403
 
368
- # Recall below is the hook's own automation — it never saves anything new, and an
369
- # agent reading only the facts/skills sections has no reason to infer that a
370
- # separate, non-automatic step exists for the other half (on-demand mid-session
371
- # recall, and saving durable results once a task lands). State that explicitly and
372
- # unconditionally (not gated behind having any facts to show) so an agent that
373
- # finds nothing below still knows to check back in before finishing a task.
374
- #
404
+ # Unconditional, not gated behind having any facts to show, so an agent that finds nothing below still knows to check back in before finishing a task.
375
405
  # First, not last: it is the only part that asks for an action, so it has to survive the
376
406
  # budget even when nothing else does.
377
407
  # A stale build cannot warn about itself, so the hook, which a git pull does refresh, has to.
@@ -392,13 +422,86 @@ if [ -n "$MCP_DIR" ] && mcp_build_is_stale "$MCP_DIR"; then
392
422
  STALE_MCP="WARNING: the memory-hub MCP build in this checkout is older than its source, so tools the guide names (memory_get) may be missing and recalled items cut at 500 chars cannot be fetched whole. Tell the user to run ./scripts/setup-dev.sh (or cd memory-hub-mcp && yarn build) and restart the session.${NL}${NL}"
393
423
  fi
394
424
 
425
+ auto_capture_registered() {
426
+ local f
427
+ for f in "${MEMORY_HUB_SETTINGS:-$HOME/.claude/settings.json}" "${MEMORY_HUB_SETTINGS_LOCAL:-$HOME/.claude/settings.local.json}"; do
428
+ [ -f "$f" ] || continue
429
+ jq -e '[(.hooks.Stop // [])[], (.hooks.SessionEnd // [])[] | (.hooks // [])[] | .command // empty | select(type == "string" and contains("session-stop.sh"))] | length > 0' "$f" >/dev/null 2>&1 && return 0
430
+ done
431
+ return 1
432
+ }
433
+
434
+ if auto_capture_registered; then
435
+ SAVE_LINE='Auto-capture is on: after long stretches and at session end, a background run saves or updates a Fact for this session'"'"'s work, shown as "memory-hub auto-saved" notices. Still save what matters yourself.'
436
+ else
437
+ SAVE_LINE='What follows is an automatic recall only - nothing in this session is saved unless you call memory_save.'
438
+ fi
439
+
440
+ STATE_DIR="${MEMORY_HUB_STATE_DIR:-$HOME/.claude/memory-hub-hook/state}"
441
+
442
+ # Lists captures the optional session-stop.sh hook saved in the background.
443
+ # Renders capture log lines as "<line number><TAB>notice"; the same in session-start.sh and user-prompt-submit.sh, change both together.
444
+ render_capture_notices() {
445
+ jq -R -r '
446
+ def clean: tostring | gsub("[[:cntrl:]]"; " ");
447
+ input_line_number as $n
448
+ | fromjson?
449
+ | select(type == "object" and (.uid | type) == "string" and (.action == "saved" or .action == "updated"))
450
+ | "\($n)\t- memory-hub auto-" + .action + " " + ((.type // "Fact") | clean) + " " + (.uid | clean)
451
+ + (if (.externalRef | type) == "string" and .externalRef != "" then " for " + (.externalRef | clean) else "" end)' 2>/dev/null
452
+ }
453
+
454
+ capture_unreported() {
455
+ local file="$1" marker="${1%.jsonl}.reported" total reported
456
+ total=$(wc -l < "$file" 2>/dev/null | tr -d ' ')
457
+ case "$total" in '' | *[!0-9]*) return 1 ;; esac
458
+ reported=$(cat "$marker" 2>/dev/null)
459
+ case "$reported" in '' | *[!0-9]*) reported=0 ;; esac
460
+ [ "$total" -ge "$reported" ] || reported=0
461
+ [ "$total" -gt "$reported" ] || return 1
462
+ CAPTURE_TOTAL=$total
463
+ CAPTURE_REPORTED=$reported
464
+ }
465
+
466
+ # Fits $2 chars. A notice is marked reported only once shown, so a dropped one is announced next session.
467
+ collect_capture_notices() {
468
+ local state="$1" room="$2" heading="## Memory saved automatically" file out n text consumed lines="" used hidden=0 stopped=0
469
+ used=$((${#heading} + 1))
470
+ room=$((room - 28))
471
+ while IFS= read -r file; do
472
+ [ -n "$file" ] || continue
473
+ capture_unreported "$file" || continue
474
+ out=$(head -n "$CAPTURE_TOTAL" "$file" | tail -n +"$((CAPTURE_REPORTED + 1))" | render_capture_notices)
475
+ consumed=$((CAPTURE_TOTAL - CAPTURE_REPORTED))
476
+ [ "$stopped" = 0 ] || consumed=0
477
+ while IFS=$'\t' read -r n text; do
478
+ [ -n "$n" ] || continue
479
+ if [ "$stopped" = 0 ] && [ $((used + ${#text} + 1)) -le "$room" ]; then
480
+ lines="${lines}${text}${NL}"
481
+ used=$((used + ${#text} + 1))
482
+ else
483
+ [ "$stopped" = 1 ] || consumed=$((n - 1))
484
+ stopped=1
485
+ hidden=$((hidden + 1))
486
+ fi
487
+ done <<< "$out"
488
+ [ "$consumed" -eq 0 ] || printf '%s\n' "$((CAPTURE_REPORTED + consumed))" > "${file%.jsonl}.reported" 2>/dev/null
489
+ done < <(find "$state" -maxdepth 1 -type f -name 'captures-*.jsonl' -mtime -7 2>/dev/null | sort)
490
+ [ -n "$lines" ] || return 0
491
+ [ "$hidden" -eq 0 ] || lines="${lines}- (${hidden} more not shown)${NL}"
492
+ printf '%s%s%s' "${heading}${NL}" "$lines"
493
+ }
494
+
395
495
  REMINDER="## Reminder${NL}"
396
- REMINDER="${REMINDER}What follows is an automatic recall only - it never saves anything new.${NL}"
496
+ REMINDER="${REMINDER}${SAVE_LINE}${NL}"
397
497
  REMINDER="${REMINDER}Invoke the se-ai-memory-hub skill during this session: memory_recall before${NL}"
398
498
  REMINDER="${REMINDER}investigating something that smells like prior context, and memory_save${NL}"
399
499
  REMINDER="${REMINDER}(type \"Fact\" or \"Scenario\") once a task produces a durable decision, root${NL}"
400
500
  REMINDER="${REMINDER}cause, or fix worth keeping for next time.${NL}${NL}"
401
501
  REMINDER="${REMINDER}${STALE_MCP}"
502
+ NOTICES=$(collect_capture_notices "$STATE_DIR" "$((REMAINING - ${#REMINDER} - ${#DIAG}))" 2>/dev/null || true)
503
+ [ -z "$NOTICES" ] || NOTICES="${NOTICES}${NL}${NL}"
504
+ REMINDER="${REMINDER}${NOTICES}"
402
505
  CONTEXT="$REMINDER"
403
506
  REMAINING=$((REMAINING - ${#REMINDER} - ${#DIAG}))
404
507
 
@@ -1,60 +1,175 @@
1
1
  #!/usr/bin/env bash
2
- # Stop hook: when a session ends, resumes it headlessly with a narrow tool
3
- # allowlist and asks it to save anything durable it didn't already save. Closes
4
- # the gap that session-start.sh's injected "## Reminder" only nudges at —
5
- # nothing upstream of this actually saves memory on its own.
6
- #
7
- # Must never block session exit or crash: every failure path degrades to a
8
- # silent no-op. Runs as an "async": true Stop hook (see ~/.claude/settings.json)
9
- # so the harness doesn't wait on it either way.
2
+ # Stop / SessionEnd hook: throttled headless capture of durable knowledge from the session.
10
3
  set -u
11
4
 
12
- # Recursion guard: the headless `claude -p --resume` call below is itself a
13
- # Claude Code invocation, and this Stop hook is registered at the user level,
14
- # so it would otherwise fire again when THAT session ends, forever. Set before
15
- # spawning, checked first thing here.
5
+ # The headless resume below is itself a Claude session whose end would fire this hook again.
16
6
  if [ -n "${MEMORY_HUB_STOP_HOOK_ACTIVE:-}" ]; then
17
7
  exit 0
18
8
  fi
19
9
 
20
- TOKEN="${MEMORY_HUB_MCP_TOKEN:-}"
10
+ TOKEN="${MEMORY_HUB_MCP_TOKEN:-${CLAUDE_PLUGIN_OPTION_TOKEN:-}}"
21
11
  [ -n "$TOKEN" ] || exit 0
12
+ command -v jq >/dev/null 2>&1 || exit 0
13
+
14
+ # Same default as session-start.sh; change both together.
15
+ FUNCTION_URL="${MEMORY_HUB_FUNCTION_URL:-https://dev-api.test.skl.io/function/memory-hub/memory-hub}"
16
+ CLAUDE_BIN="${MEMORY_HUB_CLAUDE_BIN:-claude}"
17
+ INTERVAL_MIN="${MEMORY_HUB_CAPTURE_INTERVAL_MIN:-30}"
18
+ MIN_NEW_LINES="${MEMORY_HUB_CAPTURE_MIN_NEW_LINES:-40}"
19
+ SESSION_END_MIN_LINES=8
20
+ case "$INTERVAL_MIN" in ''|*[!0-9]*) INTERVAL_MIN=30 ;; esac
21
+ case "$MIN_NEW_LINES" in ''|*[!0-9]*) MIN_NEW_LINES=40 ;; esac
22
22
 
23
23
  INPUT=$(cat)
24
- SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null) || exit 0
24
+ EVENT=$(printf '%s' "$INPUT" | jq -r '.hook_event_name // empty' 2>/dev/null)
25
+ case "$EVENT" in Stop|SessionEnd) ;; *) exit 0 ;; esac
26
+ SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null | tr -cd 'A-Za-z0-9_-')
25
27
  [ -n "$SESSION_ID" ] || exit 0
28
+ TRANSCRIPT_PATH=$(printf '%s' "$INPUT" | jq -r '.transcript_path // empty' 2>/dev/null)
29
+ INPUT_CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
30
+
31
+ umask 077
32
+ STATE_DIR="${MEMORY_HUB_STATE_DIR:-$HOME/.claude/memory-hub-hook/state}"
33
+ mkdir -p "$STATE_DIR/logs" 2>/dev/null || exit 0
34
+ STATE_FILE="$STATE_DIR/capture-$SESSION_ID.json"
26
35
 
27
- # Cheap pre-filter before spawning a whole headless agent: a transcript this
28
- # short is a trivial exchange (a one-off question, an aborted session) with
29
- # nothing durable to extract. Line count, not a parsed field, on purpose — it
30
- # doesn't depend on the transcript JSONL's exact schema, just its volume.
31
- TRANSCRIPT_PATH=$(printf '%s' "$INPUT" | jq -r '.transcript_path // empty' 2>/dev/null) || TRANSCRIPT_PATH=""
36
+ LINES=0
32
37
  if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ]; then
33
- LINE_COUNT=$(wc -l < "$TRANSCRIPT_PATH" 2>/dev/null | tr -d ' ')
34
- if [ -n "$LINE_COUNT" ] && [ "$LINE_COUNT" -lt 8 ] 2>/dev/null; then
38
+ LINES=$(wc -l < "$TRANSCRIPT_PATH" 2>/dev/null | tr -d ' ')
39
+ case "$LINES" in ''|*[!0-9]*) LINES=0 ;; esac
40
+ fi
41
+ NOW_EPOCH=$(date +%s)
42
+
43
+ write_state() {
44
+ printf '{"lastEpoch":%d,"lastLines":%d}\n' "$NOW_EPOCH" "$LINES" > "$STATE_FILE.tmp" 2>/dev/null &&
45
+ mv "$STATE_FILE.tmp" "$STATE_FILE" 2>/dev/null
46
+ }
47
+
48
+ HAVE_STATE=0
49
+ LAST_EPOCH=0
50
+ LAST_LINES=0
51
+ if [ -f "$STATE_FILE" ]; then
52
+ state=$(jq -r '[.lastEpoch, .lastLines] | @tsv' "$STATE_FILE" 2>/dev/null) || state=""
53
+ if [ -n "$state" ]; then
54
+ saved_epoch=${state%%$'\t'*}
55
+ saved_lines=${state#*$'\t'}
56
+ epoch_ok=0
57
+ lines_ok=0
58
+ case "$saved_epoch" in ''|*[!0-9]*) ;; *) [ "${#saved_epoch}" -le 12 ] && { LAST_EPOCH=$((10#$saved_epoch)); epoch_ok=1; } ;; esac
59
+ case "$saved_lines" in ''|*[!0-9]*) ;; *) [ "${#saved_lines}" -le 12 ] && { LAST_LINES=$((10#$saved_lines)); lines_ok=1; } ;; esac
60
+ [ "$epoch_ok$lines_ok" = 11 ] && HAVE_STATE=1
61
+ fi
62
+ fi
63
+
64
+ if [ "$EVENT" = "Stop" ]; then
65
+ if [ "$HAVE_STATE" = 0 ]; then
66
+ write_state
35
67
  exit 0
36
68
  fi
69
+ [ $((NOW_EPOCH - LAST_EPOCH)) -ge $((INTERVAL_MIN * 60)) ] || exit 0
70
+ [ $((LINES - LAST_LINES)) -ge "$MIN_NEW_LINES" ] || exit 0
71
+ else
72
+ [ $((LINES - LAST_LINES)) -ge "$SESSION_END_MIN_LINES" ] || exit 0
73
+ fi
74
+
75
+ LOCK_DIR="$STATE_DIR/capture-$SESSION_ID.lock"
76
+ if ! mkdir "$LOCK_DIR" 2>/dev/null; then
77
+ # A capture that died without cleaning up must not block the session forever.
78
+ [ -n "$(find "$LOCK_DIR" -maxdepth 0 -mmin +60 2>/dev/null)" ] || exit 0
79
+ rmdir "$LOCK_DIR" 2>/dev/null
80
+ mkdir "$LOCK_DIR" 2>/dev/null || exit 0
37
81
  fi
38
82
 
39
- PROMPT='This session is ending. Scan it for a decision, root cause, or fix that
40
- would be worth knowing next time, in this repo or across the team — not
41
- narration or exploration. If you already called memory_save with type
42
- "Fact" or "Scenario" for it earlier in this same session, do not save it
43
- again. If nothing in this session qualifies, do nothing and finish.
44
- For each item that qualifies, first call memory_recall with a query for it.
45
- If one of your own memories already covers it, call memory_update on that
46
- memory with the revised full text instead of saving a copy. Otherwise call
47
- memory_save (type "Fact" or "Scenario"). Never delete anything.'
48
-
49
- LOG_FILE="${TMPDIR:-/tmp}/memory-hub-stop-hook.log"
50
- {
51
- echo "---- $(date -u +%FT%TZ) session=$SESSION_ID ----"
52
- MEMORY_HUB_STOP_HOOK_ACTIVE=1 claude -p --resume "$SESSION_ID" \
53
- --allowedTools "mcp__memory-hub__memory_recall,mcp__memory-hub__memory_save,mcp__memory-hub__memory_update,mcp__plugin_memory-hub_memory-hub__memory_recall,mcp__plugin_memory-hub_memory-hub__memory_save,mcp__plugin_memory-hub_memory-hub__memory_update" \
83
+ write_state
84
+ [ -n "$INPUT_CWD" ] && [ -d "$INPUT_CWD" ] && cd "$INPUT_CWD" 2>/dev/null
85
+
86
+ TICKET_DENYLIST=" UTF ISO SHA RFC HTTP HTTPS TLS SSL MD AES RSA X Y Z UTC GMT CVE COVID PR "
87
+
88
+ transcript_text() {
89
+ local text
90
+ [ -f "$TRANSCRIPT_PATH" ] || return 0
91
+ text=$(jq -r 'select(.type == "user" or .type == "assistant") | .message.content
92
+ | if type == "string" then .
93
+ elif type == "array" then .[] | select(type == "object" and .type == "text") | .text
94
+ else empty end' "$TRANSCRIPT_PATH" 2>/dev/null) || text=$(cat "$TRANSCRIPT_PATH" 2>/dev/null)
95
+ printf '%s\n' "$text"
96
+ }
97
+
98
+ top_ticket_refs() {
99
+ transcript_text | jq -Rr 'scan("\\b[A-Z][A-Z0-9]{1,9}-[0-9]{1,6}\\b")' 2>/dev/null |
100
+ awk -v deny="$TICKET_DENYLIST" '
101
+ { split($0, parts, "-"); if (index(deny, " " parts[1] " ")) next
102
+ if (!($0 in count)) order[++n] = $0
103
+ count[$0]++ }
104
+ END { for (i = 1; i <= n; i++) print count[order[i]], i, order[i] }' |
105
+ sort -k1,1nr -k2,2n | head -n 3 | awk '{ print $3 }'
106
+ }
107
+
108
+ existing_fact_uid() {
109
+ local ref="$1" body out
110
+ body=$(jq -nc --arg r "$ref" '{scope: "self", externalRef: $r, maxCharsPerItem: 1, maxTotalChars: 2000}')
111
+ if [ -n "${MEMORY_HUB_FIXTURE_DIR:-}" ]; then
112
+ mkdir -p "$MEMORY_HUB_FIXTURE_DIR/requests"
113
+ printf '%s' "$body" > "$MEMORY_HUB_FIXTURE_DIR/requests/capture-recall-$ref.json" 2>/dev/null
114
+ out=$(cat "$MEMORY_HUB_FIXTURE_DIR/capture-recall-$ref.json" 2>/dev/null)
115
+ else
116
+ out=$(curl -sS --connect-timeout 3 --max-time 7 \
117
+ -X POST "${FUNCTION_URL}/memory/recall" \
118
+ -H "Authorization: Bearer ${TOKEN}" \
119
+ -H "Content-Type: application/json" \
120
+ -d "$body" 2>/dev/null)
121
+ fi
122
+ printf '%s' "$out" | jq -r '[.facts[]? | select(.uid)]
123
+ | if length == 0 then empty
124
+ elif any(.[]; .lastModifiedDate) then max_by(.lastModifiedDate // "")
125
+ else .[0] end | .uid' 2>/dev/null
126
+ }
127
+
128
+ build_prompt() {
129
+ local now existing="" ref uid head tail
130
+ now=$(date -u +%Y-%m-%dT%H:%MZ)
131
+ for ref in $(top_ticket_refs); do
132
+ uid=$(existing_fact_uid "$ref")
133
+ [ -n "$uid" ] || continue
134
+ existing="${existing}- ${ref}: Fact ${uid} already exists — read it in full with memory_get, then memory_update it with the merged, corrected full text; do not save another.
135
+ "
136
+ done
137
+ read -r -d '' head <<'EOF' || true
138
+ Review this session for knowledge worth keeping: a decision, a root cause, a fix, or a gotcha that someone would need next time. Skip narration and exploration. If nothing qualifies, do nothing and finish without writing anything.
139
+
140
+ Rules for what you write:
141
+ - Only state what the transcript shows was verified: tested, observed, or confirmed by the user. Leave out guesses and unconfirmed hypotheses.
142
+ - Keep conclusions that were ruled out, written as "NOT <thing>", so nobody re-tries them.
143
+ - Give any status a timestamp: "Status as of <NOW>: ...". Prefer the latest state in the transcript over earlier ones.
144
+ - Name the files and commands involved.
145
+ - Only add tags that clearly apply; when unsure, add none.
146
+ - Pass the ticket ref as externalRef when the work is for a ticket.
147
+ - One memory per topic or ticket. If you already saved or updated one for it in this session, update that one instead of saving again.
148
+ EOF
149
+ read -r -d '' tail <<'EOF' || true
150
+ For anything not listed above: call memory_recall with a short query first; if one of your own memories already covers it, memory_update that memory with the merged, corrected full text. Otherwise memory_save (type "Fact" or "Scenario"). Never delete anything.
151
+ EOF
152
+ printf '%s\n%s%s' "${head//<NOW>/$now}" "$existing" "$tail"
153
+ }
154
+
155
+ run_capture() {
156
+ local prompt log_file="$STATE_DIR/logs/capture-$SESSION_ID.log" index_file="${TMPDIR:-/tmp}/memory-hub-stop-hook.log"
157
+ prompt=$(build_prompt)
158
+ echo "---- $(date -u +%FT%TZ) session=$SESSION_ID event=$EVENT ----" >> "$index_file" 2>/dev/null
159
+ echo "---- $(date -u +%FT%TZ) session=$SESSION_ID event=$EVENT ----" >> "$log_file" 2>/dev/null
160
+ nohup env MEMORY_HUB_STOP_HOOK_ACTIVE=1 MEMORY_HUB_CAPTURE=1 \
161
+ MEMORY_HUB_CAPTURE_LOG="$STATE_DIR/captures-$SESSION_ID.jsonl" \
162
+ "$CLAUDE_BIN" -p --resume "$SESSION_ID" \
163
+ --allowedTools "mcp__memory-hub__memory_recall,mcp__memory-hub__memory_get,mcp__memory-hub__memory_save,mcp__memory-hub__memory_update,mcp__plugin_memory-hub_memory-hub__memory_recall,mcp__plugin_memory-hub_memory-hub__memory_get,mcp__plugin_memory-hub_memory-hub__memory_save,mcp__plugin_memory-hub_memory-hub__memory_update" \
54
164
  --permission-prompts none \
55
- --model haiku \
165
+ --model "${MEMORY_HUB_CAPTURE_MODEL:-sonnet}" \
56
166
  --no-session-persistence \
57
- "$PROMPT" </dev/null
58
- } >>"$LOG_FILE" 2>&1 || true
167
+ --output-format stream-json --verbose \
168
+ "$prompt" </dev/null >> "$log_file" 2>&1 || true
169
+ }
170
+
171
+ # Claude Code does not wait for the hook once the session is over, and Stop must not hold up the next prompt.
172
+ (trap '' HUP; trap 'rmdir "$LOCK_DIR" 2>/dev/null' EXIT; run_capture) </dev/null >/dev/null 2>&1 &
173
+ disown 2>/dev/null || true
59
174
 
60
175
  exit 0
@@ -4,7 +4,9 @@
4
4
  # degrades to injecting nothing.
5
5
  set -u
6
6
 
7
- TOKEN="${MEMORY_HUB_MCP_TOKEN:-}"
7
+ [ -n "${MEMORY_HUB_STOP_HOOK_ACTIVE:-}" ] && exit 0
8
+
9
+ TOKEN="${MEMORY_HUB_MCP_TOKEN:-${CLAUDE_PLUGIN_OPTION_TOKEN:-}}"
8
10
  [ -n "$TOKEN" ] || exit 0
9
11
  command -v jq >/dev/null 2>&1 || exit 0
10
12
 
@@ -25,23 +27,223 @@ NL=$'\n'
25
27
  INPUT=$(cat)
26
28
  SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // empty' 2>/dev/null | tr -cd 'A-Za-z0-9_-')
27
29
  PROMPT=$(printf '%s' "$INPUT" | jq -r '.prompt // empty' 2>/dev/null)
30
+ INPUT_CWD=$(printf '%s' "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
28
31
  [ -n "$SESSION_ID" ] && [ -n "$PROMPT" ] || exit 0
29
32
 
30
- # A slash command or a one-line reply has nothing to match on, and must not use up the session's one shot.
31
- case "$PROMPT" in /*) exit 0 ;; esac
32
- [ "$(printf '%s' "$PROMPT" | wc -w)" -ge "${MEMORY_HUB_MIN_PROMPT_WORDS:-4}" ] || exit 0
33
-
34
33
  STATE_DIR="${MEMORY_HUB_STATE_DIR:-$HOME/.claude/memory-hub-hook/state}"
35
34
  mkdir -p "$STATE_DIR" 2>/dev/null || exit 0
36
35
  find "$STATE_DIR" -type f -mtime +7 -delete 2>/dev/null || true
36
+
37
+ # Lists captures the optional session-stop.sh hook saved in the background.
38
+ # Renders capture log lines as "<line number><TAB>notice"; the same in session-start.sh and user-prompt-submit.sh, change both together.
39
+ render_capture_notices() {
40
+ jq -R -r '
41
+ def clean: tostring | gsub("[[:cntrl:]]"; " ");
42
+ input_line_number as $n
43
+ | fromjson?
44
+ | select(type == "object" and (.uid | type) == "string" and (.action == "saved" or .action == "updated"))
45
+ | "\($n)\t- memory-hub auto-" + .action + " " + ((.type // "Fact") | clean) + " " + (.uid | clean)
46
+ + (if (.externalRef | type) == "string" and .externalRef != "" then " for " + (.externalRef | clean) else "" end)' 2>/dev/null
47
+ }
48
+
49
+ capture_unreported() {
50
+ local file="$1" marker="${1%.jsonl}.reported" total reported
51
+ total=$(wc -l < "$file" 2>/dev/null | tr -d ' ')
52
+ case "$total" in '' | *[!0-9]*) return 1 ;; esac
53
+ reported=$(cat "$marker" 2>/dev/null)
54
+ case "$reported" in '' | *[!0-9]*) reported=0 ;; esac
55
+ [ "$total" -ge "$reported" ] || reported=0
56
+ [ "$total" -gt "$reported" ] || return 1
57
+ CAPTURE_TOTAL=$total
58
+ CAPTURE_REPORTED=$reported
59
+ }
60
+
61
+ collect_capture_notices() {
62
+ local file="$1/captures-$2.jsonl" lines
63
+ [ -f "$file" ] || return 0
64
+ capture_unreported "$file" || return 0
65
+ lines=$(head -n "$CAPTURE_TOTAL" "$file" | tail -n +"$((CAPTURE_REPORTED + 1))" | render_capture_notices | cut -f2-)
66
+ printf '%s\n' "$CAPTURE_TOTAL" > "${file%.jsonl}.reported" 2>/dev/null
67
+ [ -n "$lines" ] || return 0
68
+ printf '## Memory saved automatically%s%s' "$NL" "$lines"
69
+ }
70
+
71
+ NOTICES=$(collect_capture_notices "$STATE_DIR" "$SESSION_ID" 2>/dev/null || true)
72
+ [ -z "$NOTICES" ] || NOTICES="${NOTICES}${NL}${NL}"
73
+
74
+ emit() {
75
+ jq -nc --arg c "$1" '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: $c}}'
76
+ }
77
+ finish_with_notices() {
78
+ [ -z "$NOTICES" ] || emit "$NOTICES"
79
+ exit 0
80
+ }
81
+
82
+ CLOSE_FENCE='if ([match("```"; "g")] | length) % 2 == 1 then . + "\n```" else . end'
83
+ INDENT='gsub("\n"; "\n ")'
84
+ STAMP='(if .lastModifiedDate then " (updated " + .lastModifiedDate[0:10] + ")" else "" end)'
85
+ ELIDE="if length >= $ITEM_CAP then . + \"…\" else . end"
86
+ cut_pointer() {
87
+ printf '(if .truncated then " [cut at \\(.%s | length) of \\(.fullLength) — memory_get type=%s uid=\\(.uid)]" else "" end)' "${2:-content}" "$1"
88
+ }
89
+
90
+ EXTRAS_DEF='def extras($under; $text):
91
+ (if (.externalRef | type) == "string" and .externalRef != "" and .externalRef != $under then " · " + (.externalRef | gsub("[[:cntrl:]]"; " ")) else "" end)
92
+ + ((first(($text // "") | gsub("[A-Za-z][A-Za-z0-9+.-]*://[^\\s)]*"; " ") | scan("[A-Za-z0-9_./-]+\\.(?:tsx|ts|jsx|js|mjs|sh|py|json|md|yml|yaml|cls|java|kt|swift|go|rb)\\b") | select(startswith("http") | not)) // null) | if . then " · cites " + . else "" end);'
93
+
94
+ TICKET_DENYLIST=" UTF ISO SHA RFC HTTP HTTPS TLS SSL MD AES RSA X Y Z UTC GMT CVE COVID PR "
95
+ REFS_FILE="$STATE_DIR/$SESSION_ID.refs"
96
+
97
+ ticket_refs() {
98
+ printf '%s\n' "$PROMPT" | jq -Rr '
99
+ (scan("(?:linear\\.app/[^/\\s]+/issue|/browse)/([A-Z][A-Z0-9]{1,9}-[0-9]{1,6})\\b") | "\(.[0])\turl"),
100
+ (scan("\\b[A-Z][A-Z0-9]{1,9}-[0-9]{1,6}\\b") | "\(.)\tbare")' 2>/dev/null |
101
+ awk -F'\t' -v deny="$TICKET_DENYLIST" '
102
+ { split($1, p, "-"); if (index(deny, " " p[1] " ")) next
103
+ if (!($1 in kind)) order[++n] = $1
104
+ if (kind[$1] != "url") kind[$1] = $2 }
105
+ END { for (i = 1; i <= n; i++) print order[i] "\t" kind[order[i]] }'
106
+ }
107
+
108
+ ticket_call() {
109
+ local path="$1" kind="$2" ref="$3" out="$TMP_DIR/ticket-$2-$3.json" body
110
+ body=$(jq -nc --arg r "$ref" --argjson cap "$((BUDGET / 2))" '{scope: "team", externalRef: $r, maxCharsPerItem: 500, maxTotalChars: $cap}')
111
+ if [ -n "${MEMORY_HUB_FIXTURE_DIR:-}" ]; then
112
+ mkdir -p "$MEMORY_HUB_FIXTURE_DIR/requests"
113
+ printf '%s' "$body" > "$MEMORY_HUB_FIXTURE_DIR/requests/ticket-$kind-$ref.json" 2>/dev/null
114
+ cp "$MEMORY_HUB_FIXTURE_DIR/ticket-$kind-$ref.json" "$out" 2>/dev/null || true
115
+ return 0
116
+ fi
117
+ curl -sS --connect-timeout 3 --max-time 7 \
118
+ -X POST "${FUNCTION_URL}${path}" \
119
+ -H "Authorization: Bearer ${TOKEN}" \
120
+ -H "Content-Type: application/json" \
121
+ -d "$body" \
122
+ -o "$out" 2>/dev/null || true
123
+ }
124
+
125
+ ticket_items() {
126
+ local ref="$1"
127
+ jq -j --arg under "$ref" "$EXTRAS_DEF [.facts[]?][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP + extras(\$under; .content)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/ticket-facts-$ref.json" 2>/dev/null
128
+ jq -j --arg under "$ref" "$EXTRAS_DEF [.scenarios[]?][] | ((\"- \" + (.summary | $ELIDE) + $(cut_pointer Scenario summary) + $STAMP + extras(\$under; .summary)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/ticket-scenarios-$ref.json" 2>/dev/null
129
+ }
130
+
131
+ ticket_valid() {
132
+ jq -e --arg k "$2" 'type == "object" and (.[$k] | type) == "array"' "$1" >/dev/null 2>&1
133
+ }
134
+
135
+ TICKET_OUT=""
136
+ NEW_REFS=()
137
+ while IFS=$'\t' read -r ref kind; do
138
+ [ -n "$ref" ] || continue
139
+ grep -qxF "$ref" "$REFS_FILE" 2>/dev/null && continue
140
+ [ "${#NEW_REFS[@]}" -lt 3 ] && NEW_REFS+=("$ref:$kind")
141
+ done < <(ticket_refs)
142
+
143
+ if [ "${#NEW_REFS[@]}" -gt 0 ] && TMP_DIR=$(mktemp -d 2>/dev/null); then
144
+ trap 'rm -rf "$TMP_DIR"' EXIT
145
+ for entry in "${NEW_REFS[@]}"; do
146
+ ticket_call /memory/recall facts "${entry%%:*}" &
147
+ ticket_call /memory/recall-scenarios scenarios "${entry%%:*}" &
148
+ done
149
+ wait
150
+ ticket_room=$((BUDGET - ${#NOTICES}))
151
+ for entry in "${NEW_REFS[@]}"; do
152
+ ref="${entry%%:*}"
153
+ facts_ok=0
154
+ scenarios_ok=0
155
+ ticket_valid "$TMP_DIR/ticket-facts-$ref.json" facts && facts_ok=1
156
+ ticket_valid "$TMP_DIR/ticket-scenarios-$ref.json" scenarios && scenarios_ok=1
157
+ [ $((facts_ok + scenarios_ok)) -gt 0 ] || continue
158
+ ticket_items_list=()
159
+ while IFS= read -r -d $'\x1e' item; do
160
+ [ -n "$item" ] || continue
161
+ ticket_items_list+=("$item")
162
+ done < <(ticket_items "$ref")
163
+ found=${#ticket_items_list[@]}
164
+ if [ "$found" -gt 0 ]; then
165
+ section="## Memory for ticket $ref${NL}Ticket $ref detected — memory_recall type=Fact externalRef=$ref returns these. Update the matching one with memory_update rather than saving a copy.${NL}"
166
+ elif [ "$facts_ok$scenarios_ok" != 11 ]; then
167
+ continue
168
+ elif [ "${entry#*:}" = url ]; then
169
+ section="## Memory for ticket $ref${NL}Ticket $ref detected — no memory yet. When the work is done, memory_save with externalRef=$ref.${NL}"
170
+ else
171
+ printf '%s\n' "$ref" >> "$REFS_FILE" 2>/dev/null
172
+ continue
173
+ fi
174
+ [ $((${#section} + 1)) -le "$ticket_room" ] || continue
175
+ if [ "$found" -gt 0 ]; then
176
+ avail=$((ticket_room - ${#section} - 1))
177
+ total=0
178
+ for item in "${ticket_items_list[@]}"; do total=$((total + ${#item} + 1)); done
179
+ more_line="_${found} more for $ref: memory_recall type=Fact externalRef=${ref}_"
180
+ [ "$total" -le "$avail" ] || avail=$((avail - ${#more_line} - 1))
181
+ shown=0
182
+ used=0
183
+ for item in "${ticket_items_list[@]}"; do
184
+ if [ $((used + ${#item} + 1)) -le "$avail" ]; then
185
+ section="${section}${item}${NL}"
186
+ used=$((used + ${#item} + 1))
187
+ shown=$((shown + 1))
188
+ fi
189
+ done
190
+ if [ "$shown" -lt "$found" ]; then
191
+ more_line="_$((found - shown)) more for $ref: memory_recall type=Fact externalRef=${ref}_"
192
+ [ $((${#section} + ${#more_line} + 2)) -le "$ticket_room" ] || continue
193
+ section="${section}${more_line}${NL}"
194
+ fi
195
+ fi
196
+ printf '%s\n' "$ref" >> "$REFS_FILE" 2>/dev/null
197
+ TICKET_OUT="${TICKET_OUT}${section}${NL}"
198
+ ticket_room=$((ticket_room - ${#section} - 1))
199
+ done
200
+ fi
201
+ NOTICES="${NOTICES}${TICKET_OUT}"
202
+ [ -z "$TICKET_OUT" ] || finish_with_notices
203
+
204
+ # A slash command or a one-line reply has nothing to match on, and must not use up the session's one shot.
205
+ case "$PROMPT" in /*) finish_with_notices ;; esac
206
+ [ "$(printf '%s' "$PROMPT" | wc -w)" -ge "${MEMORY_HUB_MIN_PROMPT_WORDS:-4}" ] || finish_with_notices
207
+
37
208
  MARKER="$STATE_DIR/$SESSION_ID"
38
- [ -e "$MARKER" ] && exit 0
209
+ [ -e "$MARKER" ] && finish_with_notices
39
210
  # Marked before any work, so a slow or failing function costs one prompt, not every prompt.
40
- : > "$MARKER" 2>/dev/null || exit 0
211
+ : > "$MARKER" 2>/dev/null || finish_with_notices
41
212
 
213
+ [ -z "${TMP_DIR:-}" ] || rm -rf "$TMP_DIR"
42
214
  TMP_DIR=$(mktemp -d)
43
215
  trap 'rm -rf "$TMP_DIR"' EXIT
44
216
 
217
+ # Same as session-start.sh; change both together.
218
+ canonicalize_remote_url() {
219
+ local url="${1:-}"
220
+ url=$(printf '%s' "$url" | sed -e 's/[[:space:]]*$//')
221
+ url="${url%.git}"
222
+ # bash =~ has no non-capturing groups, so the URL form's name is BASH_REMATCH[3].
223
+ if [[ "$url" =~ ^git@[^:]+:(.+)$ ]]; then
224
+ printf '%s' "${BASH_REMATCH[1]}"
225
+ elif [[ "$url" =~ ^(https?|ssh)://([^@]+@)?[^/]+/(.+)$ ]]; then
226
+ printf '%s' "${BASH_REMATCH[3]}"
227
+ fi
228
+ }
229
+
230
+ # Same as session-start.sh; change both together.
231
+ detect_repo_name() {
232
+ local url first
233
+ url=$(git remote get-url origin 2>/dev/null) || url=""
234
+ if [ -z "$url" ]; then
235
+ first=$(git remote 2>/dev/null | head -n 1) || first=""
236
+ if [ -n "$first" ]; then
237
+ url=$(git remote get-url "$first" 2>/dev/null) || url=""
238
+ fi
239
+ fi
240
+ [ -n "$url" ] || return 0
241
+ canonicalize_remote_url "$url"
242
+ }
243
+
244
+ REPO=$({ [ -n "$INPUT_CWD" ] && [ -d "$INPUT_CWD" ] && cd "$INPUT_CWD"; } 2>/dev/null; detect_repo_name 2>/dev/null) || REPO=""
245
+ OTHER_REPO_MIN=$(jq -n --argjson m "$MIN_SIMILARITY" '$m + 0.1' 2>/dev/null) || OTHER_REPO_MIN=1
246
+
45
247
  HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
46
248
  EMBED=()
47
249
  if [ -n "${MEMORY_HUB_EMBED_CMD:-}" ]; then
@@ -94,23 +296,16 @@ call "/memory/recall-wiki" "$TMP_DIR/wiki.json" &
94
296
  call "/memory/recall-scenarios" "$TMP_DIR/scenarios.json" &
95
297
  wait
96
298
 
97
- CLOSE_FENCE='if ([match("```"; "g")] | length) % 2 == 1 then . + "\n```" else . end'
98
- INDENT='gsub("\n"; "\n ")'
99
- STAMP='(if .lastModifiedDate then " (updated " + .lastModifiedDate[0:10] + ")" else "" end)'
100
- ELIDE="if length >= $ITEM_CAP then . + \"…\" else . end"
101
- cut_pointer() {
102
- printf '(if .truncated then " [cut at \\(.%s | length) of \\(.fullLength) — memory_get type=%s uid=\\(.uid)]" else "" end)' "${2:-content}" "$1"
103
- }
104
-
105
299
  # Judged across every list: one list alone may have no strong match, and would keep its weak ones.
106
300
  BEST=""
107
301
  for kind in facts skills wiki scenarios; do
108
- top=$(jq -r '[(.facts // [])[], (.skills // [])[], (.pages // [])[], (.scenarios // [])[]] | map(.similarity // empty) | max // empty' "$TMP_DIR/$kind.json" 2>/dev/null)
302
+ top=$(jq -r '[(.facts // [])[], (.skills // [])[], (.pages // [])[], (.scenarios // [])[]] | map(select(.similarity != null) | .similarity + (.boost // 0)) | max // empty' "$TMP_DIR/$kind.json" 2>/dev/null)
109
303
  if [ -n "$top" ] && { [ -z "$BEST" ] || [ "$(jq -n --argjson a "$top" --argjson b "$BEST" '$a > $b' 2>/dev/null)" = true ]; }; then BEST="$top"; fi
110
304
  done
111
305
  FLOOR=-1
112
306
  [ -n "$BEST" ] && FLOOR=$(jq -n --argjson best "$BEST" --argjson band "$SIMILARITY_BAND" '$best - $band')
113
- KEEP='select(.similarity == null or .similarity >= $floor)'
307
+ KEEP='select(.similarity == null or ((.similarity + (.boost // 0)) >= $floor and ((.repoName // "" | ascii_downcase) == ($repo | ascii_downcase) or $repo == "" or (.similarity + (.boost // 0)) >= $other)))'
308
+ KEEP_ARGS=(--argjson floor "$FLOOR" --arg repo "$REPO" --argjson other "$OTHER_REPO_MIN")
114
309
 
115
310
  HEADING="## Memory relevant to this prompt"
116
311
  FOOTER="_Matched to your prompt, not newest-first. memory_recall with a query finds more; memory_get fetches a cut item._"
@@ -125,12 +320,11 @@ while IFS= read -r -d $'\x1e' item; do
125
320
  used=$((used + ${#item} + 1))
126
321
  fi
127
322
  done < <(
128
- jq -j --argjson floor "$FLOOR" "[.facts[]? | $KEEP][:$FACTS_N][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/facts.json" 2>/dev/null
129
- jq -j --argjson floor "$FLOOR" "[.skills[]? | $KEEP][:$SKILLS_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/skills.json" 2>/dev/null
130
- jq -j --argjson floor "$FLOOR" "[.pages[]? | $KEEP][:$WIKI_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/wiki.json" 2>/dev/null
131
- jq -j --argjson floor "$FLOOR" "[.scenarios[]? | $KEEP][:$SCENARIOS_N][] | ((\"- \" + (.summary | $ELIDE) + $(cut_pointer Scenario summary) + $STAMP) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/scenarios.json" 2>/dev/null
323
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF [.facts[]? | $KEEP][:$FACTS_N][] | ((\"- \" + (.content | $ELIDE) + $(cut_pointer Fact) + $STAMP + extras(\"\"; .content)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/facts.json" 2>/dev/null
324
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF [.skills[]? | $KEEP][:$SKILLS_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Skill) + $STAMP + extras(\"\"; .content)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/skills.json" 2>/dev/null
325
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF [.pages[]? | $KEEP][:$WIKI_N][] | ((\"- \" + .title + \": \" + (.content | $ELIDE) + $(cut_pointer Wiki) + $STAMP + extras(\"\"; .content)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/wiki.json" 2>/dev/null
326
+ jq -j "${KEEP_ARGS[@]}" "$EXTRAS_DEF [.scenarios[]? | $KEEP][:$SCENARIOS_N][] | ((\"- \" + (.summary | $ELIDE) + $(cut_pointer Scenario summary) + $STAMP + extras(\"\"; .summary)) | $CLOSE_FENCE | $INDENT), \"\\u001e\"" "$TMP_DIR/scenarios.json" 2>/dev/null
132
327
  )
133
- [ -n "$BODY" ] || exit 0
328
+ [ -n "$BODY" ] || finish_with_notices
134
329
 
135
- CONTEXT="${HEADING}${NL}${BODY}${NL}${FOOTER}${NL}"
136
- jq -nc --arg c "$CONTEXT" '{hookSpecificOutput: {hookEventName: "UserPromptSubmit", additionalContext: $c}}'
330
+ emit "${NOTICES}${HEADING}${NL}${BODY}${NL}${FOOTER}${NL}"
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logCapture = exports.captureUpsert = exports.isCaptureMode = void 0;
4
+ const fs_1 = require("fs");
5
+ const SIMILAR_OWN_FACT_FLOOR = 0.86;
6
+ function isCaptureMode(env = process.env) {
7
+ return env.MEMORY_HUB_CAPTURE === '1';
8
+ }
9
+ exports.isCaptureMode = isCaptureMode;
10
+ async function findOwnFactUid(deps, content, externalRef) {
11
+ if (externalRef) {
12
+ const { facts } = await deps.client.recall({ scope: 'self', externalRef, maxCharsPerItem: 1, maxTotalChars: 10000 });
13
+ // Same pick as the session-stop hook's jq max_by: newest by lastModifiedDate, the later one on a tie, else the first returned.
14
+ const newest = facts.reduce((best, fact) => (fact.lastModifiedDate && (!best || fact.lastModifiedDate >= best.lastModifiedDate) ? fact : best), undefined);
15
+ return (newest ?? facts[0])?.uid;
16
+ }
17
+ const queryEmbedding = await deps.embed(content);
18
+ const { facts } = await deps.client.recall({
19
+ scope: 'self',
20
+ queryEmbedding,
21
+ minSimilarity: SIMILAR_OWN_FACT_FLOOR,
22
+ maxTotalChars: 2000,
23
+ });
24
+ // Checked here too, so a function that ignores minSimilarity can't turn a weak match into a refusal.
25
+ const similar = facts.filter((fact) => (fact.similarity ?? 0) >= SIMILAR_OWN_FACT_FLOOR);
26
+ return similar.sort((a, b) => (b.similarity ?? 0) - (a.similarity ?? 0))[0]?.uid;
27
+ }
28
+ async function captureUpsert(deps, input, env = process.env) {
29
+ if (!isCaptureMode(env) || input.type !== 'Fact' || !input.content) {
30
+ return undefined;
31
+ }
32
+ const uid = await findOwnFactUid(deps, input.content, input.externalRef).catch(() => undefined);
33
+ if (!uid) {
34
+ return undefined;
35
+ }
36
+ const existing = await deps.client.getFact({ uid }).catch(() => undefined);
37
+ if (!existing || typeof existing.content !== 'string') {
38
+ return undefined;
39
+ }
40
+ return {
41
+ message: `Not saved: Fact ${uid} already covers ${input.externalRef || 'this'}. ` +
42
+ `Merge what is new into the text below and call memory_update type=Fact uid=${uid} with the complete merged text. ` +
43
+ `Keep everything below that is still true.\n\n${existing.content}`,
44
+ };
45
+ }
46
+ exports.captureUpsert = captureUpsert;
47
+ function logCapture(entry, env = process.env, append = fs_1.appendFileSync, now = () => new Date()) {
48
+ const path = env.MEMORY_HUB_CAPTURE_LOG;
49
+ if (!isCaptureMode(env) || !path) {
50
+ return;
51
+ }
52
+ const { externalRef, ...rest } = entry;
53
+ const line = JSON.stringify({ time: now().toISOString(), ...rest, ...(externalRef ? { externalRef } : {}) });
54
+ try {
55
+ append(path, `${line}\n`);
56
+ }
57
+ catch { }
58
+ }
59
+ exports.logCapture = logCapture;
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ const task_context_1 = require("./task-context");
12
12
  const git_remote_1 = require("./git-remote");
13
13
  const embeddings_1 = require("./embeddings");
14
14
  const save_1 = require("./save");
15
+ const capture_1 = require("./capture");
15
16
  const recall_1 = require("./recall");
16
17
  const guide_check_1 = require("./guide-check");
17
18
  const revise_1 = require("./revise");
@@ -61,8 +62,9 @@ const client = new client_1.MemoryHubClient({ baseUrl, apiToken });
61
62
  const INSTRUCTIONS = [
62
63
  'Call memory_sessionContext once at the start of a conversation to load this',
63
64
  "developer's persona, facts, skills and wiki pages before answering from scratch.",
64
- 'Before wrapping up a task, save anything durable with memory_save — on hosts',
65
- 'without a session-end hook (e.g. Claude Desktop) nothing else will capture it.',
65
+ 'Before wrapping up a task, save anything durable with memory_save — nothing is',
66
+ 'saved automatically unless the optional capture hook is registered, and on hosts',
67
+ 'without hooks (e.g. Claude Desktop) nothing can capture it.',
66
68
  ].join(' ');
67
69
  const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: '0.1.0' }, { instructions: INSTRUCTIONS });
68
70
  // Detected from this process's own working directory, not from anything the model
@@ -138,12 +140,17 @@ server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the SE
138
140
  externalRef: zod_1.z.string().optional().describe("Fact, Scenario, Wiki only — the Linear/Jira ticket this relates to, e.g. 'SOL-1234' — pass it when the user mentions a ticket."),
139
141
  repo: zod_1.z.string().min(1).optional().describe('An explicit DevRepos uid from memory_listRepos, overriding the current-directory auto-detected repo.'),
140
142
  }, async (input) => {
143
+ const refused = await (0, capture_1.captureUpsert)({ client, embed: embeddings_1.embed }, input);
144
+ if (refused) {
145
+ return { content: [{ type: 'text', text: refused.message }] };
146
+ }
141
147
  const result = await (0, save_1.performSave)({
142
148
  client,
143
149
  embed: embeddings_1.embed,
144
150
  currentRepoUid: () => repoContext.currentRepoUid(),
145
151
  resolveTaskUid: (ref, repoUid) => taskContext.resolveTaskUid(ref, repoUid),
146
152
  }, input);
153
+ (0, capture_1.logCapture)({ action: 'saved', type: input.type, uid: result.uid, externalRef: input.externalRef });
147
154
  return {
148
155
  content: [
149
156
  ...(await joinNoticeBlocks()),
@@ -188,7 +195,7 @@ server.tool('memory_moveResourceRepo', "Reassign an already-saved Fact/Scenario/
188
195
  const result = await client.moveResourceRepo(input);
189
196
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
190
197
  });
191
- server.tool('memory_checkRepoStatus', "Check whether the current repo is linked to a memory team yet. See memory_getSkillGuide for what to do if it isn't.", {}, async () => {
198
+ server.tool('memory_checkRepoStatus', "Check whether the current repo is linked to a memory team yet, reporting the linked team and whether you are a member. See memory_getSkillGuide for what to do if it isn't.", {}, async () => {
192
199
  const status = await repoContext.checkRepoStatus();
193
200
  return { content: [...(await joinNoticeBlocks()), { type: 'text', text: JSON.stringify(status) }] };
194
201
  });
@@ -206,6 +213,7 @@ server.tool('memory_update', "Revise a memory you saved, in place, instead of sa
206
213
  repo: zod_1.z.string().min(1).nullable().optional().describe('A DevRepos uid, or null to clear it.'),
207
214
  }, async (input) => {
208
215
  const result = await (0, revise_1.performUpdate)({ client, embed: embeddings_1.embed }, input);
216
+ (0, capture_1.logCapture)({ action: 'updated', type: input.type, uid: result.uid });
209
217
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
210
218
  });
211
219
  server.tool('memory_delete', "Permanently delete one memory you saved. Use it to remove a copy you have just merged into another, or a memory that is wrong or obsolete. It cannot be undone and only the author can delete. Prefer memory_update when the memory is still partly right.", {
@@ -60,7 +60,9 @@ function createRepoContext(client, detectName = git_remote_1.detectRepoName, det
60
60
  name,
61
61
  };
62
62
  }
63
- return { uid: result.uid, name: result.name, justJoinedTeamName: result.justJoinedTeamName };
63
+ // resolveRepo auto-joins the repo's team, so a linked repo always means membership.
64
+ const team = result.devTeamId ? { teamId: result.devTeamId, teamName: result.teamName, member: true } : {};
65
+ return { uid: result.uid, name: result.name, justJoinedTeamName: result.justJoinedTeamName, ...team };
64
66
  }
65
67
  catch {
66
68
  return NO_REPO;
package/dist/revise.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.performSetTaskStatus = exports.performDelete = exports.performUpdate = void 0;
4
+ const save_1 = require("./save");
4
5
  // Which fields each type accepts. Anything else is refused, not dropped, so a typo cannot look like a successful edit.
5
6
  const ALLOWED = {
6
7
  Fact: ['content', 'tags', 'repo'],
@@ -39,6 +40,7 @@ async function performUpdate(deps, input) {
39
40
  if (refused.length > 0) {
40
41
  throw new Error(`A ${input.type} has no ${refused.join(', ')}. It accepts: ${ALLOWED[input.type].join(', ')}.`);
41
42
  }
43
+ const repo = typeof input.repo === 'string' ? await (0, save_1.validateRepoArg)(client, input.repo) : input.repo;
42
44
  const textChanged = input.content !== undefined || input.title !== undefined || input.summary !== undefined;
43
45
  let embedding;
44
46
  if (textChanged) {
@@ -51,8 +53,8 @@ async function performUpdate(deps, input) {
51
53
  // No embedding is better than a stale one: the function clears the old vector when the text changes.
52
54
  embedding = await embed(embeddedText(input.type, merged)).catch(() => undefined);
53
55
  }
54
- const { type, uid, ...changes } = input;
55
- const body = { uid, ...changes, ...(embedding ? { embedding } : {}) };
56
+ const { type, uid, repo: _repo, ...changes } = input;
57
+ const body = { uid, ...changes, ...(repo !== undefined ? { repo } : {}), ...(embedding ? { embedding } : {}) };
56
58
  switch (type) {
57
59
  case 'Fact':
58
60
  return client.updateFact(body);
package/dist/save.js CHANGED
@@ -1,6 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.performSave = void 0;
3
+ exports.performSave = exports.validateRepoArg = void 0;
4
+ const UID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
+ const OWNER_NAME_PATTERN = /^[^/\s]+\/[^/\s]+$/;
6
+ async function validateRepoArg(client, repo) {
7
+ if (UID_PATTERN.test(repo)) {
8
+ return repo;
9
+ }
10
+ if (OWNER_NAME_PATTERN.test(repo)) {
11
+ const resolved = await client.resolveRepo({ name: repo });
12
+ if (resolved.uid) {
13
+ return resolved.uid;
14
+ }
15
+ throw new Error(`repo must be a uid from memory_listRepos; "${repo}" is not a linked repo`);
16
+ }
17
+ throw new Error(`repo must be a uid from memory_listRepos, got "${repo}"`);
18
+ }
19
+ exports.validateRepoArg = validateRepoArg;
4
20
  // Extracted from four near-identical memory_saveX tool handlers so the per-type
5
21
  // dispatch logic — which fields are required, what gets embedded, which client
6
22
  // method is called — is unit-testable. index.ts's module-scope side effects
@@ -8,6 +24,7 @@ exports.performSave = void 0;
8
24
  // itself untestable, the same reason list-repos.ts was extracted earlier.
9
25
  async function performSave(deps, input) {
10
26
  const { client, embed, currentRepoUid, resolveTaskUid } = deps;
27
+ const explicitRepo = () => (input.repo === undefined ? undefined : validateRepoArg(client, input.repo));
11
28
  // Required-field checks run BEFORE any repo resolution/network call — the old
12
29
  // per-type tools got this for free from Zod (`content: z.string()`, not
13
30
  // `.optional()`), which the consolidated schema can't do since requiredness is
@@ -18,7 +35,7 @@ async function performSave(deps, input) {
18
35
  if (!input.content) {
19
36
  throw new Error("content is required when type is 'Fact'");
20
37
  }
21
- const repo = input.repo ?? (await currentRepoUid());
38
+ const repo = (await explicitRepo()) ?? (await currentRepoUid());
22
39
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
23
40
  const embedding = await embed(input.content).catch(() => undefined);
24
41
  return client.saveFact({ content: input.content, tags: input.tags, devTaskId, repo, embedding });
@@ -27,7 +44,7 @@ async function performSave(deps, input) {
27
44
  if (!input.title || !input.content) {
28
45
  throw new Error("title and content are required when type is 'Skill'");
29
46
  }
30
- const repo = input.repo ?? (await currentRepoUid());
47
+ const repo = (await explicitRepo()) ?? (await currentRepoUid());
31
48
  const embedding = await embed(`${input.title}\n\n${input.content}`).catch(() => undefined);
32
49
  return client.saveSkill({ title: input.title, content: input.content, tags: input.tags, repo, embedding });
33
50
  }
@@ -35,7 +52,7 @@ async function performSave(deps, input) {
35
52
  if (!input.summary) {
36
53
  throw new Error("summary is required when type is 'Scenario'");
37
54
  }
38
- const repo = input.repo ?? (await currentRepoUid());
55
+ const repo = (await explicitRepo()) ?? (await currentRepoUid());
39
56
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
40
57
  const embedding = await embed(input.summary).catch(() => undefined);
41
58
  return client.saveScenario({ summary: input.summary, factIds: input.factIds, devTaskId, repo, embedding });
@@ -44,7 +61,7 @@ async function performSave(deps, input) {
44
61
  if (!input.title || !input.content) {
45
62
  throw new Error("title and content are required when type is 'Wiki'");
46
63
  }
47
- const repo = input.repo ?? (await currentRepoUid());
64
+ const repo = (await explicitRepo()) ?? (await currentRepoUid());
48
65
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
49
66
  const embedding = await embed(`${input.title}\n\n${input.content}`).catch(() => undefined);
50
67
  return client.saveWikiPage({
package/dist/setup.js CHANGED
@@ -21,8 +21,8 @@ function launchPath(execPath, currentPath = process.env.PATH || '', sep = path_1
21
21
  exports.launchPath = launchPath;
22
22
  exports.MARKETPLACE_NAME = 'se-ai-memory-hub';
23
23
  exports.MARKETPLACE_REPO = 'Skedulo/se-ai-memory-hub';
24
- // npm releases ship from dev, and plugin.json's pinned version gates the update, so hooks move with the server.
25
- exports.MARKETPLACE_REF = 'dev';
24
+ // main only moves when a release is merged into it, so installs and updates both get released hooks.
25
+ exports.MARKETPLACE_REF = 'main';
26
26
  exports.PLUGIN_ID = `memory-hub@${exports.MARKETPLACE_NAME}`;
27
27
  function pluginInstalled(path = (0, path_1.join)((0, os_1.homedir)(), '.claude', 'plugins', 'installed_plugins.json')) {
28
28
  return Object.prototype.hasOwnProperty.call(readJson(path).plugins || {}, exports.PLUGIN_ID);
@@ -478,7 +478,7 @@ async function runSetup(argv = []) {
478
478
  console.log(` MCP server -> ${shown}`);
479
479
  console.log(` config -> ${path}`);
480
480
  console.log(' no hook: Desktop has no hook system, so startup injection and');
481
- console.log(' end-of-session auto-save are Claude Code only.');
481
+ console.log(' background capture are Claude Code only; nothing is saved automatically.');
482
482
  }
483
483
  console.log();
484
484
  console.log('==> Verifying');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "MCP server for the SE AI Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
package/skill-guide.md CHANGED
@@ -5,7 +5,8 @@ _Served live by memory_getSkillGuide — this is the single source of truth, edi
5
5
  If the session-start hook (see `memory-hub-hook/`) is registered, it already
6
6
  injected your own and your team's recent facts and skills as context. This
7
7
  skill covers what to do *during* the session, beyond that automatic
8
- injection.
8
+ injection. Recall never saves anything; see "Automatic capture (when enabled)"
9
+ for the one optional hook that does.
9
10
 
10
11
  ## Recall on demand
11
12
 
@@ -147,6 +148,41 @@ stopping point, save what's already distilled now — compaction summarizes
147
148
  lossily, and a fact that only exists in your reasoning does not survive
148
149
  it. A save that happens is worth more than a better-timed one that doesn't.
149
150
 
151
+ ## Automatic capture (when enabled)
152
+
153
+ Nothing saves on its own unless the user has switched on the optional capture
154
+ hook. It is `memory-hub-hook/session-stop.sh`, registered by hand in
155
+ `~/.claude/settings.json` as a `Stop` and/or `SessionEnd` hook; the plugin and
156
+ `setup` do not install it. The session-start Reminder says "Auto-capture is on"
157
+ when it is registered. Without it, a memory exists only if you called
158
+ `memory_save`.
159
+
160
+ When it runs, it resumes the session headlessly and asks the model to keep
161
+ anything durable:
162
+
163
+ - **`Stop`**: at most every 30 minutes (`MEMORY_HUB_CAPTURE_INTERVAL_MIN`) and
164
+ only with 40 or more new transcript lines (`MEMORY_HUB_CAPTURE_MIN_NEW_LINES`).
165
+ - **`SessionEnd`**: once, in the background, when the session ends.
166
+
167
+ It updates the existing Fact for a ticket instead of adding copies, so a
168
+ ticket's Fact is revised as the work moves on. Saving yourself is still the
169
+ right move for anything you know matters now. The capture model is
170
+ `MEMORY_HUB_CAPTURE_MODEL`, default `sonnet`.
171
+
172
+ Each save or update surfaces as a "memory-hub auto-saved" or "memory-hub
173
+ auto-updated" notice under `## Memory saved automatically`, on the next prompt
174
+ or at the next session start. Tell the user about these notices when you see
175
+ them; do not claim a memory was saved if no notice or `memory_save` result says
176
+ so.
177
+
178
+ Logs: the full run is in `~/.claude/memory-hub-hook/state/logs/capture-<session>.log`,
179
+ the list of saves in `~/.claude/memory-hub-hook/state/captures-<session>.jsonl`,
180
+ and a one-line entry per run in `$TMPDIR/memory-hub-stop-hook.log`
181
+ (`/tmp/memory-hub-stop-hook.log` when `TMPDIR` is unset).
182
+
183
+ To turn it off, remove the `session-stop.sh` entry from the `Stop` and
184
+ `SessionEnd` hooks in `~/.claude/settings.json`.
185
+
150
186
  ## Revise, don't re-save
151
187
 
152
188
  A memory is not frozen. When you learn something that corrects, completes or