Skip to content

Latest commit

 

History

History
265 lines (206 loc) · 8.98 KB

interfaces.md

File metadata and controls

265 lines (206 loc) · 8.98 KB

Core Interfaces (Go)

The Go types that define ACP's component boundaries, as implemented in internal/.


1. StateStore

The foundational layer. Everything else is built on top of this.

// internal/store/store.go
package store

// StateStore abstracts all filesystem operations on the vault.
type StateStore interface {
    // Read returns the full contents of a file.
    // Returns an error satisfying errors.Is(err, fs.ErrNotExist) if missing.
    Read(path string) ([]byte, error)

    // Write atomically creates or replaces a file: the data is written to a
    // hidden temp file in the same directory and renamed into place, so
    // readers never observe a partial write. Creates parent directories.
    Write(path string, data []byte) error

    // Append adds data to a file, creating it if needed. Used for logs.
    Append(path string, data []byte) error

    // List returns the sorted names of entries in a directory, excluding
    // hidden entries (names starting with "."). This is what keeps temp
    // files and the .wip/ staging dir invisible to scans.
    List(path string) ([]string, error)

    // Exists reports whether a path exists.
    Exists(path string) bool

    // Delete removes a file. No-op if the file doesn't exist.
    Delete(path string) error

    // Move atomically moves src to dest via rename(2). Exactly one caller
    // can win a Move from a given src; losers get fs.ErrNotExist.
    Move(src, dest string) error

    // ModTime returns the modification time (used by the .wip janitor).
    ModTime(path string) (time.Time, error)
}

V1 implementation: FileSystemStore (internal/store/filesystem.go).

A caveat on swappability: the method signatures could be implemented over Redis or Postgres, but everything above this layer depends on the semantics of Move (same-filesystem atomic rename, exactly-one-winner) and Write (atomic replace), and the directory-per-state vault layout is filesystem-shaped. A different backend means porting the concurrency model, not just re-implementing seven methods. Treat StateStore as a seam for testing and instrumentation, not as proof that the storage layer is pluggable for free.


2. Queue

Built on top of StateStore. Manages the task lifecycle using the .wip mutation protocol (see Task State Machine §6): every mutation renames the task file into tasks/.wip/, mutates it there, and renames it to its destination. No code path writes a task file it has not first acquired.

// internal/task/queue.go
package task

// Sentinel errors callers test with errors.Is:
var (
    ErrNotFound          = errors.New("task not found")
    ErrLeaseLost         = errors.New("lease lost")   // stop work, discard results
    ErrNotOwner          = errors.New("task assigned to a different agent")
    ErrInvalidTransition = errors.New("invalid state transition")
)

type Config struct {
    LeaseDuration time.Duration // default 30m
    MaxRetries    int           // default 3
    MaxReleases   int           // default 5 (poison-pill guard)
}

type Queue struct {
    Store store.StateStore
    Vault string
    Cfg   Config
    Now   func() time.Time // injectable clock for tests
}

// CreateTask writes a new task to vault/tasks/pending/.
func (q *Queue) CreateTask(input CreateTaskInput) (*Task, error)

// ClaimTask atomically claims the best available task matching the agent's
// capabilities: highest priority first, then oldest. Returns (nil, nil)
// when nothing is claimable. The returned task is already in doing/ with
// lease fields set — there is no window where a doing/ task lacks a lease.
func (q *Queue) ClaimTask(agentID string, capabilities []string) (*Task, error)

// CompleteTask marks a doing task done. Idempotent (already-done = no-op
// success). Returns ErrLeaseLost if the task was re-queued or re-claimed,
// ErrNotOwner if another agent holds it.
func (q *Queue) CompleteTask(taskID, agentID, result string) error

// FailTask marks a doing task permanently failed (agent-reported).
// Idempotent. Does NOT increment retry_count.
func (q *Queue) FailTask(taskID, agentID, errorMsg string) error

// RenewLease extends the lease on a doing task. Safe against concurrent
// recovery: both must win the same rename into .wip/, so a stale renewal
// can never resurrect a re-queued task. ErrLeaseLost means: stop working.
func (q *Queue) RenewLease(taskID, agentID string) error

// ReleaseTask voluntarily returns a doing task to pending. Does not touch
// retry_count, but increments release_count; a task released more than
// MaxReleases times is failed as a poison pill.
func (q *Queue) ReleaseTask(taskID, agentID string) error

// RetryTask moves a failed task back to pending, resetting counters.
func (q *Queue) RetryTask(taskID string) (*Task, error)

// ListTasks returns tasks filtered by status, agent, and/or role.
func (q *Queue) ListTasks(filter ListFilter) ([]*Task, error)

// GetTask finds a task by ID across all state directories.
func (q *Queue) GetTask(taskID string) (*Task, error)

type CreateTaskInput struct {
    Description string
    Priority    Priority          // defaults to Normal
    Role        string            // capability tag; empty = any worker may claim
    Metadata    map[string]string
}

type ListFilter struct {
    Status  *Status // nil = all statuses
    AgentID string  // empty = all agents
    Role    string  // empty = all roles
}

3. Task Model

// internal/task/task.go
package task

type Status string

const (
    Pending Status = "pending"
    Doing   Status = "doing"
    Done    Status = "done"
    Failed  Status = "failed"
)

type Priority string

const (
    Low      Priority = "low"
    Normal   Priority = "normal"
    High     Priority = "high"
    Critical Priority = "critical"
)

type Task struct {
    ID           string            `json:"id"`
    Status       Status            `json:"status"`
    Description  string            `json:"description"`
    Priority     Priority          `json:"priority"`
    Role         string            `json:"role,omitempty"`
    CreatedAt    string            `json:"created_at"`
    RetryCount   int               `json:"retry_count"`
    ReleaseCount int               `json:"release_count,omitempty"`
    Metadata     map[string]string `json:"metadata,omitempty"`

    // Set when status = doing
    AssignedAgent string `json:"assigned_agent,omitempty"`
    LeaseExpiry   string `json:"lease_expiry,omitempty"`
    HeartbeatAt   string `json:"heartbeat_at,omitempty"`
    StartedAt     string `json:"started_at,omitempty"`

    // Set when status = done
    Result      string `json:"result,omitempty"`
    CompletedAt string `json:"completed_at,omitempty"`

    // Set when status = failed
    Error    string `json:"error,omitempty"`
    FailedAt string `json:"failed_at,omitempty"`
}

4. Agent Registration

Agents write this to vault/agents/{agent_id}.json at startup and update last_seen_at on each poll.

// internal/agent/agent.go
package agent

type Record struct {
    AgentID      string   `json:"agent_id"`
    StartedAt    string   `json:"started_at"`
    LastSeenAt   string   `json:"last_seen_at"`
    Capabilities []string `json:"capabilities,omitempty"`
    CurrentTask  string   `json:"current_task,omitempty"`
}

Capabilities matches against Task.Role at claim time: a worker passes its capabilities to ClaimTask, which only considers tasks whose role is empty or present in that list.


5. The Worker Loop

internal/agent/agent.go implements the standard loop every worker follows. The important part is the lease-loss contract:

w := &agent.Worker{
    ID:           "coder-1",
    Capabilities: []string{"coder"},
    Queue:        queue,
    Store:        store,
    Exec:         execFn, // runs the AI tool; receives a cancellable ctx
}
w.Run(ctx)

Per task, the worker:

  1. Claims via ClaimTask (lease fields already set on return).
  2. Starts a background goroutine renewing the lease every HeartbeatInterval.
  3. Runs Exec with a context that is cancelled if renewal returns ErrLeaseLost — the task belongs to someone else now, and any result must be discarded, not reported.
  4. On success: writes vault/results/{id}.{agent}.{attempt_ns}.md — the path is attempt-specific so a stale attempt can never overwrite the new owner's result file — then CompleteTask records that path. If completion returns ErrLeaseLost, the result file is orphaned but harmless — the queue records exactly one completion.
  5. On executor error: FailTask (agent-reported, no retry_count change).

Implementation Map

Type Location Notes
StateStore / FileSystemStore internal/store/ Atomic write + move primitives
Task, Queue internal/task/ Lifecycle + .wip mutation protocol
RecoveryController, VaultController, AgentObserver internal/controller/ Reconciliation loops
Worker, Record internal/agent/ Standard worker loop
acp CLI cmd/acp/ Wraps all of the above