Skip to content

PLAN: Architecture design for 9 TRI commands + agent interfaces (parent: 45) #118

Closed

Description

@gHashTag

Parent: issue 45. Design .vibee specs structure for all 9 TRI commands. Define agent interface types. Design parallel execution system. Create architecture diagram. Depends on: issue 117 (RESEARCH).

Activity

  1. added this to the Ralph Swarm v1.0 milestone on Mar 10, 2026
  2. gHashTag commented on Mar 17, 2026

    @gHashTag
    CollaboratorAuthor

    🔬 Agent: Ralph | 2026-03-17
    📋 Step: 1/3 — PLAN phase started
    🔄 Status: THINKING
    Thought: RESEARCH phase (#117) identified 6/9 commands with existing specs, 3 agent patterns, and process-level parallelism as the execution model. Now designing the full architecture for 9 TRI commands + agent interfaces + parallel execution.
    Action: Analyzing existing codebase: main.zig dispatch, golden_chain (26 links), command_interface.zig registry, tri_swarm.zig agents, pathology.zig verdict, loop_decide.zig, task_decomposer.zig, spec_create.zig, benchmark.zig, mu_agent.zig.
    Result: Architecture inputs gathered. Proceeding to design.
    Next: Post full architecture design document.

  3. gHashTag commented on Mar 17, 2026

    @gHashTag
    CollaboratorAuthor

    🔬 Agent: Ralph | 2026-03-17
    📋 Step: 2/3 — Architecture Design Document
    🔄 Status: DONE

    Architecture Design: 9 TRI Commands + Agent Interfaces

    1. Command Architecture Overview

    All 9 commands follow the unified pattern established by command_interface.zig:

    User → tri <command> [args]
         → main.zig dispatch
         → command handler (allocator, args) → Error!void
         → output (text/json via tri_config)
    

    Each command maps 1:1 to a Golden Chain link (or group of links) and has a .tri spec as source of truth.

    Command → Golden Chain → Spec Mapping

    # Command Golden Chain Link(s) Existing Impl Spec Status Agent Owner
    1 tri decompose "task" — (pre-chain) task_decomposer.zig + tri_swarm.zig 20% — needs tri_decompose.tri Swarm
    2 tri plan L3 (PAS_ANALYZE) + L4 (TECH_TREE) tri_pipeline.zig stub 60% — extend tri_plan_commands.tri Ralph
    3 tri spec create L6 (SPEC_CREATE) + L25 (SPEC_LINT) spec_create.zig (v2, real impl) 70% — adequate Ralph
    4 tri gen L7 (CODE_GENERATE) rna_polymerase.zig (pipeline_executor) 90% — adequate Ralph
    5 tri test L9 (TEST_RUN) tri_commands.zig → zig build test 95% — adequate Linter
    6 tri bench L10-L13 (BENCHMARK_*) benchmark.zig + perf_benchmark.zig 80% — adequate Oracle
    7 tri verdict L17 (TOXIC_VERDICT) pathology.zig (12 dimensions, v3) 0% spec — needs tri_verdict.tri Oracle
    8 tri git L18 (GIT) tri_commands.zig → runGitCommand 70% — extend tri_git.tri Ralph
    9 tri loop decision L19 (LOOP) loop_decide.zig (v2, real impl) 75% — extend tri_loop.tri MU

    2. New .tri Specs Required

    2.1 specs/tri/tri_decompose.tri (NEW — critical)

    name: tri_decompose
    version: "1.0.0"
    module: task_decomposer
    
    types:
      DecomposeInput:
        task_description: "[]const u8"    # Natural language task
        parent_issue: "?u32"              # GitHub issue number
        max_subtasks: "u8"                # Default: 5 (RESEARCH/PLAN/IMPLEMENT/TEST/VERIFY)
        agent_hints: "[]const AgentRole"  # Preferred agent assignments
    
      DecomposeOutput:
        subtasks: "[]SubTask"
        dag: "DependencyGraph"            # Which subtasks depend on which
        estimated_tokens: "u64"           # Total token budget estimate
        parallel_groups: "[][]u32"        # Groups that can run in parallel
    
      DependencyGraph:
        edges: "[][2]u32"                 # (from_idx, to_idx) pairs
        critical_path: "[]u32"            # Longest dependency chain
    
    behaviors:
      decompose:
        given: "DecomposeInput"
        when: "tri decompose <task> [--issue N] [--max-subtasks N]"
        then: >
          1. Parse task into semantic chunks
          2. Map chunks to Phase enum (research/plan/implement/test/verify)
          3. Build dependency DAG (research→plan→implement→test→verify default)
          4. Assign agents based on phase (scholar→research, ralph→implement, etc.)
          5. Create GitHub sub-issues via gh CLI
          6. Return DecomposeOutput with parallel groups
    
      parallelize:
        given: "DependencyGraph"
        when: "computing parallel groups"
        then: >
          Topological sort → group by depth level.
          Subtasks at same depth = same parallel group.
          Default: [RESEARCH] → [PLAN] → [IMPLEMENT] → [TEST, VERIFY]
    

    2.2 specs/tri/tri_verdict.tri (NEW — critical, 0% coverage)

    name: tri_verdict
    version: "1.0.0"
    module: pathology
    
    types:
      VerdictInput:
        build_ok: "bool"
        test_passed: "u32"
        test_total: "u32"
        lines_added: "u32"
        lines_removed: "u32"
        todo_count: "u32"
        god_file_count: "u32"         # Files > 500 LOC
        dead_code_ratio: "f32"
        duplication_ratio: "f32"
        spec_coverage: "f32"          # % of .zig files with .tri specs
        research_score: "f32"
        token_cost: "u64"
        energy_score: "f32"
    
      VerdictOutput:
        total_score: "f32"            # 0-100
        level: "VerdictLevel"         # legendary/solid/mediocre/garbage/disaster
        dimensions: "[12]DimensionScore"
        recommendation: "Decision"    # continue/fix/revise/escalate
        report_text: "[]const u8"     # Formatted terminal output
    
      VerdictLevel: enum legendary|solid|mediocre|garbage|disaster
      DimensionScore:
        name: "[]const u8"
        raw: "f32"
        weighted: "f32"
        tier: "u8"                    # 1, 2, or 3
    
    behaviors:
      compute:
        given: "VerdictInput"
        when: "tri verdict [--json] [--threshold N]"
        then: >
          Apply 12-dimension formula:
            Tier 1 (0.50): BUILD(0.20) + TEST_PASS(0.15) + TEST_COVER(0.15)
            Tier 2 (0.30): TODO_DEBT(0.06) + GOD_FILES(0.05) + DEAD_CODE(0.06) + DUPLICATION(0.05) + SPEC_GAP(0.08)
            Tier 3 (0.20): RESEARCH(0.08) + TOKEN_COST(0.06) + ENERGY(0.06)
          Classify level. Generate report.
    
      auto_collect:
        given: "allocator"
        when: "tri verdict (no explicit input)"
        then: >
          1. Run zig build → build_ok
          2. Run zig build test → test counts
          3. Count TODOs via grep
          4. Count god files (>500 LOC)
          5. Read .doctor/scan_results.json → spec coverage
          6. Feed all into compute()
    

    2.3 specs/tri/tri_pipeline_parallel.tri (NEW — infrastructure)

    name: tri_pipeline_parallel
    version: "1.0.0"
    module: pipeline_parallel
    
    types:
      PipelineJob:
        id: "u64"
        command: "PipelineCommand"     # Which of the 9 commands
        args: "[8][256]u8"
        status: "JobStatus"
        started_at: "i64"
        finished_at: "i64"
        exit_code: "u8"
        output_path: "[256]u8"        # File path for captured output
    
      PipelineCommand: enum decompose|plan|spec|gen|test|bench|verdict|git|loop
    
      JobStatus: enum queued|running|done|failed|skipped
    
      PipelineDAG:
        jobs: "[16]PipelineJob"       # Max 16 concurrent jobs
        job_count: "u8"
        edges: "[32][2]u8"            # Dependency edges (from_idx → to_idx)
        edge_count: "u8"
    
      PipelineState:
        dag: "PipelineDAG"
        current_group: "u8"           # Which parallel group is executing
        total_groups: "u8"
        state_path: "[256]u8"         # .trinity/pipeline_state.json
    
    behaviors:
      execute_dag:
        given: "PipelineDAG, allocator"
        when: "tri pipeline run <task>"
        then: >
          1. Topological sort jobs by dependency edges
          2. Group into parallel levels
          3. For each level:
             a. Spawn all jobs in group via std.process.Child
             b. Wait for all to complete (sequential wait, process-level parallel)
             c. If any job fails → check if critical (build/test) or optional (bench/docs)
             d. Critical fail → stop pipeline, report
             e. Optional fail → mark skipped, continue
          4. Persist state to .trinity/pipeline_state.json after each group
    
      resume:
        given: "PipelineState from disk"
        when: "tri pipeline resume"
        then: "Load state, find first incomplete group, continue from there"
    

    3. Specs to Extend

    3.1 tri_plan_commands.tri — Add Behaviors

    Add to existing spec:

    behaviors:
      strategic_plan:
        given: "DecomposeOutput from tri decompose"
        when: "tri plan [--issue N]"
        then: >
          1. Read decomposed subtasks
          2. Analyze dependency graph for parallelism opportunities
          3. Estimate token costs per subtask (context size × turns)
          4. Generate step-by-step execution plan
          5. Post plan as GitHub comment (Protocol v2 format)
          6. Return PlanOutput with ordered steps + time estimates
    
      replan:
        given: "PipelineState with failures"
        when: "tri plan --replan"
        then: >
          Read failed jobs from pipeline state.
          Adjust plan: add retry steps, skip non-critical, escalate blockers.
    

    3.2 swarm_github.tri → extend to tri_git.tri

    Add to existing spec:

    behaviors:
      commit_safe:
        when: "tri git commit <msg>"
        then: "zig fmt → zig build test → git add → git commit (block main push)"
    
      branch_create:
        when: "tri git branch <name>"
        then: "Create branch from main, validate naming (ralph/w{N}/feat-*)"
    
      pr_create:
        when: "tri git pr [--issue N]"
        then: "Push branch → gh pr create with Closes #N → return PR URL"
    

    3.3 learning_loops.tri → extend to tri_loop.tri

    Add to existing spec:

    behaviors:
      decide:
        when: "tri loop decision"
        then: >
          Collect signals: build status, test ratio, verdict score, doctor health, dirty count.
          Apply priority rules (build fail → escalate at 5+ → test < 50% → etc.)
          Return Decision enum (continue_next | fix_first | spec_revise | idle_wait | escalate)
    
      needle_check:
        when: "loop decides to continue"
        then: >
          Run needle analysis: is the system actually improving?
          Compare current verdict score to previous N scores.
          If regression detected → switch to fix_first.
    

    4. Agent Interface Architecture

    4.1 Unified Agent Interface

    All agents implement the same protocol. Source of truth: command_interface.zig CommandFn type.

    /// Every agent command follows this signature:
    pub const CommandFn = *const fn (allocator: Allocator, args: []const []const u8) Error!void;

    Inter-agent communication uses the filesystem (no sockets, no threads):

    Agent A writes → .trinity/pipeline_state.json → Agent B reads
    Agent A writes → .trinity/farm/events.jsonl → Agent B reads
    Agent A runs → gh issue comment N → Agent B reads via gh CLI
    

    4.2 Agent Roles → Command Ownership

    ┌─────────────────────────────────────────────────────┐
    │                    SWARM (Coordinator)               │
    │  tri decompose → SubTask[] + DAG                     │
    │  Assigns agents to subtasks                          │
    └──────┬──────────────┬──────────────┬────────────────┘
           │              │              │
      ┌────▼────┐   ┌────▼────┐   ┌────▼────┐
      │  RALPH  │   │ SCHOLAR │   │   MU    │
      │ (Coder) │   │(Research│   │(Memory) │
      │         │   │ + Plan) │   │         │
      │ spec    │   │ plan    │   │ loop    │
      │ gen     │   │ bench   │   │ verdict │
      │ git     │   │         │   │ test    │
      └────┬────┘   └────┬────┘   └────┬────┘
           │              │              │
           └──────────────┼──────────────┘
                          │
                  ┌───────▼───────┐
                  │    ORACLE     │
                  │  (Watchdog)   │
                  │               │
                  │  verdict      │
                  │  bench        │
                  │  loop decide  │
                  └───────────────┘
    

    Role assignments (flexible — Swarm can reassign):

    Agent Primary Commands Rationale
    Swarm decompose Task breakdown is coordination
    Scholar plan, bench (external) Research-oriented analysis
    Ralph spec create, gen, git Core implementation cycle
    MU test, loop Error detection + memory
    Oracle verdict, bench (compare) Quality gatekeeping

    4.3 Agent State Machine

    Each agent follows the ReAct pattern from vibeec/agent_loop.zig:

    Idle → Thinking → Planning → Acting → Observing → Done/Error
     ↑                                         │
     └─────────────────────────────────────────┘
    

    State transitions are recorded as GitHub issue comments (Protocol v2):

    {emoji} **Agent: {name}** | {timestamp}
    📋 **Step**: {N}/{total} — {description}
    🔄 **Status**: THINKING | ACTING | DONE | FAILED
    

    4.4 Agent Communication Protocol

    1. FILE-BASED (primary):
       .trinity/pipeline_state.json  — pipeline DAG + job status
       .trinity/agent_state.json     — per-agent status
       .trinity/farm/events.jsonl    — append-only event log
    
    2. GITHUB-BASED (audit trail):
       Issue comments                — every step recorded
       Labels                        — status:in-progress, agent:ralph
       Sub-issues                    — task decomposition
    
    3. PROCESS-BASED (execution):
       std.process.Child             — spawn agent as subprocess
       Exit code                     — 0=success, 1=fail, 2=escalate
       Stdout capture                — output → .trinity/job_output/
    

    5. Parallel Execution Design

    5.1 Execution Model: Process-Level Parallelism

    No Zig threads. Each command runs as a tri <cmd> subprocess via std.process.Child.

    tri pipeline run "implement feature X"
      │
      ├─ Group 0: [tri decompose "implement feature X"]
      │    └─ produces: subtask list + DAG
      │
      ├─ Group 1: [tri plan --issue 123]
      │    └─ produces: execution plan
      │
      ├─ Group 2: [tri spec create feat_x, tri spec create feat_y]  ← PARALLEL
      │    └─ produces: .tri spec files
      │
      ├─ Group 3: [tri gen feat_x, tri gen feat_y]  ← PARALLEL
      │    └─ produces: .zig source files
      │
      ├─ Group 4: [tri test, tri bench]  ← PARALLEL
      │    └─ produces: test results + benchmarks
      │
      ├─ Group 5: [tri verdict]
      │    └─ produces: quality score + recommendation
      │
      ├─ Group 6: [tri git commit "feat(x): description"]
      │    └─ produces: git commit
      │
      └─ Group 7: [tri loop decision]
           └─ produces: continue/fix/escalate
    

    5.2 DAG Execution Algorithm

    // Pseudocode for pipeline_parallel.zig
    fn executeDag(dag: *PipelineDAG, allocator: Allocator) !void {
        const groups = topologicalGroupSort(dag);
        
        for (groups) |group| {
            // Spawn all jobs in group as child processes
            var children: [16]std.process.Child = undefined;
            var count: usize = 0;
            
            for (group.jobs) |job| {
                children[count] = try std.process.Child.init(.{
                    .argv = buildArgv(job),
                    .stdout_behavior = .pipe,
                    .stderr_behavior = .pipe,
                });
                try children[count].spawn();
                count += 1;
            }
            
            // Wait for all in group
            for (children[0..count]) |*child| {
                const term = try child.wait();
                // Record result in pipeline state
            }
            
            // Persist state after each group
            try persistState(dag, ".trinity/pipeline_state.json");
            
            // Check for critical failures
            if (hasCriticalFailure(group)) return error.PipelineFailed;
        }
    }

    5.3 Error Recovery Strategy

    Failure Type Response Max Retries
    Build fail (tri test) Stop pipeline, invoke MU agent 3
    Spec lint fail (tri spec) Auto-fix with MU suggestions 2
    Codegen fail (tri gen) Revise spec, re-gen 2
    Bench regression (tri bench) Warning only, continue 0
    Verdict < 30 (tri verdict) Escalate to human 0
    Git conflict (tri git) Rebase, retry 1
    Network error (GitHub API) Exponential backoff 3

    6. File Structure (New/Modified)

    specs/tri/
      tri_decompose.tri          (NEW — task decomposition spec)
      tri_verdict.tri            (NEW — verdict/acceptance spec)
      tri_pipeline_parallel.tri  (NEW — parallel execution spec)
      tri_plan_commands.tri      (EXTEND — add strategic_plan, replan)
      tri_git.tri                (NEW — rename from swarm_github.tri extension)
      tri_loop.tri               (NEW — rename from learning_loops.tri extension)
    
    src/tri/
      task_decomposer.zig        (EXISTS — enhance with DAG output)
      pathology.zig              (EXISTS — add auto_collect behavior)
      pipeline_parallel.zig      (NEW — DAG executor, process spawning)
      loop_decide.zig            (EXISTS — add needle_check)
      spec_create.zig            (EXISTS — adequate)
      rna_polymerase.zig         (EXISTS — adequate)
      benchmark.zig              (EXISTS — adequate)
      tri_commands.zig            (EXISTS — git commands adequate)
      tri_pipeline.zig           (EXISTS — wire up pipeline_parallel)
    
    .trinity/
      pipeline_state.json        (NEW — persisted DAG state)
      job_output/                (NEW — captured stdout/stderr per job)
    

    7. Implementation Order (for issue #119 IMPLEMENT)

    Phase A — Infrastructure (must be first):

    1. tri_pipeline_parallel.tri → pipeline_parallel.zig (DAG executor)
    2. Wire into tri_pipeline.zig runPipelineCommand

    Phase B — Missing Commands (parallel, no deps between them):
    3. tri_decompose.tri → enhance task_decomposer.zig
    4. tri_verdict.tri → enhance pathology.zig with auto_collect

    Phase C — Extensions (parallel, no deps between them):
    5. Extend tri_plan_commands.tri → plan behaviors
    6. Create tri_git.tri → git lifecycle
    7. Create tri_loop.tri → needle integration

    Phase D — Integration + Test:
    8. Wire all 9 commands into pipeline DAG
    9. E2E test: tri pipeline run "hello world" executes full chain
    10. Verdict on the pipeline itself (dogfood)


    8. Constraints & Decisions

    Decision Rationale
    Process-level parallelism only No Zig threading complexity. MCP servers already run as processes. Oracle watchdog is the only thread user and that's special-cased.
    File-based inter-agent state Zero external deps. JSON files in .trinity/. Atomic via write-tmp-rename.
    GitHub as audit trail Protocol v2 requirement. Every agent step = issue comment.
    Max 16 jobs per DAG Fixed-size arrays, no heap allocation for the DAG structure itself.
    CommandFn signature unchanged All 9 commands use fn(Allocator, []const []const u8) Error!void. No new interface needed.
    Verdict = quality gate Pipeline stops if verdict < 30 (disaster level). No override without explicit --force.
    MU agent as error memory Error patterns from failed jobs persist in .trinity/mu/ JSONL. MU suggests fixes on retry.

    Summary: 3 new specs + 3 spec extensions + 1 new module (pipeline_parallel.zig) + enhancements to 3 existing modules. Total estimated: ~1200 LOC new, ~400 LOC modified. All pure Zig, zero external deps, process-level parallelism, file-based state, GitHub audit trail.

  4. gHashTag commented on Mar 17, 2026

    @gHashTag
    CollaboratorAuthor

    🔬 Agent: Ralph | 2026-03-17
    📋 Step: 3/3 — PLAN phase complete
    🔄 Status: DONE
    Thought: Architecture design covers all 9 commands, agent interfaces, parallel execution, and spec gap analysis.
    Action: Posted comprehensive architecture document with: command mapping table, 3 new .tri specs (decompose, verdict, pipeline_parallel), 3 spec extensions (plan, git, loop), agent role assignments, DAG execution algorithm, error recovery strategy, and implementation order.
    Result: Architecture design document posted as comment on #118. Key decisions: process-level parallelism (no threads), file-based inter-agent state, GitHub audit trail, CommandFn signature unchanged, max 16 jobs per DAG, verdict as quality gate.
    Next: PLAN complete. Ready for IMPLEMENT phase (#119). Implementation order: infrastructure (pipeline_parallel) → missing commands (decompose, verdict) → extensions (plan, git, loop) → integration + E2E test.

  5. gHashTag commented on Apr 29, 2026

    @gHashTag
    CollaboratorAuthor

    522 .vibee specs exist in specs/tri/. Architecture design complete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions