Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- `devcompass why <package>`: shows every path from the project to an installed package, so a vulnerable or outdated transitive dependency like `qs` nested under `express` is traceable back to what pulled it in.
- A dependency graph built from `package-lock.json` (npm only — pnpm/yarn/bun, a missing lockfile, or a lockfileVersion 1 file report `incomplete` instead of silently returning an empty graph). It correctly distinguishes several installed versions of one package at different nesting depths (e.g. a direct `qs@6.9.0` alongside `express`'s own nested `qs@6.7.0`), and is built from the lockfile alone, so it is complete before `npm install` has run.
- `devcompass clean` has a `-p, --path <path>` option, like every other command — it could only ever operate on the current directory.
- Every finding now carries a `ruleId` (e.g. `vuln`, `typosquat`, `outdated/major`, `unused`), a `confidence` (`high`/`medium`/`low` — heuristics like unused/typosquat are never `high`), and the full list of `advisoryIds` it merged (previously only the first GHSA/CVE id was kept, though a count was computed and silently discarded). A finding's `id` is now `<ruleId>:<package>@<version>[:<advisoryId>]` instead of `<package>@<version>`, so two different findings for the same package no longer share an id.
- `analyze --json`'s `metadata` has a `scanIncomplete` object with an entry per collector, alongside the existing `cveScanIncomplete`/`securityScanIncomplete`/... flags.
- A weekly CI job runs `analyze` against five well-known open-source projects (express, lodash, chalk, execa, yargs) and flags likely false positives — typosquat or unused flags on real, popular packages — before a user reports them. Informational only.

### Changed

- **The OSV check now covers the whole dependency tree, not just direct dependencies.** Every installed `name@version` in the lockfile is checked, so a vulnerability in a transitive package is found on its own rather than only when npm audit happens to also flag it (npm audit's results are filtered to HIGH/CRITICAL). On a project whose only dependencies are `express@4.17.1` and `lodash`, this finds 7 vulnerable packages instead of 4. Projects without a usable `package-lock.json` keep the previous direct-dependency check.
- OSV queries are sent 200 packages per request (4 in flight) instead of all in one request — needed now that whole trees are checked, and one slow or rejected chunk no longer fails every package in the scan.
- **`npm-check-updates` is gone** (−6.3 MB). The outdated check uses the npm registry client DevCompass already ships, plus `semver`. `wanted` is now the highest published version the declared range allows (e.g. `4.1.2` for `chalk@^4.0.0`); npm-check-updates always reported the latest version, even across a major the range doesn't allow.
- The four separate severity/priority tables (`severity.js`, `issue.model.js`, `data/priorities.json`, and the inline tables in `console-formatter.js`) are down to one, `core/utils/severity.js`; everything else imports from it. They had already drifted out of sync with each other.
- Collectors run from one registry (`src/features/analyze/collectors/index.js`) instead of a hardcoded list in `analyze`'s core — a new check is one collector file plus one entry, and its "scan incomplete" message comes from that entry.
- Test coverage is now measured over every file in `src/` (except the browser dashboard) rather than only the files a test happens to load, which had been inflating the number. The honest figure is ~29%, so the CI floor is 25% instead of the previous, misleading 60%.
Expand Down Expand Up @@ -43,6 +48,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `cve.collector.js` kept only the first advisory id per package (it counted the rest and discarded them); every advisory id now reaches the finding.
- An ecosystem alert whose suggested fix is free text no longer reads "Update to Consider alternatives…", and isn't marked as a safe fix.

### Security

- `follow-redirects` 1.16.0 → 1.16.1 and `zod` 4.3.6 → 4.6.7 for newly published advisories (lockfile-only).

## [4.1.9] - 2026-10-06

### Fixed
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,19 @@ devcompass fix undo

### Visualization

#### `why` - Why Is This Package Installed?

Show every path from your project to an installed package — useful when a vulnerable or outdated package is a transitive dependency you never declared.

```bash
devcompass why qs
# qs@6.7.0 (2 paths)
# my-app → express@4.17.1 → body-parser@1.19.0 → qs@6.7.0
# my-app → express@4.17.1 → qs@6.7.0
```

It reads `package-lock.json` only (npm; pnpm/yarn/bun lockfiles aren't supported yet), so it works before `npm install` has run. Each installed version of the package is listed separately.

#### `graph` - Dependency Graph Visualization

Generate interactive dependency graphs with multiple layouts and filters.
Expand Down
1 change: 1 addition & 0 deletions bin/devcompass.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ require('../src/cli/commands/llm.cmd')(program);
require('../src/cli/commands/ai.cmd')(program);
require('../src/cli/commands/config.cmd')(program);
require('../src/cli/commands/clean.cmd')(program);
require('../src/cli/commands/why.cmd')(program);

if (process.argv.length === 2) {
(async () => {
Expand Down
1 change: 1 addition & 0 deletions llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ DevCompass is a complement to `npm audit` and Dependabot for teams that also wan
- `devcompass analyze` — Full dependency analysis: security, health score, license, unused/outdated packages. Flags: `--deep` (all issues, default shows top 3), `--json`, `--silent`, `--ci`, `--ci --threshold 8.0`. Health score bands: 9.0-10.0 excellent, 8.0-8.9 good, 6.0-7.9 needs attention, 4.0-5.9 poor, 0.0-3.9 critical.
- `devcompass cve` — CVE database management. `cve key --set --api-key <KEY>` / `cve key` (status) / `cve key --remove`; `cve test` (test NVD connection); `cve cache --stats` / `cve cache --clear`.
- `devcompass fix` — Automated issue resolution with risk classification (safe/moderate/risky), preview (including a live `package.json` diff), automatic backup before changes, interactive confirmation, and rollback support. Supports `--dry-run`. `--migrate-syntax` additionally rewrites source call-sites broken by a major-version update (built-in codemod, falling back to your configured AI provider), snapshotting every touched file; `devcompass fix undo` reverts the most recent `--migrate-syntax` run.
- `devcompass why <package>` — Every path from the project to an installed package, from package-lock.json (works before `npm install`).
- `devcompass graph` — Interactive dependency graph, 5 layouts: Tree, Force-directed, Radial, Conflict, Analytics. Real-time filtering (vulnerable/outdated/unused), dark/light themes, export to PNG/JSON/HTML. Flag: `--open`.
- `devcompass snapshot` — Save/manage point-in-time dependency state snapshots (`snapshot save`, etc.), stored in a local SQLite database.
- `devcompass compare` — Side-by-side diff between two snapshots: `devcompass compare <before-id> <after-id>`.
Expand Down
27 changes: 6 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
"cross-spawn": "^7.0.6",
"d3": "^7.8.5",
"knip": "^6.12.2",
"npm-check-updates": "^20.0.0",
"open": "^11.0.0",
"ora": "5.4.1",
"p-limit": "^3.1.0",
Expand Down
58 changes: 58 additions & 0 deletions src/cli/commands/why.cmd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// src/cli/commands/why.cmd.js
//
// FT-06: `devcompass why <package>` — how did this package get into the
// dependency tree, and is it vulnerable?

const chalk = require('chalk');
const fs = require('fs');
const path = require('path');

module.exports = function registerWhyCommand(program) {
program
.command('why <package>')
.description('Show how a package got into the dependency tree')
.option('-p, --path <path>', 'Project path', process.cwd())
.action(async (packageName, options) => {
const projectPath = options.path;
try {
const { loadDependencyGraph } = require('../../core/graph');
const { why } = require('../../core/graph/why');

const graph = await loadDependencyGraph(projectPath);

if (graph.incomplete) {
console.error(chalk.yellow(`\n⚠️ ${graph.incompleteReason}\n`));
process.exitCode = 1;
return;
}

const results = why(graph, packageName);
if (results.length === 0) {
console.log(chalk.yellow(`\n"${packageName}" isn't in the installed dependency tree.\n`));
return;
}

const packageJson = JSON.parse(fs.readFileSync(path.join(projectPath, 'package.json'), 'utf8'));
const projectName = packageJson.name || path.basename(projectPath);

console.log('');
for (const { node, paths } of results) {
console.log(chalk.bold.cyan(`${node.id} (${paths.length} path${paths.length === 1 ? '' : 's'})`) + (node.direct ? chalk.gray(' [direct dependency]') : ''));
paths.forEach(trail => {
const printable = [projectName, ...trail.slice(1)].join(chalk.gray(' → '));
console.log(` ${printable}`);
});
if (paths.length === 0 && !node.direct) {
console.log(chalk.gray(' (no path found from the root — check the lockfile for an inconsistency)'));
}
console.log('');
}

console.log(chalk.gray('Run `devcompass analyze --deep` for vulnerability/license findings on these packages, and `devcompass fix --dry-run` for suggested overrides.\n'));
} catch (error) {
console.error(chalk.red('\n❌ why failed:'), error.message);
if (process.env.DEBUG) console.error(error.stack);
process.exitCode = 1;
}
});
};
199 changes: 199 additions & 0 deletions src/core/graph/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// src/core/graph/index.js
//
// AR-01: one dependency graph, built from the lockfile, that every collector
// can read from instead of each re-deriving its own partial view (the OSV
// check only covering direct dependencies, the dashboard's graph only
// looking up top-level node_modules/<name> and getting nested versions
// wrong, "unknown" versions when a collector didn't resolve one itself).
//
// Deliberately dependency-free: @npmcli/arborist (npm's own resolver, the
// obvious library choice) pulls in ~115 packages / 24 MB. Edges are resolved
// from package-lock.json alone — its install paths already encode the
// node_modules layout — so the graph is complete even before `npm install`
// / `npm ci` has run, and never reads the disk beyond the lockfile.
//
// npm only for now — pnpm/yarn/bun need their own lockfile parsers (not
// implemented; see incomplete/incompleteReason below).

const fs = require('fs');
const path = require('path');

/**
* @typedef {object} PackageNode
* @property {string} id "name@version"
* @property {string} name
* @property {string} version
* @property {string[]} paths lockfile install paths, e.g. ["node_modules/express/node_modules/qs"]
* @property {boolean} direct declared in the root package.json
* @property {boolean} dev
* @property {boolean} optional
* @property {boolean} hasInstallScript
* @property {string|null} license
*/

function detectPackageManager(projectPath) {
if (fs.existsSync(path.join(projectPath, 'package-lock.json'))) return 'npm';
if (fs.existsSync(path.join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm';
if (fs.existsSync(path.join(projectPath, 'yarn.lock'))) return 'yarn';
if (fs.existsSync(path.join(projectPath, 'bun.lock')) || fs.existsSync(path.join(projectPath, 'bun.lockb'))) return 'bun';
return null;
}

function packageNameFromPath(pkgPath) {
const idx = pkgPath.lastIndexOf('node_modules/');
return idx === -1 ? pkgPath : pkgPath.slice(idx + 'node_modules/'.length);
}

// Which lockfile entry `depName` resolves to when required from the package
// installed at `fromKey` ('' for the project root): Node's own lookup —
// nearest node_modules wins, walking up — applied to the lockfile's install
// paths. A package that isn't installed on this platform (an optional,
// OS-specific binary) still resolves to its own nested copy, where walking
// the real node_modules would have climbed to an unrelated top-level one.
function resolveInLockfile(packages, fromKey, depName) {
let base = fromKey;
while (true) {
const candidate = base ? `${base}/node_modules/${depName}` : `node_modules/${depName}`;
if (packages[candidate]) return candidate;
if (!base) return null;
const idx = base.lastIndexOf('/node_modules/');
base = idx === -1 ? '' : base.slice(0, idx);
}
}

function loadNpmGraph(lock) {
const packages = lock.packages || {};
const nodes = new Map(); // id ("name@version") -> PackageNode
const pathKeyToNodeId = new Map(); // lockfile path key -> node id, for edge resolution
const roots = [];

const rootEntry = packages[''] || {};
const rootDirect = new Set(Object.keys({
...(rootEntry.dependencies || {}),
...(rootEntry.devDependencies || {}),
...(rootEntry.optionalDependencies || {})
}));

for (const [key, entry] of Object.entries(packages)) {
if (key === '' || !entry || !key.includes('node_modules/')) continue;
const name = packageNameFromPath(key);
if (!name || !entry.version) continue;

const id = `${name}@${entry.version}`;
// A direct dependency's node_modules entry sits right at the top level
// (node_modules/<name>), never nested under another package.
const isTopLevel = key === `node_modules/${name}`;

if (!nodes.has(id)) {
nodes.set(id, {
id,
name,
version: entry.version,
paths: [],
direct: isTopLevel && rootDirect.has(name),
dev: !!entry.dev,
optional: !!entry.optional,
hasInstallScript: !!entry.hasInstallScript,
license: entry.license || null
});
}
const node = nodes.get(id);
node.paths.push(key);
if (isTopLevel && rootDirect.has(name)) node.direct = true;
// dev/optional are per-install-location in npm's own model; a package
// is only dev-only/optional-only overall if every location it appears
// at agrees (a prod dep that's *also* pulled in by a devDependency is
// still a prod dep).
if (!entry.dev) node.dev = false;
if (!entry.optional) node.optional = false;

pathKeyToNodeId.set(key, id);
if (isTopLevel && rootDirect.has(name)) roots.push(id);
}

// Nodes are deduplicated by name@version, but a node can have several
// physical install locations (paths.length > 1) — without deduping here
// too, each of those locations would independently produce the same
// logical (fromId -> toId) edge, and a path search downstream (why.js)
// would then "discover" the identical path once per redundant edge.
const edgeKeys = new Set();
const edges = [];
function addEdge(fromId, toId) {
if (!toId || toId === fromId) return;
const key = `${fromId}->${toId}`;
if (edgeKeys.has(key)) return;
edgeKeys.add(key);
edges.push([fromId, toId]);
}

for (const [key, entry] of Object.entries(packages)) {
if (key === '' || !entry) continue;
const fromId = pathKeyToNodeId.get(key);
if (!fromId) continue;

const declaredDeps = {
...(entry.dependencies || {}),
...(entry.optionalDependencies || {})
};
for (const depName of Object.keys(declaredDeps)) {
const resolvedKey = resolveInLockfile(packages, key, depName);
if (resolvedKey) addEdge(fromId, pathKeyToNodeId.get(resolvedKey));
}
}

// The root package.json's own declared deps -> edges from a synthetic "root" id.
for (const depName of rootDirect) {
const resolvedKey = resolveInLockfile(packages, '', depName);
if (resolvedKey) addEdge('root', pathKeyToNodeId.get(resolvedKey));
}

return { packageManager: 'npm', nodes, edges, roots };
}

/**
* @param {string} projectPath
* @returns {Promise<{packageManager: string|null, nodes: Map<string, PackageNode>, edges: Array<[string,string]>, roots: string[], incomplete?: boolean, incompleteReason?: string}>}
*/
async function loadDependencyGraph(projectPath) {
const packageManager = detectPackageManager(projectPath);

if (packageManager === null) {
return { packageManager: null, nodes: new Map(), edges: [], roots: [], incomplete: true, incompleteReason: 'No lockfile found' };
}

if (packageManager !== 'npm') {
return {
packageManager,
nodes: new Map(),
edges: [],
roots: [],
incomplete: true,
incompleteReason: `${packageManager} lockfiles aren't supported yet — only npm's package-lock.json is`
};
}

const lockPath = path.join(projectPath, 'package-lock.json');
let lock;
try {
lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
} catch (error) {
return { packageManager, nodes: new Map(), edges: [], roots: [], incomplete: true, incompleteReason: `Could not read package-lock.json: ${error.message}` };
}

if (!lock.packages) {
// lockfileVersion 1 (npm <=6): a different, nested `dependencies` shape
// this parser doesn't read yet.
return {
packageManager,
nodes: new Map(),
edges: [],
roots: [],
incomplete: true,
incompleteReason: `package-lock.json is lockfileVersion ${lock.lockfileVersion || 1}, which this parser doesn't support yet (needs lockfileVersion 2 or 3)`
};
}

return loadNpmGraph(lock);
}

module.exports = { loadDependencyGraph, detectPackageManager, resolveInLockfile };
Loading