-
-
Notifications
You must be signed in to change notification settings - Fork 0
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.
Source: pkg/arbitrage/arbitrage.go
Model cost optimization engine. Scores task complexity, estimates token usage, and recommends the cheapest model that meets quality requirements.
| 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.
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
}| 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.
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.
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
- Compute protected indices
- Compute candidate indices (non-protected)
- Select oldest 50% of candidates (ceiling)
- Build summary using role-sampled content (~500 tokens)
- Replace selected messages with a single
[AutoDream Context Summary]system message
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
}Consolidate() uses atomic.Bool with CompareAndSwap to prevent nested /compress calls from creating a double-summary state.
Source: pkg/bisect/bisect.go
Git bisect wrapper for finding the commit that introduced a bug.
bisect start
bisect good <sessionStartHash>
bisect bad <headHash>
loop:
checkFn() → pass → bisect good
checkFn() → fail → bisect bad
until "first bad commit" in log
bisect reset (deferred, always runs)
Returns BisectResult with the offending commit hash and its diff.
type BisectResult struct {
OffendingCommit git.CommitInfo
Diff string
}
type GitRunner interface {
Run(args ...string) (string, error)
}Source: pkg/history/history.go
Session history store. Tracks prompt history with frecent (frequent + recent) ranking for autocomplete and quick access.
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.
Source: pkg/ledger/ledger.go
Cross-session learning ledger stored as a markdown table in ~/.m31a/LEDGER.md.
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
}- 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)
type LedgerStats struct {
TotalSessions int
AvgTaskCount float64
AvgCost float64
AvgDurationMinutes float64
TotalFailedTasks int
TopFailures []string
TopFrameworks []string
ByProjectType map[string]int
}Source: pkg/rollback/rollback.go
Commit-chain manager providing safe git reset operations.
| 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 |
- 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
-
onResetcallback for synchronizing TASKS.md state
type RollbackEntry struct {
CommitInfo git.CommitInfo
Diff string
IsCurrent bool
HasCheckpoint bool
}Source: pkg/session/
Full session lifecycle management. See Session Management for detailed documentation.
Source: pkg/taskrunner/runner.go
Sequential and parallel task executor. Executes tasks from the plan phase respecting dependency order.
- Topological sort for dependency ordering
- Parallel execution within independent task groups (up to
DefaultMaxParallelTasks = 4) - Circular dependency detection
- Per-task timeout and error handling