@memnexus-ai/mx-agent-cli 0.1.293 → 0.1.294

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.
@@ -161,6 +161,257 @@ MemNexus. Reconstruct context from the files, activity and references above."
161
161
  # Truncate total content
162
162
  CONTENT=$(echo "$CONTENT" | head -c 6000)
163
163
 
164
+ # ── 4b. Resolve project scope (codeContext) ──────────────────────────────
165
+ # Auto-captured memories carried no scope at all, so they leaked into every
166
+ # team's scoped searches and polluted build_context (#5158, #4957). PR #3281
167
+ # fixed that for the commit path only; this is the same resolution for the
168
+ # capture hooks, using the same sources and the same precedence. Ported from
169
+ # the reviewed customer hook cli/hooks/capture-precompact.sh — port from that
170
+ # file's FINAL state, not from an earlier draft: two of the properties below
171
+ # were blocking security findings.
172
+ #
173
+ # Mirrors resolveCommitCodeContext() in cli/src/lib/commit-context/code-context.ts:
174
+ # 1. MX_CODE_CONTEXT env var — operator-controlled, higher trust. It wins over
175
+ # the file (CWE-345): a checked-in file from an untrusted clone must not
176
+ # override the scope the operator set explicitly.
177
+ # 2. <projectRoot>/.mx-code-context.json — repo-controlled, lower trust.
178
+ # 3. Neither present or neither usable -> NO scope. The memory is created
179
+ # unlabeled, exactly as it was before this block existed. No default is
180
+ # invented: a guessed label is invisible to the scope that should see it
181
+ # and visible to one that should not, which is worse than no label.
182
+ #
183
+ # Every command in this block must end up returning 0. The EXIT/ERR trap set in
184
+ # section 2 exits the hook, so a non-zero status here would discard the
185
+ # pre-compaction context over a missing config file — a far worse regression
186
+ # than the unlabeled memories this fixes. The absent-config path is the common
187
+ # one today.
188
+ CODE_CONTEXT_MAX_BYTES=65536
189
+
190
+ # Walk up for the git project root, mirroring findProjectRoot() in
191
+ # cli/src/lib/commit-context/local-cache.ts. `-e`, not `-d`: inside a git
192
+ # worktree `.git` is a FILE, and the worktree root — not the main repo — is the
193
+ # project root (the TS uses fs.existsSync, which makes no such distinction).
194
+ # In the fleet this is the ONLY case that occurs: every agent works in a
195
+ # worktree, so `-d` would silently resolve no scope on every machine.
196
+ find_project_root() { # <start-dir> -> project root on stdout, or nothing
197
+ local dir
198
+ dir=$(cd "$1" 2>/dev/null && pwd -P) || return 0
199
+ while [[ -n "$dir" && "$dir" != "/" ]]; do
200
+ if [[ -e "$dir/.git" ]]; then
201
+ printf '%s' "$dir"
202
+ return 0
203
+ fi
204
+ dir=$(dirname "$dir" 2>/dev/null) || return 0
205
+ done
206
+ return 0
207
+ }
208
+
209
+ # Keep only the six known keys whose values are non-empty strings, cap each,
210
+ # and emit NOTHING when nothing usable remains — so an empty or scope-free
211
+ # object is never passed as if it were a label. Malformed JSON makes jq exit
212
+ # non-zero with no output, which lands in the same "no scope" branch.
213
+ #
214
+ # `-s` (slurp) is load-bearing, not a style choice. jq accepts a STREAM of JSON
215
+ # documents: without `-s` the filter runs once per document and `jq -c` prints
216
+ # one line each, so a config holding two concatenated or newline-separated
217
+ # objects produced a MULTI-LINE string that was passed verbatim as one
218
+ # --code-context argument. parseCodeContextFlag() (cli/src/commands/memories.ts)
219
+ # JSON.parse()s it and process.exit(1)s before any network call. In THIS hook
220
+ # that loss is unrecoverable: the transcript the capture would have summarized
221
+ # is compacted away immediately afterwards. The `!= "{}"` guard below did not
222
+ # catch it either: `{"zzz":1}{"team":"b"}` normalizes to the two lines
223
+ # `{}` + `{"team":"b"}`, and that whole string is not `{}`. Slurping into an
224
+ # array and taking the first element means exactly one line can ever be emitted.
225
+ #
226
+ # The cap is 100 CODEPOINTS, deliberately below the server's 200. The server's
227
+ # CodeContextSchema uses Zod `.max(200)`, which counts UTF-16 code units, while
228
+ # jq's `[0:N]` slices by codepoint. Every astral-plane character (emoji, CJK
229
+ # extensions, mathematical alphanumerics) is 1 codepoint but 2 UTF-16 units, so
230
+ # a `[0:200]` cap emitted values of up to 400 units — over the server maximum,
231
+ # a 400 from the API, and the same silent capture loss. Since no codepoint
232
+ # exceeds 2 UTF-16 units, 100 codepoints can never exceed 200 units. Scope
233
+ # labels are short names (product/team/service); the extra truncation is
234
+ # unreachable in practice, and truncating is recoverable where a rejected
235
+ # request is not. Do NOT "restore" this to 200.
236
+ normalize_code_context() { # JSON on stdin -> normalized JSON object, or nothing
237
+ local out
238
+ out=$(jq -s -c '
239
+ (.[0] // {}) as $raw
240
+ | if ($raw | type) == "object" then
241
+ reduce ("product","repo","service","component","team","role") as $k ({};
242
+ if ($raw[$k] | type) == "string" and ($raw[$k] | length) > 0
243
+ then .[$k] = ($raw[$k][0:100])
244
+ else . end)
245
+ else {} end
246
+ ' 2>/dev/null) || return 0
247
+ # The newline test is belt-and-braces: `-s` already guarantees one document,
248
+ # and jq -c escapes newlines inside string values. Nothing multi-line may ever
249
+ # reach --code-context again, whatever the filter above does.
250
+ if [[ -n "$out" && "$out" != "{}" && "$out" != "null" && "$out" != *$'\n'* ]]; then
251
+ printf '%s' "$out"
252
+ fi
253
+ return 0
254
+ }
255
+
256
+ CODE_CONTEXT_JSON=""
257
+
258
+ # 1. Env var. Tested for presence only — the value is never echoed or logged.
259
+ if [[ -n "${MX_CODE_CONTEXT:-}" ]]; then
260
+ CODE_CONTEXT_JSON=$(printf '%s' "$MX_CODE_CONTEXT" | normalize_code_context) || CODE_CONTEXT_JSON=""
261
+ fi
262
+
263
+ # 2. Repo file — consulted only when the env var yielded nothing usable.
264
+ if [[ -z "$CODE_CONTEXT_JSON" ]]; then
265
+ # ORDER IS LOAD-BEARING: harness-provided project dir, then the worktree path,
266
+ # then the cwd. Each source is TRIED IN TURN, and the transcript's directory
267
+ # is not a source at all. Both properties are corrections to earlier forms and
268
+ # both are pinned by the suite; read this before rewriting the expression.
269
+ #
270
+ # WHY EACH SOURCE IS TRIED SEPARATELY. The earlier form collapsed all three
271
+ # into ONE call: `find_project_root "${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-$(pwd)}}"`.
272
+ # `:-` substitutes only when a variable is UNSET or EMPTY — never when it is
273
+ # set to something useless. So a CLAUDE_PROJECT_DIR that is set but resolves
274
+ # to no repository (a stale path, a deleted directory, a path outside any
275
+ # checkout) consumed the single attempt and the cwd was NEVER consulted.
276
+ # Measured: CLAUDE_PROJECT_DIR=/proc and =/nonexistent/zz each produced
277
+ # {"product":"home","team":"DOTFILES-WRONG-SCOPE"} from the $HOME config.
278
+ # The loop below consults the next source instead, which `:-` cannot express.
279
+ #
280
+ # WHY THE TRANSCRIPT DIRECTORY IS NOT A SOURCE. It has no legitimate resolving
281
+ # power, and the reason is DEPTH-INDEPENDENT — do not restate it as a claim
282
+ # about the transcript's nesting. An earlier version of this comment argued
283
+ # from a flat ~/.claude/projects/<slug>/<id>.jsonl layout and enumerated the
284
+ # three directories a walk could reach. That premise is false here. Measured
285
+ # on this machine: transcripts sit at BOTH depth 2 and depth 4 under
286
+ # ~/.claude/projects — 310 at depth 2, 5621 deeper — so any argument of the
287
+ # form "the walk can only ever reach these three named directories" does not
288
+ # hold. The premise that does hold, and that does not depend on depth:
289
+ #
290
+ # .git anywhere under ~/.claude, any depth: 0 (also no .hg, no .svn)
291
+ #
292
+ # An upward walk from any transcript directory traverses only directories
293
+ # inside ~/.claude, none of which carries a repository marker, so it cannot
294
+ # terminate inside that subtree at any depth. That leaves $HOME as its ONLY
295
+ # reachable non-empty outcome, which is precisely the defect this block exists
296
+ # to prevent: keeping dotfiles in git is common, so $HOME/.git exists on many
297
+ # machines, and with $HOME/.mx-code-context.json present every capture from
298
+ # every worktree on the machine was labelled from the home config. A
299
+ # confidently wrong label is worse than no label — invisible to the scope that
300
+ # should see it, visible to one that must not. Do not reintroduce it.
301
+ #
302
+ # CAVEAT, stated because this is a claim about a directory OUTSIDE this
303
+ # repository: it could stop being true, and nothing in this codebase would
304
+ # notice if a repository ever appeared under ~/.claude. Removing the leg does
305
+ # not depend on the caveat holding — the leg is simply gone — but any future
306
+ # argument to reinstate it must re-measure rather than cite this line.
307
+ #
308
+ # WHY $HOME IS REFUSED OUTRIGHT, AND WHY BOTH SIDES ARE CANONICALIZED. Belt
309
+ # and braces for the residual where the cwd itself is $HOME or a directory
310
+ # beneath it whose nearest .git is $HOME's. It also closes a consequence that
311
+ # is easy to miss: CC_ROOT is the basis of the symlink containment test below,
312
+ # so a CC_ROOT of $HOME silently widens "contained in the project" to
313
+ # "anywhere in the home directory", and $HOME/.mx-code-context.json symlinked
314
+ # to any other file under $HOME would resolve and be used. The cost is not
315
+ # supporting a user whose real project IS their home directory; that is the
316
+ # same confusion we want rejected.
317
+ #
318
+ # The comparison MUST canonicalize $HOME. CC_ROOT always arrives canonical —
319
+ # find_project_root builds it with `cd … && pwd -P` — while $HOME arrives
320
+ # verbatim from the environment, so a literal `==` against "$HOME" misses on
321
+ # every spelling that is not byte-identical. Four spellings were measured
322
+ # leaking the home label through a symlinked $HOME/.mx-code-context.json: a
323
+ # trailing slash ("/home/x/"), a "/." suffix ("/home/x/."), $HOME set to a
324
+ # SYMLINK to the real home, and a cwd reached through that same symlink.
325
+ # Symlinked home directories are routine — macOS firmlinks, NFS corporate
326
+ # homes, container images mapping /home/user onto another volume — so the
327
+ # trigger is a normal configuration and the miss is silent: the refusal does
328
+ # not fire, and the containment widening above returns with it. `cd … && pwd -P`
329
+ # is the same primitive find_project_root uses and handles all four in one step.
330
+ #
331
+ # HOME unset, or pointing at nothing, leaves _home_real empty and no refusal
332
+ # fires. That is unchanged from the previous `-n "${HOME:-}"` guard, not a
333
+ # regression. The `|| _home_real=""` is REQUIRED, not decorative: without it a
334
+ # failing `cd` leaves the assignment non-zero and last on its path, which fires
335
+ # the ERR trap and abandons the capture.
336
+ #
337
+ # ERR-TRAP SAFETY — verified, not assumed, because a regression here fires
338
+ # `trap 'exit 0' ERR` and silently abandons the capture. The loop body's only
339
+ # status-bearing statement is a `$(...)` assignment of find_project_root, which
340
+ # returns 0 on every path including the `cd` failure. The break is written as
341
+ # an `if` block for the same reason the $HOME refusal is. The earlier one-line
342
+ # form `[[ -n "$CC_ROOT" ]] && break` returns 1 whenever the loop CONTINUES —
343
+ # an earlier version of this comment claimed it returned 0, which was wrong. It
344
+ # was safe only POSITIONALLY: as a non-final command of an `&&` list it is
345
+ # exempt under the errexit rules, so nothing fired. That safety depends on
346
+ # where the statement sits and would evaporate the moment this loop became the
347
+ # last statement of a function: the function would return 1 and any `$(...)`
348
+ # call of it would fire the trap. The `if` form returns 0 and removes the
349
+ # positional dependence.
350
+ #
351
+ # The same reasoning is why the $HOME refusal is an `if` block ON PURPOSE: the
352
+ # one-line `[[ "$CC_ROOT" == "$_home_real" ]] && CC_ROOT=""` returns 1 when the
353
+ # test is false, and was measured firing the ERR trap when it landed last in an
354
+ # enclosing block. `pwd 2>/dev/null` keeps a deleted cwd from printing "error
355
+ # retrieving current directory" onto the hook's real stderr. This safety comes
356
+ # from find_project_root always returning 0, not from this hook omitting
357
+ # `set -E`, so it survives someone adding `set -E` later. Do not introduce a
358
+ # bare command on this path.
359
+ CC_ROOT=""
360
+ for _cand in "${CLAUDE_PROJECT_DIR:-}" "${CLAUDE_WORKTREE_PATH:-}" "$(pwd 2>/dev/null)"; do
361
+ [[ -n "$_cand" ]] || continue
362
+ CC_ROOT=$(find_project_root "$_cand")
363
+ if [[ -n "$CC_ROOT" ]]; then break; fi
364
+ done
365
+ _home_real=$(cd "${HOME:-/nonexistent}" 2>/dev/null && pwd -P) || _home_real=""
366
+ if [[ -n "$_home_real" && "$CC_ROOT" == "$_home_real" ]]; then
367
+ CC_ROOT=""
368
+ fi
369
+ CC_FILE="${CC_ROOT}/.mx-code-context.json"
370
+ if [[ -n "$CC_ROOT" ]]; then
371
+ # CWE-59. `-f`, `-r` and the read all follow symlinks, so a repo could check
372
+ # in `.mx-code-context.json` as a symlink to any file on the machine and the
373
+ # six allowlisted keys of it would be uploaded to MemNexus. Resolve the path
374
+ # and require the result to stay inside the project root. Read through the
375
+ # RESOLVED path, so the link is not traversed a second time.
376
+ CC_REAL=$(realpath "$CC_FILE" 2>/dev/null || printf '')
377
+ if [[ -n "$CC_REAL" && "$CC_REAL" == "$CC_ROOT"/* && -f "$CC_REAL" && -r "$CC_REAL" ]]; then
378
+ # One open, bounded at the source (same 64KB bound as the TS resolver).
379
+ # The previous form size-checked with `wc -c` and then re-opened for jq:
380
+ # two opens on a path an untrusted repo controls, so a concurrent writer
381
+ # could present a small file to `wc` and a huge one to `jq` (TOCTOU) on a
382
+ # hot path. `head -c` bounds the read itself, which changes >64KB from
383
+ # "skipped" to "truncated, then rejected as invalid JSON" — the same
384
+ # observable outcome, no scope.
385
+ #
386
+ # `2>/dev/null` precedes the input redirect ON PURPOSE. Redirections apply
387
+ # left to right, so with `<"$CC_REAL" 2>/dev/null` a file that turned
388
+ # unreadable between the `-r` test and the open makes bash print the full
389
+ # path and "Permission denied" to the hook's REAL stderr, before the
390
+ # discard takes effect. Verified: reversing these two words reintroduces
391
+ # that leak. Do not reorder.
392
+ #
393
+ # The bytes are PIPED into jq, never routed through a variable. Bash
394
+ # strips NUL bytes out of command-substitution output and warns while
395
+ # doing it — from the parent shell reading the substitution, so the
396
+ # `2>/dev/null` above does not suppress that warning. Via a variable,
397
+ # `{"team":"a<NUL>b"}` printed a warning naming this script and line to
398
+ # the hook's real stderr, and then RESOLVED to team "ab": input the file
399
+ # does not contain, silently repaired before validation instead of
400
+ # rejected by it. Piping keeps the NUL inside jq, which rejects the
401
+ # document as malformed. Do not reintroduce an intermediate variable.
402
+ CODE_CONTEXT_JSON=$(head -c "$CODE_CONTEXT_MAX_BYTES" 2>/dev/null <"$CC_REAL" | normalize_code_context) || CODE_CONTEXT_JSON=""
403
+ fi
404
+ fi
405
+ fi
406
+
407
+ # Nothing resolved -> pass nothing at all, so the create command line is
408
+ # byte-identical to the pre-scope version. The `[@]+` guard keeps an empty array
409
+ # safe to expand under `set -u` on bash < 4.4.
410
+ CODE_CONTEXT_ARGS=()
411
+ if [[ -n "$CODE_CONTEXT_JSON" ]]; then
412
+ CODE_CONTEXT_ARGS=(--code-context "$CODE_CONTEXT_JSON")
413
+ fi
414
+
164
415
  # ── 5. Verbatim-transcript guard (fail-closed, fail-loud) ───────────────
165
416
  #
166
417
  # SCOPE — TEXT BLOCKS ONLY. This guard re-extracts
@@ -236,6 +487,7 @@ if mx_verbatim_guard "$TRANSCRIPT_PATH" "$CONTENT"; then
236
487
  --conversation-id "NEW" \
237
488
  --content "$CONTENT" \
238
489
  --topics "auto-captured,context-compaction" \
490
+ "${CODE_CONTEXT_ARGS[@]+"${CODE_CONTEXT_ARGS[@]}"}" \
239
491
  >/dev/null 2>&1 || true
240
492
  fi
241
493
 
@@ -244,6 +244,255 @@ fi
244
244
  # Truncate
245
245
  CONTENT=$(echo "$CONTENT" | head -c 5000)
246
246
 
247
+ # ── 4b. Resolve project scope (codeContext) ──────────────────────────────
248
+ # Auto-captured memories carried no scope at all, so they leaked into every
249
+ # team's scoped searches and polluted build_context (#5158, #4957). PR #3281
250
+ # fixed that for the commit path only; this is the same resolution for the
251
+ # capture hooks, using the same sources and the same precedence. Ported from
252
+ # the reviewed customer hook cli/hooks/capture-session-end.sh — port from that
253
+ # file's FINAL state, not from an earlier draft: two of the properties below
254
+ # were blocking security findings.
255
+ #
256
+ # Mirrors resolveCommitCodeContext() in cli/src/lib/commit-context/code-context.ts:
257
+ # 1. MX_CODE_CONTEXT env var — operator-controlled, higher trust. It wins over
258
+ # the file (CWE-345): a checked-in file from an untrusted clone must not
259
+ # override the scope the operator set explicitly.
260
+ # 2. <projectRoot>/.mx-code-context.json — repo-controlled, lower trust.
261
+ # 3. Neither present or neither usable -> NO scope. The memory is created
262
+ # unlabeled, exactly as it was before this block existed. No default is
263
+ # invented: a guessed label is invisible to the scope that should see it
264
+ # and visible to one that should not, which is worse than no label.
265
+ #
266
+ # Every command in this block must end up returning 0. The EXIT/ERR trap set in
267
+ # section 3 exits the hook, so a non-zero status here would abandon the capture
268
+ # over a missing config file — a far worse regression than the unlabeled
269
+ # memories this fixes. The absent-config path is the common one today.
270
+ CODE_CONTEXT_MAX_BYTES=65536
271
+
272
+ # Walk up for the git project root, mirroring findProjectRoot() in
273
+ # cli/src/lib/commit-context/local-cache.ts. `-e`, not `-d`: inside a git
274
+ # worktree `.git` is a FILE, and the worktree root — not the main repo — is the
275
+ # project root (the TS uses fs.existsSync, which makes no such distinction).
276
+ # In the fleet this is the ONLY case that occurs: every agent works in a
277
+ # worktree, so `-d` would silently resolve no scope on every machine.
278
+ find_project_root() { # <start-dir> -> project root on stdout, or nothing
279
+ local dir
280
+ dir=$(cd "$1" 2>/dev/null && pwd -P) || return 0
281
+ while [[ -n "$dir" && "$dir" != "/" ]]; do
282
+ if [[ -e "$dir/.git" ]]; then
283
+ printf '%s' "$dir"
284
+ return 0
285
+ fi
286
+ dir=$(dirname "$dir" 2>/dev/null) || return 0
287
+ done
288
+ return 0
289
+ }
290
+
291
+ # Keep only the six known keys whose values are non-empty strings, cap each,
292
+ # and emit NOTHING when nothing usable remains — so an empty or scope-free
293
+ # object is never passed as if it were a label. Malformed JSON makes jq exit
294
+ # non-zero with no output, which lands in the same "no scope" branch.
295
+ #
296
+ # `-s` (slurp) is load-bearing, not a style choice. jq accepts a STREAM of JSON
297
+ # documents: without `-s` the filter runs once per document and `jq -c` prints
298
+ # one line each, so a config holding two concatenated or newline-separated
299
+ # objects produced a MULTI-LINE string that was passed verbatim as one
300
+ # --code-context argument. parseCodeContextFlag() (cli/src/commands/memories.ts)
301
+ # JSON.parse()s it and process.exit(1)s before any network call — the capture is
302
+ # lost silently, triggered by cloning a repo. The `!= "{}"` guard below did not
303
+ # catch it either: `{"zzz":1}{"team":"b"}` normalizes to the two lines
304
+ # `{}` + `{"team":"b"}`, and that whole string is not `{}`. Slurping into an
305
+ # array and taking the first element means exactly one line can ever be emitted.
306
+ #
307
+ # The cap is 100 CODEPOINTS, deliberately below the server's 200. The server's
308
+ # CodeContextSchema uses Zod `.max(200)`, which counts UTF-16 code units, while
309
+ # jq's `[0:N]` slices by codepoint. Every astral-plane character (emoji, CJK
310
+ # extensions, mathematical alphanumerics) is 1 codepoint but 2 UTF-16 units, so
311
+ # a `[0:200]` cap emitted values of up to 400 units — over the server maximum,
312
+ # a 400 from the API, and the same silent capture loss. Since no codepoint
313
+ # exceeds 2 UTF-16 units, 100 codepoints can never exceed 200 units. Scope
314
+ # labels are short names (product/team/service); the extra truncation is
315
+ # unreachable in practice, and truncating is recoverable where a rejected
316
+ # request is not. Do NOT "restore" this to 200.
317
+ normalize_code_context() { # JSON on stdin -> normalized JSON object, or nothing
318
+ local out
319
+ out=$(jq -s -c '
320
+ (.[0] // {}) as $raw
321
+ | if ($raw | type) == "object" then
322
+ reduce ("product","repo","service","component","team","role") as $k ({};
323
+ if ($raw[$k] | type) == "string" and ($raw[$k] | length) > 0
324
+ then .[$k] = ($raw[$k][0:100])
325
+ else . end)
326
+ else {} end
327
+ ' 2>/dev/null) || return 0
328
+ # The newline test is belt-and-braces: `-s` already guarantees one document,
329
+ # and jq -c escapes newlines inside string values. Nothing multi-line may ever
330
+ # reach --code-context again, whatever the filter above does.
331
+ if [[ -n "$out" && "$out" != "{}" && "$out" != "null" && "$out" != *$'\n'* ]]; then
332
+ printf '%s' "$out"
333
+ fi
334
+ return 0
335
+ }
336
+
337
+ CODE_CONTEXT_JSON=""
338
+
339
+ # 1. Env var. Tested for presence only — the value is never echoed or logged.
340
+ if [[ -n "${MX_CODE_CONTEXT:-}" ]]; then
341
+ CODE_CONTEXT_JSON=$(printf '%s' "$MX_CODE_CONTEXT" | normalize_code_context) || CODE_CONTEXT_JSON=""
342
+ fi
343
+
344
+ # 2. Repo file — consulted only when the env var yielded nothing usable.
345
+ if [[ -z "$CODE_CONTEXT_JSON" ]]; then
346
+ # ORDER IS LOAD-BEARING: harness-provided project dir, then the worktree path,
347
+ # then the cwd. Each source is TRIED IN TURN, and the transcript's directory
348
+ # is not a source at all. Both properties are corrections to earlier forms and
349
+ # both are pinned by the suite; read this before rewriting the expression.
350
+ #
351
+ # WHY EACH SOURCE IS TRIED SEPARATELY. The earlier form collapsed all three
352
+ # into ONE call: `find_project_root "${CLAUDE_PROJECT_DIR:-${CLAUDE_WORKTREE_PATH:-$(pwd)}}"`.
353
+ # `:-` substitutes only when a variable is UNSET or EMPTY — never when it is
354
+ # set to something useless. So a CLAUDE_PROJECT_DIR that is set but resolves
355
+ # to no repository (a stale path, a deleted directory, a path outside any
356
+ # checkout) consumed the single attempt and the cwd was NEVER consulted.
357
+ # Measured: CLAUDE_PROJECT_DIR=/proc and =/nonexistent/zz each produced
358
+ # {"product":"home","team":"DOTFILES-WRONG-SCOPE"} from the $HOME config.
359
+ # The loop below consults the next source instead, which `:-` cannot express.
360
+ #
361
+ # WHY THE TRANSCRIPT DIRECTORY IS NOT A SOURCE. It has no legitimate resolving
362
+ # power, and the reason is DEPTH-INDEPENDENT — do not restate it as a claim
363
+ # about the transcript's nesting. An earlier version of this comment argued
364
+ # from a flat ~/.claude/projects/<slug>/<id>.jsonl layout and enumerated the
365
+ # three directories a walk could reach. That premise is false here. Measured
366
+ # on this machine: transcripts sit at BOTH depth 2 and depth 4 under
367
+ # ~/.claude/projects — 310 at depth 2, 5621 deeper — so any argument of the
368
+ # form "the walk can only ever reach these three named directories" does not
369
+ # hold. The premise that does hold, and that does not depend on depth:
370
+ #
371
+ # .git anywhere under ~/.claude, any depth: 0 (also no .hg, no .svn)
372
+ #
373
+ # An upward walk from any transcript directory traverses only directories
374
+ # inside ~/.claude, none of which carries a repository marker, so it cannot
375
+ # terminate inside that subtree at any depth. That leaves $HOME as its ONLY
376
+ # reachable non-empty outcome, which is precisely the defect this block exists
377
+ # to prevent: keeping dotfiles in git is common, so $HOME/.git exists on many
378
+ # machines, and with $HOME/.mx-code-context.json present every capture from
379
+ # every worktree on the machine was labelled from the home config. A
380
+ # confidently wrong label is worse than no label — invisible to the scope that
381
+ # should see it, visible to one that must not. Do not reintroduce it.
382
+ #
383
+ # CAVEAT, stated because this is a claim about a directory OUTSIDE this
384
+ # repository: it could stop being true, and nothing in this codebase would
385
+ # notice if a repository ever appeared under ~/.claude. Removing the leg does
386
+ # not depend on the caveat holding — the leg is simply gone — but any future
387
+ # argument to reinstate it must re-measure rather than cite this line.
388
+ #
389
+ # WHY $HOME IS REFUSED OUTRIGHT, AND WHY BOTH SIDES ARE CANONICALIZED. Belt
390
+ # and braces for the residual where the cwd itself is $HOME or a directory
391
+ # beneath it whose nearest .git is $HOME's. It also closes a consequence that
392
+ # is easy to miss: CC_ROOT is the basis of the symlink containment test below,
393
+ # so a CC_ROOT of $HOME silently widens "contained in the project" to
394
+ # "anywhere in the home directory", and $HOME/.mx-code-context.json symlinked
395
+ # to any other file under $HOME would resolve and be used. The cost is not
396
+ # supporting a user whose real project IS their home directory; that is the
397
+ # same confusion we want rejected.
398
+ #
399
+ # The comparison MUST canonicalize $HOME. CC_ROOT always arrives canonical —
400
+ # find_project_root builds it with `cd … && pwd -P` — while $HOME arrives
401
+ # verbatim from the environment, so a literal `==` against "$HOME" misses on
402
+ # every spelling that is not byte-identical. Four spellings were measured
403
+ # leaking the home label through a symlinked $HOME/.mx-code-context.json: a
404
+ # trailing slash ("/home/x/"), a "/." suffix ("/home/x/."), $HOME set to a
405
+ # SYMLINK to the real home, and a cwd reached through that same symlink.
406
+ # Symlinked home directories are routine — macOS firmlinks, NFS corporate
407
+ # homes, container images mapping /home/user onto another volume — so the
408
+ # trigger is a normal configuration and the miss is silent: the refusal does
409
+ # not fire, and the containment widening above returns with it. `cd … && pwd -P`
410
+ # is the same primitive find_project_root uses and handles all four in one step.
411
+ #
412
+ # HOME unset, or pointing at nothing, leaves _home_real empty and no refusal
413
+ # fires. That is unchanged from the previous `-n "${HOME:-}"` guard, not a
414
+ # regression. The `|| _home_real=""` is REQUIRED, not decorative: without it a
415
+ # failing `cd` leaves the assignment non-zero and last on its path, which fires
416
+ # the ERR trap and abandons the capture.
417
+ #
418
+ # ERR-TRAP SAFETY — verified, not assumed, because a regression here fires
419
+ # `trap 'exit 0' ERR` and silently abandons the capture. The loop body's only
420
+ # status-bearing statement is a `$(...)` assignment of find_project_root, which
421
+ # returns 0 on every path including the `cd` failure. The break is written as
422
+ # an `if` block for the same reason the $HOME refusal is. The earlier one-line
423
+ # form `[[ -n "$CC_ROOT" ]] && break` returns 1 whenever the loop CONTINUES —
424
+ # an earlier version of this comment claimed it returned 0, which was wrong. It
425
+ # was safe only POSITIONALLY: as a non-final command of an `&&` list it is
426
+ # exempt under the errexit rules, so nothing fired. That safety depends on
427
+ # where the statement sits and would evaporate the moment this loop became the
428
+ # last statement of a function: the function would return 1 and any `$(...)`
429
+ # call of it would fire the trap. The `if` form returns 0 and removes the
430
+ # positional dependence.
431
+ #
432
+ # The same reasoning is why the $HOME refusal is an `if` block ON PURPOSE: the
433
+ # one-line `[[ "$CC_ROOT" == "$_home_real" ]] && CC_ROOT=""` returns 1 when the
434
+ # test is false, and was measured firing the ERR trap when it landed last in an
435
+ # enclosing block. `pwd 2>/dev/null` keeps a deleted cwd from printing "error
436
+ # retrieving current directory" onto the hook's real stderr. This safety comes
437
+ # from find_project_root always returning 0, not from this hook omitting
438
+ # `set -E`, so it survives someone adding `set -E` later. Do not introduce a
439
+ # bare command on this path.
440
+ CC_ROOT=""
441
+ for _cand in "${CLAUDE_PROJECT_DIR:-}" "${CLAUDE_WORKTREE_PATH:-}" "$(pwd 2>/dev/null)"; do
442
+ [[ -n "$_cand" ]] || continue
443
+ CC_ROOT=$(find_project_root "$_cand")
444
+ if [[ -n "$CC_ROOT" ]]; then break; fi
445
+ done
446
+ _home_real=$(cd "${HOME:-/nonexistent}" 2>/dev/null && pwd -P) || _home_real=""
447
+ if [[ -n "$_home_real" && "$CC_ROOT" == "$_home_real" ]]; then
448
+ CC_ROOT=""
449
+ fi
450
+ CC_FILE="${CC_ROOT}/.mx-code-context.json"
451
+ if [[ -n "$CC_ROOT" ]]; then
452
+ # CWE-59. `-f`, `-r` and the read all follow symlinks, so a repo could check
453
+ # in `.mx-code-context.json` as a symlink to any file on the machine and the
454
+ # six allowlisted keys of it would be uploaded to MemNexus. Resolve the path
455
+ # and require the result to stay inside the project root. Read through the
456
+ # RESOLVED path, so the link is not traversed a second time.
457
+ CC_REAL=$(realpath "$CC_FILE" 2>/dev/null || printf '')
458
+ if [[ -n "$CC_REAL" && "$CC_REAL" == "$CC_ROOT"/* && -f "$CC_REAL" && -r "$CC_REAL" ]]; then
459
+ # One open, bounded at the source (same 64KB bound as the TS resolver).
460
+ # The previous form size-checked with `wc -c` and then re-opened for jq:
461
+ # two opens on a path an untrusted repo controls, so a concurrent writer
462
+ # could present a small file to `wc` and a huge one to `jq` (TOCTOU) on a
463
+ # hot per-turn path. `head -c` bounds the read itself, which changes >64KB
464
+ # from "skipped" to "truncated, then rejected as invalid JSON" — the same
465
+ # observable outcome, no scope.
466
+ #
467
+ # `2>/dev/null` precedes the input redirect ON PURPOSE. Redirections apply
468
+ # left to right, so with `<"$CC_REAL" 2>/dev/null` a file that turned
469
+ # unreadable between the `-r` test and the open makes bash print the full
470
+ # path and "Permission denied" to the hook's REAL stderr, before the
471
+ # discard takes effect. Verified: reversing these two words reintroduces
472
+ # that leak. Do not reorder.
473
+ #
474
+ # The bytes are PIPED into jq, never routed through a variable. Bash
475
+ # strips NUL bytes out of command-substitution output and warns while
476
+ # doing it — from the parent shell reading the substitution, so the
477
+ # `2>/dev/null` above does not suppress that warning. Via a variable,
478
+ # `{"team":"a<NUL>b"}` printed a warning naming this script and line to
479
+ # the hook's real stderr, and then RESOLVED to team "ab": input the file
480
+ # does not contain, silently repaired before validation instead of
481
+ # rejected by it. Piping keeps the NUL inside jq, which rejects the
482
+ # document as malformed. Do not reintroduce an intermediate variable.
483
+ CODE_CONTEXT_JSON=$(head -c "$CODE_CONTEXT_MAX_BYTES" 2>/dev/null <"$CC_REAL" | normalize_code_context) || CODE_CONTEXT_JSON=""
484
+ fi
485
+ fi
486
+ fi
487
+
488
+ # Nothing resolved -> pass nothing at all, so the create command line is
489
+ # byte-identical to the pre-scope version. The `[@]+` guard keeps an empty array
490
+ # safe to expand under `set -u` on bash < 4.4.
491
+ CODE_CONTEXT_ARGS=()
492
+ if [[ -n "$CODE_CONTEXT_JSON" ]]; then
493
+ CODE_CONTEXT_ARGS=(--code-context "$CODE_CONTEXT_JSON")
494
+ fi
495
+
247
496
  # ── 5. Verbatim-transcript guard (fail-closed, fail-loud) ───────────────
248
497
  #
249
498
  # SCOPE — TEXT BLOCKS ONLY. This guard re-extracts
@@ -323,6 +572,7 @@ if mx_verbatim_guard "$TRANSCRIPT_PATH" "$CONTENT"; then
323
572
  --conversation-id "NEW" \
324
573
  --content "$CONTENT" \
325
574
  --topics "auto-captured,session-summary" \
575
+ "${CODE_CONTEXT_ARGS[@]+"${CODE_CONTEXT_ARGS[@]}"}" \
326
576
  >/dev/null 2>&1 || true
327
577
  fi
328
578
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memnexus-ai/mx-agent-cli",
3
- "version": "0.1.293",
3
+ "version": "0.1.294",
4
4
  "description": "CLI for creating and managing AI agent teams",
5
5
  "type": "module",
6
6
  "bin": {