Enterprise Discover — Deep Stack Learning Agent
You are profiling a codebase you have never seen before. Your job: produce structured JSON profiles that tell every downstream enterprise skill exactly where things live, how to run tests, what conventions to follow, and what landmines to avoid.
This skill exists because hardcoded paths kill portability. When enterprise-build assumes npx jest and the project uses pytest, the pipeline breaks. Discovery eliminates these assumptions.
WHEN TO TRIGGER
- Always: as Stage 0 of
/enterprise on any project without existing profile JSONs
- Always: when switching to a new codebase or monorepo package
- Always: when a downstream skill fails due to wrong paths, wrong test commands, or wrong conventions
- On demand:
/enterprise-discover standalone
- Incremental: when profile exists but
profiled_commit != HEAD — only re-run affected phases
OUTPUT FILES
All files written to .claude/enterprise-state/:
| File |
Purpose |
stack-profile.json |
Structure, commands, conventions — the primary config |
stack-traps.json |
Type/schema/convention traps that will break code |
stack-best-practices.json |
Framework-specific guidance from web research |
project-profile.md |
Human-readable summary (generated FROM stack-profile.json) |
Schema reference: references/stack-profile-schema.md
INCREMENTAL MODE
When .claude/enterprise-state/stack-profile.json exists:
- Read
profiled_commit from the JSON
- Compare:
git diff --stat <profiled_commit>...HEAD
- If no changes: SKIP — announce "Profile is current" and exit
- Classify what changed:
- New dependencies (package.json, Gemfile, etc.) → re-run Phase 1 + Phase 2-G
- New migrations or schema changes → re-run Phase 2-E, 2-F
- New source files only → re-run Phase 2-D (auth patterns check)
- Config file changes → re-run Phase 1
- Merge updates into existing JSON — preserve manually-added traps in
stack-traps.json
- Update
profiled_commit and profiled_at
PIPELINE: 5 PHASES
Phase 1: SCAN (3 parallel agents)
Launch three agents simultaneously:
Agent A — Stack Detection:
- Check for stack indicator files at project root and one level down:
package.json → Node.js (check dependencies for framework: express, fastify, koa, next, nest)
Gemfile → Ruby (check for rails, sinatra)
requirements.txt / pyproject.toml / setup.py → Python (check for django, flask, fastapi)
go.mod → Go
Cargo.toml → Rust
pom.xml / build.gradle → Java/Kotlin
composer.json → PHP (check for laravel, symfony)
mix.exs → Elixir
*.csproj / *.sln → C#/.NET
- Detect monorepo tool:
turbo.json, nx.json, lerna.json, pnpm-workspace.yaml, workspaces in package.json
- Detect package manager from lockfiles:
package-lock.json (npm), yarn.lock (yarn), pnpm-lock.yaml (pnpm), bun.lockb (bun)
- Record:
stack.*, workspace_packages[]
Agent B — Directory Mapping + Conventions:
- Map directory structure:
ls on root, each workspace package
- Identify source dirs, test dirs, migration dirs, config files, entry points
- Sample 5+ source files from main source directory:
- Naming convention (camelCase, snake_case, PascalCase)
- Import style (CommonJS require, ES modules import, path aliases)
- Error handling pattern (custom classes, try/catch, Result types)
- Logger (console, winston, pino, structlog, slog)
- Service pattern (class-based, function exports, modules)
- Scan 5 largest source files for de facto size limits
- Catalog config files: linting, TypeScript, testing, CI/CD, env, editor, project instructions
- Record:
structure.*, conventions.*
Agent C — Git Analysis:
git remote -v → remote type (github, gitlab, bitbucket)
git branch -a → all branches, detect default and protected
git log --oneline -10 → recent commit style (conventional, free-form, ticket-prefixed)
- Check CLAUDE.md/AGENTS.md for branch rules
- Record:
git.*
Phase 2: DEEP ANALYZE (4 parallel agents, needs Phase 1 results)
Agent D — Auth Pattern Detection:
# Search for auth patterns across the codebase
grep -rn "middleware.*auth\|authenticate\|requireAuth\|@login_required\|permission_classes\|before_action.*authenticate\|Authorization.*header" $SOURCE_DIR --include="*.$EXT" -l
- Identify middleware name, file path, user object, user fields
- Check route registration for auth middleware application pattern
- Check for public-before-auth route ordering
- Record:
auth.*, routes.*
Agent E — Multi-Tenancy Detection:
# Search for tenant isolation patterns
grep -rn "tenant_id\|organization_id\|org_id\|account_id\|workspace_id\|team_id" $SOURCE_DIR --include="*.$EXT"
# Check for RLS policies
grep -rn "CREATE POLICY\|ROW LEVEL SECURITY" $MIGRATION_DIR --include="*.sql"
- Identify tenant field name, enforcement mechanism
- Find exceptions (tables without tenant scoping)
- Record:
multi_tenancy.*
Agent F — Type/Schema Trap Detection:
- Read migration files to catalog all tables and column types
- Cross-reference foreign keys: check type consistency (UUID vs integer, text vs varchar)
- Check for timestamp columns using TIMESTAMP instead of TIMESTAMPTZ
- Check for naming inconsistencies across tables
- Record:
stack-traps.json entries
Agent G — Test Infrastructure Verification:
# Verify test framework is installed and configured
$TEST_FRAMEWORK --version
# Check test config files exist
ls jest.config* vitest.config* pytest.ini .rspec 2>/dev/null
# Run a quick test to confirm the command works
$TEST_CMD --listTests 2>/dev/null | head -5
- Detect test framework, config, naming patterns
- Verify test command actually works (dry run)
- Detect coverage configuration
- Record:
commands.test_*, structure.test_dirs.*
Phase 3: RESEARCH (web search, needs Phase 1 results)
Search for current best practices for the detected stack:
Search: "[framework] [version] best practices [current year]"
Search: "[test framework] configuration patterns [current year]"
Search: "[database] migration best practices"
Search: "[framework] security checklist"
Synthesize findings into stack-best-practices.json with:
- Category (testing, security, database, error_handling, performance, deployment)
- Practice description
- Rationale
- Source
Skip if: web search is unavailable or rate-limited. The pipeline works without best practices.
Phase 4: SYNTHESIZE
- Merge all agent results into
stack-profile.json
- Generate
stack-traps.json from Phase 2-F findings
- Generate
stack-best-practices.json from Phase 3 findings
- Validate: run the test command once to confirm it works
# Validation: does the test command actually run?
$TEST_CMD 2>&1 | tail -5
If test command fails: flag as "test_command_verified": false in profile
- Generate
project-profile.md from stack-profile.json (human-readable)
Phase 5: PRESENT
- Print summary — stack, key commands, notable conventions, trap count
- Flag unknowns — any section that could not be determined. Do not guess.
- Flag conflicts — if discovered conventions conflict with CLAUDE.md instructions, flag both. CLAUDE.md wins.
- Save to memory — if a memory backend is available, save profile summary
- Hand off — if invoked as Stage 0 of
/enterprise, proceed to TRIAGE. If standalone, stop.
PROJECT PROFILE TEMPLATE (generated from JSON)
# Project Profile
<!-- Generated by /enterprise-discover from stack-profile.json -->
<!-- profiled_commit: [GIT_SHA] -->
<!-- profiled_at: [ISO_DATE] -->
## Stack
- **Language**: [stack.language]
- **Framework**: [stack.framework] [stack.framework_version]
- **Runtime**: [stack.runtime] [stack.runtime_version]
- **Package manager**: [stack.package_manager]
- **Monorepo**: [stack.monorepo_tool or "no"]
## Structure
- **Backend source**: [structure.source_dirs.backend]
- **Frontend source**: [structure.source_dirs.frontend or "none"]
- **Test dirs**: [structure.test_dirs.*]
- **Migration dir**: [structure.migration_dir]
## Commands
- **Test (all)**: `[commands.test_all]`
- **Test (single)**: `[commands.test_single]`
- **Build**: `[commands.build_frontend or "none"]`
- **Lint**: `[commands.lint or "none"]`
## Auth
- **Middleware**: `[auth.middleware_name]` at `[auth.middleware_path]`
- **User object**: `[auth.user_object]`
- **Pattern**: [auth.pattern]
## Multi-Tenancy
- **Enabled**: [multi_tenancy.enabled]
- **Field**: `[multi_tenancy.field]`
- **Enforcement**: [multi_tenancy.enforcement]
- **Exceptions**: [multi_tenancy.exceptions]
## Database
- **Type**: [database.type]
- **ORM**: [database.orm]
- **Migrations**: [database.migration_system]
## Conventions
- **File naming**: [conventions.file_naming]
- **Import style**: [conventions.import_style]
- **File extensions**: [conventions.file_extensions]
- **File size limits**: soft [conventions.file_size_soft_limit], hard [conventions.file_size_hard_limit]
## Git
- **Default branch**: [git.default_branch]
- **Protected**: [git.protected_branches]
- **Commit style**: [git.commit_style]
## Traps (from stack-traps.json)
[List each trap with severity and description]
## Workspace Packages (monorepo only)
| Package | Path | Purpose |
|---------|------|---------|
[workspace_packages entries]
USAGE BY DOWNSTREAM SKILLS
Stack Resolution Preamble (copy into each skill)
Every enterprise skill must read the profile at start:
## STACK RESOLUTION
Read `.claude/enterprise-state/stack-profile.json` at skill start.
Extract variables:
$TEST_CMD = commands.test_all
$TEST_SINGLE = commands.test_single
$SOURCE_DIR = structure.source_dirs.backend
$FRONTEND_DIR = structure.source_dirs.frontend
$BUILD_CMD = commands.build_frontend
$TEST_FRAMEWORK = commands.test_framework
$AUTH_MIDDLEWARE = auth.middleware_name
$TENANT_FIELD = multi_tenancy.field
$TENANT_ENABLED = multi_tenancy.enabled
$FILE_EXTENSIONS = conventions.file_extensions
$BRANCH_MAIN = git.default_branch
If no profile exists: BLOCKED — run /enterprise-discover first.
Conditional Blocks
# Only if multi-tenancy is enabled
if $TENANT_ENABLED:
verify every INSERT includes $TENANT_FIELD
verify every SELECT scopes by $TENANT_FIELD
# Only if auth middleware exists
if $AUTH_MIDDLEWARE != "":
verify protected routes use $AUTH_MIDDLEWARE
# Only if frontend exists
if $FRONTEND_DIR != "":
run $BUILD_CMD to verify build
1---2name: enterprise-discover3description: Deep codebase learning agent. Run FIRST on any new project, any new worktree, or whenever hardcoded paths break. Produces stack-profile.json, stack-traps.json, and stack-best-practices.json that all enterprise-* skills consume. Supports incremental mode — only re-scans what changed since last profile. Without this, the pipeline guesses — and guesses wrong.4---5
6# Enterprise Discover — Deep Stack Learning Agent
7
8You are profiling a codebase you have never seen before. Your job: produce structured JSON profiles that tell every downstream enterprise skill exactly where things live, how to run tests, what conventions to follow, and what landmines to avoid.
9
10This skill exists because hardcoded paths kill portability. When enterprise-build assumes `npx jest` and the project uses `pytest`, the pipeline breaks. Discovery eliminates these assumptions.
11
12---
13
14## WHEN TO TRIGGER
15
16- **Always**: as Stage 0 of `/enterprise` on any project without existing profile JSONs
17- **Always**: when switching to a new codebase or monorepo package
18- **Always**: when a downstream skill fails due to wrong paths, wrong test commands, or wrong conventions
19- **On demand**: `/enterprise-discover` standalone
20- **Incremental**: when profile exists but `profiled_commit != HEAD` — only re-run affected phases
21
22---
23
24## OUTPUT FILES
25
26All files written to `.claude/enterprise-state/`:
27
28| File | Purpose |
29|------|---------|
30| `stack-profile.json` | Structure, commands, conventions — the primary config |
31| `stack-traps.json` | Type/schema/convention traps that will break code |
32| `stack-best-practices.json` | Framework-specific guidance from web research |
33| `project-profile.md` | Human-readable summary (generated FROM stack-profile.json) |
34
35Schema reference: `references/stack-profile-schema.md`
36
37---
38
39## INCREMENTAL MODE
40
41When `.claude/enterprise-state/stack-profile.json` exists:
42
431. Read `profiled_commit` from the JSON
442. Compare: `git diff --stat <profiled_commit>...HEAD`
453. If no changes: **SKIP** — announce "Profile is current" and exit
464. Classify what changed:
47 - New dependencies (package.json, Gemfile, etc.) → re-run Phase 1 + Phase 2-G
48 - New migrations or schema changes → re-run Phase 2-E, 2-F
49 - New source files only → re-run Phase 2-D (auth patterns check)
50 - Config file changes → re-run Phase 1
515. Merge updates into existing JSON — preserve manually-added traps in `stack-traps.json`
526. Update `profiled_commit` and `profiled_at`
53
54---
55
56## PIPELINE: 5 PHASES
57
58### Phase 1: SCAN (3 parallel agents)
59
60Launch three agents simultaneously:
61
62**Agent A — Stack Detection:**
63- Check for stack indicator files at project root and one level down:
64 - `package.json` → Node.js (check `dependencies` for framework: express, fastify, koa, next, nest)
65 - `Gemfile` → Ruby (check for rails, sinatra)
66 - `requirements.txt` / `pyproject.toml` / `setup.py` → Python (check for django, flask, fastapi)
67 - `go.mod` → Go
68 - `Cargo.toml` → Rust
69 - `pom.xml` / `build.gradle` → Java/Kotlin
70 - `composer.json` → PHP (check for laravel, symfony)
71 - `mix.exs` → Elixir
72 - `*.csproj` / `*.sln` → C#/.NET
73- Detect monorepo tool: `turbo.json`, `nx.json`, `lerna.json`, `pnpm-workspace.yaml`, `workspaces` in package.json
74- Detect package manager from lockfiles: `package-lock.json` (npm), `yarn.lock` (yarn), `pnpm-lock.yaml` (pnpm), `bun.lockb` (bun)
75- Record: `stack.*`, `workspace_packages[]`
76
77**Agent B — Directory Mapping + Conventions:**
78- Map directory structure: `ls` on root, each workspace package
79- Identify source dirs, test dirs, migration dirs, config files, entry points
80- Sample 5+ source files from main source directory:
81 - Naming convention (camelCase, snake_case, PascalCase)
82 - Import style (CommonJS require, ES modules import, path aliases)
83 - Error handling pattern (custom classes, try/catch, Result types)
84 - Logger (console, winston, pino, structlog, slog)
85 - Service pattern (class-based, function exports, modules)
86 - Scan 5 largest source files for de facto size limits
87- Catalog config files: linting, TypeScript, testing, CI/CD, env, editor, project instructions
88- Record: `structure.*`, `conventions.*`
89
90**Agent C — Git Analysis:**
91- `git remote -v` → remote type (github, gitlab, bitbucket)
92- `git branch -a` → all branches, detect default and protected
93- `git log --oneline -10` → recent commit style (conventional, free-form, ticket-prefixed)
94- Check CLAUDE.md/AGENTS.md for branch rules
95- Record: `git.*`
96
97### Phase 2: DEEP ANALYZE (4 parallel agents, needs Phase 1 results)
98
99**Agent D — Auth Pattern Detection:**
100```bash
101# Search for auth patterns across the codebase
102grep -rn "middleware.*auth\|authenticate\|requireAuth\|@login_required\|permission_classes\|before_action.*authenticate\|Authorization.*header" $SOURCE_DIR --include="*.$EXT" -l
103```
104- Identify middleware name, file path, user object, user fields
105- Check route registration for auth middleware application pattern
106- Check for public-before-auth route ordering
107- Record: `auth.*`, `routes.*`
108
109**Agent E — Multi-Tenancy Detection:**
110```bash
111# Search for tenant isolation patterns
112grep -rn "tenant_id\|organization_id\|org_id\|account_id\|workspace_id\|team_id" $SOURCE_DIR --include="*.$EXT"
113# Check for RLS policies
114grep -rn "CREATE POLICY\|ROW LEVEL SECURITY" $MIGRATION_DIR --include="*.sql"
115```
116- Identify tenant field name, enforcement mechanism
117- Find exceptions (tables without tenant scoping)
118- Record: `multi_tenancy.*`
119
120**Agent F — Type/Schema Trap Detection:**
121- Read migration files to catalog all tables and column types
122- Cross-reference foreign keys: check type consistency (UUID vs integer, text vs varchar)
123- Check for timestamp columns using TIMESTAMP instead of TIMESTAMPTZ
124- Check for naming inconsistencies across tables
125- Record: `stack-traps.json` entries
126
127**Agent G — Test Infrastructure Verification:**
128```bash
129# Verify test framework is installed and configured
130$TEST_FRAMEWORK --version
131# Check test config files exist
132ls jest.config* vitest.config* pytest.ini .rspec 2>/dev/null
133# Run a quick test to confirm the command works
134$TEST_CMD --listTests 2>/dev/null | head -5
135```
136- Detect test framework, config, naming patterns
137- Verify test command actually works (dry run)
138- Detect coverage configuration
139- Record: `commands.test_*`, `structure.test_dirs.*`
140
141### Phase 3: RESEARCH (web search, needs Phase 1 results)
142
143Search for current best practices for the detected stack:
144
145```
146Search: "[framework] [version] best practices [current year]"
147Search: "[test framework] configuration patterns [current year]"
148Search: "[database] migration best practices"
149Search: "[framework] security checklist"
150```
151
152Synthesize findings into `stack-best-practices.json` with:
153- Category (testing, security, database, error_handling, performance, deployment)
154- Practice description
155- Rationale
156- Source
157
158**Skip if**: web search is unavailable or rate-limited. The pipeline works without best practices.
159
160### Phase 4: SYNTHESIZE
161
1621. Merge all agent results into `stack-profile.json`
1632. Generate `stack-traps.json` from Phase 2-F findings
1643. Generate `stack-best-practices.json` from Phase 3 findings
1654. Validate: run the test command once to confirm it works
166 ```bash
167 # Validation: does the test command actually run?
168 $TEST_CMD 2>&1 | tail -5
169 ```
170 If test command fails: flag as `"test_command_verified": false` in profile
1715. Generate `project-profile.md` from `stack-profile.json` (human-readable)
172
173### Phase 5: PRESENT
174
1751. **Print summary** — stack, key commands, notable conventions, trap count
1762. **Flag unknowns** — any section that could not be determined. Do not guess.
1773. **Flag conflicts** — if discovered conventions conflict with CLAUDE.md instructions, flag both. CLAUDE.md wins.
1784. **Save to memory** — if a memory backend is available, save profile summary
1795. **Hand off** — if invoked as Stage 0 of `/enterprise`, proceed to TRIAGE. If standalone, stop.
180
181---
182
183## PROJECT PROFILE TEMPLATE (generated from JSON)
184
185```markdown
186# Project Profile
187<!-- Generated by /enterprise-discover from stack-profile.json -->
188<!-- profiled_commit: [GIT_SHA] -->
189<!-- profiled_at: [ISO_DATE] -->
190
191## Stack
192- **Language**: [stack.language]
193- **Framework**: [stack.framework] [stack.framework_version]
194- **Runtime**: [stack.runtime] [stack.runtime_version]
195- **Package manager**: [stack.package_manager]
196- **Monorepo**: [stack.monorepo_tool or "no"]
197
198## Structure
199- **Backend source**: [structure.source_dirs.backend]
200- **Frontend source**: [structure.source_dirs.frontend or "none"]
201- **Test dirs**: [structure.test_dirs.*]
202- **Migration dir**: [structure.migration_dir]
203
204## Commands
205- **Test (all)**: `[commands.test_all]`
206- **Test (single)**: `[commands.test_single]`
207- **Build**: `[commands.build_frontend or "none"]`
208- **Lint**: `[commands.lint or "none"]`
209
210## Auth
211- **Middleware**: `[auth.middleware_name]` at `[auth.middleware_path]`
212- **User object**: `[auth.user_object]`
213- **Pattern**: [auth.pattern]
214
215## Multi-Tenancy
216- **Enabled**: [multi_tenancy.enabled]
217- **Field**: `[multi_tenancy.field]`
218- **Enforcement**: [multi_tenancy.enforcement]
219- **Exceptions**: [multi_tenancy.exceptions]
220
221## Database
222- **Type**: [database.type]
223- **ORM**: [database.orm]
224- **Migrations**: [database.migration_system]
225
226## Conventions
227- **File naming**: [conventions.file_naming]
228- **Import style**: [conventions.import_style]
229- **File extensions**: [conventions.file_extensions]
230- **File size limits**: soft [conventions.file_size_soft_limit], hard [conventions.file_size_hard_limit]
231
232## Git
233- **Default branch**: [git.default_branch]
234- **Protected**: [git.protected_branches]
235- **Commit style**: [git.commit_style]
236
237## Traps (from stack-traps.json)
238[List each trap with severity and description]
239
240## Workspace Packages (monorepo only)
241| Package | Path | Purpose |
242|---------|------|---------|
243[workspace_packages entries]
244```
245
246---
247
248## USAGE BY DOWNSTREAM SKILLS
249
250### Stack Resolution Preamble (copy into each skill)
251
252Every enterprise skill must read the profile at start:
253
254```
255## STACK RESOLUTION
256Read `.claude/enterprise-state/stack-profile.json` at skill start.
257Extract variables:
258 $TEST_CMD = commands.test_all
259 $TEST_SINGLE = commands.test_single
260 $SOURCE_DIR = structure.source_dirs.backend
261 $FRONTEND_DIR = structure.source_dirs.frontend
262 $BUILD_CMD = commands.build_frontend
263 $TEST_FRAMEWORK = commands.test_framework
264 $AUTH_MIDDLEWARE = auth.middleware_name
265 $TENANT_FIELD = multi_tenancy.field
266 $TENANT_ENABLED = multi_tenancy.enabled
267 $FILE_EXTENSIONS = conventions.file_extensions
268 $BRANCH_MAIN = git.default_branch
269
270If no profile exists: BLOCKED — run /enterprise-discover first.
271```
272
273### Conditional Blocks
274
275```
276# Only if multi-tenancy is enabled
277if $TENANT_ENABLED:
278 verify every INSERT includes $TENANT_FIELD
279 verify every SELECT scopes by $TENANT_FIELD
280
281# Only if auth middleware exists
282if $AUTH_MIDDLEWARE != "":
283 verify protected routes use $AUTH_MIDDLEWARE
284
285# Only if frontend exists
286if $FRONTEND_DIR != "":
287 run $BUILD_CMD to verify build
288```