session

package
v0.32.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package session owns the on-disk layout of a single ICM workflow run. Every artifact, sidecar, and run-state document the orchestrator produces is funneled through a Session value so the directory layout stays uniform across stage modes (plain / loop / fan-out / fan-out + loop).

The package is a leaf: it imports only the standard library plus log/slog and the tiny icmtypes shared-value package. The plugin layer (plugin.go) handles ExpandPath on user input and passes already- absolute paths down to NewSession.

Index

Constants

View Source
const (
	OutcomeRunning   = "running"
	OutcomeCompleted = "completed"
	OutcomeHalted    = "halted"
	OutcomeRejected  = "rejected"
	OutcomeCancelled = "cancelled"
)

Run outcome values written into RunState.Outcome.

Variables

This section is empty.

Functions

func SidecarPath

func SidecarPath(artifactPath string) string

SidecarPath returns the path of the .icm.json metadata sidecar for an artifact at the given path.

Types

type ArtifactMeta

type ArtifactMeta struct {
	StageID           string                     `json:"stage_id"`
	IterationsRun     int                        `json:"iterations_run,omitempty"`
	ConvergenceFailed bool                       `json:"convergence_failed,omitempty"`
	UnmetConditions   []icmtypes.ConditionResult `json:"unmet_conditions,omitempty"`
	ValidatorsPassed  []icmtypes.ConditionResult `json:"validators_passed,omitempty"`
	GroundingHashes   map[string]string          `json:"grounding_hashes,omitempty"`
	ParentArtifacts   []string                   `json:"parent_artifacts,omitempty"`
	Delegate          DelegateMeta               `json:"delegate,omitempty"`
	WrittenAt         time.Time                  `json:"written_at"`
}

ArtifactMeta is the per-artifact sidecar payload written to <artifact>.icm.json beside every artifact. The orchestrator populates it from the run state + the invocation that produced the artifact.

type ConditionResult

type ConditionResult = icmtypes.ConditionResult

ConditionResult is re-exported from icmtypes for callers that already import the session package. Sidecars + state.json reference these in their JSON.

type DelegateMeta

type DelegateMeta struct {
	PostureName    string `json:"posture_name,omitempty"`
	PostureVersion string `json:"posture_version,omitempty"`
	TokensUsed     int    `json:"tokens_used,omitempty"`
	ToolCallsUsed  int    `json:"tool_calls_used,omitempty"`
	ElapsedMS      int64  `json:"elapsed_ms,omitempty"`
}

DelegateMeta captures the budget + posture identity of the sub-agent invocation that produced an artifact. Embedded inside ArtifactMeta.

type ItemState

type ItemState struct {
	ID          string           `json:"id"`
	Index       int              `json:"index"`
	Status      StageStatus      `json:"status"`
	StartedAt   time.Time        `json:"started_at,omitempty"`
	CompletedAt time.Time        `json:"completed_at,omitempty"`
	Error       string           `json:"error,omitempty"`
	Iterations  []IterationState `json:"iterations,omitempty"`
	Path        string           `json:"path,omitempty"`
}

ItemState tracks a single item of a fan-out stage. Iterations is populated when the stage has both loop and fan_out modes composed.

type IterationState

type IterationState struct {
	Index       int                        `json:"index"`
	Status      StageStatus                `json:"status"`
	StartedAt   time.Time                  `json:"started_at,omitempty"`
	CompletedAt time.Time                  `json:"completed_at,omitempty"`
	TurnCount   int                        `json:"turn_count,omitempty"`
	ExitResults []icmtypes.ConditionResult `json:"exit_results,omitempty"`
}

IterationState tracks a single iteration of a looping stage.

type RunMeta

type RunMeta struct {
	RunID          string         `json:"run_id"`
	InstanceID     string         `json:"instance_id"`
	WorkspaceRoot  string         `json:"workspace_root"`
	WorkspaceName  string         `json:"workspace_name"`
	StartedAt      time.Time      `json:"started_at"`
	ConfigSnapshot map[string]any `json:"config_snapshot,omitempty"`
}

RunMeta is the immutable per-run metadata written exactly once at session creation to <runID>/.icm/run.json. Used by operators and downstream tooling to inspect a finished or in-flight run.

type RunState

type RunState struct {
	RunID               string                   `json:"run_id"`
	InstanceID          string                   `json:"instance_id,omitempty"`
	WorkspaceRoot       string                   `json:"workspace_root,omitempty"`
	WorkspaceDocSummary string                   `json:"workspace_doc_summary,omitempty"`
	StartedAt           time.Time                `json:"started_at"`
	UpdatedAt           time.Time                `json:"updated_at"`
	CurrentStage        int                      `json:"current_stage"`
	Outcome             string                   `json:"outcome,omitempty"`
	Stages              []StageState             `json:"stages,omitempty"`
	Verifiers           map[string]VerifierState `json:"verifiers,omitempty"`
}

RunState is the orchestrator's view of a run's progress. Persisted to <session>/.icm/state.json after every state transition. Enables inspection today and (in a future version) resume.

type Session

type Session struct {
	// RunID is the unique identifier for this run; supplied by the
	// caller (the plugin generates these via engine.GenerateID()).
	RunID string

	// RootDir is the absolute path to <dataDir>/<runID>/.
	RootDir string

	// StartedAt is captured at session creation in UTC.
	StartedAt time.Time

	// Announce, when set, is called after every artifact this session writes
	// under the run tree, with the absolute path and whether it already
	// existed. The plugin wires it to SessionWorkspace.AnnounceWrite so a
	// sync backend learns about stage output as it lands rather than at the
	// next turn boundary — an ICM run is long enough that waiting discards
	// completed stages on a crash.
	//
	// A plain func field rather than an engine.SessionWorkspace parameter on
	// NewSession/OpenSession, for two reasons. This package is a pure
	// filesystem-layout library with no engine import, deliberately, and one
	// callback is a smaller price than that dependency. And the constructors
	// have twenty-six call sites across the ICM tests, none of which care
	// about announcements; a nil-by-default field leaves every one of them
	// unchanged and correct.
	Announce func(fullPath string, existed bool)
	// contains filtered or unexported fields
}

Session is a single run of a workflow. It owns a directory under the plugin's per-session data dir and tracks all artifacts the orchestrator produces.

func NewSession

func NewSession(dataDir, runID string, logger *slog.Logger) (*Session, error)

NewSession creates the session root directory and its .icm/ subfolder. dataDir is the plugin's per-session data dir (ctx.DataDir); runID is caller-supplied. The directory is created with 0o755 perms.

func OpenSession

func OpenSession(dataDir, runID string, logger *slog.Logger) (*Session, error)

OpenSession opens an existing session root for read-only inspection. V1 has no resume — this exists so operators (and future tooling) can inspect prior runs without re-creating the root.

func (*Session) AggregatePath

func (s *Session) AggregatePath(stageID, filename string) string

AggregatePath is the downstream-facing artifact for a fan-out stage — always written at the plain stage path regardless of per-item layout.

func (*Session) ArtifactPath

func (s *Session) ArtifactPath(stageID, filename string) string

ArtifactPath returns the path where a plain (non-looping, non-fan-out) stage's artifact will be written. Also used for fan-out aggregates.

func (*Session) ClearStage

func (s *Session) ClearStage(stageID string) error

ClearStage removes <stageDir> in full. Used by capability b (human_gate: end → restart) and capability d (loop.on_exhausted: human_gate → restart) to wipe a stage's artifacts before a re-run. Missing stage dir is not an error.

func (*Session) CopyInitialInputs

func (s *Session) CopyInitialInputs(srcPaths []string) error

CopyInitialInputs copies each provided source path into <session>/00_input/, preserving the basename. Called once at run start by the orchestrator when the operator supplied an explicit input set.

func (*Session) CopyInitialInputsFromDir

func (s *Session) CopyInitialInputsFromDir(workspaceInputsDir string) error

CopyInitialInputsFromDir copies every regular file from the workspace inputs/ directory into <session>/00_input/. Missing source directory is a silent no-op (the run may not need any inputs).

func (*Session) ItemArtifactPath

func (s *Session) ItemArtifactPath(stageID, itemID, filename string) string

ItemArtifactPath returns the artifact path for a single fan-out item in a non-looping fan-out stage.

func (*Session) ItemDir

func (s *Session) ItemDir(stageID, itemID string) string

ItemDir returns the per-item directory for a fan-out stage.

func (*Session) ItemIterationArtifactPath

func (s *Session) ItemIterationArtifactPath(stageID, itemID, filename string, iter int) string

ItemIterationArtifactPath returns the artifact path for a specific iteration of a single fan-out item (fan-out + loop composition).

func (*Session) IterationArtifactPath

func (s *Session) IterationArtifactPath(stageID, filename string, iter int) string

IterationArtifactPath returns the artifact path for a specific iteration of a looping stage.

func (*Session) IterationDir

func (s *Session) IterationDir(stageID string, iter int) string

IterationDir returns the directory for a single iteration of a looping stage. iter is 1-based and zero-padded to two digits in the on-disk name (iter_01, iter_02, ...); ResolveLogicalRef handles iter_NN directories with any digit width.

func (*Session) LoadState

func (s *Session) LoadState() (*RunState, error)

LoadState reads state.json if present. Returns a zero-value RunState seeded with the session's RunID and StartedAt (no error) when the file does not exist yet.

func (*Session) ResolveLogicalRef

func (s *Session) ResolveLogicalRef(ref string) (string, error)

ResolveLogicalRef turns an inputs.artifacts entry of the form "<stage_id>/<filename>" into an absolute path under this session. For looping stages the latest iteration wins; for fan-out stages the aggregate wins (which is the same as the plain stage path).

Iteration directories are parsed as integers and sorted numerically: iter_9 < iter_10 < iter_99 < iter_100. (Naive string-sort breaks past iter_99; that's a known handoff bug this implementation avoids.)

func (*Session) SaveState

func (s *Session) SaveState(st *RunState) error

SaveState writes the RunState atomically under stateMu so fan-out goroutines that each transition a different stage/item still produce a coherent on-disk document. UpdatedAt is stamped here.

func (*Session) StageDir

func (s *Session) StageDir(stageID string) string

StageDir returns the per-stage directory under the session, regardless of stage mode. The orchestrator creates this lazily on first write.

func (*Session) WriteArtifact

func (s *Session) WriteArtifact(path string, content []byte) error

WriteArtifact ensures the parent directory exists and writes content atomically via temp file + rename. The orchestrator funnels every artifact write through this so the disk layout is uniform.

Object-store disposition: emit. Because every artifact write already funnels through here, one announcement covers sidecars, run metadata and stage output alike. The temp file is deliberately not announced: it is an implementation detail of atomicity that exists for one syscall and is gone by the time anyone could act on the event, and announcing it would tell a sync backend to upload a path that no longer exists.

func (*Session) WriteRunMeta

func (s *Session) WriteRunMeta(meta RunMeta) error

WriteRunMeta writes <runID>/.icm/run.json. Intended to be called once at session creation by the plugin; existing run.json content is overwritten (the file is atomic at the filesystem level).

func (*Session) WriteSidecar

func (s *Session) WriteSidecar(artifactPath string, meta ArtifactMeta) error

WriteSidecar writes the .icm.json metadata file next to an artifact. WrittenAt is stamped here if the caller left it zero.

type StageState

type StageState struct {
	ID           string           `json:"id"`
	Status       StageStatus      `json:"status"`
	StartedAt    time.Time        `json:"started_at,omitempty"`
	CompletedAt  time.Time        `json:"completed_at,omitempty"`
	TurnCount    int              `json:"turn_count,omitempty"`
	RestartCount int              `json:"restart_count,omitempty"`
	Iterations   []IterationState `json:"iterations,omitempty"`
	Items        []ItemState      `json:"items,omitempty"`
}

StageState tracks the progress of a single stage.

type StageStatus

type StageStatus string

StageStatus is the lifecycle state of a single stage in a RunState.

const (
	StageStatusPending     StageStatus = "pending"
	StageStatusRunning     StageStatus = "running"
	StageStatusGatePending StageStatus = "gate_pending"
	StageStatusDone        StageStatus = "done"
	StageStatusFailed      StageStatus = "failed"
)

Stage lifecycle values written into state.json.

type VerifierState

type VerifierState struct {
	Status      StageStatus `json:"status"`
	StartedAt   time.Time   `json:"started_at,omitempty"`
	CompletedAt time.Time   `json:"completed_at,omitempty"`
	Verdict     string      `json:"verdict,omitempty"`
	Feedback    string      `json:"feedback,omitempty"`
}

VerifierState tracks a single verifier outcome for the run.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL