forked from cflmy/deepseek-harness
feat(infra): reject silent empty catch clauses
AGENTS.md requires an empty `catch` to name the discarded error, state why it needs no handling, and keep its `try` to one statement, but nothing enforced it: 119 clauses break a condition today. The new `verify-empty-catch` gate scans tracked and non-ignored untracked first-party source with the TypeScript syntax tree. It records those 119 legacy clauses by path, syntax fingerprint, and count in `scripts/empty-catch.baseline.json`, so enforcement starts without a repository-wide edit. A new or changed clause fails the gate, and fixing a recorded clause requires `--prune` to retire its allowance; no command adds one. The recorded-inventory bookkeeping shared with `verify-no-unknown-casts` moves to `scripts/baseline-inventory.ts`, which keeps one copy of baseline validation, counting, pruning, and the command itself.
This commit is contained in:
1 parent
8c192ad810
commit
05883ff6b5
11 files changed
+936
-133
No files matched your search
@@ -149,7 +149,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and
|
||||
- **Source plane vs artifact plane, never mixed.** Static gates and tests resolve workspace imports through tsconfig `paths` to `src` and pass on a clean tree; gates consuming built `lib/` declare that dependency ([layout](docs/development.md#typescript-project-layout)).
|
||||
- **Keep compiler faces explicit.** A package with both Host and Client programs exposes face-specific leaf configs and a solution-only root; repo-wide programs seed a face config, never the root solution ([layout](docs/development.md#typescript-project-layout)).
|
||||
- **Error handling:** use typed, structured failures and localized, actionable reports. Coded errors and expected tool failures use `HarnessError`. Define handling ownership, containment, and failure guarantees; stop dependent work and visibly report untrusted state or unknown outcomes. Follow [dsh-error-handling](.agents/skills/dsh-error-handling/SKILL.md).
|
||||
- **An empty `catch` names the error** and why; keep its `try` to one statement.
|
||||
- **An empty `catch` names the error** and why; keep its `try` to one statement ([checker](scripts/verify-empty-catch.ts)).
|
||||
- **Keep comments local.** Do not restate code, expand unrelated comments, or explain distant behavior without local need ([rationale](.agents/skills/dsh-prose-standard/SKILL.md)).
|
||||
- **Ban `prove` + `nance`** ([rule](.agents/notes/implemented/process/2026-08-26-ban-ambiguous-origin-label.md)).
|
||||
- **Prefer symmetry for parallel values**; unexplained asymmetry usually signals a missed extraction.
|
||||
|
||||
@@ -111,6 +111,7 @@
|
||||
"verify-repository-references": "tsx scripts/verify-repository-references.ts",
|
||||
"verify-concrete-terms": "tsx scripts/verify-concrete-terms.ts",
|
||||
"verify-no-unknown-casts": "tsx scripts/verify-no-unknown-casts.ts",
|
||||
"verify-empty-catch": "tsx scripts/verify-empty-catch.ts",
|
||||
"verify-doc-refs": "tsx scripts/verify-doc-refs.ts",
|
||||
"verify-subsystem-pages": "tsx scripts/verify-subsystem-pages.ts",
|
||||
"verify-package-paths": "tsx scripts/verify-package-paths.ts",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Temporary-repository fixture shared by recorded-inventory gate specs. */
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
/** Repository roots created by {@link createInventoryRepo}, removed by {@link removeInventoryRepos}. */
|
||||
const roots: string[] = []
|
||||
|
||||
/**
|
||||
* Write one fixture file, creating its parent directories.
|
||||
* @param root - fixture repository root.
|
||||
* @param file - repository-relative path.
|
||||
* @param contents - file text.
|
||||
*/
|
||||
export function writeFixture(root: string, file: string, contents: string): void {
|
||||
const path = join(root, file)
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, contents)
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one Git command in a fixture repository.
|
||||
* @param root - fixture repository root.
|
||||
* @param args - Git arguments.
|
||||
*/
|
||||
export function gitFixture(root: string, ...args: string[]): void {
|
||||
execFileSync('git', args, { cwd: root, stdio: 'pipe' })
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary repository with one seed source file per scanned area and an empty inventory.
|
||||
* @param baselinePath - repository-relative inventory path the gate reads.
|
||||
* @param seed - contents of each area's seed source file.
|
||||
* @returns the repository root, tracked for {@link removeInventoryRepos}.
|
||||
*/
|
||||
export function createInventoryRepo(baselinePath: string, seed: string): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-inventory-'))
|
||||
roots.push(root)
|
||||
gitFixture(root, 'init', '--quiet')
|
||||
for (const area of ['packages', 'apps', 'scripts', 'website']) {
|
||||
writeFixture(root, `${area}/seed.ts`, seed)
|
||||
}
|
||||
writeFixture(root, baselinePath, '{}\n')
|
||||
gitFixture(root, 'add', '.')
|
||||
return root
|
||||
}
|
||||
|
||||
/** Remove every repository created by {@link createInventoryRepo}. */
|
||||
export function removeInventoryRepos(): void {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* Recorded-inventory bookkeeping for gates that reject one source form.
|
||||
*
|
||||
* A gate scans first-party source, records the findings that predate its rule as a fingerprint
|
||||
* inventory, and rejects a finding the inventory does not allow. Keying by repository path and by
|
||||
* the finding's syntax tokens keeps an allowance across formatting and comment edits, while a
|
||||
* changed form needs a new allowance. Fixing a recorded finding leaves a stale allowance, which
|
||||
* `--prune` retires.
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import ts from 'typescript'
|
||||
|
||||
/** Source areas every inventory gate must find, so a narrowed scan cannot pass silently. */
|
||||
const AREAS = ['packages/', 'apps/', 'scripts/', 'website/'] as const
|
||||
|
||||
/** Source extensions an inventory gate scans, including tests and configuration files. */
|
||||
const SOURCE_EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/u
|
||||
|
||||
/** Existing finding counts, keyed by repository path and syntax fingerprint. */
|
||||
export type InventoryBaseline = Record<string, Record<string, number>>
|
||||
|
||||
/** One finding a gate rejects unless the inventory records it. */
|
||||
export interface InventoryFinding {
|
||||
/** Repository-relative path with forward slashes. */
|
||||
file: string
|
||||
/** SHA-256 of the finding's syntax tokens, excluding comments and whitespace. */
|
||||
fingerprint: string
|
||||
}
|
||||
|
||||
/** Everything shared inventory bookkeeping needs to know about one gate. */
|
||||
export interface InventoryGate<T extends InventoryFinding> {
|
||||
/** Gate name that prefixes every diagnostic and names the `pnpm run` script. */
|
||||
name: string
|
||||
/** Repository-relative path of the recorded inventory. */
|
||||
baselinePath: string
|
||||
/** Scan first-party source for the rejected form. */
|
||||
scan: (repoRoot: string) => T[]
|
||||
/** Rejection text after the gate name for a finding the inventory does not allow. */
|
||||
rejection: string
|
||||
/** One line describing a finding, appended to {@link rejection}. */
|
||||
describe: (finding: T) => string
|
||||
/** Console line for a passing run, given the number of recorded findings. */
|
||||
success: (count: number) => string
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a repository path belongs to an inventory gate's corpus.
|
||||
* @param file - repository-relative path with forward slashes.
|
||||
* @returns `true` for first-party source outside vendored code and frozen archived notes.
|
||||
*/
|
||||
export function isInventorySource(file: string): boolean {
|
||||
return SOURCE_EXTENSIONS.test(file)
|
||||
&& !file.startsWith('vendor/')
|
||||
&& !file.startsWith('.agents/notes/archived/')
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash a node's syntax tokens, so formatting and comment edits keep one identity.
|
||||
* @param node - the node whose form the inventory records.
|
||||
* @param source - the file that owns the node.
|
||||
* @returns SHA-256 of the node's token texts.
|
||||
*/
|
||||
export function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
|
||||
const tokens: string[] = []
|
||||
const visit = (child: ts.Node): void => {
|
||||
if (ts.isJSDoc(child)) return
|
||||
if (ts.isToken(child)) tokens.push(child.getText(source))
|
||||
else child.getChildren(source).forEach(visit)
|
||||
}
|
||||
visit(node)
|
||||
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* List the first-party source paths a gate scans.
|
||||
* @param repoRoot - repository root containing the Git index.
|
||||
* @param name - gate name for diagnostics.
|
||||
* @returns sorted repository-relative paths of tracked and non-ignored untracked source files.
|
||||
* @throws when a required source area is missing or an eligible path is a symlink.
|
||||
*/
|
||||
export function listInventorySources(repoRoot: string, name: string): string[] {
|
||||
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isInventorySource))].sort()
|
||||
const present = files.filter((file) => {
|
||||
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
|
||||
if (stat?.isSymbolicLink()) throw new Error(`${name}: source symlink is unsupported: ${file}`)
|
||||
return stat?.isFile() === true
|
||||
})
|
||||
for (const area of AREAS) {
|
||||
if (!present.some(file => file.startsWith(area))) {
|
||||
throw new Error(`${name}: source discovery omitted ${area}`)
|
||||
}
|
||||
}
|
||||
return present
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and validate one recorded inventory.
|
||||
* @param gate - the gate whose findings the inventory allows.
|
||||
* @param repoRoot - repository root holding the inventory.
|
||||
* @returns the recorded counts, keyed by repository path and fingerprint.
|
||||
* @throws when the inventory is malformed or names a path outside the gate's corpus.
|
||||
*/
|
||||
export function readInventoryBaseline<T extends InventoryFinding>(
|
||||
gate: InventoryGate<T>,
|
||||
repoRoot: string,
|
||||
): InventoryBaseline {
|
||||
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, gate.baselinePath), 'utf8'))
|
||||
if (!isRecord(value)) throw new Error(`${gate.name}: baseline must be a file-to-counts object`)
|
||||
const baseline: InventoryBaseline = {}
|
||||
for (const [file, counts] of Object.entries(value)) {
|
||||
if (!isInventorySource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|
||||
|| !isRecord(counts) || Object.keys(counts).length === 0) {
|
||||
throw new Error(`${gate.name}: invalid baseline file: ${file}`)
|
||||
}
|
||||
const parsed: Record<string, number> = {}
|
||||
for (const [fingerprint, count] of Object.entries(counts)) {
|
||||
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
|
||||
throw new Error(`${gate.name}: invalid baseline count: ${file}:${fingerprint}`)
|
||||
}
|
||||
parsed[fingerprint] = count
|
||||
}
|
||||
baseline[file] = parsed
|
||||
}
|
||||
return baseline
|
||||
}
|
||||
|
||||
/**
|
||||
* Count exact findings without granting a file-wide allowance.
|
||||
* @param findings - observed findings.
|
||||
* @returns path and fingerprint counts in stable order for comparison and pruning.
|
||||
*/
|
||||
export function countInventory(findings: readonly InventoryFinding[]): InventoryBaseline {
|
||||
const baseline: InventoryBaseline = {}
|
||||
for (const { file, fingerprint } of findings) {
|
||||
const counts = baseline[file] ??= {}
|
||||
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
|
||||
}
|
||||
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce one gate's recorded inventory, optionally deleting retired allowances.
|
||||
* @param gate - the gate to enforce.
|
||||
* @param repoRoot - repository root to scan.
|
||||
* @param prune - remove stale entries only after establishing that no new finding exists.
|
||||
* @returns the number of findings still present.
|
||||
* @throws for new findings, malformed inventories, or stale entries without pruning.
|
||||
*/
|
||||
export function verifyInventory<T extends InventoryFinding>(
|
||||
gate: InventoryGate<T>,
|
||||
repoRoot: string,
|
||||
prune = false,
|
||||
): number {
|
||||
const baseline = readInventoryBaseline(gate, repoRoot)
|
||||
const findings = gate.scan(repoRoot)
|
||||
const remaining = structuredClone(baseline)
|
||||
const added: T[] = []
|
||||
for (const finding of findings) {
|
||||
const counts = remaining[finding.file]
|
||||
const allowance = counts?.[finding.fingerprint] ?? 0
|
||||
if (counts !== undefined && allowance > 0) counts[finding.fingerprint] = allowance - 1
|
||||
else added.push(finding)
|
||||
}
|
||||
if (added.length > 0) {
|
||||
throw new Error(`${gate.name}: ${gate.rejection}\n`
|
||||
+ added.map(finding => ` ${gate.describe(finding)}`).join('\n'))
|
||||
}
|
||||
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
|
||||
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
|
||||
if (stale.length > 0) {
|
||||
if (!prune) {
|
||||
throw new Error(`${gate.name}: remove retired baseline entries with pnpm run ${gate.name} --prune.\n`
|
||||
+ stale.join('\n'))
|
||||
}
|
||||
writeFileSync(resolve(repoRoot, gate.baselinePath), `${JSON.stringify(countInventory(findings), null, 2)}\n`)
|
||||
}
|
||||
return findings.length
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one gate as a command: `--prune` retires stale entries, anything else fails the process.
|
||||
* @param gate - the gate to enforce.
|
||||
* @param root - repository root to scan.
|
||||
*/
|
||||
export function runInventoryGate<T extends InventoryFinding>(gate: InventoryGate<T>, root: string): void {
|
||||
try {
|
||||
const args = process.argv.slice(2)
|
||||
if (args.length > 1 || (args.length === 1 && args[0] !== '--prune')) {
|
||||
throw new Error(`Usage: pnpm run ${gate.name} [--prune]`)
|
||||
}
|
||||
console.log(gate.success(verifyInventory(gate, root, args[0] === '--prune')))
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
{
|
||||
"apps/cli/tests/built-bin.e2e.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"apps/web/tests/chat-scroll-contract.e2e.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"apps/web/tests/support.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/api/gateway/src/client/remote-stream.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/api/gateway/tests/gateway-stream.host.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/api/workspace-files/src/client/change-feed.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/boot/app-boot/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/boot/hmr/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/boot/plugin-manager/src/registry.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/client/modules/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/client/store/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/client/ui-open-in-app/src/client/controller.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/client/ui-open-in-app/src/client/open-path.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/client/ui-sidebar-browser/src/client/browser/url.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/client/ui-sidebar-right/src/client/tab-inventory.ts": {
|
||||
"e97a9c346a760763bd576d2b89b55a62bc5abaddf29ca057aac0b5b855eb4a04": 1
|
||||
},
|
||||
"packages/client/ui-skill/src/client/SkillRow.tsx": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/context/file-reference-local/tests/search.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/client/bridge/transport.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/client/cdp/console.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/experimental/inspector/src/client/inspection/realm.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/bridge/hub.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/bridge/runtime-rpc.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 4
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/bridge/session.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/cdp/domains/dom/model.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/cdp/realm-sessions.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/inspection/cordis-store.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/inspection/network-store.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/inspection/query-router.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/inspection/realm-store.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/realms/host/bridge.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"packages/experimental/inspector/src/worker/realms/host/sources.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/ptc-runtime-python/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 5
|
||||
},
|
||||
"packages/experimental/webworker-runtime/src/client/client.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/webworker-runtime/src/transport/tunnel.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/webworker-runtime/tests/compile/transform-corpus-check.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/experimental/webworker-runtime/tests/polyfill/als-shim.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/host/directory-picker-browse/tests/service.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/host/open-in-app/src/icons.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/host/open-in-app/src/resolver.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/identity/anonymous-user-id/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/llm/llm-deepseek/src/file-store.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/llm/llm-deepseek/src/files-api.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/llm/llm-pi-ai/src/replay.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/llm/llm/src/adapter-failure.ts": {
|
||||
"deaf1f3ce375367e779f482ad95bad5556ef9f3d53b67df6011c9d8cebe319e9": 1
|
||||
},
|
||||
"packages/lsp/lsp-stdio/src/instance.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/session-query/session-query-sqlite/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/session-query/session-query/src/cold-read.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/src/generation.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/session/session-persistence-jsonl/tests/zstd.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/shell/bash-local/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/shell/pwsh-local/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/skill/skill-filesystem/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/skill/skill/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/spill/spill-local/src/cleanup.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subagent/subagent-acp/src/run.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subagent/subagent-claude-code/src/run.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subagent/subagent-codex/src/run.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"packages/subagent/subagent-dsh-sdk/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subagent/subagent-dsh-sdk/src/run.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subagent/subagent/src/out-of-process.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/index.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/linux-scope.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 5
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/output.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/runner-protocol.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/spawn-runner.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 6
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/spawn.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"packages/subprocess/subprocess-local/src/windows-job.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subprocess/subprocess-local/tests/native-containment.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"packages/subprocess/subprocess-local/tests/native-windows.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/subprocess/subprocess-local/tests/spawn.spec.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 6
|
||||
},
|
||||
"packages/test-support/client-runtime/src/assembly/test-client.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"packages/webhook/webhook-github/src/handler.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"scripts/gen-cordis-catalog.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"scripts/gen-session-format-catalog.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"scripts/run-gates.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3
|
||||
},
|
||||
"scripts/slot-walk.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"vitest.e2e.config.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
},
|
||||
"vitest.web.config.ts": {
|
||||
"d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1
|
||||
}
|
||||
}
|
||||
@@ -383,7 +383,7 @@ describe('gate graph validation', () => {
|
||||
'rescope-vendor', 'publint', 'constraints', 'default-product-isolation', 'product-use', 'official-bundle-catalog', 'provider-data', 'package-dependencies', 'application-entrypoints',
|
||||
'dsh-package-licenses', 'node-next-types',
|
||||
'optional-dependency-imports', 'client-packages', 'installer-locales', 'locale-metadata', 'client-ui-i18n', 'client-route-resolution', 'no-bare-dispatcher',
|
||||
'plugin-record-callers', 'no-unknown-casts', 'no-top-level-await', 'plugin-entry-exports',
|
||||
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'no-top-level-await', 'plugin-entry-exports',
|
||||
'cordis-config', 'runtime-closure',
|
||||
])
|
||||
})
|
||||
@@ -449,6 +449,16 @@ describe('gate graph validation', () => {
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
|
||||
'rejects silent empty catches in %s',
|
||||
(mode) => {
|
||||
const gate = withPnpmEntrypoint(() => gatesForMode(mode).find(subject => subject.id === 'empty-catch'))
|
||||
|
||||
expect(gate?.args).toContain('verify-empty-catch')
|
||||
expect(gate?.allowFailure).not.toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
|
||||
'keeps package dependency enforcement in %s',
|
||||
(mode) => {
|
||||
|
||||
@@ -424,6 +424,7 @@ function sharedHygieneGates(): Gate[] {
|
||||
pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
|
||||
pnpmScript('plugin-record-callers', 'verify-plugin-record-callers', { label: 'plugin record callers' }),
|
||||
pnpmScript('no-unknown-casts', 'verify-no-unknown-casts', { label: 'no new unknown casts' }),
|
||||
pnpmScript('empty-catch', 'verify-empty-catch', { label: 'no new silent catches' }),
|
||||
pnpmScript('no-top-level-await', 'verify-no-top-level-await', { label: 'no module-scope await' }),
|
||||
pnpmScript('plugin-entry-exports', 'verify-plugin-entry-exports', { label: 'plugin entry exports' }),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { readFileSync, symlinkSync, unlinkSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { createInventoryRepo, gitFixture as git, removeInventoryRepos, writeFixture as write } from './baseline-inventory.fixture.ts'
|
||||
import { countEmptyCatches, findEmptyCatches, scanEmptyCatches, verifyEmptyCatch } from './verify-empty-catch.ts'
|
||||
|
||||
const baselinePath = 'scripts/empty-catch.baseline.json'
|
||||
const sourcePath = 'packages/example/src/index.ts'
|
||||
const seed = 'try { run() } catch (_failure) { /* seed */ }\n'
|
||||
const broken = 'try { run() } catch {}\n'
|
||||
|
||||
afterEach(removeInventoryRepos)
|
||||
|
||||
function fixture(): string {
|
||||
return createInventoryRepo(baselinePath, seed)
|
||||
}
|
||||
|
||||
function recordBaseline(root: string): string {
|
||||
const text = `${JSON.stringify(countEmptyCatches(scanEmptyCatches(root)), null, 2)}\n`
|
||||
write(root, baselinePath, text)
|
||||
return text
|
||||
}
|
||||
|
||||
function defects(file: string, text: string): (readonly string[])[] {
|
||||
return findEmptyCatches(file, text).map(finding => finding.defects)
|
||||
}
|
||||
|
||||
describe('empty catch syntax', () => {
|
||||
it.each([
|
||||
['unbound and unexplained', 'try { run() } catch {}', ['unnamed', 'unexplained']],
|
||||
['unbound with a reason', 'try { run() } catch { /* already gone */ }', ['unnamed']],
|
||||
['bound without a reason', 'try { run() } catch (_missing) {}', ['unexplained']],
|
||||
['bound to a bare underscore', 'try { run() } catch (_) { /* already gone */ }', ['unnamed']],
|
||||
['reason between the keyword and the block', 'try { run() } catch /* already gone */ {}', ['unnamed']],
|
||||
['comment above the statement', '// already gone\ntry { run() } catch {}', ['unnamed', 'unexplained']],
|
||||
['multi-statement try', 'try { first(); second() } catch (_missing) { /* already gone */ }', ['wide-try']],
|
||||
['a nested clause inside a handled clause', 'try { run() } catch (error) { try { log() } catch {} }', ['unnamed', 'unexplained']],
|
||||
])('reports %s', (_name, text, expected) => {
|
||||
expect(defects('input.ts', text)).toEqual([expected])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a named and explained clause', 'try { run() } catch (_missing) { /* already gone */ }'],
|
||||
['an ordinary binding name', 'try { run() } catch (error) { /* reported above */ }'],
|
||||
['a finally block', 'try { run() } catch (_missing) { /* already gone */ } finally { stop() }'],
|
||||
['a destructured binding', 'try { run() } catch ({ message }) { /* reported above */ }'],
|
||||
['a handled clause around a conforming clause', 'try { run() } catch (error) { try { log() } catch (_inner) { /* reported */ } }'],
|
||||
])('accepts %s', (_name, text) => {
|
||||
expect(findEmptyCatches('input.ts', text)).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a handled clause', 'try { run() } catch (error) { report(error) }'],
|
||||
['a clause that rethrows', 'try { run() } catch (error) { throw error }'],
|
||||
['a clause with a return', 'try { return run() } catch { return undefined }'],
|
||||
['comment text inside a string', 'try { run() } catch (error) { report("// not a comment") }'],
|
||||
])('ignores %s', (_name, text) => {
|
||||
expect(findEmptyCatches('input.ts', text)).toEqual([])
|
||||
})
|
||||
|
||||
it('parses TSX so a JSX sibling does not hide the clause', () => {
|
||||
const text = 'export const view = <View onClick={() => { try { run() } catch {} }} />\n'
|
||||
expect(defects('input.tsx', text)).toEqual([['unnamed', 'unexplained']])
|
||||
})
|
||||
|
||||
it('reports normalized paths and the catch keyword line', () => {
|
||||
const findings = findEmptyCatches('packages\\example\\index.ts', '\n\ntry { run() }\ncatch {}')
|
||||
expect(findings).toHaveLength(1)
|
||||
expect(findings[0]).toMatchObject({ file: 'packages/example/index.ts', line: 4 })
|
||||
expect(findings[0]?.fingerprint).toMatch(/^[a-f0-9]{64}$/u)
|
||||
})
|
||||
|
||||
it('keeps syntax fingerprints through whitespace and comment edits', () => {
|
||||
const original = findEmptyCatches('input.ts', 'try { run() } catch (_missing) {}')
|
||||
const formatted = findEmptyCatches('input.ts', '\ntry {\n /* retried above */ run()\n}\ncatch (\n_missing\n) {\n}\n')
|
||||
expect(formatted.map(finding => finding.fingerprint)).toEqual(original.map(finding => finding.fingerprint))
|
||||
expect(findEmptyCatches('input.ts', 'try { run() } catch (_other) {}').map(finding => finding.fingerprint))
|
||||
.not.toEqual(original.map(finding => finding.fingerprint))
|
||||
})
|
||||
|
||||
it('counts identical clauses per file', () => {
|
||||
expect(countEmptyCatches(findEmptyCatches('input.ts', `${broken}${broken}`))).toEqual({
|
||||
'input.ts': { [findEmptyCatches('input.ts', broken)[0]?.fingerprint ?? '']: 2 },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty catch inventory', () => {
|
||||
it('accepts a recorded clause after formatting without rewriting the baseline', () => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, broken)
|
||||
const baseline = recordBaseline(root)
|
||||
write(root, sourcePath, 'try { run() }\ncatch {\n}\n')
|
||||
expect(verifyEmptyCatch(root)).toBe(1)
|
||||
expect(verifyEmptyCatch(root, true)).toBe(1)
|
||||
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['additional clause', `${broken}${broken}`],
|
||||
['differently bound clause', 'try { stop() } catch (error) {}\n'],
|
||||
['unexplained clause', 'try { run() } catch (_missing) {}\n'],
|
||||
['wide try', 'try { first(); second() } catch (_missing) { /* reason */ }\n'],
|
||||
])('rejects an %s without changing the baseline', (_name, text) => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, broken)
|
||||
const baseline = recordBaseline(root)
|
||||
write(root, sourcePath, text)
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(/verify-empty-catch: an empty catch/u)
|
||||
expect(() => verifyEmptyCatch(root, true)).toThrow(/verify-empty-catch: an empty catch/u)
|
||||
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
|
||||
})
|
||||
|
||||
it('keeps a recorded clause inside its file allowance when an identical shape moves', () => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, broken)
|
||||
recordBaseline(root)
|
||||
write(root, sourcePath, 'try { stop() } catch {}\n')
|
||||
expect(verifyEmptyCatch(root)).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects a new clause when the inventory is empty', () => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, broken)
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(`${sourcePath}:1 (unnamed, unexplained)`)
|
||||
})
|
||||
|
||||
it('requires pruning retired counts while preserving the remaining clause', () => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, `${broken}${broken}`)
|
||||
write(root, 'apps/retired.ts', broken)
|
||||
recordBaseline(root)
|
||||
write(root, sourcePath, broken)
|
||||
unlinkSync(join(root, 'apps/retired.ts'))
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(/remove retired baseline entries/u)
|
||||
expect(verifyEmptyCatch(root, true)).toBe(1)
|
||||
expect(JSON.parse(readFileSync(join(root, baselinePath), 'utf8'))).toEqual(
|
||||
countEmptyCatches(findEmptyCatches(sourcePath, broken)),
|
||||
)
|
||||
expect(verifyEmptyCatch(root)).toBe(1)
|
||||
})
|
||||
|
||||
it('prunes a fixed clause and a deleted tracked file without treating them as discovery failures', () => {
|
||||
const root = fixture()
|
||||
write(root, sourcePath, broken)
|
||||
git(root, 'add', sourcePath)
|
||||
recordBaseline(root)
|
||||
write(root, sourcePath, seed)
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(/remove retired baseline entries/u)
|
||||
expect(verifyEmptyCatch(root, true)).toBe(0)
|
||||
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n')
|
||||
})
|
||||
|
||||
// The shared inventory reader owns the complete malformed-input table; these two rows prove this
|
||||
// gate reads through it rather than around it.
|
||||
it.each([
|
||||
['not an object', '[]'],
|
||||
['excluded path', '{"vendor/input.ts":{"HASH":1}}'],
|
||||
])('rejects a malformed baseline: %s', (_name, text) => {
|
||||
const root = fixture()
|
||||
const contents = text.replaceAll('HASH', 'a'.repeat(64))
|
||||
write(root, baselinePath, contents)
|
||||
expect(() => verifyEmptyCatch(root, true)).toThrow()
|
||||
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(contents)
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty catch source discovery', () => {
|
||||
it('checks tracked source across areas, extensions and tests', () => {
|
||||
const root = fixture()
|
||||
const files = [
|
||||
'packages/example/src/input.ts',
|
||||
'apps/example/input.tsx',
|
||||
'scripts/input.mts',
|
||||
'website/input.cts',
|
||||
'packages/example/tests/input.js',
|
||||
'apps/example/input.jsx',
|
||||
'scripts/input.mjs',
|
||||
'website/input.cjs',
|
||||
]
|
||||
for (const file of files) write(root, file, broken)
|
||||
git(root, 'add', '.')
|
||||
expect(scanEmptyCatches(root).map(finding => finding.file)).toEqual(files.toSorted())
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(/verify-empty-catch: an empty catch/u)
|
||||
})
|
||||
|
||||
it('includes untracked source while excluding ignored files, vendor, archives and other extensions', () => {
|
||||
const root = fixture()
|
||||
write(root, '.gitignore', 'ignored/\n')
|
||||
for (const file of ['ignored/input.ts', 'vendor/input.ts', '.agents/notes/archived/input.ts', 'docs/input.md']) {
|
||||
write(root, file, broken)
|
||||
}
|
||||
git(root, 'add', '.')
|
||||
write(root, 'scripts/new.ts', broken)
|
||||
expect(scanEmptyCatches(root).map(finding => finding.file)).toEqual(['scripts/new.ts'])
|
||||
expect(() => verifyEmptyCatch(root)).toThrow('scripts/new.ts:1')
|
||||
unlinkSync(join(root, 'scripts/new.ts'))
|
||||
expect(verifyEmptyCatch(root)).toBe(0)
|
||||
})
|
||||
|
||||
it.each(['packages', 'apps', 'scripts', 'website'])('rejects discovery missing %s', (area) => {
|
||||
const root = fixture()
|
||||
unlinkSync(join(root, `${area}/seed.ts`))
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(`source discovery omitted ${area}/`)
|
||||
})
|
||||
|
||||
it('rejects a corpus without any catch clause', () => {
|
||||
const root = fixture()
|
||||
for (const area of ['packages', 'apps', 'scripts', 'website']) write(root, `${area}/seed.ts`, 'export {}\n')
|
||||
expect(() => verifyEmptyCatch(root)).toThrow(/found no catch clause/u)
|
||||
})
|
||||
|
||||
// Creating file symlinks requires privileges that Windows CI does not guarantee.
|
||||
it.skipIf(process.platform === 'win32')('rejects a source symlink', () => {
|
||||
const root = fixture()
|
||||
write(root, 'target.txt', broken)
|
||||
const link = join(root, 'scripts/linked.ts')
|
||||
symlinkSync(join(root, 'target.txt'), link)
|
||||
try {
|
||||
expect(() => verifyEmptyCatch(root)).toThrow('source symlink is unsupported: scripts/linked.ts')
|
||||
} finally {
|
||||
unlinkSync(link)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Reject empty `catch` clauses that break the recorded rule, retiring the legacy clauses.
|
||||
*
|
||||
* A clause with statements carries a disposition this checker cannot judge, so only an empty
|
||||
* block is in scope. An empty clause must name the discarded error, state in a comment why the
|
||||
* error needs no handling, and wrap a `try` holding one statement; a wider `try` hides
|
||||
* statements whose failures the clause also discards. Legacy clauses that break a condition are
|
||||
* recorded in `scripts/empty-catch.baseline.json`, and fixing one requires `--prune` to retire
|
||||
* its entry.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import ts from 'typescript'
|
||||
import {
|
||||
countInventory,
|
||||
listInventorySources,
|
||||
runInventoryGate,
|
||||
syntaxFingerprint,
|
||||
verifyInventory,
|
||||
type InventoryBaseline,
|
||||
type InventoryGate,
|
||||
} from './baseline-inventory.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
/** Existing empty-clause counts, keyed by repository path and syntax fingerprint. */
|
||||
export type EmptyCatchBaseline = InventoryBaseline
|
||||
|
||||
/** One condition of the rule that an empty clause breaks. */
|
||||
export type EmptyCatchDefect = 'unnamed' | 'unexplained' | 'wide-try'
|
||||
|
||||
/** One empty `catch` clause that breaks at least one condition. */
|
||||
export interface EmptyCatch {
|
||||
/** Repository-relative path with forward slashes. */
|
||||
file: string
|
||||
/** One-based line of the `catch` keyword. */
|
||||
line: number
|
||||
/** SHA-256 of the clause's syntax tokens, excluding comments and whitespace. */
|
||||
fingerprint: string
|
||||
/** Broken conditions in {@link EmptyCatchDefect} order. */
|
||||
defects: readonly EmptyCatchDefect[]
|
||||
}
|
||||
|
||||
/** Findings plus the number of clauses examined, which detects a walk that stopped matching. */
|
||||
interface EmptyCatchScan {
|
||||
findings: EmptyCatch[]
|
||||
clauses: number
|
||||
}
|
||||
|
||||
function scriptKind(file: string): ts.ScriptKind {
|
||||
if (file.endsWith('.tsx')) return ts.ScriptKind.TSX
|
||||
if (file.endsWith('.jsx')) return ts.ScriptKind.JSX
|
||||
if (/\.(?:js|mjs|cjs)$/u.test(file)) return ts.ScriptKind.JS
|
||||
return ts.ScriptKind.TS
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the span holds a comment token.
|
||||
*
|
||||
* Scanning the span keeps comment markers inside a string or template literal from counting.
|
||||
* @param text - the whole source file.
|
||||
* @param from - inclusive start offset of the span.
|
||||
* @param to - exclusive end offset of the span.
|
||||
* @returns `true` when the span holds a line or block comment.
|
||||
*/
|
||||
function hasComment(text: string, from: number, to: number): boolean {
|
||||
const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, text.slice(from, to))
|
||||
for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
|
||||
if (kind === ts.SyntaxKind.SingleLineCommentTrivia || kind === ts.SyntaxKind.MultiLineCommentTrivia) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Bound name of the thrown value, or `undefined` for `catch {`. */
|
||||
function bindingName(clause: ts.CatchClause, source: ts.SourceFile): string | undefined {
|
||||
const declaration = clause.variableDeclaration
|
||||
return declaration === undefined ? undefined : declaration.name.getText(source)
|
||||
}
|
||||
|
||||
function analyze(file: string, text: string): EmptyCatchScan {
|
||||
const normalized = file.replaceAll('\\', '/')
|
||||
const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true, scriptKind(normalized))
|
||||
const findings: EmptyCatch[] = []
|
||||
let clauses = 0
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (ts.isCatchClause(node)) {
|
||||
clauses += 1
|
||||
if (node.block.statements.length === 0) {
|
||||
const name = bindingName(node, source)
|
||||
const defects: EmptyCatchDefect[] = []
|
||||
if (name === undefined || name === '_') defects.push('unnamed')
|
||||
if (!hasComment(text, node.getStart(source), node.end)) defects.push('unexplained')
|
||||
if (!ts.isTryStatement(node.parent) || node.parent.tryBlock.statements.length !== 1) defects.push('wide-try')
|
||||
if (defects.length > 0) {
|
||||
findings.push({
|
||||
file: normalized,
|
||||
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
||||
fingerprint: syntaxFingerprint(node, source),
|
||||
defects,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
return { findings, clauses }
|
||||
}
|
||||
|
||||
/**
|
||||
* Find empty catch clauses that break the rule.
|
||||
* @param file - repository-relative source path; its extension selects the parse mode.
|
||||
* @param text - source contents.
|
||||
* @returns findings in AST traversal order; clauses with statements never match.
|
||||
*/
|
||||
export function findEmptyCatches(file: string, text: string): EmptyCatch[] {
|
||||
return analyze(file, text).findings
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan tracked source and non-ignored new source, including tests and configuration files.
|
||||
* @param repoRoot - repository root containing the Git index.
|
||||
* @returns every empty clause that breaks the rule in the current working tree.
|
||||
* @throws if discovery omits a required source area, finds no catch clause at all, or an eligible path is a symlink.
|
||||
*/
|
||||
export function scanEmptyCatches(repoRoot: string): EmptyCatch[] {
|
||||
const scans = listInventorySources(repoRoot, 'verify-empty-catch')
|
||||
.map(file => analyze(file, readFileSync(resolve(repoRoot, file), 'utf8')))
|
||||
if (scans.every(scan => scan.clauses === 0)) {
|
||||
throw new Error('verify-empty-catch: source discovery found no catch clause')
|
||||
}
|
||||
return scans.flatMap(scan => scan.findings)
|
||||
}
|
||||
|
||||
const gate: InventoryGate<EmptyCatch> = {
|
||||
name: 'verify-empty-catch',
|
||||
baselinePath: 'scripts/empty-catch.baseline.json',
|
||||
scan: scanEmptyCatches,
|
||||
rejection: 'an empty catch must name the discarded error, state why it needs no handling,'
|
||||
+ ' and keep its try to one statement.',
|
||||
describe: finding => `${finding.file}:${String(finding.line)} (${finding.defects.join(', ')})`,
|
||||
success: count => `verify-empty-catch: no new silent catches; ${String(count)} recorded clauses remain.`,
|
||||
}
|
||||
|
||||
/**
|
||||
* Count exact clauses without granting a file-wide allowance.
|
||||
* @param findings - observed empty clauses.
|
||||
* @returns path and fingerprint counts in stable order for comparison and pruning.
|
||||
*/
|
||||
export function countEmptyCatches(findings: readonly EmptyCatch[]): EmptyCatchBaseline {
|
||||
return countInventory(findings)
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce the recorded clause inventory, optionally deleting retired allowances.
|
||||
* @param repoRoot - repository root to scan.
|
||||
* @param prune - remove stale entries only after establishing that no new clause breaks the rule.
|
||||
* @returns the number of clauses that still break the rule.
|
||||
* @throws for new broken clauses, malformed inventories, or stale entries without pruning.
|
||||
*/
|
||||
export function verifyEmptyCatch(repoRoot: string, prune = false): number {
|
||||
return verifyInventory(gate, repoRoot, prune)
|
||||
}
|
||||
|
||||
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
|
||||
runInventoryGate(gate, root)
|
||||
}
|
||||
@@ -1,39 +1,17 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { readFileSync, symlinkSync, unlinkSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { createInventoryRepo, gitFixture as git, removeInventoryRepos, writeFixture as write } from './baseline-inventory.fixture.ts'
|
||||
import { countUnknownCasts, findUnknownCasts, scanUnknownCasts, verifyNoUnknownCasts } from './verify-no-unknown-casts.ts'
|
||||
|
||||
const roots: string[] = []
|
||||
const baselinePath = 'scripts/no-unknown-casts.baseline.json'
|
||||
const sourcePath = 'packages/example/src/index.ts'
|
||||
const assertion = 'const result = value as unknown\n'
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function write(root: string, file: string, contents: string): void {
|
||||
const path = join(root, file)
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, contents)
|
||||
}
|
||||
|
||||
function git(root: string, ...args: string[]): void {
|
||||
execFileSync('git', args, { cwd: root, stdio: 'pipe' })
|
||||
}
|
||||
afterEach(removeInventoryRepos)
|
||||
|
||||
function fixture(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-unknown-casts-'))
|
||||
roots.push(root)
|
||||
git(root, 'init', '--quiet')
|
||||
for (const area of ['packages', 'apps', 'scripts', 'website']) {
|
||||
write(root, `${area}/seed.ts`, 'export {}\n')
|
||||
}
|
||||
write(root, baselinePath, '{}\n')
|
||||
git(root, 'add', '.')
|
||||
return root
|
||||
return createInventoryRepo(baselinePath, 'export {}\n')
|
||||
}
|
||||
|
||||
function recordBaseline(root: string): string {
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
/** Reject new assertions to unknown while retiring the recorded existing assertions. */
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import ts from 'typescript'
|
||||
import {
|
||||
countInventory,
|
||||
listInventorySources,
|
||||
runInventoryGate,
|
||||
syntaxFingerprint,
|
||||
verifyInventory,
|
||||
type InventoryBaseline,
|
||||
type InventoryGate,
|
||||
} from './baseline-inventory.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const baselinePath = 'scripts/no-unknown-casts.baseline.json'
|
||||
|
||||
/** Existing assertion counts, keyed by repository path and syntax fingerprint. */
|
||||
export type UnknownCastBaseline = Record<string, Record<string, number>>
|
||||
export type UnknownCastBaseline = InventoryBaseline
|
||||
|
||||
/** One direct assertion to unknown in authored source. */
|
||||
export interface UnknownCast {
|
||||
@@ -22,17 +28,6 @@ export interface UnknownCast {
|
||||
fingerprint: string
|
||||
}
|
||||
|
||||
function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
|
||||
const tokens: string[] = []
|
||||
const visit = (child: ts.Node): void => {
|
||||
if (ts.isJSDoc(child)) return
|
||||
if (ts.isToken(child)) tokens.push(child.getText(source))
|
||||
else child.getChildren(source).forEach(visit)
|
||||
}
|
||||
visit(node)
|
||||
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
|
||||
}
|
||||
|
||||
function assertsUnknown(type: ts.TypeNode): boolean {
|
||||
if (ts.isParenthesizedTypeNode(type)) return assertsUnknown(type.type)
|
||||
return type.kind === ts.SyntaxKind.UnknownKeyword
|
||||
@@ -65,12 +60,6 @@ export function findUnknownCasts(file: string, text: string): UnknownCast[] {
|
||||
return casts
|
||||
}
|
||||
|
||||
function isSource(file: string): boolean {
|
||||
return /\.(?:[cm]?[jt]s|[jt]sx)$/u.test(file)
|
||||
&& !file.startsWith('vendor/')
|
||||
&& !file.startsWith('.agents/notes/archived/')
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan tracked source and non-ignored new source, including tests and configuration files.
|
||||
* @param repoRoot - repository root containing the Git index.
|
||||
@@ -78,47 +67,17 @@ function isSource(file: string): boolean {
|
||||
* @throws if discovery omits a required source area or an eligible path is a symlink.
|
||||
*/
|
||||
export function scanUnknownCasts(repoRoot: string): UnknownCast[] {
|
||||
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isSource))].sort()
|
||||
const present = files.filter((file) => {
|
||||
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
|
||||
if (stat?.isSymbolicLink()) throw new Error(`verify-no-unknown-casts: source symlink is unsupported: ${file}`)
|
||||
return stat?.isFile() === true
|
||||
})
|
||||
for (const area of ['packages/', 'apps/', 'scripts/', 'website/']) {
|
||||
if (!present.some(file => file.startsWith(area))) {
|
||||
throw new Error(`verify-no-unknown-casts: source discovery omitted ${area}`)
|
||||
}
|
||||
}
|
||||
return present.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
|
||||
return listInventorySources(repoRoot, 'verify-no-unknown-casts')
|
||||
.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function readBaseline(repoRoot: string): UnknownCastBaseline {
|
||||
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, baselinePath), 'utf8'))
|
||||
if (!isRecord(value)) throw new Error('verify-no-unknown-casts: baseline must be a file-to-counts object')
|
||||
const baseline: UnknownCastBaseline = {}
|
||||
for (const [file, counts] of Object.entries(value)) {
|
||||
if (!isSource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|
||||
|| !isRecord(counts) || Object.keys(counts).length === 0) {
|
||||
throw new Error(`verify-no-unknown-casts: invalid baseline file: ${file}`)
|
||||
}
|
||||
const parsed: Record<string, number> = {}
|
||||
for (const [fingerprint, count] of Object.entries(counts)) {
|
||||
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
|
||||
throw new Error(`verify-no-unknown-casts: invalid baseline count: ${file}:${fingerprint}`)
|
||||
}
|
||||
parsed[fingerprint] = count
|
||||
}
|
||||
baseline[file] = parsed
|
||||
}
|
||||
return baseline
|
||||
const gate: InventoryGate<UnknownCast> = {
|
||||
name: 'verify-no-unknown-casts',
|
||||
baselinePath: 'scripts/no-unknown-casts.baseline.json',
|
||||
scan: scanUnknownCasts,
|
||||
rejection: 'new assertions to unknown are forbidden. Use a typed value or narrow the input.',
|
||||
describe: cast => `${cast.file}:${String(cast.line)} (${cast.fingerprint})`,
|
||||
success: count => `verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`,
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,13 +86,7 @@ function readBaseline(repoRoot: string): UnknownCastBaseline {
|
||||
* @returns path and fingerprint counts in stable order for comparison and pruning.
|
||||
*/
|
||||
export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBaseline {
|
||||
const baseline: UnknownCastBaseline = {}
|
||||
for (const { file, fingerprint } of casts) {
|
||||
const counts = baseline[file] ??= {}
|
||||
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
|
||||
}
|
||||
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
|
||||
return countInventory(casts)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,43 +97,9 @@ export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBas
|
||||
* @throws for new assertions, malformed inventories, or stale entries without pruning.
|
||||
*/
|
||||
export function verifyNoUnknownCasts(repoRoot: string, prune = false): number {
|
||||
const baseline = readBaseline(repoRoot)
|
||||
const casts = scanUnknownCasts(repoRoot)
|
||||
const current = countUnknownCasts(casts)
|
||||
const remaining = structuredClone(baseline)
|
||||
const added: UnknownCast[] = []
|
||||
for (const cast of casts) {
|
||||
const counts = remaining[cast.file]
|
||||
const allowance = counts?.[cast.fingerprint] ?? 0
|
||||
if (counts !== undefined && allowance > 0) counts[cast.fingerprint] = allowance - 1
|
||||
else added.push(cast)
|
||||
}
|
||||
if (added.length > 0) {
|
||||
throw new Error('verify-no-unknown-casts: new assertions to unknown are forbidden. Use a typed value or narrow the input.\n'
|
||||
+ added.map(cast => ` ${cast.file}:${String(cast.line)} (${cast.fingerprint})`).join('\n'))
|
||||
}
|
||||
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
|
||||
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
|
||||
if (stale.length > 0) {
|
||||
if (!prune) {
|
||||
throw new Error('verify-no-unknown-casts: remove retired baseline entries with pnpm run verify-no-unknown-casts --prune.\n'
|
||||
+ stale.join('\n'))
|
||||
}
|
||||
writeFileSync(resolve(repoRoot, baselinePath), `${JSON.stringify(current, null, 2)}\n`)
|
||||
}
|
||||
return casts.length
|
||||
return verifyInventory(gate, repoRoot, prune)
|
||||
}
|
||||
|
||||
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
|
||||
try {
|
||||
const args = process.argv.slice(2)
|
||||
if (args.length > 1 || (args.length === 1 && args[0] !== '--prune')) {
|
||||
throw new Error('Usage: pnpm run verify-no-unknown-casts [--prune]')
|
||||
}
|
||||
const count = verifyNoUnknownCasts(root, args[0] === '--prune')
|
||||
console.log(`verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`)
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
runInventoryGate(gate, root)
|
||||
}
|
||||
Reference in new issue
Block a user