Skip to content

Public Packages

Eshan Roy edited this page Jun 21, 2026 · 3 revisions

Public Packages

The pkg/ directory of M31 Autonomous (M31A) contains importable Go packages that can be used by external projects. Each package has a doc.go file with package-level documentation.

arbitrage

Source: pkg/arbitrage/arbitrage.go

Model cost optimization engine. Scores task complexity, estimates token usage, and recommends the cheapest model that meets quality requirements.

Task Classification

Level Estimated Tokens Keywords
Simple 2,000 input + 1,000 output fix, add, update, change, rename, typo, format
Moderate 5,500 input + 2,750 output implement, create, refactor, database, api, frontend
Complex 14,000 input + 7,000 output design, architect, migrate, rewrite, system, deploy

Complexity is boosted one level when a task has more than 3 files or more than 3 dependencies.

Key Types

type Scorer struct {
    SimpleThreshold  int  // default 2000
    ComplexThreshold int  // default 8000
}

type CostEstimate struct {
    ModelID      string
    Provider     string
    InputCost    float64
    OutputCost   float64
    TotalCost    float64
    Currency     string
    InputTokens  int
    OutputTokens int
}

type ArbitrageRecommendation struct {
    RecommendedModel CostEstimate
    Alternatives     []CostEstimate
    Complexity       ComplexityLevel
    Savings          float64
    Reason           string
}

Key Functions

Function Description
Score(task) Classify task complexity and estimate tokens
EstimateTokens(complexity, task) Compute input/output token estimates
CompareModels(models, inputTokens, outputTokens) Rank models by cost
Recommend(models, task, threshold) Get best model recommendation
ShouldArbitrage(current, alternative, threshold) Check if switching saves money

For complex tasks, models with context windows ≤64K are rejected unless no alternative is within the price threshold.

autodream

Source: pkg/autodream/autodream.go

Context consolidation engine. Compresses the oldest 50% of non-protected messages into a single memory segment to prevent context window overflow.

Protected Messages

The following are never consolidated:

  • First message (index 0) -- initial goal
  • All system messages
  • Messages with tool calls
  • Tool result messages (role="tool")
  • Messages containing critical context (plans, task lists, acceptance criteria)
  • Last 5 messages

Consolidation Algorithm

  1. Compute protected indices
  2. Compute candidate indices (non-protected)
  3. Select oldest 50% of candidates (ceiling)
  4. Build summary using role-sampled content (~500 tokens)
  5. Replace selected messages with a single [AutoDream Context Summary] system message

Key Types

type Consolidator struct {
    messages            []types.Message
    paused              bool
    lastConsolidation   time.Time
    totalConsolidations int
    consolidating       atomic.Bool  // reentrancy guard
}

type ConsolidationResult struct {
    Success         bool
    MessagesRemoved int
    TokensSaved     int
    DurationMs      int64
    Summary         string
    Error           string
}

Reentrancy Guard

Consolidate() uses atomic.Bool with CompareAndSwap to prevent nested /compress calls from creating a double-summary state.

bisect

Source: pkg/bisect/bisect.go

Git bisect wrapper for finding the commit that introduced a bug.

Algorithm

sequenceDiagram
    participant B as Bisect
    participant G as Git
    participant C as checkFn

    B->>G: bisect start
    B->>G: bisect good sessionStartHash
    B->>G: bisect bad headHash
    loop Until first bad commit
        G-->>B: current commit (HEAD)
        B->>C: checkFn()
        alt Pass
            B->>G: bisect good
        else Fail
            B->>G: bisect bad
        end
    end
    B->>G: bisect log → offending commit
    B->>G: diff offending^..offending
    B->>G: bisect reset (deferred)
Loading

Returns BisectResult with the offending commit hash and its diff.

Key Types

type BisectResult struct {
    OffendingCommit git.CommitInfo
    Diff            string
}

type GitRunner interface {
    Run(args ...string) (string, error)
}

history

Source: pkg/history/history.go

Session history store. Tracks prompt history with frecent (frequent + recent) ranking for autocomplete and quick access. Uses an O(1) textIndex map for instant upsert lookups instead of linear scanning through entries.

keychain

Source: pkg/keychain/keychain.go

OS keychain abstraction for secure API key storage. Three platform implementations:

Platform File Backend
Linux keychain_linux.go D-Bus Secret Service + pass CLI fallback
macOS keychain_darwin.go /usr/bin/security (Keychain Access)
Windows keychain_windows.go Windows Credential Manager
type Keychain interface {
    Get(service string) (string, error)
    Set(service, value string) error
    Delete(service string) error
}

All keys are prefixed with m31a/ and use account name m31a.

ledger

Source: pkg/ledger/ledger.go

Cross-session learning ledger stored as a markdown table in ~/.m31a/LEDGER.md.

LedgerEntry

type LedgerEntry struct {
    SessionID       string
    Timestamp       time.Time
    Model           string
    Provider        string
    ProjectType     string
    GoalKeywords    []string
    Framework       string
    TaskCount       int
    FailedTasks     int
    SkippedTasks    int
    CostEstimate    float64
    DurationMinutes int
    CommitCount     int
}

Features

  • Append-only writes (new entries appended, not full rewrite)
  • Deduplication by SessionID (idempotency guard)
  • Filtered queries by project type and keywords
  • Aggregate statistics with mtime-based caching
  • Truncation support (keep newest N entries)

LedgerStats

type LedgerStats struct {
    TotalSessions      int
    AvgTaskCount       float64
    AvgCost            float64
    AvgDurationMinutes float64
    TotalFailedTasks   int
    TopFailures        []string
    TopFrameworks      []string
    ByProjectType      map[string]int
}

rollback

Source: pkg/rollback/rollback.go

Commit-chain manager providing safe git reset operations.

Reset Modes

Mode Description Safety
SoftReset git reset --soft Keeps changes staged
HardReset git reset --hard Creates backup branch first
SafeReset git reset --hard + stash pop Preserves uncommitted changes

Key Features

  • Auto-stash before reset (dirty working tree protection)
  • Backup branch creation (m31a/rollback-backup-<timestamp>) before hard reset
  • Commit counting between two hashes
  • Diff preview capped at 50,000 characters
  • onReset callback for synchronizing TASKS.md state

RollbackEntry

type RollbackEntry struct {
    CommitInfo    git.CommitInfo
    Diff          string
    IsCurrent     bool
    HasCheckpoint bool
}

metrics

Source: pkg/metrics/

Centralized session observability pipeline. Tracks tool execution, LLM token usage/cost, and workflow phase metrics with thread-safe collection and JSON persistence.

Key Types

type Collector struct {
    mu          sync.Mutex
    sessionID   string
    sessionsDir string
    metrics     *SessionMetrics
    enabled     bool
}

type SessionMetrics struct {
    SessionID string
    StartedAt time.Time
    Tools     []ToolMetric   // per-tool call count, success/fail, avg duration
    LLMs      []LLMMetric    // per-phase tokens, cost, interaction count
    Phases    []PhaseMetric  // per-phase duration, transitions, heal/bisect triggers
}

See Metrics & Observability for detailed documentation.

session

Source: pkg/session/

Full session lifecycle management. See Session Management for detailed documentation.

taskrunner

Source: pkg/taskrunner/runner.go

Sequential and parallel task executor. Executes tasks from the plan phase respecting dependency order.

Features

  • Topological sort for dependency ordering
  • Parallel execution within independent task groups (up to DefaultMaxParallelTasks = 4)
  • Circular dependency detection
  • Per-task timeout and error handling

Clone this wiki locally