From 4ace58a993fbb1cbbfc88dc3000c69dc183ef512 Mon Sep 17 00:00:00 2001 From: Jakob Heuser Date: Sun, 29 Nov 2026 14:16:12 -0800 Subject: [PATCH 1/3] feat(validate): let a rule acknowledge a trap notice by id Each ast-grep trap notice gets a stable id, and a rule listing one under metadata.taskless.acknowledge stops drawing it. validate/verify --json report silenced notices under an always-present acknowledged array. --- .changeset/acknowledge-sg-trap-notices.md | 5 + .../.openspec.yaml | 2 + .../acknowledge-sg-trap-notices/design.md | 67 +++++++ .../acknowledge-sg-trap-notices/proposal.md | 37 ++++ .../specs/cli-rule-validation/spec.md | 43 +++++ .../acknowledge-sg-trap-notices/tasks.md | 15 ++ packages/cli/src/agent/create-sg-rule.md | 40 ++++- packages/cli/src/agent/validate-rule.md | 11 +- packages/cli/src/rules/inspect.ts | 21 +++ packages/cli/src/rules/sg-traps.ts | 168 +++++++++++++++--- packages/cli/src/rules/verify.ts | 26 ++- packages/cli/src/schemas/rule-check.ts | 17 ++ packages/cli/test/sg-traps.test.ts | 156 +++++++++++++--- packages/cli/test/verify-status.test.ts | 1 + packages/cli/test/verify.test.ts | 83 +++++++++ 15 files changed, 640 insertions(+), 52 deletions(-) create mode 100644 .changeset/acknowledge-sg-trap-notices.md create mode 100644 openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml create mode 100644 openspec/changes/acknowledge-sg-trap-notices/design.md create mode 100644 openspec/changes/acknowledge-sg-trap-notices/proposal.md create mode 100644 openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md create mode 100644 openspec/changes/acknowledge-sg-trap-notices/tasks.md diff --git a/.changeset/acknowledge-sg-trap-notices.md b/.changeset/acknowledge-sg-trap-notices.md new file mode 100644 index 000000000..089f7b065 --- /dev/null +++ b/.changeset/acknowledge-sg-trap-notices.md @@ -0,0 +1,5 @@ +--- +"@taskless/cli": patch +--- + +`validate` trap notices can now be acknowledged per rule. Each ast-grep authoring-trap notice has a stable id (`ellipsis-before-comma`, `comma-before-ellipsis`, `sibling-without-stopby`, `descent-without-stopby`, `awaited-generic-callee`), and a rule that lists one under `metadata.taskless.acknowledge` stops drawing that notice while every other notice on it still prints. `validate --json` and `verify --json` report what was silenced in a new, always-present `acknowledged` array, and an unknown id draws a notice of its own. The `create-sg-rule` and `validate-rule` recipes document the ids and when to acknowledge one. diff --git a/openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml b/openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml new file mode 100644 index 000000000..992733754 --- /dev/null +++ b/openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-29 diff --git a/openspec/changes/acknowledge-sg-trap-notices/design.md b/openspec/changes/acknowledge-sg-trap-notices/design.md new file mode 100644 index 000000000..007f3d314 --- /dev/null +++ b/openspec/changes/acknowledge-sg-trap-notices/design.md @@ -0,0 +1,67 @@ +## Context + +`findSgTraps` walks the parsed rule object and returns notice strings. `verifyRule` (`src/rules/verify.ts`) appends them to the schema layer's `notices`, `inspect.ts` carries them to `RuleValidation` and `RuleVerification`, and `commands/verify.ts` prints or serializes them for both `validate` and `verify`. Nothing about a trap is stable except its text, and nothing in a rule can speak to a notice. + +`.taskless/rule-metadata/.yml` exists as a path, but `agent rule-meta` documents that no sidecar has ever been written and `rule meta` always exits with `RULE_META_UNAVAILABLE`. ast-grep's rule schema has a top-level `metadata` field (`"type": "object", "additionalProperties": true`, "Additional metadata for the rule"), which ast-grep parses and otherwise ignores. + +## Goals / Non-Goals + +**Goals:** + +- An author can silence one trap notice on one rule, in the rule, durably. +- Acknowledging one trap does not hide another on the same rule. +- An agent reading `--json` can tell a notice was acknowledged rather than never raised. + +**Non-Goals:** + +- Narrowing any trap's heuristic. +- Per-relation acknowledgement (see D2). +- Acknowledging anything other than the five ast-grep trap notices, such as the `language:` spelling or `files:` scope notices, which already have a fix in the rule. + +## Decisions + +### D1. The acknowledgement lives in the rule file, under `metadata.taskless.acknowledge` + +```yaml +id: prisma-updatemany-where +language: TypeScript +metadata: + taskless: + acknowledge: [awaited-generic-callee] +rule: ... +``` + +The issue asks for "whichever `validate` already reads". `validate` reads the rule file and parses it to an object; it reads no sidecar, and the sidecar has no writer. `metadata` is ast-grep's own extension point, so the rule stays valid to ast-grep, passes the vendored schema with no change, and travels with the rule when it is copied, moved or delivered. Namespacing under `taskless` leaves the rest of `metadata` to the author. + +Rejected: a YAML comment beside the relation. The `yaml` parser `validate` uses drops comments, so reading one means a second, comment-preserving parse of the file, and a comment is invisible to every tool that round-trips the rule (a formatter, a generator rewriting it). + +### D2. Per rule and per id, not per relation + +An acknowledgement silences every notice with that id on the rule. A rule with two callee relations, one of which genuinely could see `await fn()`, cannot acknowledge only the other. That case is rare, the remedy for it is to add the `await_expression` branch the notice asks for, and a per-path acknowledgement would key on the dotted path in the notice (`rule.any[1].has`), which shifts whenever a branch is added or reordered and would silently stop matching. The issue's acceptance criteria are per rule. + +### D3. One id per notice kind, five in all + +| id | notice | +| ------------------------ | ------------------------------------------------------------- | +| `ellipsis-before-comma` | `$$$` before a `,` (the leading form) | +| `comma-before-ellipsis` | `,` before `$$$` under smart strictness (the trailing form) | +| `sibling-without-stopby` | `follows` / `precedes` with no `stopBy` | +| `descent-without-stopby` | `has` / `inside` with neither `stopBy` nor `field` | +| `awaited-generic-callee` | callee `regex` under `field: function` with no awaited branch | + +The two `$$$` forms get separate ids because they have different remedies, and the existing design already reports them separately so that fixing one still leaves the other audible. The two `stopBy` traps are separate for the same reason: a sibling stopping at its neighbour and a descent looking one level are different decisions. + +Every trap is acknowledgeable. Three already have an in-rule spelling that says "I meant this" (`stopBy: neighbor`, `strictness: ast`), and the recipe says to prefer it; the acknowledgement is the only option for the leading `$$$` form and for the awaited callee. + +### D4. `--json` carries `acknowledged`, always present + +Each per-rule result gains `acknowledged: [{ id, notice }]`, empty rather than absent, following the same reasoning as `findings`: a key that is sometimes absent gets read as optional. `notice` is the text that would have printed, so an agent sees exactly what was silenced. Human output prints nothing for an acknowledged notice; the point is that it stops repeating. + +### D5. A malformed or unknown acknowledgement is a notice + +An id that names no trap (a typo, or `missing-stopby` from the issue's sketch) draws a notice listing the known ids. A `metadata.taskless.acknowledge` that is not a list of strings draws one too. Neither fails the rule: like every trap notice, it is something the author decides about. An acknowledgement of a known id that currently fires nothing is not reported; the decision is still recorded, and the trap may come back when the rule changes. + +## Risks / Trade-offs + +- [An author acknowledges a trap that does apply] → The acknowledgement is visible in the rule and in `--json`'s `acknowledged`, and the recipe tells authors to acknowledge only after checking the code base for the shape. +- [Notice ids become a contract] → They are named in the spec and the recipe; renaming one would un-acknowledge it on every rule, so ids are treated like constraint ids and not renamed. diff --git a/openspec/changes/acknowledge-sg-trap-notices/proposal.md b/openspec/changes/acknowledge-sg-trap-notices/proposal.md new file mode 100644 index 000000000..b9f7aa546 --- /dev/null +++ b/openspec/changes/acknowledge-sg-trap-notices/proposal.md @@ -0,0 +1,37 @@ +## Why + +`validate` reports the ast-grep authoring traps as notices (`findSgTraps`, `packages/cli/src/rules/sg-traps.ts`). They are structural: the awaited-generic callee notice fires for every TypeScript or Tsx rule that matches a callee by `regex` under `field: function` without an `await_expression` branch, whether or not the code base ever writes `await fn()`. Once an author has decided a trap does not apply, nothing in the rule can record that, so every `validate` run repeats the notice. Two CLI PMF agent survey runs (a 0.13.0 nightly and 0.13.7) reported it as noise, for a member callee (`prisma.x.updateMany`) and for logger calls that are never called with type arguments (issue #713). + +Narrowing the heuristic is not sound: `await api.get()` is a member callee too, and it is the case the recipe's method workaround exists for. The author is the only one who knows, so the fix is to let the author say so. + +## What Changes + +- Every trap notice gets a stable id: `ellipsis-before-comma`, `comma-before-ellipsis`, `sibling-without-stopby`, `descent-without-stopby`, `awaited-generic-callee`. +- An `sg` rule acknowledges a trap by listing its id under `metadata.taskless.acknowledge` in the rule file. `metadata` is ast-grep's own free-form field, already accepted by its schema and its parser, and the rule file is the one thing `validate` reads. +- `validate` and `verify` skip a notice the rule acknowledges and still print every other notice, including other traps on the same rule. +- Under `--json`, each rule result carries an `acknowledged` array (always present, empty when nothing was acknowledged) naming each silenced notice's id and text, so an agent can see why a notice went quiet. +- An acknowledgement naming an id that is not a trap id, or a `metadata.taskless.acknowledge` that is not a list of strings, draws a notice of its own. +- `create-sg-rule` documents the acknowledgement next to the traps. + +Not breaking. The bump is `patch`. + +## Delivery shape + +**Single PR.** The change is a few hundred lines across one module, its caller, the output schema, a recipe and their tests. Spec, implementation and the archive land together. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `cli-rule-validation`: adds a requirement that a rule can acknowledge a trap notice by id. + +## Impact + +- `packages/cli/src/rules/sg-traps.ts`: trap ids, acknowledgement reading and filtering. +- `packages/cli/src/rules/verify.ts`, `src/rules/inspect.ts`, `src/schemas/rule-check.ts`: carry `acknowledged` to the JSON output. +- `packages/cli/src/agent/create-sg-rule.md`: the Quirks section documents the ids and the acknowledgement. +- Tests in `packages/cli/test/sg-traps.test.ts` and a `validate` end-to-end case. diff --git a/openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md b/openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md new file mode 100644 index 000000000..4065ed770 --- /dev/null +++ b/openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md @@ -0,0 +1,43 @@ +## ADDED Requirements + +### Requirement: A rule can acknowledge a trap notice by id + +Each ast-grep trap notice SHALL carry a stable id: + +| id | Trap | +| ------------------------ | -------------------------------------------------------------------------------- | +| `ellipsis-before-comma` | a pattern places a `$$$` metavariable directly before a `,` | +| `comma-before-ellipsis` | a pattern places a `,` directly before a `$$$` metavariable | +| `sibling-without-stopby` | a `follows` or `precedes` relation declares no `stopBy` | +| `descent-without-stopby` | a `has` or `inside` relation declares neither `stopBy` nor `field` | +| `awaited-generic-callee` | a TypeScript or Tsx callee `regex` under `field: function` has no awaited branch | + +An `sg` rule SHALL be able to acknowledge a trap by listing its id in the rule file under `metadata.taskless.acknowledge`. `validate` and `verify` SHALL NOT print a notice whose id the rule acknowledges, and SHALL still print every other notice on the rule. An acknowledgement SHALL apply to the rule that declares it only. + +Under `--json`, every per-rule result SHALL carry an `acknowledged` array, empty rather than absent, with one entry per silenced notice giving its `id` and the `notice` text that would have been printed. + +An acknowledgement that names an id no trap carries, or a `metadata.taskless.acknowledge` that is not a list of strings, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. + +#### Scenario: An acknowledged awaited-generic notice is silent + +- **WHEN** a `TypeScript` rule matches `kind: call_expression` with `has: { field: function, regex: '\.updateMany$' }` and declares `metadata: { taskless: { acknowledge: [awaited-generic-callee] } }` +- **THEN** `validate` SHALL report the rule as valid with no awaited-generic notice +- **AND** under `--json` its `acknowledged` SHALL hold one entry with id `awaited-generic-callee` + +#### Scenario: The same rule without the acknowledgement still draws the notice + +- **WHEN** the rule above omits `metadata` +- **THEN** the rule SHALL carry the awaited-generic notice +- **AND** under `--json` its `acknowledged` SHALL be empty + +#### Scenario: Acknowledging one trap does not hide another + +- **WHEN** a rule acknowledges `awaited-generic-callee` and also declares a `follows` relation with no `stopBy` +- **THEN** the rule SHALL carry the `follows` notice +- **AND** SHALL NOT carry the awaited-generic notice + +#### Scenario: An unknown acknowledgement id draws a notice + +- **WHEN** a rule lists `missing-stopby` under `metadata.taskless.acknowledge` +- **THEN** the rule SHALL carry a notice naming `missing-stopby` and the known ids +- **AND** `validate` SHALL report the rule as valid diff --git a/openspec/changes/acknowledge-sg-trap-notices/tasks.md b/openspec/changes/acknowledge-sg-trap-notices/tasks.md new file mode 100644 index 000000000..e1724fafd --- /dev/null +++ b/openspec/changes/acknowledge-sg-trap-notices/tasks.md @@ -0,0 +1,15 @@ +## 1. Trap ids and acknowledgement + +- [x] 1.1 Give each trap in `sg-traps.ts` a stable id and have `findSgTraps` return the notices to print and the acknowledged ones, reading `metadata.taskless.acknowledge`; report an unknown id or a malformed list as a notice; verify with new cases in `test/sg-traps.test.ts`. +- [x] 1.2 Carry `acknowledged` through `verify.ts`, `inspect.ts` and the `rule-check` output schema, always present; verify with `pnpm typecheck`. +- [x] 1.3 Add a `validate --json` case for the issue's reproduction rule, with and without the acknowledgement, confirming ast-grep accepts the `metadata` block. + +## 2. Recipe and release note + +- [x] 2.1 Document the ids and `metadata.taskless.acknowledge` in `create-sg-rule`'s Quirks section and bump its topic version. +- [x] 2.2 Add one `patch` changeset. + +## 3. Checks and archive + +- [x] 3.1 Run `pnpm typecheck`, `pnpm lint` and the CLI test suite. +- [x] 3.2 Archive the change and confirm every prior `cli-rule-validation` scenario survives. diff --git a/packages/cli/src/agent/create-sg-rule.md b/packages/cli/src/agent/create-sg-rule.md index 4738b9d84..40b7c4bc3 100644 --- a/packages/cli/src/agent/create-sg-rule.md +++ b/packages/cli/src/agent/create-sg-rule.md @@ -1,4 +1,4 @@ -# Topic: create-sg-rule (CLI v%(CLI_VERSION)s / topic v18) +# Topic: create-sg-rule (CLI v%(CLI_VERSION)s / topic v19) %(ONE_COMMAND_PER_CALL)s @@ -261,6 +261,39 @@ sometimes what the author meant. Read it and decide. | `has` or `inside` without `stopBy` | silent | as a notice | | a `not` containing a bare metavariable | silent | no | +### Acknowledging a notice + +A notice repeats on every `validate` run until the rule changes. Once +you have checked that a trap cannot bite this rule, say so in the rule +file and the notice stops: + +```yaml +metadata: + taskless: + acknowledge: [awaited-generic-callee] +``` + +| notice id | trap | say it in the rule instead | +|--------------------------|---------------------------------------------------------|-------------------------------------| +| `ellipsis-before-comma` | `$$$` before a `,` (`foo($$$A, $B)`) | none | +| `comma-before-ellipsis` | `,` before `$$$` (`foo($A, $$$)`) | `strictness: ast` on the pattern | +| `sibling-without-stopby` | `follows` or `precedes` without `stopBy` | `stopBy: neighbor` | +| `descent-without-stopby` | `has` or `inside` without `stopBy` or `field` | `stopBy: neighbor` | +| `awaited-generic-callee` | a callee `regex` with no `await_expression` branch | none | + +Where the last column names a spelling, prefer it: it states what the +relation does, and the notice goes away on its own. Acknowledge only +the traps that have no such spelling, and only after checking the +codebase. For `awaited-generic-callee`, that means confirming this +callee is never called as `await f(...)`; a method such as +`await api.get()` is a member callee and is affected too. + +An acknowledgement covers every notice with that id on the rule and +nothing else, so a second trap on the same rule still reports. An id +that is not in the table draws a notice of its own. `validate --json` +lists what was silenced under each rule's `acknowledged`, so a quiet +rule can be told from one that never drew the notice. + ### Every `regex`, at any depth, needs a `kind` This one is a Taskless rule, wider than ast-grep's own check. ast-grep @@ -479,6 +512,11 @@ Add a `unary_expression` branch the same way if `!`, `void` or `typeof` matter. The wrapped match spans the `await` too, so a `fix:` on this rule rewrites it along with the call. +`validate` notices this shape whether or not the codebase ever awaits +the callee with type arguments. If it never does (a Prisma +`updateMany`, a logger), acknowledge `awaited-generic-callee`; see +"Acknowledging a notice" under [Quirks](#quirks). + ## Relational quirks diff --git a/packages/cli/src/agent/validate-rule.md b/packages/cli/src/agent/validate-rule.md index 693e3723c..1549f1c7a 100644 --- a/packages/cli/src/agent/validate-rule.md +++ b/packages/cli/src/agent/validate-rule.md @@ -1,4 +1,4 @@ -# Topic: validate-rule (CLI v%(CLI_VERSION)s / topic v12) +# Topic: validate-rule (CLI v%(CLI_VERSION)s / topic v13) %(ONE_COMMAND_PER_CALL)s @@ -100,6 +100,15 @@ Both commands answer in the same shape, one entry per rule: `%(RECIPE_FETCH)screate-sg-rule --section quirks`, `%(RECIPE_FETCH)screate-sg-rule --section pattern-quirks` and `%(RECIPE_FETCH)screate-sg-rule --section relational-quirks`. +- A trap notice repeats on every run until the rule changes. If you + have checked that a trap cannot bite the rule, list its id under + `metadata.taskless.acknowledge` in the rule file and it stops; the + ids are under "Acknowledging a notice" in the `quirks` section. Do + not acknowledge a trap to quiet a rule you have not checked. + `acknowledged` lists each notice a rule silenced this way, with the + id and the text it would have printed, so a quiet rule can be told + from one that never drew the notice. It is always present, empty + when nothing was acknowledged. A green Vale `verify` also assumes Vale read every fixture. A fixture whose front matter Vale cannot parse is excluded from the run and diff --git a/packages/cli/src/rules/inspect.ts b/packages/cli/src/rules/inspect.ts index 4eb7cc365..e10c6e4a0 100644 --- a/packages/cli/src/rules/inspect.ts +++ b/packages/cli/src/rules/inspect.ts @@ -31,6 +31,7 @@ import { valeTreeGrammarsViolation } from "./vale/grammar-tree"; import { validateValeRule } from "../schemas/vale-rule"; import { collectNotices } from "../util/notices"; import { verifyRule, type VerifyResult } from "./verify"; +import type { SgTrap } from "./sg-traps"; import { violate, type RuleViolation } from "./constraints"; import { describeRuleIdCollision, findRuleIdCollision } from "./id-uniqueness"; import { verifyValeRule } from "./vale/verify"; @@ -70,6 +71,13 @@ export interface RuleValidation { * joining two independent advisories with a space into one run-on line. */ notices: string[]; + /** + * Notices the rule acknowledged and so are not in `notices`, each with the + * id the rule named and the text that would have printed. Only an sg trap + * notice can be acknowledged (`metadata.taskless.acknowledge`); every other + * engine reports `[]`. Empty, never absent, for `findings`' reason. + */ + acknowledged: SgTrap[]; } /** @@ -146,6 +154,8 @@ export interface RuleVerification { * on a pass, since a pass is the case it exists for. */ notices: string[]; + /** As {@link RuleValidation.acknowledged}. */ + acknowledged: SgTrap[]; /** * Every finding this rule's fixtures produced, tagged with its bucket. * @@ -233,6 +243,7 @@ export function verification( ran: status === "passed" || status === "failed", ...(outcome.status === "refused" ? { refused: outcome.reason } : {}), notices: body.notices, + acknowledged: body.acknowledged, findings: body.findings, cases: body.cases, }; @@ -281,6 +292,7 @@ async function validateSgRule( errors, violations, notices: result.schema.notices, + acknowledged: result.schema.acknowledged, }, result, }; @@ -448,6 +460,7 @@ async function validateRuleComponents( errors, violations, notices: collectNotices(advisories), + acknowledged: [], }; } @@ -503,6 +516,7 @@ async function validateRuleComponents( errors, violations: [], notices: [], + acknowledged: [], }; } @@ -554,6 +568,7 @@ export async function verifyOneRule( ...validation.notices, await describeEmptySgScope(cwd, ruleId), ]), + acknowledged: validation.acknowledged, // The findings that decided the verdict, as the scan reported them: // rendered messages, and `file` naming the fixture in its case. findings: result.tests.findings, @@ -575,6 +590,7 @@ export async function verifyOneRule( errors: [result.outcome.message], violations: [], notices: [], + acknowledged: [], findings: [], cases: [], }); @@ -589,6 +605,7 @@ export async function verifyOneRule( errors, violations: [], notices: result.notices, + acknowledged: [], findings: result.findings, cases: result.cases, }); @@ -632,6 +649,7 @@ export async function verifyOneRule( findings: [], cases: [], notices: [], + acknowledged: [], } ); } @@ -658,6 +676,7 @@ export async function verifyOneRule( findings: [], cases: [], notices: [], + acknowledged: [], } ); } @@ -676,6 +695,7 @@ export async function verifyOneRule( errors: [error instanceof Error ? error.message : String(error)], violations: [], notices: [], + acknowledged: [], findings: [], cases: [], }); @@ -692,6 +712,7 @@ export async function verifyOneRule( errors: describeFixtureReport(ruleId, report), violations: [], notices: [], + acknowledged: [], findings: report.findings, cases: report.cases, }); diff --git a/packages/cli/src/rules/sg-traps.ts b/packages/cli/src/rules/sg-traps.ts index c0ced4710..51f3e34de 100644 --- a/packages/cli/src/rules/sg-traps.ts +++ b/packages/cli/src/rules/sg-traps.ts @@ -17,9 +17,14 @@ import { resolveAstGrepLanguage } from "./capabilities"; * * A trap ast-grep refuses outright (a keyword named as a `kind`, a Markdown * inline construct) is not here: `parseSgRuleAlone` rejects those. + * + * Every trap carries a stable id, and a rule that has decided a trap does not + * apply says so by listing that id under `metadata.taskless.acknowledge`. An + * acknowledged trap moves from `notices` to `acknowledged`, so it stops + * repeating on every run while `--json` still shows why it went quiet. */ -export function findSgTraps(rule: Record): string[] { - const notices: string[] = []; +export function findSgTraps(rule: Record): SgTrapReport { + const traps: SgTrap[] = []; const language = typeof rule.language === "string" ? resolveAstGrepLanguage(rule.language) @@ -30,7 +35,7 @@ export function findSgTraps(rule: Record): string[] { const container = rule[key]; if (container === undefined) continue; walk(container, key, (node, path) => { - notices.push( + traps.push( ...separatorTraps(node, path), ...siblingTraps(node, path), ...descentTraps(node, path), @@ -39,7 +44,105 @@ export function findSgTraps(rule: Record): string[] { }); } - return notices; + const { ids, notices } = readAcknowledgements(rule); + return { + notices: [ + ...traps.filter((trap) => !ids.has(trap.id)).map((trap) => trap.notice), + ...notices, + ], + acknowledged: traps.filter((trap) => ids.has(trap.id)), + }; +} + +/** + * The stable id of each trap: what a rule names to acknowledge one. + * + * One id per remedy rather than per kind of relation. The two `$$$` forms and + * the two `stopBy` forms are separate decisions, so acknowledging one must + * leave the other audible. Rules name these strings, so an id is a contract: + * renaming one would un-acknowledge it everywhere without a word. + */ +export const SG_TRAP_IDS = [ + "ellipsis-before-comma", + "comma-before-ellipsis", + "sibling-without-stopby", + "descent-without-stopby", + "awaited-generic-callee", +] as const; + +export type SgTrapId = (typeof SG_TRAP_IDS)[number]; + +/** One trap found in a rule: its id and the notice that describes it. */ +export interface SgTrap { + id: SgTrapId; + notice: string; +} + +/** + * What `validate` has to say about a rule's traps. + * + * `notices` is what prints: every trap the rule did not acknowledge, then any + * complaint about the acknowledgement itself. `acknowledged` is what does not. + */ +export interface SgTrapReport { + notices: string[]; + acknowledged: SgTrap[]; +} + +/** + * The trap ids a rule acknowledges under `metadata.taskless.acknowledge`. + * + * `metadata` is ast-grep's own free-form field, so the acknowledgement lives in + * the rule file `validate` already reads, passes ast-grep's schema untouched, + * and travels with the rule. Per rule and per id, never per relation: a + * relation's dotted path shifts whenever a branch is added, and an + * acknowledgement keyed on it would stop matching silently. + * + * A malformed list or an unknown id is a notice rather than an error, like the + * traps themselves: the rule still runs, and the author decides. + */ +function readAcknowledgements(rule: Record): { + ids: Set; + notices: string[]; +} { + const ids = new Set(); + const taskless = field(field(rule, "metadata"), "taskless"); + if (taskless === undefined || !("acknowledge" in taskless)) { + return { ids, notices: [] }; + } + const list = taskless.acknowledge; + const known = SG_TRAP_IDS.map((id) => `\`${id}\``).join(", "); + if (!Array.isArray(list) || list.some((item) => typeof item !== "string")) { + return { + ids, + notices: [ + `metadata.taskless.acknowledge must be a list of notice ids, so it acknowledges nothing. Known ids: ${known}.`, + ], + }; + } + const notices: string[] = []; + for (const id of list as string[]) { + if ((SG_TRAP_IDS as readonly string[]).includes(id)) { + ids.add(id); + } else { + notices.push( + `metadata.taskless.acknowledge names \`${id}\`, which is not a notice id, so it acknowledges nothing. Known ids: ${known}.` + ); + } + } + return { ids, notices }; +} + +/** A child object of `value`, or undefined when either is not one. */ +function field( + value: Record | undefined, + key: string +): Record | undefined { + const child = value?.[key]; + if (child === null || typeof child !== "object" || Array.isArray(child)) { + return undefined; + } + return child as Record; } type Visit = (node: Record, path: string) => void; @@ -76,7 +179,7 @@ const TRAILING_ELLIPSIS = /,\s*\$\$\$/; * so each is reported on its own: an author who fixes one must still hear * about the other. */ -function separatorTraps(node: Record, path: string): string[] { +function separatorTraps(node: Record, path: string): SgTrap[] { const pattern = node.pattern; let text: string | undefined; let astStrict = false; @@ -93,18 +196,24 @@ function separatorTraps(node: Record, path: string): string[] { } if (text === undefined) return []; - const notices: string[] = []; + const traps: SgTrap[] = []; if (LEADING_ELLIPSIS.test(text)) { - notices.push( - `${path}.pattern \`${text}\` puts \`$$$\` before a \`,\`, so it never matches a call where nothing precedes the last item: the comma is a node the target must also have. \`strictness: ast\` does not rescue this form. Match each arity as its own branch of an \`any\` instead.` + traps.push( + trap( + "ellipsis-before-comma", + `${path}.pattern \`${text}\` puts \`$$$\` before a \`,\`, so it never matches a call where nothing precedes the last item: the comma is a node the target must also have. \`strictness: ast\` does not rescue this form. Match each arity as its own branch of an \`any\` instead.` + ) ); } if (TRAILING_ELLIPSIS.test(text) && !astStrict) { - notices.push( - `${path}.pattern \`${text}\` puts a \`,\` before \`$$$\`, so under the default \`smart\` strictness it never matches zero trailing items (\`foo($A, $$$)\` misses \`foo(1)\`). Write it as a pattern object with \`context\`, \`selector\` and \`strictness: ast\`, which ignores the separator.` + traps.push( + trap( + "comma-before-ellipsis", + `${path}.pattern \`${text}\` puts a \`,\` before \`$$$\`, so under the default \`smart\` strictness it never matches zero trailing items (\`foo($A, $$$)\` misses \`foo(1)\`). Write it as a pattern object with \`context\`, \`selector\` and \`strictness: ast\`, which ignores the separator.` + ) ); } - return notices; + return traps; } /** @@ -112,19 +221,22 @@ function separatorTraps(node: Record, path: string): string[] { * immediate sibling, and separators are siblings too, so the previous element * of `[10, 10]` is the `,` rather than the `10`. */ -function siblingTraps(node: Record, path: string): string[] { - const notices: string[] = []; +function siblingTraps(node: Record, path: string): SgTrap[] { + const traps: SgTrap[] = []; for (const relation of ["follows", "precedes"] as const) { const value = node[relation]; if (value === null || typeof value !== "object" || Array.isArray(value)) { continue; } if ("stopBy" in value) continue; - notices.push( - `${path}.${relation} declares no \`stopBy\`, so it checks only the immediately adjacent sibling, and punctuation such as \`,\` counts as one: in \`[10, 10]\` the second \`10\` does not follow a number. Add \`stopBy: end\` inside \`${relation}\` unless stopping at the neighbour is what you mean.` + traps.push( + trap( + "sibling-without-stopby", + `${path}.${relation} declares no \`stopBy\`, so it checks only the immediately adjacent sibling, and punctuation such as \`,\` counts as one: in \`[10, 10]\` the second \`10\` does not follow a number. Add \`stopBy: end\` inside \`${relation}\` unless stopping at the neighbour is what you mean.` + ) ); } - return notices; + return traps; } /** How far `has` and `inside` look under the default `stopBy: neighbor`. */ @@ -150,8 +262,8 @@ const DESCENT = { * A relation that names a `field` is left alone: the field already pins one * particular parent-child link, which is exactly what the default looks at. */ -function descentTraps(node: Record, path: string): string[] { - const notices: string[] = []; +function descentTraps(node: Record, path: string): SgTrap[] { + const traps: SgTrap[] = []; for (const relation of ["has", "inside"] as const) { const value = node[relation]; if (value === null || typeof value !== "object" || Array.isArray(value)) { @@ -164,11 +276,14 @@ function descentTraps(node: Record, path: string): string[] { const negated = /(^|\.)not(\.|$)/.test(path) ? `, so the \`not\` around it excludes nothing nested deeper` : ""; - notices.push( - `${path}.${relation} declares no \`stopBy\`, so it checks ${reach}: ${missed}${negated}. Add \`stopBy: end\` inside \`${relation}\` to search the ${scope}, or \`stopBy: neighbor\` if stopping there is what you mean.` + traps.push( + trap( + "descent-without-stopby", + `${path}.${relation} declares no \`stopBy\`, so it checks ${reach}: ${missed}${negated}. Add \`stopBy: end\` inside \`${relation}\` to search the ${scope}, or \`stopBy: neighbor\` if stopping there is what you mean.` + ) ); } - return notices; + return traps; } /** @@ -180,7 +295,7 @@ function descentTraps(node: Record, path: string): string[] { * Any `await_expression` inside the relation counts as handling it, which is * how both of the recipe's workarounds (function and method) are written. */ -function calleeTraps(node: Record, path: string): string[] { +function calleeTraps(node: Record, path: string): SgTrap[] { if (node.field !== "function") return []; if ( !subtreeHas(node, (key, value) => key === "regex" && value !== undefined) @@ -196,10 +311,17 @@ function calleeTraps(node: Record, path: string): string[] { return []; } return [ - `${path} matches the callee by \`regex\` under \`field: function\`, which misses every awaited generic call: TypeScript parses \`await rpc()\` as a call of the \`await_expression\`, so the callee is never \`rpc\`. Add an \`any\` branch with \`kind: await_expression\` that matches the same callee inside it.`, + trap( + "awaited-generic-callee", + `${path} matches the callee by \`regex\` under \`field: function\`, which misses every awaited generic call: TypeScript parses \`await rpc()\` as a call of the \`await_expression\`, so the callee is never \`rpc\`. Add an \`any\` branch with \`kind: await_expression\` that matches the same callee inside it. If this callee is never awaited with type arguments, acknowledge the notice instead: list \`awaited-generic-callee\` under \`metadata.taskless.acknowledge\`.` + ), ]; } +function trap(id: SgTrapId, notice: string): SgTrap { + return { id, notice }; +} + function subtreeHas( value: unknown, test: (key: string, value: unknown) => boolean diff --git a/packages/cli/src/rules/verify.ts b/packages/cli/src/rules/verify.ts index 64c7b491c..2a42c4d3f 100644 --- a/packages/cli/src/rules/verify.ts +++ b/packages/cli/src/rules/verify.ts @@ -37,7 +37,7 @@ import { RULE_EXAMPLES } from "./verify-examples"; import { violate, type RuleViolation } from "./constraints"; import { isValidRuleId } from "./validate-id"; import { parseSgRuleAlone } from "./sg-parse"; -import { findSgTraps } from "./sg-traps"; +import { findSgTraps, type SgTrap } from "./sg-traps"; import { getCliPrefix } from "../util/package-manager"; /** @@ -83,6 +83,11 @@ export interface LayerResult { */ export interface SchemaLayerResult extends LayerResult { notices: string[]; + /** + * Trap notices the rule acknowledged under `metadata.taskless.acknowledge`, + * and so left out of `notices`. Empty, never absent. + */ + acknowledged: SgTrap[]; } export interface RequirementsResult extends LayerResult { @@ -506,7 +511,12 @@ export async function verifyRule( return { success: false, ruleId, - schema: { valid: false, errors: [errorMessage], notices: [] }, + schema: { + valid: false, + errors: [errorMessage], + notices: [], + acknowledged: [], + }, requirements: { valid: false, errors: [errorMessage] }, tests: { valid: false, @@ -542,6 +552,7 @@ export async function verifyRule( `Rule file not found: .taskless/${RULES_DIRECTORY}/sg/${ruleId}/${ruleId}.yml`, ], notices: [], + acknowledged: [], }, requirements: { valid: false, @@ -567,7 +578,12 @@ export async function verifyRule( return { success: false, ruleId, - schema: { valid: false, errors: [message], notices: [] }, + schema: { + valid: false, + errors: [message], + notices: [], + acknowledged: [], + }, requirements: { valid: false, errors: ["Cannot check requirements: invalid YAML"], @@ -603,11 +619,13 @@ export async function verifyRule( const refusal = await parseSgRuleAlone(cwd, ruleId); if (refusal !== undefined) schemaErrors.push(refusal); } + const traps = findSgTraps(ruleRecord); const schemaResult: SchemaLayerResult = { valid: schemaErrors.length === 0, errors: schemaErrors, violations: [...(parsed.violations ?? []), ...language.violations], - notices: [...language.notices, ...findSgTraps(ruleRecord)], + notices: [...language.notices, ...traps.notices], + acknowledged: traps.acknowledged, }; // Layer 2 diff --git a/packages/cli/src/schemas/rule-check.ts b/packages/cli/src/schemas/rule-check.ts index e7e551c9b..9154e0b2a 100644 --- a/packages/cli/src/schemas/rule-check.ts +++ b/packages/cli/src/schemas/rule-check.ts @@ -123,6 +123,23 @@ const ruleResultSchema = z.object({ .describe( "Things true about the rule that do not make it a failure, reported even on a pass. One notice per element, so a consumer can render each on its own; empty when there is nothing to say, never absent" ), + acknowledged: z + .array( + z.object({ + id: z + .string() + .describe( + "The notice's stable id, as the rule names it under `metadata.taskless.acknowledge`" + ), + notice: z + .string() + .describe("The notice text that would have been printed"), + }) + ) + .default([]) + .describe( + "Notices the rule acknowledged, and which are therefore NOT in `notices`. Only an ast-grep authoring-trap notice can be acknowledged, by listing its id under `metadata.taskless.acknowledge` in the rule file. ALWAYS PRESENT, empty when the rule acknowledged nothing or nothing it acknowledged fired. Read it to tell a notice the author silenced from one that was never raised" + ), findings: z .array(fixtureFindingSchema) .default([]) diff --git a/packages/cli/test/sg-traps.test.ts b/packages/cli/test/sg-traps.test.ts index 607a650ce..357f969b2 100644 --- a/packages/cli/test/sg-traps.test.ts +++ b/packages/cli/test/sg-traps.test.ts @@ -2,6 +2,11 @@ import { describe, expect, it } from "vitest"; import { findSgTraps } from "../src/rules/sg-traps"; +/** The notices `validate` would print for a rule. */ +function trapNotices(rule: Record): string[] { + return findSgTraps(rule).notices; +} + /** A TypeScript rule around the given `rule:` body. */ function typescript(rule: unknown, language = "TypeScript") { return { @@ -15,14 +20,14 @@ function typescript(rule: unknown, language = "TypeScript") { describe("$$$ beside a comma", () => { it("notices the trailing form in a plain pattern", () => { - const notices = findSgTraps(typescript({ pattern: "foo($A, $$$)" })); + const notices = trapNotices(typescript({ pattern: "foo($A, $$$)" })); expect(notices).toHaveLength(1); expect(notices[0]).toContain("foo($A, $$$)"); expect(notices[0]).toContain("strictness: ast"); }); it("is silent when the pattern object already declares strictness: ast", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ pattern: { context: "foo($A, $$$)", @@ -37,7 +42,7 @@ describe("$$$ beside a comma", () => { // The mirror case: the recipe says `strictness: ast` does not rescue it, so // declaring it must not silence the notice. it("notices the leading form even under strictness: ast", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ pattern: { context: "foo($$$REST, $LAST)", @@ -54,7 +59,7 @@ describe("$$$ beside a comma", () => { // first would leave an author who fixes the leading form with no word of the // trailing one. it("notices both forms when one pattern holds both", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ pattern: "foo($$$HEAD, $A, $$$TAIL)" }) ); expect(notices).toHaveLength(2); @@ -65,11 +70,11 @@ describe("$$$ beside a comma", () => { }); it("is silent for a standalone $$$", () => { - expect(findSgTraps(typescript({ pattern: "foo($$$)" }))).toEqual([]); + expect(trapNotices(typescript({ pattern: "foo($$$)" }))).toEqual([]); }); it("finds a pattern nested inside a relation", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "expression_statement", has: { pattern: "foo($A, $$$)", stopBy: "end" }, @@ -82,7 +87,7 @@ describe("$$$ beside a comma", () => { describe("a sibling relation without stopBy", () => { it("notices follows with no stopBy", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "number", follows: { kind: "number" } }) ); expect(notices).toHaveLength(1); @@ -91,7 +96,7 @@ describe("a sibling relation without stopBy", () => { }); it("notices precedes the same way", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "number", precedes: { kind: "number" } }) ); expect(notices).toHaveLength(1); @@ -100,7 +105,7 @@ describe("a sibling relation without stopBy", () => { it("is silent once stopBy is declared", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "number", follows: { kind: "number", stopBy: "end" }, @@ -112,7 +117,7 @@ describe("a sibling relation without stopBy", () => { describe("a descent relation without stopBy", () => { it("notices inside with no stopBy", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "call_expression", not: { inside: { kind: "try_statement" } }, @@ -126,7 +131,7 @@ describe("a descent relation without stopBy", () => { }); it("notices has with no stopBy", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "template_string", has: { kind: "template_substitution" }, @@ -140,7 +145,7 @@ describe("a descent relation without stopBy", () => { }); it("finds one nested under constraints and utils", () => { - const notices = findSgTraps({ + const notices = trapNotices({ ...typescript({ pattern: "$F()" }), constraints: { F: { kind: "identifier", inside: { kind: "program" } } }, utils: { u: { kind: "identifier", has: { kind: "identifier" } } }, @@ -152,7 +157,7 @@ describe("a descent relation without stopBy", () => { it("is silent once stopBy is declared, end or neighbor", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "call_expression", not: { inside: { kind: "try_statement", stopBy: "end" } }, @@ -166,7 +171,7 @@ describe("a descent relation without stopBy", () => { // the author has already said how far to look. it("is silent when the relation names a field", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "variable_declarator", has: { field: "name", kind: "identifier" }, @@ -174,7 +179,7 @@ describe("a descent relation without stopBy", () => { ) ).toEqual([]); expect( - findSgTraps( + trapNotices( typescript({ kind: "statement_block", inside: { field: "body", kind: "function_declaration" }, @@ -191,21 +196,21 @@ describe("an awaited generic call hides its callee", () => { }; it("notices a callee regex under TypeScript", () => { - const notices = findSgTraps(typescript(plain)); + const notices = trapNotices(typescript(plain)); expect(notices).toHaveLength(1); expect(notices[0]).toContain("await_expression"); }); it("notices it under Tsx", () => { - expect(findSgTraps(typescript(plain, "Tsx"))).toHaveLength(1); + expect(trapNotices(typescript(plain, "Tsx"))).toHaveLength(1); }); it("is silent under any other language", () => { - expect(findSgTraps(typescript(plain, "JavaScript"))).toEqual([]); + expect(trapNotices(typescript(plain, "JavaScript"))).toEqual([]); }); it("notices a method callee", () => { - const notices = findSgTraps( + const notices = trapNotices( typescript({ kind: "call_expression", has: { @@ -226,7 +231,7 @@ describe("an awaited generic call hides its callee", () => { // flagged the recipe's own fix would teach authors to ignore it. it("is silent for the recipe's function workaround", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "call_expression", has: { @@ -246,7 +251,7 @@ describe("an awaited generic call hides its callee", () => { it("is silent for the recipe's method workaround", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "call_expression", has: { @@ -281,7 +286,7 @@ describe("an awaited generic call hides its callee", () => { it("is silent when the callee is matched without a regex", () => { expect( - findSgTraps( + trapNotices( typescript({ kind: "call_expression", has: { field: "function", pattern: "rpc" }, @@ -293,6 +298,111 @@ describe("an awaited generic call hides its callee", () => { describe("a rule with none of the traps", () => { it("carries no notices", () => { - expect(findSgTraps(typescript({ pattern: "eval($ARG)" }))).toEqual([]); + expect(trapNotices(typescript({ pattern: "eval($ARG)" }))).toEqual([]); + }); +}); + +/** A TypeScript rule that acknowledges `acknowledge` in its metadata. */ +function acknowledging(rule: unknown, acknowledge: unknown) { + return { + ...typescript(rule), + metadata: { taskless: { acknowledge } }, + }; +} + +describe("acknowledging a trap", () => { + /** The issue's reproduction: a member callee never called with type arguments. */ + const updateMany = { + kind: "call_expression", + has: { + field: "function", + kind: "member_expression", + regex: String.raw`\.updateMany$`, + }, + }; + + it("still notices the callee without an acknowledgement", () => { + const report = findSgTraps(typescript(updateMany)); + expect(report.notices).toHaveLength(1); + expect(report.notices[0]).toContain("await_expression"); + expect(report.notices[0]).toContain("metadata.taskless.acknowledge"); + expect(report.acknowledged).toEqual([]); + }); + + it("moves an acknowledged notice out of the printed list", () => { + const report = findSgTraps( + acknowledging(updateMany, ["awaited-generic-callee"]) + ); + expect(report.notices).toEqual([]); + expect(report.acknowledged).toHaveLength(1); + expect(report.acknowledged[0]?.id).toBe("awaited-generic-callee"); + expect(report.acknowledged[0]?.notice).toContain("await_expression"); + }); + + it("leaves another trap on the same rule audible", () => { + const report = findSgTraps( + acknowledging({ ...updateMany, follows: { kind: "number" } }, [ + "awaited-generic-callee", + ]) + ); + expect(report.notices).toHaveLength(1); + expect(report.notices[0]).toContain("follows"); + expect(report.acknowledged.map((trap) => trap.id)).toEqual([ + "awaited-generic-callee", + ]); + }); + + it("keeps the two $$$ forms apart", () => { + const report = findSgTraps( + acknowledging({ pattern: "foo($$$HEAD, $A, $$$TAIL)" }, [ + "comma-before-ellipsis", + ]) + ); + expect(report.notices).toHaveLength(1); + expect(report.notices[0]).toContain("before a `,`"); + expect(report.acknowledged.map((trap) => trap.id)).toEqual([ + "comma-before-ellipsis", + ]); + }); + + it("keeps the sibling and descent stopBy traps apart", () => { + const report = findSgTraps( + acknowledging( + { + kind: "number", + follows: { kind: "number" }, + inside: { kind: "array" }, + }, + ["descent-without-stopby"] + ) + ); + expect(report.notices).toHaveLength(1); + expect(report.notices[0]).toContain("follows"); + }); + + it("notices an id no trap carries, naming the known ids", () => { + const report = findSgTraps(acknowledging(updateMany, ["missing-stopby"])); + expect(report.acknowledged).toEqual([]); + expect(report.notices).toHaveLength(2); + expect(report.notices[1]).toContain("`missing-stopby`"); + expect(report.notices[1]).toContain("`awaited-generic-callee`"); + }); + + it("notices an acknowledgement that is not a list of strings", () => { + const report = findSgTraps( + acknowledging(updateMany, "awaited-generic-callee") + ); + expect(report.acknowledged).toEqual([]); + expect(report.notices).toHaveLength(2); + expect(report.notices[1]).toContain("must be a list"); + }); + + it("ignores metadata that says nothing about Taskless", () => { + const report = findSgTraps({ + ...typescript(updateMany), + metadata: { owner: "payments" }, + }); + expect(report.notices).toHaveLength(1); + expect(report.acknowledged).toEqual([]); }); }); diff --git a/packages/cli/test/verify-status.test.ts b/packages/cli/test/verify-status.test.ts index 05122d487..792e7e5cc 100644 --- a/packages/cli/test/verify-status.test.ts +++ b/packages/cli/test/verify-status.test.ts @@ -9,6 +9,7 @@ const BODY = { errors: [], violations: [], notices: [], + acknowledged: [], findings: [], cases: [], }; diff --git a/packages/cli/test/verify.test.ts b/packages/cli/test/verify.test.ts index 0bdf9427e..f562ba21b 100644 --- a/packages/cli/test/verify.test.ts +++ b/packages/cli/test/verify.test.ts @@ -1324,3 +1324,86 @@ export default async function (root, matches) { }); }); }); + +describe("validate honors a rule's trap acknowledgement (#713)", () => { + let cwd: string; + + beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), "tskl-acknowledge-")); + await runVerifyMixedRunCli(["init", "-d", cwd]); + }); + + afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + /** The issue's reproduction: a member callee never awaited with type arguments. */ + const UPDATE_MANY = { + id: "prisma-updatemany-where", + language: "TypeScript", + severity: "error", + message: "updateMany needs a where", + rule: { + kind: "call_expression", + has: { + field: "function", + kind: "member_expression", + regex: String.raw`\.updateMany$`, + }, + }, + }; + + const CASES = { + pass: ["db.user.update({ where: {} });"], + fail: ["db.user.updateMany({ data: {} });"], + }; + + interface AcknowledgeReport { + ok: boolean; + rules: { + ok: boolean; + errors: string[]; + notices: string[]; + acknowledged: { id: string; notice: string }[]; + }[]; + } + + async function validateJson(): Promise { + const { stdout } = await runVerifyMixedRunCli([ + "validate", + ".taskless/rules/sg/prisma-updatemany-where", + "-d", + cwd, + "--json", + ]); + return JSON.parse(stdout) as AcknowledgeReport; + } + + it("prints the awaited-generic notice without an acknowledgement", async () => { + await sgProject(cwd, UPDATE_MANY, CASES); + const report = await validateJson(); + expect(report.rules[0]?.ok).toBe(true); + expect(report.rules[0]?.notices.join("\n")).toContain("await_expression"); + expect(report.rules[0]?.acknowledged).toEqual([]); + }); + + it("silences it, and reports it as acknowledged, once the rule says so", async () => { + // Also proves ast-grep itself accepts the `metadata` block: the engine + // parse runs on every rule the schema passes, and would fail it here. + await sgProject( + cwd, + { + ...UPDATE_MANY, + metadata: { taskless: { acknowledge: ["awaited-generic-callee"] } }, + }, + CASES + ); + const report = await validateJson(); + expect(report.rules[0]?.errors).toEqual([]); + expect(report.rules[0]?.ok).toBe(true); + expect(report.rules[0]?.notices).toEqual([]); + expect(report.rules[0]?.acknowledged.map((entry) => entry.id)).toEqual([ + "awaited-generic-callee", + ]); + }); +}); From 1180768877cdf1c43daacc4a501265e722411f14 Mon Sep 17 00:00:00 2001 From: Jakob Heuser Date: Sun, 29 Nov 2026 14:16:37 -0800 Subject: [PATCH 2/3] chore(openspec): archive acknowledge-sg-trap-notices --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/cli-rule-validation/spec.md | 0 .../tasks.md | 0 openspec/specs/cli-rule-validation/spec.md | 42 +++++++++++++++++++ 6 files changed, 42 insertions(+) rename openspec/changes/{acknowledge-sg-trap-notices => archive/2026-11-29-acknowledge-sg-trap-notices}/.openspec.yaml (100%) rename openspec/changes/{acknowledge-sg-trap-notices => archive/2026-11-29-acknowledge-sg-trap-notices}/design.md (100%) rename openspec/changes/{acknowledge-sg-trap-notices => archive/2026-11-29-acknowledge-sg-trap-notices}/proposal.md (100%) rename openspec/changes/{acknowledge-sg-trap-notices => archive/2026-11-29-acknowledge-sg-trap-notices}/specs/cli-rule-validation/spec.md (100%) rename openspec/changes/{acknowledge-sg-trap-notices => archive/2026-11-29-acknowledge-sg-trap-notices}/tasks.md (100%) diff --git a/openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/.openspec.yaml similarity index 100% rename from openspec/changes/acknowledge-sg-trap-notices/.openspec.yaml rename to openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/.openspec.yaml diff --git a/openspec/changes/acknowledge-sg-trap-notices/design.md b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/design.md similarity index 100% rename from openspec/changes/acknowledge-sg-trap-notices/design.md rename to openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/design.md diff --git a/openspec/changes/acknowledge-sg-trap-notices/proposal.md b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/proposal.md similarity index 100% rename from openspec/changes/acknowledge-sg-trap-notices/proposal.md rename to openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/proposal.md diff --git a/openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md similarity index 100% rename from openspec/changes/acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md rename to openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md diff --git a/openspec/changes/acknowledge-sg-trap-notices/tasks.md b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/tasks.md similarity index 100% rename from openspec/changes/acknowledge-sg-trap-notices/tasks.md rename to openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/tasks.md diff --git a/openspec/specs/cli-rule-validation/spec.md b/openspec/specs/cli-rule-validation/spec.md index 680785849..321405ad3 100644 --- a/openspec/specs/cli-rule-validation/spec.md +++ b/openspec/specs/cli-rule-validation/spec.md @@ -572,3 +572,45 @@ Under `--json`, each rule result from `verify` SHALL carry a `status` naming its - **WHEN** `validate --json` reports a rule - **THEN** the rule's result SHALL NOT carry `status` + +### Requirement: A rule can acknowledge a trap notice by id + +Each ast-grep trap notice SHALL carry a stable id: + +| id | Trap | +| ------------------------ | -------------------------------------------------------------------------------- | +| `ellipsis-before-comma` | a pattern places a `$$$` metavariable directly before a `,` | +| `comma-before-ellipsis` | a pattern places a `,` directly before a `$$$` metavariable | +| `sibling-without-stopby` | a `follows` or `precedes` relation declares no `stopBy` | +| `descent-without-stopby` | a `has` or `inside` relation declares neither `stopBy` nor `field` | +| `awaited-generic-callee` | a TypeScript or Tsx callee `regex` under `field: function` has no awaited branch | + +An `sg` rule SHALL be able to acknowledge a trap by listing its id in the rule file under `metadata.taskless.acknowledge`. `validate` and `verify` SHALL NOT print a notice whose id the rule acknowledges, and SHALL still print every other notice on the rule. An acknowledgement SHALL apply to the rule that declares it only. + +Under `--json`, every per-rule result SHALL carry an `acknowledged` array, empty rather than absent, with one entry per silenced notice giving its `id` and the `notice` text that would have been printed. + +An acknowledgement that names an id no trap carries, or a `metadata.taskless.acknowledge` that is not a list of strings, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. + +#### Scenario: An acknowledged awaited-generic notice is silent + +- **WHEN** a `TypeScript` rule matches `kind: call_expression` with `has: { field: function, regex: '\.updateMany$' }` and declares `metadata: { taskless: { acknowledge: [awaited-generic-callee] } }` +- **THEN** `validate` SHALL report the rule as valid with no awaited-generic notice +- **AND** under `--json` its `acknowledged` SHALL hold one entry with id `awaited-generic-callee` + +#### Scenario: The same rule without the acknowledgement still draws the notice + +- **WHEN** the rule above omits `metadata` +- **THEN** the rule SHALL carry the awaited-generic notice +- **AND** under `--json` its `acknowledged` SHALL be empty + +#### Scenario: Acknowledging one trap does not hide another + +- **WHEN** a rule acknowledges `awaited-generic-callee` and also declares a `follows` relation with no `stopBy` +- **THEN** the rule SHALL carry the `follows` notice +- **AND** SHALL NOT carry the awaited-generic notice + +#### Scenario: An unknown acknowledgement id draws a notice + +- **WHEN** a rule lists `missing-stopby` under `metadata.taskless.acknowledge` +- **THEN** the rule SHALL carry a notice naming `missing-stopby` and the known ids +- **AND** `validate` SHALL report the rule as valid From feb7a289dbb71d3676ce3b1ac8b76f31b54faa17 Mon Sep 17 00:00:00 2001 From: Jakob Heuser Date: Sun, 29 Nov 2026 14:21:07 -0800 Subject: [PATCH 3/3] fix(validate): notice a metadata.taskless block with no acknowledge list --- .../specs/cli-rule-validation/spec.md | 2 +- openspec/specs/cli-rule-validation/spec.md | 2 +- packages/cli/src/rules/sg-traps.ts | 20 +++++++++++++++---- packages/cli/test/sg-traps.test.ts | 14 +++++++++++++ 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md index 4065ed770..90e3d694e 100644 --- a/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md +++ b/openspec/changes/archive/2026-11-29-acknowledge-sg-trap-notices/specs/cli-rule-validation/spec.md @@ -16,7 +16,7 @@ An `sg` rule SHALL be able to acknowledge a trap by listing its id in the rule f Under `--json`, every per-rule result SHALL carry an `acknowledged` array, empty rather than absent, with one entry per silenced notice giving its `id` and the `notice` text that would have been printed. -An acknowledgement that names an id no trap carries, or a `metadata.taskless.acknowledge` that is not a list of strings, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. +An acknowledgement that names an id no trap carries, a `metadata.taskless.acknowledge` that is not a list of strings, or a `metadata.taskless` that holds no `acknowledge` list, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. #### Scenario: An acknowledged awaited-generic notice is silent diff --git a/openspec/specs/cli-rule-validation/spec.md b/openspec/specs/cli-rule-validation/spec.md index 321405ad3..5460a018b 100644 --- a/openspec/specs/cli-rule-validation/spec.md +++ b/openspec/specs/cli-rule-validation/spec.md @@ -589,7 +589,7 @@ An `sg` rule SHALL be able to acknowledge a trap by listing its id in the rule f Under `--json`, every per-rule result SHALL carry an `acknowledged` array, empty rather than absent, with one entry per silenced notice giving its `id` and the `notice` text that would have been printed. -An acknowledgement that names an id no trap carries, or a `metadata.taskless.acknowledge` that is not a list of strings, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. +An acknowledgement that names an id no trap carries, a `metadata.taskless.acknowledge` that is not a list of strings, or a `metadata.taskless` that holds no `acknowledge` list, SHALL draw a notice naming the known ids. It SHALL NOT fail the rule. #### Scenario: An acknowledged awaited-generic notice is silent diff --git a/packages/cli/src/rules/sg-traps.ts b/packages/cli/src/rules/sg-traps.ts index 51f3e34de..f706c2e92 100644 --- a/packages/cli/src/rules/sg-traps.ts +++ b/packages/cli/src/rules/sg-traps.ts @@ -99,19 +99,31 @@ export interface SgTrapReport { * acknowledgement keyed on it would stop matching silently. * * A malformed list or an unknown id is a notice rather than an error, like the - * traps themselves: the rule still runs, and the author decides. + * traps themselves: the rule still runs, and the author decides. So is a + * `taskless` block that holds no `acknowledge` list, such as the id placed one + * level too high: an acknowledgement that does nothing must say so, or the + * author reads the repeating notice as a bug rather than a typo. */ function readAcknowledgements(rule: Record): { ids: Set; notices: string[]; } { const ids = new Set(); - const taskless = field(field(rule, "metadata"), "taskless"); - if (taskless === undefined || !("acknowledge" in taskless)) { + const known = SG_TRAP_IDS.map((id) => `\`${id}\``).join(", "); + const metadata = field(rule, "metadata"); + if (metadata === undefined || !("taskless" in metadata)) { return { ids, notices: [] }; } + const taskless = field(metadata, "taskless"); + if (taskless === undefined || !("acknowledge" in taskless)) { + return { + ids, + notices: [ + `metadata.taskless holds no \`acknowledge\` list, so it acknowledges nothing. Write \`metadata: { taskless: { acknowledge: [] } }\`. Known ids: ${known}.`, + ], + }; + } const list = taskless.acknowledge; - const known = SG_TRAP_IDS.map((id) => `\`${id}\``).join(", "); if (!Array.isArray(list) || list.some((item) => typeof item !== "string")) { return { ids, diff --git a/packages/cli/test/sg-traps.test.ts b/packages/cli/test/sg-traps.test.ts index 357f969b2..737bd2b27 100644 --- a/packages/cli/test/sg-traps.test.ts +++ b/packages/cli/test/sg-traps.test.ts @@ -397,6 +397,20 @@ describe("acknowledging a trap", () => { expect(report.notices[1]).toContain("must be a list"); }); + it.each([ + ["a list", ["awaited-generic-callee"]], + ["a string", "awaited-generic-callee"], + ["an object with no acknowledge", { acknowledges: ["x"] }], + ])("notices a taskless block that is %s", (_label, taskless) => { + const report = findSgTraps({ + ...typescript(updateMany), + metadata: { taskless }, + }); + expect(report.acknowledged).toEqual([]); + expect(report.notices).toHaveLength(2); + expect(report.notices[1]).toContain("holds no `acknowledge` list"); + }); + it("ignores metadata that says nothing about Taskless", () => { const report = findSgTraps({ ...typescript(updateMany),