Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d94f712401 |
No files matched your search
@@ -0,0 +1,223 @@
|
||||
---
|
||||
name: garbage-collector
|
||||
description: Daily maintenance agent that reads pre-scanned gc-findings.json, then opens Tier A draft PRs (mechanical fixes like removing stale TODOs and console.logs) and Tier B GitHub Issues (architectural drift, oversized files, outdated deps). Runs headless via the garbage-collector.yml cron. Also invokable interactively as @garbage-collector for manual sweeps.
|
||||
tools: Read, Grep, Glob, Bash, Edit, Write
|
||||
model: haiku
|
||||
color: orange
|
||||
---
|
||||
|
||||
You are the WorldWideView Garbage Collector — a low-cost maintenance agent responsible for keeping the codebase clean between human-led development cycles.
|
||||
|
||||
## Step 1 — Read your charter
|
||||
|
||||
```bash
|
||||
cat .agents/rules/garbage-collection.md
|
||||
```
|
||||
|
||||
Internalize all guard rails, caps, and the never-touch list before taking any action.
|
||||
|
||||
## Step 2 — Read the findings
|
||||
|
||||
```bash
|
||||
cat gc-findings.json
|
||||
```
|
||||
|
||||
This was produced by `scripts/gc-scan.mjs` before you were invoked. You do **not** re-scan the codebase — you triage this list only.
|
||||
|
||||
If `gc-findings.json` does not exist or is empty, output "No findings to process." and stop.
|
||||
|
||||
## Step 3 — Check dry-run mode
|
||||
|
||||
```bash
|
||||
echo "${DRY_RUN:-false}"
|
||||
```
|
||||
|
||||
If `true`, jump to **Step 7 (Dry-run summary)** and skip all PR/Issue creation.
|
||||
|
||||
## Step 4 — Check for existing GC work (idempotency)
|
||||
|
||||
```bash
|
||||
# Open gc-bot PRs
|
||||
gh pr list --label gc-bot --state open --json number,title,headRefName,body
|
||||
|
||||
# Existing gc/* remote branches
|
||||
git branch -r --list 'origin/gc/*'
|
||||
|
||||
# Open gc-bot Issues
|
||||
gh issue list --label gc-bot --state open --json number,title
|
||||
```
|
||||
|
||||
Build a mental map of already-handled concerns. For each finding, skip it if an open PR or Issue already covers the same file + pattern.
|
||||
|
||||
## Step 5 — Tier A: Create draft PRs (max 3 per run)
|
||||
|
||||
Group related Tier A findings by `patternId` or `type`. Process the highest-value group first (most findings → most cleanup per PR).
|
||||
|
||||
For each group (up to 3 total):
|
||||
|
||||
### 5a — Create a branch
|
||||
|
||||
```bash
|
||||
SHA=$(git rev-parse --short HEAD)
|
||||
BRANCH="gc/<patternId>-${SHA}"
|
||||
git checkout -b "${BRANCH}"
|
||||
```
|
||||
|
||||
### 5b — Apply the mechanical fix
|
||||
|
||||
Follow these per-type rules:
|
||||
|
||||
**stale-todo (issueClosed: true)**
|
||||
Delete the entire comment line. Do not change surrounding code.
|
||||
|
||||
**stale-todo (issueClosed: false, age > 90d)**
|
||||
Add `# STALE(gc-bot):` prefix to the comment so the human sees it needs resolution. Do not delete — the human decides. This makes it Tier A-lite (no code risk, just marks it).
|
||||
|
||||
**anti-pattern: mdc-ref**
|
||||
Replace `.mdc` with `.md` in the file content. Check that the referenced file actually exists with `.md` extension before renaming.
|
||||
|
||||
**anti-pattern: console-log**
|
||||
Delete the `console.log(...)` line entirely. If it's the only statement in a block, delete the block too (only if the block has no other statements).
|
||||
|
||||
**anti-pattern: ts-ignore**
|
||||
Delete the `// @ts-ignore` line. If the next line now has a type error that is trivially fixable (e.g., adding a missing cast), fix it. If the type error is non-trivial, revert to Tier B (create an Issue instead).
|
||||
|
||||
**anti-pattern: ts-nocheck**
|
||||
Delete the `// @ts-nocheck` line. Check if the file still compiles cleanly with `npx tsc --noEmit --skipLibCheck` — if not, revert the deletion and file a Tier B Issue instead.
|
||||
|
||||
### 5c — Verify the change is safe
|
||||
|
||||
```bash
|
||||
# Count changed lines — must be ≤150
|
||||
git diff --stat
|
||||
|
||||
# Quick type check on changed files only
|
||||
npx tsc --noEmit --skipLibCheck 2>&1 | head -20
|
||||
```
|
||||
|
||||
If changed lines exceed 150 or type errors are introduced, `git checkout .` and file a Tier B Issue for this group instead.
|
||||
|
||||
### 5d — Commit and push
|
||||
|
||||
```bash
|
||||
git add -p # stage only the GC changes
|
||||
git commit -m "chore: [gc] remove <N> stale <type> findings"
|
||||
git push origin "${BRANCH}"
|
||||
```
|
||||
|
||||
### 5e — Open a draft PR
|
||||
|
||||
```bash
|
||||
gh pr create --draft --label gc-bot \
|
||||
--title "chore: [gc] <short description (≤60 chars)>" \
|
||||
--body "$(cat <<'EOF'
|
||||
## What changed
|
||||
<bullet list of files and what was removed/changed>
|
||||
|
||||
## Why
|
||||
Detector: `<patternId>` in `scripts/gc-scan.mjs`
|
||||
Rule violated: `<rule from garbage-collection.md>`
|
||||
Age / evidence: <age in days, or closed issue number>
|
||||
|
||||
## How to verify
|
||||
1. <step>
|
||||
2. Run `pnpm test` — all tests should still pass
|
||||
3. Run `pnpm build` — build must be clean
|
||||
|
||||
> This PR was opened automatically by the GC bot. Review before merging.
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
Return to main: `git checkout main`
|
||||
|
||||
## Step 6 — Tier B: Create GitHub Issues (max 5 per run)
|
||||
|
||||
Group related Tier B findings into one Issue per `type` (e.g., all oversized files in one Issue).
|
||||
|
||||
```bash
|
||||
gh issue create --label gc-bot \
|
||||
--title "[gc] <type>: <short description>" \
|
||||
--body "$(cat <<'EOF'
|
||||
## Summary
|
||||
<what was detected and why it matters>
|
||||
|
||||
## Files / packages affected
|
||||
<file list with line counts or versions>
|
||||
|
||||
## Suggested action
|
||||
<concrete next step — e.g., "split this file", "upgrade this dep", "fix this rule reference">
|
||||
|
||||
## How to close this
|
||||
Resolve the issue and close this ticket manually.
|
||||
|
||||
> Filed automatically by the GC bot on <date>.
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
## Step 7 — Dry-run summary
|
||||
|
||||
Find or create the tracking Issue:
|
||||
|
||||
```bash
|
||||
gh issue list --label gc-bot --state open --search "[gc-bot] Daily Scan Reports" --json number,title
|
||||
```
|
||||
|
||||
If it does not exist:
|
||||
```bash
|
||||
gh issue create --label gc-bot \
|
||||
--title "[gc-bot] Daily Scan Reports" \
|
||||
--body "This issue collects daily dry-run scan summaries. Enable normal mode by setting DRY_RUN=false in the workflow."
|
||||
```
|
||||
|
||||
Then post a comment:
|
||||
```bash
|
||||
gh issue comment <number> --body "$(cat <<'EOF'
|
||||
## GC Dry-run Report — <date>
|
||||
|
||||
| Tier | Count | Types |
|
||||
|---|---|---|
|
||||
| A (would fix) | <n> | <comma-separated types> |
|
||||
| B (would file) | <n> | <comma-separated types> |
|
||||
|
||||
### Tier A findings
|
||||
<table: file | line | type | description>
|
||||
|
||||
### Tier B findings
|
||||
<table: file/package | type | description>
|
||||
|
||||
No PRs or Issues were created (dry-run mode).
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
## Step 8 — Output summary
|
||||
|
||||
Print a clean markdown summary:
|
||||
|
||||
```
|
||||
## GC Run Complete
|
||||
|
||||
### PRs opened (<n>/3)
|
||||
- #<number>: <title> (<branch>)
|
||||
|
||||
### Issues opened (<n>/5)
|
||||
- #<number>: <title>
|
||||
|
||||
### Skipped (already handled)
|
||||
- <n> findings skipped — covered by existing open work
|
||||
|
||||
### Not actioned
|
||||
- <n> Tier B findings below cap — will appear in next run
|
||||
```
|
||||
|
||||
If nothing was created: "No new findings requiring action."
|
||||
|
||||
## Important invariants
|
||||
|
||||
- Never touch the never-touch list in the charter.
|
||||
- Never create a PR with more than 150 changed lines.
|
||||
- Never mark a PR as ready-for-review.
|
||||
- Never push directly to `main`.
|
||||
- If a Tier A fix risks introducing a regression and you cannot verify it is safe, file a Tier B Issue instead — safety always beats throughput.
|
||||
@@ -0,0 +1,74 @@
|
||||
# Garbage Collection Policy
|
||||
|
||||
## Purpose
|
||||
|
||||
The Garbage Collector (GC) is a daily Haiku-model agent that keeps the codebase clean. It detects stale TODOs, deprecated patterns, and architectural drift, then either applies a small mechanical fix (Tier A → draft PR) or files a report for human decision (Tier B → GitHub Issue). The GC **never makes architectural decisions** and **never auto-merges** anything.
|
||||
|
||||
## Two-tier output model
|
||||
|
||||
| Tier | Criteria | Output |
|
||||
|---|---|---|
|
||||
| **A — Mechanical** | Safe, codemod-like, no architectural judgement required | Draft PR with code change |
|
||||
| **B — Judgement** | Requires human architectural decision or context | GitHub Issue, no code |
|
||||
|
||||
When unsure of the tier, escalate to Tier B. Never attempt a refactor that requires understanding business intent.
|
||||
|
||||
## How the GC works
|
||||
|
||||
1. `scripts/gc-scan.mjs` runs first — deterministic shell-based detectors, zero cost, emits `gc-findings.json`.
|
||||
2. The Haiku agent reads `gc-findings.json` and the policy below. It **does not free-scan the codebase** — it only triages the pre-computed findings list.
|
||||
3. The agent creates draft PRs and Issues per the caps and guard rails below.
|
||||
|
||||
## Approved finding types (from gc-scan.mjs)
|
||||
|
||||
| Type | Tier | Description |
|
||||
|---|---|---|
|
||||
| `stale-todo` | A | TODO/FIXME/HACK/XXX comment older than 90 days, or referencing a closed issue |
|
||||
| `anti-pattern` (mdc-ref) | A | `.mdc` file reference — must be `.md` |
|
||||
| `anti-pattern` (console-log) | A | Stray `console.log(` in `.ts`/`.tsx` files |
|
||||
| `anti-pattern` (ts-ignore) | A | `@ts-ignore` suppressing a real type error |
|
||||
| `anti-pattern` (ts-nocheck) | A | `@ts-nocheck` disabling all type checking |
|
||||
| `anti-pattern` (hardcoded-url) | B | Hardcoded `localhost:5001`/`5000` engine URL |
|
||||
| `anti-pattern` (deprecated) | B | `@deprecated` symbol still active in production code |
|
||||
| `oversized-file` | B | Source file exceeding ~350 lines |
|
||||
| `orphaned-rule-ref` | B | Rule file references a path that no longer exists |
|
||||
| `outdated-dep` | B | Dependency behind latest version |
|
||||
|
||||
## PR guard rails (mandatory — no exceptions)
|
||||
|
||||
- All PRs are **DRAFT**. Never mark ready-for-review. Never auto-merge.
|
||||
- Label every PR and Issue `gc-bot`.
|
||||
- **Max 3 PRs per run. Max 5 Issues per run.**
|
||||
- **Max ~150 changed lines per PR.** One concern per PR.
|
||||
- Branch naming: `gc/<patternId-or-type>-<git-short-sha>` (e.g. `gc/console-log-a3f1b2c`)
|
||||
- Before creating anything: check open `gc-bot` PRs and Issues for the same concern — skip if already covered.
|
||||
- Commit prefix: `chore:` for removal/cleanup, `refactor:` for structural fixes. Both are patch-level per the project `/commit` rule.
|
||||
- Every PR description must include: what changed · which detector flagged it · which rule it violates · how to verify the fix is correct.
|
||||
|
||||
## Never-touch list (absolute — the agent must refuse)
|
||||
|
||||
- `prisma/migrations/**` — migrations are irreversible
|
||||
- `pnpm-lock.yaml` — lockfile integrity
|
||||
- `.env`, `.env.local`, `.env.*`, any file containing secrets or tokens
|
||||
- Generated assets: `public/cesium/**`, `.next/**`, `node_modules/**`
|
||||
- Large seed files: `packages/*/data/**`, `local-seeders/**`
|
||||
- Binary assets: images, videos, fonts, `.db` files
|
||||
- `local-scripts/` — scratch / one-off scripts, not subject to conventions
|
||||
|
||||
## Dry-run mode
|
||||
|
||||
When `DRY_RUN=true` (set in the workflow dispatch input):
|
||||
|
||||
- Post one summary comment on the tracking Issue (`[gc-bot] Daily Scan Reports`). Create that Issue if it does not exist (label: `gc-bot`).
|
||||
- List every finding with tier, file, line, description.
|
||||
- **Do not create any PRs or Issues.**
|
||||
- Use dry-run for the first 3–5 days after deployment to validate finding quality before enabling normal mode.
|
||||
|
||||
## Idempotency rules
|
||||
|
||||
A finding is already handled if **either** of these is true:
|
||||
|
||||
1. A remote branch matching `gc/<same-patternId-or-type>-*` exists (`git branch -r --list 'origin/gc/<type>-*'`).
|
||||
2. An open PR or Issue labelled `gc-bot` already covers the same file + concern.
|
||||
|
||||
Skip handled findings without error or noise.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Garbage Collector — Daily Sweep Prompt
|
||||
|
||||
You are the WorldWideView Garbage Collector agent running headless in GitHub Actions.
|
||||
|
||||
Run the garbage-collector agent sweep:
|
||||
|
||||
1. Read `.agents/rules/garbage-collection.md` for your charter and all guard rails.
|
||||
2. Read `gc-findings.json` for the pre-scanned findings produced by `scripts/gc-scan.mjs`.
|
||||
3. Check the `DRY_RUN` environment variable — if `true`, post a dry-run summary only (no PRs or Issues).
|
||||
4. Execute the full sweep procedure described in `.agents/agents/garbage-collector.md`.
|
||||
|
||||
Do not scan the codebase yourself. Work only from `gc-findings.json`.
|
||||
@@ -1,10 +1,12 @@
|
||||
name: Garbage Collector
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * *' # 06:00 UTC daily
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Dry run — post report only, open no PRs/Issues'
|
||||
description: 'Dry run — report findings only, open no PRs or Issues (recommended for first 3–5 days)'
|
||||
required: false
|
||||
default: 'true'
|
||||
type: choice
|
||||
@@ -18,97 +20,77 @@ on:
|
||||
required: false
|
||||
default: '180'
|
||||
|
||||
schedule:
|
||||
- cron: '0 3 * * 1'
|
||||
concurrency:
|
||||
group: garbage-collector
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
gc-scan:
|
||||
name: Scan for stale artefacts
|
||||
collect:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
env:
|
||||
DRY_RUN: ${{ github.event.inputs.dry_run || 'true' }}
|
||||
GH_TOKEN: ${{ secrets.GC_BOT_TOKEN }}
|
||||
DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }}
|
||||
DAYS_BRANCH: ${{ github.event.inputs.days_branch || '90' }}
|
||||
DAYS_COMMENT: ${{ github.event.inputs.days_comment || '180' }}
|
||||
GH_TOKEN: ${{ secrets.GC_BOT_TOKEN }}
|
||||
|
||||
steps:
|
||||
- name: Checkout (full history for git blame)
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.GC_BOT_TOKEN }}
|
||||
fetch-depth: 0 # full history required for git blame and branch age
|
||||
token: ${{ secrets.GC_BOT_TOKEN }} # PAT so pushed branches trigger CI
|
||||
|
||||
- name: Set up Node
|
||||
- name: Configure git user
|
||||
run: |
|
||||
git config user.name 'WorldWideView GC Bot'
|
||||
git config user.email '[email protected]'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Run GC scan
|
||||
id: scan
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Run deterministic scan
|
||||
run: |
|
||||
node scripts/gc-scan.mjs \
|
||||
--out gc-findings.json \
|
||||
--days-branch=${{ env.DAYS_BRANCH }} \
|
||||
--days-comment=${{ env.DAYS_COMMENT }} \
|
||||
> gc-report.json
|
||||
FINDINGS_COUNT=$(node -e "const r=require('./gc-report.json');console.log(r.findings.length)")
|
||||
echo "findings_count=$FINDINGS_COUNT" >> "$GITHUB_OUTPUT"
|
||||
echo "GC scan complete — $FINDINGS_COUNT finding(s)"
|
||||
--days-comment=${{ env.DAYS_COMMENT }}
|
||||
|
||||
- name: Upload raw report
|
||||
- name: Upload findings artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: gc-report
|
||||
path: gc-report.json
|
||||
name: gc-findings-${{ github.run_id }}
|
||||
path: gc-findings.json
|
||||
retention-days: 30
|
||||
|
||||
- name: Find or create tracking issue
|
||||
id: tracking
|
||||
run: |
|
||||
# gh issue list output: number<TAB>title<TAB>...
|
||||
ISSUE_NUMBER=$(gh issue list \
|
||||
--label gc-bot \
|
||||
--state open \
|
||||
--limit 1 | awk '{print $1}')
|
||||
- name: Run Garbage Collector agent
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
model: claude-haiku-4-5-20251001
|
||||
prompt: |
|
||||
You are the WorldWideView Garbage Collector agent running headless in GitHub Actions.
|
||||
|
||||
if [ -z "$ISSUE_NUMBER" ]; then
|
||||
ISSUE_NUMBER=$(gh issue create \
|
||||
--title "🗑️ Garbage Collector — tracking issue" \
|
||||
--body "This issue is updated automatically each time the GC scanner runs." \
|
||||
--label gc-bot | grep -oE '[0-9]+$')
|
||||
echo "Created tracking issue #$ISSUE_NUMBER"
|
||||
else
|
||||
echo "Found existing tracking issue #$ISSUE_NUMBER"
|
||||
fi
|
||||
echo "issue_number=$ISSUE_NUMBER" >> "$GITHUB_OUTPUT"
|
||||
Read `.agents/rules/garbage-collection.md` for your charter and all guard rails.
|
||||
Read `gc-findings.json` for the pre-scanned findings produced by `scripts/gc-scan.mjs`.
|
||||
Check the DRY_RUN environment variable — if "true", post a dry-run summary only (no PRs or Issues).
|
||||
Execute the full sweep procedure described in `.agents/agents/garbage-collector.md`.
|
||||
|
||||
- name: Build report comment
|
||||
id: report
|
||||
run: |
|
||||
node scripts/gc-format-report.mjs gc-report.json "$DRY_RUN" > report-comment.md
|
||||
echo "Built report comment ($(wc -c < report-comment.md) bytes)"
|
||||
|
||||
- name: Post scan report as comment
|
||||
run: |
|
||||
gh issue comment "${{ steps.tracking.outputs.issue_number }}" --body-file report-comment.md
|
||||
|
||||
- name: Open stale-branch PRs (live mode only)
|
||||
if: env.DRY_RUN == 'false'
|
||||
run: |
|
||||
node -e "
|
||||
const { execSync } = require('child_process');
|
||||
const r = require('./gc-report.json');
|
||||
const merged = r.findings.filter(f => f.type === 'stale-branch' && f.isMerged);
|
||||
for (const b of merged.slice(0, 5)) {
|
||||
try {
|
||||
const body = 'Branch merged ' + b.ageDays + ' days ago — safe to delete.\\nLast commit: ' + b.lastSubject + '\\nAuthor: ' + b.author;
|
||||
execSync('gh issue create --title "chore(gc): delete merged stale branch ' + b.branch + '" --body "' + body + '" --label gc-bot', { stdio: 'inherit' });
|
||||
} catch(e) { console.error(e.message); }
|
||||
}
|
||||
"
|
||||
Do not scan the codebase yourself. Work only from gc-findings.json.
|
||||
allowed_tools: 'Bash,Read,Edit,Write,Grep,Glob'
|
||||
@@ -21,6 +21,7 @@ node_modules/
|
||||
/.agents/plans
|
||||
/.agents/research/
|
||||
/.agents/context/
|
||||
/.agents/settings.local.json
|
||||
|
||||
# performance
|
||||
/performance/
|
||||
@@ -28,6 +29,9 @@ node_modules/
|
||||
# artifacts
|
||||
/artifacts/
|
||||
|
||||
# gc bot — generated scan output, never commit
|
||||
gc-findings.json
|
||||
|
||||
# scripts (tracked, but temporary scratchpads should go in /local-scripts/)
|
||||
|
||||
|
||||
|
||||
+301
-75
@@ -1,36 +1,29 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* gc-scan.mjs — Garbage Collector scanner for worldwideview
|
||||
*
|
||||
* Scans the repository for:
|
||||
* 1. Stale branches (merged or idle > STALE_BRANCH_DAYS)
|
||||
* 2. TODO/FIXME/HACK comments older than STALE_COMMENT_DAYS (via git blame)
|
||||
* 3. Orphaned workspace packages (zero reverse-deps inside the monorepo)
|
||||
* 4. Very old Prisma migrations (> 1 year untouched)
|
||||
*
|
||||
* Outputs a JSON report to stdout.
|
||||
* The workflow decides whether to open Issues/PRs based on dry_run flag.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/gc-scan.mjs [--days-branch=90] [--days-comment=180]
|
||||
*/
|
||||
// gc-scan.mjs — deterministic garbage detection for the GC bot
|
||||
// Zero npm dependencies. Emits gc-findings.json consumed by the garbage-collector agent.
|
||||
//
|
||||
// Usage: node scripts/gc-scan.mjs [--out <path>] [--days-branch=90] [--days-comment=180]
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { resolve, relative } from 'node:path';
|
||||
import { argv, cwd } from 'node:process';
|
||||
import { writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||
import { join, resolve, relative } from 'node:path';
|
||||
|
||||
// ─── Tuneable thresholds ──────────────────────────────────────────────────────
|
||||
const ROOT = process.cwd();
|
||||
|
||||
// Parse CLI args: --out <path>, --days-branch=N, --days-comment=N
|
||||
const ARGS = Object.fromEntries(
|
||||
argv.slice(2).flatMap(a => {
|
||||
process.argv.slice(2).flatMap(a => {
|
||||
const m = a.match(/^--([\w-]+)=(.+)$/);
|
||||
return m ? [[m[1], m[2]]] : [];
|
||||
})
|
||||
);
|
||||
|
||||
const outIdx = process.argv.indexOf('--out');
|
||||
const OUT = outIdx !== -1 ? process.argv[outIdx + 1] : (ARGS['out'] ?? 'gc-findings.json');
|
||||
const STALE_BRANCH_DAYS = Number(ARGS['days-branch'] ?? 90);
|
||||
const STALE_COMMENT_DAYS = Number(ARGS['days-comment'] ?? 180);
|
||||
const ROOT = cwd();
|
||||
|
||||
/** @type {Array<Record<string, unknown>>} */
|
||||
const findings = [];
|
||||
|
||||
function run(cmd) {
|
||||
try {
|
||||
@@ -40,14 +33,17 @@ function run(cmd) {
|
||||
}
|
||||
}
|
||||
|
||||
function add(finding) {
|
||||
findings.push(finding);
|
||||
}
|
||||
|
||||
function daysAgo(isoDate) {
|
||||
if (!isoDate) return Infinity;
|
||||
return (Date.now() - new Date(isoDate).getTime()) / 86_400_000;
|
||||
}
|
||||
|
||||
// ─── 1. Stale branches ────────────────────────────────────────────────────────
|
||||
function scanStaleBranches() {
|
||||
const findings = [];
|
||||
// ─── Detector 1: Stale branches ──────────────────────────────────────────────
|
||||
function detectStaleBranches() {
|
||||
const out = run(
|
||||
'git for-each-ref --sort=committerdate refs/remotes/origin ' +
|
||||
'--format=%(refname:short)|%(committerdate:iso8601)|%(authorname)|%(subject)'
|
||||
@@ -60,54 +56,204 @@ function scanStaleBranches() {
|
||||
if (age < STALE_BRANCH_DAYS) continue;
|
||||
const mergeBase = run(`git merge-base origin/main "${ref}" 2>/dev/null`);
|
||||
const branchHead = run(`git rev-parse "${ref}"`);
|
||||
findings.push({
|
||||
const isMerged = mergeBase === branchHead;
|
||||
add({
|
||||
type: 'stale-branch',
|
||||
tier: 'B',
|
||||
branch,
|
||||
author,
|
||||
lastCommitDate: date?.trim(),
|
||||
ageDays: Math.floor(age),
|
||||
isMerged: mergeBase === branchHead,
|
||||
isMerged,
|
||||
lastSubject: subject,
|
||||
description: `Branch '${branch}' is ${Math.floor(age)} days old${isMerged ? ' and fully merged into main — safe to delete' : ' with no recent activity'}`,
|
||||
});
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── 2. Stale TODO/FIXME/HACK comments ───────────────────────────────────────
|
||||
function scanStaleComments() {
|
||||
const findings = [];
|
||||
const grepResult = run(
|
||||
'git grep -rn --include=*.ts --include=*.tsx --include=*.mjs --include=*.js ' +
|
||||
'-E "TODO|FIXME|HACK|XXX" -- . :(exclude)node_modules :(exclude).next :(exclude)dist :(exclude)prisma/migrations'
|
||||
// ─── Detector 2: Stale TODO/FIXME/HACK comments ──────────────────────────────
|
||||
function detectStaleTodos() {
|
||||
const raw = run(
|
||||
'git grep -rn --fixed-strings -e "TODO" -e "FIXME" -e "HACK" -e "XXX" ' +
|
||||
'-- "*.ts" "*.tsx" "*.mjs" "*.js"'
|
||||
);
|
||||
for (const line of grepResult.split('\n').filter(Boolean).slice(0, 200)) {
|
||||
const m = line.match(/^([^:]+):(\d+):(.+)$/);
|
||||
if (!m) continue;
|
||||
const [, file, lineNum, text] = m;
|
||||
const blameOut = run(`git blame -L ${lineNum},${lineNum} --porcelain "${file}" 2>/dev/null`);
|
||||
const authorTimeMatch = blameOut.match(/author-time (\d+)/);
|
||||
if (!authorTimeMatch) continue;
|
||||
const age = (Date.now() - Number(authorTimeMatch[1]) * 1000) / 86_400_000;
|
||||
if (age < STALE_COMMENT_DAYS) continue;
|
||||
const authorMatch = blameOut.match(/^author (.+)$/m);
|
||||
findings.push({
|
||||
type: 'stale-comment',
|
||||
file: relative(ROOT, resolve(ROOT, file)),
|
||||
line: Number(lineNum),
|
||||
text: text.trim().slice(0, 120),
|
||||
author: authorMatch?.[1] ?? 'unknown',
|
||||
ageDays: Math.floor(age),
|
||||
if (!raw) return;
|
||||
|
||||
// Cap at 40 matches to keep git blame calls fast on large repos
|
||||
const lines = raw.split('\n').filter(Boolean).slice(0, 40);
|
||||
|
||||
for (const line of lines) {
|
||||
const firstColon = line.indexOf(':');
|
||||
if (firstColon === -1) continue;
|
||||
const afterFile = line.slice(firstColon + 1);
|
||||
const secondColon = afterFile.indexOf(':');
|
||||
if (secondColon === -1) continue;
|
||||
|
||||
const file = line.slice(0, firstColon);
|
||||
const lineNum = afterFile.slice(0, secondColon);
|
||||
const content = afterFile.slice(secondColon + 1).trim();
|
||||
|
||||
if (file.startsWith('node_modules/') || file.includes('public/cesium')) continue;
|
||||
|
||||
const blameOut = run(`git blame -L ${lineNum},${lineNum} --porcelain "${file}"`);
|
||||
const timeMatch = blameOut.match(/^author-time (\d+)/m);
|
||||
if (!timeMatch) continue;
|
||||
|
||||
const ageInDays = (Date.now() - parseInt(timeMatch[1], 10) * 1000) / 86_400_000;
|
||||
if (ageInDays < STALE_COMMENT_DAYS) continue;
|
||||
|
||||
const issueMatch = content.match(/#(\d+)/);
|
||||
let issueClosed = false;
|
||||
if (issueMatch) {
|
||||
const state = run(`gh issue view ${issueMatch[1]} --json state -q .state 2>/dev/null`);
|
||||
issueClosed = state.toUpperCase() === 'CLOSED';
|
||||
}
|
||||
|
||||
add({
|
||||
type: 'stale-todo',
|
||||
tier: 'A',
|
||||
file,
|
||||
line: parseInt(lineNum, 10),
|
||||
content: content.slice(0, 200),
|
||||
ageInDays: Math.round(ageInDays),
|
||||
issueClosed,
|
||||
linkedIssue: issueMatch ? issueMatch[1] : null,
|
||||
description: issueClosed
|
||||
? `TODO references closed issue #${issueMatch[1]} (${Math.round(ageInDays)}d old) — safe to delete`
|
||||
: `TODO/comment is ${Math.round(ageInDays)} days old — review and resolve or delete`,
|
||||
});
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── 3. Orphaned workspace packages ──────────────────────────────────────────
|
||||
function scanOrphanedPackages() {
|
||||
const findings = [];
|
||||
// ─── Detector 3: Known anti-patterns ─────────────────────────────────────────
|
||||
const ANTI_PATTERNS = [
|
||||
{
|
||||
id: 'mdc-ref',
|
||||
tier: 'A',
|
||||
globs: ['*.ts', '*.tsx', '*.md', '*.mjs'],
|
||||
pattern: '\\.mdc',
|
||||
desc: '.mdc file reference — must be .md (project invariant: never .mdc files)',
|
||||
},
|
||||
{
|
||||
id: 'console-log',
|
||||
tier: 'A',
|
||||
globs: ['*.ts', '*.tsx'],
|
||||
pattern: 'console\\.log(',
|
||||
excludePrefix: 'scripts/',
|
||||
desc: 'stray console.log — remove or replace with structured logging',
|
||||
},
|
||||
{
|
||||
id: 'ts-ignore',
|
||||
tier: 'A',
|
||||
globs: ['*.ts', '*.tsx'],
|
||||
pattern: '@ts-ignore',
|
||||
desc: '@ts-ignore suppresses real type errors — remove and fix the underlying type',
|
||||
},
|
||||
{
|
||||
id: 'ts-nocheck',
|
||||
tier: 'A',
|
||||
globs: ['*.ts', '*.tsx'],
|
||||
pattern: '@ts-nocheck',
|
||||
desc: '@ts-nocheck disables all type checking for the file — remove and fix types',
|
||||
},
|
||||
{
|
||||
id: 'hardcoded-url',
|
||||
tier: 'B',
|
||||
globs: ['*.ts', '*.tsx'],
|
||||
pattern: 'localhost:500',
|
||||
excludePrefix: 'scripts/',
|
||||
desc: 'hardcoded engine URL (localhost:5001/5000) — use env var or plugin streamUrl instead',
|
||||
},
|
||||
{
|
||||
id: 'deprecated',
|
||||
tier: 'B',
|
||||
globs: ['*.ts', '*.tsx'],
|
||||
pattern: '@deprecated',
|
||||
desc: '@deprecated JSDoc on a symbol — audit whether all callers have migrated',
|
||||
},
|
||||
];
|
||||
|
||||
function detectAntiPatterns() {
|
||||
for (const { id, tier, globs, pattern, desc, excludePrefix } of ANTI_PATTERNS) {
|
||||
const globArgs = globs.map(g => `"${g}"`).join(' ');
|
||||
const raw = run(`git grep -En "${pattern}" -- ${globArgs}`);
|
||||
if (!raw) continue;
|
||||
|
||||
const hits = raw
|
||||
.split('\n')
|
||||
.filter(l => l && !(excludePrefix && l.startsWith(excludePrefix)))
|
||||
.slice(0, 15);
|
||||
|
||||
for (const line of hits) {
|
||||
const m = line.match(/^([^:]+):(\d+):(.*)/);
|
||||
if (!m) continue;
|
||||
if (m[1].startsWith('node_modules/') || m[1].includes('public/cesium')) continue;
|
||||
add({
|
||||
type: 'anti-pattern',
|
||||
patternId: id,
|
||||
tier,
|
||||
file: m[1],
|
||||
line: parseInt(m[2], 10),
|
||||
content: m[3].trim().slice(0, 200),
|
||||
description: desc,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Detector 4: Oversized source files ──────────────────────────────────────
|
||||
function detectOversizedFiles() {
|
||||
const fileList = run('git ls-files "*.ts" "*.tsx"').split('\n').filter(Boolean);
|
||||
for (const file of fileList) {
|
||||
if (file.startsWith('node_modules/') || file.includes('public/cesium') || file.includes('.next/')) continue;
|
||||
const fullPath = join(ROOT, file);
|
||||
if (!existsSync(fullPath)) continue;
|
||||
const lineCount = readFileSync(fullPath, 'utf8').split('\n').length;
|
||||
if (lineCount > 350) {
|
||||
add({
|
||||
type: 'oversized-file',
|
||||
tier: 'B',
|
||||
file,
|
||||
lines: lineCount,
|
||||
description: `${lineCount} lines exceeds ~300-line convention — extract helpers, split component, or use hooks`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Detector 5: Orphaned rule file references ───────────────────────────────
|
||||
function detectOrphanedRuleRefs() {
|
||||
const ruleFiles = run('git ls-files ".agents/rules/"').split('\n').filter(f => f.endsWith('.md'));
|
||||
for (const ruleFile of ruleFiles) {
|
||||
const fullPath = join(ROOT, ruleFile);
|
||||
if (!existsSync(fullPath)) continue;
|
||||
const content = readFileSync(fullPath, 'utf8');
|
||||
const seen = new Set();
|
||||
for (const [, ref] of content.matchAll(
|
||||
/`((?:src|packages|local-plugins|local-seeders|\.agents)\/[^`\s]+)`/g
|
||||
)) {
|
||||
const base = ref.replace(/\/\*\*.*/, '').replace(/\/\*.*/, '').replace(/\{[^}]+\}.*/, '');
|
||||
if (!base || seen.has(base)) continue;
|
||||
seen.add(base);
|
||||
const tracked = run(`git ls-files "${base}" "${base}/" 2>/dev/null`);
|
||||
if (!tracked && !existsSync(join(ROOT, base))) {
|
||||
add({
|
||||
type: 'orphaned-rule-ref',
|
||||
tier: 'B',
|
||||
file: ruleFile,
|
||||
ref: base,
|
||||
description: `Rule file references '${base}' which no longer exists — update or remove`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Detector 6: Orphaned workspace packages ─────────────────────────────────
|
||||
function detectOrphanedPackages() {
|
||||
try {
|
||||
const wsInfo = run('pnpm list --recursive --depth=0 --json 2>/dev/null');
|
||||
if (!wsInfo) return findings;
|
||||
if (!wsInfo) return;
|
||||
const pkgs = JSON.parse(wsInfo);
|
||||
const allNames = new Set(pkgs.map(p => p.name).filter(Boolean));
|
||||
const reverseDepCount = Object.fromEntries([...allNames].map(n => [n, 0]));
|
||||
@@ -120,18 +266,22 @@ function scanOrphanedPackages() {
|
||||
const pkg = pkgs.find(p => p.name === name);
|
||||
if (!pkg?.path?.includes('/packages/')) continue;
|
||||
if (count === 0) {
|
||||
findings.push({ type: 'orphaned-package', name, path: relative(ROOT, pkg.path) });
|
||||
add({
|
||||
type: 'orphaned-package',
|
||||
tier: 'B',
|
||||
name,
|
||||
path: relative(ROOT, pkg.path),
|
||||
description: `Workspace package '${name}' has no reverse dependencies inside the monorepo — consider removing`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch { /* skip */ }
|
||||
return findings;
|
||||
} catch { /* skip if pnpm unavailable */ }
|
||||
}
|
||||
|
||||
// ─── 4. Old Prisma migrations ─────────────────────────────────────────────────
|
||||
function scanOldMigrations() {
|
||||
const findings = [];
|
||||
// ─── Detector 7: Old Prisma migrations ───────────────────────────────────────
|
||||
function detectOldMigrations() {
|
||||
const migrationsDir = resolve(ROOT, 'prisma/migrations');
|
||||
if (!existsSync(migrationsDir)) return findings;
|
||||
if (!existsSync(migrationsDir)) return;
|
||||
const dirs = run(`ls -1 "${migrationsDir}"`).split('\n').filter(Boolean);
|
||||
for (const dir of dirs) {
|
||||
const sqlFile = `prisma/migrations/${dir}/migration.sql`;
|
||||
@@ -139,26 +289,102 @@ function scanOldMigrations() {
|
||||
if (!lastTouch) continue;
|
||||
const age = daysAgo(lastTouch);
|
||||
if (age < 365) continue;
|
||||
findings.push({
|
||||
add({
|
||||
type: 'old-migration',
|
||||
tier: 'B',
|
||||
migration: dir,
|
||||
ageDays: Math.floor(age),
|
||||
lastTouched: lastTouch.trim(),
|
||||
description: `Migration '${dir}' is ${Math.floor(age)} days old — verify it is still actively needed`,
|
||||
});
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
// ─── Main ─────────────────────────────────────────────────────────────────────
|
||||
const report = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
// ─── Detector 8: Outdated dependencies ───────────────────────────────────────
|
||||
function detectOutdatedDeps() {
|
||||
if (!existsSync(join(ROOT, 'package.json'))) return;
|
||||
const raw = run('pnpm outdated --no-color 2>/dev/null || true');
|
||||
if (!raw) return;
|
||||
const dataLines = raw
|
||||
.split('\n')
|
||||
.filter(l => l.trim() && !l.startsWith('Package') && !l.startsWith('Legend') && !l.startsWith(' '));
|
||||
for (const line of dataLines.slice(0, 12)) {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
if (cols.length < 3) continue;
|
||||
const [pkg, current, latest] = cols;
|
||||
if (!pkg || !current || !latest || current === latest) continue;
|
||||
const isMajor = current.replace(/^[^0-9]*/, '').split('.')[0] !== latest.replace(/^[^0-9]*/, '').split('.')[0];
|
||||
add({
|
||||
type: 'outdated-dep',
|
||||
tier: 'B',
|
||||
package: pkg,
|
||||
current,
|
||||
latest,
|
||||
isMajor,
|
||||
description: `${pkg}: ${current} → ${latest}${isMajor ? ' ⚠ MAJOR bump — review breaking changes before upgrading' : ''}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Run all detectors ────────────────────────────────────────────────────────
|
||||
console.log('WorldWideView GC Scan');
|
||||
console.log(`Repo: ${run('git remote get-url origin') || ROOT}`);
|
||||
console.log(`Commit: ${run('git rev-parse --short HEAD') || 'unknown'}`);
|
||||
console.log(`Thresholds: branch=${STALE_BRANCH_DAYS}d comment=${STALE_COMMENT_DAYS}d`);
|
||||
console.log('');
|
||||
|
||||
detectStaleBranches();
|
||||
console.log(` stale-branch ${findings.filter(f => f.type === 'stale-branch').length}`);
|
||||
|
||||
detectStaleTodos();
|
||||
console.log(` stale-todo ${findings.filter(f => f.type === 'stale-todo').length}`);
|
||||
|
||||
detectAntiPatterns();
|
||||
console.log(` anti-pattern ${findings.filter(f => f.type === 'anti-pattern').length}`);
|
||||
|
||||
detectOversizedFiles();
|
||||
console.log(` oversized-file ${findings.filter(f => f.type === 'oversized-file').length}`);
|
||||
|
||||
detectOrphanedRuleRefs();
|
||||
console.log(` orphaned-rule-ref ${findings.filter(f => f.type === 'orphaned-rule-ref').length}`);
|
||||
|
||||
detectOrphanedPackages();
|
||||
console.log(` orphaned-package ${findings.filter(f => f.type === 'orphaned-package').length}`);
|
||||
|
||||
detectOldMigrations();
|
||||
console.log(` old-migration ${findings.filter(f => f.type === 'old-migration').length}`);
|
||||
|
||||
detectOutdatedDeps();
|
||||
console.log(` outdated-dep ${findings.filter(f => f.type === 'outdated-dep').length}`);
|
||||
|
||||
// Deduplicate
|
||||
const seen = new Set();
|
||||
const deduped = findings.filter(f => {
|
||||
const key = [
|
||||
f.type,
|
||||
f.file ?? f.package ?? f.name ?? f.migration ?? f.branch ?? '',
|
||||
f.line ?? f.ref ?? '',
|
||||
f.patternId ?? '',
|
||||
].join(':');
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
|
||||
const output = {
|
||||
scanDate: new Date().toISOString(),
|
||||
thresholds: { STALE_BRANCH_DAYS, STALE_COMMENT_DAYS },
|
||||
findings: [
|
||||
...scanStaleBranches(),
|
||||
...scanStaleComments(),
|
||||
...scanOrphanedPackages(),
|
||||
...scanOldMigrations(),
|
||||
],
|
||||
repo: run('git remote get-url origin') || ROOT,
|
||||
commit: run('git rev-parse --short HEAD') || 'unknown',
|
||||
summary: {
|
||||
total: deduped.length,
|
||||
tierA: deduped.filter(f => f.tier === 'A').length,
|
||||
tierB: deduped.filter(f => f.tier === 'B').length,
|
||||
},
|
||||
findings: deduped,
|
||||
};
|
||||
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
writeFileSync(OUT, JSON.stringify(output, null, 2));
|
||||
console.log('');
|
||||
console.log(`Total: ${deduped.length} (Tier A: ${output.summary.tierA}, Tier B: ${output.summary.tierB})`);
|
||||
console.log(`Output: ${OUT}`);
|
||||
Reference in new issue
Block a user