@memnexus-ai/cli 1.7.234 → 1.7.236

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