@memnexus-ai/mx-agent-cli 0.1.263 → 0.1.265

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.
@@ -14,6 +14,85 @@
14
14
  # mechanism used by auto-capture-session-end.sh), reads the iteration log via
15
15
  # the mx CLI, and compares timestamps.
16
16
 
17
+ MXHT_HOOK=iteration-log-check MXHT_EVENT=Stop MXHT_TOOL=-
18
+ # >>> SHARED hook-timing probe v1
19
+ # Diagnostic instrumentation: records how long THIS hook ran, so hook time can be
20
+ # separated from time spent waiting on the API when a session stalls mid-stream.
21
+ # Appends one line to a local, gitignored log. Read it with
22
+ # mx-agent-system/scripts/hook-timing-report.sh. Nothing is transmitted anywhere.
23
+ #
24
+ # FAIL SILENT IS DELIBERATE HERE, and it is the opposite of this repo's usual
25
+ # fail-loud direction. Do not "correct" it to fail-loud by applying the fleet
26
+ # default. A diagnostic that can break the gate it observes is worse than no
27
+ # diagnostic: an unwritable path or a full disk would otherwise take out every
28
+ # guard on the PreToolUse path at once. Every step below is guarded and every
29
+ # failure path is a silent no-op that leaves the hook's behaviour untouched.
30
+ #
31
+ # NEAR-ZERO OVERHEAD: bash builtins only on the hot path ($EPOCHREALTIME, printf
32
+ # -T, one read, one append). No subprocess, no network, no JSON parsing, and the
33
+ # hook's stdin is never touched (the hook owns it). mkdir runs at most once per
34
+ # worktree. Kill switch: MX_HOOK_TIMING=0.
35
+ MXHT_T0="${EPOCHREALTIME:-}"
36
+ _mxht_emit() {
37
+ [ -z "${MXHT_DONE:-}" ] || return 0 # an ERR trap that exits fires EXIT too
38
+ MXHT_DONE=1
39
+ [ "${MX_HOOK_TIMING:-1}" != "0" ] || return 0
40
+ [ -n "${MXHT_T0:-}" ] && [ -n "${EPOCHREALTIME:-}" ] || return 0
41
+ local root="${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-}}"
42
+ [ -n "$root" ] && [ -d "$root" ] || return 0
43
+ local dir="$root/.mx-hook-timing"
44
+ [ -d "$dir" ] || mkdir -p "$dir" 2>/dev/null || return 0
45
+ # EPOCHREALTIME is seconds.microseconds; the separator is locale-dependent, so
46
+ # strip both forms and subtract as plain integer microseconds.
47
+ local dur=-1
48
+ { dur=$(( ${EPOCHREALTIME//[.,]/} - ${MXHT_T0//[.,]/} )); } 2>/dev/null
49
+ [ "$dur" -ge 0 ] 2>/dev/null || return 0
50
+ local stamp hour
51
+ printf -v stamp '%(%Y-%m-%d %H:%M:%S)T' -1
52
+ printf -v hour '%(%H)T' -1
53
+ # BOUNDED BY CONSTRUCTION: a 24-slot ring, one file per hour-of-day, so the log
54
+ # is at most 24 files each holding one hour of this machine's hook calls. The
55
+ # first writer into a slot on a new day truncates it instead of appending —
56
+ # detected by reading the slot's first line, which is a builtin read (no stat,
57
+ # no rm, no find, no cron). Two writers can race that truncation and lose a
58
+ # line or two at an hour boundary; that is acceptable for a sampling diagnostic.
59
+ local f="$dir/h$hour.log" first="" line
60
+ # THE SLOT MUST BE AN ORDINARY FILE, OR NOT EXIST YET (security review, #4848).
61
+ # Anything else is a silent no-op. Two concrete failures if this check is
62
+ # dropped: a FIFO at the slot makes the `read` below block until the hook's
63
+ # settings.json timeout kills it, and a PreToolUse guard killed that way loses
64
+ # its exit 2 — the command it meant to block then runs; a symlink at the slot
65
+ # sends the day-rollover truncation onto the symlink's target. The `-e || -L`
66
+ # wrapper is what lets a not-yet-created slot through (-e is false for a
67
+ # dangling symlink, so -L is needed to catch that case too).
68
+ if [ -e "$f" ] || [ -L "$f" ]; then
69
+ [ -f "$f" ] && [ ! -L "$f" ] || return 0
70
+ fi
71
+ [ -r "$f" ] && { read -r first < "$f"; } 2>/dev/null
72
+ printf -v line '%s dur_us=%s hook=%s event=%s ppid=%s tool=%s\n' \
73
+ "$stamp" "$dur" "${MXHT_HOOK:--}" "${MXHT_EVENT:--}" "$PPID" "${MXHT_TOOL:--}"
74
+ # One printf of ~90 bytes to an O_APPEND fd is atomic under PIPE_BUF, so
75
+ # concurrent hooks cannot interleave partial lines.
76
+ # The 2>/dev/null wraps the GROUP, not the printf: a failing redirection is
77
+ # reported by the shell before an inner 2>/dev/null would be in effect, and a
78
+ # "Permission denied" on stderr from a PreToolUse hook is surfaced to the model.
79
+ if [ "${first%% *}" = "${stamp%% *}" ]; then
80
+ { printf '%s' "$line" >>"$f"; } 2>/dev/null
81
+ else
82
+ { printf '%s' "$line" >"$f"; } 2>/dev/null
83
+ fi
84
+ }
85
+ # `|| :` IS LOAD-BEARING — do not simplify to `trap _mxht_emit EXIT`. The hooks
86
+ # this block is inlined into run under `set -e`, and the EXIT trap runs with
87
+ # errexit still in force. Without `|| :`, a non-zero return from the probe — the
88
+ # final printf failing on an unwritable slot is the reachable case — replaces the
89
+ # hook's own exit status: a PreToolUse guard's exit 2 becomes exit 1, which the
90
+ # harness reads as "error", not "block", so the command it meant to block runs.
91
+ # Pinned verbatim by hook-timing-parity.test.sh.
92
+ trap '_mxht_emit || :' EXIT
93
+ # <<< SHARED hook-timing probe v1
94
+
95
+
17
96
  # Fail-open: any unexpected error → exit 0 silently
18
97
  trap 'exit 0' ERR
19
98
  set -u
@@ -5,8 +5,10 @@
5
5
  #
6
6
  # Fires on: PreToolUse (empty matcher — all tool calls)
7
7
  # Input: JSON on stdin with tool_name and tool_input
8
- # Output: reminder message on stderr (fd 3) when counter >= 50
9
- # Exit: 2 when the reminder is emitted, 0 otherwise.
8
+ # Output: reminder message on stderr (fd 3) when counter >= 50 — a required-save
9
+ # demand for a session observed to have a memory-write tool, otherwise a
10
+ # once-per-session advisory that demands nothing (#4863, see CAPABILITY below)
11
+ # Exit: 2 when either message is emitted, 0 otherwise.
10
12
  # The previous header here read "always 0 (never blocks tool calls)". That has
11
13
  # not matched the code since the reminder moved to exit 2 (see the exit at the
12
14
  # end of section 3), which is what makes a PreToolUse message visible to the
@@ -29,6 +31,124 @@
29
31
  # When no session id is available (harness supplied none, or jq is unavailable) the
30
32
  # counter falls back to the legacy worktree-wide key. That over-counts rather than
31
33
  # under-counts, which keeps the reminder firing instead of silently disabling it.
34
+ # #4863 added a branch whose effect is SILENCE (the once-per-session advisory), so
35
+ # that promise is no longer automatic: the quiet period is honoured only when a real
36
+ # per-session key exists. Without a session id the message repeats rather than
37
+ # suppressing — see the suppression check in section 3.
38
+ #
39
+ # CAPABILITY OBSERVATION (#4863). This hook is registered with an empty matcher, so
40
+ # it fires in EVERY session — including subagents provisioned with Read/Grep/Glob and
41
+ # no Bash and no MCP server. Those sessions were handed a demand ("required before
42
+ # continuing: mx memories create") they had no tool to satisfy, mid-tool-call, shaped
43
+ # exactly like the injected content #4697/#4734 taught agents to distrust. Product's
44
+ # bar-raiser hit this on 2026-08-02 and correctly reported it as a suspected injection.
45
+ #
46
+ # The hook event carries no toolset: PreToolUse gives session_id, tool_name, tool_input
47
+ # and transcript_path, none of which enumerate what the session may call. So capability
48
+ # is not asserted — it is OBSERVED, from the only evidence this hook actually has: the
49
+ # tool calls it sees. A session that has used Bash can run the CLI; a session that has
50
+ # used a MemNexus MCP tool has the MCP server connected and can call create_memory.
51
+ # Either observation marks the session capable (a marker file beside its counter) and
52
+ # the demand is unchanged for it.
53
+ #
54
+ # A session with NO such observation after 50 tool calls gets an advisory instead: same
55
+ # information, no demand, and an explicit "no action required if you cannot save" —
56
+ # emitted ONCE per session, because repeating a no-action notice to a session that
57
+ # provably cannot act is pure interruption. Absence of observation is not proof of
58
+ # absence of capability, which is exactly why the advisory branch downgrades the wording
59
+ # instead of going silent. If the session later uses Bash or an MCP memory tool, it is
60
+ # marked capable and the normal demand resumes.
61
+ #
62
+ # Both messages carry a provenance block naming this hook's file path and trigger, per
63
+ # #4734: a receiving agent can check the claim against the repo instead of guessing
64
+ # whether an interruption is genuine.
65
+ #
66
+ # Without a session id, capability degrades to the worktree-wide key along with the
67
+ # counter — the same known #4802 limitation, in the over-report direction. The
68
+ # advisory's quiet period does NOT degrade with it: suppression requires a real
69
+ # per-session key, because suppression is the one outcome that cannot be recovered
70
+ # from by the agent receiving it. Likewise, a payload this hook cannot parse counts
71
+ # as capable, not as read-only, so a broken jq degrades to the demand rather than
72
+ # turning the gate off (see PAYLOAD_OPAQUE below).
73
+
74
+ MXHT_HOOK=memory-checkpoint-reminder MXHT_EVENT=PreToolUse MXHT_TOOL=-
75
+ # >>> SHARED hook-timing probe v1
76
+ # Diagnostic instrumentation: records how long THIS hook ran, so hook time can be
77
+ # separated from time spent waiting on the API when a session stalls mid-stream.
78
+ # Appends one line to a local, gitignored log. Read it with
79
+ # mx-agent-system/scripts/hook-timing-report.sh. Nothing is transmitted anywhere.
80
+ #
81
+ # FAIL SILENT IS DELIBERATE HERE, and it is the opposite of this repo's usual
82
+ # fail-loud direction. Do not "correct" it to fail-loud by applying the fleet
83
+ # default. A diagnostic that can break the gate it observes is worse than no
84
+ # diagnostic: an unwritable path or a full disk would otherwise take out every
85
+ # guard on the PreToolUse path at once. Every step below is guarded and every
86
+ # failure path is a silent no-op that leaves the hook's behaviour untouched.
87
+ #
88
+ # NEAR-ZERO OVERHEAD: bash builtins only on the hot path ($EPOCHREALTIME, printf
89
+ # -T, one read, one append). No subprocess, no network, no JSON parsing, and the
90
+ # hook's stdin is never touched (the hook owns it). mkdir runs at most once per
91
+ # worktree. Kill switch: MX_HOOK_TIMING=0.
92
+ MXHT_T0="${EPOCHREALTIME:-}"
93
+ _mxht_emit() {
94
+ [ -z "${MXHT_DONE:-}" ] || return 0 # an ERR trap that exits fires EXIT too
95
+ MXHT_DONE=1
96
+ [ "${MX_HOOK_TIMING:-1}" != "0" ] || return 0
97
+ [ -n "${MXHT_T0:-}" ] && [ -n "${EPOCHREALTIME:-}" ] || return 0
98
+ local root="${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-}}"
99
+ [ -n "$root" ] && [ -d "$root" ] || return 0
100
+ local dir="$root/.mx-hook-timing"
101
+ [ -d "$dir" ] || mkdir -p "$dir" 2>/dev/null || return 0
102
+ # EPOCHREALTIME is seconds.microseconds; the separator is locale-dependent, so
103
+ # strip both forms and subtract as plain integer microseconds.
104
+ local dur=-1
105
+ { dur=$(( ${EPOCHREALTIME//[.,]/} - ${MXHT_T0//[.,]/} )); } 2>/dev/null
106
+ [ "$dur" -ge 0 ] 2>/dev/null || return 0
107
+ local stamp hour
108
+ printf -v stamp '%(%Y-%m-%d %H:%M:%S)T' -1
109
+ printf -v hour '%(%H)T' -1
110
+ # BOUNDED BY CONSTRUCTION: a 24-slot ring, one file per hour-of-day, so the log
111
+ # is at most 24 files each holding one hour of this machine's hook calls. The
112
+ # first writer into a slot on a new day truncates it instead of appending —
113
+ # detected by reading the slot's first line, which is a builtin read (no stat,
114
+ # no rm, no find, no cron). Two writers can race that truncation and lose a
115
+ # line or two at an hour boundary; that is acceptable for a sampling diagnostic.
116
+ local f="$dir/h$hour.log" first="" line
117
+ # THE SLOT MUST BE AN ORDINARY FILE, OR NOT EXIST YET (security review, #4848).
118
+ # Anything else is a silent no-op. Two concrete failures if this check is
119
+ # dropped: a FIFO at the slot makes the `read` below block until the hook's
120
+ # settings.json timeout kills it, and a PreToolUse guard killed that way loses
121
+ # its exit 2 — the command it meant to block then runs; a symlink at the slot
122
+ # sends the day-rollover truncation onto the symlink's target. The `-e || -L`
123
+ # wrapper is what lets a not-yet-created slot through (-e is false for a
124
+ # dangling symlink, so -L is needed to catch that case too).
125
+ if [ -e "$f" ] || [ -L "$f" ]; then
126
+ [ -f "$f" ] && [ ! -L "$f" ] || return 0
127
+ fi
128
+ [ -r "$f" ] && { read -r first < "$f"; } 2>/dev/null
129
+ printf -v line '%s dur_us=%s hook=%s event=%s ppid=%s tool=%s\n' \
130
+ "$stamp" "$dur" "${MXHT_HOOK:--}" "${MXHT_EVENT:--}" "$PPID" "${MXHT_TOOL:--}"
131
+ # One printf of ~90 bytes to an O_APPEND fd is atomic under PIPE_BUF, so
132
+ # concurrent hooks cannot interleave partial lines.
133
+ # The 2>/dev/null wraps the GROUP, not the printf: a failing redirection is
134
+ # reported by the shell before an inner 2>/dev/null would be in effect, and a
135
+ # "Permission denied" on stderr from a PreToolUse hook is surfaced to the model.
136
+ if [ "${first%% *}" = "${stamp%% *}" ]; then
137
+ { printf '%s' "$line" >>"$f"; } 2>/dev/null
138
+ else
139
+ { printf '%s' "$line" >"$f"; } 2>/dev/null
140
+ fi
141
+ }
142
+ # `|| :` IS LOAD-BEARING — do not simplify to `trap _mxht_emit EXIT`. The hooks
143
+ # this block is inlined into run under `set -e`, and the EXIT trap runs with
144
+ # errexit still in force. Without `|| :`, a non-zero return from the probe — the
145
+ # final printf failing on an unwritable slot is the reachable case — replaces the
146
+ # hook's own exit status: a PreToolUse guard's exit 2 becomes exit 1, which the
147
+ # harness reads as "error", not "block", so the command it meant to block runs.
148
+ # Pinned verbatim by hook-timing-parity.test.sh.
149
+ trap '_mxht_emit || :' EXIT
150
+ # <<< SHARED hook-timing probe v1
151
+
32
152
 
33
153
  # Fail-open: any error → exit 0 silently
34
154
  trap 'exit 0' ERR
@@ -49,6 +169,23 @@ INPUT=$(cat)
49
169
  # as "not a memory save", which over-reminds rather than never reminding.
50
170
  TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null) || TOOL_NAME=""
51
171
 
172
+ # PAYLOAD OPAQUE (#4863 security review). An empty tool name means the payload could
173
+ # not be read — broken/missing jq, or a shape this hook does not understand. #4863's
174
+ # capability observation is built entirely on reading tool names, so in that state it
175
+ # can NEVER observe capability: every session would look read-only, and a read-only
176
+ # session is the one branch that goes quiet. Left unhandled, a broken jq turns this
177
+ # hook permanently inert after a single advisory — precisely the silent-disable the
178
+ # `|| TOOL_NAME=""` above exists to prevent, reintroduced one layer up.
179
+ #
180
+ # So an unreadable payload is treated as CAPABLE: the demand fires. That is the
181
+ # over-report direction (#4755/#4756), consistent with every other degradation in
182
+ # this file — a session that cannot act may see a demand it must reason about,
183
+ # which is recoverable; a fleet-wide silent checkpoint gate is not.
184
+ PAYLOAD_OPAQUE=0
185
+ if [[ -z "$TOOL_NAME" ]]; then
186
+ PAYLOAD_OPAQUE=1
187
+ fi
188
+
52
189
  # Session attribution (#4802), same parse and same sanitization #4758 established
53
190
  # for deploy-verification-reminder.sh. `|| SESSION_ID=""` is load-bearing for the
54
191
  # same reason TOOL_NAME's is: a missing or broken jq must degrade to the legacy
@@ -74,6 +211,12 @@ if [[ -n "$SESSION_ID" ]]; then
74
211
  COUNTER_FILE="${COUNTER_FILE}.session-${SESSION_ID}"
75
212
  fi
76
213
  THRESHOLD=50
214
+ # Companion state, named off the counter base for the same reason the per-session
215
+ # counter is (#4758's convention): one family of files, one sweep pattern.
216
+ # .cap — this session has been OBSERVED using a memory-capable tool (#4863)
217
+ # .advised — the once-per-session advisory has already been emitted (#4863)
218
+ CAP_FILE="${COUNTER_FILE}.cap"
219
+ ADVISED_FILE="${COUNTER_FILE}.advised"
77
220
 
78
221
  # Reset counter if it's stale (from a previous session — >30 min old)
79
222
  if [[ -f "$COUNTER_FILE" ]]; then
@@ -82,9 +225,33 @@ if [[ -f "$COUNTER_FILE" ]]; then
82
225
  AGE=$((NOW - MTIME))
83
226
  if [[ "$AGE" -gt 1800 ]]; then
84
227
  echo "0" > "$COUNTER_FILE" 2>/dev/null || true
228
+ # A stale counter means the key is being reused by different work; the
229
+ # capability and advisory observations belonged to that older occupant, so
230
+ # they go with it. Dropping them re-arms the advisory rather than the demand,
231
+ # which is the safe direction: it re-observes before it re-demands.
232
+ rm -f "$CAP_FILE" "$ADVISED_FILE" 2>/dev/null || true
85
233
  fi
86
234
  fi
87
235
 
236
+ # ── 0. Observe memory-write capability (#4863) ───────────────────────────────
237
+ # Positive evidence only, from tool calls this hook is already given. Bash → the
238
+ # session can run `mx memories create`. A MemNexus MCP tool → the server is
239
+ # connected, so create_memory is callable. Cheap on the hot path: a builtin test,
240
+ # and at most one file creation per session.
241
+ #
242
+ # The MCP patterns mirror section 1's save-detection substrings rather than listing
243
+ # server prefixes: section 1 already accepts *create_memory* / *manage_memory* under
244
+ # any prefix, and a tool this hook counts as a memory SAVE must also count as
245
+ # evidence the session can save. Two different notions of "a memory tool" in one
246
+ # file is how a capable session ends up classified read-only.
247
+ case "$TOOL_NAME" in
248
+ Bash|mcp__memnexus__*|mcp__MX__*|*create_memory*|*manage_memory*|*memnexus*)
249
+ if [[ ! -f "$CAP_FILE" ]]; then
250
+ : > "$CAP_FILE" 2>/dev/null || true
251
+ fi
252
+ ;;
253
+ esac
254
+
88
255
  # ── 1. Detect memory save operations ────────────────────────────────────────
89
256
  # Reset counter if this tool call IS a memory save:
90
257
  # - MCP tools: mcp__memnexus__create_memory, mcp__memnexus__manage_memory
@@ -132,8 +299,41 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
132
299
  # Reset counter — after save + retry, next 50 calls proceed unblocked
133
300
  echo "0" > "$COUNTER_FILE" 2>/dev/null || true
134
301
 
302
+ # Capability decision (#4863). `if`, not `[[ ... ]] && VAR=1` — FL-13, never
303
+ # leave a failing test in reach of the ERR trap.
304
+ CAPABLE=0
305
+ if [[ -f "$CAP_FILE" ]]; then
306
+ CAPABLE=1
307
+ fi
308
+ # An unreadable payload cannot have been observed, so it must not be scored as
309
+ # "observed read-only" — see PAYLOAD_OPAQUE above. Degrade to the demand.
310
+ if [[ "$PAYLOAD_OPAQUE" -eq 1 ]]; then
311
+ CAPABLE=1
312
+ fi
313
+
314
+ # A session with no observed memory-write tool is advised at most once. Past
315
+ # that, staying quiet is the correct behaviour: it has already been told, it
316
+ # cannot act, and every further interruption is cost with no possible outcome.
317
+ # This is not the hook being disabled — the demand returns the moment the
318
+ # session uses Bash or a MemNexus MCP tool.
319
+ #
320
+ # The `-n "$SESSION_ID"` is the load-bearing part (#4863 security review). The
321
+ # quiet period is a claim about ONE session ("this session has already been
322
+ # advised"), so it may only be honoured when the state it reads is actually
323
+ # keyed to a session. Without a session id every session in the worktree shares
324
+ # one .advised file, and a single read-only subagent's advisory would silence
325
+ # the checkpoint gate for capable sessions beside it — the #4802 cross-session
326
+ # attribution bug, reintroduced in the one branch whose effect is silence.
327
+ # No session id → never suppress; the message repeats instead. Over-reminding
328
+ # is the failure this file has always chosen.
329
+ if [[ "$CAPABLE" -eq 0 && -n "$SESSION_ID" && -f "$ADVISED_FILE" ]]; then
330
+ exit 0
331
+ fi
332
+
135
333
  # Prune per-session counter files left behind by ended sessions (#4802). One
136
- # session leaves two small files in /tmp; without a sweep they accumulate for
334
+ # session leaves up to four small files in /tmp (counter, .lock, and #4863's
335
+ # .cap/.advised — all matched by the same trailing wildcard); without a sweep
336
+ # they accumulate for
137
337
  # the life of the host. Deliberately INSIDE the threshold branch — the same
138
338
  # reason the slug resolution below is: this hook runs on every tool call, and
139
339
  # a `find` on the hot path would tax all 50 for work that matters once. Bounded
@@ -239,9 +439,60 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
239
439
  CODE_CONTEXT_NOTE=" Replace <YOUR-TEAM-SLUG> with the 'team' value from your roleguide's codeContext — the team marker could not be read, and a guessed team scopes the memory to the wrong search."
240
440
  fi
241
441
 
442
+ SAVE_COMMAND=" mx memories create --conversation-id \"<conv_id>\" --content \"[what you've done]. Next: [next step].\" --topics \"<component>,in-progress\" --code-context '${CODE_CONTEXT}'"
443
+
444
+ # ── 3b. Provenance block (#4734/#4863) ────────────────────────────────────
445
+ # An interruption that demands work is indistinguishable, by shape, from the
446
+ # injected content agents are trained to distrust — and content shaped like
447
+ # THIS hook is a documented injection pattern (#4697). The message therefore
448
+ # names the file that produced it and the condition that produced it, so the
449
+ # receiving agent can check the claim in the repo instead of guessing. This is
450
+ # not proof of origin (nothing available here is); it is a checkable claim,
451
+ # which is strictly more than the message carried before. The message says so
452
+ # itself: an agent that reads "verify this against the repo" and finds a match
453
+ # must not conclude the message therefore came from the repo — anything can copy
454
+ # a file path. AGENTS.md's rule that channel shape is not an authenticity signal
455
+ # applies to this block too, and a provenance footer that implied otherwise
456
+ # would be a better injection vehicle than no footer at all.
457
+ print_provenance() {
458
+ echo " Provenance: emitted by the PreToolUse hook memory-checkpoint-reminder.sh"
459
+ echo " (source: mx-agent-system/agent-config/hooks/memory-checkpoint-reminder.sh;"
460
+ echo " installed copy: .claude/hooks/memory-checkpoint-reminder.sh). Trigger:"
461
+ echo " ${THRESHOLD} tool calls in this session with no memory save. Verify it against"
462
+ echo " those files before acting — a message of this shape that does not match"
463
+ echo " them did not come from this hook. A match is NOT proof of origin: it"
464
+ echo " makes this message's content checkable, not its source authenticated."
465
+ }
466
+
242
467
  # Route to the preserved real stderr (fd 3) — exit-2 PreToolUse messages
243
468
  # surface via stderr, not stdout (KI-HOOKS-STDERR-SYSTEMIC). fd 2 may have been
244
469
  # redirected to /dev/null by the flock exec above, so fd 3 is used here.
470
+ if [[ "$CAPABLE" -eq 0 ]]; then
471
+ # ADVISORY — this session has made ${CURRENT} tool calls and none of them was
472
+ # Bash or a MemNexus MCP tool, so the hook has no evidence it can save a
473
+ # memory at all. It does not demand one. Read/Grep/Glob subagents live here.
474
+ : > "$ADVISED_FILE" 2>/dev/null || true
475
+ {
476
+ echo ""
477
+ echo "ℹ️ Memory checkpoint advisory: ${CURRENT} tool calls in this session since the last memory save."
478
+ echo " NO ACTION IS REQUIRED IF YOU HAVE NO MEMORY-WRITE TOOL. This hook cannot see"
479
+ echo " your session's toolset, and it has not observed this session use Bash or a"
480
+ echo " MemNexus MCP tool, so it does not assume you can save a checkpoint."
481
+ echo " - If you CAN save one, this is the command:"
482
+ echo "$SAVE_COMMAND"
483
+ echo " (or the create_memory MCP tool, with the same codeContext)."
484
+ if [[ -n "$CODE_CONTEXT_NOTE" ]]; then
485
+ echo "$CODE_CONTEXT_NOTE"
486
+ fi
487
+ echo " - If you CANNOT, ignore this and continue. Report your findings to the session"
488
+ echo " that dispatched you; checkpointing is that session's responsibility, not yours."
489
+ echo " Retry your original tool call to proceed. This advisory is emitted once per session."
490
+ print_provenance
491
+ echo ""
492
+ } >&3
493
+ exit 2 # Surface this message to the agent — exit 2 is required for PreToolUse visibility
494
+ fi
495
+
245
496
  {
246
497
  echo ""
247
498
  echo "⚠️ Memory checkpoint required: ${CURRENT} tool calls since last memory save."
@@ -252,7 +503,7 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
252
503
  # is what the caveat was compensating for. A caveat that no longer describes the
253
504
  # code is the same defect class in the other direction.
254
505
  echo "1. Save a checkpoint now (required before continuing):"
255
- echo " mx memories create --conversation-id \"<conv_id>\" --content \"[what you've done]. Next: [next step].\" --topics \"<component>,in-progress\" --code-context '${CODE_CONTEXT}'"
506
+ echo "$SAVE_COMMAND"
256
507
  # `if`, not `[[ ... ]] && echo`. Policy, not a claim about this line: never
257
508
  # leave a failing test within reach of an ERR trap. Whether a given position
258
509
  # is exempt depends on where the list sits and how it is nested — too fragile
@@ -261,6 +512,7 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
261
512
  echo "$CODE_CONTEXT_NOTE"
262
513
  fi
263
514
  echo "2. After saving, retry your original tool call."
515
+ print_provenance
264
516
  echo ""
265
517
  } >&3
266
518
  exit 2 # Surface this message to the agent — exit 2 is required for PreToolUse visibility
@@ -38,6 +38,83 @@
38
38
  # `git -C /treeA push && git -C /treeB push` pushed unlinted. Every push
39
39
  # segment is now resolved and every distinct toplevel linted.
40
40
 
41
+ MXHT_HOOK=mx-guard-hook MXHT_EVENT=PreToolUse MXHT_TOOL=Bash
42
+ # >>> SHARED hook-timing probe v1
43
+ # Diagnostic instrumentation: records how long THIS hook ran, so hook time can be
44
+ # separated from time spent waiting on the API when a session stalls mid-stream.
45
+ # Appends one line to a local, gitignored log. Read it with
46
+ # mx-agent-system/scripts/hook-timing-report.sh. Nothing is transmitted anywhere.
47
+ #
48
+ # FAIL SILENT IS DELIBERATE HERE, and it is the opposite of this repo's usual
49
+ # fail-loud direction. Do not "correct" it to fail-loud by applying the fleet
50
+ # default. A diagnostic that can break the gate it observes is worse than no
51
+ # diagnostic: an unwritable path or a full disk would otherwise take out every
52
+ # guard on the PreToolUse path at once. Every step below is guarded and every
53
+ # failure path is a silent no-op that leaves the hook's behaviour untouched.
54
+ #
55
+ # NEAR-ZERO OVERHEAD: bash builtins only on the hot path ($EPOCHREALTIME, printf
56
+ # -T, one read, one append). No subprocess, no network, no JSON parsing, and the
57
+ # hook's stdin is never touched (the hook owns it). mkdir runs at most once per
58
+ # worktree. Kill switch: MX_HOOK_TIMING=0.
59
+ MXHT_T0="${EPOCHREALTIME:-}"
60
+ _mxht_emit() {
61
+ [ -z "${MXHT_DONE:-}" ] || return 0 # an ERR trap that exits fires EXIT too
62
+ MXHT_DONE=1
63
+ [ "${MX_HOOK_TIMING:-1}" != "0" ] || return 0
64
+ [ -n "${MXHT_T0:-}" ] && [ -n "${EPOCHREALTIME:-}" ] || return 0
65
+ local root="${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-}}"
66
+ [ -n "$root" ] && [ -d "$root" ] || return 0
67
+ local dir="$root/.mx-hook-timing"
68
+ [ -d "$dir" ] || mkdir -p "$dir" 2>/dev/null || return 0
69
+ # EPOCHREALTIME is seconds.microseconds; the separator is locale-dependent, so
70
+ # strip both forms and subtract as plain integer microseconds.
71
+ local dur=-1
72
+ { dur=$(( ${EPOCHREALTIME//[.,]/} - ${MXHT_T0//[.,]/} )); } 2>/dev/null
73
+ [ "$dur" -ge 0 ] 2>/dev/null || return 0
74
+ local stamp hour
75
+ printf -v stamp '%(%Y-%m-%d %H:%M:%S)T' -1
76
+ printf -v hour '%(%H)T' -1
77
+ # BOUNDED BY CONSTRUCTION: a 24-slot ring, one file per hour-of-day, so the log
78
+ # is at most 24 files each holding one hour of this machine's hook calls. The
79
+ # first writer into a slot on a new day truncates it instead of appending —
80
+ # detected by reading the slot's first line, which is a builtin read (no stat,
81
+ # no rm, no find, no cron). Two writers can race that truncation and lose a
82
+ # line or two at an hour boundary; that is acceptable for a sampling diagnostic.
83
+ local f="$dir/h$hour.log" first="" line
84
+ # THE SLOT MUST BE AN ORDINARY FILE, OR NOT EXIST YET (security review, #4848).
85
+ # Anything else is a silent no-op. Two concrete failures if this check is
86
+ # dropped: a FIFO at the slot makes the `read` below block until the hook's
87
+ # settings.json timeout kills it, and a PreToolUse guard killed that way loses
88
+ # its exit 2 — the command it meant to block then runs; a symlink at the slot
89
+ # sends the day-rollover truncation onto the symlink's target. The `-e || -L`
90
+ # wrapper is what lets a not-yet-created slot through (-e is false for a
91
+ # dangling symlink, so -L is needed to catch that case too).
92
+ if [ -e "$f" ] || [ -L "$f" ]; then
93
+ [ -f "$f" ] && [ ! -L "$f" ] || return 0
94
+ fi
95
+ [ -r "$f" ] && { read -r first < "$f"; } 2>/dev/null
96
+ printf -v line '%s dur_us=%s hook=%s event=%s ppid=%s tool=%s\n' \
97
+ "$stamp" "$dur" "${MXHT_HOOK:--}" "${MXHT_EVENT:--}" "$PPID" "${MXHT_TOOL:--}"
98
+ # One printf of ~90 bytes to an O_APPEND fd is atomic under PIPE_BUF, so
99
+ # concurrent hooks cannot interleave partial lines.
100
+ # The 2>/dev/null wraps the GROUP, not the printf: a failing redirection is
101
+ # reported by the shell before an inner 2>/dev/null would be in effect, and a
102
+ # "Permission denied" on stderr from a PreToolUse hook is surfaced to the model.
103
+ if [ "${first%% *}" = "${stamp%% *}" ]; then
104
+ { printf '%s' "$line" >>"$f"; } 2>/dev/null
105
+ else
106
+ { printf '%s' "$line" >"$f"; } 2>/dev/null
107
+ fi
108
+ }
109
+ # `|| :` IS LOAD-BEARING — do not simplify to `trap _mxht_emit EXIT`. The hooks
110
+ # this block is inlined into run under `set -e`, and the EXIT trap runs with
111
+ # errexit still in force. Without `|| :`, a non-zero return from the probe — the
112
+ # final printf failing on an unwritable slot is the reachable case — replaces the
113
+ # hook's own exit status: a PreToolUse guard's exit 2 becomes exit 1, which the
114
+ # harness reads as "error", not "block", so the command it meant to block runs.
115
+ # Pinned verbatim by hook-timing-parity.test.sh.
116
+ trap '_mxht_emit || :' EXIT
117
+ # <<< SHARED hook-timing probe v1
41
118
 
42
119
 
43
120
  # Read hook input from stdin
@@ -39,6 +39,85 @@
39
39
  # refuse()->stderr+exit2, fail-open), iteration-log-check.sh (best-effort
40
40
  # emit_telemetry with the MX_HOOK_TELEMETRY kill-switch and mx-on-PATH guard).
41
41
 
42
+ MXHT_HOOK=named-memory-write-guard MXHT_EVENT=PreToolUse MXHT_TOOL=Bash
43
+ # >>> SHARED hook-timing probe v1
44
+ # Diagnostic instrumentation: records how long THIS hook ran, so hook time can be
45
+ # separated from time spent waiting on the API when a session stalls mid-stream.
46
+ # Appends one line to a local, gitignored log. Read it with
47
+ # mx-agent-system/scripts/hook-timing-report.sh. Nothing is transmitted anywhere.
48
+ #
49
+ # FAIL SILENT IS DELIBERATE HERE, and it is the opposite of this repo's usual
50
+ # fail-loud direction. Do not "correct" it to fail-loud by applying the fleet
51
+ # default. A diagnostic that can break the gate it observes is worse than no
52
+ # diagnostic: an unwritable path or a full disk would otherwise take out every
53
+ # guard on the PreToolUse path at once. Every step below is guarded and every
54
+ # failure path is a silent no-op that leaves the hook's behaviour untouched.
55
+ #
56
+ # NEAR-ZERO OVERHEAD: bash builtins only on the hot path ($EPOCHREALTIME, printf
57
+ # -T, one read, one append). No subprocess, no network, no JSON parsing, and the
58
+ # hook's stdin is never touched (the hook owns it). mkdir runs at most once per
59
+ # worktree. Kill switch: MX_HOOK_TIMING=0.
60
+ MXHT_T0="${EPOCHREALTIME:-}"
61
+ _mxht_emit() {
62
+ [ -z "${MXHT_DONE:-}" ] || return 0 # an ERR trap that exits fires EXIT too
63
+ MXHT_DONE=1
64
+ [ "${MX_HOOK_TIMING:-1}" != "0" ] || return 0
65
+ [ -n "${MXHT_T0:-}" ] && [ -n "${EPOCHREALTIME:-}" ] || return 0
66
+ local root="${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-}}"
67
+ [ -n "$root" ] && [ -d "$root" ] || return 0
68
+ local dir="$root/.mx-hook-timing"
69
+ [ -d "$dir" ] || mkdir -p "$dir" 2>/dev/null || return 0
70
+ # EPOCHREALTIME is seconds.microseconds; the separator is locale-dependent, so
71
+ # strip both forms and subtract as plain integer microseconds.
72
+ local dur=-1
73
+ { dur=$(( ${EPOCHREALTIME//[.,]/} - ${MXHT_T0//[.,]/} )); } 2>/dev/null
74
+ [ "$dur" -ge 0 ] 2>/dev/null || return 0
75
+ local stamp hour
76
+ printf -v stamp '%(%Y-%m-%d %H:%M:%S)T' -1
77
+ printf -v hour '%(%H)T' -1
78
+ # BOUNDED BY CONSTRUCTION: a 24-slot ring, one file per hour-of-day, so the log
79
+ # is at most 24 files each holding one hour of this machine's hook calls. The
80
+ # first writer into a slot on a new day truncates it instead of appending —
81
+ # detected by reading the slot's first line, which is a builtin read (no stat,
82
+ # no rm, no find, no cron). Two writers can race that truncation and lose a
83
+ # line or two at an hour boundary; that is acceptable for a sampling diagnostic.
84
+ local f="$dir/h$hour.log" first="" line
85
+ # THE SLOT MUST BE AN ORDINARY FILE, OR NOT EXIST YET (security review, #4848).
86
+ # Anything else is a silent no-op. Two concrete failures if this check is
87
+ # dropped: a FIFO at the slot makes the `read` below block until the hook's
88
+ # settings.json timeout kills it, and a PreToolUse guard killed that way loses
89
+ # its exit 2 — the command it meant to block then runs; a symlink at the slot
90
+ # sends the day-rollover truncation onto the symlink's target. The `-e || -L`
91
+ # wrapper is what lets a not-yet-created slot through (-e is false for a
92
+ # dangling symlink, so -L is needed to catch that case too).
93
+ if [ -e "$f" ] || [ -L "$f" ]; then
94
+ [ -f "$f" ] && [ ! -L "$f" ] || return 0
95
+ fi
96
+ [ -r "$f" ] && { read -r first < "$f"; } 2>/dev/null
97
+ printf -v line '%s dur_us=%s hook=%s event=%s ppid=%s tool=%s\n' \
98
+ "$stamp" "$dur" "${MXHT_HOOK:--}" "${MXHT_EVENT:--}" "$PPID" "${MXHT_TOOL:--}"
99
+ # One printf of ~90 bytes to an O_APPEND fd is atomic under PIPE_BUF, so
100
+ # concurrent hooks cannot interleave partial lines.
101
+ # The 2>/dev/null wraps the GROUP, not the printf: a failing redirection is
102
+ # reported by the shell before an inner 2>/dev/null would be in effect, and a
103
+ # "Permission denied" on stderr from a PreToolUse hook is surfaced to the model.
104
+ if [ "${first%% *}" = "${stamp%% *}" ]; then
105
+ { printf '%s' "$line" >>"$f"; } 2>/dev/null
106
+ else
107
+ { printf '%s' "$line" >"$f"; } 2>/dev/null
108
+ fi
109
+ }
110
+ # `|| :` IS LOAD-BEARING — do not simplify to `trap _mxht_emit EXIT`. The hooks
111
+ # this block is inlined into run under `set -e`, and the EXIT trap runs with
112
+ # errexit still in force. Without `|| :`, a non-zero return from the probe — the
113
+ # final printf failing on an unwritable slot is the reachable case — replaces the
114
+ # hook's own exit status: a PreToolUse guard's exit 2 becomes exit 1, which the
115
+ # harness reads as "error", not "block", so the command it meant to block runs.
116
+ # Pinned verbatim by hook-timing-parity.test.sh.
117
+ trap '_mxht_emit || :' EXIT
118
+ # <<< SHARED hook-timing probe v1
119
+
120
+
42
121
  set -euo pipefail
43
122
 
44
123
  # ── Config ───────────────────────────────────────────────────────────────────