@memnexus-ai/mx-agent-cli 0.1.253 → 0.1.254

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.
@@ -15,9 +15,20 @@
15
15
  # the same defect class as the misattributed reminder #4734 addresses — in a
16
16
  # file that runs on EVERY tool call for every agent.
17
17
  #
18
- # NOTE (#4734): the counter below is keyed by WORKTREE, not by session, so it
19
- # aggregates tool calls across every agent session active in the worktree. That
20
- # is deliberate — see the caveat emitted with the reminder in section 3.
18
+ # COUNTING SCOPE (#4802). The counter is keyed by SESSION (harness-supplied
19
+ # .session_id) within a worktree, so each session counts only its own tool calls.
20
+ # It used to be keyed by worktree alone, which made this guard resolve its subject
21
+ # from ambient context rather than from the agent it was actually guarding: a
22
+ # session that had made two tool calls itself was told "50 tool calls since last
23
+ # memory save" and required to write a checkpoint because OTHER sessions in the
24
+ # worktree were busy. A read-only auditor was forced to write durable memory purely
25
+ # to unblock itself. #4758 established that .session_id is on the payload and how to
26
+ # key state with it; this hook now uses it too. The discipline is unchanged — same
27
+ # threshold, same required save — it is the attribution that is fixed.
28
+ #
29
+ # When no session id is available (harness supplied none, or jq is unavailable) the
30
+ # counter falls back to the legacy worktree-wide key. That over-counts rather than
31
+ # under-counts, which keeps the reminder firing instead of silently disabling it.
21
32
 
22
33
  # Fail-open: any error → exit 0 silently
23
34
  trap 'exit 0' ERR
@@ -38,11 +49,30 @@ INPUT=$(cat)
38
49
  # as "not a memory save", which over-reminds rather than never reminding.
39
50
  TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null) || TOOL_NAME=""
40
51
 
52
+ # Session attribution (#4802), same parse and same sanitization #4758 established
53
+ # for deploy-verification-reminder.sh. `|| SESSION_ID=""` is load-bearing for the
54
+ # same reason TOOL_NAME's is: a missing or broken jq must degrade to the legacy
55
+ # worktree-wide key, not return non-zero into the ERR trap and take the hook out.
56
+ # The value is used only as a filename component, never printed into the message,
57
+ # so no harness-supplied text reaches agent context through it.
58
+ SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty' 2>/dev/null) || SESSION_ID=""
59
+ SESSION_ID="${SESSION_ID//[^a-zA-Z0-9_-]/}"
60
+
41
61
  WORKTREE_NAME="${CLAUDE_WORKTREE_NAME:-default}"
42
62
  # Sanitize: alphanumeric, hyphens, underscores only — prevent path traversal
43
63
  WORKTREE_NAME="${WORKTREE_NAME//[^a-zA-Z0-9_-]/}"
44
64
  WORKTREE_NAME="${WORKTREE_NAME:-default}"
45
65
  COUNTER_FILE="/tmp/.mx-checkpoint-counter-${WORKTREE_NAME}"
66
+ # Per-session counter file. Naming follows #4758's `${STATE_FILE}.notice-${SESSION_ID}`
67
+ # convention — derive from the existing base rather than inventing a second scheme —
68
+ # so the worktree base name still identifies the family and a worktree name can never
69
+ # collide with a worktree+session name. No session id → legacy worktree-wide file.
70
+ # `if`, not `[[ ... ]] && ...` — this file's own FL-13 policy: never leave a
71
+ # failing test within reach of the ERR trap, regardless of whether a given
72
+ # position happens to be exempt today.
73
+ if [[ -n "$SESSION_ID" ]]; then
74
+ COUNTER_FILE="${COUNTER_FILE}.session-${SESSION_ID}"
75
+ fi
46
76
  THRESHOLD=50
47
77
 
48
78
  # Reset counter if it's stale (from a previous session — >30 min old)
@@ -102,6 +132,15 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
102
132
  # Reset counter — after save + retry, next 50 calls proceed unblocked
103
133
  echo "0" > "$COUNTER_FILE" 2>/dev/null || true
104
134
 
135
+ # 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
137
+ # the life of the host. Deliberately INSIDE the threshold branch — the same
138
+ # reason the slug resolution below is: this hook runs on every tool call, and
139
+ # a `find` on the hot path would tax all 50 for work that matters once. Bounded
140
+ # by -maxdepth 1 and a fixed name pattern; best-effort, errors ignored (other
141
+ # users' files are simply not ours to delete).
142
+ find /tmp -maxdepth 1 -name '.mx-checkpoint-counter-*.session-*' -mmin +1440 -delete 2>/dev/null || true
143
+
105
144
  # ── 3a. Resolve codeContext for the suggested command (#4652) ──────────────
106
145
  # Deliberately INSIDE the threshold branch. This hook runs on every single
107
146
  # tool call; the resolved slug is used once per 50. Resolving it on the hot
@@ -199,13 +238,12 @@ if [[ "$CURRENT" -ge "$THRESHOLD" ]]; then
199
238
  {
200
239
  echo ""
201
240
  echo "⚠️ Memory checkpoint required: ${CURRENT} tool calls since last memory save."
202
- # Attribution caveat (#4734). COUNTER_FILE is keyed by worktree alone, so this
203
- # total spans every agent session active in this worktree. Without this line an
204
- # agent that had made two calls itself read "50 tool calls" as its OWN count
205
- # and reported the reminder as inexplicable. The counter's worktree-wide
206
- # semantics are intentional (it tracks team checkpoint cadence) and are NOT
207
- # changed here — only the claim the message makes about whose calls these are.
208
- echo " Note: this count includes tool calls from all agent sessions active in this worktree, not only your own."
241
+ # The cross-session caveat #4734 added here is GONE as of #4802, because it is
242
+ # no longer true: the counter is keyed by session, so this count is the reading
243
+ # session's own tool calls. #4734 could only correct the message because the
244
+ # counter's scope was out of scope for that change; #4802 fixed the scope, which
245
+ # is what the caveat was compensating for. A caveat that no longer describes the
246
+ # code is the same defect class in the other direction.
209
247
  echo "1. Save a checkpoint now (required before continuing):"
210
248
  echo " mx memories create --conversation-id \"<conv_id>\" --content \"[what you've done]. Next: [next step].\" --topics \"<component>,in-progress\" --code-context '${CODE_CONTEXT}'"
211
249
  # `if`, not `[[ ... ]] && echo`. Policy, not a claim about this line: never
@@ -5,7 +5,38 @@
5
5
  #
6
6
  # Exit codes:
7
7
  # 0 = allow (not a push command, or mx-guard passes)
8
- # 2 = block (mx-guard found errors)
8
+ # 2 = block (mx-guard found errors, OR the push target could not be identified)
9
+ #
10
+ # PUSH TARGET RESOLUTION (#4803). Before this fix the hook ran a bare
11
+ # `mx-guard check`, which resolves its repo root from the PROCESS cwd. The hook
12
+ # subprocess always starts in the session's own team worktree — `cd`, `git -C`,
13
+ # and env vars exported inside the tool command do not reach it. So a push from
14
+ # a scratch worktree was linted against the SHARED worktree's checkout, in both
15
+ # directions: unrelated mess in the shared tree blocked clean scratch pushes
16
+ # (false block), and a scratch branch with real lint failures pushed cleanly
17
+ # whenever the shared tree happened to be clean (false pass — six such pushes on
18
+ # 2026-07-31 passed by luck, not by inspection). The gate never examined the
19
+ # thing it was gating.
20
+ #
21
+ # The fix derives the target from the push command itself (option 1 in #4803):
22
+ # the `git -C <path> push` form, and the `cd <path> && git push` compound form,
23
+ # resolved against the payload's cwd. When an explicit path is present but
24
+ # cannot be resolved to a local git work tree (an unexpanded variable, a path
25
+ # that does not exist), the hook does NOT guess — it fails loudly and blocks
26
+ # (option 3), because a gate that cannot identify its subject must say so rather
27
+ # than produce a verdict on the wrong tree.
28
+ #
29
+ # Two Should Fix findings from the security review of this change are folded in
30
+ # below, both instances of the same "gate stands down without examining its
31
+ # subject" shape #4803 is about:
32
+ # SF-1 the stand-down for remote pushes matched `ssh`/`scp` as a substring
33
+ # anywhere in the command, so a trailing `# over ssh tunnel` comment
34
+ # turned a block into a silent skip while the local push still ran. The
35
+ # token must now LEAD the segment the push belongs to; everything else
36
+ # fails closed.
37
+ # SF-2 only the first push segment was examined, so the second half of
38
+ # `git -C /treeA push && git -C /treeB push` pushed unlinted. Every push
39
+ # segment is now resolved and every distinct toplevel linted.
9
40
 
10
41
  # Read hook input from stdin
11
42
  INPUT=$(cat)
@@ -54,6 +85,212 @@ if ! command -v mx-guard &>/dev/null; then
54
85
  exit 0
55
86
  fi
56
87
 
88
+ # >>> #4803 BEGIN push-target resolution
89
+ # Everything between these markers is the #4803 fix. Deleting the region
90
+ # restores the pre-fix behaviour (lint whatever directory the hook happens to
91
+ # start in); mx-guard-hook.test.sh builds exactly that mutant and asserts every
92
+ # #4803 test fails against it.
93
+
94
+ # BASE_DIR — the directory the hook itself is standing in. `.cwd` is supplied by
95
+ # the harness on the PreToolUse payload (same field reload-checkpoint.sh reads);
96
+ # it is the session's default working directory, NOT the invoking command's, so
97
+ # it is only ever the right answer for a bare `git push`. $PWD is the fallback
98
+ # when the field is absent.
99
+ BASE_DIR=$(echo "$INPUT" | jq -r '.cwd // empty' 2>/dev/null)
100
+ if [ -z "$BASE_DIR" ] || [ ! -d "$BASE_DIR" ]; then
101
+ BASE_DIR="$PWD"
102
+ fi
103
+
104
+ # Expand only the two path variables the harness sets identically in this
105
+ # subprocess and in the tool command's shell. Anything else stays unexpanded and
106
+ # is reported as unresolvable rather than guessed at.
107
+ mxg_expand_known_vars() {
108
+ local p="$1"
109
+ if [ -n "${CLAUDE_WORKTREE_PATH:-}" ]; then
110
+ p="${p//\$\{CLAUDE_WORKTREE_PATH\}/$CLAUDE_WORKTREE_PATH}"
111
+ p="${p//\$CLAUDE_WORKTREE_PATH/$CLAUDE_WORKTREE_PATH}"
112
+ fi
113
+ if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then
114
+ p="${p//\$\{CLAUDE_PROJECT_DIR\}/$CLAUDE_PROJECT_DIR}"
115
+ p="${p//\$CLAUDE_PROJECT_DIR/$CLAUDE_PROJECT_DIR}"
116
+ fi
117
+ # Literal leading tilde in the command text — expand it ourselves (SC2088 is
118
+ # about tildes we write; this one arrived as data).
119
+ # shellcheck disable=SC2088
120
+ case "$p" in
121
+ "~"|"~/"*) p="${HOME}${p#\~}" ;;
122
+ esac
123
+ printf '%s' "$p"
124
+ }
125
+
126
+ mxg_dequote() {
127
+ local p="$1"
128
+ p="${p%\"}"; p="${p#\"}"
129
+ p="${p%\'}"; p="${p#\'}"
130
+ printf '%s' "$p"
131
+ }
132
+
133
+ # Walk the command's segments in order, tracking the last `cd <path>` seen, and
134
+ # recording EVERY segment that begins a push. A `-C <path>` on a push segment
135
+ # wins over the tracked `cd` (git applies it last). Segment splitting is the same
136
+ # approximation the sibling guards use — it is a guardrail, not a parser, and
137
+ # every ambiguity it cannot settle lands on the loud-block path below rather
138
+ # than on a silent verdict.
139
+ #
140
+ # SF-2 (security review of this PR): the walk used to `break` at the first push
141
+ # segment, so `git -C /treeA push && git -C /treeB push` linted treeA and let
142
+ # treeB through unexamined — the same "verdict without examining the subject"
143
+ # defect #4803 is about, one compound command later. Every push segment is now
144
+ # collected and every distinct toplevel is linted; any failure blocks.
145
+ #
146
+ # SF-1 (same review): remote-push detection used to substring-match `ssh`/`scp`
147
+ # ANYWHERE in the command, and an unresolvable target then exited 0 with no
148
+ # linting while the LOCAL push still ran. A trailing comment was enough:
149
+ # `cd /nonexistent ; git push origin b ` blocked, and the same
150
+ # command plus `# over ssh tunnel` skipped. A remote push is now recognised only
151
+ # when the ssh/scp/container-exec token is the LEAD command of the segment the
152
+ # push belongs to (or of the segment whose still-open quote encloses it, which
153
+ # is the `ssh host "cd X && git push"` form). Everything else fails CLOSED.
154
+ MXG_PUSH_RAWS=() # one entry per push segment: the path text, "" = bare push
155
+ MXG_PUSH_REMOTE=() # "1" iff that push segment runs on another host
156
+ CD_RAW=""
157
+ MXG_IN_QUOTE=0 # quote parity carried across segments
158
+ MXG_REMOTE_CTX=0 # remote-launcher context of the current quoting level
159
+ while IFS= read -r rawseg; do
160
+ seg="${rawseg#"${rawseg%%[![:space:]]*}"}"
161
+ seg="${seg#\(}"; seg="${seg#\{}"
162
+ seg="${seg#"${seg%%[![:space:]]*}"}"
163
+ if [[ "$seg" =~ ^(then|do|else)[[:space:]]+(.*)$ ]]; then
164
+ seg="${BASH_REMATCH[2]}"
165
+ fi
166
+
167
+ # Remote context. Re-evaluated only at the top quoting level: a segment that
168
+ # begins inside a quote opened by an earlier segment inherits that segment's
169
+ # verdict, which is how the push inside `ssh host "..."` is recognised while
170
+ # `ssh host uptime && git push` (quote closed, new lead token `git`) is not.
171
+ MXG_SEG_IN_QUOTE=$MXG_IN_QUOTE
172
+ if [ "$MXG_SEG_IN_QUOTE" -eq 0 ]; then
173
+ MXG_REMOTE_CTX=0
174
+ MXG_LEAD="${seg%%[[:space:]]*}"
175
+ case "$MXG_LEAD" in
176
+ ssh|scp|sftp|rsh) MXG_REMOTE_CTX=1 ;;
177
+ docker|podman|kubectl|oc)
178
+ if [[ "$seg" =~ [[:space:]]exec([[:space:]]|$) ]]; then MXG_REMOTE_CTX=1; fi ;;
179
+ esac
180
+ fi
181
+ MXG_SEG_REMOTE=$MXG_REMOTE_CTX
182
+
183
+ # Quote parity for the NEXT segment. Deliberately naive — an apostrophe inside
184
+ # a word can skew it. Skew can only ever extend a remote context that a lead
185
+ # token already established; with no remote lead the parity is unused and the
186
+ # command still fails closed.
187
+ MXG_Q="${rawseg//[^\"\']/}"
188
+ if [ $(( ${#MXG_Q} % 2 )) -eq 1 ]; then
189
+ MXG_IN_QUOTE=$(( 1 - MXG_IN_QUOTE ))
190
+ fi
191
+
192
+ if [[ "$seg" =~ ^cd[[:space:]]+([^[:space:]]+) ]]; then
193
+ CD_RAW="${BASH_REMATCH[1]}"
194
+ continue
195
+ fi
196
+ if [[ "$seg" =~ $PUSH_RE ]]; then
197
+ MXG_RAW=""
198
+ if [[ "$seg" =~ (^|[[:space:]])-C[[:space:]]+([^[:space:]]+) ]]; then
199
+ MXG_RAW="${BASH_REMATCH[2]}"
200
+ fi
201
+ # A relative `-C` is applied on top of the tracked `cd`, matching git.
202
+ if [ -n "$MXG_RAW" ] && [ -n "$CD_RAW" ]; then
203
+ case "$MXG_RAW" in
204
+ /*|'~'*|'$'*) ;;
205
+ *) MXG_RAW="$CD_RAW/$MXG_RAW" ;;
206
+ esac
207
+ elif [ -z "$MXG_RAW" ]; then
208
+ MXG_RAW="$CD_RAW"
209
+ fi
210
+ MXG_PUSH_RAWS+=("$MXG_RAW")
211
+ MXG_PUSH_REMOTE+=("$MXG_SEG_REMOTE")
212
+ fi
213
+ done < <(printf '%s\n' "$COMMAND" | sed -e 's/&&/\n/g' -e 's/||/\n/g' -e 's/[;&|]/\n/g')
214
+ # printf's trailing newline is deliberate: without it `read` hits EOF on the
215
+ # final segment and the loop body never sees it, which silently drops the `-C`
216
+ # on the common single-segment form `git -C <path> push`.
217
+
218
+ # The whole-command matcher fired but no segment did — the push is in a form the
219
+ # splitter does not model. Treat it as a bare push against the hook's own tree
220
+ # rather than skipping: linting something is the fail-closed side here.
221
+ if [ "${#MXG_PUSH_RAWS[@]}" -eq 0 ]; then
222
+ MXG_PUSH_RAWS=("")
223
+ MXG_PUSH_REMOTE=(0)
224
+ fi
225
+
226
+ BASE_TOP=$(git -C "$BASE_DIR" rev-parse --show-toplevel 2>/dev/null) || BASE_TOP="$BASE_DIR"
227
+
228
+ # Resolve every push segment. Unresolvable + not remote = loud block; the hook
229
+ # never falls back to linting whatever tree it happens to be standing in.
230
+ MXG_DIRS=()
231
+ for MXG_I in "${!MXG_PUSH_RAWS[@]}"; do
232
+ TARGET_RAW="${MXG_PUSH_RAWS[$MXG_I]}"
233
+
234
+ if [ "${MXG_PUSH_REMOTE[$MXG_I]}" = "1" ]; then
235
+ echo "⚠ mx-guard: a push in this command runs on a remote host — skipping local validation for it." >&2
236
+ continue
237
+ fi
238
+
239
+ TARGET_DIR=""
240
+ UNRESOLVED=""
241
+ if [ -z "$TARGET_RAW" ]; then
242
+ # Bare `git push` — the hook's own directory really is the push target.
243
+ TARGET_DIR="$BASE_DIR"
244
+ else
245
+ MXG_CAND=$(mxg_expand_known_vars "$(mxg_dequote "$TARGET_RAW")")
246
+ case "$MXG_CAND" in
247
+ *'$'*|*'`'*|*'*'*|*'?'*)
248
+ UNRESOLVED="it contains a shell expression this hook cannot expand" ;;
249
+ *)
250
+ case "$MXG_CAND" in
251
+ /*) ;;
252
+ *) MXG_CAND="$BASE_DIR/$MXG_CAND" ;;
253
+ esac
254
+ if [ ! -d "$MXG_CAND" ]; then
255
+ UNRESOLVED="no such directory on this machine"
256
+ elif ! TARGET_DIR=$(git -C "$MXG_CAND" rev-parse --show-toplevel 2>/dev/null); then
257
+ UNRESOLVED="it is not inside a git work tree"
258
+ fi ;;
259
+ esac
260
+ fi
261
+
262
+ if [ -n "$UNRESOLVED" ]; then
263
+ {
264
+ echo "mx-guard: push BLOCKED — cannot identify the tree this push targets."
265
+ echo ""
266
+ echo " the push names: $TARGET_RAW"
267
+ echo " problem: $UNRESOLVED"
268
+ echo " would have run: mx-guard check in $BASE_DIR"
269
+ echo ""
270
+ echo " Linting $BASE_DIR would produce a verdict on a tree that is not the"
271
+ echo " one being pushed — a pass would mean nothing and a failure would be"
272
+ echo " someone else's. Re-run the push with a literal absolute path, e.g."
273
+ echo " git -C /abs/path/to/worktree push <remote> <branch>"
274
+ } >&2
275
+ exit 2
276
+ fi
277
+
278
+ if [ "$TARGET_DIR" != "$BASE_TOP" ]; then
279
+ echo "mx-guard: push targets $TARGET_DIR (shell cwd is $BASE_TOP) — linting the push target." >&2
280
+ fi
281
+
282
+ MXG_SEEN=0
283
+ for MXG_D in ${MXG_DIRS[@]+"${MXG_DIRS[@]}"}; do
284
+ [ "$MXG_D" = "$TARGET_DIR" ] && MXG_SEEN=1
285
+ done
286
+ [ "$MXG_SEEN" -eq 0 ] && MXG_DIRS+=("$TARGET_DIR")
287
+ done
288
+
289
+ # Every push in the command was remote — nothing local to lint.
290
+ if [ "${#MXG_DIRS[@]}" -eq 0 ]; then
291
+ exit 0
292
+ fi
293
+
57
294
  # Run mx-guard check (change-aware — only checks files on current branch).
58
295
  # Route its output to stderr so its findings are visible on the block path.
59
296
  {
@@ -61,8 +298,31 @@ fi
61
298
  echo ""
62
299
  } >&2
63
300
 
301
+ # Lint every distinct target but the last here; the last is left to the shared
302
+ # `mx-guard check` below, which is the line the mutation harness deletes the
303
+ # #4803 region around. MXG_PRIOR_FAIL carries the earlier verdicts past the
304
+ # region boundary so "any target fails => push blocked" holds.
305
+ MXG_PRIOR_FAIL=0
306
+ MXG_LAST=$(( ${#MXG_DIRS[@]} - 1 ))
307
+ for MXG_I in "${!MXG_DIRS[@]}"; do
308
+ [ "$MXG_I" -eq "$MXG_LAST" ] && break
309
+ if ! ( cd "${MXG_DIRS[$MXG_I]}" && mx-guard check >&2 ); then
310
+ MXG_PRIOR_FAIL=1
311
+ fi
312
+ done
313
+ TARGET_DIR="${MXG_DIRS[$MXG_LAST]}"
314
+
315
+ if ! cd "$TARGET_DIR"; then
316
+ echo "mx-guard: push BLOCKED — could not enter $TARGET_DIR to validate it." >&2
317
+ exit 2
318
+ fi
319
+ # <<< #4803 END push-target resolution
320
+
64
321
  mx-guard check >&2
65
322
  GUARD_EXIT=$?
323
+ if [ "${MXG_PRIOR_FAIL:-0}" -ne 0 ]; then
324
+ GUARD_EXIT=1
325
+ fi
66
326
 
67
327
  if [ $GUARD_EXIT -ne 0 ]; then
68
328
  {
@@ -8,6 +8,10 @@
8
8
  # `reason` reinjects into the model: continue with unblocked work, or — if a
9
9
  # roleguide stop-condition genuinely applies — mint a verified pause token.
10
10
  #
11
+ # NOT IDLE (#4802). A session that has dispatched async subagents which have not
12
+ # reported back is NOT parking work, and is not challenged — see section 3, which
13
+ # also explains why that stand-down is bounded rather than open-ended.
14
+ #
11
15
  # POSITION. Registered in the Stop chain AFTER coordination-midsession-drain.sh.
12
16
  # The drain hook may already emit a Stop-block this turn (queued P0-P2 messages);
13
17
  # when it does we must NOT also block. The two hooks share a per-turn sentinel:
@@ -33,6 +37,14 @@
33
37
  # with no matching mint line in session-pause.jsonl is a detectable bypass at
34
38
  # baseline review. Same posture as git-mutation-guard (guardrail, not access
35
39
  # control).
40
+ #
41
+ # ...but the bypasses must stay NAMED and LOGGED. The subagent stand-down in
42
+ # section 3 is not a second, silent one: its evidence must be a harness-authored
43
+ # record shape (not prose the session wrote itself), and its bound cannot be
44
+ # extended past a hard ceiling by an env var. Both constraints were added after
45
+ # the security review of this change (SF-5) found the gate could be switched off
46
+ # by the party it guards. Precedent: 6f934aaee removed the same affordance from
47
+ # the override audit log.
36
48
 
37
49
  trap 'exit 0' ERR
38
50
  set -u
@@ -121,7 +133,132 @@ if [ -f "$TOKEN_FILE" ] && [ ! -L "$TOKEN_FILE" ]; then
121
133
  esac
122
134
  fi
123
135
 
124
- # ── 3. Throttle: challenge at most once per 30 min per worktree. ─────────────
136
+ # ── 3. Outstanding dispatched subagent work → stand down (bounded). ──────────
137
+ #
138
+ # WHY (#4802). The gate exists to catch a session PARKING unblocked work. It could
139
+ # not tell that apart from a session WAITING ON WORK IT HAD ALREADY DISPATCHED,
140
+ # because it resolved "idle" from the fact of a Stop event alone. Async subagents
141
+ # return their tool result in ~30ms ("Async agent launched successfully, agentId:
142
+ # X") and keep running, so the parent's turn ends — and the Stop chain runs — while
143
+ # its teammates are working. Measured on this worktree's own transcript: all 10
144
+ # challenges this session landed while 1-4 dispatched agents had not reported back.
145
+ #
146
+ # WHAT IS ACTUALLY KNOWABLE. The harness records DISPATCH and COMPLETION, not
147
+ # liveness. Both are in the parent transcript, whose path the Stop payload supplies
148
+ # as .transcript_path (established in production, not assumed: delegation-audit.sh
149
+ # reads only that field and has emitted real per-session tool-call counts):
150
+ # dispatch — a tool_result containing "Async agent launched successfully" with
151
+ # "agentId: <id>"; a SendMessage tool_use re-engages agent .input.to
152
+ # completion — a queue-operation/enqueue record carrying
153
+ # <task-notification><task-id><id></task-id>, which the harness
154
+ # emits "each time this agent stops with no live background children"
155
+ # Replaying those in order gives OUTSTANDING DISPATCHED WORK exactly. It does NOT
156
+ # give liveness: an agent that died without notifying (one did on this worktree —
157
+ # agent a20479ad, killed by an API ENOTFOUND at 19:56 and never notified) stays
158
+ # outstanding forever, and no harness-recorded fact distinguishes it from a slow
159
+ # agent. Nothing here guesses at that difference from file mtimes or process state.
160
+ #
161
+ # SO THE STAND-DOWN IS BOUNDED, and the bound also uses only recorded events, no
162
+ # clocks: a stand-down streak that resets whenever the completion total INCREASES
163
+ # between stops. A working team keeps reporting completions, so the streak keeps
164
+ # resetting and the gate stays quiet. A session whose outstanding agents have all
165
+ # stalled produces no new completions, the streak reaches the cap, and the gate
166
+ # challenges anyway — with wording that names the outstanding agents. The guard is
167
+ # not weakened: it always speaks eventually, and it never goes silent on a session
168
+ # that is genuinely parked.
169
+ #
170
+ # Fail direction is CHALLENGE: no transcript, unreadable, missing jq/awk, or an
171
+ # oversized file → skip this section entirely and behave exactly as before.
172
+ SUBAGENT_STATE="${STATE_DIR}/${WORKTREE_NAME}.subagents"
173
+ SUB_LIVE=0
174
+ SUB_STALLED=0
175
+ if [ "${MX_IDLE_GATE_SUBAGENT_CHECK_DISABLED:-}" != "1" ]; then
176
+ TRANSCRIPT_PATH="$(printf '%s' "$INPUT" | jq -r '.transcript_path // empty' 2>/dev/null || echo '')"
177
+ # Bound the work: the check runs inside a <=5s hook budget. Typical transcripts
178
+ # here are 5-8MB and scan in ~0.1s; anything beyond the cap is skipped rather
179
+ # than risking the budget (skip == challenge, the safe direction).
180
+ TSIZE=0
181
+ if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ] && [ ! -L "$TRANSCRIPT_PATH" ]; then
182
+ TSIZE="$(stat -c %s "$TRANSCRIPT_PATH" 2>/dev/null || stat -f %z "$TRANSCRIPT_PATH" 2>/dev/null || echo 0)"
183
+ fi
184
+ MAX_SCAN_BYTES="${MX_IDLE_GATE_MAX_TRANSCRIPT_BYTES:-67108864}"
185
+ case "$TSIZE" in ''|*[!0-9]*) TSIZE=0 ;; esac
186
+ if [ "$TSIZE" -gt 0 ] && [ "$TSIZE" -le "$MAX_SCAN_BYTES" ] && command -v awk >/dev/null 2>&1; then
187
+ # One jq pass emits an ordered event stream (L launch / S re-engage / D done);
188
+ # awk replays it. `tostring` is used for the two text-embedded ids because they
189
+ # live inside free-text tool results and notification bodies, not typed fields —
190
+ # but it is applied to a SELECTED record shape, never to the whole record.
191
+ #
192
+ # SF-5 (security review of this PR). The launch clause used to test the
193
+ # stringification of ANY record, so a message merely DISCUSSING the hook —
194
+ # quoting the marker text and an id-shaped token — registered as a live agent
195
+ # and stood the gate down. That let the gate be silenced by the party it
196
+ # guards, writing prose. The marker must now come from a tool_result content
197
+ # block: a record shape the model cannot author, only the harness can. Same
198
+ # no-suppression principle as 6f934aaee, which removed the equivalent
199
+ # affordance from the override audit log. The completion clause was already
200
+ # shape-typed (queue-operation/enqueue) and is unchanged.
201
+ SUB_SCAN="$(jq -r '
202
+ . as $r | ($r|tostring) as $s
203
+ | ($r.message.content[]?
204
+ | select(type=="object" and .type=="tool_result")
205
+ | tostring
206
+ | select(test("Async agent launched successfully"))
207
+ | [scan("agentId: ([a-z0-9]{6,})")][]
208
+ | "L \(.[0])"),
209
+ (if ($r.type=="queue-operation" and $r.operation=="enqueue" and ($s|test("<task-notification>")))
210
+ then ($s | [scan("<task-id>([a-z0-9]{6,})</task-id>")][] | "D \(.[0])") else empty end),
211
+ ($r.message.content[]? | select(.type=="tool_use" and .name=="SendMessage") | .input.to // empty | "S \(.)")
212
+ ' "$TRANSCRIPT_PATH" 2>/dev/null \
213
+ | awk '{ if ($1=="D") { live[$2]=0; done++ } else { live[$2]=1 } }
214
+ END { n=0; for (k in live) n+=live[k]; printf "%d %d\n", n, done }' 2>/dev/null || echo '')"
215
+ SUB_LIVE="${SUB_SCAN%% *}"
216
+ SUB_DONE="${SUB_SCAN##* }"
217
+ case "$SUB_LIVE" in ''|*[!0-9]*) SUB_LIVE=0 ;; esac
218
+ case "$SUB_DONE" in ''|*[!0-9]*) SUB_DONE=0 ;; esac
219
+ fi
220
+
221
+ if [ "$SUB_LIVE" -gt 0 ]; then
222
+ PREV_DONE=0; PREV_STREAK=0
223
+ if [ -f "$SUBAGENT_STATE" ] && [ ! -L "$SUBAGENT_STATE" ]; then
224
+ read -r PREV_DONE PREV_STREAK < "$SUBAGENT_STATE" 2>/dev/null || { PREV_DONE=0; PREV_STREAK=0; }
225
+ case "$PREV_DONE" in ''|*[!0-9]*) PREV_DONE=0 ;; esac
226
+ case "$PREV_STREAK" in ''|*[!0-9]*) PREV_STREAK=0 ;; esac
227
+ fi
228
+ # Progress = at least one MORE completion than at the last stop. Purely a
229
+ # comparison of harness-recorded totals; no wall-clock reasoning.
230
+ if [ "$SUB_DONE" -gt "$PREV_DONE" ]; then
231
+ STREAK=1
232
+ else
233
+ STREAK=$(( PREV_STREAK + 1 ))
234
+ fi
235
+ printf '%s %s\n' "$SUB_DONE" "$STREAK" > "$SUBAGENT_STATE" 2>/dev/null || true
236
+ # SF-5 (security review of this PR). The env override had no ceiling, so
237
+ # `MX_IDLE_GATE_SUBAGENT_MAX_STANDDOWNS=99999` turned the bounded stand-down
238
+ # into an unbounded one — the gate silenced permanently, by the session it
239
+ # guards, with one exported variable. The override may only ever make the
240
+ # gate SPEAK SOONER: it is clamped to the hard ceiling below, and a
241
+ # non-numeric or negative value falls back to the default. The kill switch
242
+ # (MX_SESSION_IDLE_GATE_DISABLED) remains the documented, LOGGED way to turn
243
+ # the gate off; this knob is not a second one.
244
+ MAX_STANDDOWNS_CEILING=5
245
+ MAX_STANDDOWNS="${MX_IDLE_GATE_SUBAGENT_MAX_STANDDOWNS:-3}"
246
+ case "$MAX_STANDDOWNS" in ''|*[!0-9]*) MAX_STANDDOWNS=3 ;; esac
247
+ if [ "$MAX_STANDDOWNS" -gt "$MAX_STANDDOWNS_CEILING" ]; then
248
+ MAX_STANDDOWNS="$MAX_STANDDOWNS_CEILING"
249
+ fi
250
+ if [ "$STREAK" -le "$MAX_STANDDOWNS" ]; then
251
+ log_decision standdown "subagents-live-${SUB_LIVE}"
252
+ exit 0
253
+ fi
254
+ # Streak exhausted with no new completions — challenge, and say why.
255
+ SUB_STALLED=1
256
+ else
257
+ rm -f "$SUBAGENT_STATE" 2>/dev/null || true
258
+ fi
259
+ fi
260
+
261
+ # ── 4. Throttle: challenge at most once per 30 min per worktree. ─────────────
125
262
  # An agent that was just challenged and chose to stop anyway is NOT re-nagged
126
263
  # every turn; the repeated-stop pattern surfaces in the idle-gate log instead.
127
264
  THROTTLE_SECS="${MX_IDLE_GATE_THROTTLE_SECS:-1800}"
@@ -135,9 +272,19 @@ if [ -e "$LAST_FILE" ] && [ ! -L "$LAST_FILE" ]; then
135
272
  fi
136
273
  [ -L "$LAST_FILE" ] && { log_decision standdown throttle; exit 0; } # symlinked throttle path → refuse to write through it
137
274
 
138
- # ── 4. Challenge: record the throttle stamp, log, emit ONE Stop-block. ───────
275
+ # ── 5. Challenge: record the throttle stamp, log, emit ONE Stop-block. ───────
139
276
  touch "$LAST_FILE" 2>/dev/null || true
140
277
 
278
+ if [ "$SUB_STALLED" = "1" ]; then
279
+ # Outstanding dispatched work, but nothing has reported back across the last
280
+ # several stops. Do NOT assert the agents are dead — the harness cannot tell us
281
+ # that. Name the fact and hand the judgement to the session.
282
+ log_decision challenge "subagents-no-progress-${SUB_LIVE}"
283
+ REASON="Session is stopping with ${SUB_LIVE} dispatched agent(s) that have not reported back, and no agent has reported back across the last few stops either. Either they are still working — in which case check on them rather than stopping — or one has stalled and its work is silently parked. If a roleguide stop-condition genuinely applies, run: mx-agent session pause --reason <code> --ref <verifiable-artifact>."
284
+ printf '%s' "$REASON" | jq -Rs '{decision:"block", reason:.}'
285
+ exit 0
286
+ fi
287
+
141
288
  # Layer 3-minimal logging: one line per challenge (local JSONL, best-effort).
142
289
  log_decision challenge idle
143
290
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memnexus-ai/mx-agent-cli",
3
- "version": "0.1.253",
3
+ "version": "0.1.254",
4
4
  "description": "CLI for creating and managing AI agent teams",
5
5
  "type": "module",
6
6
  "bin": {