Repository navigation
TML-1790: Add CI check to limit agent docs growth - #82
Conversation
WalkthroughAdds footprint monitoring for Cursor rulecards: a new Node.js analysis script, configuration and schema files, README docs, package scripts and workspace dependency, and a CI step to run footprint checks (optional check mode enforces thresholds). Changes
Sequence Diagram(s)Comment |
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Lite
📒 Files selected for processing (4)
.cursor/rules/README.md.github/workflows/ci.ymlpackage.jsonscripts/rules-footprint.mjs
🧰 Additional context used
📓 Path-based instructions (3)
{architecture.config.json,dependency-cruiser.config.mjs,turbo.json,scripts/**/*.mjs}
📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)
Prefer declarative configuration over hardcoded logic when implementing validation rules, constraints, or configuration logic
Files:
scripts/rules-footprint.mjs
{dependency-cruiser.config.mjs,scripts/**/*.mjs}
📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)
Read configuration rules declaratively from config files in generator scripts rather than implementing hardcoded conditionals
Files:
scripts/rules-footprint.mjs
.cursor/rules/**/*
📄 CodeRabbit inference engine (.cursor/rules/doc-maintenance.mdc)
Update or add new documentation in .cursor/rules whenever corrections or mistakes are fixed
Files:
.cursor/rules/README.md
🧠 Learnings (1)
📚 Learning: 2026-01-02T11:49:27.327Z
Learnt from: igalklebanov
Repo: prisma/prisma-next PR: 68
File: package.json:5-5
Timestamp: 2026-01-02T11:49:27.327Z
Learning: In package.json, when Corepack is involved, the packageManager field should use Corepack's hash format (hexadecimal, sha512.<hex>). This hex-based Corepack format is the standard representation of the hash; the base64 form (sha512-<base64>) is also a valid representation of the same hash but Corepack's hex format is the correct one to rely on in this field. Ensure you use the Corepack hex format for packageManager whenever Corepack is used to generate or verify integrity.
Applied to files:
package.json
🔇 Additional comments (6)
.github/workflows/ci.yml (1)
50-51: LGTM! Clean CI integration.The new footprint check step is well-placed in the Lint job and follows the established pattern of other lint steps.
package.json (1)
27-28: LGTM! Script naming and structure follow conventions.The two scripts appropriately separate reporting (
rules:footprint) from CI enforcement (lint:rules:footprint), consistent with the existing script organization..cursor/rules/README.md (1)
10-19: LGTM! Clear and concise documentation.The new section provides users with the commands they need and correctly points them to the script for threshold details.
scripts/rules-footprint.mjs (3)
33-35: LGTM! Line counting handles cross-platform line endings correctly.
70-74: LGTM! Byte formatting is clear and appropriate.
81-81: The file filtering regex is correct and captures all rulecard formats in the repository.The regex
/\.(md|mdc)$/iproperly matches both.mdc(47 files) and.mdfiles (1 file:no-backward-compatibility.md), while correctly excludingREADME.md. The pattern handles all rulecard formats currently in the.cursor/rulesdirectory with appropriate case-insensitive matching.
Introduces scripts/rules-footprint.mjs to measure context bloat from Cursor rules and agent documentation. The script reports: - Total bytes/lines for .cursor/rules/** - Bytes/lines for alwaysApply: true rulecards (always loaded) - Bytes/lines for AGENTS.md - Combined always-loaded context size Supports --check flag to validate against configurable thresholds, enabling CI enforcement of footprint budgets.
Adds two new scripts: - pnpm rules:footprint — display current footprint report - pnpm lint:rules:footprint — check against thresholds (for CI) Documents the footprint monitoring workflow in .cursor/rules/README.md so contributors can track context bloat and understand thresholds.
Adds footprint check to the lint CI job to prevent context bloat regressions. The check fails if any of these thresholds are exceeded: - alwaysApply rulecards: 500 lines / 20KB - AGENTS.md: 200 lines / 10KB - Total rules: 5,000 lines / 200KB This ensures new rulecards or expansions stay within budget and keeps agent context lean.
The custom frontmatter parser in rules-footprint.mjs is fragile and cannot handle multi-line values, quoted strings, or complex arrays. Adding gray-matter as a dev dependency provides battle-tested parsing that handles all edge cases correctly.
Move hardcoded THRESHOLDS from the script to a JSON config file at .cursor/rules-footprint.config.json. This follows the project pattern of preferring declarative configuration over embedded constants. Include a JSON schema for validation and editor autocomplete support.
Address code quality feedback by restructuring the monolithic main(): - Use gray-matter instead of fragile custom frontmatter parser - Load thresholds from .cursor/rules-footprint.config.json with sensible defaults and clear error handling if missing/malformed - Extract scanRulecardFiles(dir) to gather rulecard statistics - Extract readAgentsStats(file) to read AGENTS.md metrics - Extract printReport(stats) for the report output - Extract checkThresholds(stats, thresholds, checkMode) for validation - Slim main() to pure orchestration (~10 lines) Each helper has clear inputs/outputs, improving testability.
Point users to .cursor/rules-footprint.config.json instead of the script file when they need to adjust footprint thresholds.
5aae0a6 to
c04c658
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Lite
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (7)
.cursor/rules-footprint.config.json.cursor/rules/README.md.github/workflows/ci.ymlpackage.jsonpnpm-workspace.yamlrules-footprint.config.schema.jsonscripts/rules-footprint.mjs
🧰 Additional context used
📓 Path-based instructions (4)
.cursor/rules/**/*
📄 CodeRabbit inference engine (.cursor/rules/doc-maintenance.mdc)
Update or add new documentation in .cursor/rules whenever corrections or mistakes are fixed
Files:
.cursor/rules/README.md
pnpm-workspace.yaml
📄 CodeRabbit inference engine (.cursor/rules/import-validation.mdc)
Update
pnpm-workspace.yamlwith package glob pattern when adding new packagesUpdate
pnpm-workspace.yamlto add or remove package globs when moving packages between locations
Files:
pnpm-workspace.yaml
{architecture.config.json,dependency-cruiser.config.mjs,turbo.json,scripts/**/*.mjs}
📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)
Prefer declarative configuration over hardcoded logic when implementing validation rules, constraints, or configuration logic
Files:
scripts/rules-footprint.mjs
{dependency-cruiser.config.mjs,scripts/**/*.mjs}
📄 CodeRabbit inference engine (.cursor/rules/declarative-config.mdc)
Read configuration rules declaratively from config files in generator scripts rather than implementing hardcoded conditionals
Files:
scripts/rules-footprint.mjs
🧠 Learnings (2)
📚 Learning: 2026-01-02T11:49:27.327Z
Learnt from: igalklebanov
Repo: prisma/prisma-next PR: 68
File: package.json:5-5
Timestamp: 2026-01-02T11:49:27.327Z
Learning: In package.json, when Corepack is involved, the packageManager field should use Corepack's hash format (hexadecimal, sha512.<hex>). This hex-based Corepack format is the standard representation of the hash; the base64 form (sha512-<base64>) is also a valid representation of the same hash but Corepack's hex format is the correct one to rely on in this field. Ensure you use the Corepack hex format for packageManager whenever Corepack is used to generate or verify integrity.
Applied to files:
package.json
📚 Learning: 2026-01-02T11:49:19.994Z
Learnt from: igalklebanov
Repo: prisma/prisma-next PR: 68
File: pnpm-workspace.yaml:6-10
Timestamp: 2026-01-02T11:49:19.994Z
Learning: In pnpm-workspace.yaml, when configuring allowBuilds, pin exact package versions (e.g., 'prisma/client6.18.0') rather than semver ranges to reduce risk of malicious versions being installed. This pattern should apply to all pnpm-workspace.yaml files in the repository. Regularly audit these pins and manage upgrades through controlled, documented changes.
Applied to files:
pnpm-workspace.yaml
🔇 Additional comments (13)
pnpm-workspace.yaml (1)
19-19: LGTM!The addition of
gray-matterto the workspace catalog is correct and follows standard catalog dependency patterns. The semver range is appropriate for catalog entries..cursor/rules/README.md (1)
10-20: LGTM!The footprint monitoring documentation is clear, concise, and provides actionable commands for developers. The reference to the configuration file path is accurate.
.github/workflows/ci.yml (1)
50-51: LGTM!The new CI step for checking rules footprint is well-placed in the lint job and follows the established pattern. The command correctly references the lint script that enforces thresholds.
.cursor/rules-footprint.config.json (1)
1-12: LGTM!The configuration file is well-structured with threshold values that match the schema defaults. The schema reference path is correct, and the values align with the PR objectives showing current footprint is within these thresholds.
package.json (1)
27-28: LGTM!The new npm scripts and gray-matter dependency are well-integrated:
- Script naming follows existing patterns (e.g.,
lint:depsvslint:rules:footprint)- The
--checkflag inlint:rules:footprintappropriately enforces thresholds for CI- Using
catalog:for gray-matter is consistent with other dependenciesAlso applies to: 43-43
scripts/rules-footprint.mjs (8)
1-20: LGTM!The file header, imports, and constants are well-structured:
- Clear usage documentation
- Modern
node:protocol for built-in modules- gray-matter integration addresses previous review feedback
- Sensible path constants
53-70: LGTM!The utility functions are clean and correct:
countLines()handles both Unix and Windows line endingsextractFrontmatter()uses the robust gray-matter library (addressing previous feedback)formatBytes()provides human-readable output with appropriate precision
130-142: LGTM!The function appropriately treats AGENTS.md as optional, returning zeros when missing rather than failing. Error handling is consistent with the tolerant approach throughout the script.
144-190: LGTM!The report formatting is excellent:
- Clear visual hierarchy with section separators
- Helpful breakdown of alwaysApply files sorted by size
- Good use of
toLocaleString()for readability- Combined context calculation provides useful insight
192-242: LGTM!The threshold checking logic is thorough and user-friendly:
- Validates all six metrics (alwaysApply, AGENTS.md, and total for both lines and bytes)
- Collects all violations before reporting (better UX than failing on first issue)
- Exits with code 1 for CI integration
- Helpful message directing users to the config file
244-255: LGTM!Displaying current thresholds provides valuable transparency, especially when running the script in check mode. Formatting is consistent with the report output.
257-271: LGTM!The refactored
main()function is clean and focused on orchestration (addressing previous feedback about the 162-line main). Each step is clear, and the helper functions are well-composed.
72-128: No action needed—the directory structure is flat and the implementation is correct.The
.cursor/rules/directory contains only files at the root level with no subdirectories. ThereaddirSync()call on line 73 correctly scans all rulecards. The "**" in the documentation (line 10) refers to the globbing pattern conceptually, not an actual need for recursive scanning.
| { | ||
| "$schema": "http://json-schema.org/draft-07/schema#", | ||
| "title": "Rules Footprint Config", | ||
| "description": "Configuration for the rules-footprint.mjs script thresholds", | ||
| "type": "object", | ||
| "properties": { | ||
| "thresholds": { | ||
| "type": "object", | ||
| "description": "Threshold values for --check mode", | ||
| "properties": { | ||
| "alwaysApplyLines": { | ||
| "type": "integer", | ||
| "description": "Maximum lines for alwaysApply rulecards", | ||
| "default": 500 | ||
| }, | ||
| "alwaysApplyBytes": { | ||
| "type": "integer", | ||
| "description": "Maximum bytes for alwaysApply rulecards", | ||
| "default": 20000 | ||
| }, | ||
| "agentsLines": { | ||
| "type": "integer", | ||
| "description": "Maximum lines for AGENTS.md", | ||
| "default": 200 | ||
| }, | ||
| "agentsBytes": { | ||
| "type": "integer", | ||
| "description": "Maximum bytes for AGENTS.md", | ||
| "default": 10000 | ||
| }, | ||
| "totalRulesLines": { | ||
| "type": "integer", | ||
| "description": "Maximum total lines for all rules", | ||
| "default": 5000 | ||
| }, | ||
| "totalRulesBytes": { | ||
| "type": "integer", | ||
| "description": "Maximum total bytes for all rules", | ||
| "default": 200000 | ||
| } | ||
| }, | ||
| "additionalProperties": false | ||
| } | ||
| }, | ||
| "additionalProperties": false | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Well-structured schema with clear threshold definitions.
The JSON Schema is well-formed and provides clear validation for the footprint configuration. All threshold properties are appropriately typed as integers with descriptive text.
Optional: Add minimum constraints to threshold properties
Consider adding "minimum": 0 or "minimum": 1 to each integer threshold property to prevent negative or zero values, which wouldn't make sense for size thresholds:
"alwaysApplyLines": {
"type": "integer",
"description": "Maximum lines for alwaysApply rulecards",
+ "minimum": 1,
"default": 500
}Apply similar constraints to all six threshold properties.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In rules-footprint.config.schema.json around lines 1 to 46, add a "minimum": 0
constraint to each of the six integer threshold properties (alwaysApplyLines,
alwaysApplyBytes, agentsLines, agentsBytes, totalRulesLines, totalRulesBytes) so
negative values are rejected; keep the existing "type", "description", and
"default" entries unchanged and apply the same "minimum": 0 to all six
properties.
| function loadThresholds() { | ||
| if (!existsSync(CONFIG_FILE)) { | ||
| console.warn(`Warning: ${CONFIG_FILE} not found, using defaults`); | ||
| return DEFAULT_THRESHOLDS; | ||
| } | ||
|
|
||
| try { | ||
| const raw = readFileSync(CONFIG_FILE, 'utf8'); | ||
| const config = JSON.parse(raw); | ||
|
|
||
| if (!config.thresholds || typeof config.thresholds !== 'object') { | ||
| console.warn(`Warning: ${CONFIG_FILE} missing 'thresholds' object, using defaults`); | ||
| return DEFAULT_THRESHOLDS; | ||
| } | ||
|
|
||
| return { ...DEFAULT_THRESHOLDS, ...config.thresholds }; | ||
| } catch (err) { | ||
| console.warn(`Warning: Failed to parse ${CONFIG_FILE}: ${err.message}, using defaults`); | ||
| return DEFAULT_THRESHOLDS; | ||
| } | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider validating threshold value types.
The loadThresholds() function correctly checks for the presence of the thresholds object but doesn't validate that the values are numbers. If the config file contains non-numeric values (e.g., strings), the threshold comparisons in checkThresholds() could produce incorrect results.
🔎 Proposed validation logic
if (!config.thresholds || typeof config.thresholds !== 'object') {
console.warn(`Warning: ${CONFIG_FILE} missing 'thresholds' object, using defaults`);
return DEFAULT_THRESHOLDS;
}
- return { ...DEFAULT_THRESHOLDS, ...config.thresholds };
+ // Validate that all values are positive numbers
+ const merged = { ...DEFAULT_THRESHOLDS, ...config.thresholds };
+ for (const [key, value] of Object.entries(merged)) {
+ if (typeof value !== 'number' || value < 0) {
+ console.warn(`Warning: Invalid threshold value for '${key}': ${value}, using default`);
+ merged[key] = DEFAULT_THRESHOLDS[key];
+ }
+ }
+ return merged;🤖 Prompt for AI Agents
In scripts/rules-footprint.mjs around lines 31 to 51, loadThresholds returns
thresholds without validating that each threshold value is a number; this can
break comparisons later. Update loadThresholds to iterate the merged thresholds,
verify each value is a finite number (or coerce numeric strings safely), replace
or omit invalid entries, and emit a warning listing any keys with invalid types;
finally return the sanitized thresholds object (falling back to the
DEFAULT_THRESHOLDS values for any invalid/missing keys).
Goal / purpose
Adds automated monitoring and CI enforcement for Cursor rules footprint to prevent context bloat regression.
Part of a larger effort to audit and consolidate Cursor rules and agent onboarding docs. This PR introduces guardrails to ensure the reduced footprint is maintained over time.
Linear
TML-1790: Audit + consolidate Cursor rules and AGENT_ONBOARDING.md (reduce prompt/context bloat)
What changed
scripts/rules-footprint.mjs— reports footprint metrics for:.cursor/rules/**(lines/bytes)alwaysApply: truerulecards only (loaded on every prompt)AGENTS.mdsize--checkmode fails if exceeded:alwaysApply: 500 lines / 20 KBAGENTS.md: 200 lines / 10 KBpnpm rules:footprint— run reportpnpm lint:rules:footprint— check thresholds (CI mode)lint:rules:footprintadded to CI workflow to catch regressions.cursor/rules/README.mddocuments how to monitor footprintCurrent footprint (all within thresholds):
How to verify
Expected: Report prints without errors,
--checkexits 0.To test threshold enforcement:
Summary by CodeRabbit
New Features
Documentation
Chores
✏️ Tip: You can customize this high-level summary in your review settings.