From 05883ff6b51d41c45fc501bffafec07ff6004398 Mon Sep 17 00:00:00 2001 From: turtle1999 Date: Mon, 21 Sep 2026 23:16:46 +0800 Subject: [PATCH 1/8] 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. --- AGENTS.md | 2 +- package.json | 1 + scripts/baseline-inventory.fixture.ts | 53 ++++++ scripts/baseline-inventory.ts | 209 +++++++++++++++++++++ scripts/empty-catch.baseline.json | 239 ++++++++++++++++++++++++ scripts/run-gates.spec.ts | 12 +- scripts/run-gates.ts | 1 + scripts/verify-empty-catch.spec.ts | 225 ++++++++++++++++++++++ scripts/verify-empty-catch.ts | 168 +++++++++++++++++ scripts/verify-no-unknown-casts.spec.ts | 32 +--- scripts/verify-no-unknown-casts.ts | 127 +++---------- 11 files changed, 936 insertions(+), 133 deletions(-) create mode 100644 scripts/baseline-inventory.fixture.ts create mode 100644 scripts/baseline-inventory.ts create mode 100644 scripts/empty-catch.baseline.json create mode 100644 scripts/verify-empty-catch.spec.ts create mode 100644 scripts/verify-empty-catch.ts diff --git a/AGENTS.md b/AGENTS.md index f189147619..37b385c8bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/package.json b/package.json index afa89fcf07..80cf510e9c 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/scripts/baseline-inventory.fixture.ts b/scripts/baseline-inventory.fixture.ts new file mode 100644 index 0000000000..21a5f8fd61 --- /dev/null +++ b/scripts/baseline-inventory.fixture.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 }) +} diff --git a/scripts/baseline-inventory.ts b/scripts/baseline-inventory.ts new file mode 100644 index 0000000000..82d6035274 --- /dev/null +++ b/scripts/baseline-inventory.ts @@ -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> + +/** 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 { + /** 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 { + 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( + gate: InventoryGate, + 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 = {} + 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( + gate: InventoryGate, + 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(gate: InventoryGate, 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 + } +} diff --git a/scripts/empty-catch.baseline.json b/scripts/empty-catch.baseline.json new file mode 100644 index 0000000000..fa5b1f43b2 --- /dev/null +++ b/scripts/empty-catch.baseline.json @@ -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 + } +} diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 89458b4d2b..462f6c2f18 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -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) => { diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index 782ed05639..f269622944 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -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' }), ] diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts new file mode 100644 index 0000000000..aba2a9892d --- /dev/null +++ b/scripts/verify-empty-catch.spec.ts @@ -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 = { 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) + } + }) +}) diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts new file mode 100644 index 0000000000..c6d3c90548 --- /dev/null +++ b/scripts/verify-empty-catch.ts @@ -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 = { + 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) +} diff --git a/scripts/verify-no-unknown-casts.spec.ts b/scripts/verify-no-unknown-casts.spec.ts index 18dca407fe..25c302f2e8 100644 --- a/scripts/verify-no-unknown-casts.spec.ts +++ b/scripts/verify-no-unknown-casts.spec.ts @@ -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 { diff --git a/scripts/verify-no-unknown-casts.ts b/scripts/verify-no-unknown-casts.ts index d57a108250..680d96bb3a 100644 --- a/scripts/verify-no-unknown-casts.ts +++ b/scripts/verify-no-unknown-casts.ts @@ -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> +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 { - 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 = {} - 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 = { + 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) } From a51a1fc79c87a9664e1dcb5fe604534cd850613a Mon Sep 17 00:00:00 2001 From: turtle1999 Date: Mon, 21 Sep 2026 23:23:18 +0800 Subject: [PATCH 2/8] fix(infra): read a body of empty statements as an empty catch `catch { ; }` counted as a handled clause because the block held one statement. A block whose statements are all bare `;` handles nothing, so both the clause body and its `try` now count only statements that do something. --- scripts/verify-empty-catch.spec.ts | 2 ++ scripts/verify-empty-catch.ts | 11 +++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts index aba2a9892d..6a5184b820 100644 --- a/scripts/verify-empty-catch.spec.ts +++ b/scripts/verify-empty-catch.spec.ts @@ -34,6 +34,7 @@ describe('empty catch syntax', () => { ['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 body of empty statements', 'try { run() } catch { ;;; }', ['unnamed', 'unexplained']], ['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]) @@ -43,6 +44,7 @@ describe('empty catch syntax', () => { ['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() }'], + ['empty statements beside the try statement', 'try { ; run() } catch (_missing) { /* already gone */ }'], ['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) => { diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts index c6d3c90548..3a0f545b28 100644 --- a/scripts/verify-empty-catch.ts +++ b/scripts/verify-empty-catch.ts @@ -78,6 +78,11 @@ function bindingName(clause: ts.CatchClause, source: ts.SourceFile): string | un return declaration === undefined ? undefined : declaration.name.getText(source) } +/** Statements that do something, so a bare `;` cannot stand in for handling an error. */ +function meaningfulStatements(block: ts.Block): readonly ts.Statement[] { + return block.statements.filter(statement => !ts.isEmptyStatement(statement)) +} + function analyze(file: string, text: string): EmptyCatchScan { const normalized = file.replaceAll('\\', '/') const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true, scriptKind(normalized)) @@ -86,12 +91,14 @@ function analyze(file: string, text: string): EmptyCatchScan { const visit = (node: ts.Node): void => { if (ts.isCatchClause(node)) { clauses += 1 - if (node.block.statements.length === 0) { + if (meaningfulStatements(node.block).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 (!ts.isTryStatement(node.parent) || meaningfulStatements(node.parent.tryBlock).length !== 1) { + defects.push('wide-try') + } if (defects.length > 0) { findings.push({ file: normalized, From 6572c8a63bf48cedd49948300edfac993d5305c7 Mon Sep 17 00:00:00 2001 From: turtle1999 Date: Mon, 21 Sep 2026 23:23:32 +0800 Subject: [PATCH 3/8] chore(infra): record the clauses master added before this gate The merge brings apps/desktop/src/client/WelcomePage.tsx:132, apps/desktop/src/preload-platform-account.ts:26, packages/credentials/deepseek-account-platform/src/index.ts:432, and packages/credentials/deepseek-account-platform/src/logout.ts:33 into the recorded inventory, so the gate passes on the merged tree. The two wide `try` clauses need their owners' judgement: narrowing one changes which failures its clause discards. --- scripts/empty-catch.baseline.json | 64 +++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 11 deletions(-) diff --git a/scripts/empty-catch.baseline.json b/scripts/empty-catch.baseline.json index fa5b1f43b2..cb6cbb590f 100644 --- a/scripts/empty-catch.baseline.json +++ b/scripts/empty-catch.baseline.json @@ -2,6 +2,15 @@ "apps/cli/tests/built-bin.e2e.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, + "apps/desktop/scripts/desktop-publish.ts": { + "3b036b0072b7f055aaebb8f06b8573cef49a85fb6a93c2a427ee9af1ec83fce5": 1 + }, + "apps/desktop/src/client/WelcomePage.tsx": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "apps/desktop/src/preload-platform-account.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, "apps/web/tests/chat-scroll-contract.e2e.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, @@ -20,12 +29,15 @@ "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/boot/plugin-manager/tests/operations-process.spec.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + }, + "packages/boot/plugin-market/src/repository-cache.ts": { + "7e75c6700190a354f1bbce07a4bcb3f4b2c897e56c66891ea495b8f4d007f714": 1 + }, "packages/client/modules/src/index.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 }, @@ -33,11 +45,14 @@ "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, "packages/client/ui-open-in-app/src/client/controller.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "fcfce66431fe6341a798a6fc6d80e9eedbfee291f1a5b790e4726c80bac6324d": 1 }, "packages/client/ui-open-in-app/src/client/open-path.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 }, + "packages/client/ui-schedule/src/client/recent-time-zones.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, "packages/client/ui-sidebar-browser/src/client/browser/url.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, @@ -50,6 +65,15 @@ "packages/context/file-reference-local/tests/search.spec.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, + "packages/credentials/deepseek-account/src/index.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "packages/credentials/deepseek-account/src/logout.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "packages/experimental/client-ui-forge/src/panel.ts": { + "fcfce66431fe6341a798a6fc6d80e9eedbfee291f1a5b790e4726c80bac6324d": 1 + }, "packages/experimental/inspector/src/client/bridge/transport.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, @@ -92,8 +116,32 @@ "packages/experimental/inspector/src/worker/realms/host/sources.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, + "packages/experimental/liveshare/src/client/owner-login.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + }, + "packages/experimental/liveshare/src/client/share-relay-address.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "packages/experimental/liveshare/src/client/ShareEditPanel.tsx": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + }, + "packages/experimental/liveshare/src/host/shareable-catalog.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + }, + "packages/experimental/liveshare/src/host/tunnel-supervision.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "packages/experimental/liveshare/src/host/viewer-dispatch.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, + "packages/experimental/liveshare/tests/fixtures/base-llm.mjs": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + }, "packages/experimental/ptc-runtime-python/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 5 + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + }, + "packages/experimental/webhook-github/src/handler.ts": { + "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 }, "packages/experimental/webworker-runtime/src/client/client.ts": { "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 @@ -215,12 +263,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 }, From 4cfd7e025735d703c100d7c5894bc5ccfe6428d5 Mon Sep 17 00:00:00 2001 From: turtle1999 Date: Mon, 21 Sep 2026 23:32:41 +0800 Subject: [PATCH 4/8] fix(infra): read the empty catch rule the way its authors write it Review of the gate found the reason-comment span too narrow: a comment on the line above `catch`, or trailing the closing brace, was rejected, so the natural place to explain a clause did not count. The span now starts at the preceding token and ends with the line closing the clause. A binding pattern that names nothing (`catch ({})`, `catch ([])`, `catch ({ _ })`) counted as naming the error. The gate now requires one bound name other than `_`. `--record REF` writes the inventory for a merged tree and refuses any clause the named revision does not already carry, so no command allows a clause this branch introduced; a merge that lands recorded clauses is the only case that adds entries. The no-op body boundary (`catch { "use strict" }`) and the tolerance for a file the parser cannot read past are stated in the module docblock and pinned by specification rows. --- scripts/baseline-inventory.fixture.ts | 12 ++++ scripts/baseline-inventory.ts | 79 ++++++++++++++++++++++--- scripts/verify-empty-catch.spec.ts | 72 ++++++++++++++++++++++- scripts/verify-empty-catch.ts | 84 +++++++++++++++++++++------ 4 files changed, 218 insertions(+), 29 deletions(-) diff --git a/scripts/baseline-inventory.fixture.ts b/scripts/baseline-inventory.fixture.ts index 21a5f8fd61..e01a763b4c 100644 --- a/scripts/baseline-inventory.fixture.ts +++ b/scripts/baseline-inventory.fixture.ts @@ -29,6 +29,15 @@ export function gitFixture(root: string, ...args: string[]): void { execFileSync('git', args, { cwd: root, stdio: 'pipe' }) } +/** + * Commit every change in a fixture repository. + * @param root - fixture repository root. + * @param message - commit message. + */ +export function commitFixture(root: string, message: string): void { + gitFixture(root, 'commit', '--quiet', '--message', message) +} + /** * 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. @@ -39,6 +48,9 @@ export function createInventoryRepo(baselinePath: string, seed: string): string const root = mkdtempSync(join(tmpdir(), 'dsh-inventory-')) roots.push(root) gitFixture(root, 'init', '--quiet') + // A runner without a global Git identity must still be able to commit this fixture. + gitFixture(root, 'config', 'user.email', 'fixture@example.com') + gitFixture(root, 'config', 'user.name', 'Fixture') for (const area of ['packages', 'apps', 'scripts', 'website']) { writeFixture(root, `${area}/seed.ts`, seed) } diff --git a/scripts/baseline-inventory.ts b/scripts/baseline-inventory.ts index 82d6035274..74ef6e7058 100644 --- a/scripts/baseline-inventory.ts +++ b/scripts/baseline-inventory.ts @@ -6,12 +6,18 @@ * 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. + * + * The inventory grows in exactly one case: a merge that brings findings recorded on the target + * branch. `--record REF` writes the current findings only after proving each one the inventory did + * not already allow is also a finding at `REF`, so no command can allow a finding this branch + * introduced. */ import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { lstatSync, readFileSync, writeFileSync } from 'node:fs' -import { resolve } from 'node:path' +import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' import ts from 'typescript' /** Source areas every inventory gate must find, so a narrowed scan cannot pass silently. */ @@ -190,18 +196,77 @@ export function verifyInventory( return findings.length } +/** Scan one gate's corpus at another revision, checked out through a temporary Git worktree. */ +function scanRevision(gate: InventoryGate, repoRoot: string, ref: string): T[] { + const path = mkdtempSync(join(tmpdir(), 'dsh-inventory-')) + try { + execFileSync('git', ['worktree', 'add', '--detach', path, ref], { cwd: repoRoot, stdio: 'pipe' }) + return gate.scan(path) + } finally { + try { + execFileSync('git', ['worktree', 'remove', '--force', path], { cwd: repoRoot, stdio: 'pipe' }) + } catch (_worktreeNeverAdded) { + // A checkout that failed to materialize leaves nothing to remove. + } + rmSync(path, { recursive: true, force: true }) + } +} + +/** Identity of one finding inside a revision, for set membership across revisions. */ +function findingKey(finding: InventoryFinding): string { + return `${finding.file}\0${finding.fingerprint}` +} + /** - * Run one gate as a command: `--prune` retires stale entries, anything else fails the process. + * Record the current findings, after proving every finding the inventory does not allow also + * exists at `ref`. Entries whose findings are gone are dropped in the same write. + * @param gate - the gate whose inventory to write. + * @param repoRoot - repository root to scan and write. + * @param ref - a revision the repository contains, normally the merged target branch. + * @returns the number of recorded findings. + * @throws when `ref` is not an ancestor of the current commit, or a newly allowed finding is absent at `ref`. + */ +export function recordInventory( + gate: InventoryGate, + repoRoot: string, + ref: string, +): number { + try { + execFileSync('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], { cwd: repoRoot, stdio: 'pipe' }) + } catch (_notAnAncestor) { + throw new Error(`${gate.name}: --record needs a revision the current branch already contains: ${ref}`) + } + const baseline = readInventoryBaseline(gate, repoRoot) + const findings = gate.scan(repoRoot) + const recorded = new Set(scanRevision(gate, repoRoot, ref).map(findingKey)) + const unproven = findings.filter(finding => + (baseline[finding.file]?.[finding.fingerprint] ?? 0) === 0 && !recorded.has(findingKey(finding))) + if (unproven.length > 0) { + throw new Error(`${gate.name}: --record refuses findings absent at ${ref}:\n` + + unproven.map(finding => ` ${gate.describe(finding)}`).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, `--record REF` writes the inventory + * for a merged tree, no argument verifies, anything else fails the process. * @param gate - the gate to enforce. * @param root - repository root to scan. */ export function runInventoryGate(gate: InventoryGate, 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]`) + const [first, second] = process.argv.slice(2) + if (process.argv.length === 3 && first === '--prune') { + console.log(gate.success(verifyInventory(gate, root, true))) + } else if (process.argv.length === 4 && first === '--record' && second !== undefined) { + console.log(`${gate.name}: recorded ${String(recordInventory(gate, root, second))} findings.`) + } else if (process.argv.length === 2) { + console.log(gate.success(verifyInventory(gate, root))) + } else { + throw new Error(`Usage: pnpm run ${gate.name} [--prune | --record ]`) } - console.log(gate.success(verifyInventory(gate, root, args[0] === '--prune'))) } catch (error) { console.error(error instanceof Error ? error.message : String(error)) process.exitCode = 1 diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts index 6a5184b820..493b54b0b8 100644 --- a/scripts/verify-empty-catch.spec.ts +++ b/scripts/verify-empty-catch.spec.ts @@ -1,8 +1,20 @@ 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' +import { + commitFixture, + createInventoryRepo, + gitFixture as git, + removeInventoryRepos, + writeFixture as write, +} from './baseline-inventory.fixture.ts' +import { + countEmptyCatches, + findEmptyCatches, + recordEmptyCatch, + scanEmptyCatches, + verifyEmptyCatch, +} from './verify-empty-catch.ts' const baselinePath = 'scripts/empty-catch.baseline.json' const sourcePath = 'packages/example/src/index.ts' @@ -32,10 +44,15 @@ describe('empty catch syntax', () => { ['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']], + ['comment above the whole statement', '// already gone\ntry { run() } catch {}', ['unnamed', 'unexplained']], + ['comment inside the try block', 'try { run() /* already gone */ } catch {}', ['unnamed', 'unexplained']], ['multi-statement try', 'try { first(); second() } catch (_missing) { /* already gone */ }', ['wide-try']], ['a body of empty statements', 'try { run() } catch { ;;; }', ['unnamed', 'unexplained']], + ['a pattern that binds nothing', 'try { run() } catch ({}) { /* already gone */ }', ['unnamed']], + ['an array pattern that binds nothing', 'try { run() } catch ([]) { /* already gone */ }', ['unnamed']], + ['a pattern binding only the discarded name', 'try { run() } catch ({ _ }) { /* already gone */ }', ['unnamed']], ['a nested clause inside a handled clause', 'try { run() } catch (error) { try { log() } catch {} }', ['unnamed', 'unexplained']], + ['a comment marker inside a trailing string', 'try { run() } catch (_missing) {} finally { log("// not a comment") }', ['unexplained']], ])('reports %s', (_name, text, expected) => { expect(defects('input.ts', text)).toEqual([expected]) }) @@ -43,6 +60,9 @@ describe('empty catch syntax', () => { it.each([ ['a named and explained clause', 'try { run() } catch (_missing) { /* already gone */ }'], ['an ordinary binding name', 'try { run() } catch (error) { /* reported above */ }'], + ['a reason on the line above the clause', 'try { run() }\n// The session may already be gone.\ncatch (_missing) {}'], + ['a reason on the line closing the clause', 'try { run() } catch (_missing) {} // The session may already be gone.'], + ['a reason in the clause trailing a finally block', 'try { run() } catch (_missing) {} finally { stop() } // Reported above.'], ['a finally block', 'try { run() } catch (_missing) { /* already gone */ } finally { stop() }'], ['empty statements beside the try statement', 'try { ; run() } catch (_missing) { /* already gone */ }'], ['a destructured binding', 'try { run() } catch ({ message }) { /* reported above */ }'], @@ -51,10 +71,14 @@ describe('empty catch syntax', () => { expect(findEmptyCatches('input.ts', text)).toEqual([]) }) + // A no-op body other than `;` is out of scope, so the gate must not claim it. 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 }'], + ['a directive body', 'try { run() } catch { "use strict" }'], + ['a void expression body', 'try { run() } catch { void 0 }'], + ['a block expression body', 'try { run() } catch { {} }'], ['comment text inside a string', 'try { run() } catch (error) { report("// not a comment") }'], ])('ignores %s', (_name, text) => { expect(findEmptyCatches('input.ts', text)).toEqual([]) @@ -153,6 +177,48 @@ describe('empty catch inventory', () => { expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n') }) + // A merge that brings clauses recorded on the target branch is the one case where entries may + // be added, and only for clauses the named revision already carries. + it('records a merged clause and drops the entry it replaces', () => { + const root = fixture() + write(root, sourcePath, broken) + git(root, 'add', '.') + commitFixture(root, 'base') + // The target branch adds a clause; this branch merges it and fixes its own recorded clause. + git(root, 'checkout', '--quiet', '-b', 'target') + write(root, 'apps/landed.ts', broken) + git(root, 'add', '.') + commitFixture(root, 'landed') + git(root, 'checkout', '--quiet', '-') + git(root, 'merge', '--quiet', '--no-edit', 'target') + write(root, sourcePath, seed) + expect(recordEmptyCatch(root, 'target')).toBe(1) + expect(JSON.parse(readFileSync(join(root, baselinePath), 'utf8'))).toEqual( + countEmptyCatches(findEmptyCatches('apps/landed.ts', broken)), + ) + expect(verifyEmptyCatch(root)).toBe(1) + }) + + it('refuses a clause the named revision does not carry', () => { + const root = fixture() + commitFixture(root, 'base') + write(root, sourcePath, broken) + expect(() => recordEmptyCatch(root, 'HEAD')).toThrow(/--record refuses findings absent at HEAD/u) + expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n') + }) + + it('refuses a revision the branch does not contain', () => { + const root = fixture() + git(root, 'add', '.') + commitFixture(root, 'base') + git(root, 'checkout', '--quiet', '-b', 'side') + write(root, 'apps/side.ts', broken) + git(root, 'add', '.') + commitFixture(root, 'side') + git(root, 'checkout', '--quiet', '-') + expect(() => recordEmptyCatch(root, 'side')).toThrow(/--record needs a revision/u) + }) + // 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([ diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts index 3a0f545b28..193eb4f76b 100644 --- a/scripts/verify-empty-catch.ts +++ b/scripts/verify-empty-catch.ts @@ -1,12 +1,18 @@ /** * 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. + * An empty clause — a body whose statements, if any, are all bare `;` — 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. + * + * A body holding any other statement is out of scope: whether it handles the error is not + * decidable from syntax, so `catch { "use strict" }` and similar no-ops stay legal and the + * specification records that boundary. So is a file the parser cannot read past, which yields + * whatever clauses it recovered; the typecheck covers tracked source. + * + * Legacy clauses that break a condition are recorded in `scripts/empty-catch.baseline.json`. + * Fixing one requires `--prune` to retire its entry, and a merge that brings recorded clauses + * requires `--record `. */ import { readFileSync } from 'node:fs' @@ -15,6 +21,7 @@ import ts from 'typescript' import { countInventory, listInventorySources, + recordInventory, runInventoryGate, syntaxFingerprint, verifyInventory, @@ -58,7 +65,7 @@ function scriptKind(file: string): ts.ScriptKind { /** * Whether the span holds a comment token. * - * Scanning the span keeps comment markers inside a string or template literal from counting. + * Scanning the span keeps a comment marker 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. @@ -72,14 +79,40 @@ function hasComment(text: string, from: number, to: number): boolean { 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) +/** + * Span that can carry a clause's reason: from just after the preceding token — a line above the + * `catch` keyword belongs to the clause — through the end of the line closing its block. + * @param clause - the catch clause whose reason to look for. + * @param text - the whole source file. + * @returns inclusive start and exclusive end offsets. + */ +function reasonSpan(clause: ts.CatchClause, text: string): { from: number; to: number } { + const lineEnd = text.indexOf('\n', clause.end) + return { from: clause.getFullStart(), to: lineEnd === -1 ? text.length : lineEnd } } -/** Statements that do something, so a bare `;` cannot stand in for handling an error. */ -function meaningfulStatements(block: ts.Block): readonly ts.Statement[] { +/** Names a binding pattern binds, so `catch ({})` names nothing. */ +function boundNames(name: ts.BindingName, names: string[]): void { + if (ts.isIdentifier(name)) { + names.push(name.text) + return + } + for (const element of name.elements) { + if (!ts.isOmittedExpression(element)) boundNames(element.name, names) + } +} + +/** Bound names of the thrown value; empty for `catch {` and for a pattern that binds nothing. */ +function bindingNames(clause: ts.CatchClause): readonly string[] { + const declaration = clause.variableDeclaration + if (declaration === undefined) return [] + const names: string[] = [] + boundNames(declaration.name, names) + return names +} + +/** Statements other than a bare `;`, which cannot stand in for handling an error. */ +function nonEmptyStatements(block: ts.Block): readonly ts.Statement[] { return block.statements.filter(statement => !ts.isEmptyStatement(statement)) } @@ -91,12 +124,13 @@ function analyze(file: string, text: string): EmptyCatchScan { const visit = (node: ts.Node): void => { if (ts.isCatchClause(node)) { clauses += 1 - if (meaningfulStatements(node.block).length === 0) { - const name = bindingName(node, source) + if (nonEmptyStatements(node.block).length === 0) { + const names = bindingNames(node) 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) || meaningfulStatements(node.parent.tryBlock).length !== 1) { + if (!names.some(name => name !== '_')) defects.push('unnamed') + const span = reasonSpan(node, text) + if (!hasComment(text, span.from, span.to)) defects.push('unexplained') + if (!ts.isTryStatement(node.parent) || nonEmptyStatements(node.parent.tryBlock).length !== 1) { defects.push('wide-try') } if (defects.length > 0) { @@ -119,7 +153,7 @@ function analyze(file: string, text: string): EmptyCatchScan { * 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. + * @returns findings in AST traversal order; a clause whose body holds a real statement never matches. */ export function findEmptyCatches(file: string, text: string): EmptyCatch[] { return analyze(file, text).findings @@ -170,6 +204,18 @@ export function verifyEmptyCatch(repoRoot: string, prune = false): number { return verifyInventory(gate, repoRoot, prune) } +/** + * Record the current clauses, after proving every clause the inventory does not allow already + * exists at `ref`. A merge that lands recorded clauses is the only case that adds entries. + * @param repoRoot - repository root to scan and write. + * @param ref - a revision the repository contains, normally the merged target branch. + * @returns the number of recorded clauses. + * @throws when `ref` is not an ancestor of the current commit, or a newly allowed clause is absent at `ref`. + */ +export function recordEmptyCatch(repoRoot: string, ref: string): number { + return recordInventory(gate, repoRoot, ref) +} + if (import.meta.filename === resolve(process.argv[1] ?? '')) { runInventoryGate(gate, root) } From 9dc86febb68d8c794f0bdd9ed2c3b0f33eec15bd Mon Sep 17 00:00:00 2001 From: turtle1999 Date: Fri, 6 Nov 2026 16:01:25 +0800 Subject: [PATCH 5/8] feat(infra): point empty catch rejections at the error-handling guidance --- .agents/skills/dsh-error-handling/SKILL.md | 2 ++ scripts/verify-empty-catch.spec.ts | 8 ++++++++ scripts/verify-empty-catch.ts | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index 930c19adfd..fd8e0659f6 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -34,6 +34,8 @@ For each failure, define handling and reporting owners, containment, and guarant Catching limits exception propagation, not mutations. Only the affected state's owner can establish safe continuation. Otherwise stop dependent work, discard invalid state or instances, or escalate. Logging alone is not recovery. Retries require safe repetition, cancellation, and an explicit owner; finite operations need budgets, while continuing supervision needs lifecycle ownership and observable degradation. +An empty `catch` discards every failure of its `try`, so it is acceptable only when each such failure leaves the owner's state valid and no caller can act on it, such as best-effort cleanup after a primary failure. Keep the `try` to one statement, bind the error to an underscore-prefixed name that states the expected failure, such as `_alreadyGone` (lint requires the prefix on an unused binding; a bare `_` counts as unnamed), and explain in the `catch` block why the state stays valid. When only some failures are acceptable, test `code` or `name` and rethrow the rest; an unconditional discard also reports defects as success. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) enforces the form; review checks that the name and reason are true. + ## Localized, actionable, visible reports Every final report needs a readable summary, affected operation, and safe next action. Localize through the receiving application's locale mechanism where one exists; other diagnostics use their existing output language. Keep sensitive internal details out of user-facing text. diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts index 493b54b0b8..df36c0ecc2 100644 --- a/scripts/verify-empty-catch.spec.ts +++ b/scripts/verify-empty-catch.spec.ts @@ -151,6 +151,14 @@ describe('empty catch inventory', () => { expect(() => verifyEmptyCatch(root)).toThrow(`${sourcePath}:1 (unnamed, unexplained)`) }) + it('points a rejection at the repository guidance for discarding an error', () => { + const root = fixture() + write(root, sourcePath, broken) + const skillPath = '.agents/skills/dsh-error-handling/SKILL.md' + expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#catch-recover-or-stop)`) + expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^## Catch, recover, or stop$/mu) + }) + it('requires pruning retired counts while preserving the remaining clause', () => { const root = fixture() write(root, sourcePath, `${broken}${broken}`) diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts index 193eb4f76b..2f8aea694b 100644 --- a/scripts/verify-empty-catch.ts +++ b/scripts/verify-empty-catch.ts @@ -179,7 +179,7 @@ const gate: InventoryGate = { 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.', + + ' and keep its try to one statement (see .agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop).', describe: finding => `${finding.file}:${String(finding.line)} (${finding.defects.join(', ')})`, success: count => `verify-empty-catch: no new silent catches; ${String(count)} recorded clauses remain.`, } From 62cce39c063531b6930a0012f2e32861f6d93e5e Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 9 Nov 2026 14:58:22 +0800 Subject: [PATCH 6/8] fix(infra): drop --record and treat a new defect on a recorded empty catch as new --- scripts/baseline-inventory.fixture.ts | 12 -- scripts/baseline-inventory.ts | 84 ++--------- scripts/empty-catch.baseline.json | 195 ++++++++++++++------------ scripts/verify-empty-catch.spec.ts | 95 +++++-------- scripts/verify-empty-catch.ts | 88 +++++------- 5 files changed, 183 insertions(+), 291 deletions(-) diff --git a/scripts/baseline-inventory.fixture.ts b/scripts/baseline-inventory.fixture.ts index e01a763b4c..21a5f8fd61 100644 --- a/scripts/baseline-inventory.fixture.ts +++ b/scripts/baseline-inventory.fixture.ts @@ -29,15 +29,6 @@ export function gitFixture(root: string, ...args: string[]): void { execFileSync('git', args, { cwd: root, stdio: 'pipe' }) } -/** - * Commit every change in a fixture repository. - * @param root - fixture repository root. - * @param message - commit message. - */ -export function commitFixture(root: string, message: string): void { - gitFixture(root, 'commit', '--quiet', '--message', message) -} - /** * 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. @@ -48,9 +39,6 @@ export function createInventoryRepo(baselinePath: string, seed: string): string const root = mkdtempSync(join(tmpdir(), 'dsh-inventory-')) roots.push(root) gitFixture(root, 'init', '--quiet') - // A runner without a global Git identity must still be able to commit this fixture. - gitFixture(root, 'config', 'user.email', 'fixture@example.com') - gitFixture(root, 'config', 'user.name', 'Fixture') for (const area of ['packages', 'apps', 'scripts', 'website']) { writeFixture(root, `${area}/seed.ts`, seed) } diff --git a/scripts/baseline-inventory.ts b/scripts/baseline-inventory.ts index 74ef6e7058..062501d4e3 100644 --- a/scripts/baseline-inventory.ts +++ b/scripts/baseline-inventory.ts @@ -4,20 +4,15 @@ * 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. - * - * The inventory grows in exactly one case: a merge that brings findings recorded on the target - * branch. `--record REF` writes the current findings only after proving each one the inventory did - * not already allow is also a finding at `REF`, so no command can allow a finding this branch - * introduced. + * changed form is a new finding. Fixing a recorded finding leaves a stale allowance, which + * `--prune` retires; a partial fix that leaves a changed finding is a new finding, so a finding is + * fixed completely before pruning. No command adds an allowance. */ import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' +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. */ @@ -33,7 +28,7 @@ export type InventoryBaseline = Record> export interface InventoryFinding { /** Repository-relative path with forward slashes. */ file: string - /** SHA-256 of the finding's syntax tokens, excluding comments and whitespace. */ + /** SHA-256 of the finding's form, derived from syntax tokens that exclude comments and whitespace. */ fingerprint: string } @@ -196,76 +191,21 @@ export function verifyInventory( return findings.length } -/** Scan one gate's corpus at another revision, checked out through a temporary Git worktree. */ -function scanRevision(gate: InventoryGate, repoRoot: string, ref: string): T[] { - const path = mkdtempSync(join(tmpdir(), 'dsh-inventory-')) - try { - execFileSync('git', ['worktree', 'add', '--detach', path, ref], { cwd: repoRoot, stdio: 'pipe' }) - return gate.scan(path) - } finally { - try { - execFileSync('git', ['worktree', 'remove', '--force', path], { cwd: repoRoot, stdio: 'pipe' }) - } catch (_worktreeNeverAdded) { - // A checkout that failed to materialize leaves nothing to remove. - } - rmSync(path, { recursive: true, force: true }) - } -} - -/** Identity of one finding inside a revision, for set membership across revisions. */ -function findingKey(finding: InventoryFinding): string { - return `${finding.file}\0${finding.fingerprint}` -} - /** - * Record the current findings, after proving every finding the inventory does not allow also - * exists at `ref`. Entries whose findings are gone are dropped in the same write. - * @param gate - the gate whose inventory to write. - * @param repoRoot - repository root to scan and write. - * @param ref - a revision the repository contains, normally the merged target branch. - * @returns the number of recorded findings. - * @throws when `ref` is not an ancestor of the current commit, or a newly allowed finding is absent at `ref`. - */ -export function recordInventory( - gate: InventoryGate, - repoRoot: string, - ref: string, -): number { - try { - execFileSync('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], { cwd: repoRoot, stdio: 'pipe' }) - } catch (_notAnAncestor) { - throw new Error(`${gate.name}: --record needs a revision the current branch already contains: ${ref}`) - } - const baseline = readInventoryBaseline(gate, repoRoot) - const findings = gate.scan(repoRoot) - const recorded = new Set(scanRevision(gate, repoRoot, ref).map(findingKey)) - const unproven = findings.filter(finding => - (baseline[finding.file]?.[finding.fingerprint] ?? 0) === 0 && !recorded.has(findingKey(finding))) - if (unproven.length > 0) { - throw new Error(`${gate.name}: --record refuses findings absent at ${ref}:\n` - + unproven.map(finding => ` ${gate.describe(finding)}`).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, `--record REF` writes the inventory - * for a merged tree, no argument verifies, anything else fails the process. + * Run one gate as a command: `--prune` retires stale entries, no argument verifies, anything else + * fails the process. * @param gate - the gate to enforce. * @param root - repository root to scan. */ export function runInventoryGate(gate: InventoryGate, root: string): void { try { - const [first, second] = process.argv.slice(2) - if (process.argv.length === 3 && first === '--prune') { + const args = process.argv.slice(2) + if (args.length === 1 && args[0] === '--prune') { console.log(gate.success(verifyInventory(gate, root, true))) - } else if (process.argv.length === 4 && first === '--record' && second !== undefined) { - console.log(`${gate.name}: recorded ${String(recordInventory(gate, root, second))} findings.`) - } else if (process.argv.length === 2) { + } else if (args.length === 0) { console.log(gate.success(verifyInventory(gate, root))) } else { - throw new Error(`Usage: pnpm run ${gate.name} [--prune | --record ]`) + throw new Error(`Usage: pnpm run ${gate.name} [--prune]`) } } catch (error) { console.error(error instanceof Error ? error.message : String(error)) diff --git a/scripts/empty-catch.baseline.json b/scripts/empty-catch.baseline.json index cb6cbb590f..1d6ab2b85c 100644 --- a/scripts/empty-catch.baseline.json +++ b/scripts/empty-catch.baseline.json @@ -1,281 +1,290 @@ { "apps/cli/tests/built-bin.e2e.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "apps/desktop/scripts/desktop-publish.ts": { - "3b036b0072b7f055aaebb8f06b8573cef49a85fb6a93c2a427ee9af1ec83fce5": 1 + "d37e8639087921e2491d45d40d63b44e72b30a516ad3a5f3155f467c7f5c3ac7": 1 }, "apps/desktop/src/client/WelcomePage.tsx": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "apps/desktop/src/preload-platform-account.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "apps/web/tests/chat-scroll-contract.e2e.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "apps/web/tests/support.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/api/gateway/src/client/remote-stream.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/api/gateway/tests/gateway-stream.host.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/api/workspace-files/src/client/change-feed.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/boot/app-boot/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/boot/plugin-manager/src/registry.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/boot/plugin-manager/tests/operations-process.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/boot/plugin-market/src/repository-cache.ts": { - "7e75c6700190a354f1bbce07a4bcb3f4b2c897e56c66891ea495b8f4d007f714": 1 + "3d8f6e3468aecc6e006ee3e5f20a5c6c5277316636c8849756fc6d710e9d907b": 1 }, "packages/client/modules/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/client/store/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/client/ui-open-in-app/src/client/controller.ts": { - "fcfce66431fe6341a798a6fc6d80e9eedbfee291f1a5b790e4726c80bac6324d": 1 + "ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1 }, "packages/client/ui-open-in-app/src/client/open-path.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/client/ui-schedule/src/client/recent-time-zones.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/client/ui-sidebar-browser/src/client/browser/url.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/client/ui-sidebar-right/src/client/tab-inventory.ts": { - "e97a9c346a760763bd576d2b89b55a62bc5abaddf29ca057aac0b5b855eb4a04": 1 + "ee22b9dbd07fc0b76f0464bf59386efb6925dab82c4539a2772b909b944ee33c": 1 }, "packages/client/ui-skill/src/client/SkillRow.tsx": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/context/file-reference-local/tests/search.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/credentials/deepseek-account/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/credentials/deepseek-account/src/logout.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/experimental/client-ui-forge/src/panel.ts": { - "fcfce66431fe6341a798a6fc6d80e9eedbfee291f1a5b790e4726c80bac6324d": 1 + "ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1 }, "packages/experimental/inspector/src/client/bridge/transport.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/client/cdp/console.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2 }, "packages/experimental/inspector/src/client/inspection/realm.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/experimental/inspector/src/worker/bridge/hub.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/experimental/inspector/src/worker/bridge/runtime-rpc.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 4 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4 }, "packages/experimental/inspector/src/worker/bridge/session.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/cdp/domains/dom/model.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/cdp/realm-sessions.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/inspection/cordis-store.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/inspection/network-store.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/experimental/inspector/src/worker/inspection/query-router.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/inspection/realm-store.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/inspector/src/worker/realms/host/bridge.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3 }, "packages/experimental/inspector/src/worker/realms/host/sources.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/liveshare/src/client/owner-login.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3 }, "packages/experimental/liveshare/src/client/share-relay-address.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/experimental/liveshare/src/client/ShareEditPanel.tsx": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2 }, "packages/experimental/liveshare/src/host/shareable-catalog.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2 }, "packages/experimental/liveshare/src/host/tunnel-supervision.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/liveshare/src/host/viewer-dispatch.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/experimental/liveshare/tests/fixtures/base-llm.mjs": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "8b2766548472fe722af04dc7c95b06d303bb164fd12fbec87a07ea6eaae7146a": 1 }, "packages/experimental/ptc-runtime-python/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/webhook-github/src/handler.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/webworker-runtime/src/client/client.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/webworker-runtime/src/transport/tunnel.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/webworker-runtime/tests/compile/transform-corpus-check.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/experimental/webworker-runtime/tests/polyfill/als-shim.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/host/directory-picker-browse/tests/service.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/host/open-in-app/src/icons.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/host/open-in-app/src/resolver.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/identity/anonymous-user-id/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/llm/llm-deepseek/src/file-store.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/llm/llm-deepseek/src/files-api.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/llm/llm-pi-ai/src/replay.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/llm/llm/src/adapter-failure.ts": { - "deaf1f3ce375367e779f482ad95bad5556ef9f3d53b67df6011c9d8cebe319e9": 1 + "19186deef10a7178489ddf20fcaf6688a0baf38bf6d9933cb78fe65023f3280f": 1 }, "packages/lsp/lsp-stdio/src/instance.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/session-query/session-query-sqlite/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/session-query/session-query/src/cold-read.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/session/session-persistence-jsonl/src/generation.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/session/session-persistence-jsonl/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/session/session-persistence-jsonl/tests/zstd.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/shell/bash-local/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/shell/pwsh-local/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/skill/skill-filesystem/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/skill/skill/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/spill/spill-local/src/cleanup.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subagent/subagent-acp/src/run.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subagent/subagent-claude-code/src/run.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subagent/subagent-codex/src/run.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/subagent/subagent-dsh-sdk/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subagent/subagent-dsh-sdk/src/run.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subagent/subagent/src/out-of-process.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subprocess/subprocess-local/src/index.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/subprocess/subprocess-local/src/linux-scope.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 5 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5 }, "packages/subprocess/subprocess-local/src/output.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 2 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/subprocess/subprocess-local/src/runner-protocol.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/subprocess/subprocess-local/src/spawn-runner.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 6 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4 }, "packages/subprocess/subprocess-local/src/spawn.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3 }, "packages/subprocess/subprocess-local/src/windows-job.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "packages/subprocess/subprocess-local/tests/native-containment.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2 }, "packages/subprocess/subprocess-local/tests/native-windows.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "packages/subprocess/subprocess-local/tests/spawn.spec.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 6 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5 }, "packages/test-support/client-runtime/src/assembly/test-client.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "scripts/gen-session-format-catalog.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "scripts/run-gates.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 3 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2, + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "scripts/slot-walk.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1 }, "vitest.e2e.config.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 }, "vitest.web.config.ts": { - "d47e64f018c8caf61f05cc0c9aede6d0ecac10ec4829d61d9978c50380f1b945": 1 + "cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1 } } diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts index df36c0ecc2..eabc522e9c 100644 --- a/scripts/verify-empty-catch.spec.ts +++ b/scripts/verify-empty-catch.spec.ts @@ -2,24 +2,18 @@ import { readFileSync, symlinkSync, unlinkSync } from 'node:fs' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { - commitFixture, createInventoryRepo, gitFixture as git, removeInventoryRepos, writeFixture as write, } from './baseline-inventory.fixture.ts' -import { - countEmptyCatches, - findEmptyCatches, - recordEmptyCatch, - scanEmptyCatches, - verifyEmptyCatch, -} from './verify-empty-catch.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' +const recorded = 'try { run() } catch { /* reason */ }\n' afterEach(removeInventoryRepos) @@ -53,6 +47,13 @@ describe('empty catch syntax', () => { ['a pattern binding only the discarded name', 'try { run() } catch ({ _ }) { /* already gone */ }', ['unnamed']], ['a nested clause inside a handled clause', 'try { run() } catch (error) { try { log() } catch {} }', ['unnamed', 'unexplained']], ['a comment marker inside a trailing string', 'try { run() } catch (_missing) {} finally { log("// not a comment") }', ['unexplained']], + ['a comment marker inside a trailing regular expression', 'try { run() } catch (_missing) {} finally { match(/[/*]/) }', ['unexplained']], + ['a comment trailing a finally block', 'try { run() } catch (_missing) {} finally { stop() } // Reported above.', ['unexplained']], + ['a comment after another statement on the closing line', 'try { run() } catch (_missing) {}; stop() // Stopped.', ['unexplained']], + ['a comment on the line after the clause', 'try { run() } catch (_missing) {}\n// Stopped.\nstop()', ['unexplained']], + ['a comment on the line after the clause with CRLF', 'try { run() } catch (_missing) {}\r\n// Stopped.\r\nstop()', ['unexplained']], + ['a comment marker inside a binding default regular expression', 'try { run() } catch ({ message = /[/*]/ }) {}', ['unexplained']], + ['a comment marker inside a binding default template', 'try { run() } catch ({ message = `${prefix}//` }) {}', ['unexplained']], ])('reports %s', (_name, text, expected) => { expect(defects('input.ts', text)).toEqual([expected]) }) @@ -62,7 +63,12 @@ describe('empty catch syntax', () => { ['an ordinary binding name', 'try { run() } catch (error) { /* reported above */ }'], ['a reason on the line above the clause', 'try { run() }\n// The session may already be gone.\ncatch (_missing) {}'], ['a reason on the line closing the clause', 'try { run() } catch (_missing) {} // The session may already be gone.'], - ['a reason in the clause trailing a finally block', 'try { run() } catch (_missing) {} finally { stop() } // Reported above.'], + ['a reason on the line closing the clause with CRLF', 'try { run() } catch (_missing) {} // Already gone.\r\nstop()'], + ['a block comment above the clause', 'try { run() }\n/* The session may already be gone. */\ncatch (_missing) {}'], + ['a reason between the clause and a finally block', 'try { run() } catch (_missing) {} /* Reported above. */ finally { stop() }'], + // One block or compound statement counts as one statement, however much it holds. + ['a try holding one block', 'try { { first(); second() } } catch (_missing) { /* already gone */ }'], + ['a try holding one if statement', 'try { if (ready) { first(); second() } } catch (_missing) { /* already gone */ }'], ['a finally block', 'try { run() } catch (_missing) { /* already gone */ } finally { stop() }'], ['empty statements beside the try statement', 'try { ; run() } catch (_missing) { /* already gone */ }'], ['a destructured binding', 'try { run() } catch ({ message }) { /* reported above */ }'], @@ -96,6 +102,16 @@ describe('empty catch syntax', () => { expect(findings[0]?.fingerprint).toMatch(/^[a-f0-9]{64}$/u) }) + it('changes the fingerprint when a clause gains a defect', () => { + const [recorded] = findEmptyCatches('input.ts', 'try { run() } catch { /* already gone */ }') + const [widened] = findEmptyCatches('input.ts', 'try { first(); second() } catch { /* already gone */ }') + const [unexplained] = findEmptyCatches('input.ts', 'try { run() } catch {}') + expect(widened?.fingerprint).not.toBe(recorded?.fingerprint) + expect(unexplained?.fingerprint).not.toBe(recorded?.fingerprint) + expect(findEmptyCatches('input.ts', 'try { stop() } catch { /* already gone */ }')[0]?.fingerprint) + .toBe(recorded?.fingerprint) + }) + 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') @@ -123,13 +139,15 @@ describe('empty catch inventory', () => { }) 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) => { + ['another copy of a recorded clause', `${recorded}${recorded}`], + ['a differently bound clause', 'try { stop() } catch (error) {}\n'], + ['an unexplained clause', 'try { run() } catch (_missing) {}\n'], + ['a wide try', 'try { first(); second() } catch (_missing) { /* reason */ }\n'], + ['a recorded clause with a widened try', 'try { first(); second() } catch { /* reason */ }\n'], + ['a recorded clause without its reason', 'try { run() } catch {}\n'], + ])('rejects %s without changing the baseline', (_name, text) => { const root = fixture() - write(root, sourcePath, broken) + write(root, sourcePath, recorded) const baseline = recordBaseline(root) write(root, sourcePath, text) expect(() => verifyEmptyCatch(root)).toThrow(/verify-empty-catch: an empty catch/u) @@ -137,7 +155,7 @@ describe('empty catch inventory', () => { expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline) }) - it('keeps a recorded clause inside its file allowance when an identical shape moves', () => { + it('keeps a recorded clause inside its file allowance when only its try statement changes', () => { const root = fixture() write(root, sourcePath, broken) recordBaseline(root) @@ -185,48 +203,6 @@ describe('empty catch inventory', () => { expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n') }) - // A merge that brings clauses recorded on the target branch is the one case where entries may - // be added, and only for clauses the named revision already carries. - it('records a merged clause and drops the entry it replaces', () => { - const root = fixture() - write(root, sourcePath, broken) - git(root, 'add', '.') - commitFixture(root, 'base') - // The target branch adds a clause; this branch merges it and fixes its own recorded clause. - git(root, 'checkout', '--quiet', '-b', 'target') - write(root, 'apps/landed.ts', broken) - git(root, 'add', '.') - commitFixture(root, 'landed') - git(root, 'checkout', '--quiet', '-') - git(root, 'merge', '--quiet', '--no-edit', 'target') - write(root, sourcePath, seed) - expect(recordEmptyCatch(root, 'target')).toBe(1) - expect(JSON.parse(readFileSync(join(root, baselinePath), 'utf8'))).toEqual( - countEmptyCatches(findEmptyCatches('apps/landed.ts', broken)), - ) - expect(verifyEmptyCatch(root)).toBe(1) - }) - - it('refuses a clause the named revision does not carry', () => { - const root = fixture() - commitFixture(root, 'base') - write(root, sourcePath, broken) - expect(() => recordEmptyCatch(root, 'HEAD')).toThrow(/--record refuses findings absent at HEAD/u) - expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n') - }) - - it('refuses a revision the branch does not contain', () => { - const root = fixture() - git(root, 'add', '.') - commitFixture(root, 'base') - git(root, 'checkout', '--quiet', '-b', 'side') - write(root, 'apps/side.ts', broken) - git(root, 'add', '.') - commitFixture(root, 'side') - git(root, 'checkout', '--quiet', '-') - expect(() => recordEmptyCatch(root, 'side')).toThrow(/--record needs a revision/u) - }) - // 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([ @@ -242,7 +218,7 @@ describe('empty catch inventory', () => { }) describe('empty catch source discovery', () => { - it('checks tracked source across areas, extensions and tests', () => { + it('checks tracked source across areas, extensions, tests and root configuration', () => { const root = fixture() const files = [ 'packages/example/src/input.ts', @@ -253,6 +229,7 @@ describe('empty catch source discovery', () => { 'apps/example/input.jsx', 'scripts/input.mjs', 'website/input.cjs', + 'config.ts', ] for (const file of files) write(root, file, broken) git(root, 'add', '.') diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts index 2f8aea694b..d988aee658 100644 --- a/scripts/verify-empty-catch.ts +++ b/scripts/verify-empty-catch.ts @@ -3,25 +3,30 @@ * * An empty clause — a body whose statements, if any, are all bare `;` — 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. + * statement; a wider `try` hides statements whose failures the clause also discards. The reason + * comment may sit anywhere in the clause, between the `try` block and the `catch` keyword, or + * right after the clause on its closing line, before any further token. * * A body holding any other statement is out of scope: whether it handles the error is not * decidable from syntax, so `catch { "use strict" }` and similar no-ops stay legal and the * specification records that boundary. So is a file the parser cannot read past, which yields - * whatever clauses it recovered; the typecheck covers tracked source. + * whatever clauses it recovered; the typecheck covers tracked source. A `try` holding one block or + * one compound statement, such as `if`, counts as one statement. * - * Legacy clauses that break a condition are recorded in `scripts/empty-catch.baseline.json`. - * Fixing one requires `--prune` to retire its entry, and a merge that brings recorded clauses - * requires `--record `. + * Legacy clauses that break a condition are recorded in `scripts/empty-catch.baseline.json`. A + * clause's identity covers its syntax tokens and its broken conditions, so turning a recorded + * one-statement `try` into a wider one or deleting a recorded reason is a new finding, while edits + * inside the `try` that keep its conditions are not. Moving a file that holds recorded clauses + * renames its baseline key in the same change. */ +import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import ts from 'typescript' import { countInventory, listInventorySources, - recordInventory, runInventoryGate, syntaxFingerprint, verifyInventory, @@ -31,7 +36,7 @@ import { const root = resolve(import.meta.dirname, '..') -/** Existing empty-clause counts, keyed by repository path and syntax fingerprint. */ +/** Existing empty-clause counts, keyed by repository path and clause fingerprint. */ export type EmptyCatchBaseline = InventoryBaseline /** One condition of the rule that an empty clause breaks. */ @@ -43,7 +48,7 @@ export interface EmptyCatch { file: string /** One-based line of the `catch` keyword. */ line: number - /** SHA-256 of the clause's syntax tokens, excluding comments and whitespace. */ + /** SHA-256 of the clause's syntax tokens, excluding comments and whitespace, and its defects. */ fingerprint: string /** Broken conditions in {@link EmptyCatchDefect} order. */ defects: readonly EmptyCatchDefect[] @@ -55,40 +60,24 @@ interface EmptyCatchScan { 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 a comment marker 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 -} - -/** - * Span that can carry a clause's reason: from just after the preceding token — a line above the - * `catch` keyword belongs to the clause — through the end of the line closing its block. + * Whether a comment states the clause's reason: in the trivia before any token of the clause, + * which starts just after the `try` block so a line above the `catch` keyword belongs to it, or + * after the clause on its closing line before the next token. Reading parsed comment ranges keeps + * comment markers inside strings, templates and regular expressions from counting. * @param clause - the catch clause whose reason to look for. - * @param text - the whole source file. - * @returns inclusive start and exclusive end offsets. + * @param source - the file that owns the clause. + * @returns `true` when such a comment exists. */ -function reasonSpan(clause: ts.CatchClause, text: string): { from: number; to: number } { - const lineEnd = text.indexOf('\n', clause.end) - return { from: clause.getFullStart(), to: lineEnd === -1 ? text.length : lineEnd } +function hasReason(clause: ts.CatchClause, source: ts.SourceFile): boolean { + const hasCommentAt = (position: number): boolean => + (ts.getLeadingCommentRanges(source.text, position)?.length ?? 0) > 0 + || (ts.getTrailingCommentRanges(source.text, position)?.length ?? 0) > 0 + const visit = (node: ts.Node): boolean => { + if (ts.isJSDoc(node)) return true + return ts.isToken(node) ? hasCommentAt(node.pos) : node.getChildren(source).some(visit) + } + return visit(clause) || (ts.getTrailingCommentRanges(source.text, clause.end)?.length ?? 0) > 0 } /** Names a binding pattern binds, so `catch ({})` names nothing. */ @@ -118,7 +107,7 @@ function nonEmptyStatements(block: ts.Block): readonly ts.Statement[] { function analyze(file: string, text: string): EmptyCatchScan { const normalized = file.replaceAll('\\', '/') - const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true, scriptKind(normalized)) + const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true) const findings: EmptyCatch[] = [] let clauses = 0 const visit = (node: ts.Node): void => { @@ -128,8 +117,7 @@ function analyze(file: string, text: string): EmptyCatchScan { const names = bindingNames(node) const defects: EmptyCatchDefect[] = [] if (!names.some(name => name !== '_')) defects.push('unnamed') - const span = reasonSpan(node, text) - if (!hasComment(text, span.from, span.to)) defects.push('unexplained') + if (!hasReason(node, source)) defects.push('unexplained') if (!ts.isTryStatement(node.parent) || nonEmptyStatements(node.parent.tryBlock).length !== 1) { defects.push('wide-try') } @@ -137,7 +125,9 @@ function analyze(file: string, text: string): EmptyCatchScan { findings.push({ file: normalized, line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1, - fingerprint: syntaxFingerprint(node, source), + fingerprint: createHash('sha256') + .update(`${syntaxFingerprint(node, source)}:${defects.join(',')}`) + .digest('hex'), defects, }) } @@ -204,18 +194,6 @@ export function verifyEmptyCatch(repoRoot: string, prune = false): number { return verifyInventory(gate, repoRoot, prune) } -/** - * Record the current clauses, after proving every clause the inventory does not allow already - * exists at `ref`. A merge that lands recorded clauses is the only case that adds entries. - * @param repoRoot - repository root to scan and write. - * @param ref - a revision the repository contains, normally the merged target branch. - * @returns the number of recorded clauses. - * @throws when `ref` is not an ancestor of the current commit, or a newly allowed clause is absent at `ref`. - */ -export function recordEmptyCatch(repoRoot: string, ref: string): number { - return recordInventory(gate, repoRoot, ref) -} - if (import.meta.filename === resolve(process.argv[1] ?? '')) { runInventoryGate(gate, root) } From 33e22855478cb08f4f0df2f1c305e062bef243bb Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 9 Nov 2026 14:58:24 +0800 Subject: [PATCH 7/8] docs(infra): record the empty catch gate decision --- ...-09-21-reject-silent-empty-catch.i18n.yaml | 19 +++++++++++ .../2026-09-21-reject-silent-empty-catch.md | 33 +++++++++++++++++++ ...2026-09-21-reject-silent-empty-catch.zh.md | 33 +++++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 .agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md create mode 100644 .agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml new file mode 100644 index 0000000000..b0b1325348 --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-21-reject-silent-empty-catch.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md +/agent-note-reject-silent-empty-catch-clauses: + en: b058c52537202c50 + zh: f48d8847967a31a8 +/agent-note-reject-silent-empty-catch-clauses/problem: + en: a89b84c7052329b4 + zh: 9c511a0b4ee3f1ef +/agent-note-reject-silent-empty-catch-clauses/decision: + en: 1b9199240c84fb54 + zh: 155f0381f09effa1 +/agent-note-reject-silent-empty-catch-clauses/alternatives-considered: + en: 65d05680072f8797 + zh: e160d37d8ece30ad +/agent-note-reject-silent-empty-catch-clauses/consequences: + en: 88a4796188c31922 + zh: bfa8efc7944ea12a diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md new file mode 100644 index 0000000000..2b4b5e514e --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md @@ -0,0 +1,33 @@ +# Agent Note: Reject silent empty catch clauses + +Status: implemented + +English | [中文](2026-09-21-reject-silent-empty-catch.zh.md) + +## Problem + +An empty `catch` discards every failure of its `try`, including defects the author did not expect. The root rule requires such a clause to name the error, state why discarding it is safe, and keep its `try` to one statement, so that the clause discards only the failure its author considered. Without a check, new clauses drifted from the rule, and existing clauses broke it across many unrelated package and test owners. + +## Decision + +The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop). + +Existing clauses have an exact baseline keyed by repository-relative path, a SHA-256 digest of the clause's syntax tokens together with its broken conditions, and occurrence count. Including the broken conditions makes turning a recorded one-statement `try` into a wider one, or deleting a recorded reason, a new finding, while edits inside the `try` that keep its conditions keep the clause's identity. The baseline follows the [unknown-cast inventory](2026-09-19-no-unknown-casts.md), and both checkers share [the inventory module](../../../../scripts/baseline-inventory.ts): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new findings exist, and no command adds an allowance. Unlike the unknown-cast inventory, which requires resolving an assertion before moving it to an unlisted file, moving a file that holds recorded clauses renames its baseline key in the same change, because narrowing a recorded `try` belongs to its owner rather than to the change that moves the file. + +The checker runs in the `hygiene` and `check-all` profiles and the CI static and primary modes of [the gate runner](../../../../scripts/run-gates.ts). Empty Promise rejection handlers such as `.catch(() => {})` are outside this rule and tracked separately in issue #8033. + +## Alternatives considered + +**Fix every existing clause before enforcing the rule.** Rejected because narrowing a multi-statement `try` changes which failures the clause discards, which only each owner can judge. The baseline lets enforcement start while the existing clauses remain recorded findings for their owners to fix. + +**Fingerprint the whole `try` statement.** Rejected because every edit inside a recorded `try` would become a new finding and force its owner to fix the clause during unrelated work. Fingerprinting the clause with its broken conditions rejects a new broken condition on a recorded clause without tying its identity to the statements inside the `try`; a `try` that is already wide can gain statements without a new finding. + +**A command that records clauses from a named revision.** Rejected because a local command cannot prove that the revision is the target branch: naming the current branch would record the branch's own clauses. Once the target branch carries the checker, merging it brings that branch's baseline along, so no command is needed. + +**Search text for `catch {}`.** Rejected because comments, strings, whitespace, and binding patterns defeat a text pattern, and the rule's conditions depend on the syntax tree. + +## Consequences + +New and changed empty clauses must conform, and fixing a recorded clause requires pruning its baseline entry. A partial fix, such as adding a name while the `try` stays wide, changes the clause's identity and therefore fails; the owner fixes the clause completely before pruning. The baseline key carries no line number, so a recorded clause can move within its file; identical clauses in one file share one fingerprint whose count covers each of them. + +Passing the checker establishes the form of every unrecorded empty clause. It does not establish that a reason is true, that a non-empty handler handles its error, or that a `try` holding one block or compound statement discards only one operation's failures. diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md new file mode 100644 index 0000000000..67611292f7 --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 拒绝静默的空 catch 子句 + +Status: implemented + +[English](2026-09-21-reject-silent-empty-catch.md) | 中文 + +## 问题 + +空 `catch` 会丢弃其 `try` 的所有失败,包括作者未预料到的缺陷。根规则要求此类子句命名错误、说明丢弃该错误为何安全,并将其 `try` 限制为一条语句,使子句只丢弃作者考虑过的失败。没有检查时,新增子句逐渐偏离该规则,而违反规则的现有子句分布在许多互不相关的包和测试所属模块中。 + +## 决策 + +[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop) 中的指引确认名称和原因属实。 + +现有子句使用精确基线记录,键由仓库相对路径、子句语法 token 连同其违反条件的 SHA-256 摘要及出现次数组成。摘要包含违反条件,因此把已记录的单语句 `try` 扩大为多语句 `try`,或删除已记录的原因,都会产生新的检查发现;而在 `try` 内部进行不改变其违反条件的修改,不改变子句的标识。基线沿用 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的做法,两个检查器共用[清单模块](../../../../scripts/baseline-inventory.ts):基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新发现时拒绝写入,且没有任何命令可以添加放行。unknown 类型断言清单要求先解决断言,才能将其移至未登记的文件;与之不同,移动包含已记录子句的文件时,须在同一变更中重命名其基线键,因为收窄已记录的 `try` 由其所属模块负责,而不属于移动文件的变更。 + +检查器在[门禁运行器](../../../../scripts/run-gates.ts)的 `hygiene` 和 `check-all` 配置以及 CI 静态模式和主模式中运行。`.catch(() => {})` 等空的 Promise 拒绝处理函数不属于此规则,另由 issue #8033 跟踪。 + +## 考虑过的替代方案 + +**先修复所有现有子句,再执行规则。** 不采用,因为收窄多语句 `try` 会改变子句丢弃哪些失败,只有各所属模块才能判断。基线使规则可以立即开始执行,同时现有子句仍作为已记录的检查发现,由其所属模块修复。 + +**对整个 `try` 语句计算指纹。** 不采用,因为已记录 `try` 内部的每次修改都会产生新的检查发现,迫使所属模块在无关工作中修复该子句。对子句连同其违反条件计算指纹,可以拒绝已记录子句上新增的违反条件,同时不让子句的标识依赖 `try` 内部的语句;已经过宽的 `try` 可以增加语句而不产生新的检查发现。 + +**提供从指定修订版本记录子句的命令。** 不采用,因为本地命令无法证明该修订版本就是目标分支:指定当前分支会记录该分支自身的子句。目标分支包含检查器后,合并目标分支会一并带入其基线,因此不需要这样的命令。 + +**在文本中搜索 `catch {}`。** 不采用,因为注释、字符串、空白和绑定模式都会使文本模式失效,而且规则的条件依赖语法树。 + +## 影响 + +新增和修改的空子句必须符合规则,修复已记录的子句时须清理其基线条目。部分修复,例如添加名称但 `try` 仍然过宽,会改变子句的标识,因此检查失败;所属模块须先完整修复子句,再清理基线条目。基线键不含行号,因此已记录的子句可以在所在文件内移动;同一文件中相同的子句共用一个指纹,其计数涵盖其中每一个子句。 + +通过检查器说明每个未记录的空子句都符合规定形式。它不证明原因属实,不证明非空处理代码处理了其错误,也不证明包含一个代码块或复合语句的 `try` 只丢弃一个操作的失败。 From 603ed7e7d0da17d3290e44d5b3b999a636840a2d Mon Sep 17 00:00:00 2001 From: Turtle Date: Tue, 10 Nov 2026 16:05:07 +0800 Subject: [PATCH 8/8] docs(error-handling): explain empty catch rules with examples --- ...-09-21-reject-silent-empty-catch.i18n.yaml | 4 +- .../2026-09-21-reject-silent-empty-catch.md | 2 +- ...2026-09-21-reject-silent-empty-catch.zh.md | 2 +- .agents/skills/dsh-error-handling/SKILL.md | 42 ++++++++++++++++++- scripts/verify-empty-catch.spec.ts | 4 +- scripts/verify-empty-catch.ts | 2 +- 6 files changed, 48 insertions(+), 8 deletions(-) diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml index b0b1325348..387e006013 100644 --- a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.i18n.yaml @@ -9,8 +9,8 @@ en: a89b84c7052329b4 zh: 9c511a0b4ee3f1ef /agent-note-reject-silent-empty-catch-clauses/decision: - en: 1b9199240c84fb54 - zh: 155f0381f09effa1 + en: 0392fb5d5cc3b387 + zh: c4219e43bded8ce6 /agent-note-reject-silent-empty-catch-clauses/alternatives-considered: en: 65d05680072f8797 zh: e160d37d8ece30ad diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md index 2b4b5e514e..bb3a6170bc 100644 --- a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.md @@ -10,7 +10,7 @@ An empty `catch` discards every failure of its `try`, including defects the auth ## Decision -The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop). +The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses). Existing clauses have an exact baseline keyed by repository-relative path, a SHA-256 digest of the clause's syntax tokens together with its broken conditions, and occurrence count. Including the broken conditions makes turning a recorded one-statement `try` into a wider one, or deleting a recorded reason, a new finding, while edits inside the `try` that keep its conditions keep the clause's identity. The baseline follows the [unknown-cast inventory](2026-09-19-no-unknown-casts.md), and both checkers share [the inventory module](../../../../scripts/baseline-inventory.ts): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new findings exist, and no command adds an allowance. Unlike the unknown-cast inventory, which requires resolving an assertion before moving it to an unlisted file, moving a file that holds recorded clauses renames its baseline key in the same change, because narrowing a recorded `try` belongs to its owner rather than to the change that moves the file. diff --git a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md index 67611292f7..e730a84bb8 100644 --- a/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md +++ b/.agents/notes/implemented/process/2026-09-21-reject-silent-empty-catch.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop) 中的指引确认名称和原因属实。 +[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses) 中的指引确认名称和原因属实。 现有子句使用精确基线记录,键由仓库相对路径、子句语法 token 连同其违反条件的 SHA-256 摘要及出现次数组成。摘要包含违反条件,因此把已记录的单语句 `try` 扩大为多语句 `try`,或删除已记录的原因,都会产生新的检查发现;而在 `try` 内部进行不改变其违反条件的修改,不改变子句的标识。基线沿用 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的做法,两个检查器共用[清单模块](../../../../scripts/baseline-inventory.ts):基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新发现时拒绝写入,且没有任何命令可以添加放行。unknown 类型断言清单要求先解决断言,才能将其移至未登记的文件;与之不同,移动包含已记录子句的文件时,须在同一变更中重命名其基线键,因为收窄已记录的 `try` 由其所属模块负责,而不属于移动文件的变更。 diff --git a/.agents/skills/dsh-error-handling/SKILL.md b/.agents/skills/dsh-error-handling/SKILL.md index fd8e0659f6..67cf503d7a 100644 --- a/.agents/skills/dsh-error-handling/SKILL.md +++ b/.agents/skills/dsh-error-handling/SKILL.md @@ -34,7 +34,47 @@ For each failure, define handling and reporting owners, containment, and guarant Catching limits exception propagation, not mutations. Only the affected state's owner can establish safe continuation. Otherwise stop dependent work, discard invalid state or instances, or escalate. Logging alone is not recovery. Retries require safe repetition, cancellation, and an explicit owner; finite operations need budgets, while continuing supervision needs lifecycle ownership and observable degradation. -An empty `catch` discards every failure of its `try`, so it is acceptable only when each such failure leaves the owner's state valid and no caller can act on it, such as best-effort cleanup after a primary failure. Keep the `try` to one statement, bind the error to an underscore-prefixed name that states the expected failure, such as `_alreadyGone` (lint requires the prefix on an unused binding; a bare `_` counts as unnamed), and explain in the `catch` block why the state stays valid. When only some failures are acceptable, test `code` or `name` and rethrow the rest; an unconditional discard also reports defects as success. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) enforces the form; review checks that the name and reason are true. +### Empty catch clauses + +An empty `catch` has no statement other than `;` in its block, and it discards every failure its `try` raises. Use one only when every such failure leaves the owner's state valid and no caller could act on it, such as failing to remove a temporary file that nothing reads. A `catch` that logs, reports, rethrows, or returns a fallback is not empty, and the rules below do not apply to it. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) checks every `try`/`catch` statement in first-party JavaScript and TypeScript, including tests; it does not check `promise.catch()` callbacks. The checker checks the form; review checks that the name and the reason are true. + +**The `try` holds one statement.** One statement means one syntactic statement, such as one call or one assignment, however many lines it spans; it does not mean one line. With several statements, the reason covers one expected failure while the clause also discards the others, including defects such as a `TypeError`, and a failure in an early statement skips the later ones while the caller sees success: + +```ts +// Rejected: three statements in one try. +try { + await unlink(tempFile) + registry.delete(id) + emit('removed', id) +} catch (_cleanupFailed) { + // A leftover temporary file holds no state anything reads. +} + +// Accepted: only the unlink failure is discarded. +try { + await unlink(tempFile) +} catch (_cleanupFailed) { + // A leftover temporary file holds no state anything reads. +} +registry.delete(id) +emit('removed', id) +``` + +When several statements each tolerate a failure, give each its own `try` and reason. The checker counts one block or one compound statement, such as one `if`, as one statement; review rejects such a `try` when it contains several operations. + +**The binding names the expected failure.** Write `catch (_cleanupFailed)`, not `catch {}` or `catch (_)`. Lint requires an unused binding to start with `_`, and a bare `_` names nothing. + +**A comment states why discarding the failure is safe.** Put it in the `catch` block or after the clause's closing `}` on the same line. A comment inside the `try` block or above `try` does not count. `// ignore` and `// expected` restate the empty block; say which failure is expected and why the state stays valid. + +**Accept only some failures by testing them.** When only some failures are safe, such as a missing file while a permission error must still surface, write a non-empty `catch` that tests `code` or `name` and rethrows the rest; the checker does not check such a clause. + +```ts +try { + await unlink(tempFile) +} catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error +} +``` ## Localized, actionable, visible reports diff --git a/scripts/verify-empty-catch.spec.ts b/scripts/verify-empty-catch.spec.ts index eabc522e9c..4e87104ee8 100644 --- a/scripts/verify-empty-catch.spec.ts +++ b/scripts/verify-empty-catch.spec.ts @@ -173,8 +173,8 @@ describe('empty catch inventory', () => { const root = fixture() write(root, sourcePath, broken) const skillPath = '.agents/skills/dsh-error-handling/SKILL.md' - expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#catch-recover-or-stop)`) - expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^## Catch, recover, or stop$/mu) + expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#empty-catch-clauses)`) + expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^### Empty catch clauses$/mu) }) it('requires pruning retired counts while preserving the remaining clause', () => { diff --git a/scripts/verify-empty-catch.ts b/scripts/verify-empty-catch.ts index d988aee658..deb90affaf 100644 --- a/scripts/verify-empty-catch.ts +++ b/scripts/verify-empty-catch.ts @@ -169,7 +169,7 @@ const gate: InventoryGate = { 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 (see .agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop).', + + ' and keep its try to one statement (see .agents/skills/dsh-error-handling/SKILL.md#empty-catch-clauses).', describe: finding => `${finding.file}:${String(finding.line)} (${finding.defects.join(', ')})`, success: count => `verify-empty-catch: no new silent catches; ${String(count)} recorded clauses remain.`, }