agentleFS
TheunsBarnardtTheunsBarnardt/ai-fdl-kit/.claude/skills/fdl-extract-code/SKILL.md

fdl-extract-code

Skill1 starsChanged 7 months agoMITView on GitHub

Extract features, rules, and requirements from a codebase (local folder or git repo) into FDL blueprints

  • Reads credentials

1 other project uses a version of this, 1 of them edited.

Adopted by

Most recently taken up by

The file

Show its rules and text

We split this skill into the rules it gives an agent

57 rules. About 0 are common, 45 are distinctive, and 12 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈45

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 12

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    NEVER show raw YAML during the conversation

    line 15
  2. Distinctive:

    NEVER use FDL-specific terms with the user (outcomes, flows, events, etc.)

    line 16
  3. Distinctive:

    DO use AskUserQuestion to clarify ambiguities found in the code

    line 17
  4. Distinctive:

    DO present extracted information as plain-English bullet points

    line 18
  5. Distinctive:

    DO generate YAML silently behind the scenes

    line 19
  6. Distinctive:

    DO flag things the code doesn't make clear — ask the user rather than guessing

    line 20
  7. Very specific:

    Use --depth 1 for speed — we only need the current state, not history

    line 47
  8. Very specific:

    If a specific branch is needed, add --branch <branch>

    line 48
  9. Distinctive:

    Verify the path exists using Glob

    line 54
  10. Very specific:

    If the path points to a specific subdirectory (e.g., ./src/auth), focus analysis there but still check the project root for config files, …

    line 55
  11. Distinctive:

    Before analyzing ANY code, scan the source for secrets and sensitive data:

    line 59
  12. Distinctive:

    NEVER include the actual secret values in the warning or anywhere else

    line 71
  13. Very specific:

    Use <api-key> or <token> as placeholders, never real values

    line 78
  14. Distinctive:

    If the codebase is very large (200+ source files in scope), ask the user which feature areas to focus on

    line 124
  15. Very specific:

    If the path points to a specific feature folder (e.g., ./src/auth), that's already scoped

    line 125
  16. Distinctive:

    Read the relevant source files and extract FDL constructs.

    line 129
  17. Distinctive:

    After reading the code, systematically map what you found:

    line 207
  18. Distinctive:

    Before generating, show the user what was found in plain language:

    line 267
  19. Distinctive:

    Wait for user confirmation before proceeding.

    line 318
  20. Distinctive:

    Check if any of the feature names you're about to create already exist

    line 323
  21. Distinctive:

    Do NOT silently overwrite it.

    line 327
  22. Distinctive:

    Read the existing blueprint

    line 329
  23. Distinctive:

    Ask: "Merge changes into existing blueprint, replace it entirely, or skip this feature?"

    line 349
  24. Distinctive:

    Run the similarity gate before creating it:

    line 356
  25. Distinctive:

    If the codebase covers multiple distinct feature areas (e.g., auth has login, registration, password-reset as separate flows), ask the user:

    line 374
  26. Distinctive:

    Default to combined unless the features are clearly independent (separate models, separate route groups, no shared state).

    line 378
  27. Distinctive:

    Add YAML comments that reference the source file and line:

    line 443
  28. Very specific:

    Write the file(s) to blueprints/{category}/{feature}.blueprint.yaml

    line 457
  29. Very specific:

    Run node scripts/validate.js blueprints/{category}/{feature}.blueprint.yaml (schema gate)

    line 458
  30. Very specific:

    Run node scripts/completeness-check.js blueprints/{category}/{feature}.blueprint.yaml (semantic gate — rejects placeholders, empty …

    line 459
  31. Distinctive:

    If either check fails, fix the issues and re-run both.

    line 460
  32. Distinctive:

    If cross-reference warnings appear, note them in the output

    line 461
  33. Distinctive:

    If a repo was cloned in Step 0:

    line 500
  34. Distinctive:

    Do NOT automatically delete the cloned directory — the user may want to reference it

    line 501
  35. Distinctive:

    If the code doesn't use a recognizable framework (plain scripts, microservices, CLIs):

    line 507
  36. Very specific:

    Look for entry points (main, index, app, server)

    line 509
  37. Distinctive:

    Follow imports/requires to map the dependency graph

    line 510
  38. Distinctive:

    If the repo contains multiple services/packages:

    line 514
  39. Distinctive:

    Ask the user which one(s) to extract

    line 516
  40. Very specific:

    Create separate blueprints with related cross-references

    line 518
  41. Distinctive:

    If there are no test files:

    line 521
  42. Distinctive:

    If the code has detailed comments explaining business rules:

    line 527
  43. Distinctive:

    Use comment text for rule descriptions and YAML comments

    line 529
  44. Distinctive:

    Ask whether to include the intended behavior (from the TODO) or only what's implemented

    line 534
  45. Very specific:

    Check .env.example, .env.sample, or .env.template (never .env itself)

    line 538
  46. Distinctive:

    Ask the user which layer to extract (or both)

    line 544
  47. Distinctive:

    If the git clone fails due to authentication:

    line 549
  48. Distinctive:

    Ensure your git credentials are configured for this URL

    line 552
  49. Distinctive:

    Never ask for or handle git credentials directly

    line 553
  50. Distinctive:

    Every extracted blueprint MUST include the three AI-proofing fields.

    line 585
  51. Very specific:

    Cross-validation: every error_code in api.response.errors[] must exist in top-level errors[].

    line 591
  52. Distinctive:

    If validation passes → proceed to Step 2

    line 601
  53. Distinctive:

    If validation fails → fix issues and re-validate until PASS

    line 602
  54. Distinctive:

    Update README.md badge (if blueprint count changed)

    line 624
  55. Distinctive:

    Update llms.txt (if blueprints added/removed)

    line 625
  56. Distinctive:

    Commit message must reference all extracted features

    line 626
  57. Distinctive:

    If validation fails, fix issues silently and re-validate.

    line 630

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

FDL Extract Code — Codebase to Blueprint

Analyze an existing codebase (local folder or git repository URL) and reverse-engineer the implemented features, business rules, fields, states, validation, error handling, and workflows into complete FDL blueprint YAML files. The user does NOT need to know YAML — use plain language throughout.

Core Principle: Plain Language, No YAML Jargon

  • NEVER show raw YAML during the conversation
  • NEVER use FDL-specific terms with the user (outcomes, flows, events, etc.)
  • DO use AskUserQuestion to clarify ambiguities found in the code
  • DO present extracted information as plain-English bullet points
  • DO generate YAML silently behind the scenes
  • DO flag things the code doesn't make clear — ask the user rather than guessing

Usage

/fdl-extract-code ./src/auth login auth
/fdl-extract-code C:/projects/my-app/src checkout payment
/fdl-extract-code https://github.com/org/repo.git payments integration
/fdl-extract-code https://github.com/org/repo checkout payment
/fdl-extract-code ../other-project

Arguments

  • <path-or-repo-url> — Local folder path OR a git repository URL (HTTPS). If a git URL, the repo will be cloned to a temp directory.
  • [feature-name] — Optional kebab-case name. If omitted, infer from the folder/repo name and code structure, or ask.
  • [category] — Optional. One of: auth, data, access, ui, integration, notification, payment, workflow. If omitted, infer or ask.

Workflow

Step 0: Resolve Input Source

If the input is a git URL:

  1. Clone the repo to a temporary directory:
    git clone --depth 1 <url> /tmp/fdl-extract-<repo-name>
    • Use --depth 1 for speed — we only need the current state, not history
    • If a specific branch is needed, add --branch <branch>
    • For GitHub URLs without .git suffix, append .git automatically
    • For GitHub URLs with paths (e.g., github.com/org/repo/tree/main/src), clone the repo and focus on the subfolder
  2. Set the working path to the cloned directory (or subfolder if specified in the URL)

If the input is a local path:

  1. Verify the path exists using Glob
  2. If the path points to a specific subdirectory (e.g., ./src/auth), focus analysis there but still check the project root for config files, package manifests, and shared utilities

Step 0.5: Security Scan (POPIA Compliance — MANDATORY)

Before analyzing ANY code, scan the source for secrets and sensitive data:

  1. Check for exposed secrets — Search for common secret patterns in the codebase:
    • API keys (sk-, AKIA, ghp_, gho_, glpat-, AIza)
    • Connection strings with credentials (mongodb://user:pass@, postgres://...)
    • Private keys (BEGIN RSA PRIVATE KEY)
    • JWT tokens (eyJ...)
    • Environment files with real values (.env files — NOT .env.example)
  2. If secrets are found:
    • ⚠️ WARN the user: "I found what looks like real credentials in this codebase. I will NOT include any of these in the blueprints."
    • List the FILE PATHS (not the values) where secrets were detected
    • NEVER include the actual secret values in the warning or anywhere else
    • Proceed with extraction but actively filter out all secret values from generated blueprints
  3. For all extracted content:
    • Replace real API endpoints with generic placeholders (e.g., https://api.example.com)
    • Replace real email addresses with example@test.com
    • Replace connection strings with <connection-string>
    • Use <api-key> or <token> as placeholders, never real values
    • Describe field validation patterns WITHOUT showing real data samples

This step is NON-NEGOTIABLE. Even if the user says "include everything" — secrets are NEVER included.

Step 1: Discover Project Structure

Map the codebase to understand its architecture before diving into details.

  1. Identify the tech stack — check for project manifests and config files:
    Glob: package.json, requirements.txt, Pipfile, Cargo.toml, go.mod, pom.xml,
          build.gradle, Gemfile, composer.json, *.csproj, pubspec.yaml,
          tsconfig.json, .eslintrc*, Dockerfile, docker-compose*
  2. Identify the framework — check for framework-specific patterns:
    FrameworkSignals
    Express/Fastify/Koaapp.get(), router.post(), route files
    Next.js/Nuxtpages/ or app/ directory, next.config.*
    Djangosettings.py, urls.py, models.py, views.py
    Railsconfig/routes.rb, app/models/, app/controllers/
    Spring Boot@RestController, @Entity, application.properties
    Laravelroutes/web.php, app/Models/, app/Http/Controllers/
    ASP.NETControllers/, Models/, Startup.cs, Program.cs
    Flask@app.route(), flask imports
    FastAPI@app.get(), @router.post(), Pydantic models
    Go (Chi/Gin/Echo)r.Get(), r.Post(), handler functions
    Rust (Actix/Axum)web::get(), Router::new(), handler functions
  3. Map the directory structure — use Glob to find key patterns:
    Glob: **/models/**,  **/entities/**,  **/schemas/**
    Glob: **/routes/**,  **/controllers/**, **/handlers/**,  **/api/**
    Glob: **/middleware/**, **/guards/**, **/interceptors/**, **/policies/**
    Glob: **/validators/**, **/validation/**
    Glob: **/services/**,  **/repositories/**, **/providers/**
    Glob: **/migrations/**, **/seeds/**
    Glob: **/tests/**,  **/specs/**,  **/__tests__/**
    Glob: **/types/**,  **/interfaces/**, **/dto/**
    Glob: **/events/**,  **/listeners/**, **/subscribers/**
    Glob: **/config/**,  **/constants/**
  4. Build a file inventory — count files by type and directory to understand scope:
    • If the codebase is very large (200+ source files in scope), ask the user which feature areas to focus on
    • If the path points to a specific feature folder (e.g., ./src/auth), that's already scoped

Step 2: Deep Code Analysis

Read the relevant source files and extract FDL constructs. Use the Explore agent for broad searches and Read for targeted file analysis.

What to extract from each code layer:

Code LayerFiles to ReadWhat to Extract
Models / Entities / SchemasModel definitions, ORM schemas, database migrations, Prisma/TypeORM/Sequelize/Django modelsFields — name, type, required, validation, defaults, relationships. States — enum fields that represent lifecycle (status, state).
Routes / Controllers / HandlersRoute definitions, controller actions, API handlersOutcomes — each route = an outcome. Extract HTTP method, path, preconditions (auth, roles, validation), success response, error responses.
Middleware / Guards / PoliciesAuth middleware, rate limiters, CORS config, role guards, permission checksRules — security rules, access control, rate limits. Map to rules.security and rules.access.
Validators / DTOsRequest validation schemas (Joi, Zod, class-validator, Pydantic, JSON Schema)Fields — validation rules, constraints, patterns, min/max. Refine field definitions from models.
Services / Business LogicService classes, use cases, domain logicRules — business rules, conditional logic, thresholds. Outcomes — complex operations that span multiple steps.
Error HandlingCustom error classes, error middleware, error constantsErrors — error codes, HTTP status codes, error messages. Map to UPPER_SNAKE_CASE codes.
Events / ListenersEvent emitters, pub/sub, message queue handlers, webhook handlersEvents — event names, payloads, triggers. Actors — external systems that send/receive events.
Tests / SpecsTest files, especially integration and e2e testsOutcomes — test descriptions ARE acceptance criteria. "it should reject expired tokens" = an outcome.
Migrations / SeedsDatabase migrations, seed dataFields — column types, constraints, indexes. States — enum values defined in migrations.
Config / ConstantsEnvironment config, feature flags, constants filesRules — configurable thresholds, limits, feature toggles.
Types / InterfacesTypeScript interfaces, Go structs, Rust types, Java POJOsFields — type definitions, optional/required markers.

Language-specific extraction patterns:

JavaScript / TypeScript:

Grep: "router\.(get|post|put|patch|delete)" — route definitions
Grep: "app\.(get|post|put|patch|delete)" — route definitions
Grep: "@(Get|Post|Put|Patch|Delete|Guard|UseGuards|Middleware)" — NestJS decorators
Grep: "z\.(string|number|boolean|object|array|enum)" — Zod schemas
Grep: "Joi\.(string|number|boolean|object|array)" — Joi validation
Grep: "@(Column|Entity|PrimaryColumn|OneToMany|ManyToOne)" — TypeORM
Grep: "mongoose\.Schema|new Schema" — Mongoose models
Grep: "prisma\.(create|find|update|delete)" — Prisma operations
Grep: "throw new.*Error|createError|HttpException" — error definitions
Grep: "emit\(|on\(|addEventListener" — event patterns
Grep: "status\(4[0-9]{2}\)|status\(5[0-9]{2}\)" — HTTP error responses

Python:

Grep: "@app\.(route|get|post|put|patch|delete)" — Flask/FastAPI routes
Grep: "class.*Model|class.*Schema" — Django/Pydantic/SQLAlchemy models
Grep: "class.*Serializer" — DRF serializers
Grep: "class.*Permission|has_permission" — permission classes
Grep: "raise.*Error|raise.*Exception|HTTPException" — error handling
Grep: "signal\.|@receiver" — Django signals
Grep: "class.*Form" — Django forms (field validation)

Go:

Grep: "func.*Handler|func.*handler|http\.Handle" — handlers
Grep: "type.*struct" — data structures
Grep: "func.*Middleware|func.*middleware" — middleware
Grep: "errors\.New|fmt\.Errorf" — error definitions

Java / Kotlin:

Grep: "@(RestController|Controller|RequestMapping|GetMapping|PostMapping)" — Spring controllers
Grep: "@Entity|@Table|@Column" — JPA entities
Grep: "@Valid|@NotNull|@NotBlank|@Size|@Pattern" — Bean validation
Grep: "@PreAuthorize|@Secured|@RolesAllowed" — security annotations

Ruby:

Grep: "class.*Controller|def (create|update|destroy|index|show)" — Rails controllers
Grep: "validates|validate|has_many|belongs_to" — ActiveRecord models
Grep: "before_action|after_action|around_action" — controller callbacks

C# / .NET:

Grep: "\[Http(Get|Post|Put|Patch|Delete)\]" — API controllers
Grep: "\[Required\]|\[StringLength\]|\[Range\]" — data annotations
Grep: "class.*Entity|class.*Model" — entity models

Step 3: Map Code to FDL Constructs

After reading the code, systematically map what you found:

Models/Schemas → Fields

Database column / model field → FDL field
  - Column type → FDL type (varchar→text, int→number, bool→boolean, etc.)
  - NOT NULL / required → required: true
  - Default values → note in description
  - Unique constraints → validation rule
  - Foreign keys → relationship (note in related)
  - Enum columns → select type with allowed values, OR states if it's a lifecycle

Routes/Controllers → Outcomes

Each API endpoint → one or more outcomes:
  - Route guard / auth check → given (precondition)
  - Request validation → given (field validation conditions)
  - Success response → result
  - Error responses → error outcomes with error binding
  - Database writes → then (set_field, create_record, etc.)
  - Events emitted → then (emit_event)
  - State changes → then (transition_state)

Middleware → Rules

Auth middleware → rules.security.authentication
Rate limiter → rules.security.rate_limit
CORS config → rules.security.cors
Role/permission checks → rules.access
Input sanitization → rules.security.input_sanitization

Test Descriptions → Outcomes (supplementary)

"it should return 401 when token is expired" → outcome: token_expired (error)
"it should create a new user" → outcome: user_created (success)
"it should not allow duplicate emails" → outcome: duplicate_email (error)

Error Classes → Errors

Custom error class → FDL error entry:
  - Class name → derive UPPER_SNAKE_CASE code
  - HTTP status → status field
  - Error message → message field (ensure user-safe)
  - Error code constant → code field

Event Emitters → Events

event.emit('user.created', payload) → FDL event:
  - Event name → dot.notation name
  - Payload fields → payload array
  - Handler/listener → note what happens on this event

Step 4: Present Extraction Summary

Before generating, show the user what was found in plain language:

Here's what I found in the codebase at ./src/auth:

TECH STACK:
  Node.js + Express + TypeScript + Prisma + PostgreSQL

FILES ANALYZED:
  14 files — 3 models, 4 routes, 2 middleware, 3 services, 2 test files

DATA THE FEATURE NEEDS:
  8 fields — email, password, first_name, last_name, role, status, last_login, refresh_token

WHAT SHOULD HAPPEN:
  ✓ User registers → account created, verification email sent
  ✓ User logs in → JWT issued, refresh token stored
  ✓ Token refreshed → new access token issued
  ✓ User logs out → refresh token invalidated
  ✗ Invalid credentials → 401 with generic message (no email enumeration)
  ✗ Account locked → 403 after 5 failed attempts
  ✗ Token expired → 401, must re-authenticate

WHO'S INVOLVED:
  2 actors — User (human), Auth Service (system)

LIFECYCLE:
  pending_verification → active → suspended → deactivated

RULES & CONSTRAINTS:
  - Passwords: bcrypt hashed, min 8 chars, must contain uppercase + number
  - Rate limiting: 5 login attempts per 15 minutes per IP
  - JWT: 15-minute access token, 7-day refresh token
  - Sessions: single active session per user (configurable)

FROM THE TESTS:
  12 test cases found — all mapped to success/error scenarios above

⚠ THINGS THE CODE DOESN'T MAKE CLEAR:
  - Password reset flow exists in routes but implementation is incomplete (TODO comment)
  - Role-based access is defined but only "user" and "admin" roles are used

Use AskUserQuestion to clarify:

  1. Ambiguous items found in the code (TODO comments, incomplete implementations)
  2. Whether to create one combined blueprint or separate blueprints per feature area
  3. Which category best fits (if not provided as argument)
  4. Whether to include incomplete/WIP features or skip them

Two-question maximum — ask only what you genuinely don't know; use the code as the source of truth for defaults.

Wait for user confirmation before proceeding.

Step 5: Check Existing Blueprints

  1. Glob blueprints/**/*.blueprint.yaml
  2. Check if any of the feature names you're about to create already exist

If a blueprint already exists for a feature:

Do NOT silently overwrite it. Instead:

  1. Read the existing blueprint
  2. Compare it with what you extracted — identify what changed:
    • ADDED: new outcomes, rules, fields, errors, or events not in the existing version
    • MODIFIED: outcomes/rules/fields that exist but have changed
    • REMOVED: things in the existing blueprint not found in the new extraction
  3. Present a plain-English diff to the user:
    ⚠️  auth/login already exists. Here's what changed:
    
    ADDED:
      + 2 new outcomes: oauth_login_success, oauth_login_failed
      + 1 new rule: MUST: validate OAuth state parameter to prevent CSRF
    
    MODIFIED:
      ~ rate_limit rule: max_attempts changed from 5 → 10
      ~ login_failed outcome: added IP-based lockout after 3 failures
    
    REMOVED:
      - legacy_session_login outcome (not found in new codebase)
  4. Ask: "Merge changes into existing blueprint, replace it entirely, or skip this feature?"
    • "Merge" → apply only ADDED and MODIFIED, preserve existing content not in the diff
    • "Replace" → overwrite with the freshly extracted version
    • "Skip" → leave the existing blueprint untouched

If the blueprint does NOT exist:

Run the similarity gate before creating it:

node scripts/similarity.js blueprints/{category}/{feature}.blueprint.yaml --threshold 0.55 --json

(Write the draft stub file first so the scanner has something to compare; delete it if the user aborts.)

  • Score ≥ 0.75 — STOP. Show: "A very similar blueprint already exists: {match.file} (similarity {score}). (a) extend the existing one, (b) differentiate — tell me what's unique, or (c) proceed anyway as a deliberate variant." Wait for user choice.
  • 0.55 ≤ score < 0.75 — Warn: "Related blueprint found: {match.file} ({score}). Proceeding, but consider linking via related[]." Continue.
  • Score < 0.55 — No conflict, proceed directly.

Step 6: Generate the Blueprint(s)

Generate complete .blueprint.yaml file(s) following the FDL meta-schema.

Single vs Multiple Blueprints

If the codebase covers multiple distinct feature areas (e.g., auth has login, registration, password-reset as separate flows), ask the user:

  • Combined: One blueprint with all operations as outcomes
  • Separate: Multiple blueprints, one per feature area, with related cross-references

Default to combined unless the features are clearly independent (separate models, separate route groups, no shared state).

Blueprint Template

# ============================================================
# {FEATURE_NAME} — Feature Blueprint
# FDL v0.1.0 | Blueprint v1.0.0
# ============================================================
# Extracted from: {source path or repo URL}
# Tech stack: {framework + language + database}
# Files analyzed: {count}
# ============================================================

feature: {feature-name}
version: "1.0.0"
description: {one-line description}
category: {category}
tags: [{relevant, tags}]

actors:
  # Systems, services, and roles identified in the code

fields:
  # Fields from models/schemas/DTOs with types and validation
  # Include source file as YAML comments

states:
  # Lifecycle enums from models/migrations

rules:
  # Business rules from middleware, services, config
  # Source: {file:line} — description of the rule

sla:
  # Timeouts, TTLs, rate limit windows from config/constants

outcomes:
  # Routes/handlers mapped to given/then/result format
  # Test descriptions used to validate completeness
  # Error responses as error-bound outcomes

flows:
  # Only if the code has multi-step orchestration (sagas, workflows)

errors:
  # UPPER_SNAKE_CASE codes from error classes/constants

events:
  # Event emitters/listeners with payloads

related:
  # Connections to existing blueprints

extensions:
  # Framework-specific details
  tech_stack:
    language: "{language}"
    framework: "{framework}"
    database: "{database}"
    orm: "{ORM if any}"

Source traceability

Add YAML comments that reference the source file and line:

rules:
  security:
    rate_limit:
      max_attempts: 5
      window: "15m"
      # Source: src/middleware/rateLimiter.ts:12
      # RateLimiter({ windowMs: 15 * 60 * 1000, max: 5 })

Step 7: Validate and Summarize

  1. Write the file(s) to blueprints/{category}/{feature}.blueprint.yaml
  2. Run node scripts/validate.js blueprints/{category}/{feature}.blueprint.yaml (schema gate)
  3. Run node scripts/completeness-check.js blueprints/{category}/{feature}.blueprint.yaml (semantic gate — rejects placeholders, empty outcomes, dangling error refs)
  4. If either check fails, fix the issues and re-run both. The terminal state of this skill is a blueprint that passes BOTH gates.
  5. If cross-reference warnings appear, note them in the output

Output a clean summary:

Created: blueprints/auth/login.blueprint.yaml
Source:  ./src/auth (14 files analyzed)
Stack:   Node.js + Express + TypeScript + Prisma

Feature: login v1.0.0
Actors:  2 (user, auth_service)
Fields:  8 (email, password, first_name, last_name, role, status, ...)
States:  4 (pending_verification → active → suspended → deactivated)
Outcomes: 7 (3 success, 4 error scenarios)
Errors:  5
Events:  3

Validation: PASS

Files analyzed:
  ✓ src/auth/models/user.model.ts — fields, states
  ✓ src/auth/routes/auth.routes.ts — outcomes
  ✓ src/auth/middleware/auth.middleware.ts — rules
  ✓ src/auth/services/auth.service.ts — business logic
  ✓ src/auth/tests/auth.test.ts — outcome validation
  ...

⚠ Items that could not be mapped:
  - Password reset flow — incomplete implementation (TODO in code)
  - OAuth providers — config exists but no handler code

💡 Suggested next steps:
  - Create blueprints for incomplete features: password-reset, oauth-login
  - Run /fdl-generate login nextjs to generate a fresh implementation from the blueprint
  - Compare generated code against original to find gaps

Step 8: Cleanup (git repos only)

If a repo was cloned in Step 0:

  • Do NOT automatically delete the cloned directory — the user may want to reference it
  • Tell the user where the clone lives: "The repo was cloned to /tmp/fdl-extract-<name>. You can delete it when you're done."

Handling Edge Cases

Codebase has no clear framework

If the code doesn't use a recognizable framework (plain scripts, microservices, CLIs):

  1. Focus on the file structure and naming patterns
  2. Look for entry points (main, index, app, server)
  3. Follow imports/requires to map the dependency graph
  4. Extract what you can — fields from data structures, rules from conditional logic

Codebase is a monorepo

If the repo contains multiple services/packages:

  1. List all packages/services found
  2. Ask the user which one(s) to extract
  3. Analyze each selected service independently
  4. Create separate blueprints with related cross-references

Codebase has no tests

If there are no test files:

  1. Note this in the summary — test descriptions are a valuable source of outcomes
  2. Rely more heavily on route definitions and error handling for outcome extraction
  3. Suggest the user run /fdl-generate from the blueprint, then compare with the original code

Code is heavily commented

If the code has detailed comments explaining business rules:

  1. Extract comments alongside the code they annotate
  2. Use comment text for rule descriptions and YAML comments
  3. Comments often contain the "why" that pure code doesn't show

Code has TODO/FIXME/HACK comments

  1. Flag these to the user — they indicate incomplete or known-broken features
  2. Ask whether to include the intended behavior (from the TODO) or only what's implemented
  3. Note TODOs in the "items that could not be mapped" section

Code uses environment variables for configuration

  1. Check .env.example, .env.sample, or .env.template (never .env itself)
  2. Extract configurable values (thresholds, limits, feature flags)
  3. Map to FDL rules with the env var name as a comment

Multiple languages in one repo (e.g., backend + frontend)

  1. Identify each language/framework
  2. Ask the user which layer to extract (or both)
  3. Backend → focus on API routes, models, business logic
  4. Frontend → focus on form fields, validation, state management, API calls

Private git repos

If the git clone fails due to authentication:

  1. Tell the user: "The repo requires authentication. You can either:"
    • Clone it yourself and point me to the local path
    • Ensure your git credentials are configured for this URL
  2. Never ask for or handle git credentials directly

Extraction Quality Checklist

Accuracy

  • Every extracted rule references its source file and line number
  • Thresholds and limits match the code exactly (don't round or approximate)
  • Field names are derived from the code's actual variable/column names
  • No requirements were invented — only what the code implements
  • Validation rules match the actual validators (Zod schemas, Joi, decorators, etc.)

Completeness

  • All models/schemas in scope were analyzed
  • All routes/controllers in scope were analyzed
  • All middleware/guards were analyzed
  • Error handling was captured (custom errors, HTTP status codes)
  • Events/listeners were captured
  • Test descriptions were used to validate outcome completeness
  • Config/constants were checked for thresholds and limits
  • Ambiguous or incomplete code was flagged, not silently dropped

FDL Compliance

  • Feature name: kebab-case
  • Field names: snake_case
  • Error codes: UPPER_SNAKE_CASE
  • Event names: dot.notation
  • Actor IDs: snake_case
  • All required top-level fields present
  • Comments explain WHY, referencing the source file

AI-Proofing (MANDATORY — prevents re-introducing the fake-endpoint gap)

Every extracted blueprint MUST include the three AI-proofing fields. If you can derive them from the source code, do so. If any cannot be derived, flag the gap in the extraction summary — do not silently omit.

  • aliases: — extract 5–10 alternate names for the feature. Sources: comment headers, README references, test file names, variable prefixes, directory naming. E.g. an auth/login/ folder with files signin.ts, authenticate.ts implies aliases [sign-in, signin, authenticate].
  • api: — if the extracted code exposes an HTTP endpoint (Express route, FastAPI path op, ASP.NET controller, etc.), pin the full wire contract: http.method, http.path (exactly as written in the source), request.schema (derived from DTO/validator), response.success.schema (from return type or response model), response.errors[] (from thrown exceptions or error returns). Each error_code must also appear in top-level errors[].
  • anti_patterns: — derive from what the source code explicitly GUARDS AGAINST. Look for: constant-time comparisons (→ "do not use == for password compare"), generic error messages (→ "do not leak user enumeration"), rate-limit checks (→ "do not skip rate limiting"), input sanitization (→ "do not trust raw input"). Each anti_pattern is { rule, why } with the why traced to the code's defensive intent.

Cross-validation: every error_code in api.response.errors[] must exist in top-level errors[]. The validator will fail the blueprint otherwise.

Automatic Post-Extraction Workflow

After Step 7 (blueprints written and validated), this must happen automatically:

  1. Validate all blueprints:
    node scripts/validate.js
    • If validation passes → proceed to Step 2
    • If validation fails → fix issues and re-validate until PASS
  2. Generate documentation and JSON API:
    npm run generate
    • Regenerates all docs/blueprints/**/*.md files
    • Regenerates all docs/api/**/*.json files and registry.json
    • Ensures documentation is always in sync with blueprints
  3. Create git commit:
    git add -A
    git commit -m "Extract/Update [feature-names]: [brief description]
    
    - [Extracted/Updated] [feature-name] ([category])
    - [Extracted/Updated] [feature-name] ([category])
    
    [One-line summary of why this change matters]
    
    Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
    • Update README.md badge (if blueprint count changed)
    • Update llms.txt (if blueprints added/removed)
    • Commit message must reference all extracted features

THIS MUST HAPPEN AUTOMATICALLY — the user should never need to ask for validation, generation, or commit. The extraction skill completes only when all three steps succeed.

If validation fails, fix issues silently and re-validate. Do not surface validation errors to the user without attempting fixes first.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.