Skip to content
Merged
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
20 changes: 13 additions & 7 deletions .ai/contexts/build-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,18 +349,24 @@ The rule is in [changelog.md](../../docs/changelog.md#documentation-in-the-same-
Review still assesses the prose. Adding the label or editing the reason needs
a rerun. Required-check settings and label creation remain separate actions.

The `deadcode` job reports and never blocks (#1356, first step). It runs one
The `deadcode` job blocks on any finding (#1356). It runs one
cell, Node 22 on `ubuntu-latest`, installs locked dependencies with
`npm ci --ignore-scripts` (knip needs no native rebuild and no Electron
download), then runs the locked knip with `npx --no-install`, so the version
is the one pinned in `package.json`. The markdown report goes to the log and to
the job summary through `tee`. The step sets `shell: bash` for pipefail, so
knip's non-zero exit still marks the step, and `continue-on-error: true`, so
the job and the workflow stay green whatever knip finds. Nothing `needs` it and
it is not a required check. Making it blocking is a later step of #1356, once
the report is clean. `test/deadcode-report.test.js` checks the pin, the job's
shape and that no gate task or job depends on it. What knip analyses and its
known false positives are in
knip's non-zero exit fails the step through `tee`; neither the step nor the
job sets `continue-on-error`, so a finding fails the workflow. Nothing `needs`
it. Whether it is a required status check is a repository ruleset setting, not
part of the workflow. False positives are dropped one (file, export) pair at a time by
`scripts/knip-preprocessor.js`, the `preprocessor` of `knip.json`; knip
computes its exit code from the counters the preprocessor returns, and a
listed pair knip no longer reports fails the run.
`test/deadcode-report.test.js` checks the pin, the job's shape, the absence
of `continue-on-error` and of any file-wide or global ignore, that neither the
task nor the step overrides the preprocessor, and that no gate task or job
depends on it; `test/knip-preprocessor.test.js` checks the filtering. What knip analyses,
its known false positives and how to add one are in
[development.md](../../docs/development.md#dead-code-report).

Linux runs the full Node suite with coverage. Every non-Linux runner runs
Expand Down
3 changes: 1 addition & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ jobs:
- name: Install dependencies without lifecycle scripts
run: npm ci --ignore-scripts

- name: Report unused files, exports and dependencies
continue-on-error: true
- name: Check for unused files, exports and dependencies
shell: bash
run: npx --no-install knip --no-progress --reporter markdown | tee -a "$GITHUB_STEP_SUMMARY"

Expand Down
2 changes: 1 addition & 1 deletion Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ tasks:
- node scripts/check-docs.js --validate

deadcode:
desc: "Report unused files, exports and dependencies with knip (report only; see docs/development.md)"
desc: "Check for unused files, exports and dependencies with knip (CI fails on any finding; see docs/development.md)"
cmds:
- npx --no-install knip {{.CLI_ARGS}}

Expand Down
41 changes: 33 additions & 8 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,18 +117,19 @@ modifies must be 80 % covered (`diff-cover`), `main.js`, `preload.js`, the MCP
bridge, `claude-auth.js`, `public/app.js`, `public/terminal-manager.js`, the
CodeMirror and Mermaid files, workers, scripts, tests and `e2e/` excepted. The
same workflow runs the [changelog check](changelog.md#the-ci-check) on pull
requests and the [end-to-end journeys](e2e.md). Its `deadcode` job prints the
[dead-code report](#dead-code-report); knip's findings and errors never fail it,
though a failed install does.
requests and the [end-to-end journeys](e2e.md). Its `deadcode` job runs the
[dead-code check](#dead-code-report) and fails on any finding knip reports.

### Dead-code report

`task deadcode` runs [knip](https://knip.dev), pinned to an exact version in
`devDependencies`, with `npx --no-install`: it uses the locked copy in
`node_modules` and never downloads another. Run `task install` first after
pulling the change that adds it. Arguments after `--` go to knip, for example
`task deadcode -- --production`. knip exits non-zero when it reports anything;
the report is information, not a gate, and no other task depends on it.
`task deadcode -- --production`. knip exits non-zero when it reports anything.
No other task depends on it, but the CI `deadcode` job fails on the same
report, so a pull request that adds an unused file, export or dependency goes
red.

`knip.json` declares what is analysed:

Expand Down Expand Up @@ -158,10 +159,34 @@ listing them: `css-tree` through jsdom's own resolution path, and
`app-builder-lib` and `builder-util` for electron-builder's macro helpers in
`test/build-workflow.test.js`.

Known false positive: knip does not follow CommonJS namespace access. An export
Known false positives: knip does not follow CommonJS namespace access. An export
read as `const ns = require('./x'); ns.name()`, destructured later from `ns`, or
re-exported with `module.exports = { ...ns }` is reported unused. Check every
reported export for that pattern before removing it.
re-exported with `module.exports = { ...ns }` (as `test/fixtures/trigger-watcher.cjs`
does) is reported unused. So is an export a test reaches by loading the module's
source into a VM context, and one the module reads back through
`module.exports.name`. Check every reported export for these patterns before
removing it.

The exports reached only that way are listed one by one in
`scripts/knip-preprocessor.js`, which `knip.json` names as its `preprocessor`.
knip hands it the report before printing it and computes its exit code from
the counters it returns. Each entry of `ALLOWED_UNUSED_EXPORTS` is one file, one
export and a reason: `namespace` (namespace access in app code),
`test-namespace` (namespace access or destructuring in a test),
`fixture-spread` (re-exported by spread from a test fixture), `source-loaded`
(a test loads the module's source) or `self-read` (the module reads
`module.exports.name` itself). The preprocessor drops exactly those pairs and
decrements the counters, so any other unused export, in the same file or not,
still fails knip. An entry knip no longer reports makes it fail with that pair
named: remove the entry with the export, or when its last reader goes.

To handle a new false positive, add one entry with its file, export and
reason, and give in the pull request the line that reads the export. Never use
a file-wide `ignoreIssues`, a glob or a global switch such as
`ignoreExportsUsedInFile`; `test/deadcode-report.test.js` refuses them, and
neither `task deadcode` nor the CI step passes `--preprocessor`, which would
replace the configured one. Arguments after `--` reach knip unchanged, so
`task deadcode -- --preprocessor …` drops the allow-list for that run.

## Running from source next to an installed copy

Expand Down
3 changes: 2 additions & 1 deletion knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@
"css-tree",
"app-builder-lib",
"builder-util"
]
],
"preprocessor": "./scripts/knip-preprocessor.js"
}
86 changes: 86 additions & 0 deletions scripts/knip-preprocessor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
'use strict';

const REASONS = ['namespace', 'test-namespace', 'fixture-spread', 'source-loaded', 'self-read'];

const ALLOWED_UNUSED_EXPORTS = [
{ file: 'archived-projects.js', symbol: 'filterArchivedProjects', reason: 'namespace' },
{ file: 'archived-projects.js', symbol: 'relatedEntries', reason: 'namespace' },
{ file: 'archived-projects.js', symbol: 'retireArchivedEntries', reason: 'namespace' },
{ file: 'archived-projects.js', symbol: 'undoArchiveProjectFolders', reason: 'namespace' },
{ file: 'jsonl-scan.js', symbol: 'MAX_LINE_BYTES', reason: 'self-read' },
{ file: 'project-remap.js', symbol: 'rewriteJsonlAtomic', reason: 'source-loaded' },
{ file: 'session-transitions.js', symbol: 'currentSessionId', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'detectPendingBackgroundContinuations', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'detectSessionTransitions', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'drainMetadataWrites', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'hasPendingLaunches', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'holdContinuationExit', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'refreshDescriptorSessions', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'resolvePendingLaunches', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'snapshotContinuations', reason: 'test-namespace' },
{ file: 'session-transitions.js', symbol: 'snapshotContinuationsBeforeSpawn', reason: 'namespace' },
{ file: 'session-transitions.js', symbol: 'sweepPendingLaunches', reason: 'namespace' },
{ file: 'src/main/changes/git-changes-file.js', symbol: 'resolveRepoDirs', reason: 'namespace' },
{ file: 'src/main/projects/project-delete-writer.js', symbol: 'buildDeletionUnits', reason: 'test-namespace' },
{ file: 'src/main/projects/project-delete-writer.js', symbol: 'buildFinalizationUnits', reason: 'test-namespace' },
{ file: 'src/main/remote/remote-ssh-binary.js', symbol: 'createBinaryResolver', reason: 'test-namespace' },
{ file: 'src/main/schedules/schedule-background.js', symbol: 'backgroundRefusal', reason: 'namespace' },
{ file: 'src/main/schedules/schedule-background.js', symbol: 'launchBackgroundSchedule', reason: 'namespace' },
{ file: 'src/main/schedules/schedule-delete-file.js', symbol: 'deleteScheduleFile', reason: 'source-loaded' },
{ file: 'src/main/schedules/schedule-ipc.js', symbol: 'ensureScheduleCreatorCommand', reason: 'namespace' },
{ file: 'src/main/schedules/schedule-ipc.js', symbol: 'init', reason: 'namespace' },
{ file: 'src/main/schedules/schedule-ipc.js', symbol: 'reportRunExit', reason: 'namespace' },
{ file: 'src/main/schedules/schedule-ipc.js', symbol: 'SHIPPED_CREATOR_TEMPLATE_SHA256', reason: 'test-namespace' },
{ file: 'src/main/schedules/schedule-run-results.js', symbol: 'writeScheduleRunResult', reason: 'test-namespace' },
{ file: 'src/main/session-index/read-counters.js', symbol: 'readBodyFile', reason: 'test-namespace' },
{ file: 'src/main/triggers/trigger-name.js', symbol: 'hasLoneSurrogate', reason: 'namespace' },
{ file: 'src/main/triggers/trigger-name.js', symbol: 'markerNaming', reason: 'namespace' },
{ file: 'src/main/triggers/trigger-name.js', symbol: 'recoveredNaming', reason: 'namespace' },
{ file: 'src/main/triggers/trigger-name.js', symbol: 'requestedNameFields', reason: 'namespace' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'deliverSingle', reason: 'test-namespace' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'isCompactCommand', reason: 'fixture-spread' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'SUBMITTED_RANK', reason: 'fixture-spread' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'submitWithVerify', reason: 'fixture-spread' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'waitForBusyFall', reason: 'fixture-spread' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'waitForCliIdleAfter', reason: 'fixture-spread' },
{ file: 'src/main/triggers/trigger-watcher.js', symbol: 'weakestSubmitted', reason: 'fixture-spread' },
{ file: 'worktree-delete.js', symbol: 'parseWorktreeList', reason: 'namespace' },
{ file: 'worktree-delete.js', symbol: 'removeWorktree', reason: 'namespace' },
{ file: 'worktree-delete.js', symbol: 'runningSessions', reason: 'namespace' },
{ file: 'worktree-delete.js', symbol: 'streamGit', reason: 'namespace' },
];

const toPosix = file => file.split('\\').join('/');

function createPreprocessor(allowed) {
const allowedKeys = new Set(allowed.map(entry => `${entry.file}#${entry.symbol}`));
return async function preprocess(data) {
if (!data.report.exports) return data;
const matched = new Set();
const exports = {};
for (const [file, symbols] of Object.entries(data.issues.exports)) {
const kept = {};
for (const [symbol, issue] of Object.entries(symbols)) {
const key = `${toPosix(file)}#${symbol}`;
if (allowedKeys.has(key)) matched.add(key);
else kept[symbol] = issue;
}
if (Object.keys(kept).length > 0) exports[file] = kept;
}
const stale = [...allowedKeys].filter(key => !matched.has(key));
if (stale.length > 0) {
throw new Error(`scripts/knip-preprocessor.js allows unused exports knip no longer reports; remove them: ${stale.join(', ')}`);
}
const dropped = matched.size;
return {
...data,
issues: { ...data.issues, exports },
counters: { ...data.counters, exports: data.counters.exports - dropped },
};
};
}

module.exports = createPreprocessor(ALLOWED_UNUSED_EXPORTS);
module.exports.ALLOWED_UNUSED_EXPORTS = ALLOWED_UNUSED_EXPORTS;
module.exports.REASONS = REASONS;
module.exports.createPreprocessor = createPreprocessor;
30 changes: 27 additions & 3 deletions test/deadcode-report.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ test('task deadcode runs the locked knip and no gate task depends on it', () =>
}
});

test('the deadcode CI job reports on Node 22 Linux without ever failing the workflow', () => {
test('the deadcode CI job runs on Node 22 Linux and fails on any finding', () => {
const { jobs } = yaml.load(read('.github/workflows/test.yml'));
const job = jobs.deadcode;
assert.ok(job, 'test.yml has a deadcode job');
Expand All @@ -55,9 +55,33 @@ test('the deadcode CI job reports on Node 22 Linux without ever failing the work
assert.match(install.run, /--ignore-scripts/, 'knip needs no native rebuild');
const report = job.steps.filter(step => knipCommand.test(step.run || ''));
assert.equal(report.length, 1, 'one step runs knip');
assert.equal(report[0]['continue-on-error'], true, 'findings never fail the job');
assert.equal(report[0].shell, 'bash', 'bash runs with pipefail, so the step still shows knip\'s exit');
assert.equal(job['continue-on-error'], undefined, 'a finding fails the workflow');
for (const step of job.steps) assert.equal(step['continue-on-error'], undefined, step.name || step.uses);
assert.equal(report[0].shell, 'bash', 'bash runs with pipefail, so tee does not hide knip\'s exit');
for (const [id, other] of Object.entries(jobs)) {
assert.ok(![].concat(other.needs || []).includes('deadcode'), `${id} must not wait on deadcode`);
}
});

test('knip silences its false positives export by export, never by a file or global switch', () => {
const config = JSON.parse(read('knip.json'));
assert.equal(config.ignoreExportsUsedInFile, undefined, 'no global export switch');
assert.equal(config.includeEntryExports, undefined);
assert.equal(config.rules, undefined, 'no issue type turned off for the whole project');
assert.equal(config.exclude, undefined, 'no issue type excluded for the whole project');
assert.equal(config.include, undefined, 'no issue type selection for the whole project');
assert.equal(config.ignoreFiles, undefined);
assert.equal(config.ignoreIssues, undefined, 'a file-wide ignore would hide a new unused export in that file');
for (const pattern of config.ignore) assert.ok(pattern === 'public/**', `only the renderer is ignored whole: ${pattern}`);
assert.equal(config.preprocessor, './scripts/knip-preprocessor.js', 'the per-export allow-list');
assert.equal(config.preprocessorOptions, undefined);
});

test('neither the task nor the CI step replaces the configured preprocessor', () => {
const { tasks } = yaml.load(read('Taskfile.yaml'));
const { jobs } = yaml.load(read('.github/workflows/test.yml'));
const commands = [...tasks.deadcode.cmds, ...jobs.deadcode.steps.map(step => step.run || '')];
for (const cmd of commands.filter(c => knipCommand.test(c))) {
assert.doesNotMatch(cmd, /--preprocessor|--no-exit-code|--max-issues|--include|--exclude/, cmd);
}
});
97 changes: 97 additions & 0 deletions test/knip-preprocessor.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
'use strict';

const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');

const preprocess = require('../scripts/knip-preprocessor');
const { ALLOWED_UNUSED_EXPORTS, REASONS, createPreprocessor } = preprocess;

const exportIssue = (filePath, symbol) => ({ type: 'exports', filePath: path.resolve(filePath), symbol, fixes: [] });

function reportOf(pairs, extra = {}) {
const exports = {};
for (const [file, symbol] of pairs) {
exports[file] = exports[file] || {};
exports[file][symbol] = exportIssue(file, symbol);
}
const files = extra.files || {};
return {
report: { exports: true, files: true },
issues: { exports, files },
counters: { exports: pairs.length, files: Object.keys(files).length, processed: 10, total: 10 + Object.keys(files).length },
};
}

const allPairs = ALLOWED_UNUSED_EXPORTS.map(entry => [entry.file, entry.symbol]);

test('every allowed pair names one file, one export and a known reason', () => {
assert.ok(ALLOWED_UNUSED_EXPORTS.length > 0);
const seen = new Set();
for (const entry of ALLOWED_UNUSED_EXPORTS) {
assert.deepEqual(Object.keys(entry).sort(), ['file', 'reason', 'symbol'], JSON.stringify(entry));
assert.doesNotMatch(entry.file, /[*?{}[\]!\\]/, `${entry.file}: one posix path, no pattern`);
assert.match(entry.symbol, /^[A-Za-z_$][\w$]*$/, entry.symbol);
assert.ok(REASONS.includes(entry.reason), `${entry.file}#${entry.symbol}: ${entry.reason}`);
const key = `${entry.file}#${entry.symbol}`;
assert.ok(!seen.has(key), `${key} listed twice`);
seen.add(key);
}
});

test('GIVEN the allowed pairs and an unlisted export in the same file WHEN preprocessed THEN only the unlisted export remains and the counters match', async () => {
const [file] = allPairs[0];
const data = reportOf([...allPairs, [file, 'genuinelyUnused']]);
const out = await preprocess(data);
assert.deepEqual(Object.keys(out.issues.exports), [file]);
assert.deepEqual(Object.keys(out.issues.exports[file]), ['genuinelyUnused']);
assert.equal(out.counters.exports, 1);
assert.equal(out.counters.total, 10, 'total counts files, not findings');
assert.equal(out.counters.processed, 10);
});

test('GIVEN only the allowed pairs WHEN preprocessed THEN no export issue and no count remain', async () => {
const out = await preprocess(reportOf(allPairs));
assert.deepEqual(out.issues.exports, {});
assert.equal(out.counters.exports, 0);
assert.equal(out.counters.total, 10, 'total counts files, not findings');
});

test('GIVEN an allowed symbol in another file WHEN preprocessed THEN it is kept', async () => {
const [, symbol] = allPairs[0];
const out = await preprocess(reportOf([...allPairs, ['encode-project-path.js', symbol]]));
assert.deepEqual(Object.keys(out.issues.exports), ['encode-project-path.js']);
assert.equal(out.counters.exports, 1);
});

test('GIVEN other issue types WHEN preprocessed THEN they are left untouched', async () => {
const files = { 'orphan.js': { 'orphan.js': { type: 'files', filePath: path.resolve('orphan.js'), symbol: 'orphan.js' } } };
const out = await preprocess(reportOf(allPairs, { files }));
assert.deepEqual(Object.keys(out.issues.files), ['orphan.js']);
assert.equal(out.counters.files, 1);
assert.equal(out.counters.total, 11, 'total counts files, not findings');
});

test('GIVEN an allowed pair knip no longer reports WHEN preprocessed THEN it fails and names the stale pair', async () => {
const [file, symbol] = allPairs[allPairs.length - 1];
await assert.rejects(preprocess(reportOf(allPairs.slice(0, -1))), error => {
assert.match(error.message, new RegExp(`${file.replace(/[.]/g, '\\.')}#${symbol}`));
return true;
});
});

test('GIVEN a run that does not report exports WHEN preprocessed THEN nothing is checked or changed', async () => {
const data = reportOf([]);
data.report.exports = false;
const out = await preprocess(data);
assert.equal(out, data);
assert.equal(out.counters.exports, 0);
});

test('GIVEN keys knip wrote with backslashes WHEN preprocessed THEN they match the posix allow-list', async () => {
const run = createPreprocessor([{ file: 'src/a.js', symbol: 'x', reason: REASONS[0] }]);
const data = reportOf([['src\\a.js', 'x']]);
const out = await run(data);
assert.deepEqual(out.issues.exports, {});
assert.equal(out.counters.exports, 0);
});
Loading