Skip to main content

AGENTS.md - AI Agent Guidelines for VIBEE Development

Author: Dmitrii Vasilev

Overview

This document provides guidelines for AI agents working on the VIBEE project. All agents must follow the Golden Chain workflow.


🚨 AUTONOMOUS DEVELOPMENT LOOP (KOSCHEI PATTERN)

Core Principles:

  1. Specification-First: NEVER write implementation code directly
  2. Auto-Generation: Code is GENERATED from specs, not written manually
  3. Continuous Improvement: Loop until EXIT_SIGNAL or completion
  4. Self-Validation: Run tests after each generation

Development Loop:

┌─────────────────────────────────────────────────────────────────┐
│ KOSCHEI DEVELOPMENT LOOP │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. ANALYZE task requirements │
│ ↓ │
│ 2. CREATE .vibee specification in specs/tri/ │
│ ↓ │
│ 3. RUN: ./bin/vibee gen specs/tri/feature.vibee │
│ ↓ │
│ 4. TEST: zig test var/trinity/output/feature.zig │
│ ↓ │
│ 5. CHECK: All tests passing? │
│ ↓ │
│ YES → Write TOXIC VERDICT + TECH TREE SELECT → EXIT │
│ NO → ITERATE (go to step 2) │
│ │
└─────────────────────────────────────────────────────────────────┘

⛔ CRITICAL PROHIBITIONS

🚫 ANTI-PATTERN #1: WRITING .zig CODE MANUALLY

❌ NEVER write .zig code directly - this is an ANTI-PATTERN!
❌ ALL .zig code MUST be GENERATED from .vibee specifications
❌ The only exception: src/vibeec/*.zig (compiler source code)

NEVER CREATE THESE FILE TYPES MANUALLY:

❌ .html files (except runtime/runtime.html)
❌ .css files
❌ .js files
❌ .ts files
❌ .jsx files
❌ .tsx files
❌ .zig files - ANTI-PATTERN! Use .vibee → gen → .zig
❌ .py files (ONLY GENERATED)
❌ .v files - ANTI-PATTERN! Use .vibee (language: varlog) → gen → .v

WHY?

VIBEE uses specification-first development:

trinity-nexus/tri/*.vibee (language: zig)    → vibee gen → trinity-nexus/output/tri/zig/*.zig
trinity-nexus/tri/*.vibee (language: varlog) → vibee gen → trinity-nexus/output/fpga/*.v

CORRECT WORKFLOW:

# 1. Create .vibee spec in trinity-nexus/tri/
cat > trinity-nexus/tri/my_feature.vibee << 'EOF'
name: my_feature
version: "1.0.0"
language: zig # For software
module: my_feature
...
EOF

# 2. Generate code (NEVER write it manually!)
zig build vibee -- gen trinity-nexus/tri/my_feature.vibee

# 3. Test generated code
zig test trinity-nexus/output/tri/zig/my_feature.zig

# 4. IF CODEGEN HAS PROBLEMS: Use agent_mu
# DO NOT fix generated code manually!

ALLOWED TO EDIT:

src/vibeec/*.zig - Compiler source code ONLY
trinity-nexus/tri/*.vibee - Specifications (NO manual code blocks!)
docs/*.md - Documentation

NEVER EDIT:

trinity-nexus/output/tri/zig/*.zig - Generated code (will be overwritten)
trinity-nexus/output/fpga/*.v - Generated Verilog (will be overwritten)
generated/*.zig - Generated code (will be overwritten)

**IF CODEGEN HAS PROBLEMS:** Use agent_mu to improve codegen - DO NOT fix manually!

⚡ VIBEE PIPELINE (MANDATORY)

Step 1: Create .vibee specification

# trinity-nexus/tri/my_feature.vibee
name: my_feature
version: "1.0.0"
language: zig
module: my_feature

types:
MyType:
fields:
name: String
count: Int

behaviors:
- name: my_behavior
given: Input
when: Action
then: Result

Step 2: Generate .zig code

zig build vibee -- gen trinity-nexus/tri/my_feature.vibee
# Output: trinity-nexus/output/tri/zig/my_feature.zig

Step 3: Test generated code

zig test trinity-nexus/output/tri/zig/my_feature.zig

# IF CODEGEN HAS PROBLEMS: Use agent_mu
# DO NOT fix generated code manually!

Type Mapping Reference:

VIBEE TypeZig Type
String[]const u8
Inti64
Floatf64
Boolbool
Option<T>?[]const u8
List<T>[]const u8
Map<K,V>std.StringHashMap([]const u8)
Timestampi64
Object[]const u8

🔥 MANDATORY: TOXIC VERDICT

After EVERY task completion, write harsh self-criticism:

╔══════════════════════════════════════════════════════════════════╗
║ 🔥 TOXIC VERDICT 🔥 ║
╠══════════════════════════════════════════════════════════════════╣
║ WHAT WAS DONE: ║
║ - [specifically what was implemented] ║
║ ║
║ WHAT FAILED: ║
║ - [honest about mistakes] ║
║ ║
║ METRICS: ║
║ - Before: X | After: Y | Δ = Z% ║
║ ║
║ SELF-CRITICISM: ║
║ - [harsh analysis without rose-colored glasses] ║
║ - [what could have been done better] ║
║ ║
║ SCORE: [1-10]/10 ║
╚══════════════════════════════════════════════════════════════════╝

🌳 MANDATORY: TECH TREE SELECT

After toxic verdict, propose 3 options for next research:

┌─────────────────────────────────────────────────────────────────┐
│ 🌳 TECH TREE - SELECT NEXT │
├─────────────────────────────────────────────────────────────────┤
│ │
│ [A] ────────────────────────────────────────────────────── │
│ Name: ... │
│ Complexity: ★★☆☆☆ │
│ Potential: +X% to metric Y │
│ Dependencies: [what's needed first] │
│ │
│ [B] ────────────────────────────────────────────────────── │
│ Name: ... │
│ Complexity: ★★★☆☆ │
│ Potential: +X% to metric Y │
│ Dependencies: [what's needed first] │
│ │
│ [C] ────────────────────────────────────────────────────── │
│ Name: ... │
│ Complexity: ★★★★☆ │
│ Potential: +X% to metric Y │
│ Dependencies: [what's needed first] │
│ │
│ RECOMMENDATION: [A/B/C] because [reason] │
│ │
└─────────────────────────────────────────────────────────────────┘

📁 File Organization

trinity-nexus/
├── tri/ # .vibee specifications (SOURCE)
│ ├── *.vibee
│ └── ...
├── output/tri/zig/ # Generated .zig (DO NOT EDIT)
│ ├── *.zig
│ └── ...
├── lang/src/ # Compiler (CAN EDIT)
│ ├── zig_codegen.zig
│ ├── vibee_parser.zig
│ └── ...
└── ...

IMPORTANT: All specs now in trinity-nexus/tri/, NOT specs/tri/


🔧 Commands Reference

# PRIMARY WORKFLOW (from project root)
zig build vibee -- gen trinity-nexus/tri/feature.vibee # Generate single

# TEST
zig test trinity-nexus/output/tri/zig/feature.zig # Test single

# IF CODEGEN HAS PROBLEMS: Use agent_mu
# DO NOT edit generated .zig files manually!

📝 MANDATORY: DOCUMENT ACHIEVEMENTS

After completing ANY significant milestone, agents MUST automatically document it:

What Requires Documentation

Achievement TypeAction Required
New feature workingCreate docs/docs/research/<feature>-report.md
Benchmark improvementUpdate docs/docs/benchmarks/
Integration successCreate research report with metrics
Node/inference milestoneDocument in research section
Performance breakthroughAdd to benchmarks with proof

Documentation Workflow (MANDATORY)

# 1. CREATE report in docs
# File: docs/docs/research/<milestone>-report.md

---
sidebar_position: N
---

# <Milestone> Report

**Date:** YYYY-MM-DD
**Status:** Production-ready / In Progress

## Key Metrics
| Metric | Value | Status |
|--------|-------|--------|
| ... | ... | ... |

## What This Means
- For users: ...
- For node operators: ...
- For investors: ...

## Technical Details
...

# 2. UPDATE sidebar
# File: docs/sidebars.ts
# Add new page to appropriate category

# 3. BUILD & DEPLOY
cd docs && npm run build
USE_SSH=true npm run deploy

# 4. COMMIT & PUSH
git add docs/
git commit -m "docs: Add <milestone> report"
git push

Report Template

---
sidebar_position: N
---

# <Feature/Milestone> Report

**Date:** February X, 2026
**Status:** Production-ready

## Executive Summary
One paragraph summary of achievement.

## Key Metrics

| Metric | Value | Status |
|--------|-------|--------|
| Coherence | X% | Verified |
| Speed | X tok/s | CPU/GPU |
| Cost | $X/hr | vs $Y cloud |

## What This Means

### For Users
- Benefit 1
- Benefit 2

### For Node Operators
- $TRI earning potential

### For Investors
- Proof of technology

## Technical Details
Architecture, implementation, test results.

## Conclusion
Summary and next steps.

---
**Formula:** phi^2 + 1/phi^2 = 3

Examples of Documented Achievements

AchievementReport Location
BitNet coherence testing/docs/research/bitnet-report
Trinity Node FFI integration/docs/research/trinity-node-ffi
Competitor comparison/docs/benchmarks/competitor-comparison
GPU inference benchmarks/docs/benchmarks/gpu-inference

🏆 EXIT_SIGNAL

Agent must continue iterations until:

  1. All tests pass
  2. Specification is complete
  3. TOXIC VERDICT is written
  4. TECH TREE SELECT is proposed
  5. Achievement documented (if milestone reached)
  6. Changes are committed
EXIT_SIGNAL = (
tests_pass AND
spec_complete AND
toxic_verdict_written AND
tech_tree_options_proposed AND
committed
)

GIT HOOKS ENFORCEMENT

The repository has pre-commit hooks that BLOCK commits containing forbidden files:

# Hook location
.githooks/pre-commit

# Activate hooks
git config core.hooksPath .githooks

BLOCKED EXTENSIONS: .html (except runtime.html), .css, .js, .ts, .jsx, .tsx

ALLOWED EXTENSIONS: .vibee, .999, .zig, .md, .json, .yaml


🌐 WEBSITE DEPLOYMENT RULES

CANONICAL URL (NEVER CHANGE!)

SettingValue
Production URLhttps://trinity-site-ghashtag.vercel.app
Vercel Projecttrinity-site
GitHub RepogHashTag/trinity
Root Directorywebsite/
FrameworkVite (React SPA)

⛔ CRITICAL: DO NOT

  • Create new Vercel projects
  • Change the production URL
  • Deploy to different project names
  • Create duplicate website folders
  • Use vibee-lang repo (use trinity only!)

✅ ALLOWED

  • Edit files in website/ folder
  • Push to main branch (auto-deploys)
  • Update translations in website/messages/*.json
https://github.com/gHashTag/trinity

🤖 AGENT MU — Post-Generation Auto-Fixer (v8.12)

μ = 1/φ²/10 = 0.0382 — Sacred Mutation

Overview

AGENT MU is the post-generation guardian that runs after every vibee gen. It automatically detects, classifies, and fixes compilation errors in generated code.

Phases of Self-Evolution

┌─────────────────────────────────────────────────────────────────┐
│ AGENT MU SELF-EVOLUTION LOOP │
├─────────────────────────────────────────────────────────────────┤
│ │
│ V01 → VERIFICATION │
│ zig build + zig test + zig fmt │
│ ↓ │
│ Phi02 → PATTERN SEARCH │
│ Search REGRESSION_PATTERNS.md for similar errors │
│ ↓ │
│ Pi03 → DIAGNOSTIC │
│ Parse error → Classify FixType │
│ ↓ │
│ Mu05 → AUTO-FIX │
│ Apply fix based on FixType │
│ ↓ │
│ Sigma07 → SUCCESS │
│ Log to SUCCESS_HISTORY.md │
│ ↓ │
│ Chi06 → REGRESS │
│ Log to REGRESSION_PATTERNS.md (if fix failed) │
│ ↓ │
│ REPEAT (max 3 attempts) │
│ │
└─────────────────────────────────────────────────────────────────┘

FixType Classifications

FixTypeDescriptionImplementedConfidence
IMPORT_FIXMissing import statements0.9
ALLOCATOR_FIXMissing allocator parameter0.7
ERROR_UNION_FIXError handling needed0.75
TYPE_FIXType mismatch0.95
TEMPLATE_FIXCodegen template error0.0 (descriptive)
GENERATOR_PATCHVIBEE compiler patch0.0 (descriptive)
SYNTAX_FIXSyntax error1.0 (fmt)
SPEC_FIXSpecification error

Auto-Fix Functions

// src/agent_mu/fixer.zig

pub fn applyFix(
allocator: std.mem.Allocator,
err_info: *const diagnostic.ErrorInfo,
file_path: []const u8,
) !FixResult;

Implemented fixes:

  1. applyImportFix() — Auto-add missing std library imports
  2. applyAllocatorFix() — Replace ArrayList.init with ArrayListUnmanaged
  3. applyErrorUnionFix() — Add try prefix to error-returning calls
  4. applyTypeFix() — Remove const from []const u8 for type mismatches
  5. applyFormatFix() — Run zig fmt on the file
// src/agent_mu/pattern_matcher.zig

pub fn semanticPatternMatch(
allocator: std.mem.Allocator,
error_message: []const u8,
error_type: diagnostic.FixType,
top_k: usize,
threshold: f64,
) ![]PatternMatch;

Features:

  • Fuzzy similarity matching (character bigrams)
  • Confidence scoring (0.0 to 1.0)
  • Top-k pattern retrieval
  • Keyword matching with 6 common error patterns

Generator Feedback Loop

// src/agent_mu/agent_mu.zig

pub const GeneratorFeedback = struct {
template_name: []const u8,
issue_type: []const u8,
suggested_fix: []const u8,
priority: u32,
before_hash: []const u8,
after_hash: []const u8,
};

pub fn createGeneratorFeedback(
allocator: std.mem.Allocator,
err_info: *const diagnostic.ErrorInfo,
fix_result: *const fixer.FixResult,
) !GeneratorFeedback;

Mutation Statistics (μ Tracking)

// src/agent_mu/logger.zig

pub const MU: f64 = 0.0382; // Sacred constant

pub const MutationStats = struct {
total_fixes: u32,
successful_fixes: u32,
failed_fixes: u32,
intelligence_gain: f64,
};

Intelligence Growth:

  • Per fix: +μ = +0.0382%
  • After 100 fixes: ×47 intelligence multiplier
  • Formula: intelligence × (1 + μ)^100

Usage

# Run AGENT MU verification (no auto-fix)
zig build agent-mu-verify

# Run AGENT MU with auto-fix enabled
zig build agent-mu-fix

# View mutation statistics
cat .ralph/memory/MUTATION_STATS.md

# View regression patterns
cat .ralph/memory/REGRESSION_PATTERNS.md

Files

FilePurposeLines
src/agent_mu/fixer.zigAuto-fix implementations659
src/agent_mu/pattern_matcher.zigSemantic search396
src/agent_mu/agent_mu.zigMain loop + feedback363
src/agent_mu/logger.zigLogging + μ tracking308
src/agent_mu/diagnostic.zigError parsing450+
src/agent_mu/verifier.zigBuild/test verification200+

Test Results

fixer.zig:        9/9 tests passed ✅
agent_mu.zig: 2/2 tests passed ✅
diagnostic.zig: 4/4 tests passed ✅
Total: 15/15 (100%)

Exit Criteria

AGENT MU completes when:

  1. All checks pass (build + test + format)
  2. Auto-fix applied successfully (if needed)
  3. Success logged to SUCCESS_HISTORY.md
  4. Mutation statistics updated
AGENT_MU_EXIT = (
verification_passed OR
(max_retries_exhausted AND regression_logged)
)

🔧 Zig 0.15 Idioms in AGENT MU

AGENT MU actively applies these idioms when fixing code:

IdiomBefore FixAfter FixWhy
ArrayListUnmanagedArrayList(T).init(allocator)ArrayListUnmanaged(T){}No allocator capture needed
Inferred errorsconst Error = error{...}; fn foo() !Errorfn foo() !voidSimpler, auto-inferred
Packed structsstruct { x: u8, y: u8, z: u8 }packed struct { xyz: u24 }Memory optimization
ArenaAllocatorMultiple allocsSingle arena blockFaster temp allocations
Error Return TracesSilent failure@errorReturnTrace() in logsBetter diagnostics
Comptime assertionsRuntime checkscomptime assert(...)Catch errors at compile time
errdeferManual cleanuperrdefer freeAlloc(ptr)Guaranteed cleanup

Example: ArrayListUnmanaged Fix

// ❌ BEFORE (causes ALLOCATOR_FIX)
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
try list.append(42);

// ✅ AFTER (AGENT MU applies)
var list = std.ArrayListUnmanaged(u8){};
defer list.deinit(allocator);
try list.append(allocator, 42);

Example: Inferred Error Set Fix

// ❌ BEFORE (causes ERROR_UNION_FIX)
const ParseError = error{ InvalidSyntax, UnexpectedEOF };
fn parse(data: []const u8) !ParseError {
// ...
}

// ✅ AFTER (AGENT MU applies)
fn parse(data: []const u8) !void {
// Error set inferred from body
return error.InvalidSyntax;
}

Sacred Constants in AGENT MU

// src/agent_mu/logger.zig
pub const MU: f64 = 1.0 / (1.618033988749895 * 1.618033988749895) / 10.0; // = 0.0382

pub const MutationStats = struct {
total_fixes: u32 = 0,
successful_fixes: u32 = 0,
failed_fixes: u32 = 0,
intelligence_gain: f64 = 0.0,

pub fn calculateGain(self: *const MutationStats) f64 {
return @as(f64, @floatFromInt(self.successful_fixes)) * MU;
}
};

More Before/After Examples

IdiomBefore FixAfter FixWhy
errdeferManual cleanup in each error patherrdefer allocator.free(ptr);Guaranteed cleanup
@prefetchNo prefetching in hot loops@prefetch(&data[i+4], .{.cache=.data, .rw=.read});Hot loop optimization
@compileLogSilent comptime failures@compileLog("Generating struct:", name);Debug codegen
@setEvalBranchQuotaQuota exceeded on complex templatesinline for (0..100) |i| { @setEvalBranchQuota(100000); }Complex templates
@shuffle/@selectScalar operations@shuffle(u32, a, b, mask)SIMD permutation

Example: errdefer Fix

// ❌ BEFORE (causes memory leak on error)
fn parseFile(allocator: std.mem.Allocator, path: []const u8) !VibeeSpec {
const content = try std.fs.cwd().readFileAlloc(allocator, path, 1024 * 1024);
// If next line fails, content leaks!
const tokens = try tokenize(allocator, content);
allocator.free(content);
return parseSpec(allocator, tokens);
}

// ✅ AFTER (AGENT MU applies errdefer)
fn parseFile(allocator: std.mem.Allocator, path: []const u8) !VibeeSpec {
const content = try std.fs.cwd().readFileAlloc(allocator, path, 1024 * 1024);
errdefer allocator.free(content); // Freed if any error occurs

const tokens = try tokenize(allocator, content);
allocator.free(content);
return parseSpec(allocator, tokens);
}

Example: @prefetch for Hot Loops

// ❌ BEFORE (no prefetching)
fn bundleMany(vectors: []const VSAVector) VSAVector {
var result: VSAVector = undefined;
for (vectors, 0..) |v, i| {
result = bundle2(result, v);
// Next iteration will cache miss!
}
return result;
}

// ✅ AFTER (AGENT MU adds prefetch)
fn bundleMany(vectors: []const VSAVector) VSAVector {
var result: VSAVector = undefined;
for (vectors, 0..) |v, i| {
// Prefetch 4 iterations ahead
if (i + 4 < vectors.len) {
@prefetch(&vectors[i + 4], .{ .cache = .data, .rw = .read });
}
result = bundle2(result, v);
}
return result;
}

Example: @compileLog for Codegen Debug

// ❌ BEFORE (silent comptime failures)
fn generateStruct(comptime name: []const u8) type {
return @Type(.{ .Struct = .{
.fields = &fields,
// If something wrong here, no output!
} });
}

// ✅ AFTER (AGENT MU adds @compileLog)
fn generateStruct(comptime name: []const u8) type {
@compileLog("Generating struct:", name);
@compileLog("Field count:", fields.len);
return @Type(.{ .Struct = .{
.fields = &fields,
} });
}

Example: @setEvalBranchQuota for Complex Templates

// ❌ BEFORE (quota exceeded)
fn generateLargeTable(comptime size: usize) type {
var fields: [size]std.builtin.Type.StructField = undefined;
inline for (0..size) |i| {
fields[i] = .{ .name = "field", .type = u32, ... };
}
// Error: evaluation exceeded 1000 branch quota
return @Type(.{ .Struct = .{ .fields = &fields } });
}

// ✅ AFTER (AGENT MU adds @setEvalBranchQuota)
fn generateLargeTable(comptime size: usize) type {
@setEvalBranchQuota(100000); // Increase quota
var fields: [size]std.builtin.Type.StructField = undefined;
inline for (0..size) |i| {
fields[i] = .{ .name = "field", .type = u32, ... };
}
return @Type(.{ .Struct = .{ .fields = &fields } });
}

KOSCHEI IS IMMORTAL | GOLDEN CHAIN IS CLOSED | φ² + 1/φ² = 3