Documentation
¶
Overview ¶
Package workitem — scheduling: claim / heartbeat / release / start / retry / repair. M2.2 (实施计划 §M2.2, 方案 §6.4 + §15.3).
Lease files live at .devsys/scheduling/<workitem-id>.yaml, written atomically alongside the workitem YAML and the audit event inside ONE storage.Write. ReconcileM2 inspects the scheduling/ directory directly.
Fencing tokens: 16 random bytes hex-encoded (32 chars). Generated by Claim; never reused across claims. Every lease-bearing call (Heartbeat / Release / Update for a leased workitem / Run update against a leased workitem) MUST present the same Owner+Token currently recorded on the lease. Mismatches return ErrLeaseTokenMismatch.
Status semantics enforced here:
- Claim: ready / retry_queued / released-claimed (scheduler re-claim) → in_progress ; writes lease + run + one combined event.
- Heartbeat: extends lease; status untouched.
- Release: removes lease; sets scheduling_state according to the workitem's terminal position so the next Claim sees the correct slot. Never demotes workitem.Status.
- Start: blocked→in_progress or retry_queued→running. Creates a Run if absent.
- QueueRetry: in_progress / failed → retry_queued with deterministic next_attempt_at.
- Repair: ApplyRepair is the only downward-completion path.
Package workitem — small shared helpers used by claim.go and state.go. Kept here so the package owns the imports (os, sort) without pulling them into the public API surface.
Record propagation on completion (实施计划 M3.3, 方案 §4.7).
When a work item enters done, its Decision and Finding records — those whose RelatedWorkItems name it — are propagated as references (decision://<id>, finding://<id>) to the parent and the direct siblings. Propagation runs inside the completion transaction: targets are read and rewritten under the same optimistic guard, their status is untouched, and a target that already carries every reference is skipped, so repeated completions stay idempotent. No links means no broadcast.
Workflow instance operations (实施计划 M3.6, 方案 §5.3). The instance state lives in the work item's `workflow` field and the step history is the event stream; every operation rewrites the field and appends its event in one storage transaction.
These operations never touch the work item status, the scheduling state, lease files or runs: advancing a step is bookkeeping of the workflow instance, not of execution. Step declarations that require a work item status are enforced as requirements, never as implicit transitions.
Package workitem persists WorkItem records as one file per task under .devsys/workitems/<id>.yaml (方案 §14.2, 实施计划 M1.2). IDs are <PREFIX>-<N>; sequence numbers are re-derived from the directory on every create, and the create itself is a CAS (ExpectAbsent) so a concurrent create of the same ID has exactly one winner.
Index ¶
- Constants
- Variables
- func ValidID(id string) bool
- type ClaimOptions
- type ClaimResult
- type HeartbeatOptions
- type LeaseRef
- type ReleaseOptions
- type RetryOptions
- type RetryResult
- type StartOptions
- type StartResult
- type Store
- func (s *Store) ApplyRepair(ctx context.Context, id string, req TransitionRequest, expected []byte) error
- func (s *Store) Claim(ctx context.Context, id string, opts ClaimOptions) (ClaimResult, error)
- func (s *Store) Create(ctx context.Context, wi *domain.WorkItem, prefix string) (string, error)
- func (s *Store) FenceRunUpdate(ctx context.Context, workitemID, owner, token string, mutate func(*domain.Run), ...) error
- func (s *Store) Get(ctx context.Context, id string) (*domain.WorkItem, error)
- func (s *Store) Heartbeat(ctx context.Context, id string, opts HeartbeatOptions) error
- func (s *Store) LeaseInspection(ctx context.Context, id string) (domain.SchedulingLease, error)
- func (s *Store) LeaseToken(ctx context.Context, id string) (string, error)
- func (s *Store) List(ctx context.Context) ([]*domain.WorkItem, error)
- func (s *Store) ListLeases(ctx context.Context) ([]LeaseRef, error)
- func (s *Store) QueueRetry(ctx context.Context, id string, opts RetryOptions) (RetryResult, error)
- func (s *Store) ReadSnapshot(ctx context.Context, id string) (*domain.WorkItem, []byte, error)
- func (s *Store) Release(ctx context.Context, id string, opts ReleaseOptions) error
- func (s *Store) Start(ctx context.Context, id string, opts StartOptions) (StartResult, error)
- func (s *Store) Transition(ctx context.Context, id string, req TransitionRequest, expected []byte) (*domain.WorkItem, error)
- func (s *Store) Update(ctx context.Context, wi *domain.WorkItem, expected []byte) error
- func (s *Store) UpdateClaimed(ctx context.Context, id, owner, token string, mutate func(*domain.WorkItem), ...) error
- func (s *Store) WorkflowCancel(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
- func (s *Store) WorkflowNext(ctx context.Context, id string, policy *workflow.Policy) (*domain.WorkItem, []workflow.StepCandidate, error)
- func (s *Store) WorkflowPause(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
- func (s *Store) WorkflowResume(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
- func (s *Store) WorkflowStart(ctx context.Context, id string, opts WorkflowStartOptions) (*domain.WorkItem, error)
- func (s *Store) WorkflowStepComplete(ctx context.Context, id string, opts WorkflowStepOptions) (*domain.WorkItem, error)
- type TransitionRequest
- type WorkflowSignalOptions
- type WorkflowStartOptions
- type WorkflowStepError
- type WorkflowStepOptions
Constants ¶
const DefaultLeaseDuration = 5 * time.Minute
DefaultLeaseDuration is the time a Claim writes into lease_until if the caller did not set ClaimOptions.LeaseDuration. Reconcile treats anything past lease_until as expired.
const SchedulingDirName = "scheduling"
SchedulingDirName mirrors storage.SchedulingDirName; both sides agree on "scheduling".
Variables ¶
var ( ErrNotInitialized = storage.ErrNotInitialized ErrNotFound = errors.New("workitem not found") ErrConflict = errors.New("workitem changed concurrently") ErrBadPrefix = errors.New("invalid workitem prefix") // ErrBadID reports a malformed work item id before any path is built, so a // caller sees "invalid workitem id" instead of the storage layer's // "unsafe managed path" fallback. ErrBadID = errors.New("invalid workitem id") )
Errors reported to callers. ErrIDTaken means the target file appeared between the scan and the write; Create retries with a new number.
var ErrAlreadyClaimed = errors.New("workitem: already claimed")
var ErrInvalidInput = errors.New("workitem: invalid input")
var ErrLeaseExpired = errors.New("workitem: lease expired")
var ErrLeaseTokenMismatch = errors.New("workitem: lease token mismatch")
var ErrNotClaimed = errors.New("workitem: no active claim")
var SchedulingStateMapping = map[string]string{ domain.StatusReady: domain.SchedulingUnclaimed, domain.StatusInProgress: domain.SchedulingUnclaimed, domain.StatusReview: domain.SchedulingReleased, domain.StatusVerification: domain.SchedulingReleased, domain.StatusDone: domain.SchedulingReleased, domain.StatusCancelled: domain.SchedulingReleased, domain.StatusBlocked: domain.SchedulingUnclaimed, domain.StatusBacklog: domain.SchedulingUnclaimed, domain.StatusDraft: domain.SchedulingUnclaimed, }
SchedulingStateMapping is the canonical (§6.4) table the runtime uses to derive SchedulingState when a lease is cleared. Keep it small and explicit so the audit trail reflects intent.
Functions ¶
Types ¶
type ClaimOptions ¶
type ClaimOptions struct {
Owner string // required; identity of the claimer
Token string // IGNORED — every claim gets a fresh token.
Expected []byte
HeadSHA string
LeaseDuration time.Duration
Agent domain.RunAgent
WorkflowID string
Actor string
Reason string
Now time.Time
}
ClaimOptions is the input to Claim.
type ClaimResult ¶
type ClaimResult struct {
RunID string
Token string
Lease domain.SchedulingLease
Status string
}
ClaimResult is the output of a successful Claim.
type HeartbeatOptions ¶
type HeartbeatOptions struct {
Owner string
Token string
Expected []byte
ExtendBy time.Duration
Actor string
Reason string
Now time.Time
}
HeartbeatOptions is the input to Heartbeat.
type LeaseRef ¶
LeaseRef is the read-only pointer reconcile consumes. Path is the managed path relative to .devsys (slash-separated).
type ReleaseOptions ¶
type ReleaseOptions struct {
Owner string
Token string
Expected []byte
ForExpired bool // require verified lease_until < now; skip owner/token
ForOrphan bool // require lease exists AND its run file is missing
// ForCompleted releases the claim whose bound run just succeeded; the
// symmetric counterpart of refuseAttempt's release on the failed path
// (#342). ForRefused is that failure-path release, used when a
// completion is refused and the item goes to human review. BoundRunID
// must equal the lease's run and the run record must carry the matching
// outcome proof, so neither can kill an active claim. Owner/token are
// not required; the run record is the proof.
ForCompleted bool
ForRefused bool
BoundRunID string
Actor string
Reason string
Now time.Time
}
ReleaseOptions is the input to Release.
type RetryOptions ¶
type RetryOptions struct {
Owner string
Token string
Expected []byte
BaseDelay time.Duration // default 1 min; deterministic scaling on attempt
// Delay overrides the built-in doubling when the caller computed the
// backoff itself (方案 §15.4: reproducible jitter, policy ceiling).
Delay time.Duration
Attempt int // next attempt number; must be > current lease attempt
Actor string
Reason string
Now time.Time
}
RetryOptions re-queues an in_progress workitem for another attempt. Expected is required; owner/token must match the active lease.
type RetryResult ¶
RetryResult records the deterministic next_attempt_at used.
type StartOptions ¶
type StartOptions struct {
Owner string
Token string
Expected []byte
HeadSHA string
LeaseDuration time.Duration
Agent domain.RunAgent
WorkflowID string
Actor string
Reason string
Now time.Time
}
StartOptions transitions a blocked / retry_queued workitem into in_progress and stages a new Run if none exists. Expected is required.
type StartResult ¶
type StartResult struct {
RunID string
Token string
Lease domain.SchedulingLease
}
StartResult is the output of Start.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store binds WorkItem operations to a project root.
func New ¶
New binds the workitem layer to a project root (the directory containing .devsys, which must exist).
func (*Store) ApplyRepair ¶
func (*Store) Claim ¶
func (s *Store) Claim(ctx context.Context, id string, opts ClaimOptions) (ClaimResult, error)
Claim atomically:
- Creates a fresh run record via run.CreateTx inside the same Write.
- Writes .devsys/scheduling/<id>.yaml with a new random token + lease_until = now + LeaseDuration.
- Writes .devsys/workitems/<id>.yaml with status=in_progress, scheduling_state=claimed, lease_owner, lease_token, lease_* fields.
- Appends ONE combined "claimed" event (no second append_jsonl to the same shard in one tx).
Preconditions:
- Status must be ready, retry_queued or released (re-claim after review/verification handback). Other current statuses return a *domain.TransitionError carrying the allowed list.
- If a lease file already exists, return ErrAlreadyClaimed.
Concurrency: the lease file is created with ExpectAbsent; two Claims on the same work item see exactly one winner. The loser sees ErrAlreadyClaimed (storage.ErrConflict is mapped).
func (*Store) Create ¶
Create assigns the next free sequence number for prefix, writes the record and returns its ID. Inside the same storage transaction the number is derived from the directory and the file is guarded with ExpectAbsent, so two concurrent creates never share an ID: the loser retries and lands on the next free number.
func (*Store) FenceRunUpdate ¶
func (s *Store) FenceRunUpdate(ctx context.Context, workitemID, owner, token string, mutate func(*domain.Run), expected []byte) error
FenceRunUpdate guards run mutations on a leased workitem: run updates must present the current lease owner/token. The caller passes the pre-read run bytes; we re-validate the lease under the same transaction to avoid stale snapshots.
func (*Store) Heartbeat ¶
Heartbeat extends the lease on a work item whose lease is still active and still owned by the caller. Mismatching owner/token or an expired lease returns ErrLeaseTokenMismatch / ErrLeaseExpired.
func (*Store) LeaseInspection ¶
LeaseInspection returns the parsed lease for the work item, or ErrNotClaimed when no lease file is present.
func (*Store) LeaseToken ¶
LeaseToken returns the current fencing token for id from the local sidecar. It exists for local operators — the dispatch tick, `devsys recover` — that must act on a claim without its holder presenting the token. The token still never enters the committed state tree (#342).
func (*Store) List ¶
List decodes every work item, ordered by numeric sequence per prefix — a stable order that does not depend on directory enumeration or mtime.
func (*Store) ListLeases ¶
ListLeases enumerates every lease file under .devsys/scheduling/. It is read-only; reconcile may call it directly.
func (*Store) QueueRetry ¶
func (s *Store) QueueRetry(ctx context.Context, id string, opts RetryOptions) (RetryResult, error)
QueueRetry moves an in_progress work item to retry_queued with a deterministic next_attempt_at = now + base * 2^(attempt-1) capped at 1 hour. Owner/token must match the current lease.
func (*Store) ReadSnapshot ¶
ReadSnapshot returns a work item together with the raw bytes it was decoded from, for read-modify-write cycles that pass the bytes back into Update as the optimistic guard.
func (*Store) Release ¶
Release removes the lease and adjusts the scheduling_state to match the workitem's logical position. ForExpired=true requires verified lease_until < now; ForOrphan=true requires the referenced Run file to be missing. Either flag bypasses owner/token. Status is never demoted.
func (*Store) Start ¶
func (s *Store) Start(ctx context.Context, id string, opts StartOptions) (StartResult, error)
Start transitions a blocked or retry_queued work item into in_progress. Equivalent to a fresh Claim but enforces the source status and reuses the existing lease file when present (resume after pause).
func (*Store) Transition ¶
func (*Store) Update ¶
Update replaces a work item only while the file still matches the bytes the caller read; a concurrent edit surfaces as storage.ErrConflict instead of being overwritten (乐观并发, 方案 §15.2). expected is the raw file content the caller's read snapshot was decoded from.
Update refuses to mutate the Status field: use Transition or ApplyRepair for status changes (§6). Other fields are written as supplied.
func (*Store) UpdateClaimed ¶
func (s *Store) UpdateClaimed(ctx context.Context, id, owner, token string, mutate func(*domain.WorkItem), expected []byte) error
UpdateClaimed updates a leased workitem's metadata (title, description, etc.) while requiring the caller to present the current lease owner/token. The status field stays fenced via Update's check; only non-status fields are mutable through this entry point.
func (*Store) WorkflowCancel ¶
func (s *Store) WorkflowCancel(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
WorkflowCancel ends the instance with the cancelled sentinel.
func (*Store) WorkflowNext ¶
func (s *Store) WorkflowNext(ctx context.Context, id string, policy *workflow.Policy) (*domain.WorkItem, []workflow.StepCandidate, error)
WorkflowNext reports the candidates out of the current step. It only reads.
func (*Store) WorkflowPause ¶
func (s *Store) WorkflowPause(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
WorkflowPause holds the instance without touching the work item status.
func (*Store) WorkflowResume ¶
func (s *Store) WorkflowResume(ctx context.Context, id string, opts WorkflowSignalOptions) (*domain.WorkItem, error)
WorkflowResume releases a paused instance.
func (*Store) WorkflowStart ¶
func (s *Store) WorkflowStart(ctx context.Context, id string, opts WorkflowStartOptions) (*domain.WorkItem, error)
WorkflowStart creates the instance at the policy's first step. The first step's declared status (if any) must already match the work item status: instance operations never move the work item status themselves.
func (*Store) WorkflowStepComplete ¶
func (s *Store) WorkflowStepComplete(ctx context.Context, id string, opts WorkflowStepOptions) (*domain.WorkItem, error)
WorkflowStepComplete advances the instance one step: the first satisfied candidate in declaration order, or the explicitly requested target when it is a declared transition whose condition currently holds.
type TransitionRequest ¶
type TransitionRequest struct {
TargetStatus string
Actor string
Reason string
RunID string
Token string
PreviousStatus string
Confirmation []byte
AllowRepair bool
Now time.Time
Guard func(*storage.Tx) ([]*domain.Event, error)
}
TransitionRequest carries mutation authority; repair additionally requires a confirmed evidence digest and a guard revalidated inside the same transaction. A normal transition may also carry a Guard (e.g. to consume the approval a gate relied on) — it runs inside the transition transaction before commit, and the events it returns are appended in the same batch as the status event (one append per JSONL shard).
type WorkflowSignalOptions ¶
type WorkflowSignalOptions struct {
Actor string
Reason string
Owner string
Token string
Expected []byte
Now time.Time
}
WorkflowSignalOptions is the input to pause / resume / cancel.
type WorkflowStartOptions ¶
type WorkflowStartOptions struct {
Policy *workflow.Policy
Actor string
Reason string
// Owner and Token must match the active lease when the work item is
// claimed; instance writes are otherwise refused (same fencing contract
// as UpdateClaimed).
Owner string
Token string
Expected []byte
Now time.Time
}
WorkflowStartOptions is the input to WorkflowStart.
type WorkflowStepError ¶
type WorkflowStepError struct {
Step string
Reason string
Allowed []workflow.StepCandidate
}
WorkflowStepError reports a refused instance operation together with the candidates that were available from the current step.
func (*WorkflowStepError) Error ¶
func (e *WorkflowStepError) Error() string