Merge pull request #4862 from deepseek-harness/turtle/catch-disposition

feat(infra): reject silent empty catch clauses
This commit is contained in:
Turtle authored and GitHub committed 2026-11-11 15:06:58 +08:00
commit 303bcb4137
15 files changed
+1203 -133

No files matched your search

@@ -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: 0392fb5d5cc3b387
zh: c4219e43bded8ce6
/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
@@ -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#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.
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.
@@ -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#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` 由其所属模块负责,而不属于移动文件的变更。
检查器在[门禁运行器](../../../../scripts/run-gates.ts)的 `hygiene` 和 `check-all` 配置以及 CI 静态模式和主模式中运行。`.catch(() => {})` 等空的 Promise 拒绝处理函数不属于此规则,另由 issue #8033 跟踪。
## 考虑过的替代方案
**先修复所有现有子句,再执行规则。** 不采用,因为收窄多语句 `try` 会改变子句丢弃哪些失败,只有各所属模块才能判断。基线使规则可以立即开始执行,同时现有子句仍作为已记录的检查发现,由其所属模块修复。
**对整个 `try` 语句计算指纹。** 不采用,因为已记录 `try` 内部的每次修改都会产生新的检查发现,迫使所属模块在无关工作中修复该子句。对子句连同其违反条件计算指纹,可以拒绝已记录子句上新增的违反条件,同时不让子句的标识依赖 `try` 内部的语句;已经过宽的 `try` 可以增加语句而不产生新的检查发现。
**提供从指定修订版本记录子句的命令。** 不采用,因为本地命令无法证明该修订版本就是目标分支:指定当前分支会记录该分支自身的子句。目标分支包含检查器后,合并目标分支会一并带入其基线,因此不需要这样的命令。
**在文本中搜索 `catch {}`。** 不采用,因为注释、字符串、空白和绑定模式都会使文本模式失效,而且规则的条件依赖语法树。
## 影响
新增和修改的空子句必须符合规则,修复已记录的子句时须清理其基线条目。部分修复,例如添加名称但 `try` 仍然过宽,会改变子句的标识,因此检查失败;所属模块须先完整修复子句,再清理基线条目。基线键不含行号,因此已记录的子句可以在所在文件内移动;同一文件中相同的子句共用一个指纹,其计数涵盖其中每一个子句。
通过检查器说明每个未记录的空子句都符合规定形式。它不证明原因属实,不证明非空处理代码处理了其错误,也不证明包含一个代码块或复合语句的 `try` 只丢弃一个操作的失败。
@@ -34,6 +34,48 @@ 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.
### 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
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.
+1 -1
View File
@@ -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.
+1
View File
@@ -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",
+53
View File
@@ -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 })
}
+214
View File
@@ -0,0 +1,214 @@
/**
* 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 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, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
/** Source areas every inventory gate must find, so a narrowed scan cannot pass silently. */
const AREAS = ['packages/', 'apps/', 'scripts/', 'website/'] as const
/** Source extensions an inventory gate scans, including tests and configuration files. */
const SOURCE_EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/u
/** Existing finding counts, keyed by repository path and syntax fingerprint. */
export type InventoryBaseline = Record<string, Record<string, number>>
/** One finding a gate rejects unless the inventory records it. */
export interface InventoryFinding {
/** Repository-relative path with forward slashes. */
file: string
/** SHA-256 of the finding's form, derived from syntax tokens that exclude comments and whitespace. */
fingerprint: string
}
/** Everything shared inventory bookkeeping needs to know about one gate. */
export interface InventoryGate<T extends InventoryFinding> {
/** Gate name that prefixes every diagnostic and names the `pnpm run` script. */
name: string
/** Repository-relative path of the recorded inventory. */
baselinePath: string
/** Scan first-party source for the rejected form. */
scan: (repoRoot: string) => T[]
/** Rejection text after the gate name for a finding the inventory does not allow. */
rejection: string
/** One line describing a finding, appended to {@link rejection}. */
describe: (finding: T) => string
/** Console line for a passing run, given the number of recorded findings. */
success: (count: number) => string
}
/**
* Whether a repository path belongs to an inventory gate's corpus.
* @param file - repository-relative path with forward slashes.
* @returns `true` for first-party source outside vendored code and frozen archived notes.
*/
export function isInventorySource(file: string): boolean {
return SOURCE_EXTENSIONS.test(file)
&& !file.startsWith('vendor/')
&& !file.startsWith('.agents/notes/archived/')
}
/**
* Hash a node's syntax tokens, so formatting and comment edits keep one identity.
* @param node - the node whose form the inventory records.
* @param source - the file that owns the node.
* @returns SHA-256 of the node's token texts.
*/
export function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
const tokens: string[] = []
const visit = (child: ts.Node): void => {
if (ts.isJSDoc(child)) return
if (ts.isToken(child)) tokens.push(child.getText(source))
else child.getChildren(source).forEach(visit)
}
visit(node)
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
}
/**
* List the first-party source paths a gate scans.
* @param repoRoot - repository root containing the Git index.
* @param name - gate name for diagnostics.
* @returns sorted repository-relative paths of tracked and non-ignored untracked source files.
* @throws when a required source area is missing or an eligible path is a symlink.
*/
export function listInventorySources(repoRoot: string, name: string): string[] {
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
cwd: repoRoot,
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isInventorySource))].sort()
const present = files.filter((file) => {
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
if (stat?.isSymbolicLink()) throw new Error(`${name}: source symlink is unsupported: ${file}`)
return stat?.isFile() === true
})
for (const area of AREAS) {
if (!present.some(file => file.startsWith(area))) {
throw new Error(`${name}: source discovery omitted ${area}`)
}
}
return present
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Read and validate one recorded inventory.
* @param gate - the gate whose findings the inventory allows.
* @param repoRoot - repository root holding the inventory.
* @returns the recorded counts, keyed by repository path and fingerprint.
* @throws when the inventory is malformed or names a path outside the gate's corpus.
*/
export function readInventoryBaseline<T extends InventoryFinding>(
gate: InventoryGate<T>,
repoRoot: string,
): InventoryBaseline {
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, gate.baselinePath), 'utf8'))
if (!isRecord(value)) throw new Error(`${gate.name}: baseline must be a file-to-counts object`)
const baseline: InventoryBaseline = {}
for (const [file, counts] of Object.entries(value)) {
if (!isInventorySource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|| !isRecord(counts) || Object.keys(counts).length === 0) {
throw new Error(`${gate.name}: invalid baseline file: ${file}`)
}
const parsed: Record<string, number> = {}
for (const [fingerprint, count] of Object.entries(counts)) {
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
throw new Error(`${gate.name}: invalid baseline count: ${file}:${fingerprint}`)
}
parsed[fingerprint] = count
}
baseline[file] = parsed
}
return baseline
}
/**
* Count exact findings without granting a file-wide allowance.
* @param findings - observed findings.
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countInventory(findings: readonly InventoryFinding[]): InventoryBaseline {
const baseline: InventoryBaseline = {}
for (const { file, fingerprint } of findings) {
const counts = baseline[file] ??= {}
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
}
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
}
/**
* Enforce one gate's recorded inventory, optionally deleting retired allowances.
* @param gate - the gate to enforce.
* @param repoRoot - repository root to scan.
* @param prune - remove stale entries only after establishing that no new finding exists.
* @returns the number of findings still present.
* @throws for new findings, malformed inventories, or stale entries without pruning.
*/
export function verifyInventory<T extends InventoryFinding>(
gate: InventoryGate<T>,
repoRoot: string,
prune = false,
): number {
const baseline = readInventoryBaseline(gate, repoRoot)
const findings = gate.scan(repoRoot)
const remaining = structuredClone(baseline)
const added: T[] = []
for (const finding of findings) {
const counts = remaining[finding.file]
const allowance = counts?.[finding.fingerprint] ?? 0
if (counts !== undefined && allowance > 0) counts[finding.fingerprint] = allowance - 1
else added.push(finding)
}
if (added.length > 0) {
throw new Error(`${gate.name}: ${gate.rejection}\n`
+ added.map(finding => ` ${gate.describe(finding)}`).join('\n'))
}
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
if (stale.length > 0) {
if (!prune) {
throw new Error(`${gate.name}: remove retired baseline entries with pnpm run ${gate.name} --prune.\n`
+ stale.join('\n'))
}
writeFileSync(resolve(repoRoot, gate.baselinePath), `${JSON.stringify(countInventory(findings), null, 2)}\n`)
}
return findings.length
}
/**
* Run one gate as a command: `--prune` retires stale entries, no argument verifies, anything else
* fails the process.
* @param gate - the gate to enforce.
* @param root - repository root to scan.
*/
export function runInventoryGate<T extends InventoryFinding>(gate: InventoryGate<T>, root: string): void {
try {
const args = process.argv.slice(2)
if (args.length === 1 && args[0] === '--prune') {
console.log(gate.success(verifyInventory(gate, root, true)))
} else if (args.length === 0) {
console.log(gate.success(verifyInventory(gate, root)))
} else {
throw new Error(`Usage: pnpm run ${gate.name} [--prune]`)
}
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
}
+290
View File
@@ -0,0 +1,290 @@
{
"apps/cli/tests/built-bin.e2e.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"apps/desktop/scripts/desktop-publish.ts": {
"d37e8639087921e2491d45d40d63b44e72b30a516ad3a5f3155f467c7f5c3ac7": 1
},
"apps/desktop/src/client/WelcomePage.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"apps/desktop/src/preload-platform-account.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"apps/web/tests/chat-scroll-contract.e2e.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"apps/web/tests/support.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/api/gateway/src/client/remote-stream.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/api/gateway/tests/gateway-stream.host.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/api/workspace-files/src/client/change-feed.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/app-boot/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/plugin-manager/src/registry.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/plugin-manager/tests/operations-process.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/boot/plugin-market/src/repository-cache.ts": {
"3d8f6e3468aecc6e006ee3e5f20a5c6c5277316636c8849756fc6d710e9d907b": 1
},
"packages/client/modules/src/index.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/store/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-open-in-app/src/client/controller.ts": {
"ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1
},
"packages/client/ui-open-in-app/src/client/open-path.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-schedule/src/client/recent-time-zones.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-sidebar-browser/src/client/browser/url.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-sidebar-right/src/client/tab-inventory.ts": {
"ee22b9dbd07fc0b76f0464bf59386efb6925dab82c4539a2772b909b944ee33c": 1
},
"packages/client/ui-skill/src/client/SkillRow.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/context/file-reference-local/tests/search.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/credentials/deepseek-account/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/credentials/deepseek-account/src/logout.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/experimental/client-ui-forge/src/panel.ts": {
"ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1
},
"packages/experimental/inspector/src/client/bridge/transport.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/client/cdp/console.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/inspector/src/client/inspection/realm.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/bridge/hub.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/bridge/runtime-rpc.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4
},
"packages/experimental/inspector/src/worker/bridge/session.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/cdp/domains/dom/model.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/cdp/realm-sessions.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/cordis-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/network-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/inspection/query-router.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/realm-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/realms/host/bridge.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/experimental/inspector/src/worker/realms/host/sources.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/liveshare/src/client/owner-login.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/experimental/liveshare/src/client/share-relay-address.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/experimental/liveshare/src/client/ShareEditPanel.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/liveshare/src/host/shareable-catalog.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/liveshare/src/host/tunnel-supervision.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/liveshare/src/host/viewer-dispatch.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/experimental/liveshare/tests/fixtures/base-llm.mjs": {
"8b2766548472fe722af04dc7c95b06d303bb164fd12fbec87a07ea6eaae7146a": 1
},
"packages/experimental/ptc-runtime-python/src/index.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webhook-github/src/handler.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/src/client/client.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/src/transport/tunnel.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/tests/compile/transform-corpus-check.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/tests/polyfill/als-shim.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/host/directory-picker-browse/tests/service.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/host/open-in-app/src/icons.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/host/open-in-app/src/resolver.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/identity/anonymous-user-id/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-deepseek/src/file-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-deepseek/src/files-api.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-pi-ai/src/replay.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/llm/llm/src/adapter-failure.ts": {
"19186deef10a7178489ddf20fcaf6688a0baf38bf6d9933cb78fe65023f3280f": 1
},
"packages/lsp/lsp-stdio/src/instance.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session-query/session-query-sqlite/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/session-query/session-query/src/cold-read.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/src/generation.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/tests/zstd.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/shell/bash-local/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/shell/pwsh-local/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/skill/skill-filesystem/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/skill/skill/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/spill/spill-local/src/cleanup.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-acp/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-claude-code/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-codex/src/run.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subagent/subagent-dsh-sdk/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-dsh-sdk/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent/src/out-of-process.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subprocess/subprocess-local/src/index.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/src/linux-scope.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5
},
"packages/subprocess/subprocess-local/src/output.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subprocess/subprocess-local/src/runner-protocol.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/src/spawn-runner.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4
},
"packages/subprocess/subprocess-local/src/spawn.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/subprocess/subprocess-local/src/windows-job.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subprocess/subprocess-local/tests/native-containment.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subprocess/subprocess-local/tests/native-windows.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/tests/spawn.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5
},
"packages/test-support/client-runtime/src/assembly/test-client.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/gen-session-format-catalog.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/run-gates.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/slot-walk.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"vitest.e2e.config.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"vitest.web.config.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
}
}
+11 -1
View File
@@ -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) => {
+1
View File
@@ -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' }),
]
+278
View File
@@ -0,0 +1,278 @@
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'
const recorded = 'try { run() } catch { /* reason */ }\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 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']],
['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])
})
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 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 */ }'],
['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([])
})
// 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([])
})
it('parses TSX so a JSX sibling does not hide the clause', () => {
const text = 'export const view = <View onClick={() => { try { run() } catch {} }} />\n'
expect(defects('input.tsx', text)).toEqual([['unnamed', 'unexplained']])
})
it('reports normalized paths and the catch keyword line', () => {
const findings = findEmptyCatches('packages\\example\\index.ts', '\n\ntry { run() }\ncatch {}')
expect(findings).toHaveLength(1)
expect(findings[0]).toMatchObject({ file: 'packages/example/index.ts', line: 4 })
expect(findings[0]?.fingerprint).toMatch(/^[a-f0-9]{64}$/u)
})
it('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')
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([
['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, recorded)
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 only its try statement changes', () => {
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('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}#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', () => {
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, tests and root configuration', () => {
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',
'config.ts',
]
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)
}
})
})
+199
View File
@@ -0,0 +1,199 @@
/**
* Reject empty `catch` clauses that break the recorded rule, retiring the legacy clauses.
*
* 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. 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. 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`. 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,
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 clause 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, and its defects. */
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
}
/**
* 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 source - the file that owns the clause.
* @returns `true` when such a comment exists.
*/
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. */
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))
}
function analyze(file: string, text: string): EmptyCatchScan {
const normalized = file.replaceAll('\\', '/')
const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true)
const findings: EmptyCatch[] = []
let clauses = 0
const visit = (node: ts.Node): void => {
if (ts.isCatchClause(node)) {
clauses += 1
if (nonEmptyStatements(node.block).length === 0) {
const names = bindingNames(node)
const defects: EmptyCatchDefect[] = []
if (!names.some(name => name !== '_')) defects.push('unnamed')
if (!hasReason(node, source)) defects.push('unexplained')
if (!ts.isTryStatement(node.parent) || nonEmptyStatements(node.parent.tryBlock).length !== 1) {
defects.push('wide-try')
}
if (defects.length > 0) {
findings.push({
file: normalized,
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
fingerprint: createHash('sha256')
.update(`${syntaxFingerprint(node, source)}:${defects.join(',')}`)
.digest('hex'),
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; a clause whose body holds a real statement never matches.
*/
export function findEmptyCatches(file: string, text: string): EmptyCatch[] {
return analyze(file, text).findings
}
/**
* Scan tracked source and non-ignored new source, including tests and configuration files.
* @param repoRoot - repository root containing the Git index.
* @returns every empty clause that breaks the rule in the current working tree.
* @throws if discovery omits a required source area, finds no catch clause at all, or an eligible path is a symlink.
*/
export function scanEmptyCatches(repoRoot: string): EmptyCatch[] {
const scans = listInventorySources(repoRoot, 'verify-empty-catch')
.map(file => analyze(file, readFileSync(resolve(repoRoot, file), 'utf8')))
if (scans.every(scan => scan.clauses === 0)) {
throw new Error('verify-empty-catch: source discovery found no catch clause')
}
return scans.flatMap(scan => scan.findings)
}
const gate: InventoryGate<EmptyCatch> = {
name: 'verify-empty-catch',
baselinePath: 'scripts/empty-catch.baseline.json',
scan: scanEmptyCatches,
rejection: 'an empty catch must name the discarded error, state why it needs no handling,'
+ ' and keep its try to one statement (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.`,
}
/**
* 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)
}
+5 -27
View File
@@ -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 {
+23 -104
View File
@@ -1,16 +1,22 @@
/** Reject new assertions to unknown while retiring the recorded existing assertions. */
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
import {
countInventory,
listInventorySources,
runInventoryGate,
syntaxFingerprint,
verifyInventory,
type InventoryBaseline,
type InventoryGate,
} from './baseline-inventory.ts'
const root = resolve(import.meta.dirname, '..')
const baselinePath = 'scripts/no-unknown-casts.baseline.json'
/** Existing assertion counts, keyed by repository path and syntax fingerprint. */
export type UnknownCastBaseline = Record<string, Record<string, number>>
export type UnknownCastBaseline = InventoryBaseline
/** One direct assertion to unknown in authored source. */
export interface UnknownCast {
@@ -22,17 +28,6 @@ export interface UnknownCast {
fingerprint: string
}
function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
const tokens: string[] = []
const visit = (child: ts.Node): void => {
if (ts.isJSDoc(child)) return
if (ts.isToken(child)) tokens.push(child.getText(source))
else child.getChildren(source).forEach(visit)
}
visit(node)
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
}
function assertsUnknown(type: ts.TypeNode): boolean {
if (ts.isParenthesizedTypeNode(type)) return assertsUnknown(type.type)
return type.kind === ts.SyntaxKind.UnknownKeyword
@@ -65,12 +60,6 @@ export function findUnknownCasts(file: string, text: string): UnknownCast[] {
return casts
}
function isSource(file: string): boolean {
return /\.(?:[cm]?[jt]s|[jt]sx)$/u.test(file)
&& !file.startsWith('vendor/')
&& !file.startsWith('.agents/notes/archived/')
}
/**
* Scan tracked source and non-ignored new source, including tests and configuration files.
* @param repoRoot - repository root containing the Git index.
@@ -78,47 +67,17 @@ function isSource(file: string): boolean {
* @throws if discovery omits a required source area or an eligible path is a symlink.
*/
export function scanUnknownCasts(repoRoot: string): UnknownCast[] {
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
cwd: repoRoot,
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isSource))].sort()
const present = files.filter((file) => {
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
if (stat?.isSymbolicLink()) throw new Error(`verify-no-unknown-casts: source symlink is unsupported: ${file}`)
return stat?.isFile() === true
})
for (const area of ['packages/', 'apps/', 'scripts/', 'website/']) {
if (!present.some(file => file.startsWith(area))) {
throw new Error(`verify-no-unknown-casts: source discovery omitted ${area}`)
}
}
return present.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
return listInventorySources(repoRoot, 'verify-no-unknown-casts')
.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function readBaseline(repoRoot: string): UnknownCastBaseline {
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, baselinePath), 'utf8'))
if (!isRecord(value)) throw new Error('verify-no-unknown-casts: baseline must be a file-to-counts object')
const baseline: UnknownCastBaseline = {}
for (const [file, counts] of Object.entries(value)) {
if (!isSource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|| !isRecord(counts) || Object.keys(counts).length === 0) {
throw new Error(`verify-no-unknown-casts: invalid baseline file: ${file}`)
}
const parsed: Record<string, number> = {}
for (const [fingerprint, count] of Object.entries(counts)) {
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
throw new Error(`verify-no-unknown-casts: invalid baseline count: ${file}:${fingerprint}`)
}
parsed[fingerprint] = count
}
baseline[file] = parsed
}
return baseline
const gate: InventoryGate<UnknownCast> = {
name: 'verify-no-unknown-casts',
baselinePath: 'scripts/no-unknown-casts.baseline.json',
scan: scanUnknownCasts,
rejection: 'new assertions to unknown are forbidden. Use a typed value or narrow the input.',
describe: cast => `${cast.file}:${String(cast.line)} (${cast.fingerprint})`,
success: count => `verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`,
}
/**
@@ -127,13 +86,7 @@ function readBaseline(repoRoot: string): UnknownCastBaseline {
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBaseline {
const baseline: UnknownCastBaseline = {}
for (const { file, fingerprint } of casts) {
const counts = baseline[file] ??= {}
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
}
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
return countInventory(casts)
}
/**
@@ -144,43 +97,9 @@ export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBas
* @throws for new assertions, malformed inventories, or stale entries without pruning.
*/
export function verifyNoUnknownCasts(repoRoot: string, prune = false): number {
const baseline = readBaseline(repoRoot)
const casts = scanUnknownCasts(repoRoot)
const current = countUnknownCasts(casts)
const remaining = structuredClone(baseline)
const added: UnknownCast[] = []
for (const cast of casts) {
const counts = remaining[cast.file]
const allowance = counts?.[cast.fingerprint] ?? 0
if (counts !== undefined && allowance > 0) counts[cast.fingerprint] = allowance - 1
else added.push(cast)
}
if (added.length > 0) {
throw new Error('verify-no-unknown-casts: new assertions to unknown are forbidden. Use a typed value or narrow the input.\n'
+ added.map(cast => ` ${cast.file}:${String(cast.line)} (${cast.fingerprint})`).join('\n'))
}
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
if (stale.length > 0) {
if (!prune) {
throw new Error('verify-no-unknown-casts: remove retired baseline entries with pnpm run verify-no-unknown-casts --prune.\n'
+ stale.join('\n'))
}
writeFileSync(resolve(repoRoot, baselinePath), `${JSON.stringify(current, null, 2)}\n`)
}
return casts.length
return verifyInventory(gate, repoRoot, prune)
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
try {
const args = process.argv.slice(2)
if (args.length > 1 || (args.length === 1 && args[0] !== '--prune')) {
throw new Error('Usage: pnpm run verify-no-unknown-casts [--prune]')
}
const count = verifyNoUnknownCasts(root, args[0] === '--prune')
console.log(`verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`)
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
runInventoryGate(gate, root)
}