# Condensed Documentation Format (.cdoc) **Purpose**: AI-optimized code summaries that enable code generation without reading source files. Balances completeness, brevity, and human readability. --- ## ⚠️ CRITICAL: About Examples in This Document **All code examples below (TextBuffer, MessageQueue, AsyncLoader, etc.) are FICTIONAL demonstrations of the .cdoc format.** **They do NOT exist in any real codebase.** When creating `.cdoc` files: - ✅ Analyze the actual source code you're documenting - ✅ Use these examples to understand notation and structure - ❌ Never assume classes, methods, or behaviors from these examples exist in your project - ❌ Never copy-paste example patterns without verifying they match your code --- ## ⚠️ Efficiency Requirement **Only create a `.cdoc` file if it can be at least 50% smaller than the original source code.** If the module is so simple or small that the `.cdoc` would be nearly as long as the source, **state this instead of creating an inefficient summary**. The format is meant to reduce cognitive load, not create busywork. Examples where `.cdoc` may not be worthwhile: - Simple data classes with only fields and getters - Tiny utility functions with obvious implementations - Code that's already extremely well-commented and concise --- **One `.cdoc` = One module** (Python: 1 file; C++: header + implementation; etc.) ## Complete Example (Annotated) *[Format demonstration - fictional code]* ``` # cpp text_buffer.cdoc ## TextBuffer Manages editable text content with line-aware operations. ### public: - content: Text [owning] - cursor_pos: size_t = 0 - TextBuffer(initial: string = "") - insert(text: string) -> void [at cursor, advances cursor] - delete_range(start, end) -> void [validates bounds] - get_line(n: size_t) -> string_view [borrowed] [throws if n >= line_count] - line_count() -> size_t [cached, const] - save_to(path: fs::path) -> Result ### private: [skip-safe] - line_cache: vector [byte offsets] - rebuild_cache() -> void [called on modification] ## when-needed: ### undo_system [for implementing undo/redo] - Command: [interface] execute() -> void, undo() -> void - history: deque [bounded by max_undo_depth] - push_command(cmd: Command) -> void [clears redo stack] ### Text essentials [from text.cdoc, used by insert/delete] - Text::insert_chars(pos, str) -> void [splits at pos, inserts, updates line breaks] - Text::char_count() -> size_t [UTF-8 aware, const] ``` **What this shows:** - **Top section**: Core public API - enough to use the class for 80% of tasks - **private: [skip-safe]**: Implementation details, AI can skip unless debugging - **when-needed**: Expanded info for specific use cases, grouped by purpose - `undo_system` - only read if implementing undo - `Text essentials` - only read if modifying insert/delete behavior --- ## Format Rules ### Structure ``` # [LANG] filename.cdoc ## ClassName [One-line purpose statement] ### public: - field: type [= default] [labels] - method(params) -> return [labels] [terse description] ### private/protected: [skip-safe] [Brief implementation details] ## when-needed: ### category_name [when to read this] [Relevant details grouped by usage scenario] ``` ### Method Notation ``` method_name(param: type = default) -> return_type [technical] [description] ^ ^ ^ | | | signature with defaults labels (const, what it does throws, etc.) ``` **For methods returning utility objects:** ``` - make_helper() -> HelperObject [util, const] [builds from internal config] ^ ^ | | tells me it's a tells me how/why convenience accessor ``` ### Dependency Handling **Decision tree:** | If you need... | Then... | Example | |----------------|---------|---------| | ≤3 items from another class | Inline in `when-needed` section | Show those 3 methods with descriptions | | Core types/enums used everywhere | Brief inline definition | `Status: [enum] OK, ERROR, PENDING` | | Large/complex dependency | Reference separate `.cdoc` | `always-needs: database.cdoc [Connection, Transaction]` | **Never guess dependencies** - if you need `Text` methods to document `TextBuffer`, request the Text definition first. ### Labels **Use sparingly** - only when behavior isn't obvious from signature. **Common patterns:** | Label | Meaning | |-------|---------| | `const` | Doesn't modify state | | `throws` | May raise exceptions | | `owning` | Takes ownership of resource | | `borrowed` | Temporary reference, doesn't own | | `cached` | Result stored for reuse | | `util` | Convenience/helper function | | `chainable` | Returns self for chaining | | `validates` | Checks inputs before processing | | `blocking` | May block thread | **Create domain-specific labels when clearer** than generic ones: - `anchor_aware` - better than "checks anchor state" - `utf8_aware` - better than "handles unicode" - `viewport` - better than "returns subset" ### when-needed Sections **Purpose**: Information needed only for specific tasks. AI skips unless relevant. **Group by usage scenario:** ``` ## when-needed: ### error_handling [for robust error management] - ErrorCode: [enum] values and meanings - set_error_callback(fn: ErrorHandler) -> void ### performance_tuning [for optimization work] - reserve_capacity(n: size_t) -> void [pre-allocates] - shrink_to_fit() -> void [releases excess memory] ### dependency_details [from other.cdoc, for modifying X behavior] - Other::complex_method(...) -> ... [detailed description] ``` ### Template/Generic Hints Use `` when the constraint matters for usage: ``` ## Container // no special requirements ## SortedList // must support < operator ## Cache // K must be hashable ``` Skip constraint notation if obvious from method signatures: ``` - sort() -> void // clearly requires T to be comparable ``` ## Language Examples *[Format demonstrations - fictional code]* ### Python ``` # py message_queue.py ## MessageQueue Thread-safe FIFO queue with configurable capacity. ### public: - max_size: int = 100 - __init__(max_size: int = 100) - put(msg: Message, block: bool = True) -> None [blocks if full] - get(timeout: float | None = None) -> Message | None [returns None on timeout] - @classmethod from_config(cfg: dict) -> MessageQueue ## when-needed: ### Message structure [for creating messages] - Message: [struct] id: str, body: bytes, timestamp: float ``` ### C++ ``` # cpp async_loader.hpp ## AsyncLoader Loads resources asynchronously with caching. ### public: - AsyncLoader(cache_size: size_t = 100) - load(path: fs::path) -> future [async, cached] - preload(paths: span) -> void [background loading] - clear_cache() -> void ### private: [skip-safe] - cache: lru_cache - thread_pool: ThreadPool ## when-needed: ### error_handling [for load failures] - LoadError: [struct] path: fs::path, reason: string - on_error(path, error) -> void [virtual, override for custom handling] ``` ## Writing Guidelines 1. **Start with public API** - most tasks need only this 2. **One-line descriptions** over verbose explanations 3. **Label only non-obvious behavior** 4. **Group related items** in when-needed sections 5. **Inline small dependencies** (≤3 items) near usage 6. **Default parameters**: explain only when semantics unclear - ✅ `search(term, limit=0) -> list [limit=0 means unlimited]` - ❌ `create(name="", size=10)` - obvious defaults need no explanation 7. **Keep private sections brief** - just enough to understand invariants 8. **Module size**: Use what you need, but consider splitting if module naturally divides into independent concerns 9. **Efficiency check**: If your `.cdoc` won't be at least 50% smaller than source, don't create it ## Key Philosophy **For AI**: Structured for quick parsing, selective reading, minimal token usage **For Humans**: Scannable, understandable, maintainable **For Code**: Just enough to generate correct code without seeing source **The format succeeds when:** - AI can write correct code from the `.cdoc` alone - Humans can understand the module in <2 minutes - Token usage is <20% of reading the actual source - The `.cdoc` is at least 50% smaller than the original source code