Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-1790: Add CI check to limit agent docs growth - #82

Merged
wmadden merged 7 commits into
mainfrom
tml-1790-guardrails-and-ci
Jan 4, 2026
Merged

wmadden merged 7 commits into
mainfrom
tml-1790-guardrails-and-ci

Conversation

@wmadden

@wmadden wmadden commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

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

  • New script scripts/rules-footprint.mjs — reports footprint metrics for:
    • Total .cursor/rules/** (lines/bytes)
    • alwaysApply: true rulecards only (loaded on every prompt)
    • AGENTS.md size
    • Combined always-loaded context
  • Thresholds defined in the script; --check mode fails if exceeded:
    • alwaysApply: 500 lines / 20 KB
    • AGENTS.md: 200 lines / 10 KB
    • Total rules: 5,000 lines / 200 KB
  • pnpm scripts added:
    • pnpm rules:footprint — run report
    • pnpm lint:rules:footprint — check thresholds (CI mode)
  • CI integration — lint:rules:footprint added to CI workflow to catch regressions
  • README update — .cursor/rules/README.md documents how to monitor footprint

Current footprint (all within thresholds):

Metric Current Threshold
alwaysApply lines 124 500
alwaysApply bytes 4.3 KB 20 KB
AGENTS.md lines 149 200
AGENTS.md bytes 6.2 KB 10 KB
Total rules lines 4,096 5,000
Total rules bytes 140 KB 200 KB

How to verify

# Run the footprint report
pnpm rules:footprint

# Run with threshold check (should pass)
pnpm lint:rules:footprint

Expected: Report prints without errors, --check exits 0.

To test threshold enforcement:

# Temporarily lower a threshold in scripts/rules-footprint.mjs
# e.g., set agentsLines: 50
pnpm lint:rules:footprint
# Expected: exits 1 with "THRESHOLDS EXCEEDED" message

Summary by CodeRabbit

  • New Features

    • Added footprint monitoring for rules: reports file/line/byte metrics with configurable thresholds and a check mode.
  • Documentation

    • Added a README section explaining footprint monitoring and available commands.
  • Chores

    • Added CLI commands to run and validate footprint checks and integrated automated footprint validation into CI.
    • Added a dev dependency to support the new tooling.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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

Cohort / File(s) Summary
Documentation & CI
.cursor/rules/README.md, .github/workflows/ci.yml
README: new "Footprint monitoring" section with pnpm commands and note about thresholds. CI: added "Check rules footprint" step to run pnpm lint:rules:footprint.
Footprint script & config
scripts/rules-footprint.mjs, .cursor/rules-footprint.config.json, rules-footprint.config.schema.json
New script that scans .cursor/rules and AGENTS.md, aggregates lines/bytes, parses frontmatter (detects alwaysApply), prints a report, and supports --check to enforce thresholds loaded from .cursor/rules-footprint.config.json. Schema defines threshold properties and defaults. Review parsing/threshold logic and exit-code behavior.
Package & workspace changes
package.json, pnpm-workspace.yaml
Added npm scripts: rules:footprint and lint:rules:footprint; added gray-matter to devDependencies/catalog. Verify script invocation and workspace dependency resolution.

Sequence Diagram(s)


Comment @coderabbitai help to get the list of available commands and usage tips.

@wmadden

wmadden commented Jan 4, 2026

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jan 4, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 8f63693 and 84edab1.

📒 Files selected for processing (4)
  • .cursor/rules/README.md
  • .github/workflows/ci.yml
  • package.json
  • scripts/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)$/i properly matches both .mdc (47 files) and .md files (1 file: no-backward-compatibility.md), while correctly excluding README.md. The pattern handles all rulecard formats currently in the .cursor/rules directory with appropriate case-insensitive matching.

Comment thread scripts/rules-footprint.mjs Resolved
Comment thread scripts/rules-footprint.mjs Resolved
Comment thread scripts/rules-footprint.mjs Resolved
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.
@wmadden
wmadden force-pushed the tml-1790-guardrails-and-ci branch from 5aae0a6 to c04c658 Compare January 4, 2026 05:58
@wmadden

wmadden commented Jan 4, 2026

Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jan 4, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 84edab1 and c04c658.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .cursor/rules-footprint.config.json
  • .cursor/rules/README.md
  • .github/workflows/ci.yml
  • package.json
  • pnpm-workspace.yaml
  • rules-footprint.config.schema.json
  • scripts/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.yaml with package glob pattern when adding new packages

Update pnpm-workspace.yaml to 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-matter to 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:deps vs lint:rules:footprint)
  • The --check flag in lint:rules:footprint appropriately enforces thresholds for CI
  • Using catalog: for gray-matter is consistent with other dependencies

Also 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 endings
  • extractFrontmatter() 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. The readdirSync() 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.

Comment on lines +1 to +46
{
"$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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 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.

Comment on lines +31 to +51
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;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 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).

@wmadden
wmadden merged commit b768d46 into main Jan 4, 2026
@wmadden
wmadden deleted the tml-1790-guardrails-and-ci branch January 4, 2026 06:09
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant