From draft
Builds federated index from child draft/ directories at monorepo root, aggregating service-level context into root knowledge without deep code analysis. Use after /draft:init on services.
npx claudepluginhub mayurpise/draft --plugin draftThis skill uses the workspace's default tool permissions.
You are building a federated knowledge index for a monorepo with multiple services.
Generates YAML index files (.ai/index/) for design system codebases: component inventory, relationship graph, summary stats. Enables fast AI agent queries on components and dependencies.
Scans codebase and generates high-level architecture graph as interlinked markdown files in docs/professor/architecture/. Use for new project analysis or significant changes.
Generates code intelligence layers: Skeleton Index (<4s zero-dep), AST knowledge graph (CodeGraph), Mermaid architecture diagrams, smart context builder for AI agents to query codebases instantly.
Share bugs, ideas, or general feedback.
You are building a federated knowledge index for a monorepo with multiple services.
/draft:initAggregate from initialized services only. Verify before overwriting.
ALL generated files MUST include the standard YAML frontmatter. This enables refresh tracking, sync verification, and traceability.
Before generating any file, run these commands to gather metadata:
# Project name (from manifest or directory)
basename "$(pwd)"
# Git branch
git branch --show-current
# Git remote tracking branch
git rev-parse --abbrev-ref --symbolic-full-name @{upstream} 2>/dev/null || echo "none"
# Git commit SHA (full)
git rev-parse HEAD
# Git commit SHA (short)
git rev-parse --short HEAD
# Git commit date
git log -1 --format="%ci"
# Git commit message (first line)
git log -1 --format="%s"
# Check for uncommitted changes
git status --porcelain | head -1
Insert this YAML frontmatter block at the top of every generated file (service-index.md, dependency-graph.md, tech-matrix.md, draft-index-bughunt-summary.md):
---
project: "{PROJECT_NAME}"
module: "root"
generated_by: "draft:index"
generated_at: "{ISO_TIMESTAMP}"
git:
branch: "{LOCAL_BRANCH}"
remote: "{REMOTE/BRANCH or 'none'}"
commit: "{FULL_SHA}"
commit_short: "{SHORT_SHA}"
commit_date: "{COMMIT_DATE}"
commit_message: "{FIRST_LINE_OF_COMMIT_MESSAGE}"
dirty: {true|false}
synced_to_commit: "{FULL_SHA}"
---
Note:
generated_byusesdraft:commandformat (not/draft:command) for cross-platform compatibility.
ls draft/ 2>/dev/null
If draft/ does NOT exist at root:
/draft:init at monorepo root first to create base context, then run /draft:index to aggregate service knowledge."If draft/ exists: Continue to lockfile check.
Before proceeding, check for a stale lock:
ls draft/.index-lock 2>/dev/null
draft/.index-lock exists and is less than 10 minutes old: Warn: "Previous indexing may be incomplete. Remove draft/.index-lock to proceed." Stop here.draft/.index-lock exists and is older than 10 minutes: Remove it and continue.Create draft/.index-lock with the current timestamp before starting:
date -u +"%Y-%m-%dT%H:%M:%SZ" > draft/.index-lock
On completion (Step 9) or fatal error, remove the lock:
rm -f draft/.index-lock
Check for optional arguments:
--init-missing: Also initialize services that don't have draft/ directoriesbughunt [dir1 dir2 ...]: Run bug hunt across subdirectories with draft/ folders
draft/draft/)draft/bughunt-summary.mdIf bughunt argument detected: Skip to Step 1A (Bughunt Mode) instead of continuing to Step 2.
This mode runs /draft:bughunt across multiple subdirectories and aggregates results.
If directories explicitly specified (e.g., bughunt dir1 dir2 dir3):
draft/ subdirectorydraft/If no directories specified (e.g., just bughunt):
draft/ subdirectorynode_modules/, vendor/, .git/, draft/, .*# Example auto-discovery
for dir in */; do
if [ -d "$dir/draft" ]; then
echo "$dir"
fi
done
Output:
Target directories for bughunt:
- services/auth/
- services/billing/
- services/notifications/
For each target directory:
Set working directory to <target-dir> for the bughunt scope. The AI agent should invoke /draft:bughunt with the target directory as the scope path, rather than using cd:
/draft:bughunt
→ (scope prompt) → "Specific paths"
→ (paths prompt) → <target-dir>
Announce:
Running bughunt in <target-dir>...
Let /draft:bughunt run its full workflow:
<target-dir>/draft/bughunt-report-<timestamp>.mdRecord results:
Note: Run bughunts sequentially, not in parallel, to avoid context conflicts.
After all bughunts complete, read each generated report:
# For each target directory
cat <dir>/draft/bughunt-report-latest.md
Extract from each report:
Create draft/bughunt-summary.md:
# Draft Index: Bughunt Summary
**Date:** YYYY-MM-DD HH:MM
**Mode:** [Auto-discovery | Explicit directories]
**Directories Scanned:** N
## Overview
| Directory | Critical | High | Medium | Low | Total | Report |
|-----------|----------|------|--------|-----|-------|--------|
| services/auth/ | 0 | 2 | 5 | 3 | 10 | [→](services/auth/draft/bughunt-report.md) |
| services/billing/ | 1 | 1 | 2 | 1 | 5 | [→](services/billing/draft/bughunt-report.md) |
| services/notifications/ | 0 | 0 | 1 | 2 | 3 | [→](services/notifications/draft/bughunt-report.md) |
**Grand Total:** X Critical, Y High, Z Medium, W Low
## Directories With Critical Issues
| Directory | Count | Details |
|-----------|-------|---------|
| services/billing/ | 1 | [→](services/billing/draft/bughunt-report.md#critical-issues) |
## Directories With No Issues
- services/api-gateway/
- services/user-service/
## Skipped Directories
| Directory | Reason |
|-----------|--------|
| services/legacy-tools/ | No draft/ directory found |
| services/experiments/ | No draft/ directory found |
## Next Steps
1. **Prioritize Critical Issues:** Review directories with Critical bugs first
2. **Review Individual Reports:** Click links above to see detailed findings
3. **Track Fixes:** Use `/draft:new-track` to create implementation tracks for fixes
4. **Re-run After Fixes:** Run `/draft:index bughunt` again to verify
---
*Generated by `/draft:index bughunt` command*
═══════════════════════════════════════════════════════════
DRAFT INDEX BUGHUNT COMPLETE
═══════════════════════════════════════════════════════════
Scanned: N directories
Completed: X successful
Skipped: Y (no draft/)
Failed: Z errors
Grand Total Bugs:
Critical: W
High: X
Medium: Y
Low: Z
Summary Report: draft/bughunt-summary.md
Directories requiring immediate attention:
- services/billing/ (1 CRITICAL)
- services/auth/ (2 HIGH)
═══════════════════════════════════════════════════════════
STOP HERE if bughunt mode. Do not continue to Step 2 (normal indexing flow).
Scan immediate child directories for service markers. Do NOT recurse beyond depth=1.
Service detection markers (any of these):
package.json (Node.js)go.mod (Go)Cargo.toml (Rust)pom.xml or build.gradle (Java)pyproject.toml or requirements.txt (Python)Dockerfile (containerized service)src/ directory with code filesExclude patterns:
node_modules/vendor/.git/draft/ (the root draft directory itself).# Example discovery (adapt to actual structure)
ls -d */ | head -50
Output: List of detected service directories.
For each detected service directory, check for draft/ subdirectory:
# For each service
ls <service>/draft/ 2>/dev/null
Categorize into:
draft/ with context filesdraft/ directoryReport:
Scanning immediate child directories...
Detected X service directories:
✓ Y initialized (draft/ found)
○ Z uninitialized
Initialized services:
- services/auth/
- services/billing/
- ...
Uninitialized services:
- services/legacy-reports/
- services/admin-tools/
- ...
If init-missing argument is present:
Initialize <service-name>/? [y/n/all/skip-rest]
y: Run /draft:init in that directoryn: Skip this serviceall: Initialize all remaining without promptingskip-rest: Skip all remaining uninitialized servicesIf init-missing argument is NOT present:
/draft:index --init-missing to initialize these services"For each initialized service, read and extract:
<service>/draft/product.md:<service>/draft/.ai-context.md (or legacy <service>/draft/architecture.md):## System Overview)## External Dependencies)## Entry Points)## Critical Invariants, if available)<service>/draft/tech-stack.md:<service>/draft/manifest.json:{
"name": "<service-name>",
"type": "service",
"summary": "<first line of product vision>",
"primaryTech": "<main language/framework>",
"dependencies": ["<other-service-names>", "<external-deps>"],
"dependents": [],
"team": "<if found in docs>",
"initialized": "<date>",
"lastIndexed": "<current-date>"
}
Analyze extracted data to build dependency graph:
draft/graph/ directories):
draft/graph/proto-index.jsonl to map which service defines vs consumes which RPCsdraft/graph/module-graph.jsonl per service for internal module structureBuild a dependency map:
auth-service: [] # no dependencies on other services
billing-service: [auth-service]
api-gateway: [auth-service, billing-service]
Cycle detection: Walk the dependency graph depth-first from each service. If a cycle is detected (service A depends on B depends on ... depends on A), emit a > WARNING: Circular dependency detected: A → B → ... → A line in dependency-graph.md, mark the back-edge with circular: true in manifest.json's dependency entry, and continue processing. Do not fail on cycles — report and proceed.
For each service S, iterate all other services' dependencies arrays. If S appears in another service's dependencies, add that service to S's dependents array. Write the updated manifest.json for each service.
draft/service-index.mdUse the following inline template:
# Service Index
> Auto-generated by `/draft:index` on <date>. Do not edit directly.
> Re-run `/draft:index` to update.
## Overview
| Metric | Count |
|--------|-------|
| Total Services Detected | X |
| Initialized | Y |
| Uninitialized | Z |
## Service Registry
| Service | Status | Tech Stack | Dependencies | Team | Details |
|---------|--------|------------|--------------|------|---------|
| auth | ✓ | Go, Postgres | - | @auth-team | [→](../services/auth/draft/.ai-context.md) |
| billing | ✓ | Node, Stripe | auth | @billing | [→](../services/billing/draft/.ai-context.md) |
| legacy-reports | ○ | - | - | - | Not initialized |
## Uninitialized Services
The following services have not been initialized with `/draft:init`:
- `services/legacy-reports/`
- `services/admin-tools/`
Run `/draft:index --init-missing` or initialize individually with:
```bash
cd services/legacy-reports && /draft:init
### 7.2 Generate `draft/dependency-graph.md`
```markdown
# Service Dependency Graph
> Auto-generated by `/draft:index` on <date>. Do not edit directly.
## System Topology
```mermaid
graph LR
subgraph "Core Services"
auth[auth-service]
billing[billing-service]
users[user-service]
end
subgraph "Edge"
gateway[api-gateway]
end
subgraph "Background"
notifications[notification-service]
reports[report-service]
end
gateway --> auth
gateway --> billing
gateway --> users
billing --> auth
notifications --> users
reports --> billing
| Service | Depends On | Depended By |
|---|---|---|
| auth-service | - | billing, gateway, users |
| billing-service | auth | gateway, reports |
| user-service | auth | gateway, notifications |
| api-gateway | auth, billing, users | - |
This ordering helps when planning cross-service changes or understanding impact.
### 7.3 Generate `draft/tech-matrix.md`
```markdown
# Technology Matrix
> Auto-generated by `/draft:index` on <date>. Do not edit directly.
## Common Stack (Org Standards)
Technologies used by majority of services:
| Technology | Usage | Services |
|------------|-------|----------|
| PostgreSQL | Database | auth, billing, users (85%) |
| Redis | Caching | auth, gateway, notifications (60%) |
| Docker | Containerization | all (100%) |
| GitHub Actions | CI/CD | all (100%) |
## Technology Distribution
### Languages
| Language | Services | Percentage |
|----------|----------|------------|
| Go | auth, users, gateway | 45% |
| TypeScript | billing, notifications, reports | 45% |
| Python | ml-service, analytics | 10% |
### Databases
| Database | Services |
|----------|----------|
| PostgreSQL | auth, billing, users, reports |
| MongoDB | notifications, analytics |
| Redis | auth, gateway (cache only) |
## Variance Report
Services deviating from org standards:
| Service | Deviation | Reason |
|---------|-----------|--------|
| ml-service | Python instead of Go/TS | ML ecosystem |
| analytics | MongoDB instead of Postgres | Time-series workload |
A file is considered a placeholder if it contains the marker <!-- AUTO-GENERATED --> or is smaller than 100 bytes. Placeholders may be overwritten without confirmation. Non-placeholder files require user confirmation before overwriting.
draft/product.md (if not exists or is placeholder)Read all service product.md files and synthesize:
# Product: [Org/Product Name]
> Synthesized from X service contexts by `/draft:index` on <date>.
> Edit this file to refine the overall product vision.
## Vision
[Synthesized from common themes across service visions - one paragraph describing what the overall product/platform does]
## Target Users
<!-- Aggregated from all services, deduplicated -->
- **End Users**: [common user types across services]
- **Developers**: [if developer-facing APIs exist]
- **Operators**: [if ops/admin services exist]
## Service Capabilities
| Capability | Provided By | Description |
|------------|-------------|-------------|
| Authentication | auth-service | User identity, JWT, OAuth |
| Payments | billing-service | Stripe integration, invoicing |
| API Access | api-gateway | Rate limiting, routing |
## Cross-Cutting Concerns
<!-- Extracted from common patterns across services -->
- **Authentication**: All services validate via auth-service
- **Observability**: [common logging/tracing approach]
- **Data Privacy**: [common compliance patterns]
draft/architecture.md (if not exists or is placeholder)# Architecture: [Org/Product Name]
> Synthesized from X service contexts by `/draft:index` on <date>.
> This is a system-of-systems view. For service internals, see individual service contexts.
## System Overview
**Key Takeaway:** [One paragraph synthesizing overall system purpose from service summaries]
### System Topology
```mermaid
graph TD
subgraph "External"
Users[Users/Clients]
ThirdParty[Third-Party Services]
end
subgraph "Edge Layer"
Gateway[API Gateway]
CDN[CDN/Static]
end
subgraph "Core Services"
Auth[Auth Service]
Billing[Billing Service]
Users2[User Service]
end
subgraph "Background"
Notifications[Notifications]
Reports[Reports]
end
subgraph "Data Layer"
Postgres[(PostgreSQL)]
Redis[(Redis)]
Queue[Message Queue]
end
Users --> Gateway
Gateway --> Auth
Gateway --> Billing
Gateway --> Users2
Billing --> ThirdParty
Auth --> Postgres
Billing --> Postgres
Notifications --> Queue
Reports --> Queue
| Service | Responsibility | Tech | Status | Details |
|---|---|---|---|---|
| auth-service | Identity & access management | Go, Postgres | ✓ Active | → context |
| billing-service | Payments & invoicing | Node, Stripe | ✓ Active | → context |
| Component | Purpose | Used By |
|---|---|---|
| PostgreSQL | Primary datastore | auth, billing, users |
| Redis | Caching, sessions | auth, gateway |
| RabbitMQ | Async messaging | notifications, reports |
| Stripe | Payment processing | billing |
| Pattern | Description | Services |
|---|---|---|
| JWT Auth | All services validate JWT via auth-service | all |
| Event-Driven | Async events via message queue | notifications, reports |
/draft:index
### 7.6 Synthesize `draft/tech-stack.md` (if not exists or is placeholder)
```markdown
# Tech Stack: [Org/Product Name]
> Synthesized from X service contexts by `/draft:index` on <date>.
> This defines org-wide standards. Service-specific additions are in their local tech-stack.md.
## Org Standards
### Languages
- **Primary**: [most common language] — [X% of services]
- **Secondary**: [second most common] — [Y% of services]
### Frameworks
- **API**: [common API framework]
- **Testing**: [common test framework]
### Infrastructure
- **Database**: PostgreSQL (standard), MongoDB (approved for specific use cases)
- **Caching**: Redis
- **Messaging**: RabbitMQ / SQS
- **Container**: Docker
- **Orchestration**: Kubernetes
### CI/CD
- **Platform**: GitHub Actions
- **Registry**: [container registry]
## Approved Variances
| Service | Variance | Justification |
|---------|----------|---------------|
| ml-service | Python | ML ecosystem requirements |
| analytics | MongoDB | Time-series workload |
## Shared Libraries
| Library | Purpose | Version | Used By |
|---------|---------|---------|---------|
| @org/auth-client | Auth service client | 2.x | billing, gateway, notifications |
| @org/logging | Structured logging | 1.x | all services |
draft/.ai-context.md (if not exists or is placeholder)After generating draft/architecture.md, derive a condensed draft/.ai-context.md using the Condensation Subroutine (as defined in core/shared/condensation.md). This provides a token-optimized, self-contained AI context file at the root level aggregating all service knowledge.
draft/architecture.mddraft/.ai-context.md already exists and is not a placeholder, prompt before overwritingCreate draft/config.yaml if not exists:
# Draft Index Configuration
# Service detection patterns (immediate children only)
service_patterns:
- "package.json"
- "go.mod"
- "Cargo.toml"
- "pom.xml"
- "build.gradle"
- "pyproject.toml"
- "requirements.txt"
- "Dockerfile"
# Directories to exclude from scanning
exclude_patterns:
- "node_modules"
- "vendor"
- ".git"
- "draft"
- ".*" # Hidden directories
# Re-index on these events (for CI integration)
reindex_triggers:
- "service added"
- "service removed"
- "weekly"
For each initialized service with both draft/architecture.md AND draft/graph/schema.yaml:
A. Read current architecture.md into memory.
B. Regenerate slot content from graph JSONL:
GRAPH:module-deps → run graph --repo . --out draft/graph --query --mode mermaid --symbol module-deps
Parse JSON response, extract .mermaid string + filtered flag + statsGRAPH:proto-map → run graph --repo . --out draft/graph --query --mode mermaid --symbol proto-map
Parse JSON response, extract .mermaid string + statsGRAPH:hotspots → read draft/graph/hotspots.jsonl, build top-10 markdown table:
| File | Lines | fanIn | Score | with one row per hotspot, ordered by score descendingC. For each slot, find <!-- GRAPH:{id}:START --> ... <!-- GRAPH:{id}:END --> markers.
Replace entire block (inclusive of markers) with regenerated content.
If a marker pair is absent (legacy file): insert slot at the designated position and log:
"Injected GRAPH:{id} slot into architecture.md (slot was absent — legacy file upgraded)"
D. Write updated architecture.md back to disk.
Update frontmatter: generated_by = "draft:index", generated_at = now.
E. Re-run Condensation Subroutine (condensation.md) to propagate updated hotspot data into .ai-context.md GRAPH:HOTSPOTS and recompute tier budget. If .ai-profile.md exists, regenerate via Profile Generation Subroutine.
F. Report per service:
✓ <service>: refreshed 3 graph slots (module-deps, proto-map, hotspots)
✓ <service>: regenerated .ai-context.md (tier N, {lines} lines)
Remove the lockfile:
rm -f draft/.index-lock
═══════════════════════════════════════════════════════════
DRAFT INDEX COMPLETE
═══════════════════════════════════════════════════════════
Scanned: X service directories (depth=1)
Indexed: Y services with draft/ context
Skipped: Z uninitialized services
Generated/Updated:
✓ draft/service-index.md (service registry)
✓ draft/dependency-graph.md (inter-service topology)
✓ draft/tech-matrix.md (technology distribution)
✓ draft/product.md (synthesized product vision)
✓ draft/architecture.md (system-of-systems view)
✓ draft/tech-stack.md (org standards)
✓ draft/config.yaml (index configuration)
Service manifests updated: Y services
Next steps:
1. Review synthesized files in draft/
2. Edit draft/product.md to refine overall vision
3. Edit draft/architecture.md to add cross-cutting context
4. Run /draft:index periodically to refresh
For uninitialized services, run:
/draft:index init-missing
═══════════════════════════════════════════════════════════
draft/*.md files/draft:init's job per service/draft:init on a new serviceWhen regenerating, the skill:
<!-- MANUAL START --> and <!-- MANUAL END --> are never overwrittenGraph injection slots (<!-- GRAPH:...:START --> / <!-- GRAPH:...:END -->) are ALWAYS overwritten during refresh — they are auto-managed. Never place manual content between these markers. Use <!-- MANUAL START --> / <!-- MANUAL END --> for content you want preserved near a slot.