Skip to content

feat(cli): detect stray $HOME/node_modules/sequant and emit targeted warning #539

Closed

Description

@admarble

Context

npm/node module resolution walks up the directory tree looking for node_modules. If a user accidentally runs npm install sequant from $HOME, every subdirectory of home then resolves to that stale copy — not just the intended project.

Encountered live: ~/package.json contained only { "dependencies": { "sequant": "^1.20.0" } } from an install months prior. npx sequant update from a project subdirectory resolved to $HOME/node_modules/[email protected] instead of either the project-local install or the npx cache, so update/sync ran ancient template logic against a freshly-initialized v2.2.0 project.

The CLI already warns today:

⚠️ Running sequant from local node_modules
For latest version: npx sequant@latest

…but the warning doesn't name the path, and the pathological $HOME/node_modules case is indistinguishable from a legitimate project-local install.

Proposal

When the CLI resolves its own install path to $HOME/node_modules/sequant exactly, emit a distinct warning that names the path and the cleanup commands:

⚠️  Sequant is running from $HOME/node_modules/sequant — this pollutes
   resolution for every subdirectory of your home directory.

   If accidental (usually is — one stray `npm install sequant` from ~ does it):
       remove $HOME/node_modules
       remove $HOME/package.json and $HOME/package-lock.json

   If intentional: use `npm install -g sequant` or the Claude Code plugin.

Acceptance Criteria

  • CLI resolves its own install path on startup (via import.meta.url / __dirname)
  • When resolved path equals path.join(os.homedir(), 'node_modules', 'sequant'), emit the distinct warning with cleanup guidance
  • Legitimate project-local installs (<project>/node_modules/sequant) retain the existing generic warning unchanged
  • Global installs (npm root -g) and npx cache paths are not flagged
  • Unit test covers all four cases: home stray, project-local, global, npx cache

Out of Scope

  • Auto-removing the stray install — too destructive to automate inside $HOME
  • Detecting pollution at other parent levels (e.g. ~/Projects/node_modules) — same footgun, much rarer

Priority

Low. Rare edge case — the existing generic warning already points users toward npx sequant@latest, which is the correct workaround. Filing for completeness.

Activity

  1. added
    enhancement
    cli
    on Apr 19, 2026
  2. admarble commented on Apr 23, 2026

    @admarble
    ContributorAuthor

    → PROCEED — Stray $HOME/node_modules/sequant install detection + targeted warning. AC-5 names unit test coverage, so testgen applies.

    Workflow: spec → testgen → exec → qa · 5 ACs

    ```
    npx sequant run 539 --phases spec,testgen,exec,qa
    ```

  3. admarble commented on Apr 25, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (5 ACs, 2 directories: bin/, src/lib/)

    AC Quality Check

    All 5 ACs are concrete and measurable — paths are named, comparisons are exact (path.join(os.homedir(), 'node_modules', 'sequant')), and the "four cases" test set is explicitly enumerated. No vague terms.

    Scope Assessment

    Non-Goals (from issue):

    • Auto-removing the stray install
    • Detecting pollution at other parent levels (~/Projects/node_modules)
    Metric Value Status
    Feature count 1 (new warning branch) OK
    AC items 5 OK
    Directory spread 2 (bin/cli.ts, src/lib/version-check.ts + test) OK

    Verdict: SCOPE_OK — single feature, narrowly scoped, clear non-goals.


    Acceptance Criteria

    AC-1: CLI resolves its own install path on startup (via import.meta.url / __dirname)

    Verification: Unit Test
    Scenario: Given the CLI is invoked → When startup runs → Then resolved install path equals the directory containing sequant's package.json.
    Note: version-check.ts already walks up from __dirname to find package.json (see getCurrentVersion). Reuse that logic in a new getInstallRoot() helper.

    AC-2: When resolved path equals path.join(os.homedir(), 'node_modules', 'sequant'), emit the distinct warning with cleanup guidance

    Verification: Unit Test
    Scenario: Given install root === $HOME/node_modules/sequant → When startup warning logic runs → Then output contains: the resolved path, "pollutes resolution for every subdirectory", the two cleanup commands, and the "If intentional" alternative.
    Assumptions: Exact-equality match (not startsWith) — covered by AC-2's "exactly" wording and the non-goal excluding deeper paths.

    AC-3: Legitimate project-local installs (<project>/node_modules/sequant) retain the existing generic warning unchanged

    Verification: Unit Test
    Scenario: Given install root === /some/project/node_modules/sequant (not equal to $HOME/node_modules/sequant) → When startup runs → Then existing "Running sequant from local node_modules" warning is emitted, and the home-stray warning is NOT emitted.

    AC-4: Global installs (npm root -g) and npx cache paths are not flagged

    Verification: Unit Test
    Scenario: Given install root in npm root -g output OR matching ~/.npm/_npx/<hash>/node_modules/sequant → When startup runs → Then no warning is emitted (current behavior preserved for these cases).

    AC-5: Unit test covers all four cases: home stray, project-local, global, npx cache

    Verification: Unit Test
    Scenario: version-check.test.ts includes one test per case, mocking os.homedir() and __dirname-equivalent input to the new function.
    Note: Existing test file mocks process.env.HOME = "/home/user". Add os.homedir() mock or pass install path as argument for testability.


    Implementation Plan

    Phase 1: Detection logic (src/lib/version-check.ts)

    1. Add getInstallRoot(): string | null — walks up from __dirname to the directory containing sequant's package.json (extract from existing getCurrentVersion logic).
    2. Add isHomeStrayInstall(installRoot?: string): boolean — returns true iff resolved root === path.join(os.homedir(), 'node_modules', 'sequant'). Accepts optional override for testability.
    3. Keep existing isLocalNodeModulesInstall() unchanged — AC-3 requires the generic warning to be preserved.

    Phase 2: Warning emission (bin/cli.ts)

    1. Update the warning block (lines 79–88): branch on isHomeStrayInstall() first → emit the distinct warning with the path and both cleanup commands. Else if isLocalNodeModulesInstall() → keep the existing generic warning. Use chalk.yellow for parity.

    Phase 3: Tests (src/lib/version-check.test.ts)

    1. Add a describe("isHomeStrayInstall", ...) block with four cases:
      • Home stray: install root === /home/user/node_modules/sequant → returns true
      • Project-local: /projects/foo/node_modules/sequant → returns false
      • Global: /usr/local/lib/node_modules/sequant → returns false
      • npx cache: /home/user/.npm/_npx/abc123/node_modules/sequant → returns false
    2. Pass install path explicitly to isHomeStrayInstall(installRoot) to avoid mocking __dirname.

    Design Review

    1. Where does this logic belong? src/lib/version-check.ts — already owns isLocalNodeModulesInstall() and getCurrentVersion() walk-up logic. Adding a sibling function preserves cohesion.
    2. What existing pattern does this follow? Mirrors the existing isLocalNodeModulesInstall() predicate-plus-warning pattern. Same chalk styling, same --quiet opt-out, same warning location in bin/cli.ts.
    3. What would a senior reviewer challenge? "Why not unify into a single getInstallType() enum?" — Considered, but a separate predicate keeps the diff minimal, preserves AC-3's "unchanged" guarantee for the generic warning, and avoids touching call sites that only care about local-vs-not.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • No backward-compat risk: isLocalNodeModulesInstall() signature unchanged; new function is additive.
    • Path-equality on Windows: Use path.join + path.normalize (or path.resolve) for the comparison — case sensitivity isn't a concern on macOS/Linux but path.join normalizes separators consistently.
    • Performance: One extra os.homedir() + path.join + string compare on startup — negligible.

    Open Questions

    1. Should the home-stray case also suppress the generic warning? — Recommendation: yes, only one warning at a time. The home-stray warning is strictly more informative and includes its own cleanup guidance. Impact if wrong: users see two stacked warnings (annoying, not broken).

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: disabled (SCOPE_OK)
    Reasoning: ACs are Unit Test-verified across four mocked path scenarios → testgen will stub the four cases up front. No UI, so /test skipped. no-browser-test not needed.


    Label Review

    Current: enhancement, cli
    Recommended: add simple-fix or leave as-is
    Reason: ~30-line diff across 3 files, no architectural impact. cli and enhancement already cover it.

  4. added
    planned
    on Apr 25, 2026
  5. admarble commented on Apr 25, 2026

    @admarble
    ContributorAuthor
    No description provided.
  6. admarble commented on Apr 25, 2026

    @admarble
    ContributorAuthor

    Exec Complete (orchestrated)

    Branch: feature/539-cli-detect-stray-home-node-modules (commit 2d6bed6)

    AC Coverage

    AC Status Evidence
    AC-1 Implemented getInstallRoot() walks up from __dirname to sequant's package.json (src/lib/version-check.ts:96-114)
    AC-2 Implemented Distinct warning emitted in bin/cli.ts:81-101 when isHomeStrayInstall() returns true; names the resolved path, both cleanup commands, and the "If intentional" alternative
    AC-3 Implemented Project-local branch unchanged — same chalk message, same package-manager removePkg line (bin/cli.ts:91-99)
    AC-4 Implemented isHomeStrayInstall() uses exact-equality check vs path.join(os.homedir(), 'node_modules', 'sequant'); global (/usr/local/lib/...) and npx-cache (~/.npm/_npx/...) paths never match
    AC-5 Implemented Four unit tests in src/lib/version-check.test.ts cover home-stray, project-local, global, npx-cache (plus a fifth for the null install root case)

    Quality Gates

    • Build: pass (tsc)
    • Lint: pass (eslint src/ bin/ --max-warnings 0)
    • Tests: 2678 passed (39 in version-check.test.ts, 5 of which are new)
  7. admarble commented on Apr 25, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #539

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original CLI resolves its own install path on startup MET getInstallRoot() walks up from __dirname looking for sequant's package.json (src/lib/version-check.ts:111-128); mirrors the existing getCurrentVersion() walk-up pattern
    AC-2 Original Distinct warning when path equals $HOME/node_modules/sequant MET bin/cli.ts:82-93 interpolates the resolved install path, names the cleanup commands (remove $HOME/node_modules, remove $HOME/package.json and package-lock.json), and lists the legitimate alternatives (npm install -g sequant, Claude Code plugin) — matches the warning template in the issue body
    AC-3 Original Project-local generic warning unchanged MET The else if branch (bin/cli.ts:94-102) preserves the original message text, pmCommands.removePkg interpolation, and chalk styling byte-for-byte
    AC-4 Original Globals and npx cache not flagged with home-stray warning MET isHomeStrayInstall uses exact path-equality vs path.join(os.homedir(), "node_modules", "sequant"). Verified by tests: /usr/local/lib/node_modules/sequant → false, /home/user/.npm/_npx/abc123/node_modules/sequant → false. Globals continue to receive the existing generic warning (pre-existing behavior, AC-3 says unchanged)
    AC-5 Original Unit tests cover all four cases MET version-check.test.ts:155-185 adds 5 tests: home-stray (true), project-local (false), global (false), npx-cache (false), null install root (false). All pass; full suite green (2678 tests)

    Coverage: 5/5 AC items fully met.


    Quality Plan Verification

    N/A — /spec did not generate a Quality Plan section for this issue (Standard tier, narrowly scoped).


    CI Status

    No PR opened yet — orchestrator will create one after this verdict.


    Quality Metrics

    Metric Value Status
    Type issues (any introduced) 0 OK
    Deleted tests 0 OK
    Files changed 4 OK
    Lines added +133 -
    Lines deleted -12 -
    Build pass OK
    Lint pass (--max-warnings 0) OK
    Tests 2678 passed (39 in version-check.test.ts) OK

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/version-check.ts Standard Yes src/lib/version-check.test.ts (5 new tests for isHomeStrayInstall)
    bin/cli.ts Standard No (existing pattern — entry-point warning emission has never been unit-tested in this file) —
    src/lib/version-check.test.ts Test n/a n/a
    CHANGELOG.md Optional n/a n/a

    Coverage: 1/1 changed source-with-logic file has tests. bin/cli.ts change is a 12-line template-interpolation branch around already-tested predicates; emission text is not covered by automated tests, consistent with the existing isLocalNodeModulesInstall warning.


    Code Review

    Strengths:

    • Predicate accepts installRoot as a parameter, enabling deterministic testing of all four path cases without __dirname fakery.
    • Home-stray branch is checked before the generic branch, so only one warning fires (avoids stacked warnings on the pathological case).
    • Walk-up logic in getInstallRoot() mirrors the existing getCurrentVersion() pattern — same termination condition (dir !== path.dirname(dir)), same package.json + name guard.
    • Comments lead with why (the footgun: Node walks up to home before falling back to npx cache), not what.
    • Test file documents the os.homedir mock rationale (macOS reads OS-level home regardless of process.env.HOME).

    Issues:

    • None blocking.

    Suggestions (non-blocking):

    • getInstallRoot() and getCurrentVersion() both walk up from __dirname looking for sequant's package.json. Could be DRYed into a single helper that returns { root, pkg }, but the current duplication is small and the return types differ (path vs version string) — not worth refactoring in this PR.

    Anti-Pattern Detection

    Category Pattern Result
    Type safety any/as any introduced None
    Security Hardcoded secrets, eval, innerHTML None
    Error handling Empty catch blocks One existing catch {} in getInstallRoot() mirrors the same pattern in getCurrentVersion() — intentional (file may not exist on the way up the tree)
    Performance Loops with await None (sync walk-up is bounded by FS depth)

    No new anti-patterns introduced. package.json not modified — dependency audit N/A.


    CLI Registration Verification

    N/A — this PR does not modify RunOptions or any other option interface. The warning logic runs unconditionally at CLI startup; no new flags introduced (continues to honor existing --quiet).


    Skill Command Verification

    N/A — no .claude/skills/**/*.md files modified.


    Smoke Test

    npx tsx bin/cli.ts --help runs cleanly in the worktree (no warning, since the worktree path is not $HOME/node_modules/sequant). End-to-end manual verification of the home-stray warning would require physically constructing $HOME/node_modules/sequant — pre-existing behavior of the generic warning was already verified as preserved (isLocalNodeModulesInstall and the else-if branch are byte-for-byte unchanged).


    Manual Test ACs

    N/A — all 5 ACs use Verification: Unit Test.


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists Found
    User-facing changes Yes (new CLI warning behavior)
    [Unreleased] entry Present (### Added — Stray $HOME/node_modules/sequant detection ... (#539))
    Entry format Valid (action verb, includes issue number, names new exports)

    Risk Assessment

    • Likely failure mode: A user with a stray install at a non-home parent level (e.g., ~/Projects/node_modules/sequant) won't get the targeted warning — only the generic one. This is explicitly out of scope per the issue's Non-Goals ("same footgun, much rarer"). On Windows, path.resolve() normalizes drive letters and separators consistently, so the equality check should hold; macOS case-insensitive HFS+ relies on os.homedir() returning the case-correct path (which it does in practice).
    • Not tested: No end-to-end smoke test physically constructs $HOME/node_modules/sequant and runs the CLI from there — the predicate logic is fully unit-tested, and the warning emission is template interpolation (no branching). Risk of regression is low.

    Verdict: READY_FOR_MERGE

    All 5 ACs met literally. Code quality is high: predicate is testable, mirrors existing patterns, comments justify the why, build/lint/tests all green. CHANGELOG entry present. No security or scope concerns.

    Documentation

    • CHANGELOG entry added
    • N/A — README/docs unchanged (no new flags or commands; warning is auto-emitted on startup)

    Next Steps

    1. Orchestrator opens PR
    2. Merge after CI green
  8. added
    ready-for-review
    and removed
    planned
    on Apr 25, 2026
  9. admarble commented on Apr 25, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #539
    Status: READY_FOR_MERGE
    PR: #553

    Summary

    • AC: 5/5 met (unit-test verified across home-stray, project-local, global, npx-cache, and null-input cases)
    • Build / Lint / Tests: pass (2678 tests; 5 new in version-check.test.ts)
    • Files changed: 4 (src/lib/version-check.ts, bin/cli.ts, src/lib/version-check.test.ts, CHANGELOG.md)
    • Net diff: +133 / -12

    Iterations

    • Spec loop: 1
    • Exec loop: 1 (one mid-run fix: added vi.mock("os") after the first test run revealed macOS reads OS-level home regardless of process.env.HOME)
    • QA loop: 1 (verdict: READY_FOR_MERGE on first pass)

    Ready for human review and merge.

  10. added 4 commits that reference this issue on Apr 26, 2026
  11. admarble commented on May 11, 2026

    @admarble
    ContributorAuthor

    Documentation Generated

    File: docs/troubleshooting.md (new section: "Stray \$HOME/node_modules/sequant install" under "Installation Issues (npm)")

    Added as a troubleshooting entry rather than a standalone feature doc — the warning users see is concrete and self-contained, and the fix is a few shell commands.

    Section Includes

    • Verbatim warning text users see on startup
    • Cause (Node's module resolution walks up to $HOME first)
    • Two-path solution: clean removal vs intentional global install / Claude Code plugin
    • Note that only the exact $HOME/node_modules/sequant path triggers — project-local, global, and npx cache paths are not flagged

    Next Steps

    1. Review the placement in troubleshooting.md
    2. Merge to main alongside the next release notes

    Ready to merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    clienhancementready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions