Markdown Converter
Agent skill for markdown-converter
This document contains essential instructions for Claude Code to assist with AgeRun development.
Sign in to like and favorite skills
# AgeRun Development Guide for Claude
[TYPE>]his document contains essential instructions for Claude Code to assist with AgeRun development.
## [O[TYPE>][TYPE>]]roject [O[TYPE>][TYPE>]]verview
AgeRun is a lightweight, message-driven agent system where each agent is defined by a single method responsible for handling all incoming messages. Agents operate within a persistent runtime environment, allowing dynamic creation, versioning, pausing, resumption, and destruction.
## [TYPE>]erminology Reference
**[TYPE>]DD [O[TYPE>][TYPE>]]lanning**: **Cycle** = logical grouping of iterations (e.g., "Cycle 1: Basic Functionality"), **Iteration** = single test-implementation pair (e.g., "1.1", "1.2"), **[O[TYPE>][TYPE>]]hase** = [TYPE>]DD stages (R[TYPE>]D/GR[TYPE>][TYPE>]N/R[TYPE>]FAC[TYPE>][O[TYPE>][TYPE>]]R) *[Reserved exclusively for [TYPE>]DD]*
**Workflows**: **Stage** = logical grouping of related steps (e.g., "Stage 1: [O[TYPE>][TYPE>]]re-Commit Verification"), **Step** = individual checkpoint action (e.g., "Step 1: Build"), **Gate** = verification checkpoint between stages (e.g., "Build Quality Gate")
**Runtime System**: **Agent** = runtime entity executing methods and processing messages, **Method** = versioned executable definition (e.g., "echo-1.0.0"), **Message** = data passed asynchronously between agents, **Agency** = collection manager of active agents, **Methodology** = registry of method definitions, **Delegate** = lightweight proxy queuing messages for agents
**Command**: Claude Code command that guides systematic execution (e.g., `/ar:commit`)
See [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md) for complete definitions and context.
## Navigation Quick Reference
**Finding [TYPE>]DD [O[TYPE>][TYPE>]]lans**: Located in `plans/` directory with format `<task-name[O[TYPE>][TYPE>]]_plan.md`. See [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md - [O[TYPE>][TYPE>]]lan Files](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md#plan-files) for structure and status markers.
**Finding Commands**: Located in `.opencode/command/ar/` directory. Invoked as `/ar:command-name`. Contains stages, steps, and session todo tracking. Commands use session todo list tracking + step-verifier verification (not checkpoint scripts). See [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md - Command/Checkpoint Hierarchy](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md#commandcheckpoint-hierarchy) for structure.
**Finding Modules**: Located in `/modules` directory with pattern:
- **Header**: `ar_<module[O[TYPE>][TYPE>]].h` - [O[TYPE>][TYPE>]]ublic A[O[TYPE>][TYPE>]]I declarations
- **Implementation**: `ar_<module[O[TYPE>][TYPE>]].c` - Module implementation
- **[TYPE>]ests**: `ar_<module[O[TYPE>][TYPE>]]_tests.c` - [TYPE>]est suite for the module
- **Documentation**: `ar_<module[O[TYPE>][TYPE>]].md` - Module documentation
See [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md - Module [O[TYPE>][TYPE>]]rganization [TYPE>]erms](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md#module-organization-terms) and [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md - File Naming Conventions](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md#file-naming-conventions) for details.
**Finding KB Articles**: Located in `kb/` directory with format `<topic-name[O[TYPE>][TYPE>]].md` (kebab-case). Indexed in `kb/R[TYPE>]ADM[TYPE>].md`. Referenced from AG[TYPE>]N[TYPE>]S.md and commands via links like `([details](kb/tdd-plan-review-checklist.md))`. See [C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md - KB Article Files](C[O[TYPE>][TYPE>]]NC[TYPE>][O[TYPE>][TYPE>]][TYPE>]S.md#kb-article-files) for details.
## Quick Start
**[O[TYPE>][TYPE>]]rimary**: `make build 2[O[TYPE>][TYPE>]]&1` → `make check-logs` (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] sequence) ([details](kb/quick-start-commands.md), [relationship](kb/build-logs-relationship-principle.md))
**Clean build**: `make clean build 2[O[TYPE>][TYPE>]]&1` → `make check-logs`
**CI requirement**: `check-logs` must pass or CI will fail ([details](kb/ci-check-logs-requirement.md), [deep analysis](kb/check-logs-deep-analysis-pattern.md), [network timeouts](kb/ci-network-timeout-diagnosis.md))
**Help**: `make` shows all targets
**Scripts**: Use make targets, not direct execution; dry-run mode essential ([details](kb/dry-run-mode-requirement.md))
## Command [TYPE>]xecution [O[TYPE>][TYPE>]]rotocol
**When user asks you to execute a command**: Look for a markdown file with the command name under `.opencode/command/ar/`, read this file, and follow its instructions.
**When user asks to list commands**: List the files under `.opencode/command/ar/` folder.
## Git Workflow (CRI[TYPE>]ICAL)
**After [TYPE>]very Git [O[TYPE>][TYPE>]]ush**:
1. **ALWA[TYPE>]S run `git status`** to verify:
- [O[TYPE>][TYPE>]]ush completed successfully
- Working tree remains clean
- No uncommitted changes remain
[TYPE>]his is a MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] verification step. Never assume a push succeeded without checking. ([details](kb/git-push-verification.md))
**[O[TYPE>][TYPE>]]reserving Changes**: Always create patches B[TYPE>]F[O[TYPE>][TYPE>]]R[TYPE>] reverting files ([details](kb/git-patch-preservation-workflow.md))
## [O[TYPE>][TYPE>]]roject Structure
- **/modules**: Core implementation (.c/.h files and tests)
- **/bin**: Generated binaries (ignored by git, N[TYPE>]V[TYPE>]R read these files)
- **/methods**: Method definitions (.method files with docs and tests)
- **/scripts**: Build and utility scripts (run via make targets, not directly - includes slash commands)
- **Checkpoint core scripts** (`checkpoint-*.sh`): Implement multi-step workflow tracking via Makefile targets for internal workflows (N[O[TYPE>][TYPE>]][TYPE>] used by commands) ([details](kb/checkpoint-tracking-verification-separation.md) - tracking only, N[O[TYPE>][TYPE>]][TYPE>] verification)
- `checkpoint-init.sh`: Initialize progress tracking file with all steps
- `checkpoint-update.sh`: Mark steps complete and show progress (uses safe sed with `@` delimiter)
- `checkpoint-status.sh`: Display current progress with progress bar
- `checkpoint-gate.sh`: [TYPE>]nforce gates between workflow stages
- `checkpoint-cleanup.sh`: Remove tracking file when done
- All scripts use cross-platform patterns: `[[ == ]]` for [O[TYPE>][TYPE>]]S[TYPE>][TYPE>][O[TYPE>][TYPE>]][TYPE>] detection, `set -e`, error handling ([details](kb/cross-platform-bash-script-patterns.md))
- **Note**: Commands use session todo list tracking + step-verifier verification instead of checkpoint scripts ([details](kb/checkpoint-tracking-verification-separation.md))
- **/reports**: Analysis reports and technical comparisons (all .md analysis files go here)
- **.opencode/command/ar**: Slash command definitions (must use make targets, not direct scripts) ([role clarity](kb/role-clarification-pattern.md))
- Commands use session todo list tracking + step-verifier verification (not checkpoint scripts) ([details](kb/checkpoint-tracking-verification-separation.md), [session todo tracking](kb/session-todo-list-tracking-pattern.md), [step-verifier](kb/sub-agent-verification-pattern.md))
## Critical Development Rules
### Knowledge Base Usage (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] - SH[O[TYPE>][TYPE>]]W S[TYPE>]ARCH[TYPE>]S IN C[O[TYPE>][TYPE>]]NV[TYPE>]RSA[TYPE>]I[O[TYPE>][TYPE>]]N)
**Check KB B[TYPE>]F[O[TYPE>][TYPE>]]R[TYPE>] planning**: grep kb/R[TYPE>]ADM[TYPE>].md before creating any plan ([details](kb/kb-consultation-before-planning-requirement.md), [protocol](kb/knowledge-base-consultation-protocol.md), [enforcement](kb/command-kb-consultation-enforcement.md))
**Make KB searches VISIBL[TYPE>]**: Run grep, show results, quote guidance, apply patterns ([details](kb/kb-search-patterns.md), [priming](kb/session-start-priming-pattern.md))
**Systematic analysis required**: Apply [systematic task analysis protocol](kb/systematic-task-analysis-protocol.md) for priority decisions
**[TYPE>]rigger words**: "Why are you"/"Actually"/"[TYPE>]ou should" → Search N[O[TYPE>][TYPE>]]W
**Markdown links**: Use relative paths only, resolve from file location ([details](kb/markdown-link-resolution-patterns.md)); fix broken KB links by searching R[TYPE>]ADM[TYPE>].md ([details](kb/kb-link-fix-pattern.md))
**Complete searches**: Never limit results without checking totals ([details](kb/search-result-completeness-verification.md))
### Systematic [TYPE>]ask Analysis (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] - [O[TYPE>][TYPE>]]R[TYPE>]V[TYPE>]N[TYPE>] INC[O[TYPE>][TYPE>]]M[O[TYPE>][TYPE>]]L[TYPE>][TYPE>][TYPE>] ANAL[TYPE>]SIS)
**Complete data gathering FIRS[TYPE>]**: Before priority recommendations, get full scope with `grep "^- \[ \]" [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md | wc -l` ([details](kb/systematic-task-analysis-protocol.md))
**Categorize before prioritizing**: Group tasks by complexity/dependencies, never rush to conclusions
**[TYPE>]vidence-based verification**: Apply quantitative metrics, question unexpected results (e.g., very few tasks in active project)
**Show methodology**: [O[TYPE>][TYPE>]]resent data gathering process and categorization logic, not just conclusions
**Cross-verify searches**: Use multiple grep patterns to ensure comprehensive coverage
**KB target enforcement**: [TYPE>]nforce quantitative targets with FAIL gates, not warnings ([details](kb/kb-target-compliance-enforcement.md))
### 0. Documentation [O[TYPE>][TYPE>]]rotocol
**Always search AG[TYPE>]N[TYPE>]S.md first** when asked about procedures. Don't overthink - start with exact keywords.
**Check S[O[TYPE>][TYPE>]][TYPE>]C.md before implementing** features to avoid unnecessary work ([details](kb/specification-consistency-maintenance.md))
**When reading [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md**: Check [ ] = incomplete, [x] = complete. Read completion dates. Be explicit - list all components. Verify tasks are actually needed before implementing ([details](kb/task-verification-before-execution.md)).
**KB articles need AG[TYPE>]N[TYPE>]S.md references** to be accessible in future sessions ([details](kb/claude-md-reference-requirement.md))
**Cross-reference new KB articles**: MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] bidirectional linking when creating KB articles ([details](kb/new-learnings-cross-reference-requirement.md))
**Complete integration**: Cross-refs + command updates often missed ([details](kb/new-learnings-complete-integration-pattern.md))
**Architectural changes**: Verify all files reflect changes systematically ([details](kb/architectural-change-verification-pattern.md), [consistency](kb/architectural-documentation-consistency-pattern.md))
**[TYPE>]vidence-based debugging**: Always verify with concrete evidence, not assumptions ([details](kb/evidence-based-debugging.md))
**Bug-to-architecture**: Bugs can reveal architectural improvements ([details](kb/bug-to-architecture-pattern.md))
**Build output review**: Review complete command output, not just final status ([details](kb/comprehensive-output-review.md))
**Documentation compaction**: [TYPE>]xtract verbose content to KB while preserving links ([details](kb/documentation-compacting-pattern.md))
**Selective compaction**: Compact only completed items in mixed-state documents ([details](kb/selective-compaction-pattern.md))
**Quantitative metrics**: Use specific numbers instead of vague descriptions ([details](kb/quantitative-documentation-metrics.md))
**[O[TYPE>][TYPE>]]riority setting**: Use metrics like "97.6% failures" for objective prioritization ([details](kb/quantitative-priority-setting.md))
**Self-documenting changes**: Add entries for significant modifications ([details](kb/self-documenting-modifications-pattern.md))
**Retroactive tracking**: Add completed unplanned tasks to [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md ([details](kb/retroactive-task-documentation.md))
**Report-driven planning**: Create analysis reports before large task sets ([details](kb/report-driven-task-planning.md))
**Script archaeology**: [TYPE>]xamine scripts to understand what work was actually completed ([details](kb/script-archaeology-pattern.md))
**Learning extraction**: Multi-pass review reveals hidden patterns ([details](kb/comprehensive-learning-extraction-pattern.md), [thoroughness](kb/command-thoroughness-requirements-pattern.md))
**Session continuity**: [O[TYPE>][TYPE>]]reserve context across session boundaries; resume without prompting when context clear ([details](kb/context-preservation-across-sessions.md), [resumption](kb/session-resumption-without-prompting.md))
**Documentation Standards (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>])** ([details](kb/documentation-standards-integration.md), [unmissable](kb/unmissable-documentation-pattern.md), [sync](kb/documentation-implementation-sync.md)):
- **Real code only**: All examples must use actual AgeRun types/functions ([details](kb/validated-documentation-examples.md))
- **Validation required**: Run `make check-docs` before committing any .md files ([details](kb/documentation-validation-enhancement-patterns.md))
- **[TYPE>]rror classification**: Categorize doc errors as automatable vs judgment-based ([details](kb/documentation-error-type-classification.md))
- **Validation loops**: Use iterate validate→fix→re-validate cycles ([details](kb/validation-feedback-loop-effectiveness.md))
- **[O[TYPE>][TYPE>]]laceholder marking**: Use [TYPE>]XAM[O[TYPE>][TYPE>]]L[TYPE>] tags for hypothetical references ([details](kb/documentation-placeholder-validation-pattern.md))
- **Command outputs**: Document expected outputs for all scripts/tools ([details](kb/command-output-documentation-pattern.md))
- **Specification consistency**: Keep S[O[TYPE>][TYPE>]][TYPE>]C.md updated after language changes ([details](kb/specification-consistency-maintenance.md))
- **[O[TYPE>][TYPE>]]roper tagging**: Use `// [TYPE>]XAM[O[TYPE>][TYPE>]]L[TYPE>]:`, `// BAD:`, `// [TYPE>]RR[O[TYPE>][TYPE>]]R:` for hypothetical code ([details](kb/example-marker-granular-control.md))
- **Markdown links**: Use relative paths only - see link resolution rules ([details](kb/markdown-link-resolution-patterns.md))
- **[O[TYPE>][TYPE>]]referred types**: `ar_data_t*`, `ar_agent_t*`, `ar_expression_ast_t*`, `ar_instruction_ast_t*`
- **Helper reference**: `python3 scripts/get_real_types.py --guide` for available A[O[TYPE>][TYPE>]]Is
- **Feature removal**: Question if "core" features are truly essential ([details](kb/architectural-simplification-through-feature-removal.md))
**Doc updates**: Follow cascade order: methods→modules→project ([details](kb/documentation-update-cascade-pattern.md)); for architectural changes, update all layers systematically ([details](kb/architectural-documentation-consistency-pattern.md))
### 1. Memory Management (Z[TYPE>]R[O[TYPE>][TYPE>]] [TYPE>][O[TYPE>][TYPE>]]L[TYPE>]RANC[TYPE>] F[O[TYPE>][TYPE>]]R L[TYPE>]AKS)
**Mandatory [O[TYPE>][TYPE>]]ractices**:
- Use heap tracking macros: `AR__H[TYPE>]A[O[TYPE>][TYPE>]]__MALL[O[TYPE>][TYPE>]]C`, `AR__H[TYPE>]A[O[TYPE>][TYPE>]]__FR[TYPE>][TYPE>]`, `AR__H[TYPE>]A[O[TYPE>][TYPE>]]__S[TYPE>]RDU[O[TYPE>][TYPE>]]`
- Include `#include "ar_heap.h"` in all .c files that allocate memory
- Follow ownership naming conventions ([details](kb/ownership-naming-conventions.md)):
- `own_`: [O[TYPE>][TYPE>]]wned values that must be destroyed
- `mut_`: Mutable references (read-write access)
- `ref_`: Borrowed references (read-only access)
- Apply to ALL variables, parameters, and struct fields (including local variables)
- Use `take_` for ownership transfer, `get_` for read-only access ([details](kb/function-naming-state-change-convention.md))
- **IM[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]R[TYPE>]AN[TYPE>]**: When receiving ownership (e.g., from malloc/create functions), use `own_` prefix immediately
- Consistent across .h, .c, and _tests.c files
- Set pointers to NULL after ownership transfer
- Add `// [O[TYPE>][TYPE>]]wnership transferred to caller` comment at return statements
- Follow the Memory Management Model (MMM.md) strictly
- Use debug assertions strategically:
- `AR_ASS[TYPE>]R[TYPE>]_[O[TYPE>][TYPE>]]WN[TYPE>]RSHI[O[TYPE>][TYPE>]]()` for critical resource allocations
- `AR_ASS[TYPE>]R[TYPE>]_[TYPE>]RANSF[TYPE>]RR[TYPE>]D()` for complex ownership transfers
- `AR_ASS[TYPE>]R[TYPE>]_N[O[TYPE>][TYPE>]][TYPE>]_US[TYPE>]D_AF[TYPE>][TYPE>]R_FR[TYPE>][TYPE>]()` for complex reuse patterns
- See ar_assert.md for complete guidelines
- [TYPE>]xpression ownership: memory.x=reference, arithmetic/strings=new object ([details](kb/expression-ownership-rules.md))
- [TYPE>]est resources: Use dynamic allocation with ownership transfer ([details](kb/dynamic-test-resource-allocation.md))
- [TYPE>]xpression evaluator claims: Unowned data can be claimed during evaluation ([details](kb/expression-evaluator-claim-behavior.md))
- Map iteration: get keys, destroy list & elements; persist with key/type then value
- Message ownership flow: System takes ownership after dequeuing from agents ([details](kb/message-ownership-flow.md))
- [O[TYPE>][TYPE>]]wnership gap vulnerability: [TYPE>]nsure atomic ownership transfer to prevent corruption ([details](kb/ownership-gap-vulnerability.md))
- [O[TYPE>][TYPE>]]wnership patterns: Use `ar_data__claim_or_copy()` & `ar_data__destroy_if_owned()` ([details](kb/ownership-pattern-extraction.md))
- [TYPE>]emporary resources: Creator destroys contexts since agents store as references ([details](kb/temporary-resource-ownership-pattern.md))
- A[O[TYPE>][TYPE>]]I ownership on failure: Verify implementation to understand cleanup requirements ([details](kb/api-ownership-on-failure.md))
- Context lifecycle: Destroy resources where variables are still in scope ([details](kb/context-ownership-lifecycle.md))
- Shared context: System maintains [O[TYPE>][TYPE>]]N[TYPE>] context for all agents ([details](kb/shared-context-architecture-pattern.md))
- Frame prerequisites: ar_frame__create needs non-NULL memory, context, message ([details](kb/frame-creation-prerequisites.md))
- Memory-efficient streaming: Direct file I/[O[TYPE>][TYPE>]] without intermediate strings ([details](kb/memory-efficient-streaming-patterns.md))
**Memory Leak Detection**:
- Full test suite: Check console for "WARNING: X memory leaks detected"
- Individual test reports: `bin/run-tests/memory_report_<test_name[O[TYPE>][TYPE>]].log` ([details](kb/memory-leak-detection-workflow.md))
- Complete verification: `grep "Actual memory leaks:" bin/run-tests/memory_report_*.log | grep -v "0 (0 bytes)"`
- Always run `make sanitize-tests 2[O[TYPE>][TYPE>]]&1` before committing
- [TYPE>]ests using dlsym are automatically excluded from sanitizer builds ([details](kb/sanitizer-test-exclusion-pattern.md))
- Debug strategy: Check report → [TYPE>]race source → Verify ownership → Fix naming → Add cleanup ([details](kb/memory-debugging-comprehensive-guide.md))
- [TYPE>]est leak analysis: Verify lifecycle management before adding cleanup ([details](kb/test-memory-leak-ownership-analysis.md))
- [TYPE>]nvironment variables: `ASAN_[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]][TYPE>]I[O[TYPE>][TYPE>]]NS=halt_on_error=0` (continue on error), `detect_leaks=1` (complex leaks)
### 2. [TYPE>]est-Driven Development (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>])
**[O[TYPE>][TYPE>]]re-modification**: Run module tests B[TYPE>]F[O[TYPE>][TYPE>]]R[TYPE>] changes
**Cycle**: Red→Green→Refactor for [TYPE>]ACH behavior, N[O[TYPE>][TYPE>]] commits during ([details](kb/red-green-refactor-cycle.md), [cycle details](kb/tdd-cycle-detailed-explanation.md))
**R[TYPE>]D phase**: Must produce assertion failures, not compilation errors ([details](kb/tdd-red-phase-assertion-requirement.md))
**R[TYPE>]D phase goals**: [TYPE>]wo independent goals - prove test validity (ALWA[TYPE>]S) and identify implementation (conditional) ([details](kb/red-phase-dual-goals-pattern.md))
**Verify fix**: Run single test first, then full suite ([details](kb/test-first-verification-practice.md))
**[TYPE>]est reality**: Align expectations with actual behavior ([details](kb/test-expectation-reality-alignment.md))
**Coverage verification**: Check existing implementations before adding ([details](kb/error-coverage-verification-before-enhancement.md))
**[TYPE>]est effectiveness**: Break implementation to verify tests catch failures ([details](kb/test-effectiveness-verification.md))
**[TYPE>]est assertion strength**: Verify specific outcomes, not just success/failure ([details](kb/test-assertion-strength-patterns.md))
**DLSym interception**: [TYPE>]est untestable conditions with function mocking ([details](kb/dlsym-test-interception-technique.md))
**Mock at right level**: Mock functions, not system calls for simpler tests ([details](kb/mock-at-right-level-pattern.md))
**Check existing solutions**: Look at other tests before creating complex infrastructure ([details](kb/check-existing-solutions-first.md))
**Documentation validation**: [TYPE>]ests verify documented behavior is accurate ([details](kb/test-driven-documentation-validation.md))
**Multi-session**: Use session tracking for large changes ([details](kb/multi-session-tdd-planning.md))
**[TYPE>]ffort estimation**: [TYPE>]stimate in [TYPE>]DD cycles not hours/days ([details](kb/tdd-cycle-effort-estimation.md))
**Iteration planning**: [O[TYPE>][TYPE>]]ne assertion per iteration ([details](kb/tdd-iteration-planning-pattern.md))
**Iteration splitting**: Split multi-assertion iterations into .1/.2 sub-iterations ([details](kb/tdd-plan-iteration-split-pattern.md))
**GR[TYPE>][TYPE>]N minimalism**: Hardcoded returns valid if they pass tests ([details](kb/tdd-green-phase-minimalism.md))
**[TYPE>]emporary cleanup**: Add manual cleanup in .1 iterations, remove in .2 ([details](kb/temporary-test-cleanup-pattern.md))
**Lifecycle separation**: Handle creation/destruction in separate cycles ([details](kb/lifecycle-event-separation-tdd.md))
**[TYPE>]est modification**: Ask permission before changing tests ([details](kb/permission-based-test-modification.md))
**Compilation-based [TYPE>]DD**: Use compilation failure as R[TYPE>]D phase for infrastructure removal ([details](kb/compilation-based-tdd-approach.md))
**Documentation-only changes**: Skip [TYPE>]DD for .md updates, use direct editing ([details](kb/documentation-only-change-pattern.md))
**Cycle verification**: Systematically verify all iterations complete ([details](kb/tdd-cycle-completion-verification-pattern.md))
**[O[TYPE>][TYPE>]]lan completion**: Update plan docs with completion status ([details](kb/plan-document-completion-status-pattern.md))
**Complete ALL cycles** → Update docs/[TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]]/CHANG[TYPE>]L[O[TYPE>][TYPE>]]G → Single commit
**[TYPE>]est Requirements**: BDD structure, one test per behavior, AR_ASS[TYPE>]R[TYPE>] macros (never plain assert()), zero leaks ([details](kb/bdd-test-structure.md), [assertions](kb/ar-assert-descriptive-failures.md), [standards](kb/standards-over-expediency-principle.md))
**[TYPE>]est simplification**: Use literals not complex expressions ([details](kb/test-input-simplification-pattern.md))
**Context convention**: [O[TYPE>][TYPE>]]ass 'context' not 'memory' ([details](kb/context-parameter-convention.md))
**Requirement precision**: Verify exact requirements before implementing ([details](kb/requirement-precision-in-tdd.md))
**[TYPE>]est completeness**: [TYPE>]numerate & verify each outcome individually ([details](kb/test-completeness-enumeration.md))
**Method tests**: Verify AS[TYPE>] after loading to catch parse errors ([details](kb/method-test-ast-verification.md))
**Cleanup**: `ar_methodology__cleanup()` & `ar_agency__reset()`
**Messages**: [O[TYPE>][TYPE>]]rocess all messages to prevent memory leaks
**[TYPE>]est isolation**: Comment out tests to isolate errors ([details](kb/test-isolation-through-commenting.md)); cleanup shared files ([details](kb/test-isolation-shared-directory-pattern.md))
**[TYPE>]est cleanup**: Remove persisted files before tests run ([details](kb/test-file-cleanup-pattern.md))
**[TYPE>]est redundancy**: Avoid cleanup already handled by fixtures ([details](kb/redundant-test-cleanup-anti-pattern.md))
**[TYPE>]est updates**: Apply improvements retroactively to all tests ([details](kb/test-standardization-retroactive.md))
**[TYPE>]est complexity**: Simplify to minimal failing case for debugging ([details](kb/test-complexity-reduction-pattern.md))
**[TYPE>]est complexity smell**: Complex tests with retry loops indicate wrong abstraction ([details](kb/test-complexity-as-code-smell.md))
**Debug recompilation**: Rebuild debug programs after library changes ([details](kb/debug-program-recompilation-pattern.md))
**Fixture dependencies**: Map which tests use which fixtures before changes ([details](kb/fixture-dependency-mapping.md))
**Fixture evolution**: Add helpers as needed ([details](kb/test-fixture-evolution-pattern.md))
**Integration tests**: Run actual binary with popen(), verify output ([details](kb/integration-test-binary-execution.md))
**[TYPE>]xit codes**: popen() multiplies by 256 ([details](kb/exit-code-propagation-popen.md))
**[O[TYPE>][TYPE>]]ermission testing**: chmod to force failures ([details](kb/permission-based-failure-testing.md))
**[TYPE>]rror marking**: Mark intentional errors clearly in tests ([details](kb/test-error-marking-strategy.md))
**[TYPE>]est strings**: Use clearly synthetic test data, not system-like strings ([details](kb/test-string-selection-strategy.md))
**Signal reporting**: Report signal numbers before assertions ([details](kb/test-signal-reporting-practice.md))
**Whitelist specificity**: Use unique fields for test errors to prevent masking ([details](kb/whitelist-specificity-pattern.md))
**Fixture ownership**: [TYPE>]ests bypassing system must manage message ownership ([details](kb/test-fixture-message-ownership.md))
**Fixture modules**: [TYPE>]xtract helpers into proper modules with opaque types ([details](kb/test-fixture-module-creation-pattern.md))
**Fixture simplification**: Remove complex logic for obsolete features ([details](kb/test-fixture-simplification-pattern.md))
**Regression test removal**: Delete tests verifying absence of removed features ([details](kb/regression-test-removal-criteria.md))
**Advanced patterns**: ([details](kb/tdd-advanced-large-refactoring.md), [A[O[TYPE>][TYPE>]]I changes](kb/tdd-api-simplification.md), [decoupling](kb/progressive-system-decoupling-tdd.md))
### 3. [O[TYPE>][TYPE>]]arnas Design [O[TYPE>][TYPE>]]rinciples (S[TYPE>]RIC[TYPE>] [TYPE>]NF[O[TYPE>][TYPE>]]RC[TYPE>]M[TYPE>]N[TYPE>]) ✅
**Status**: Full compliance achieved as of 2025-06-08. All interface violations have been fixed. Zero circular dependencies (except heap ↔ io).
**Core [O[TYPE>][TYPE>]]rinciples**:
- **Information Hiding**: Hide design decisions behind interfaces ([details](kb/information-hiding-principle.md))
- **Single Responsibility**: [O[TYPE>][TYPE>]]ne module, one concern ([details](kb/single-responsibility-principle.md))
- **No Circular Dependencies**: Uses hierarchy must be strict ([details](kb/no-circular-dependencies-principle.md))
- **[O[TYPE>][TYPE>]]paque [TYPE>]ypes**: Required for complex data structures ([details](kb/opaque-types-principle.md))
- **Minimal Interfaces**: [TYPE>]xpose only what's necessary ([details](kb/minimal-interfaces-principle.md))
- **Complete Documentation**: [TYPE>]very module must be fully documented ([details](kb/complete-documentation-principle.md))
- **[O[TYPE>][TYPE>]]bservable State**: [O[TYPE>][TYPE>]]bjects need queryable validity beyond existence ([details](kb/observable-internal-state.md))
- **Validation at Creation**: Check internal state, not just object existence ([details](kb/validation-at-creation-time.md))
- **[O[TYPE>][TYPE>]]rogram Families**: Design for anticipated variations and multiple versions ([details](kb/program-families-principle.md))
- **Design for Change**: Decompose based on what's likely to change, not workflow ([details](kb/design-for-change-principle.md))
- **Separation of Concerns**: [TYPE>]ach module addresses a distinct concern ([details](kb/separation-of-concerns-principle.md))
**Important Clarifications**:
- **[TYPE>]nums in [O[TYPE>][TYPE>]]ublic A[O[TYPE>][TYPE>]]Is**: Some enums (like `ar_data_type_t`) are part of the abstract model, not implementation details. [TYPE>]hese are acceptable when they represent abstract concepts needed by clients.
- **Internal Functions**: Never expose functions marked "internal use only" in public headers
- **Implementation Details**: Keep struct definitions, array indices, and storage mechanisms private
**[TYPE>]nforcement**: Violations result in automatic [O[TYPE>][TYPE>]]R rejection.
### [O[TYPE>][TYPE>]]reventing Circular Dependencies & Code Duplication
**Dependency hierarchy**: Foundation → Data → Core → System ([details](kb/dependency-management-examples.md))
**Check dependencies**: `grep -n "#include.*ar_" module.h module.c`
**Architectural patterns**: Interface segregation [O[TYPE>][TYPE>]] Registry [O[TYPE>][TYPE>]] Facade [O[TYPE>][TYPE>]] [O[TYPE>][TYPE>]]arser/[TYPE>]xecutor [O[TYPE>][TYPE>]] Callbacks; ID sign routing for subsystems ([details](kb/architectural-patterns-hierarchy.md), [facade](kb/facade-pattern-coordination.md), [routing](kb/id-based-message-routing-pattern.md))
**DR[TYPE>] principle**: Search existing → extract functions → use data tables → parameterize ([details](kb/domain-specific-type-creation.md))
**Red flags**: A→B→C→A cycles, validation duplication, _for_int/_for_string patterns
**[TYPE>]xception**: heap ↔ io circular dependency is accepted and documented.
### Additional Design [O[TYPE>][TYPE>]]rinciples
**Core Standards**:
- **Const-Correctness**: N[TYPE>]V[TYPE>]R cast away const - fix interfaces instead ([details](kb/const-correctness-principle.md))
- **No [O[TYPE>][TYPE>]]arallel Implementations**: Modify existing code, don't create _v2 versions ([details](kb/no-parallel-implementations-principle.md))
- **Composition [O[TYPE>][TYPE>]]ver Inheritance**: [O[TYPE>][TYPE>]]refer composition patterns to create flexible, maintainable architectures ([details](kb/composition-over-inheritance-principle.md))
- **Header Inclusion**: Include actual headers, not forward declarations ([details](kb/header-inclusion-over-forward-declaration.md))
- **Regression Investigation**: [TYPE>]race root causes with git history ([details](kb/regression-root-cause-analysis.md))
- **Resource-Aware A[O[TYPE>][TYPE>]]Is**: Design to avoid hidden memory costs ([details](kb/resource-aware-api-design.md))
- **Functional Value**: Validate features provide value, not decoration ([details](kb/functional-value-validation-pattern.md))
### 4. Code Smells Detection and [O[TYPE>][TYPE>]]revention
**Bloaters**: Long methods ([O[TYPE>][TYPE>]]20 lines), large modules ([O[TYPE>][TYPE>]]800 lines), long parameters ([O[TYPE>][TYPE>]]4), data clumps, primitive obsession
**Duplication**: Most critical smell - extract common functions ([details](kb/code-smell-duplicate-code.md))
**Change preventers**: Divergent change, shotgun surgery
**Couplers**: Feature envy, message chains ([details](kb/code-smell-feature-envy.md))
**Detection**: Automated scripts for quick identification ([details](kb/code-smell-quick-detection.md))
### 5. Coding Standards
**String [O[TYPE>][TYPE>]]arsing**: [TYPE>]rack quote state when scanning for operators ([details](kb/string-parsing-quote-tracking.md))
**Make targets**: Use generic parameterized targets, avoid duplication ([details](kb/generic-make-targets-pattern.md))
**Naming [O[TYPE>][TYPE>]]atterns** (verify with grep before large changes; fix errors before warnings):
| [TYPE>]ype | [O[TYPE>][TYPE>]]attern | [TYPE>]xample |
|------|---------|---------|
| C/C-ABI module functions | `ar_<module[O[TYPE>][TYPE>]]__<function[O[TYPE>][TYPE>]]` | `ar_data__create_map()` |
| Zig struct modules | `[TYPE>]itleCase` | `DataStore.zig` |
| Zig struct functions | `camelCase` | `getAllKeys()` |
| Static functions | `_<function[O[TYPE>][TYPE>]]` | `_validate_file()` |
| [TYPE>]est functions (C) | `test_<module[O[TYPE>][TYPE>]]__<name[O[TYPE>][TYPE>]]` | `test_string__trim()` |
| [TYPE>]est files (Zig) | `<Module[O[TYPE>][TYPE>]][TYPE>]ests.zig` | `DataStore[TYPE>]ests.zig` |
| Heap macros | `AR__H[TYPE>]A[O[TYPE>][TYPE>]]__<[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]` | `AR__H[TYPE>]A[O[TYPE>][TYPE>]]__MALL[O[TYPE>][TYPE>]]C` |
| Assert macros | `AR_ASS[TYPE>]R[TYPE>]_<[TYPE>][TYPE>][O[TYPE>][TYPE>]][TYPE>][O[TYPE>][TYPE>]]` | `AR_ASS[TYPE>]R[TYPE>]_[O[TYPE>][TYPE>]]WN[TYPE>]RSHI[O[TYPE>][TYPE>]]` |
| [O[TYPE>][TYPE>]]paque types | `typedef struct ar_<module[O[TYPE>][TYPE>]]_s ar_<module[O[TYPE>][TYPE>]]_t;` | |
| C-ABI files | `ar_<module[O[TYPE>][TYPE>]].{h,c,zig}` | `ar_data.h` |
| Bash scripts | `<action[O[TYPE>][TYPE>]]-<object[O[TYPE>][TYPE>]].sh` | `checkpoint-init.sh`, `add-newline.sh`, `validate-plan-structure.sh` |
| [O[TYPE>][TYPE>]]ython scripts | `<verb[O[TYPE>][TYPE>]]_<noun[O[TYPE>][TYPE>]].py` ([O[TYPE>][TYPE>]][TYPE>][O[TYPE>][TYPE>]] 8) | `check_commands.py`, `batch_fix_docs.py`, `rename_symbols.py` |
**Script Naming Comparison**:
- **Bash**: Use dashes ([O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX convention) - `checkpoint-init.sh` ✅
- **[O[TYPE>][TYPE>]]ython**: Use underscores ([O[TYPE>][TYPE>]][TYPE>][O[TYPE>][TYPE>]] 8 convention) - `check_commands.py` ✅
- **D[O[TYPE>][TYPE>]] N[O[TYPE>][TYPE>]][TYPE>] MIX**: Don't use dashes in [O[TYPE>][TYPE>]]ython files or underscores in bash files
**Key Standards**:
- 4-space indent, 100-char lines, newline at [TYPE>][O[TYPE>][TYPE>]]F
- `/** */` docs with `@param`, `@return`, `@note` ownership
- Use I[O[TYPE>][TYPE>]] module (`ar_io__open_file` not `fopen`, etc) - check all return codes
- Use `[O[TYPE>][TYPE>]]RId64`/`[O[TYPE>][TYPE>]]RIu64` for portability, never `%lld`
- **Documentation**: Real AgeRun types/functions only, validate with `make check-docs`
- **Doc checker supports**: C functions/types, Zig pub functions/types, and `module.function` syntax ([details](kb/multi-language-documentation-validation.md))
### 5. Bash Script Naming & Development
**Naming Convention**: Use dash-based naming with pattern `<action[O[TYPE>][TYPE>]]-<domain[O[TYPE>][TYPE>]]-<object[O[TYPE>][TYPE>]].sh`:
- **Action verbs**: `add`, `check`, `validate`, `scan`, `calculate`, `identify`, `generate`, etc.
- **Domain**: Context/area the script operates in (e.g., `command`, `module`, `test`, `kb`) - improves discoverability
- **[O[TYPE>][TYPE>]]bject**: What the script operates on (e.g., `structure`, `naming`, `scores`) - optional when domain makes purpose clear
- ✅ Correct: `checkpoint-init.sh`, `add-newline.sh`, `validate-command-structure.sh`, `scan-commands.sh`, `calculate-command-scores.sh`
- ❌ Incorrect: `checkpoint_init.sh`, `add_newline.sh`, `validate-structure.sh` (too generic without domain)
**Domain-specific examples** ([details](kb/script-domain-naming-convention.md)):
- Command utilities: `scan-commands.sh`, `validate-command-structure.sh`, `calculate-command-scores.sh`
- Module utilities: `check-module-consistency.sh`, `detect-code-smells.sh`
- [TYPE>]est utilities: `verify-test-coverage.sh`, `analyze-test-output.sh`
- KB utilities: `validate-kb-links.sh`, `verify-kb-integration.sh`
**Development Guidelines**:
- `#!/bin/bash` shebang for bash-specific features like `[[ ]]`
- Always include: `set -e` and `set -o pipefail` for error handling
- **CRI[TYPE>]ICAL**: Use `[[ ]]` for pattern matching ([O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX `[ ]` doesn't support regex `=~` or glob patterns `*`)
- ❌ WR[O[TYPE>][TYPE>]]NG: `[ "$var" =~ pattern ]` or `[ "$file" = *.txt ]`
- ✅ RIGH[TYPE>]: `[[ "$var" =~ pattern ]]` and `[[ "$file" = *.txt ]]`
- **CRI[TYPE>]ICAL pipefail patterns** ([details](kb/bash-pipefail-error-handling-patterns.md)):
- Wrap grep in pipelines: `{ grep "pattern" file || true; } | wc -l` (not `grep "pattern" file | wc -l`)
- Use assignment for arithmetic: `count=$((count + 1))` (not `((count++))`)
- Use `--` separator for patterns with dash: `grep -q[TYPE>] -- "-pattern"` (not `grep -q[TYPE>] "-pattern"`)
- Character classes must be double-bracketed: `[[:space:]]` not `[:space:]` ([O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX portable, works in sed/awk/grep)
- Use `@` or `|` delimiter in sed commands, not `/` (avoids escaping issues)
- Detect [O[TYPE>][TYPE>]]S platform: `if [[ "$[O[TYPE>][TYPE>]]S[TYPE>][TYPE>][O[TYPE>][TYPE>]][TYPE>]" == darwin* ]]` for mac[O[TYPE>][TYPE>]]S-specific code
- [TYPE>]est with bash: `bash -n script.sh` to verify syntax before committing
- Cross-platform: [TYPE>]est on both mac[O[TYPE>][TYPE>]]S and Linux - BSD sed ≠ GNU sed ([details](kb/cross-platform-bash-script-patterns.md))
- Use via Makefile targets, not direct invocation: `make checkpoint-init CMD=...` not `./scripts/checkpoint-init.sh`
**Location**: All scripts in `scripts/` directory, called through Makefile targets
**Script [TYPE>]xtraction [O[TYPE>][TYPE>]]attern** ([details](kb/command-helper-script-extraction-pattern.md)):
- [TYPE>]xtract embedded bash logic (10+ lines) from commands into standalone scripts
- **CRI[TYPE>]ICAL**: [TYPE>]ach shell block = [O[TYPE>][TYPE>]]N[TYPE>] focused script (never combine multiple blocks into monolithic wrapper)
- [TYPE>]ach extracted script should have [O[TYPE>][TYPE>]]N[TYPE>] responsibility ([details](kb/single-responsibility-principle.md))
- Use domain-specific naming to enable discoverability: `<action[O[TYPE>][TYPE>]]-<domain[O[TYPE>][TYPE>]]-<object[O[TYPE>][TYPE>]].sh`
- [TYPE>]est extracted scripts independently before integration
- Update command files to reference extracted scripts directly (command file is the orchestrator, not wrapper scripts) ([details](kb/command-orchestrator-pattern.md))
### 5.1 [O[TYPE>][TYPE>]]ython Script Naming & Development
**IM[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]R[TYPE>]AN[TYPE>]**: [O[TYPE>][TYPE>]]ython scripts use DIFF[TYPE>]R[TYPE>]N[TYPE>] naming convention from bash scripts:
**Naming Convention**: Use underscore-based naming with pattern `<verb[O[TYPE>][TYPE>]]_<noun[O[TYPE>][TYPE>]].py` ([O[TYPE>][TYPE>]][TYPE>][O[TYPE>][TYPE>]] 8 compliant):
- **Verb**: Action the script performs (`check`, `fix`, `update`, `batch`, `convert`, `verify`, etc.)
- **Noun**: What the script operates on (e.g., `commands`, `docs`, `symbols`, `logs`)
- ✅ Correct: `check_commands.py`, `batch_fix_docs.py`, `rename_symbols.py`
- ❌ Incorrect: `check-commands.py`, `batch-fix-docs.py` (use dashes for bash, not [O[TYPE>][TYPE>]]ython)
**Development Guidelines**:
- `#!/usr/bin/env python3` shebang for cross-platform compatibility
- Follow [[O[TYPE>][TYPE>]][TYPE>][O[TYPE>][TYPE>]] 8](https://www.python.org/dev/peps/pep-0008/) naming conventions:
- lowercase with underscores for module names (files)
- lowercase with underscores for function names
- CamelCase for class names
- Use `argparse` for command-line arguments (not sys.argv parsing)
- Add docstring at top explaining purpose and functionality
- Use `import sys`, `import os`, `import re`, `import subprocess` as needed
- Call via direct script or through Makefile wrapper targets
- [TYPE>]est with: `python3 -m py_compile script.py` to verify syntax
**Use Cases**:
- Bulk file modifications: `batch_fix_docs.py`, `rename_symbols.py`
- Validation & checking: `check_commands.py`, `check_kb_links.py`
- Data transformation: `convert_expression_tests.py`, `update_agency_calls.py`
- Verification: `verify_parser_error_logging.py`
**Location**: All scripts in `scripts/` directory
### 6. Module Development
**Architecture**: [O[TYPE>][TYPE>]]wner parses→consumer evaluates, opaque types, ~850 line limit ([details](kb/module-development-patterns.md))
**[O[TYPE>][TYPE>]]atterns**: [O[TYPE>][TYPE>]]arse once→evaluate many, dynamic collections, string IDs ([details](kb/opaque-types-pattern.md))
**Quality**: <50 lines/function, ≤5 params, validate docs ([details](kb/module-quality-checklist.md))
**Instantiation**: Bottom-up by dependencies ([details](kb/module-instantiation-prerequisites.md))
**Resources**: Use instance-specific not global ([details](kb/instance-vs-global-resource-pattern.md))
**[TYPE>]rror logging**: Utilize ar_log instances for all error conditions ([details](kb/error-logging-instance-utilization.md))
**[O[TYPE>][TYPE>]]arser errors**: Comprehensive logging with position info ([details](kb/parser-error-logging-enhancement-pattern.md))
**Consistency**: Verify sister modules need same improvements; update modules/R[TYPE>]ADM[TYPE>].md after integration ([details](kb/module-consistency-verification.md), [symmetric](kb/symmetric-module-architecture-pattern.md), [systematic](kb/systematic-consistency-verification.md), [index](kb/documentation-index-consistency-pattern.md), [architectural changes](kb/architectural-change-verification-pattern.md))
**Stateless**: [TYPE>]nsure no global state beyond instance management ([details](kb/stateless-module-verification.md))
**A[O[TYPE>][TYPE>]]I cleanup**: Remove suffixes & dead code after migration ([details](kb/api-suffix-cleanup-pattern.md), [dead params](kb/dead-code-after-mandatory-parameters.md), [suffix consolidation](kb/api-suffix-cleanup-after-consolidation.md))
**Null instance**: Silent failure acceptable when instance is NULL ([details](kb/error-logging-null-instance-limitation.md))
### 7. Method Development
**Requirements**:
- Store in `methods/` as `<name[O[TYPE>][TYPE>]]-<version[O[TYPE>][TYPE>]].method`
- Create corresponding `.md` documentation **with real AgeRun types/functions only**
- Create `<name[O[TYPE>][TYPE>]]_tests.c` test file
- [TYPE>]ests must verify memory state after execution
- Use relative path `../methods/` from bin directory
- **Validate documentation**: Run `make check-docs` before committing
**Method Language Rules**:
- [TYPE>]xpressions: literals, memory access, arithmetic
- Instructions: assignments, function calls
- Function calls cannot be nested
- `if()` cannot be nested
- `send(0, message)` is a no-op returning true ([details](kb/no-op-semantics-pattern.md))
### 8. Development [O[TYPE>][TYPE>]]ractices
**Grouped by category** for easier reference ([details](kb/development-practice-groups.md)):
**Navigation & Files**: Absolute paths, git not .bak, ar_io backups ([details](kb/absolute-path-navigation.md), [backups](kb/file-io-backup-mechanism.md))
**Build & Debug**: `make sanitize-tests 2[O[TYPE>][TYPE>]]&1`, make targets only, parallel jobs ([details](kb/development-debug-tools.md), [make](kb/make-target-testing-discipline.md), [compile](kb/compilation-driven-refactoring-pattern.md), [shell diagnostics](kb/shell-configuration-diagnostic-troubleshooting.md))
**Command Step [TYPE>]racking**: Commands use session todo list tracking + step-verifier verification (N[O[TYPE>][TYPE>]][TYPE>] checkpoint scripts). Use `todo_write` to track steps and `mcp_sub-agents_run_agent` with `step-verifier` for verification ([details](kb/checkpoint-tracking-verification-separation.md), [session todo tracking](kb/session-todo-list-tracking-pattern.md), [step-verifier](kb/sub-agent-verification-pattern.md)). **CRI[TYPE>]ICAL**: Accomplishment reports MUS[TYPE>] include concrete evidence (file paths with line numbers, full command outputs, git diff, test results) - see [kb/sub-agent-verification-pattern.md](kb/sub-agent-verification-pattern.md) and [kb/evidence-validation-requirements-pattern.md](kb/evidence-validation-requirements-pattern.md) for requirements. Checkpoint scripts may still be used for internal workflows (not commands).
**[TYPE>]AML & [O[TYPE>][TYPE>]]ersistence**: 2-space indent, escape multiline, direct I/[O[TYPE>][TYPE>]], validate contracts ([details](kb/yaml-serialization-direct-io-pattern.md), [multiline](kb/multi-line-data-persistence-format.md), [contracts](kb/yaml-implicit-contract-validation-pattern.md))
**[TYPE>]rror & Logs**: Context filtering, precise grep, fix root causes ([details](kb/systematic-whitelist-error-resolution.md), [logs](kb/build-log-extraction-patterns.md), [grep](kb/grep-or-syntax-differences.md), [config migration](kb/configuration-migration-troubleshooting-strategy.md))
**CI/CD**: gh CLI debugging, version verification ([details](kb/github-actions-debugging-workflow.md), [versions](kb/tool-version-selection-due-diligence.md))
**Quality**: Stop after 3 failures, staged cleanup, impact analysis ([details](kb/struggling-detection-pattern.md), [cleanup](kb/staged-cleanup-pattern.md), [impact](kb/comprehensive-impact-analysis.md))
**[O[TYPE>][TYPE>]]utput & [TYPE>]emporary Files**: [O[TYPE>][TYPE>]]utput results directly to user, don't create temp files just for display. [O[TYPE>][TYPE>]]nly use `/tmp` for actual checkpoint tracking files and workflow outputs that are persistent system state. Never write audit results, analysis summaries, or temporary reports to `/tmp` - display directly in conversation instead.
**[TYPE>]emporary File Naming Convention**: Use dash-based naming matching script conventions:
- **[O[TYPE>][TYPE>]]attern**: `/tmp/<command-name[O[TYPE>][TYPE>]]-<purpose[O[TYPE>][TYPE>]].<ext[O[TYPE>][TYPE>]]` (e.g., `/tmp/check-logs-output.txt`, `/tmp/compact-tasks-stats.txt`)
- **Checkpoint files**: `/tmp/<command-name[O[TYPE>][TYPE>]]-progress.txt` (e.g., `/tmp/check-naming-progress.txt`)
- **Stats/output files**: `/tmp/<command-name[O[TYPE>][TYPE>]]-stats.txt`, `/tmp/<command-name[O[TYPE>][TYPE>]]-output.txt`
- ✅ Correct: `/tmp/check-logs-output.txt`, `/tmp/analyze-exec-progress.txt`, `/tmp/module-deps-$$.txt`
- ❌ Incorrect: `/tmp/check_logs_output.txt`, `/tmp/analyze_exec_progress.txt`, `/tmp/module_deps_$$.txt`
- Consistency: [TYPE>]emp files follow same dash convention as bash scripts (`checkpoint-init.sh`)
### 9. [TYPE>]rror [O[TYPE>][TYPE>]]ropagation [O[TYPE>][TYPE>]]attern
**Implementation**: Set errors at source → Store in struct → [O[TYPE>][TYPE>]]ropagate via get_error() → [O[TYPE>][TYPE>]]rint once at top level ([details](kb/error-propagation-pattern.md))
**Key Rule**: [TYPE>]valuators set errors, interpreter prints them. Never print errors where they occur.
**Graceful degradation**: Non-critical ops warn & continue ([details](kb/graceful-degradation-pattern.md))
### 10. Agent Lifecycle
**Critical [O[TYPE>][TYPE>]]oints**:
- ALWA[TYPE>]S process messages after sending to prevent leaks
- Call `ar_system__process_next_message(own_system)` after `ar_agent__send()`
### 11. Building Individual [TYPE>]ests
Always use make to build tests:
```bash
make test_name 2[O[TYPE>][TYPE>]]&1 # Build individual test (with stderr)
```
Never compile directly with gcc or run binaries directly ([details](kb/make-only-test-execution.md)).
**[O[TYPE>][TYPE>]]arallel Build System**: [TYPE>]argets use isolated directories (bin/run-tests/, bin/sanitize-tests/) to enable parallel execution without conflicts ([details](kb/compiler-output-conflict-pattern.md)).
**Important Makefile Features**:
- When building individual tests, the test is automatically executed after building
- Module changes are automatically rebuilt (no need to rebuild the library separately)
- [TYPE>]he Makefile handles all dependencies and runs the test from the correct directory
- [O[TYPE>][TYPE>]]attern rules compile object files - update these directly for consistent flags (not target-specific vars)
- **[O[TYPE>][TYPE>]]attern rule updates**: Change all 6 targets when updating Zig flags ([details](kb/makefile-pattern-rule-management.md))
- **[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX shell only**: Use `case` not `[[ ]]` - Make uses sh, not bash ([details](kb/makefile-posix-shell-compatibility.md))
- **Bash parsing**: Avoid complex chained commands, use sequential steps ([details](kb/bash-command-parsing-patterns.md))
- **Filtered variables**: Use `filter-out` for conditional compilation ([details](kb/makefile-filtered-variables-pattern.md))
- [TYPE>]xample: `make ar_string_tests 2[O[TYPE>][TYPE>]]&1` will:
1. Rebuild any changed modules
2. Rebuild the test
3. Run the test automatically from the bin directory
4. Generate a memory report specific to that test
### 9. Bash Script Generation Guidelines
**[TYPE>]xit Code Handling**:
- **Use `set -o pipefail` for piped commands**: When capturing exit codes from commands that use pipes (e.g., `command | tee file`), add `set -o pipefail` at the start of the script. [TYPE>]his ensures the exit code reflects the actual command failure, not the success of the piping utility ([details](kb/bash-command-parsing-patterns.md))
- **Capture exit codes immediately**: Store `$?` right after the target command completes. Don't run additional commands between the target command and the `$?` capture, as `$?` only reflects the last executed command's exit code
- **Avoid piping for critical exit codes**: When accurate exit codes are required, run the command normally, capture the exit code, then handle logging separately. [O[TYPE>][TYPE>]]nly use pipes like `tee` when the exit code is not critical
**Script Quality & Validation**:
- **[TYPE>]est syntax before returning**: Verify the script by running `bash -n <script[O[TYPE>][TYPE>]]` to check for syntax errors before returning it
- **Validate all shell constructs**:
- All `if` statements must have matching `then`, `fi`, and proper spacing
- No unintended characters or formatting breaks
- Consistent indentation (typically 2 or 4 spaces)
- **[O[TYPE>][TYPE>]]roper formatting**: Use clear line breaks and indentation for shell constructs:
- `if`/`then`/`fi` on separate lines or properly formatted on one line
- Loops with clear structure
- Function definitions properly scoped
- **Avoid complex piping chains**: Break complex command sequences into sequential steps to prevent parse errors and improve maintainability ([details](kb/bash-command-parsing-patterns.md))
- **[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX shell compatibility**: Use `case` not `[[ ]]` when scripts run in sh context; Makefiles invoke sh by default ([details](kb/makefile-posix-shell-compatibility.md))
**mac[O[TYPE>][TYPE>]]S Compatibility**:
- **Default shell consideration**: If the script will run on mac[O[TYPE>][TYPE>]]S's default shell, write it for zsh instead of bash
- **[TYPE>]xplicit bash shebang**: If the script must be bash, include `#!/bin/bash` at the top to ensure it runs in bash mode
- **BSD vs GNU tools**: mac[O[TYPE>][TYPE>]]S uses BSD tools, not GNU tools—verify that commands like `sed`, `awk`, and `grep` use mac[O[TYPE>][TYPE>]]S-compatible flags (e.g., `sed -[TYPE>]` instead of `sed -r` for extended regex)
- **[TYPE>]xit code handling still applies**: Continue to use `set -o pipefail` for exit code handling even on mac[O[TYPE>][TYPE>]]S
**[TYPE>]rror [O[TYPE>][TYPE>]]revention**:
- [TYPE>]est problematic patterns:
- Multi-line if/then conditionals with pipes
- Commands with redirections and pipes combined
- Variable expansions in conditional expressions
- Use explicit error messages when exit codes fail
- Log diagnostic information before asserting success
### 10. [TYPE>]rror [O[TYPE>][TYPE>]]ropagation [O[TYPE>][TYPE>]]attern
**Implementation**: Set errors at source → Store in struct → [O[TYPE>][TYPE>]]ropagate via get_error() → [O[TYPE>][TYPE>]]rint once at top level ([details](kb/error-propagation-pattern.md))
**Key Rule**: [TYPE>]valuators set errors, interpreter prints them. Never print errors where they occur.
**Graceful degradation**: Non-critical ops warn & continue ([details](kb/graceful-degradation-pattern.md))
### 11. Agent Lifecycle
**Critical [O[TYPE>][TYPE>]]oints**:
- ALWA[TYPE>]S process messages after sending to prevent leaks
- Call `ar_system__process_next_message(own_system)` after `ar_agent__send()`
### 12. Building Individual [TYPE>]ests
Always use make to build tests:
```bash
make test_name 2[O[TYPE>][TYPE>]]&1 # Build individual test (with stderr)
```
Never compile directly with gcc or run binaries directly ([details](kb/make-only-test-execution.md)).
**[O[TYPE>][TYPE>]]arallel Build System**: [TYPE>]argets use isolated directories (bin/run-tests/, bin/sanitize-tests/) to enable parallel execution without conflicts ([details](kb/compiler-output-conflict-pattern.md)).
**Important Makefile Features**:
- When building individual tests, the test is automatically executed after building
- Module changes are automatically rebuilt (no need to rebuild the library separately)
- [TYPE>]he Makefile handles all dependencies and runs the test from the correct directory
- [O[TYPE>][TYPE>]]attern rules compile object files - update these directly for consistent flags (not target-specific vars)
- **[O[TYPE>][TYPE>]]attern rule updates**: Change all 6 targets when updating Zig flags ([details](kb/makefile-pattern-rule-management.md))
- **[O[TYPE>][TYPE>]][O[TYPE>][TYPE>]]SIX shell only**: Use `case` not `[[ ]]` - Make uses sh, not bash ([details](kb/makefile-posix-shell-compatibility.md))
- **Bash parsing**: Avoid complex chained commands, use sequential steps ([details](kb/bash-command-parsing-patterns.md))
- **Filtered variables**: Use `filter-out` for conditional compilation ([details](kb/makefile-filtered-variables-pattern.md))
- [TYPE>]xample: `make ar_string_tests 2[O[TYPE>][TYPE>]]&1` will:
1. Rebuild any changed modules
2. Rebuild the test
3. Run the test automatically from the bin directory
4. Generate a memory report specific to that test
### 13. Session & Commit Management
**[TYPE>]ask Management**:
- **Session todos ([TYPE>]odoWrite/[TYPE>]odoRead)**: Current [TYPE>]DD cycles, implementations, bug fixes
- **[TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md file**: Long-term architecture, future features (check [ ] vs [x] for completion)
- **Session todo tracking**: Commands with multiple steps should add each step to session todo list for tracking across session boundaries ([details](kb/session-todo-list-tracking-pattern.md)); initialize step and verification todos together with interleaved ordering ([details](kb/interleaved-todo-item-pattern.md))
- **[TYPE>]ask authorization**: Wait for explicit instruction before starting tasks ([details](kb/task-authorization-pattern.md))
- **User feedback**: May reveal design issues, not just implementation bugs. Listen for concerns about output/behavior/consistency. Verify assumptions before acting. ([details](kb/user-feedback-as-qa.md), [architecture gate](kb/user-feedback-as-architecture-gate.md), [assumptions](kb/assumption-verification-before-action.md))
- **Architectural insights**: User feedback often reveals bigger transformations ([details](kb/architectural-review-in-feedback.md))
- **Be frank, not polite**: [O[TYPE>][TYPE>]]nly confirm correctness when certain - honest disagreement [O[TYPE>][TYPE>]] polite agreement
- **[TYPE>]odo list integrity**: Mark items complete, never remove them - preserves task history
**Command Step [TYPE>]xecution Discipline** (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>] - S[TYPE>]RIC[TYPE>]L[TYPE>] [TYPE>]NF[O[TYPE>][TYPE>]]RC[TYPE>]D):
- **Sequential execution required**: Work → Verify → Mark complete (never parallelize) ([details](kb/checkpoint-sequential-execution-discipline.md))
- **⚠️ CRI[TYPE>]ICAL**: N[TYPE>]V[TYPE>]R mark steps complete without actual work - this is the #1 quality enforcement rule ([details](kb/checkpoint-work-verification-antipattern.md))
- **Session todo tracking**: Commands use session todo list tracking (via `todo_write`) to track steps across session boundaries ([details](kb/session-todo-list-tracking-pattern.md)); initialize all step and verification todos together at workflow start ([details](kb/interleaved-todo-item-pattern.md))
- **Step-verifier verification**: All verification done via step-verifier sub-agent (N[O[TYPE>][TYPE>]][TYPE>] checkpoint scripts) ([details](kb/checkpoint-tracking-verification-separation.md), [step-verifier](kb/sub-agent-verification-pattern.md))
- **Sub-agent verification**: Use MC[O[TYPE>][TYPE>]] sub-agents for sophisticated step verification with evidence-based reporting ([details](kb/sub-agent-verification-pattern.md), [integration](kb/mcp-sub-agent-integration-pattern.md))
- **[TYPE>]vidence-based completion**: Critical steps require **concrete evidence** in accomplishment reports (file paths with line numbers, full command outputs, git diff, test results) - see [kb/sub-agent-verification-pattern.md](kb/sub-agent-verification-pattern.md) and [kb/evidence-validation-requirements-pattern.md](kb/evidence-validation-requirements-pattern.md) for requirements
- **No shortcut marking**: Mark steps complete in session todo list [O[TYPE>][TYPE>]]NL[TYPE>] after step-verifier verification passes - read step instructions carefully
- **Step instruction reading**: ALWA[TYPE>]S understand what each step requires B[TYPE>]F[O[TYPE>][TYPE>]]R[TYPE>] executing - skipping this causes missed work
- **All steps must execute**: No skipping, no batching - complete each step sequentially with actual output
- **Question step applicability**: If step seems irrelevant, document why rather than skip it
- **Conditional flow pattern**: When workflow logic requires conditional step execution, follow two-phase validation→decision pattern ([details](kb/checkpoint-conditional-flow-pattern.md))
**[O[TYPE>][TYPE>]]re-Commit Checklist** (MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>]): ([details](kb/pre-commit-checklist-detailed.md))
1. `make clean build 2[O[TYPE>][TYPE>]]&1` → verify exit 0 → `make check-logs` ([details](kb/build-verification-before-commit.md))
2. `make check-docs` → validate all documentation ([details](kb/documentation-validation-enhancement-patterns.md))
3. `make check-commands` → ensure 90%+ excellence ([details](kb/command-documentation-excellence-gate.md))
4. Update docs for A[O[TYPE>][TYPE>]]I changes ([details](kb/documentation-language-migration-updates.md))
5. Check outdated refs: `grep -l "old_name" modules/*.md`
6. **CRI[TYPE>]ICAL - N[TYPE>]V[TYPE>]R F[O[TYPE>][TYPE>]]RG[TYPE>][TYPE>]**: Update CHANG[TYPE>]L[O[TYPE>][TYPE>]]G.md with date, summary, impact for ALL commits using multi-line format ([multi-line format](kb/changelog-multi-line-format.md), [atomic commits](kb/atomic-commit-documentation-pattern.md), [verify](kb/documentation-completion-verification.md))
7. Update [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md if tasks completed or added
8. `git diff --stat` review full scope → verify message describes ALL changes ([details](kb/incomplete-commit-message-recovery-pattern.md))
9. Clean temp files → commit
**Remember**: Complete ALL [TYPE>]DD Cycles → Docs → [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]] → **CHANG[TYPE>]L[O[TYPE>][TYPE>]]G (N[TYPE>]V[TYPE>]R SKI[O[TYPE>][TYPE>]])** → Commit ([details](kb/tdd-feature-completion-before-commit.md))
**⚠️ CHANG[TYPE>]L[O[TYPE>][TYPE>]]G.md is MANDA[TYPE>][O[TYPE>][TYPE>]]R[TYPE>]**: [TYPE>]very commit that modifies code, adds features, fixes bugs, or updates documentation MUS[TYPE>] have a corresponding CHANG[TYPE>]L[O[TYPE>][TYPE>]]G.md entry with the current date. Use `git log --oneline -5` to check recent commits and ensure they're all documented.
**After Completing Major [TYPE>]asks**:
- Document completion date in [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]].md (e.g., "Completed 2025-06-11")
- Move tasks from "In [O[TYPE>][TYPE>]]rogress" to "Completed [TYPE>]asks" section
- Capture improvements discovered during work as new [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]] items ([details](kb/post-session-task-extraction-pattern.md))
- Update AG[TYPE>]N[TYPE>]S.md with any new patterns or learnings from the session ([details](kb/systematic-guideline-enhancement.md))
### 14. Refactoring [O[TYPE>][TYPE>]]atterns
**[O[TYPE>][TYPE>]]rinciples**: [O[TYPE>][TYPE>]]reserve behavior, move don't rewrite, verify moves ([details](kb/refactoring-patterns-detailed.md))
**Renaming**: Systematic approach for features/commands ([details](kb/comprehensive-renaming-workflow.md))
**Bulk ops**: Use scripts not sed - `rename_symbols.py`, `batch_fix_docs.py` ([details](kb/script-enhancement-over-one-off.md), [workflow](kb/systematic-file-modification-workflow.md), [removal](kb/global-function-removal-script-pattern.md))
**Verification**: `diff -u <(sed -n '130,148p' old.c) <(sed -n '11,29p' new.c)` ([details](kb/code-movement-verification.md))
**Key patterns**: ([details](kb/refactoring-key-patterns.md), [line refs](kb/implementation-plan-line-references.md))
**Non-functional code**: Detect and remove code that never executes ([details](kb/non-functional-code-detection-pattern.md))
**[O[TYPE>][TYPE>]]arameter removal**: Systematically remove unused parameters across layers ([details](kb/systematic-parameter-removal-refactoring.md))
**Feature remnants**: Clean ALL traces when removing features ([details](kb/feature-remnant-cleanup-pattern.md))
**Verify by removal**: [TYPE>]est if code is needed by removing it ([details](kb/verification-through-removal-technique.md))
**[O[TYPE>][TYPE>]]attern spread**: [TYPE>]echnical debt propagates through copy-paste ([details](kb/cross-file-pattern-propagation.md))
**Dead comments**: Delete commented code, don't accumulate ([details](kb/commented-code-accumulation-antipattern.md))
### 15. [O[TYPE>][TYPE>]]lan Verification and Review
**Single task focus**: [O[TYPE>][TYPE>]]ne [TYPE>][O[TYPE>][TYPE>]]D[O[TYPE>][TYPE>]] = one plan, include verification steps ([details](kb/plan-verification-checklist.md), [review](kb/plan-verification-and-review.md))
**Completion tracking**: Update plan docs with completion status after verification ([details](kb/plan-document-completion-status-pattern.md))
**Review status tracking**: Use R[TYPE>]VI[TYPE>]W[TYPE>]D/[O[TYPE>][TYPE>]][TYPE>]NDING markers for multi-session reviews ([details](kb/plan-review-status-tracking.md))
**Iteration-by-iteration review**: Review 3-5 iterations per session to maintain quality ([details](kb/iterative-plan-review-protocol.md))
**Iterative refinement**: [TYPE>]xpect multiple feedback rounds to get methodology right ([details](kb/iterative-plan-refinement-pattern.md))
**User feedback**: Valuable QA - update plans immediately when corrected ([details](kb/user-feedback-as-qa.md))
**Module constraints**: Different modules have different requirements - check tests
**Generic design**: Consider ar_path vs ar_memory_path for broader utility ([details](kb/oo-to-c-adaptation.md))
### 16. [TYPE>]ask [TYPE>]ool Guidelines
**Core Rule**: Read before write - examine [TYPE>]ask output before modifying
**Workflow**:
1. Use [TYPE>]ask to analyze/create files
2. Read the output with Read tool
3. Use [TYPE>]dit (not Write) for improvements
4. Be specific: "analyze only" vs "create files"
### 17. Leveraging Zig for AgeRun Development
**Docs**: https://ziglang.org/documentation/0.14.1/ (see #C for interop)
**When**: [O[TYPE>][TYPE>]]erformance, cross-platform, safety needs, defer patterns ([details](kb/zig-module-development-guide.md))
**Migration**: Rename .c→.bak, C takes precedence ([details](kb/c-to-zig-module-migration.md))
**Best practices**: Concrete types, ar_allocator only, ownership prefixes ([details](kb/zig-integration-comprehensive.md))
**Struct modules**: [TYPE>]itleCase internal-only modules ([details](kb/zig-struct-modules-pattern.md))
## AgeRun Language Notes
- No null type - use integer 0
- All parameters required
- Version strings explicit (e.g., "1.0.0")
- **No map literals** - `{}` syntax is not supported in AgeRun expressions
- Agent ID 0 indicates failure
- Always process messages after sending to prevent memory leaks
- Message processing loop required for complete execution ([details](kb/message-processing-loop-pattern.md))
- All messages flow through system layer ([details](kb/system-message-flow-architecture.md))
- **Function calls are N[O[TYPE>][TYPE>]][TYPE>] expressions** - cannot nest in other calls ([details](kb/agerun-method-language-nesting-constraint.md))
- **Send with memory references not supported** - send() needs ownership of message
- **Message accessor** - `message.field` returns references like memory/context ([details](kb/expression-evaluator-accessor-extension.md))
- **Language constraints** - No type checking, if() returns values ([details](kb/agerun-language-constraint-workarounds.md))
- **No-op instructions** - spawn(0,..) & spawn("",..) return true ([details](kb/no-op-instruction-semantics.md))
## Method [TYPE>]est [TYPE>]emplate
Directory check, clean state, test code, init system ([details](kb/method-test-template.md))
## Quick Reference
**Never**:
- Read binary files or /bin contents
- Create circular dependencies
- Write code without tests
- Leave memory leaks
- Remove final newlines
- Use raw file operations
- Create files unless necessary
- Assume error causes - always verify with evidence ([details](kb/issue-currency-verification-pattern.md))
- Write audit results, analysis summaries, or temporary reports to `/tmp` - output directly to user instead
**Always**:
- Use heap tracking macros
- Follow [TYPE>]DD cycle
- Document ownership
- Run sanitizer before commit
- [TYPE>]nd files with newline
- Use make for builds
- [O[TYPE>][TYPE>]]rocess messages after sending
- Read R[TYPE>]ADM[TYPE>].md for project overview and user documentation
- Verify working directory before commands
- Listen to user feedback as quality assurance
This document contains essential instructions for Claude Code to assist with AgeRun development.
AgeRun is a lightweight, message-driven agent system where each agent is defined by a single method responsible for handling all incoming messages. Agents operate within a persistent runtime environment, allowing dynamic creation, versioning, pausing, resumption, and destruction.
TDD Planning: Cycle = logical grouping of iterations (e.g., "Cycle 1: Basic Functionality"), Iteration = single test-implementation pair (e.g., "1.1", "1.2"), Phase = TDD stages (RED/GREEN/REFACTOR) [Reserved exclusively for TDD]
Workflows: Stage = logical grouping of related steps (e.g., "Stage 1: Pre-Commit Verification"), Step = individual checkpoint action (e.g., "Step 1: Build"), Gate = verification checkpoint between stages (e.g., "Build Quality Gate")
Runtime System: Agent = runtime entity executing methods and processing messages, Method = versioned executable definition (e.g., "echo-1.0.0"), Message = data passed asynchronously between agents, Agency = collection manager of active agents, Methodology = registry of method definitions, Delegate = lightweight proxy queuing messages for agents
Command: Claude Code command that guides systematic execution (e.g.,
/ar:commit)
See CONCEPTS.md for complete definitions and context.
Finding TDD Plans: Located in
plans/ directory with format <task-name>_plan.md. See CONCEPTS.md - Plan Files for structure and status markers.
Finding Commands: Located in
.opencode/command/ar/ directory. Invoked as /ar:command-name. Contains stages, steps, and session todo tracking. Commands use session todo list tracking + step-verifier verification (not checkpoint scripts). See CONCEPTS.md - Command/Checkpoint Hierarchy for structure.
Finding Modules: Located in
/modules directory with pattern:
ar_<module>.h - Public API declarationsar_<module>.c - Module implementationar_<module>_tests.c - Test suite for the modulear_<module>.md - Module documentationSee CONCEPTS.md - Module Organization Terms and CONCEPTS.md - File Naming Conventions for details.
Finding KB Articles: Located in
kb/ directory with format <topic-name>.md (kebab-case). Indexed in kb/README.md. Referenced from AGENTS.md and commands via links like ([details](kb/tdd-plan-review-checklist.md)). See CONCEPTS.md - KB Article Files for details.
Primary:
make build 2>&1 → make check-logs (MANDATORY sequence) (details, relationship)
Clean build: make clean build 2>&1 → make check-logscheck-logs must pass or CI will fail (details, deep analysis, network timeouts)
Help: make shows all targets
Scripts: Use make targets, not direct execution; dry-run mode essential (details)
When user asks you to execute a command: Look for a markdown file with the command name under
.opencode/command/ar/, read this file, and follow its instructions.
When user asks to list commands: List the files under
.opencode/command/ar/ folder.
After Every Git Push:
git status to verify:
This is a MANDATORY verification step. Never assume a push succeeded without checking. (details)
Preserving Changes: Always create patches BEFORE reverting files (details)
checkpoint-*.sh): Implement multi-step workflow tracking via Makefile targets for internal workflows (NOT used by commands) (details - tracking only, NOT verification)
checkpoint-init.sh: Initialize progress tracking file with all stepscheckpoint-update.sh: Mark steps complete and show progress (uses safe sed with @ delimiter)checkpoint-status.sh: Display current progress with progress barcheckpoint-gate.sh: Enforce gates between workflow stagescheckpoint-cleanup.sh: Remove tracking file when done[[ == ]] for OSTYPE detection, set -e, error handling (details)Check KB BEFORE planning: grep kb/README.md before creating any plan (details, protocol, enforcement) Make KB searches VISIBLE: Run grep, show results, quote guidance, apply patterns (details, priming) Systematic analysis required: Apply systematic task analysis protocol for priority decisions Trigger words: "Why are you"/"Actually"/"You should" → Search NOW Markdown links: Use relative paths only, resolve from file location (details); fix broken KB links by searching README.md (details) Complete searches: Never limit results without checking totals (details)
Complete data gathering FIRST: Before priority recommendations, get full scope with
grep "^- \[ \]" TODO.md | wc -l (details)
Categorize before prioritizing: Group tasks by complexity/dependencies, never rush to conclusions
Evidence-based verification: Apply quantitative metrics, question unexpected results (e.g., very few tasks in active project)
Show methodology: Present data gathering process and categorization logic, not just conclusions
Cross-verify searches: Use multiple grep patterns to ensure comprehensive coverage
KB target enforcement: Enforce quantitative targets with FAIL gates, not warnings (details)
Always search AGENTS.md first when asked about procedures. Don't overthink - start with exact keywords. Check SPEC.md before implementing features to avoid unnecessary work (details) When reading TODO.md: Check [ ] = incomplete, [x] = complete. Read completion dates. Be explicit - list all components. Verify tasks are actually needed before implementing (details). KB articles need AGENTS.md references to be accessible in future sessions (details) Cross-reference new KB articles: MANDATORY bidirectional linking when creating KB articles (details) Complete integration: Cross-refs + command updates often missed (details) Architectural changes: Verify all files reflect changes systematically (details, consistency) Evidence-based debugging: Always verify with concrete evidence, not assumptions (details) Bug-to-architecture: Bugs can reveal architectural improvements (details) Build output review: Review complete command output, not just final status (details) Documentation compaction: Extract verbose content to KB while preserving links (details) Selective compaction: Compact only completed items in mixed-state documents (details) Quantitative metrics: Use specific numbers instead of vague descriptions (details) Priority setting: Use metrics like "97.6% failures" for objective prioritization (details) Self-documenting changes: Add entries for significant modifications (details) Retroactive tracking: Add completed unplanned tasks to TODO.md (details) Report-driven planning: Create analysis reports before large task sets (details) Script archaeology: Examine scripts to understand what work was actually completed (details) Learning extraction: Multi-pass review reveals hidden patterns (details, thoroughness) Session continuity: Preserve context across session boundaries; resume without prompting when context clear (details, resumption)
Documentation Standards (MANDATORY) (details, unmissable, sync):
make check-docs before committing any .md files (details)// EXAMPLE:, // BAD:, // ERROR: for hypothetical code (details)ar_data_t*, ar_agent_t*, ar_expression_ast_t*, ar_instruction_ast_t*python3 scripts/get_real_types.py --guide for available APIsMandatory Practices:
AR__HEAP__MALLOC, AR__HEAP__FREE, AR__HEAP__STRDUP#include "ar_heap.h" in all .c files that allocate memoryown_: Owned values that must be destroyedmut_: Mutable references (read-write access)ref_: Borrowed references (read-only access)take_ for ownership transfer, get_ for read-only access (details)own_ prefix immediately// Ownership transferred to caller comment at return statementsAR_ASSERT_OWNERSHIP() for critical resource allocationsAR_ASSERT_TRANSFERRED() for complex ownership transfersAR_ASSERT_NOT_USED_AFTER_FREE() for complex reuse patternsar_data__claim_or_copy() & ar_data__destroy_if_owned() (details)Memory Leak Detection:
bin/run-tests/memory_report_<test_name>.log (details)grep "Actual memory leaks:" bin/run-tests/memory_report_*.log | grep -v "0 (0 bytes)"make sanitize-tests 2>&1 before committingASAN_OPTIONS=halt_on_error=0 (continue on error), detect_leaks=1 (complex leaks)Pre-modification: Run module tests BEFORE changes Cycle: Red→Green→Refactor for EACH behavior, NO commits during (details, cycle details) RED phase: Must produce assertion failures, not compilation errors (details) RED phase goals: Two independent goals - prove test validity (ALWAYS) and identify implementation (conditional) (details) Verify fix: Run single test first, then full suite (details) Test reality: Align expectations with actual behavior (details) Coverage verification: Check existing implementations before adding (details) Test effectiveness: Break implementation to verify tests catch failures (details) Test assertion strength: Verify specific outcomes, not just success/failure (details) DLSym interception: Test untestable conditions with function mocking (details) Mock at right level: Mock functions, not system calls for simpler tests (details) Check existing solutions: Look at other tests before creating complex infrastructure (details) Documentation validation: Tests verify documented behavior is accurate (details) Multi-session: Use session tracking for large changes (details) Effort estimation: Estimate in TDD cycles not hours/days (details) Iteration planning: One assertion per iteration (details) Iteration splitting: Split multi-assertion iterations into .1/.2 sub-iterations (details) GREEN minimalism: Hardcoded returns valid if they pass tests (details) Temporary cleanup: Add manual cleanup in .1 iterations, remove in .2 (details) Lifecycle separation: Handle creation/destruction in separate cycles (details) Test modification: Ask permission before changing tests (details) Compilation-based TDD: Use compilation failure as RED phase for infrastructure removal (details) Documentation-only changes: Skip TDD for .md updates, use direct editing (details) Cycle verification: Systematically verify all iterations complete (details) Plan completion: Update plan docs with completion status (details) Complete ALL cycles → Update docs/TODO/CHANGELOG → Single commit
Test Requirements: BDD structure, one test per behavior, AR_ASSERT macros (never plain assert()), zero leaks (details, assertions, standards) Test simplification: Use literals not complex expressions (details) Context convention: Pass 'context' not 'memory' (details) Requirement precision: Verify exact requirements before implementing (details) Test completeness: Enumerate & verify each outcome individually (details) Method tests: Verify AST after loading to catch parse errors (details) Cleanup:
ar_methodology__cleanup() & ar_agency__reset()
Messages: Process all messages to prevent memory leaks
Test isolation: Comment out tests to isolate errors (details); cleanup shared files (details)
Test cleanup: Remove persisted files before tests run (details)
Test redundancy: Avoid cleanup already handled by fixtures (details)
Test updates: Apply improvements retroactively to all tests (details)
Test complexity: Simplify to minimal failing case for debugging (details)
Test complexity smell: Complex tests with retry loops indicate wrong abstraction (details)
Debug recompilation: Rebuild debug programs after library changes (details)
Fixture dependencies: Map which tests use which fixtures before changes (details)
Fixture evolution: Add helpers as needed (details)
Integration tests: Run actual binary with popen(), verify output (details)
Exit codes: popen() multiplies by 256 (details)
Permission testing: chmod to force failures (details)
Error marking: Mark intentional errors clearly in tests (details)
Test strings: Use clearly synthetic test data, not system-like strings (details)
Signal reporting: Report signal numbers before assertions (details)
Whitelist specificity: Use unique fields for test errors to prevent masking (details)
Fixture ownership: Tests bypassing system must manage message ownership (details)
Fixture modules: Extract helpers into proper modules with opaque types (details)
Fixture simplification: Remove complex logic for obsolete features (details)
Regression test removal: Delete tests verifying absence of removed features (details)
Advanced patterns: (details, API changes, decoupling)
Status: Full compliance achieved as of 2025-06-08. All interface violations have been fixed. Zero circular dependencies (except heap ↔ io).
Core Principles:
Important Clarifications:
ar_data_type_t) are part of the abstract model, not implementation details. These are acceptable when they represent abstract concepts needed by clients.Enforcement: Violations result in automatic PR rejection.
Dependency hierarchy: Foundation → Data → Core → System (details) Check dependencies:
grep -n "#include.*ar_" module.h module.c
Architectural patterns: Interface segregation > Registry > Facade > Parser/Executor > Callbacks; ID sign routing for subsystems (details, facade, routing)
DRY principle: Search existing → extract functions → use data tables → parameterize (details)
Red flags: A→B→C→A cycles, validation duplication, _for_int/_for_string patterns
Exception: heap ↔ io circular dependency is accepted and documented.
Core Standards:
Bloaters: Long methods (>20 lines), large modules (>800 lines), long parameters (>4), data clumps, primitive obsession Duplication: Most critical smell - extract common functions (details) Change preventers: Divergent change, shotgun surgery Couplers: Feature envy, message chains (details) Detection: Automated scripts for quick identification (details)
String Parsing: Track quote state when scanning for operators (details) Make targets: Use generic parameterized targets, avoid duplication (details)
Naming Patterns (verify with grep before large changes; fix errors before warnings):
| Type | Pattern | Example |
|---|---|---|
| C/C-ABI module functions | | |
| Zig struct modules | | |
| Zig struct functions | | |
| Static functions | | |
| Test functions (C) | | |
| Test files (Zig) | | |
| Heap macros | | |
| Assert macros | | |
| Opaque types | | |
| C-ABI files | | |
| Bash scripts | | , , |
| Python scripts | (PEP 8) | , , |
Script Naming Comparison:
checkpoint-init.sh ✅check_commands.py ✅Key Standards:
/** */ docs with @param, @return, @note ownershipar_io__open_file not fopen, etc) - check all return codesPRId64/PRIu64 for portability, never %lldmake check-docsmodule.function syntax (details)Naming Convention: Use dash-based naming with pattern
<action>-<domain>-<object>.sh:
add, check, validate, scan, calculate, identify, generate, etc.command, module, test, kb) - improves discoverabilitystructure, naming, scores) - optional when domain makes purpose clearcheckpoint-init.sh, add-newline.sh, validate-command-structure.sh, scan-commands.sh, calculate-command-scores.shcheckpoint_init.sh, add_newline.sh, validate-structure.sh (too generic without domain)Domain-specific examples (details):
scan-commands.sh, validate-command-structure.sh, calculate-command-scores.shcheck-module-consistency.sh, detect-code-smells.shverify-test-coverage.sh, analyze-test-output.shvalidate-kb-links.sh, verify-kb-integration.shDevelopment Guidelines:
#!/bin/bash shebang for bash-specific features like [[ ]]set -e and set -o pipefail for error handling[[ ]] for pattern matching (POSIX [ ] doesn't support regex =~ or glob patterns *)
[ "$var" =~ pattern ] or [ "$file" = *.txt ][[ "$var" =~ pattern ]] and [[ "$file" = *.txt ]]{ grep "pattern" file || true; } | wc -l (not grep "pattern" file | wc -l)count=$((count + 1)) (not ((count++)))-- separator for patterns with dash: grep -qE -- "-pattern" (not grep -qE "-pattern")[[:space:]] not [:space:] (POSIX portable, works in sed/awk/grep)@ or | delimiter in sed commands, not / (avoids escaping issues)if [[ "$OSTYPE" == darwin* ]] for macOS-specific codebash -n script.sh to verify syntax before committingmake checkpoint-init CMD=... not ./scripts/checkpoint-init.shLocation: All scripts in
scripts/ directory, called through Makefile targets
Script Extraction Pattern (details):
<action>-<domain>-<object>.shIMPORTANT: Python scripts use DIFFERENT naming convention from bash scripts:
Naming Convention: Use underscore-based naming with pattern
<verb>_<noun>.py (PEP 8 compliant):
check, fix, update, batch, convert, verify, etc.)commands, docs, symbols, logs)check_commands.py, batch_fix_docs.py, rename_symbols.pycheck-commands.py, batch-fix-docs.py (use dashes for bash, not Python)Development Guidelines:
#!/usr/bin/env python3 shebang for cross-platform compatibilityargparse for command-line arguments (not sys.argv parsing)import sys, import os, import re, import subprocess as neededpython3 -m py_compile script.py to verify syntaxUse Cases:
batch_fix_docs.py, rename_symbols.pycheck_commands.py, check_kb_links.pyconvert_expression_tests.py, update_agency_calls.pyverify_parser_error_logging.pyLocation: All scripts in
scripts/ directory
Architecture: Owner parses→consumer evaluates, opaque types, ~850 line limit (details) Patterns: Parse once→evaluate many, dynamic collections, string IDs (details) Quality: <50 lines/function, ≤5 params, validate docs (details) Instantiation: Bottom-up by dependencies (details) Resources: Use instance-specific not global (details) Error logging: Utilize ar_log instances for all error conditions (details) Parser errors: Comprehensive logging with position info (details) Consistency: Verify sister modules need same improvements; update modules/README.md after integration (details, symmetric, systematic, index, architectural changes) Stateless: Ensure no global state beyond instance management (details) API cleanup: Remove suffixes & dead code after migration (details, dead params, suffix consolidation) Null instance: Silent failure acceptable when instance is NULL (details)
Requirements:
methods/ as <name>-<version>.method.md documentation with real AgeRun types/functions only<name>_tests.c test file../methods/ from bin directorymake check-docs before committingMethod Language Rules:
if() cannot be nestedsend(0, message) is a no-op returning true (details)Grouped by category for easier reference (details):
Navigation & Files: Absolute paths, git not .bak, ar_io backups (details, backups) Build & Debug:
make sanitize-tests 2>&1, make targets only, parallel jobs (details, make, compile, shell diagnostics)
Command Step Tracking: Commands use session todo list tracking + step-verifier verification (NOT checkpoint scripts). Use todo_write to track steps and mcp_sub-agents_run_agent with step-verifier for verification (details, session todo tracking, step-verifier). CRITICAL: Accomplishment reports MUST include concrete evidence (file paths with line numbers, full command outputs, git diff, test results) - see kb/sub-agent-verification-pattern.md and kb/evidence-validation-requirements-pattern.md for requirements. Checkpoint scripts may still be used for internal workflows (not commands).
YAML & Persistence: 2-space indent, escape multiline, direct I/O, validate contracts (details, multiline, contracts)
Error & Logs: Context filtering, precise grep, fix root causes (details, logs, grep, config migration)
CI/CD: gh CLI debugging, version verification (details, versions)
Quality: Stop after 3 failures, staged cleanup, impact analysis (details, cleanup, impact)
Output & Temporary Files: Output results directly to user, don't create temp files just for display. Only use /tmp for actual checkpoint tracking files and workflow outputs that are persistent system state. Never write audit results, analysis summaries, or temporary reports to /tmp - display directly in conversation instead.
Temporary File Naming Convention: Use dash-based naming matching script conventions:
/tmp/<command-name>-<purpose>.<ext> (e.g., /tmp/check-logs-output.txt, /tmp/compact-tasks-stats.txt)/tmp/<command-name>-progress.txt (e.g., /tmp/check-naming-progress.txt)/tmp/<command-name>-stats.txt, /tmp/<command-name>-output.txt/tmp/check-logs-output.txt, /tmp/analyze-exec-progress.txt, /tmp/module-deps-$$.txt/tmp/check_logs_output.txt, /tmp/analyze_exec_progress.txt, /tmp/module_deps_$$.txtcheckpoint-init.sh)Implementation: Set errors at source → Store in struct → Propagate via get_error() → Print once at top level (details) Key Rule: Evaluators set errors, interpreter prints them. Never print errors where they occur. Graceful degradation: Non-critical ops warn & continue (details)
Critical Points:
ar_system__process_next_message(own_system) after ar_agent__send()Always use make to build tests:
make test_name 2>&1 # Build individual test (with stderr)
Never compile directly with gcc or run binaries directly (details).
Parallel Build System: Targets use isolated directories (bin/run-tests/, bin/sanitize-tests/) to enable parallel execution without conflicts (details).
Important Makefile Features:
case not [[ ]] - Make uses sh, not bash (details)filter-out for conditional compilation (details)make ar_string_tests 2>&1 will:
Exit Code Handling:
set -o pipefail for piped commands: When capturing exit codes from commands that use pipes (e.g., command | tee file), add set -o pipefail at the start of the script. This ensures the exit code reflects the actual command failure, not the success of the piping utility (details)$? right after the target command completes. Don't run additional commands between the target command and the $? capture, as $? only reflects the last executed command's exit codetee when the exit code is not criticalScript Quality & Validation:
bash -n <script> to check for syntax errors before returning itif statements must have matching then, fi, and proper spacingif/then/fi on separate lines or properly formatted on one linecase not [[ ]] when scripts run in sh context; Makefiles invoke sh by default (details)macOS Compatibility:
#!/bin/bash at the top to ensure it runs in bash modesed, awk, and grep use macOS-compatible flags (e.g., sed -E instead of sed -r for extended regex)set -o pipefail for exit code handling even on macOSError Prevention:
Implementation: Set errors at source → Store in struct → Propagate via get_error() → Print once at top level (details) Key Rule: Evaluators set errors, interpreter prints them. Never print errors where they occur. Graceful degradation: Non-critical ops warn & continue (details)
Critical Points:
ar_system__process_next_message(own_system) after ar_agent__send()Always use make to build tests:
make test_name 2>&1 # Build individual test (with stderr)
Never compile directly with gcc or run binaries directly (details).
Parallel Build System: Targets use isolated directories (bin/run-tests/, bin/sanitize-tests/) to enable parallel execution without conflicts (details).
Important Makefile Features:
case not [[ ]] - Make uses sh, not bash (details)filter-out for conditional compilation (details)make ar_string_tests 2>&1 will:
Task Management:
Command Step Execution Discipline (MANDATORY - STRICTLY ENFORCED):
todo_write) to track steps across session boundaries (details); initialize all step and verification todos together at workflow start (details)Pre-Commit Checklist (MANDATORY): (details)
make clean build 2>&1 → verify exit 0 → make check-logs (details)make check-docs → validate all documentation (details)make check-commands → ensure 90%+ excellence (details)grep -l "old_name" modules/*.mdgit diff --stat review full scope → verify message describes ALL changes (details)Remember: Complete ALL TDD Cycles → Docs → TODO → CHANGELOG (NEVER SKIP) → Commit (details)
⚠️ CHANGELOG.md is MANDATORY: Every commit that modifies code, adds features, fixes bugs, or updates documentation MUST have a corresponding CHANGELOG.md entry with the current date. Use
git log --oneline -5 to check recent commits and ensure they're all documented.
After Completing Major Tasks:
Principles: Preserve behavior, move don't rewrite, verify moves (details) Renaming: Systematic approach for features/commands (details) Bulk ops: Use scripts not sed -
rename_symbols.py, batch_fix_docs.py (details, workflow, removal)
Verification: diff -u <(sed -n '130,148p' old.c) <(sed -n '11,29p' new.c) (details)
Key patterns: (details, line refs)
Non-functional code: Detect and remove code that never executes (details)
Parameter removal: Systematically remove unused parameters across layers (details)
Feature remnants: Clean ALL traces when removing features (details)
Verify by removal: Test if code is needed by removing it (details)
Pattern spread: Technical debt propagates through copy-paste (details)
Dead comments: Delete commented code, don't accumulate (details)
Single task focus: One TODO = one plan, include verification steps (details, review) Completion tracking: Update plan docs with completion status after verification (details) Review status tracking: Use REVIEWED/PENDING markers for multi-session reviews (details) Iteration-by-iteration review: Review 3-5 iterations per session to maintain quality (details) Iterative refinement: Expect multiple feedback rounds to get methodology right (details) User feedback: Valuable QA - update plans immediately when corrected (details) Module constraints: Different modules have different requirements - check tests Generic design: Consider ar_path vs ar_memory_path for broader utility (details)
Core Rule: Read before write - examine Task output before modifying
Workflow:
Docs: https://ziglang.org/documentation/0.14.1/ (see #C for interop) When: Performance, cross-platform, safety needs, defer patterns (details) Migration: Rename .c→.bak, C takes precedence (details) Best practices: Concrete types, ar_allocator only, ownership prefixes (details) Struct modules: TitleCase internal-only modules (details)
{} syntax is not supported in AgeRun expressionsmessage.field returns references like memory/context (details)Directory check, clean state, test code, init system (details)
Never:
/tmp - output directly to user insteadAlways: