github.com/rotari-dev/rotari/internal/project

Overview

package project // import "github.com/rotari-dev/rotari/internal/project"

Package project owns a project's run state and its idle queue edits.

It classifies a project as idle, running, or interrupted from running.lock and
meta.json, checks that those files agree with the run directory, and explains an
interrupted run to the user. It also owns the sequence every idle edit follows:
take the state lock, require an idle project, load the queue, apply the edit,
and write metadata before the queue.

What an edit does to the queue belongs to the caller or internal/queueedit;
running a queue belongs to internal/projectrun.

Constants

const UnconfirmedStopWarning = "Do not recover until you have independently confirmed those jobs have actually stopped."
    UnconfirmedStopWarning precedes a recovery command for an interrupted run
    whose jobs InterruptedRunDetail reports as possibly still running.

Variables

var ErrNoInterruptedRun = errors.New("no matching interrupted run exists")
    ErrNoInterruptedRun reports that the project has no interrupted run with the
    requested ID.

var ErrRevisionChanged = errors.New("project changed since the planned revision")
    ErrRevisionChanged reports that a guarded edit found the project at another
    revision than the one it was planned on.

var ErrRunAlive = errors.New("run is still running")
    ErrRunAlive reports that the run Unlock was asked to recover still has a
    live coordinator on this host, so removing its lock would let a second
    runner start.

Functions

func CheckRevision(paths state.ProjectPaths, guard Guard) (string, error)
    CheckRevision returns the project's revision, refusing the edit when it is
    not guard.IfRevision. Callers hold the state lock, unless the project does
    not exist yet.

func CountRuns(paths state.ProjectPaths) int
    CountRuns counts a project's saved run directories.

func CreateQueueGuarded(paths state.ProjectPaths, guard Guard, edit func(queue *model.Queue) error) error
    CreateQueueGuarded is EditQueueGuarded for an edit that may create the
    project, such as add or import. Applying it creates the project directory
    first. A dry run of a project that does not exist yet edits an empty queue
    without locking or creating anything, and reports the revision a new project
    has.

func Edit(paths state.ProjectPaths, operation string, edit func() error) error
    Edit runs edit while holding the project's state lock, after checking that
    the project is idle. operation names the command in the rejection message.

func EditGuarded(paths state.ProjectPaths, operation string, guard Guard, edit func(dryRun bool) error) error
    EditGuarded is Edit under guard. It checks guard.IfRevision under the lock,
    and passes guard.DryRun to edit, which must not write when it is set.

func EditQueue(paths state.ProjectPaths, edit func(queue *model.Queue) error) error
    EditQueue applies edit to the project's queue under the state lock and saves
    the result. The queue holds only the next run's jobs, since a run takes
    the queue when it starts, so it can be edited whether the project is idle,
    running, or interrupted. When edit returns an error, nothing is written.

func EditQueueGuarded(paths state.ProjectPaths, guard Guard, edit func(queue *model.Queue) error) error
    EditQueueGuarded is EditQueue under guard: a dry run computes the queue edit
    reports, without writing it.

func EnsureIdle(paths state.ProjectPaths, operation string) error
    EnsureIdle rejects operation unless the project is idle. The error for an
    interrupted run tells the user how to inspect and recover it.

func EnsureRunSettled(paths state.ProjectPaths, runID, operation string) error
    EnsureRunSettled refuses the project's active or interrupted run: runID,
    or any when runID is empty. Its results are not final and its jobs may still
    run, so operation, such as copy or export, would act on results that may yet
    change.

func ExplicitCommandLocation(paths state.ProjectPaths) string
    ExplicitCommandLocation names both --basedir and --project-name, for readers
    whose environment rotari cannot know, such as the Web UI or MCP.

func InspectRunLock(paths state.ProjectPaths) (state.LockState, model.LockInfo, error)
    InspectRunLock classifies the project's run lock as found, and removes a
    stale local lock as removeStaleLock does.

func InterruptedRunDetail(paths state.ProjectPaths, runID string) (detail string, stillRunning bool)
    InterruptedRunDetail renders the job-count and phase/timestamp clause shared
    by EnsureIdle and reset's interrupted-run messages. The returned string is
    empty when the run has no recorded job directories yet. stillRunning reports
    whether any job appears non-terminal, so callers can add a stronger warning
    before offering to recover.

func MarkCollecting(paths state.ProjectPaths) error
    MarkCollecting updates only the metadata, for idle operations that leave the
    queue file untouched.

func RerunCommand(paths state.ProjectPaths, runID string) string
    RerunCommand returns the command that reruns an interrupted run's failed and
    unfinished jobs once it is recovered. The run took its jobs from the queue
    when it started, so recovery does not bring them back into the queue.

func Revision(paths state.ProjectPaths) (string, error)
    Revision identifies the project's queue and metadata as they are now:
    it changes whenever either file is written, including by a run or an earlier
    edit. A caller that previews an edit passes it back as Guard.IfRevision.

func RunActive(paths state.ProjectPaths, runID string) bool
    RunActive reports whether runID holds the project's run lock. A stale local
    lock is removed as removeStaleLock does.

func SetCommandLocation(render func(state.ProjectPaths) string)
    SetCommandLocation installs how a CLI process renders the location part of
    the commands this package prints (CLI-22).

func ValidateConsistency(paths state.ProjectPaths, inspection Inspection) error
    ValidateConsistency checks that the run lock, metadata, and run directory
    describe the same run.

func WriteIdleQueue(paths state.ProjectPaths, queue model.Queue) error
    WriteIdleQueue saves a queue edited while the project is idle and marks the
    project as collecting. The two files cannot be replaced atomically together,
    so the metadata is written first: marking an idle project as collecting is
    harmless on its own, and a failed queue write then leaves the previous queue
    in place. Callers must hold the state lock and have checked that the project
    is idle.

Types

type CoordinatorAssessment struct {
	State      CoordinatorState      `json:"state"`
	Reason     string                `json:"reason"`
	ObservedAt string                `json:"observed_at"`
	Identity   *model.RunCoordinator `json:"identity,omitempty"`
}
    CoordinatorAssessment describes process ownership, not job liveness or
    permission to unlock. A management completion marker never overrides a
    probe.

func AssessCoordinator(store state.Store, runDir string) (CoordinatorAssessment, error)
    AssessCoordinator reads the durable run context, independently of
    running.lock. Missing legacy identity is unknown; malformed or unreadable
    records are errors.

type CoordinatorState string

const (
	CoordinatorLive    CoordinatorState = "live"
	CoordinatorStopped CoordinatorState = "stopped"
	CoordinatorUnknown CoordinatorState = "unknown"
)
type ExecutionAssessment struct {
	Stopped    int                       `json:"stopped"`
	Active     int                       `json:"active"`
	Unknown    int                       `json:"unknown"`
	Executions []model.RecoveryExecution `json:"executions"`
}

func AssessExecutions(paths state.ProjectPaths, runID string) (ExecutionAssessment, error)
    AssessExecutions reads all relevant attempts, not only attempts that already
    have a command file or a final result. It never changes run or outcome
    files.

type Guard struct {
	// DryRun computes the edit without writing anything.
	DryRun bool
	// IfRevision, when set, refuses the edit unless the project is still at
	// this revision; see Revision.
	IfRevision string
	// Report, when set, receives the edit's outcome once it succeeds.
	Report func(Outcome)
}
    Guard conditions a project edit. The zero Guard applies the edit
    unconditionally.

type Inspection struct {
	State RunState
	// RunID is the active or interrupted run; empty when idle.
	RunID     string
	Lock      state.LockState
	LockRunID string
}
    Inspection is what Inspect found.

func Inspect(paths state.ProjectPaths) (Inspection, error)
    Inspect classifies a project from its lock and metadata, and removes a stale
    local lock as removeStaleLock does. The inspection describes the lock as
    found.

func InspectConsistent(paths state.ProjectPaths) (Inspection, error)
    InspectConsistent inspects a project and rejects lock, metadata, and run
    directory combinations that disagree. The caller holds the state lock;
    a stale lock is removed only after the check passes.

func InspectWithoutCleanup(paths state.ProjectPaths) (Inspection, error)
    InspectWithoutCleanup classifies a project as Inspect does but changes
    nothing: a stale local lock is reported (Lock is LockStale), not removed.
    It is for readers that collect evidence, such as bug-report, where the stale
    lock is itself evidence.

type LastRun struct {
	ID     string
	Status string
	Jobs   int
	Failed int
}
    LastRun describes a project's last run. Status is the run summary's,
    or empty without a readable summary; Jobs and Failed count its results.

type Outcome struct {
	// Revision is the project's revision before the edit.
	Revision string
	// Queue is the queue the edit produced, or nil for an edit of the run
	// history that leaves the queue alone.
	Queue *model.Queue
	// Applied reports that the edit was written; it is false for a dry run.
	Applied bool
	// NewRevision is the project's revision after an applied edit.
	NewRevision string
}
    Outcome describes a guarded edit.

type Overview struct {
	BaseDir string
	Name    string
	Queued  int
	Runs    int
	State   RunState
	LastRun LastRun
}
    Overview is what a project list shows of one project.

func Overviews(baseDir string) ([]Overview, error)
    Overviews lists the projects of baseDir, inspecting each as Inspect does.

type RepairAssessment struct {
	Complete   bool                      `json:"complete"`
	Reason     string                    `json:"reason"`
	Executions []model.RecoveryExecution `json:"executions,omitempty"`
}

type ResetResult struct {
	// Cleared counts the queued jobs removed.
	Cleared int
}
    ResetResult is what Reset did or, for a dry run, would do.

func Reset(paths state.ProjectPaths, guard Guard) (ResetResult, error)
    Reset empties the queue of a project under guard, keeping its defaults and
    run history. A project that does not exist yet is created empty; running or
    interrupted runs are left untouched. `rotari reset` and the MCP reset tools
    use it.

type RunPhase string
    RunPhase is where one run is in its life, as a reader sees it.

const (
	// RunPhaseRunning means the run holds the project's run lock, including
	// before it has written its job snapshot.
	RunPhaseRunning RunPhase = "running"
	// RunPhaseInterrupted means metadata still records the run as active but
	// no live coordinator holds the lock.
	RunPhaseInterrupted RunPhase = "interrupted"
	// RunPhaseFinished means the run is not active and has a valid summary.
	RunPhaseFinished RunPhase = "finished"
	// RunPhaseEnded means the run is not active and has no valid summary,
	// for example because its supervisor exited early.
	RunPhaseEnded RunPhase = "ended"
)
func PhaseFrom(inspection Inspection, runID string, hasSummary bool) RunPhase
    PhaseFrom is RunPhaseOf from facts a caller already read: the project's
    inspection, read before the run's summary as RunPhaseOf reads them,
    and whether the run has a valid summary. A reader of many runs inspects the
    project once.

func RunPhaseOf(paths state.ProjectPaths, runID string) (RunPhase, error)
    RunPhaseOf reports runID's phase from the project's lock and metadata and
    the run's summary. Like Inspect, it writes nothing but the removal of a
    stale lock. The lock is read before the summary, and a run writes its
    summary before it releases the lock, so a run that finishes in between is
    reported as finished.

type RunState int
    RunState is a project's run state, derived only from running.lock and
    meta.json.

const (
	// Idle means no run is active or interrupted; the queue may be edited.
	Idle RunState = iota
	// Running means a live coordinator holds the run lock.
	Running
	// Interrupted means metadata still records an active run but no live
	// coordinator holds the lock.
	Interrupted
)
type RunningError struct {
	Project, Operation string
}
    RunningError rejects an operation because the project's run is active.

func (err *RunningError) Error() string

type UnlockRefusedError struct{ Result UnlockResult }

func (err *UnlockRefusedError) Error() string

func (err *UnlockRefusedError) Unwrap() error

type UnlockResult struct {
	// RunID is the interrupted run recovered; empty when the project had none
	// and Unlock changed nothing.
	RunID string `json:"run_id,omitempty"`
	// Detail is what the run's jobs last reported, for a message.
	Detail string `json:"detail,omitempty"`
	// JobsMayBeRunning reports that some of the run's jobs have not recorded
	// a final status, so they may still be running.
	JobsMayBeRunning bool                  `json:"jobs_may_be_running"`
	ExecutionChecked bool                  `json:"execution_checked"`
	Coordinator      CoordinatorAssessment `json:"coordinator"`
	Allowed          bool                  `json:"allowed"`
	RefusalCode      string                `json:"refusal_code,omitempty"`
	AssumeStopped    bool                  `json:"assume_stopped"`
	Revision         string                `json:"revision"`
	Applied          bool                  `json:"applied"`
	Action           string                `json:"action,omitempty"`
	Repair           RepairAssessment      `json:"repair"`
}
    UnlockResult is what Unlock did or, for a dry run, would do.

func Unlock(paths state.ProjectPaths, runID string, guard Guard, assumeStopped bool) (UnlockResult, error)
    Unlock assesses coordinator and execution evidence outside the state lock,
    then revalidates the recorded state under the lock before recovery.