Repository navigation
chore: reject comments in JS/TS code and remove existing ones - #5019
Conversation
Add scripts/check-comments.mjs and run it before oxlint in `pnpm lint` and in lint-staged. It parses every JS/TS file with oxc-parser and rejects any comment except tool directives, the shebang, `/// <reference>`, and single-tag JSDoc `@type` casts in JS files. A file it cannot parse is reported instead of skipped. Paths listed in .commentignore (gitignore syntax) are exempt. A full run also reports entries that no longer match a file with comments, so the list only shrinks. `--fix` deletes the reported comments and writes a file only when its AST is unchanged.
The pre-commit hook ran `oxlint --fix` over every staged file and folded the result into the commit. Its fixes are not always safe: on main it renames a catch parameter in packages/core/src/tool/runtime/tool-executor.ts into a redeclared `error`, and rewrites `opts.match(event)` in packages/core/src/utils/wait.ts as `event.test(opts)`. Any commit that touched those files would fail or silently ship the rewrite. The hook now only checks. Commits no longer get fixable problems repaired automatically; run `pnpm lint:fix` to apply oxlint fixes by hand.
Generated with `node scripts/check-comments.mjs --fix`. Every rewritten
file parses to the same AST as before, apart from removed JSX comment
containers (`{/* ... */}`).
Two parts were not produced by `--fix` alone:
- The six files under "Kept for now" in .commentignore keep only the
comments introduced in #4630, and packages/node-sdk/src keeps its
JSDoc. Their other comments were removed with the same stripping logic.
- apps/kimi-code/scripts/native/native-deps.mjs drops a `@type` cast that
referred to the removed `NativeDepDescriptor` typedef.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
|
❌ Nix build failed Hash mismatch in
Please update |
sherif rejects a dependency declared at different versions in the workspace. agent-core-v2 already depends on ignore ^5.3.2, and the root check script only uses its add/ignores API, which 5.x provides.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b92370d9f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "lint-staged": "16.4.0", | ||
| "oxc-parser": "0.159.0", |
There was a problem hiding this comment.
Update the Nix dependency hash for the new dependencies
For Nix installations, adding oxc-parser and its native bindings changes the fetched dependency contents, but flake.nix:154–158 still declares the previous fixed-output pnpmDeps hash. That fetch includes the root workspace, so these development dependencies affect it even though they are not runtime dependencies. The Nix package build will fail with a hash mismatch until the hash is updated alongside the lockfile; the commit description also acknowledges this update as pending.
Useful? React with 👍 / 👎.
| for (const child of children) { | ||
| if (child.type === 'JSXExpressionContainer' && child.expression.type === 'JSXEmptyExpression') continue; | ||
| const last = merged.at(-1); | ||
| if (child.type === 'JSXText' && last?.type === 'JSXText') last.value += child.value; |
There was a problem hiding this comment.
Preserve JSX text boundaries in the fixer's safety check
When --fix removes a comment between multiline JSX text nodes, merging their raw text before whitespace normalization can hide a rendered-text change. For example, <span>a\n {/* x */}\n b</span> becomes <span>a\n b</span>. Local TypeScript transpilation confirms that the original produces text children "a", "b" (rendering ab), whereas the rewrite produces "a b". This canonicalizer treats both as identical, allowing the safety check to approve a behavior-changing rewrite. Preserve the original text-node boundaries during normalization, or reject removals that change the resulting children.
Useful? React with 👍 / 👎.
The --fix safety check merged adjacent JSX text before normalizing its
whitespace, while the JSX transform cleans each text node on its own.
Removing a comment that sits on its own line between two lines of text,
as in `<span>a\n {/* x */}\n b</span>`, turns children ["a", "b"] into
"a b", yet the check reported no change and wrote the file.
Normalize each JSX text node separately and drop empty ones, matching the
compiler. Such removals, and inline comments inside JSX text, are now
reported for manual deletion instead of being rewritten.
…ings (#5023) * chore: stop the pre-commit hook from rewriting staged code lint-staged ran `oxlint --fix --quiet` before the type-aware check. `--quiet` only hides warnings: fixes from warn-level rules were still applied and staged into the commit without any output. Some of those fixes change behavior, e.g. unicorn/no-array-sort rewrites `xs.sort()` to `xs.toSorted()`, so callers relying on the in-place sort break. The type-aware step already runs every rule, so dropping the fix step only removes the silent rewrite. Errors still block the commit. * chore: guard the lint setup and run the import-boundary check in pnpm lint pnpm lint now runs oxlint (errors only), the agent-core-v2 import boundary check, and scripts/checks/guards.mjs. The guards fail when the effective oxlint config drifts from the committed snapshot, when a registered check stops being invoked where it is registered, or when the pre-commit hook passes --fix again. CI runs the guards' tests in the lint job. The boundary check passed on main but nothing ran it, although AGENTS.md says it enforces the remote executor layering. check-service-naming.mjs is removed: no command or workflow ran it, half of its scan roots no longer exist, and no AGENTS.md rule refers to its naming convention. AGENTS.md and CONTRIBUTING now say how to run lint, that lint:fix is not a formatter, and that some of its fixes change behavior. * chore: upgrade oxlint to 1.94 without changing what lint reports Upgrade oxlint 1.59.0 -> 1.94.0 and oxlint-tsgolint 0.20.0 -> 7.0.2007 (1.94 requires tsgolint >= 7.0.2007). With the config unchanged, the upgrade enabled new rules through the enabled categories, including vitest rules for test files that --print-config does not show, and started applying import/extensions options that 1.59 never reported: 1,176 errors and 34,910 warnings (before: 0 and 2,801). This change keeps what lint reports unchanged: - Turn off the 14 newly enabled rules that already report on existing code until the lint restructure decides each one. Newly enabled rules without findings stay on. - Allow `.js` import specifiers in minidb, klient, migration-legacy and one acp-server test helper, which 1.59 did not report. - Teach vitest/expect-expect the repository's assertion helpers (expect*, assert*, *.expect*) instead of turning it off. - Remove ten imports that were only re-exported from their source module, and rename two unicorn/no-thenable directives that 1.94 no longer matched. The guards now add the category rules of plugins enabled only in an override and compare every top-level key of the printed config, so the snapshot records changes like the hidden vitest rules. The pnpm dependency hash in flake.nix still needs the value reported by the Nix build. * chore: list every oxlint rule explicitly and enforce them as errors All rule categories are now off and each enabled rule is listed in .oxlintrc.json as an error: 165 rules, plus 16 vitest rules for test files. The 1.94 upgrade moved rules between categories and enabled vitest rules that --print-config does not show, so with categories on an oxlint upgrade could change the rule set without this file changing. The rules come from the upstream recommended configs (eslint, typescript-eslint) or report bug patterns. All rules that were errors stay errors, and the 62 newly enabled ones have no findings today. The plugins list now includes oxc. Listing plugins replaces oxlint's defaults and the list had left oxc out, so oxlint's own bug detectors (const-comparisons, erasing-op and others) never ran. The warn level is gone: lint and the pre-commit hook run with --deny-warnings. Former warn rules are either errors now, off as style, or will be frozen at their current findings by a follow-up change. Rules kept off on purpose are listed with the reason. * chore: remove lint suppression comments that suppress nothing Remove 82 disable directives that no rule uses, checked against the full rule set: the enabled rules plus the rules a follow-up change freezes at their current findings. - 54 Event2 headers also named eslint-plugin-import/namespace, which no config enables. The no-unsafe-declaration-merging suppression and its reason stay. - 27 standalone directives and one trailing directive suppressed rules that are off: style rules, rules the team keeps off, or rules whose checks no longer report the line. Five directives that only suppress rules frozen by the follow-up stay, including the documented switch-exhaustiveness exception in the TUI notify controller. Only comments change. * chore: freeze lint rules that already have findings at their current count Thirty-two rules that report bugs or bug-prone patterns already have findings in existing code, and fixing those changes behavior. Instead of leaving them off, .oxlintrc.ratchet.json turns them on over the main config and scripts/checks/ratchet.mjs holds each file to its current count: 1,542 findings in 429 files. Frozen rules include no-explicit-any (outside tests), switch exhaustiveness, empty blocks, in-place array sort, || where ?? may be meant, console calls in packages/*/src and apps/*/src, conditional expects and skipped tests. The check fails when a file gains findings (listing its locations), when the baseline allows more than the code has, when a disable directive suppresses nothing with all rules on, and when the ratchet config's ignorePatterns drift from the main config, since extends does not carry them over. --update only lowers the baseline; raising it needs --allow-increase. pnpm lint runs the check and the registry keeps it wired. The pre-commit hook and editors keep using the main config. * chore: remove type arguments that repeat their defaults Remove 91 explicit type arguments that equal the type parameter's default, in 16 files, and enforce typescript/no-unnecessary-type-arguments. Type arguments are erased at compile time, so runtime behavior does not change; type-checking passes for every project CI checks. * chore: drop redundant undefined from optional parameters Remove `| undefined` from 31 optional parameters in 8 files, where the `?` already allows undefined, and enforce typescript/no-duplicate-type-constituents. All 31 sites are function or method parameters, including methods of the node-sdk and oauth packages; parameter types are unaffected by exactOptionalPropertyTypes, so the published signatures stay equivalent. * chore: use const for bindings that are never reassigned Change 11 let declarations that are never reassigned to const, which does not change behavior, and freeze eslint/prefer-const in the ratchet for the other 41. Those declare a binding early and assign it later (for example a TUI referenced by closures created before it exists); making them const means moving the declaration, which can change when the value is first read. * chore: merge duplicate imports of the same module Merge 59 duplicate imports in 46 files into one statement per module and enforce import/no-duplicates. Under verbatimModuleSyntax a declaration that is not `import type` still loads its module, so every touched file was checked: the set of modules loaded at runtime is unchanged for all 1,293 imports. Merged statements follow the existing layout: one line up to 100 characters, otherwise one specifier per line. * chore: keep no-unnecessary-type-assertion off Applying this rule's fixes removed 1,135 assertions and broke type-checking with 97 errors in 41 files: assertions it reports as unnecessary are needed by tsc in this codebase, mostly for index-signature access and properties absent from the declared type. Its findings are not reliable here, so the rule stays off with the reason in .oxlintrc.json. * docs: describe the lint ratchet and suppression rules for agents AGENTS.md now lists what pnpm lint runs, forbids editing the ratchet config or raising its baseline to get a passing run, says how a needed disable directive gives its reason, and explains that rules frozen in the ratchet must not gain findings and that the baseline is lowered after fixing them. CONTRIBUTING describes the ratchet in pnpm lint. * chore: fit the comment check into the lint guards Register the comment check in pnpm lint and lint-staged, and its tests in CI, in the wiring registry, so the guards report it if it is unwired. List it in the pnpm lint descriptions in AGENTS.md and CONTRIBUTING. Empty catch blocks used to carry a comment such as `// ignore`, which eslint/no-empty accepts. #5019 removed those comments and comments are no longer allowed, so after the merge the rule reported 116 more findings, all of them empty catch blocks, and new code had no way to write one. Allow empty catch blocks instead of freezing them. The rule has two findings left, both empty for-await loops in tests, and the ratchet baseline drops from 1,583 findings in 442 files to 1,412 in 368. Also reword a config comment that still called the lint restructure a future step. * build(nix): update the pnpm dependency hash for the oxlint upgrade The oxlint and oxlint-tsgolint upgrade changed pnpm-lock.yaml, so the fixed-output hash of pnpmDeps no longer matched and `nix build .#kimi-code` failed. Use the hash that the CI build reported. * fix(vis): call useState before the early return in ToolBubble ToolBubble returned null for non-tool messages before it called useState, so its hook order depended on the message role, which React does not allow. Call useState first. Tool messages start with the same state as before. * chore: drop noisy lint rules, add rules-of-hooks, freeze deprecated APIs Remove five rules from the ratchet and record why in .oxlintrc.json: - unicorn/require-post-message-target-origin: every call here is a Worker, MessagePort, or VS Code webview postMessage, which takes no target origin. - eslint/no-promise-executor-return: every finding was a one-line executor such as `new Promise((resolve) => setTimeout(resolve, ms))`. - eslint/no-unmodified-loop-condition: every finding was a compound condition whose other operand changes in the loop, or a flag that a callback sets while the loop awaits. - eslint/no-loop-func: every finding was a callback that runs within the same iteration or shares state with the loop on purpose. - typescript/prefer-nullish-coalescing: its fix turns || into ??, which changes the result for '' and 0, and many || here fall back on an empty string on purpose. Add three rules that have no findings today: eslint/radix, unicorn/no-abusive-eslint-disable, so every disable directive names the rules it disables, and react/rules-of-hooks for the two React apps. Freeze typescript/no-deprecated at its current count so new code does not add more uses of deprecated APIs, most of them zod 3 ones. In tests, freeze no-unused-vars and no-unsafe-optional-chaining instead of exempting tests from them. The ratchet now freezes 31 rules at 1,629 findings in 422 files. lint:fix only runs the main config, which no longer has the rules behind the old `||` to `??` and `sort()` to `toSorted()` examples. Replace them in AGENTS.md, CONTRIBUTING, and the wiring registry with one that applies. * chore: remove imports a merged test no longer uses The 2.6.3 release sync removed the code in idle-notification-repro.test.ts that used one of its imports, so the ratchet reported a new unused import. Drop createMockProvider and the TestAgentOptions type from the harness import, which still loads the same module, and lower the baseline for that file and for the two findings the release sync fixed. * chore: fail the ratchet on findings it cannot attribute to a rule oxlint reports the react hooks rules under the react-hooks prefix while the config names them react/..., so the ratchet dropped those findings without a word: a frozen react/exhaustive-deps would never have been counted or enforced. Map that prefix, and fail with a clear message on any finding that matches no rule in the ratchet config instead of skipping it. * chore: freeze type-safety rules for new code and add React correctness rules Freeze these rules in the ratchet without changing existing code: - all files: use-unknown-in-catch-callback-variable (108), import/no-named-as-default-member (27), oxc/no-accumulating-spread (8) and no-unnecessary-template-expression (5); - typed source only (packages/*/src, apps/*/src, apps/vis/*/src and apps/vscode/webview-ui/src; tests, JS scripts and bench excluded): no-unsafe-argument, no-unsafe-call, no-unsafe-member-access, no-unsafe-assignment and no-unsafe-return (317 together) and no-unnecessary-type-parameters (32); - the React apps: react/exhaustive-deps (7). Add 18 React correctness rules that have no findings to the React override. Move six rules from "off for now" to "off on purpose", with the reason found when sampling their findings: no-unsafe-type-assertion, no-unnecessary-condition, require-await, no-invalid-void-type, no-dynamic-delete and no-confusing-void-expression. The ratchet now freezes 42 rules at 2,129 findings in 538 files.
Requirement or Bug
没有关联 issue。仓库原本只对 agent-core-v2 和 kap-server 做禁注释检查(
scripts/check-no-comments.mjs),#4630 把它删掉以后,这两个包里又陆续冒出约 30 条注释;其他包从来没有约束,JS/TS 代码里累积了 1.6 万多条注释。这个 PR 把"JS/TS 代码不写注释"变成全仓的 lint 规则:确实需要保留注释的路径登记在 gitignore 语法的.commentignore里,其余现有注释一次性删掉。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路:新增一个独立的检查脚本
scripts/check-comments.mjs。它用 oxc-parser 解析每个 JS/TS 文件,拿到完整的注释列表;除了工具指令这类有语法作用的注释,其余一律报错。.commentignore里登记的路径不检查。脚本的--fix模式负责删除注释,但每个文件只有在删除前后语法树完全一致时才会写回,所以删注释不会改变程序。三个 commit 分别是:检查工具、pre-commit 钩子不再自动修复、机械删除现有注释。flowchart TD A[git ls-files: 已跟踪 + 未跟踪且未忽略的 JS/TS 文件] --> B{命中 .commentignore?} B -- 是 --> C[跳过; 全量运行时用于检查过期条目] B -- 否 --> D[oxc-parser 解析] D -- 解析失败 --> E[报错: 无法验证] D --> F{注释是工具指令?} F -- 是 --> G[放行] F -- 否 --> H{--fix?} H -- 否 --> I[报告 文件:行:列] H -- 是 --> J[删除注释并整理空行] --> K{删除前后 AST 一致?} K -- 是 --> L[写回] K -- 否 --> I检查脚本放在 oxlint 之外独立运行,原因是 oxlint 里的规则能被
/* oxlint-disable */之类的指令整文件压掉,而独立脚本不受这些指令影响。默认放行的注释:shebang、
/// <reference>、@ts-expect-error/@ts-ignore/@ts-nocheck/@ts-check、oxlint-/eslint-的 disable 和 enable(包括后面的说明文字)、prettier-ignore/oxfmt-ignore、@__PURE__/@__NO_SIDE_EFFECTS__、@vite-ignore、istanbul/c8/v8 ignore、@vitest-environment、@jsx*,以及 JS 文件里只有一个@type {…}或@satisfies {…}标签的 JSDoc。最后这一类在allowJs下是 TS 的类型断言,删掉会让apps/kimi-code的测试丢失类型收窄。.commentignore当前内容:apps/kimi-code/dist-web/(从 code-app 同步的构建产物)、packages/pi-tui/(上游代码,带 license 头)、packages/minidb/、packages/node-sdk/src/(公共 SDK 的 API 文档注释)。packages/agent-core-v2/,以及 refactor(agent-core-v2): port agent loop runtime core #4630 引入注释的 6 个文件。关键决策
/* oxlint-disable */整文件压掉(实测零报告),且 JS 插件仍是 alpha.commentignore按文件/目录登记--fix的安全性return和返回值之间时,直接删会改变自动分号插入的结果oxlint --fixpre-commit 钩子不再自动修复:lint-staged 原本会对每个暂存文件整体跑
oxlint --fix,并把修复结果直接写进 commit。这些修复并不安全:在 main 上,它会把packages/core/src/tool/runtime/tool-executor.ts的 catch 参数改名成error,和函数里已有的const error重名,导致提交失败;还会把packages/core/src/utils/wait.ts的!opts.match(event)改成!event.test(opts),这种不会报错,会被悄悄提交进去。删掉个别规则治标不治本,所以钩子改为只检查不修改,需要自动修复时手动跑pnpm lint:fix。第三个 commit 碰到 919 个文件,正是因此暴露了这个问题。阅读指南
scripts/check-comments.mjs:豁免规则、--fix的删除和空行整理、AST 比对、.commentignore匹配和过期条目检查。scripts/check-comments.test.mjs:各种边界情况的期望输出,可以对照着看。.commentignore、package.json(lint和 lint-staged)、.github/workflows/ci.yml、AGENTS.md:接线和规则说明。如何复核删除 commit
除两处外,删除改动都由
node scripts/check-comments.mjs --fix生成:.commentignore里"暂时保留"的 6 个文件只保留 refactor(agent-core-v2): port agent loop runtime core #4630 引入的注释,packages/node-sdk/src只保留 JSDoc,其余注释用同一套删除逻辑删掉;apps/kimi-code/scripts/native/native-deps.mjs删掉了一个@type断言,它引用的NativeDepDescriptortypedef 已被删除。逐文件比对 base 和 head 的语法树(去掉位置信息):919 个改动的源文件中,908 个完全一致;另外 11 个
.tsx的差异只是删掉了独占一行的{/* ... */}JSX 注释,它们在 JSX 文本规范化之后也一致。Behavior Changes and Affected Users
pnpm lint、pre-commit、CI 报错.commentignore.commentignore以外全部删除oxlint --fix,并把结果写进 commitpnpm lint:fixnode scripts/check-comments.mjs --fix契约文件:
apps/kimi-code/src/cli/和packages/acp-server/只删了注释,语法树一致,headless 输出解析方和 ACP 客户端的行为不变。packages/agent-core-v2/(包括 docs 下的 manifest)、packages/kap-server/test/__snapshots__/、packages/node-sdk/src/index.ts都没有改动。不写 changeset:CLI 的行为和输出都没有变化,钩子的调整只影响开发流程。
测试覆盖:
scripts/check-comments.test.mjs共 11 个用例,覆盖注释识别、各类豁免、删除后的格式、JSX、自动分号插入、拒绝会改变程序的删除、.commentignore匹配和过期条目、只检查指定文件、解析失败、--fix。已加到 CI 的 lint job。本地验证结果
pnpm run typecheck:通过。pnpm run lint:注释检查通过;oxlint 0 个错误,warning 2803 条(main 是 2805 条)。pnpm run test:17607 个通过,6 个失败。其中 5 个在本地干净的 main 上同样失败(agent-core-v2的test/tool/tool.test.ts3 个 30s 超时、kap-server的test/hosts.test.ts1 个、node-sdk的test/sdk-rpc-client-v2.test.ts1 个),另 1 个watch.test.ts单独运行可以通过,是时序不稳定。待办:新增了
oxc-parser和ignore两个开发依赖,flake.nix里的pnpmDepshash 需要按 nix-build CI 报出的新值更新。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.