Skip to content

AP-1530 Organize and verify SonarJS agent documentation - #8518

Open
erwan-leforestier-sonarsource wants to merge 4 commits into
ap/AP-1516from
ap/AP-1530
Open

erwan-leforestier-sonarsource wants to merge 4 commits into
ap/AP-1516from
ap/AP-1530

Conversation

@erwan-leforestier-sonarsource

@erwan-leforestier-sonarsource erwan-leforestier-sonarsource commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor
  • Use a short root guide with scoped instructions and one canonical copy of each skill.
  • Organize repository knowledge into indexed system guides and decision records.
  • Check documentation, protect the README Marketing block, and verify changed generated files in CI.

Part of AP-1486. Implements AP-1530.


Summary by Gitar

  • Agent skills consolidation:
    • Moved canonical skill instructions to .agents/skills/ with thin .claude/skills/ adapters that point to them
    • Renamed the peach-check helpers and updated the Peach origin check to require an approved origin hash
  • Documentation checks:
    • Added tools/docs/check-docs.mjs with tests and a check:docs mise task, run in a new docs CI workflow
    • Added tools/check-marketing-block.sh to guard the README Marketing block from changes

This will update automatically on new commits.

@erwan-leforestier-sonarsource
erwan-leforestier-sonarsource marked this pull request as ready for review November 30, 2026 15:28
@hashicorp-vault-sonar-prod

hashicorp-vault-sonar-prod Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

AP-1530

Comment on lines 1 to +6
---
name: new-rule
description: Implement a new SonarJS rule from scratch. Use when creating a new rule, scaffolding rule files, or understanding the full rule implementation workflow.
disable-model-invocation: true
description: 'Implement a new SonarJS rule from scratch. Use when creating a new rule, scaffolding rule files, or understanding the full rule implementation workflow.'
---

## Overview

New rules follow the pattern: RSPEC description → scaffold → implement → test → ruling.

## Step 1: Scaffold the Rule

```bash
npm run new-rule
```

This interactive script generates in `packages/analysis/src/jsts/rules/SXXXX/`:

- `index.ts` — rule export
- `rule.ts` — ESLint rule implementation (skeleton)
- `cb.fixture.js` — empty comment-based test fixture
- `cb.test.js` — test launcher

It also auto-generates (not tracked by git):

- Java check class `SXXXX.java`
- Updates `rules/rules.ts` and `rules/plugin-rules.ts`
- Updates `AllRules.java`

## Step 2: Configure the Java Check Class

In the generated Java class, verify:

- `@JavaScriptRule` and/or `@TypeScriptRule` annotations match target languages
- If rule has options, override `configurations()` method (see `/rule-options` skill)
- If rule targets test files, extend `TestFileCheck` instead of `MainFileCheck`

## Step 3: Implement the Rule

### File Structure

| File | Purpose |
| ------------------- | ---------------------------------------------------------------------------- |
| `rule.ts` | ESLint rule implementation |
| `meta.ts` | Manual metadata: `implementation`, `eslintId`, `schema`, re-exports `fields` |
| `config.ts` | Option definitions with `fields` array (if rule has options) |
| `generated-meta.ts` | Auto-generated from RSPEC — do not edit |

### Rule Template

```typescript
import { generateMeta } from '../helpers/index.js';
import { meta } from './meta.js';

const messages = {
errorKey: 'Error message to display',
};

export const rule: Rule.RuleModule = {
meta: generateMeta(meta, { messages }),
create(context: Rule.RuleContext) {
return {
Identifier(node: estree.Identifier) {
if (/* violation detected */) {
context.report({ messageId: 'errorKey', node });
}
},
};
},
};
```

### Be Conservative

**Never report when uncertain.** False positives are worse than missed detections.

```typescript
const services = context.sourceCode.parserServices;
if (!isRequiredParserServices(services)) {
return; // No type info — don't report
}
```

When in doubt: skip.

## Step 4: Check Shared Helpers

**Before writing any utility code**, check `packages/analysis/src/jsts/rules/helpers/`:

| File | Contains |
| ------------------------------- | ------------------------------------------------------------------------- |
| `ast.ts` | `isFunctionNode`, `isIdentifier`, `hasTypePredicateReturn`, AST traversal |
| `module.ts` | `isESModule`, `getImportDeclarations`, `getFullyQualifiedName` |
| `package-jsons/dependencies.ts` | `getDependencies`, `getReactVersion` |
| `index.ts` | Re-exports all helpers — check here first |

If a new utility would benefit multiple rules, add it to the appropriate helper file.

## Step 5: Generate Metadata

After setting up `meta.ts` and optionally `config.ts`:

```bash
npm run generate-meta
```

This creates/updates `generated-meta.ts` with `defaultOptions`, `sonarKey`, `scope`, `languages`.

## Step 6: Write Tests

See `/test-rule` skill for full testing documentation.

Quick start — write `cb.fixture.js`:

```javascript
someCleanCode(); // no issue raised

someFaultyCode(); // Noncompliant {{message}}
// ^^^^^^^^^^
```

Run:

```bash
npx tsx --test packages/analysis/src/jsts/rules/S1234/**/*.test.ts
```

## Step 7: Run Ruling

See `/ruling` skill. Required before merging new or modified rules.

## Rule Implementation Patterns

### Wrapping an ESLint Rule (`decorated`)

```typescript
// meta.ts
export const implementation = 'decorated';
export const eslintId = 'no-magic-numbers';
export const externalRules = [
{ externalPlugin: 'typescript-eslint', externalRule: 'no-magic-numbers' },
];
export * from './config.js';
```

### Original Rule

```typescript
// meta.ts
export const implementation = 'original';
export const eslintId = 'function-name';
export * from './config.js';
import type { JSONSchema4 } from '@typescript-eslint/utils/json-schema';
export const schema = {
type: 'array',
items: [{ type: 'object', properties: { format: { type: 'string' } } }],
} as const satisfies JSONSchema4;
```

### RSPEC Tags

When creating the RSPEC PR:

- Tag `type-dependent` if the rule uses TypeScript type information
- Add `dependencies` field if rule requires a specific import (e.g., `'react'`, `'jest'`)
- Add `compatibleLanguages: ['js', 'ts']` as appropriate

## References

- Security Hotspot: [PR #3148](https://github.com/SonarSource/SonarJS/pull/3148)
- Rule with quickfix: [PR #3141](https://github.com/SonarSource/SonarJS/pull/3141)
- Wrapping ESLint rule: [PR #3134](https://github.com/SonarSource/SonarJS/pull/3134)
Read and follow `.agents/skills/new-rule/SKILL.md`, relative to the repository root.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bug: Claude skill adapters drop disable-model-invocation and allowed-tools

Claude Code reads frontmatter only from .claude/skills/<name>/SKILL.md. The keys in the .agents/skills copy are just text the agent reads after the skill is already running. The canonical new-rule and ruling skills are 172 and 80 lines, the same as the removed .claude originals, and both declare disable-model-invocation: true. The new .claude adapters for them keep only name and description. As a result, Claude can now start these skills on its own. That matters most for ruling, whose own text warns that running it removes the root node_modules.

The peach-check adapter has the same problem: allowed-tools and argument-hint exist only in .agents/skills/peach-check/SKILL.md. Claude Code therefore no longer pre-approves the gh/jq/node commands or shows the [run-id] hint. checkSkill in tools/docs/check-docs.mjs only checks name/description, so CI does not catch this. Copy the Claude-specific frontmatter keys into each adapter, and consider having the checker require adapter frontmatter to match the canonical skill.

Keep Claude-interpreted keys in the adapter (ruling shown; same for new-rule; add allowed-tools/argument-hint to peach-check).:

---
name: ruling
description: 'Run ruling integration tests and update expected results for SonarJS rules. Use when running ruling tests or syncing expected ruling output.'
disable-model-invocation: true
---

Read and follow `.agents/skills/ruling/SKILL.md`, relative to the repository root.
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎

@gitar-bot

gitar-bot Bot commented Nov 30, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 🔴 High risk 3 closed / 3 findings

The Peach helper changes the API-token egress boundary by validating an approved origin hash; a mistake could send credentials to an unapproved host.

Organizes SonarJS agent documentation with a short root guide, canonical skill copies in .agents/skills/ with thin .claude/skills/ adapters, indexed system guides, and a new docs CI workflow running tools/docs/check-docs.mjs. Resolved the dropped disable-model-invocation and allowed-tools in Claude skill adapters, the ERROR state from a missing PEACH_BASE_URL, and the PEACH_KEY leak to arbitrary HTTPS origins. No open issues found.

✅ 3 closed
✅ Bug: Claude skill adapters drop disable-model-invocation and allowed-tools

📄 .claude/skills/ruling/SKILL.md:4 📄 .claude/skills/new-rule/SKILL.md:4 📄 .claude/skills/peach-check/SKILL.md:4-5
Claude Code reads frontmatter only from .claude/skills/<name>/SKILL.md. The keys in the .agents/skills copy are just text the agent reads after the skill is already running. The canonical new-rule and ruling skills are 172 and 80 lines, the same as the removed .claude originals, and both declare disable-model-invocation: true. The new .claude adapters for them keep only name and description. As a result, Claude can now start these skills on its own. That matters most for ruling, whose own text warns that running it removes the root node_modules.

The peach-check adapter has the same problem: allowed-tools and argument-hint exist only in .agents/skills/peach-check/SKILL.md. Claude Code therefore no longer pre-approves the gh/jq/node commands or shows the [run-id] hint. checkSkill in tools/docs/check-docs.mjs only checks name/description, so CI does not catch this. Copy the Claude-specific frontmatter keys into each adapter, and consider having the checker require adapter frontmatter to match the canonical skill.

✅ Edge Case: Missing PEACH_BASE_URL turns every project row into ERROR

📄 .agents/skills/peach-check/peach-issue-history.js:42-46 📄 .agents/skills/peach-check/peach-issue-history.js:448-456 📄 .agents/skills/peach-check/peach-issue-history.js:361-363 📄 .agents/skills/peach-check/INSTRUCTIONS.md:26-27 📄 .agents/skills/peach-check/INSTRUCTIONS.md:161
The helper now needs PEACH_BASE_URL, but only fetchPeachJson checks for it, once per request. runIssueHistory, by contrast, checks PEACH_KEY up front and fails fast. When the variable is unset, evaluateProjectHistory catches the error and writes an ERROR row for every project. INSTRUCTIONS.md tells the agent to treat each of those rows as a separate NEEDS-MANUAL-REVIEW finding, so one missing variable shows up as dozens of per-project failures.

The Prerequisites section (INSTRUCTIONS.md:26) also lists only PEACH_KEY and PEACHEE_ROOT, so the new variable is easy to miss. Fix: check and parse PEACH_BASE_URL once in runIssueHistory next to the PEACH_KEY check, and add it to the prerequisites.

✅ Security: PEACH_KEY is sent to any HTTPS origin set in PEACH_BASE_URL

📄 .agents/skills/peach-check/peach-issue-history.js:448-462 📄 .agents/skills/peach-check/INSTRUCTIONS.md:152-162
Before this change, fetchPeachJson sent the PEACH_KEY Basic credential to one fixed origin. Now it sends the credential and the project key to whatever origin process.env.PEACH_BASE_URL names (lines 449-463). The only checks are that the URL uses HTTPS and has no userinfo.

The skill asks agents to run this helper as a required step of the release check (INSTRUCTIONS.md:143-162). The rule to "obtain it from an authorized maintainer" is only written guidance; the code does not enforce it. A wrong value, a value left in the shell, or one an agent copies from a log or chat therefore receives the reusable token on the first request, and redirect: 'manual' does not prevent that.

The repository cannot name the internal host because it is public, but the helper can still bind the token to an approved origin. For example, it could compare the host against an allowlist or hash kept outside the repo, or at minimum print the resolved origin and require explicit confirmation before sending credentials.

Verification Rules 3/3 met PRs 1 inspected

Functional validation No results

Rules 3 passed 1 not applicable

✅ Internal artifact registries
✅ Keep SonarJS documentation in sync
✅ Preserve SonarJS generated sources and public contracts

Broader impact PRs 1 inspected
Cross-PR 1 PR inspected 0 open impacts

PR 8519: AP-1582 Run changed-file checks before pushes Inspected

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant