@whitehatd/crag 0.0.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,32 +1,855 @@
1
1
  # crag
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/%40whitehatd%2Fcrag?color=%23e8bb3a&label=npm&logo=npm)](https://www.npmjs.com/package/@whitehatd/crag)
4
+ [![Test](https://github.com/WhitehatD/crag/actions/workflows/test.yml/badge.svg)](https://github.com/WhitehatD/crag/actions/workflows/test.yml)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
6
+ [![Node](https://img.shields.io/node/v/%40whitehatd%2Fcrag)](https://nodejs.org)
7
+ [![Zero dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)](./package.json)
8
+ [![159 tests](https://img.shields.io/badge/tests-159%20passing-brightgreen)](./test)
9
+
3
10
  **The bedrock layer for AI coding agents. One `governance.md`. Any project. Never stale.**
4
11
 
5
- > This is a name-reservation placeholder. The full tool is in active development and will ship shortly.
12
+ Write your AI agent rules once. Enforce them in **Claude Code, Cursor, Copilot, Codex, Gemini, Aider, Cline, Continue, Windsurf, Zed, and Sourcegraph Cody** — plus your CI pipeline and git hooks. From a single 20-line file.
13
+
14
+ ```bash
15
+ npx @whitehatd/crag init # Interview → generate governance
16
+ npx @whitehatd/crag analyze # Or skip the interview: infer from existing project
17
+ npx @whitehatd/crag compile --target all # Output for 12 downstream tools
18
+ ```
19
+
20
+ > **The one-sentence pitch:** Every other AI coding tool ships static config files that hardcode your project's current shape. They rot. crag ships a runtime discovery engine plus a single governance file — the engine reads the filesystem every session so it never goes stale, and the governance is your rules, not your paths.
21
+
22
+ ---
23
+
24
+ ## The 12-target pitch, visually
25
+
26
+ ```
27
+ ┌──────────────────┐
28
+ │ governance.md │ ← you maintain this (20-30 lines)
29
+ │ one file │
30
+ └────────┬─────────┘
31
+
32
+ crag compile
33
+
34
+ ┌─────────────────────┼─────────────────────┐
35
+ │ │ │
36
+ ┌─────┴──────┐ ┌─────┴──────┐ ┌─────┴──────┐
37
+ │ CI / hooks │ │ AI native │ │ AI extras │
38
+ ├────────────┤ ├────────────┤ ├────────────┤
39
+ │ GitHub CI │ │ AGENTS.md │ │ Copilot │
40
+ │ husky │ │ Cursor │ │ Cline │
41
+ │ pre-commit │ │ Gemini │ │ Continue │
42
+ └────────────┘ └────────────┘ │ Windsurf │
43
+ │ Zed │
44
+ │ Cody │
45
+ └────────────┘
46
+ ```
47
+
48
+ Change one line in `governance.md`, re-run `crag compile --target all`, and 12 downstream configs regenerate. Your rules, your CI, your git hooks, and 9 different AI coding agents all stay in lock-step from a single source.
49
+
50
+ ---
51
+
52
+ ## Why "crag"?
53
+
54
+ A crag is a rocky outcrop — an unmoving landmark that stands while seasons, paths, and generations change around it. That's exactly what this tool is. Your skills discover. Your gates run. Your CI regenerates. But `governance.md` — the crag — doesn't move until you say so. Your AI agents anchor to it.
55
+
56
+ ---
57
+
58
+ ## Proven in Production
59
+
60
+ Not on demos. On real systems, in production, shipping to real infrastructure.
61
+
62
+ | Project | Stack | Services | Deployment | Result |
63
+ |---|---|---|---|---|
64
+ | **Leyoda** | Spring Boot + Next.js 16 + Python | Monolith + signal engine | Docker blue-green, NGINX | Discovered entire stack, 215-line governance, zero skill modification |
65
+ | **MetricHost** | Spring Boot + Next.js 16 | 11 microservices | Kubernetes (k3s), Kafka, Redis | 3-level governance hierarchy (root + backend + frontend), dual-repo |
66
+ | **StructuAI** | Node + Rust + Python + Java + React | 9 Docker Compose services | Docker Compose | 5 languages detected, all gates generated from interview |
67
+ | **crag** | Node.js CLI | Single module | npm | Scaffolds itself — full dogfooding, 159 tests, zero deps |
68
+
69
+ The same universal skills — written once, never modified per project — discovered a full-stack monolith with OAuth and blue-green deploys, an 11-microservice K8s platform with Stripe billing and Kafka event buses, a 5-language polyglot with Rust decoders and Puppeteer rendering, and a Node.js CLI. Zero project-specific instructions in the skills. They discovered everything.
70
+
71
+ ---
72
+
73
+ ## The Architecture
74
+
75
+ ```
76
+ ┌──────────────────────────────────────────────────────────────┐
77
+ │ Ships with crag (universal — same for every project) │
78
+ │ │
79
+ │ ┌──────────────────────┐ ┌──────────────────────┐ │
80
+ │ │ pre-start skill │ │ post-start skill │ │
81
+ │ │ discovers ANY │ │ validates using │ │
82
+ │ │ project │ │ YOUR gates │ │
83
+ │ └──────────┬───────────┘ └──────────┬───────────┘ │
84
+ └─────────────┼───────────────────────────────┼───────────────┘
85
+ │ │
86
+ │ reads at runtime │ reads at runtime
87
+ ▼ ▼
88
+ ┌──────────────────────────────────────────────────────────────┐
89
+ │ Generated from interview or analyze (project-specific) │
90
+ │ │
91
+ │ ┌────────────────────────────────────────────┐ │
92
+ │ │ governance.md — 20-30 lines of YOUR rules │ │
93
+ │ └────────────────────────────────────────────┘ │
94
+ │ │
95
+ │ Also generated: hooks/ agents/ settings │
96
+ └──────────────────────────────────────────────────────────────┘
97
+ ```
98
+
99
+ The skills ship once and work forever. They don't know your stack — they discover it. They don't know your gates — they read them from governance.md. Add a service, change your CI, switch frameworks — the skills adapt. Nothing to update.
100
+
101
+ ### The Core Insight: Discovery vs Governance
102
+
103
+ Every other tool in this space mixes "how to find things" with "what to enforce." crag separates them cleanly:
104
+
105
+ - **Discovery** (universal skills) — reads the filesystem, detects runtimes, maps architecture, finds configs. Works on any project without modification.
106
+ - **Governance** (your `governance.md`) — defines YOUR rules: quality gates, security requirements, branch strategy, deployment pipeline. Changes only when YOU change it.
107
+
108
+ The skills handle discovery. `governance.md` handles governance. The skills never go stale because they re-discover every session. The governance never goes stale because it's your standards, not your file paths.
109
+
110
+ ---
111
+
112
+ ## Quick Start
113
+
114
+ ```bash
115
+ # Install once globally (the package is scoped; the binary name is `crag`)
116
+ npm install -g @whitehatd/crag
117
+
118
+ # Or use via npx (no install)
119
+ npx @whitehatd/crag init
120
+
121
+ # After install, all commands use the plain `crag` binary
122
+ crag init # Interview → generate governance + hooks + agents
123
+ crag analyze # Zero-interview: infer governance from existing project
124
+ crag check # Verify infrastructure
125
+ crag diff # Compare governance against codebase reality
126
+ crag upgrade # Update universal skills (with hash-based conflict detection)
127
+ crag workspace # Inspect detected workspace
128
+ crag compile --target all # Compile governance → CI, hooks, and 9 AI agent configs
129
+ crag install # Install interview agent globally for /crag-project
130
+ ```
131
+
132
+ After setup, in any Claude Code session:
133
+ ```bash
134
+ /pre-start-context # Discovers project, loads governance, ready to work
135
+ # ... do your task ...
136
+ /post-start-validation # Validates, captures knowledge, commits, deploys
137
+ ```
138
+
139
+ ---
140
+
141
+ ## User Guide
142
+
143
+ ### Installation
144
+
145
+ crag is a zero-dependency Node.js CLI. You don't need to install it — run it via `npx`:
146
+
147
+ ```bash
148
+ npx crag <command>
149
+ ```
150
+
151
+ Or install globally:
152
+ ```bash
153
+ npm install -g @whitehatd/crag
154
+ crag <command>
155
+ ```
156
+
157
+ The package is published under a scope (`@whitehatd/crag`) but the binary name remains `crag`, so after installation all commands work as `crag init`, `crag analyze`, etc.
158
+
159
+ **Requirements:**
160
+ - Node.js 18+ (uses built-in `https`, `crypto`, `fs`, `child_process`)
161
+ - Git (for branch strategy inference and discovery cache)
162
+ - Claude Code CLI (`claude --version`) — only needed for `crag init`
163
+
164
+ ### Choosing Your Entry Point
165
+
166
+ crag has two ways to generate governance for a project:
167
+
168
+ | Situation | Command | What happens |
169
+ |-----------|---------|--------------|
170
+ | New project, unsure of standards | `crag init` | Interactive interview — agent asks about your stack, quality bar, security, deployment |
171
+ | Existing project with CI/linters already configured | `crag analyze` | Zero-interview mode — reads your CI workflows, package.json scripts, linter configs, git history |
172
+ | Want to see what would be generated | `crag analyze --dry-run` | Prints inferred governance without writing |
173
+ | Already have governance, want to add inferred gates | `crag analyze --merge` | Preserves existing governance, appends inferred additions |
174
+ | Monorepo with sub-projects | `crag analyze --workspace` | Analyzes root + every workspace member |
175
+
176
+ ### Command Reference
177
+
178
+ #### `crag init` — Interactive Setup
179
+
180
+ Runs an interview agent that asks about your project, then generates all infrastructure:
181
+
182
+ ```bash
183
+ cd your-project
184
+ npx crag init
185
+ ```
186
+
187
+ **What gets generated:**
188
+ - `.claude/skills/pre-start-context/SKILL.md` — universal discovery skill
189
+ - `.claude/skills/post-start-validation/SKILL.md` — universal validation skill
190
+ - `.claude/governance.md` — your rules (from interview answers)
191
+ - `.claude/hooks/` — sandbox-guard, drift-detector, circuit-breaker, auto-post-start
192
+ - `.claude/agents/` — test-runner, security-reviewer, skill-auditor
193
+ - `.claude/settings.local.json` — permissions + hook wiring
194
+ - `.claude/ci-playbook.md` — empty template for known CI failures
195
+
196
+ After init, the skills are ready to use in any Claude Code session via `/pre-start-context`.
197
+
198
+ #### `crag analyze` — Zero-Interview Governance
199
+
200
+ Generates `governance.md` from your existing project without asking questions:
201
+
202
+ ```bash
203
+ crag analyze # Generate .claude/governance.md
204
+ crag analyze --dry-run # Preview without writing
205
+ crag analyze --workspace # Analyze all workspace members
206
+ crag analyze --merge # Merge with existing governance
207
+ ```
208
+
209
+ **What it detects:**
210
+ - **Stack:** Node, Rust, Python, Java, Go, Docker (from manifests)
211
+ - **Gates from CI:** parses `.github/workflows/*.yml` (recursively) for `run:` steps including multiline `run: |` blocks
212
+ - **Gates from scripts:** `package.json` `test`, `lint`, `build`, `format`, `typecheck`
213
+ - **Linters:** ESLint, Biome, Prettier, Ruff, Clippy, Rustfmt, Mypy, TypeScript
214
+ - **Branch strategy:** feature branches vs trunk-based (from git history)
215
+ - **Commit convention:** conventional vs free-form (from git log)
216
+ - **Deployment:** Docker, Kubernetes, Vercel, Fly.io, Netlify, Render, Terraform
217
+
218
+ Output sections marked `# Inferred` should be reviewed.
219
+
220
+ #### `crag check` — Verify Infrastructure
221
+
222
+ Lists all core and optional files, shows which are present:
223
+
224
+ ```bash
225
+ crag check
226
+ ```
227
+
228
+ Run this after `crag init` to verify everything was generated, or any time you're unsure if the setup is complete.
229
+
230
+ #### `crag compile` — Export Governance (12 targets)
231
+
232
+ Compiles your `governance.md` to multiple formats:
233
+
234
+ ```bash
235
+ # CI / git hooks
236
+ crag compile --target github # .github/workflows/gates.yml
237
+ crag compile --target husky # .husky/pre-commit
238
+ crag compile --target pre-commit # .pre-commit-config.yaml
239
+
240
+ # AI coding agents — native formats
241
+ crag compile --target agents-md # AGENTS.md (Codex, Aider, Factory)
242
+ crag compile --target cursor # .cursor/rules/governance.mdc
243
+ crag compile --target gemini # GEMINI.md
244
+
245
+ # AI coding agents — additional formats
246
+ crag compile --target copilot # .github/copilot-instructions.md
247
+ crag compile --target cline # .clinerules
248
+ crag compile --target continue # .continuerules
249
+ crag compile --target windsurf # .windsurfrules
250
+ crag compile --target zed # .zed/rules.md
251
+ crag compile --target cody # .sourcegraph/cody-instructions.md
252
+
253
+ crag compile --target all # All 12 targets at once
254
+ crag compile # List available targets
255
+ ```
256
+
257
+ **Why this matters:** one `governance.md` becomes your CI workflow, your git hooks, and configuration for **9 different AI coding agents**. Change a gate once, recompile, and every downstream tool sees the update. The generator detects Node/Python/Java/Go versions from your project files (`package.json engines.node`, `pyproject.toml requires-python`, `build.gradle.kts` toolchain, `go.mod` directive) instead of hardcoding defaults.
258
+
259
+ Gate classifications control behavior per target:
260
+ - `# [MANDATORY]` (default) — stop on failure
261
+ - `# [OPTIONAL]` — warn via `continue-on-error: true` (GitHub) or wrapper (husky/pre-commit)
262
+ - `# [ADVISORY]` — log result, never block
263
+
264
+ #### `crag diff` — Governance Drift Detection
265
+
266
+ Compares `governance.md` against codebase reality:
267
+
268
+ ```bash
269
+ crag diff
270
+ ```
271
+
272
+ ```
273
+ MATCH node --check bin/crag.js
274
+ DRIFT ESLint referenced but biome.json found
275
+ MISSING CI gate: cargo test (in governance, not in CI)
276
+ EXTRA docker build (in CI, not in governance)
277
+
278
+ 3 match, 1 drift, 1 missing, 1 extra
279
+ ```
280
+
281
+ Command alias normalization means `npm test` and `npm run test` are treated as equivalent, as are `./gradlew` and `gradlew`.
282
+
283
+ #### `crag upgrade` — Update Skills
284
+
285
+ Updates universal skills in the current project to the latest version:
286
+
287
+ ```bash
288
+ crag upgrade # Update skills in current project
289
+ crag upgrade --check # Dry run — show what would change
290
+ crag upgrade --workspace # Update all workspace members
291
+ crag upgrade --force # Overwrite locally modified skills (creates backup)
292
+ ```
293
+
294
+ **How it works:**
295
+ - Skills track their version in YAML frontmatter (`version: 0.2.1`)
296
+ - A `source_hash` (SHA-256, CRLF-normalized) detects local modifications
297
+ - If you modified a skill locally, upgrade won't overwrite it without `--force`
298
+ - When force-overwriting, a timestamped backup is created (`SKILL.md.bak.1712252400`)
299
+ - Global 24-hour cache at `~/.claude/crag/update-check.json`
300
+ - Opt-out: `CRAG_NO_UPDATE_CHECK=1`
301
+
302
+ #### `crag workspace` — Inspect Workspace
303
+
304
+ Shows the detected workspace, all members, their tech stacks, and governance hierarchy:
305
+
306
+ ```bash
307
+ crag workspace # Human-readable
308
+ crag workspace --json # Machine-readable JSON (for CI/scripting)
309
+ ```
310
+
311
+ Example output:
312
+ ```
313
+ Workspace: npm
314
+ Root: /path/to/monorepo
315
+ Config: package.json
316
+ Members: 3
317
+ Root governance: 2 gate section(s), runtimes: node
318
+
319
+ Members:
320
+ ✓ backend [node]
321
+ packages/backend
322
+ ✓ frontend [node] (inherits)
323
+ packages/frontend
324
+ ○ shared [node]
325
+ packages/shared
326
+ ```
327
+
328
+ Use this to debug workspace detection or understand governance inheritance in monorepos.
329
+
330
+ #### `crag install` — Install Global Agent
331
+
332
+ Installs the `crag-project` interview agent to `~/.claude/agents/` so you can invoke it with `/crag-project` from any Claude Code session:
333
+
334
+ ```bash
335
+ crag install
336
+ ```
337
+
338
+ #### `crag version` / `crag help`
339
+
340
+ ```bash
341
+ crag version # Print version
342
+ crag help # Print usage
343
+ ```
344
+
345
+ ### The Session Loop
346
+
347
+ Once crag is set up, your workflow in any Claude Code session becomes:
348
+
349
+ ```
350
+ 1. /pre-start-context → Discovers project, loads governance, checks skill currency
351
+ 2. ... your task ... → Write code, fix bugs, add features
352
+ 3. /post-start-validation → Runs gates, security review, captures knowledge, commits
353
+ ```
354
+
355
+ **Pre-start does:**
356
+ - Detects workspace type (pnpm, Cargo, Go, Gradle, Maven, Nx, Turbo, Bazel, submodules, nested repos)
357
+ - Enumerates members and checks for multi-level governance
358
+ - Detects runtime versions (Node, Java, Python, Go, Rust, Docker)
359
+ - Reads `governance.md` and applies rules for the session
360
+ - Loads cross-session memory (if MemStack enabled)
361
+ - Checks skill currency — notifies if `crag upgrade` available
362
+
363
+ **Post-start does:**
364
+ - Runs governance gates in order (stops on MANDATORY failure; logs OPTIONAL/ADVISORY)
365
+ - Auto-fixes mechanical errors (lint, format) with bounded retry
366
+ - Runs security review (grep for secrets, check new endpoints)
367
+ - Captures knowledge (insights, sessions) if MemStack enabled
368
+ - Commits with conventional commit format
369
+ - Writes `.session-state.json` for next session's warm start
370
+
371
+ ### Common Workflows
372
+
373
+ **Workflow 1: Add crag to an existing project**
374
+ ```bash
375
+ cd my-existing-project
376
+ npx crag analyze --dry-run # Preview what it would generate
377
+ npx crag analyze # Write .claude/governance.md
378
+ # Review the generated file, adjust as needed
379
+ npx crag check # Verify infrastructure
380
+ # Use /pre-start-context in Claude Code
381
+ ```
382
+
383
+ **Workflow 2: Start a brand new project**
384
+ ```bash
385
+ mkdir my-new-project && cd my-new-project
386
+ git init
387
+ npx crag init # Interactive interview
388
+ # Follow the prompts — agent asks ~20 questions
389
+ # Skills + hooks + agents are all generated
390
+ npx crag check
391
+ ```
6
392
 
7
- ## What crag will be
393
+ **Workflow 3: Monorepo with per-service governance**
394
+ ```bash
395
+ cd my-monorepo
396
+ npx crag workspace # See detected type + members
397
+ npx crag init # Root-level governance
398
+ cd packages/backend
399
+ npx crag analyze --merge # Add backend-specific gates
400
+ cd ../../packages/frontend
401
+ npx crag analyze --merge # Add frontend-specific gates
402
+ # Now each package has its own governance.md, and root has cross-cutting rules
403
+ ```
8
404
 
9
- crag inverts how AI coding setups work. Every AI agent today reads static config files — CLAUDE.md, AGENTS.md, Cursor rules, Gemini docs. They hardcode facts about your project. Facts change. Instructions rot.
405
+ **Workflow 4: Keep everything current**
406
+ ```bash
407
+ npx crag upgrade --check # See what would update
408
+ npx crag upgrade # Apply updates (preserves local changes)
409
+ npx crag diff # Check governance hasn't drifted
410
+ npx crag compile --target all # Regenerate CI workflows, hooks, cross-agent files
411
+ ```
10
412
 
11
- crag ships **universal skills** that discover any project at runtime any language, any framework, any deployment target — and reads your rules from a single `governance.md` file. The skills are the engine. The governance is the crag — the ancient landmark that doesn't drift while everything else changes.
413
+ **Workflow 5: Switch AI tools (Claude Cursor Gemini)**
414
+ ```bash
415
+ npx crag compile --target agents-md # Generate AGENTS.md
416
+ npx crag compile --target cursor # Generate .cursor/rules/
417
+ npx crag compile --target gemini # Generate GEMINI.md
418
+ # Same governance rules now work in Codex, Cursor, Gemini CLI, Aider, Factory
419
+ ```
12
420
 
13
- ## What's shipping
421
+ ### Troubleshooting
14
422
 
15
- - `crag init` interview-driven setup
16
- - `crag analyze` zero-interview governance generation from existing CI/scripts/git
17
- - `crag diff` — drift detection
18
- - `crag upgrade` — version-tracked skill updates
19
- - `crag workspace` — 11+ workspace type detection (pnpm, Cargo, Go, Gradle, Nx, Turbo, Bazel, submodules, nested repos)
20
- - `crag compile` — compile one governance.md to 6 targets: GitHub Actions, husky, pre-commit, AGENTS.md, Cursor, Gemini
423
+ **Q: `crag init` says "Claude Code CLI not found"**
424
+ A: Install Claude Code from https://claude.com/claude-code. Only `init` needs it; other commands don't.
21
425
 
22
- Proven in production on 4 projects (StructuAI, Leyoda, MetricHost, crag itself). 117 tests. Zero dependencies.
426
+ **Q: `crag upgrade` shows "locally modified" and won't update**
427
+ A: You edited a skill file. Either (1) accept that your edits are preserved and stay on the old version, or (2) run `crag upgrade --force` to overwrite (backup is created).
23
428
 
24
- ## Status
429
+ **Q: `crag analyze` generates nothing useful**
430
+ A: It needs signals — CI configs, `package.json` scripts, linter configs. For greenfield projects, use `crag init` for the interview flow instead.
25
431
 
26
- Name reserved on npm. Full release coming soon.
432
+ **Q: `crag diff` reports drift but my CI is working**
433
+ A: Drift means `governance.md` says one thing and the codebase uses another. Either update `governance.md` to match reality, or update the codebase to match governance. Both are valid.
27
434
 
28
- **Follow:** https://github.com/WhitehatD/crag
435
+ **Q: Skills don't auto-update when I run `/pre-start-context`**
436
+ A: Auto-update runs via the CLI commands, not the skill itself. Run `crag upgrade` from your terminal. The skill reports skill version on pre-start so you know when to run upgrade.
437
+
438
+ **Q: Multi-level governance not merging correctly**
439
+ A: Check that member governance files use `## Gates (inherit: root)` to opt in to inheritance. Without this marker, member governance replaces root.
440
+
441
+ ---
442
+
443
+ ## governance.md
444
+
445
+ The only file you maintain. 20-30 lines. Everything else is universal.
446
+
447
+ ```markdown
448
+ # Governance — StructuAI
449
+
450
+ ## Identity
451
+ - Project: StructuAI
452
+ - Description: AI-powered Minecraft schematic describer
453
+
454
+ ## Gates (run in order, stop on failure)
455
+ ### Frontend
456
+ - npx eslint frontend/ --max-warnings 0
457
+ - cd frontend && npx vite build
458
+
459
+ ### Backend
460
+ - node --check scripts/api-server.js scripts/worker.js scripts/queue.js
461
+ - cargo clippy --manifest-path source/decode/Cargo.toml
462
+ - cargo test --manifest-path source/decode/Cargo.toml
463
+
464
+ ### Infrastructure
465
+ - docker compose config --quiet
466
+
467
+ ## Branch Strategy
468
+ - Trunk-based, conventional commits
469
+ - Auto-commit after all gates pass
470
+
471
+ ## Security
472
+ - Schematic file uploads only (validate file type server-side)
473
+ - No hardcoded secrets or API keys in source
474
+ ```
475
+
476
+ Change a gate → takes effect next session. Add a security rule → enforced immediately. The skills read this file every time — they never cache stale instructions.
477
+
478
+ ### Governance v2 annotations (optional)
479
+
480
+ Gate sections support optional annotations for workspace-aware execution:
481
+
482
+ ```markdown
483
+ ## Gates (run in order, stop on failure)
484
+ ### Frontend (path: frontend/) # cd to frontend/ before running
485
+ - npx biome check . # [MANDATORY] (default)
486
+ - npx tsc --noEmit # [OPTIONAL] — warn but don't fail
487
+
488
+ ### TypeScript (if: tsconfig.json) # skip section if file doesn't exist
489
+ - npx tsc --noEmit
490
+
491
+ ### Audit
492
+ - npm audit # [ADVISORY] — informational only
493
+
494
+ ## Gates (inherit: root) # merge with root governance
495
+ ```
496
+
497
+ All annotations are optional. Existing governance files work unchanged. Classifications are honored by all compile targets (GitHub Actions `continue-on-error`, husky/pre-commit wrapper scripts).
498
+
499
+ ### Multi-level governance (monorepos)
500
+
501
+ For projects with multiple sub-repos or services, governance can be hierarchical:
502
+
503
+ ```
504
+ project-root/
505
+ ├── .claude/governance.md # Cross-stack: branch strategy, deployment, security
506
+ ├── backend/.claude/governance.md # Backend-specific: Gradle gates, service tests
507
+ └── frontend/.claude/governance.md # Frontend-specific: Biome, Vitest, responsive audit
508
+ ```
509
+
510
+ Each level gets the same universal skills. Each reads its own `governance.md`. Open Claude Code at the root — get the cross-stack view. Open it in `backend/` — get backend-specific gates. The skills adapt to wherever you are.
511
+
512
+ ---
513
+
514
+ ## Workspace Detection
515
+
516
+ crag auto-detects 11+ workspace types:
517
+
518
+ | Marker | Workspace Type |
519
+ |--------|----------------|
520
+ | `pnpm-workspace.yaml` | pnpm |
521
+ | `package.json` with `"workspaces"` | npm/yarn |
522
+ | `Cargo.toml` with `[workspace]` | Cargo |
523
+ | `go.work` | Go |
524
+ | `settings.gradle.kts` with `include(` | Gradle |
525
+ | `pom.xml` with `<modules>` | Maven |
526
+ | `nx.json` | Nx |
527
+ | `turbo.json` | Turborepo |
528
+ | `WORKSPACE` / `MODULE.bazel` | Bazel |
529
+ | `.gitmodules` | Git submodules |
530
+ | Multiple child `.git` dirs | Independent repos |
531
+
532
+ Workspace members are enumerated, checked for their own `.claude/governance.md`, and their tech stacks detected. Multi-level governance merges root gates (mandatory) with member gates (additive).
533
+
534
+ ---
535
+
536
+ ## Governance Compiler — 12 Targets
537
+
538
+ `governance.md` is agent-readable. But the gates in it are just shell commands — they can also drive your CI pipeline, git hooks, and configuration for **9 different AI coding agents**. One source of truth, twelve outputs:
539
+
540
+ ### Full target list
541
+
542
+ | Group | Target | Output path | Consumed by |
543
+ |---|---|---|---|
544
+ | **CI** | `github` | `.github/workflows/gates.yml` | GitHub Actions |
545
+ | **CI** | `husky` | `.husky/pre-commit` | husky pre-commit framework |
546
+ | **CI** | `pre-commit` | `.pre-commit-config.yaml` | pre-commit.com framework |
547
+ | **AI native** | `agents-md` | `AGENTS.md` | Codex, Aider, Factory, and any tool reading `AGENTS.md` |
548
+ | **AI native** | `cursor` | `.cursor/rules/governance.mdc` | Cursor |
549
+ | **AI native** | `gemini` | `GEMINI.md` | Google Gemini CLI |
550
+ | **AI extras** | `copilot` | `.github/copilot-instructions.md` | GitHub Copilot (VS Code, JetBrains, Visual Studio, Copilot Workspace) |
551
+ | **AI extras** | `cline` | `.clinerules` | Cline (VS Code extension) |
552
+ | **AI extras** | `continue` | `.continuerules` | Continue.dev |
553
+ | **AI extras** | `windsurf` | `.windsurfrules` | Windsurf IDE (Codeium) |
554
+ | **AI extras** | `zed` | `.zed/rules.md` | Zed Editor AI assistant |
555
+ | **AI extras** | `cody` | `.sourcegraph/cody-instructions.md` | Sourcegraph Cody |
556
+
557
+ ```bash
558
+ crag compile --target all # Generate all 12 at once
559
+ crag compile --target github # Or pick one
560
+ crag compile # Or list targets interactively
561
+ ```
562
+
563
+ The compiler parses your gates, auto-detects runtimes from the commands (Node, Rust, Python, Java, Go, Docker), and generates the right setup steps with proper version inference from your project files (not hardcoded defaults). Human-readable `Verify X contains Y` gates are compiled to `grep` commands automatically (with shell-injection-safe escaping). All 12 targets write atomically (temp file + rename) so partial failures leave the old state intact.
564
+
565
+ ```
566
+ ┌────────────────────┐
567
+ │ governance.md │
568
+ │ (one file) │
569
+ └──────────┬─────────┘
570
+
571
+ crag compile --target all
572
+
573
+ ┌─────────────────────────┼─────────────────────────┐
574
+ │ │ │
575
+ ▼ ▼ ▼
576
+ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
577
+ │ CI / hooks │ │ AI native │ │ AI extras │
578
+ ├─────────────┤ ├─────────────┤ ├─────────────┤
579
+ │ gates.yml │ │ AGENTS.md │ │ Copilot │
580
+ │ husky │ │ Cursor MDC │ │ Cline │
581
+ │ pre-commit │ │ GEMINI.md │ │ Continue │
582
+ └─────────────┘ └─────────────┘ │ Windsurf │
583
+ │ Zed │
584
+ │ Cody │
585
+ └─────────────┘
586
+
587
+ + read at runtime by
588
+ universal skills
589
+ (pre-start / post-start)
590
+ ```
591
+
592
+ Governance-as-config that compiles to agent behavior, CI/CD pipelines, and **9 different AI coding tool configs** from a single 20-line file.
593
+
594
+ ---
595
+
596
+ ## Zero-Interview Mode
597
+
598
+ Don't want an interview? `crag analyze` generates governance from your existing project:
599
+
600
+ ```bash
601
+ crag analyze # Infer governance from codebase + CI
602
+ crag analyze --dry-run # Preview without writing
603
+ crag analyze --workspace # Analyze all workspace members
604
+ crag analyze --merge # Merge with existing governance
605
+ ```
606
+
607
+ It reads your CI workflows (recursively, handling `run: |` multiline blocks), `package.json` scripts, linter configs, git history, and deployment configs. Outputs `governance.md` with `# Inferred` markers so you know what to verify.
608
+
609
+ ---
610
+
611
+ ## Governance Drift Detection
612
+
613
+ `crag diff` compares your `governance.md` against codebase reality:
614
+
615
+ ```bash
616
+ crag diff
617
+ ```
618
+
619
+ ```
620
+ MATCH node --check bin/crag.js (tool exists)
621
+ DRIFT ESLint referenced but biome.json found
622
+ MISSING CI gate: cargo test (in governance, not in CI)
623
+ EXTRA CI step: docker build (in CI, not in governance)
624
+
625
+ 3 match, 1 drift, 1 missing, 1 extra
626
+ ```
627
+
628
+ ---
629
+
630
+ ## Auto-Update
631
+
632
+ Skills track their version in YAML frontmatter. When you run any crag command, it checks for updates:
633
+
634
+ ```bash
635
+ crag upgrade # Update skills in current project
636
+ crag upgrade --workspace # Update all workspace members
637
+ crag upgrade --check # Dry run — show what would change
638
+ crag upgrade --force # Overwrite locally modified skills (with backup)
639
+ ```
640
+
641
+ The update checker queries the npm registry (cached for 24 hours, 3s timeout, graceful failure offline). Skills are only overwritten if the user hasn't modified them — local modifications are detected via SHA-256 content hash (CRLF-normalized for cross-platform consistency) and preserved unless `--force` is used.
642
+
643
+ ---
644
+
645
+ ## What Ships vs What's Generated
646
+
647
+ | Component | Source | Maintains itself? |
648
+ |-----------|--------|-------------------|
649
+ | Pre-start skill | **Ships universal** | Yes — discovers at runtime, caches results, auto-updates |
650
+ | Post-start skill | **Ships universal** | Yes — reads governance for gates, auto-fixes, auto-updates |
651
+ | `governance.md` | **Generated from interview or analyze** | No — you maintain it (20-30 lines) |
652
+ | Hooks | **Generated for your tools** | Yes — sandbox guard + drift detector + gate enforcement |
653
+ | Agents | **Generated for your stack** | Yes — read governance for commands |
654
+ | Settings | **Generated** | Yes — RTK wildcards cover new tools |
655
+ | CI playbook | **Generated template** | You add entries as failures are found |
656
+ | Compile targets | **Generated on demand** | `crag compile` regenerates from governance (12 targets) |
657
+ | Workspace detection | **Ships universal** | Yes — detects 11+ workspace types at runtime |
658
+ | Governance diff | **Ships universal** | Yes — compares governance vs codebase reality |
659
+
660
+ ---
661
+
662
+ ## Why Everything Else Is Static
663
+
664
+ | Current ecosystem | Why it rots | crag's approach |
665
+ |-------------------------------------------|--------------------------------------|------------------------------------------------|
666
+ | **CLAUDE.md / AGENTS.md** static files | Hardcode project facts; manual edits | **Universal skills** read filesystem every session — always current |
667
+ | **Skill collections** (1,234+ skills) | Pick-per-project; stack mismatch | **One engine** that works for any stack |
668
+ | **Per-framework templates** | One stack per template; rot on change | **`governance.md`** — 20–30 lines of YOUR rules only, human-controlled |
669
+
670
+ **The difference:** everything else tries to pack facts INTO config files. crag reads facts FROM the filesystem at runtime. The skills don't know your stack — they discover it. The governance doesn't know your paths — it holds your rules.
671
+
672
+ ---
673
+
674
+ ## The Session Loop
675
+
676
+ ```
677
+ ┌────────────────────────────────────────────────────────────────┐
678
+ │ PRE-START (universal skill — runs before every task) │
679
+ │ │
680
+ │ Warm start? Intent? Cache valid? │
681
+ │ .session-state.json → classify → .discovery-cache.json │
682
+ │ │ │ │ │
683
+ │ │ │ ┌───────┴───────┐ │
684
+ │ │ │ ▼ ▼ │
685
+ │ │ │ Fast path Full discovery │
686
+ │ │ │ (skip 80%) (detect stack, │
687
+ │ │ │ │ load memory) │
688
+ │ └────────────────┴──────────┴───────────────┘ │
689
+ │ │ │
690
+ │ ▼ │
691
+ │ Read governance.md │
692
+ └───────────────────────────────┬────────────────────────────────┘
693
+
694
+
695
+ ┌──────────────────┐
696
+ │ YOUR TASK │
697
+ │ (code changes) │
698
+ └────────┬─────────┘
699
+
700
+
701
+ ┌────────────────────────────────────────────────────────────────┐
702
+ │ POST-START (universal skill — runs after every task) │
703
+ │ │
704
+ │ Detect changes → Run gates → (fail?) → Auto-fix → retry │
705
+ │ │ │
706
+ │ pass │
707
+ │ ▼ │
708
+ │ Security review → Capture knowledge │
709
+ │ │ │
710
+ │ ▼ │
711
+ │ Write session state · Commit │
712
+ └────────────────────────────────┬───────────────────────────────┘
713
+
714
+ │ cache + state + knowledge
715
+ └─────► feeds next session
716
+ ```
717
+
718
+ ### What makes this loop tight
719
+
720
+ | Feature | What it does | Savings |
721
+ |---|---|---|
722
+ | **Discovery cache** | Hashes build files, skips unchanged domains | ~80% of pre-start tool calls on unchanged projects |
723
+ | **Intent-scoped discovery** | Classifies task, skips irrelevant domains | Skip frontend discovery for backend bugs, and vice versa |
724
+ | **Session continuity** | Reads `.session-state.json` for warm starts | Near-zero-latency startup when continuing work |
725
+ | **Gate auto-fix** | Fixes lint/format errors, retries gate (max 2x) | Eliminates human round-trip for mechanical failures |
726
+ | **Auto-post-start** | Hook warns before commit if gates haven't run | Removes "forgot to validate" failure mode |
727
+ | **Sandbox guard** | Hard-blocks destructive commands at hook level | Security at system level, not instruction level |
728
+ | **Workspace detection** | Detects 11+ workspace types, enumerates members | Automatic monorepo/polyrepo awareness |
729
+ | **Auto-update** | Version-tracked skills with hash-based conflict detection | Skills stay current across all projects |
730
+ | **Governance diff** | Compares `governance.md` against actual codebase | Catches drift before it causes failures |
731
+
732
+ No agent framework does all of these. Most re-discover cold every session, require manual validation, and trust instructions for safety.
733
+
734
+ ---
735
+
736
+ ## Generated Infrastructure
737
+
738
+ ```
739
+ .claude/
740
+ ├── governance.md # YOUR rules (only custom file)
741
+ ├── skills/
742
+ │ ├── pre-start-context/SKILL.md # Universal discoverer
743
+ │ └── post-start-validation/SKILL.md # Universal validator
744
+ ├── hooks/
745
+ │ ├── sandbox-guard.sh # Hard-blocks destructive commands
746
+ │ ├── auto-post-start.sh # Gate enforcement before commits
747
+ │ ├── drift-detector.sh # Checks key files exist
748
+ │ ├── circuit-breaker.sh # Failure loop detection
749
+ │ ├── pre-compact-snapshot.sh # Memory before compaction
750
+ │ └── post-compact-recovery.sh # Memory after compaction
751
+ ├── agents/
752
+ │ ├── test-runner.md # Parallel tests (Sonnet)
753
+ │ ├── security-reviewer.md # Security audit (Opus)
754
+ │ ├── dependency-scanner.md # Vulnerability scan
755
+ │ └── skill-auditor.md # Infrastructure audit
756
+ ├── rules/ # Cross-session memory
757
+ ├── ci-playbook.md # Known CI failures
758
+ ├── .session-name # Notification routing
759
+ ├── .discovery-cache.json # Cached discovery (auto-generated)
760
+ ├── .session-state.json # Session continuity (auto-generated)
761
+ ├── .gates-passed # Gate sentinel (auto-generated)
762
+ └── settings.local.json # Hooks + permissions
763
+ ```
764
+
765
+ ---
766
+
767
+ ## Principles
768
+
769
+ 1. **Discover, don't hardcode.** Every fact about the codebase is read at runtime. The skills never say "22 controllers" — they say "read the controller directory."
770
+
771
+ 2. **Govern, don't hope.** Your quality bar lives in `governance.md`. The skills enforce it but never modify it. It changes only when you change it.
772
+
773
+ 3. **Ship the engine, generate the config.** Universal skills ship once. `governance.md` is generated per-project. The engine works forever. The config is 20 lines.
774
+
775
+ 4. **Enforce, don't instruct.** Hooks are 100% reliable at zero token cost. CLAUDE.md rules are ~80% compliance. Critical behavior goes in hooks.
776
+
777
+ 5. **Compound, don't restart.** Cross-session memory means each session knows what the last one learned. Knowledge self-verifies against source files.
778
+
779
+ 6. **Guard, don't trust.** Security hooks hard-block destructive commands at the system level — `rm -rf /`, `DROP TABLE`, `curl|bash`, force-push to main. Even if instructions are misread, the sandbox catches it. Defense in depth: hooks enforce what skills instruct.
780
+
781
+ 7. **Cache, don't re-discover.** Every discovery result is cached with content hashes. If nothing changed, the next session starts in seconds, not minutes. The cache is advisory — if it's wrong, full discovery runs as normal.
782
+
783
+ ---
784
+
785
+ ## Prior Art
786
+
787
+ An independent review assessed every major AI coding tool, open-source project, academic paper, and patent filing as of April 2026. The closest candidates and why they differ:
788
+
789
+ | Candidate | What it does | Why it's not this |
790
+ |---|---|---|
791
+ | **AGENTS.md** (60K+ repos) | Static config file AI agents read | Human-maintained, multiple files by scope, no runtime discovery |
792
+ | **Claude Code** `/init` + CLAUDE.md | Scans repo, generates static instructions | Generates static output that rots. Multiple files. No governance separation |
793
+ | **Cursor** `.cursor/rules/` | Per-directory rule files | Static context, multiple artifacts, no universal engine |
794
+ | **Gemini CLI** GEMINI.md hierarchy | JIT instruction file scanning | Discovers *instruction files*, not the project itself |
795
+ | **Kiro** steering docs | Generates product/tech/structure docs | Multiple steering files, not single governance, not universal |
796
+ | **Codex** AGENTS.md + hooks + skills | Layered static instructions + extensibility | Instruction chain by directory. Could host this engine but doesn't ship one |
797
+ | **claude-code-kit** | Framework detection + generated .claude/ | Kit/framework-specific (Next.js, React, Express). Not universal polyglot |
798
+ | **OpenDev** (arxiv paper) | CLI agent with lazy tool discovery | Research prototype. No governance file. Not productized |
799
+ | **Repo2Run** (arxiv paper) | Repo → runnable Dockerfile synthesis | Build/CI domain only. No agent governance architecture |
800
+
801
+ **Adjacent patents identified:**
802
+ - **US20250291583A1** (Microsoft) — YAML-configured agent rules/actions. Covers "config file drives AI agents" broadly but not universal repo discovery.
803
+ - **US9898393B2** (Solano Labs) — Repo pattern analysis → inferred CI config. Strong historic prior art for build-system discovery, but not AI agent governance.
804
+
805
+ Neither patent blocks this architecture. Both are adjacent, not overlapping.
806
+
807
+ **Three novelty hypotheses validated by the review:**
808
+ 1. **Compositional:** Many systems have pieces (hooks, skills, context files). None compose them into universal discovery engine + single governance file + continuously regenerated artifacts.
809
+ 2. **Scope:** Closest implementations (claude-code-kit) are framework-specific, not polyglot-universal.
810
+ 3. **Governance-as-contract:** Existing tools treat instruction files as context (often non-enforced). This treats governance as an executable contract that deterministically shapes gates and commit behavior.
811
+
812
+ ---
813
+
814
+ ## Roadmap
815
+
816
+ - [x] Universal pre-start and post-start skills
817
+ - [x] Interview-driven governance generation
818
+ - [x] CLI (`crag init`, `crag check`, `crag install`)
819
+ - [x] Proven on 5-language multi-service project (StructuAI)
820
+ - [x] Proven on full-stack monolith with blue-green deploys (Leyoda)
821
+ - [x] Proven on 11-microservice K8s platform with dual-repo governance (MetricHost)
822
+ - [x] Multi-level governance hierarchy (root + backend + frontend)
823
+ - [x] `crag compile` — governance.md → GitHub Actions, husky, pre-commit, AGENTS.md, Cursor, Gemini
824
+ - [x] Incremental discovery cache — content-addressed, skips 80% of pre-start on unchanged projects
825
+ - [x] Intent-scoped discovery — classifies task, skips irrelevant domains
826
+ - [x] Session continuity — warm starts via `.session-state.json`
827
+ - [x] Gate auto-fix loop — fixes lint/format errors automatically, bounded retry (max 2x)
828
+ - [x] Auto-post-start hook — gate enforcement before commits
829
+ - [x] Sandbox guard — hard-blocks destructive commands (rm -rf /, DROP TABLE, curl|bash, force-push main)
830
+ - [x] `crag analyze` — generate governance from existing project without interview
831
+ - [x] `crag diff` — compare governance against codebase reality
832
+ - [x] `crag upgrade` — update universal skills when new version ships
833
+ - [x] `crag workspace` — inspect detected workspace type and members
834
+ - [x] Workspace detection — 11+ types (pnpm, npm, Cargo, Go, Gradle, Maven, Nx, Turbo, Bazel, submodules, nested repos)
835
+ - [x] Governance v2 format — path-scoped gates, conditional sections, mandatory/optional/advisory classification
836
+ - [x] Auto-update — version tracking, npm registry check, content-hash conflict detection
837
+ - [x] Cross-agent compilation — **12 targets** (GitHub Actions, husky, pre-commit, AGENTS.md, Cursor, Gemini, Copilot, Cline, Continue, Windsurf, Zed, Sourcegraph Cody)
838
+ - [x] Modular architecture — 24 modules across 6 directories (zero dependencies)
839
+ - [x] Test suite — 159 tests covering parse, integrity, detect, enumerate, merge, compile, version, shell, CLI, 6 new compile targets, analyze internals, diff internals
840
+ - [x] Published on npm as `@whitehatd/crag`
841
+ - [x] GitHub Actions CI/CD — multi-OS (Ubuntu/macOS/Windows) × multi-Node (18/20/22) test matrix, automated npm publish with SLSA provenance, stale issue cleanup
842
+ - [ ] Cross-repo benchmark — 20-30 repos, measure coverage %, false positives, failure modes
843
+ - [ ] Drift resilience test — add services, change linters, rename directories. Does the engine re-discover?
844
+ - [ ] Baseline comparison — same governance in AGENTS.md, CLAUDE.md, .cursor/rules, GEMINI.md
845
+ - [ ] crag Cloud (paid tier) — hosted governance registry, cross-repo dashboard, team library, compliance templates, drift alerts
846
+
847
+ ---
29
848
 
30
849
  ## License
31
850
 
32
851
  MIT
852
+
853
+ ---
854
+
855
+ *Built by [Alexandru Cioc (WhitehatD)](https://github.com/WhitehatD)*