--- name: code-documenter description: "Generates and maintains OKF v0.2-compliant knowledge bases documenting a codebase's modules, classes, functions, architecture, and configuration. Use when creating a knowledge base for a codebase, updating documentation after code changes, or exporting codebase knowledge in a portable, provenance-tracked format." --- # Code Documenter Skill ## Overview The **Code Documenter** skill automatically generates and maintains OKF v0.2-compliant knowledge bases that document codebases. It analyzes source code to extract and structure information about functions, classes, modules, architecture, APIs, and configuration—then organizes this knowledge using the Open Knowledge Format. This skill implements the format defined in [references/SPEC.md](references/SPEC.md). That document is the normative source for frontmatter fields, conformance rules, and file conventions (index.md, log.md, cross-linking); this file describes how the skill applies it to a codebase. When in doubt, defer to the spec. ## Purpose This skill addresses the challenge of keeping codebase documentation current and accessible as code evolves. It: - **Auto-generates** documentation by parsing code, extracting docstrings, and analyzing structure - **Structures knowledge** following OKF v0.2, making it portable, versioned, and agent-friendly - **Maintains provenance** through source tracking and credibility signals - **Supports trust tiers** (unverified, machine-confirmed, human-reviewed) - **Enables discovery** through progressive disclosure with index files - **Bridges code and knowledge** without requiring separate manual documentation ## When to Use This Skill Use this skill when you need to: - **Create a knowledge base** for a new or existing codebase - **Update documentation** after significant code changes - **Discover** code structure, modules, and APIs quickly - **Export codebase knowledge** in a portable, version-controlled format - **Collaborate** on documentation that tracks authorship and verification - **Maintain** documentation that stays fresh and indicates staleness ## How It Works ### Workflow Overview ``` ┌─ Analyze Codebase │ ├─ Scan directory structure │ ├─ Parse source files (language-specific) │ └─ Extract docstrings, type hints, signatures │ ├─ Check Existing Docs │ ├─ Look for docs/knowledge or user-specified path │ └─ Ask before creating or overwriting │ ├─ Generate Concepts │ ├─ Modules → concepts (one per significant file or package) │ ├─ Classes → concepts (key types and their relationships) │ ├─ Functions/Methods → concepts (public APIs and key internal functions) │ ├─ Architecture → concepts (high-level design, patterns) │ └─ Config → concepts (environment, settings, build system) │ ├─ Structure as OKF │ ├─ Frontmatter: type, title, description, resource, tags │ ├─ Provenance: sources pointing to code files │ ├─ Trust: generated by skill, awaiting human verification │ ├─ Lifecycle: draft (awaiting review) or stable │ └─ Body: markdown with schema, examples, references │ └─ Output Knowledge Base ├─ Index files for progressive disclosure ├─ Log file tracking changes └─ Git-ready structure ``` ### Input The skill takes: - **`workspace_root`** (optional, default: current workspace): Root of the codebase to document - **`output_path`** (optional, default: `docs/knowledge`): Where to write the OKF bundle - **`languages`** (optional, default: auto-detect): Which languages to parse (e.g., Python, TypeScript, Java) - **`depth`** (optional, default: `medium`): - `quick` — module and class level only - `medium` — modules, classes, public functions (default) - `thorough` — include private functions and detailed internals - **`include_config`** (optional, default: true): Include configuration and environment docs - **`include_architecture`** (optional, default: true): Generate architecture overview concepts - **`initial_status`** (optional, default: `draft`): The lifecycle `status` (SPEC.md §5.4) written to generated concepts: - `draft` — not yet reviewed; the recommended default for machine-generated content - `stable` — ready for consumption; use only if you don't intend a review pass The skill never writes a `verified` field itself, since verification requires a human or process actor (SPEC.md §5.2, §7). Generated concepts therefore always start at the **unverified** trust tier regardless of `initial_status`. ### Output Structure The skill creates an OKF v0.2 bundle: ``` docs/knowledge/ ├─ index.md # Progressive disclosure index ├─ log.md # Change history ├─ modules/ │ ├─ index.md # Module directory │ ├─ {module-name}.md # One per top-level module │ └─ {submodule}/ │ ├─ index.md │ └─ ... ├─ types/ # Classes, interfaces, types │ ├─ index.md │ └─ {typename}.md ├─ functions/ # Functions and methods │ ├─ index.md │ └─ {function-name}.md ├─ architecture/ │ ├─ index.md │ ├─ design-patterns.md │ └─ system-overview.md ├─ config/ │ ├─ index.md │ ├─ environment.md │ └─ build-system.md └─ references/ # Linked code files, schema definitions └─ ... ``` The bundle-root `index.md` carries an `okf_version: "0.2"` frontmatter key (SPEC.md §12); this is the only place an `index.md` may contain frontmatter. All other `index.md` and `log.md` files stay frontmatter-free per SPEC.md §8–§9. ### Example Concepts #### Module Concept ```markdown --- type: Module title: "payment-processor" description: "Handles payment transactions, validation, and settlement." resource: file:///path/to/payment_processor/__init__.py tags: [payments, core, billing] generated: { by: code-documenter/skill-v1.0, at: 2026-09-18T14:30:00Z } status: draft sources: - resource: file:///path/to/payment_processor/ id: source-code last_modified: 2026-09-15T10:00:00Z --- # Overview The `payment_processor` module provides a high-level API for handling payment transactions. It coordinates validation, processing, and settlement across multiple payment gateways. ## Key Classes - [`PaymentGateway`](/types/PaymentGateway.md) — Abstract interface for gateway implementations - [`StripeGateway`](/types/StripeGateway.md) — Stripe implementation - [`PaymentTransaction`](/types/PaymentTransaction.md) — Transaction record ## Key Functions - [`process_payment()`](/functions/process_payment.md) — Main entry point - [`validate_card()`](/functions/validate_card.md) — Card validation ``` #### Class Concept ```markdown --- type: Class title: "PaymentTransaction" description: "Represents a single payment transaction with metadata." resource: file:///path/to/payment_processor/models.py#PaymentTransaction tags: [models, payments] generated: { by: code-documenter/skill-v1.0, at: 2026-09-18T14:30:00Z } status: draft sources: - resource: file:///path/to/payment_processor/models.py id: source-code author: reference_agent/code-documenter-v1.0 --- # Schema | Attribute | Type | Description | |----------------|-----------|------------------------------------------| | `id` | str | Globally unique transaction identifier | | `amount_usd` | Decimal | Amount in US dollars | | `status` | Status | One of: pending, processing, completed, failed | | `gateway` | str | Payment gateway (stripe, paypal, etc.) | | `created_at` | datetime | When transaction was created | # Methods - `__init__(amount, currency, gateway)` — Constructor - `execute() -> Receipt` — Process the transaction - `refund() -> bool` — Issue a refund ``` #### Function Concept ```markdown --- type: Function title: "process_payment" description: "Execute a payment transaction and return the result." resource: file:///path/to/payment_processor/api.py#process_payment tags: [api, payments, public] generated: { by: code-documenter/skill-v1.0, at: 2026-09-18T14:30:00Z } status: draft --- # Signature ```python def process_payment( transaction: PaymentTransaction, idempotency_key: str | None = None ) -> Receipt ``` # Parameters - `transaction` — [PaymentTransaction](/types/PaymentTransaction.md) to process - `idempotency_key` — Optional idempotency key for retries # Returns [`Receipt`](/types/Receipt.md) with transaction result and metadata. # Raises - `ValidationError` — Invalid transaction data - `GatewayError` — Payment gateway error ``` ## Invocation ### As a Skill in an Agent When invoked in an agent chat: ``` Create OKF documentation for the codebase ``` The skill will: 1. Ask if an existing knowledge base exists (if not found automatically) 2. Scan the codebase and extract information 3. Generate OKF concepts organized by type 4. Create index files for navigation 5. Add a log entry documenting the run 6. Return a summary of what was created/updated ### Parameters (if user provides them) ``` Create OKF documentation at docs/api-knowledge with thorough depth for Python files only ``` Supported parameter format: - `at ` — Output location (default: `docs/knowledge`) - `with ` — Scan depth: quick, medium, thorough - `for ` — Languages to parse (comma-separated, or auto-detect) - `include ` — Features to include: config, architecture (or both) ## Key Features ### Provenance Tracking Each generated concept includes: - **`sources`** pointing to the code file(s) it derives from - **`generated.by`** indicating this skill auto-generated it - **`generated.at`** timestamp for when it was created - **Optional credibility signals**: `last_modified` from source files Example: ```yaml generated: { by: code-documenter/skill-v1.0, at: 2026-09-18T14:30:00Z } sources: - resource: file:///path/to/module.py id: source last_modified: 2026-09-15T10:00:00Z ``` ### Trust Tiers Per SPEC.md §5.3, a consumer derives one of three trust tiers from the `verified` field: - **unverified** — no `verified` field. Every concept this skill generates starts here, since the skill is the sole `generated.by` actor and never adds `verified` itself. - **machine-confirmed** — `verified` present with only non-`human:` actors (e.g. a CI `process:`). - **human-reviewed** — `verified` includes at least one `human:` actor. A human or process promotes a concept's trust tier by adding a `verified: { by: ..., at: ... }` entry after review; the skill leaves that field untouched on incremental updates (see Incremental Updates below). ### Lifecycle Management `status` (SPEC.md §5.4) is independent of trust and takes `draft`, `stable`, or `deprecated`; absent `status` means `stable`. - The skill writes `status: ` (default `draft`) on every concept it generates. - **`stale_after`** (SPEC.md §5.5) can be set if the codebase has a release cycle (e.g., quarterly review); consumers treat a concept as stale once `now >= stale_after`. - Consumers can warn when documentation lags behind code changes. ### Incremental Updates When invoked again on the same codebase: 1. Skill detects existing knowledge base 2. Identifies changed files (new, modified, deleted) 3. Updates affected concepts 4. Leaves human-verified content untouched 5. Logs all changes in `log.md` ## Example: Full Workflow ### Step 1: Initial Generation ``` User: "Document the codebase with OKF" ``` Skill scans the workspace and finds no existing docs at `docs/knowledge`. It asks: ``` No existing OKF bundle found. Create at docs/knowledge? (y/n) ``` User confirms. Skill: - Parses all `.py` files (auto-detected) - Generates ~30 concepts (modules, classes, functions) - Creates index files for each subdirectory - Outputs summary: ``` ✓ Created OKF bundle at docs/knowledge/ ✓ 8 modules documented ✓ 15 classes documented ✓ 22 functions documented ✓ 1 architecture overview ✓ 1 config reference All concepts marked as 'draft' awaiting review. ``` ### Step 2: Human Review User opens the bundle, reads concepts, and marks some as verified: ```yaml verified: { by: human:jane.smith, at: 2026-09-18T16:00:00Z } ``` ### Step 3: Codebase Change Two weeks later, a developer refactors the `payment_processor` module. User invokes: ``` Update the OKF documentation ``` Skill: - Detects changes to `payment_processor/*.py` - Regenerates affected concepts - Preserves human `verified` metadata - Logs: "Updated payment_processor module (3 concepts changed, 2 unchanged)" - Prompts: "3 concepts were regenerated. Review changes before committing." ## Configuration ### Environment Variables The skill respects these variables (optional): - `OKF_WORKSPACE_ROOT` — Codebase to document (default: current workspace) - `OKF_OUTPUT_PATH` — Bundle location (default: `docs/knowledge`) - `OKF_SCAN_LANGUAGES` — Comma-separated list (e.g., `python,typescript`) - `OKF_SCAN_DEPTH` — `quick`, `medium`, or `thorough` ### .okf-config.json (optional) A codebase may include `.okf-config.json` to customize generation: ```json { "output_path": "docs/knowledge", "languages": ["python", "typescript"], "depth": "medium", "include_config": true, "include_architecture": true, "exclude_paths": ["tests/", "node_modules/", ".venv/"], "include_paths": ["src/", "lib/"], "type_mappings": { "dataclass": "Model", "abstract method": "Contract" } } ``` If present, skill uses it; otherwise uses defaults. ## Limitations & Future Work ### Current Limitations - Language support: Python, TypeScript/JavaScript, Java (others on request) - Docstring parsing: Works best with well-formatted docstrings (Google, NumPy, JSDoc styles) - No deep call-graph analysis or dependency resolution (yet) - Architecture concepts are structured templates, not AI-inferred ### Future Enhancements - Attested Computations for code metrics (test coverage, complexity) - Call graph visualization and dependency tracking - Automatic `stale_after` based on commit history - Integration with code review workflows (auto-verify when merged) - Support for more languages (Go, Rust, C++, etc.) - Configuration documentation extraction (env vars, config files) ## References - [references/SPEC.md](references/SPEC.md) — The Open Knowledge Format v0.2 specification this skill targets. Consult it directly for authoritative frontmatter field definitions, conformance rules (§11), and versioning (§12). --- ## Schema & Examples This skill is self-contained and requires only the ability to: 1. Read and parse source code 2. Generate markdown with YAML frontmatter 3. Create directory structures 4. Parse existing OKF bundles No external tools or SDKs are required.