Documentation
¶
Overview ¶
Package job is the async job state machine: it accepts a JobRequest, resolves the agent+cwd, runs it on a runner in a background goroutine, streams logs to the store and tracks status/timeout/cancel. See plan §6.2 and §9 (P4).
Index ¶
- Constants
- Variables
- func AgentEventScope(agentKey string) string
- func AllowAllWakeups(JobResult) bool
- func BackoffForPolicy(p *RetryPolicy, attempt int) int
- func CaptureSessionIDBytes(b []byte, reSrc string) string
- func CheckBudget(b *Budget) error
- func CheckFromSession(id string) error
- func CheckModel(m string) error
- func CheckProjectKey(key string) error
- func DiffFiles(diff string) []string
- func EffectiveDeliveryMode(cfg *config.Config, req JobRequest) string
- func EstimateJobCost(cfg *config.Config, res JobResult) float64
- func ExtractPlanTodosBlock(text string) (string, bool)
- func FormatTokens(n int64) string
- func FormatUsage(u *Usage) string
- func IsFinished(status string) bool
- func IsRemoteRunner(cfg *config.Config, name string) bool
- func IsRemoteSource(source string) bool
- func IsTerminal(status string) bool
- func JobTokenLooksLikeCredential(token string) bool
- func LoadEnvFilesMap(paths []string, cfg *config.Config, proj config.ProjectConfig) (map[string]string, error)
- func MCPFormatOf(ac config.AgentConfig) string
- func MCPNamesFromWire(in []wsproto.MCPSpec) []string
- func MCPSpecsFromWire(in []wsproto.MCPSpec) map[string]config.MCPServerConfig
- func MaxAttemptsPolicy(p *RetryPolicy) int
- func OutOfScope(files, scope []string) []string
- func ParseFindings(report string) []string
- func ParseKnowledge(report string) []string
- func ParseMentions(body string) []string
- func ParseReportSection(report string, titles ...string) []string
- func PlanEventScope(planID string) string
- func RandomSuffix() string
- func RetryMaxAttempts(rec jobstore.RetryRecord) int
- func RetryableExitPolicy(p *RetryPolicy, exitCode int) bool
- func ScopeMatch(glob, file string) bool
- func SessionCaptureBy(reSrc string) string
- func SkillDest(name, rel string) string
- func SplitInjectedRules(prompt string) (body, injected string)
- func StatusLabelZH(status string) string
- func SyncWaitDuration(sec int) time.Duration
- func TitleFromRequestJSON(s string) string
- func Unstarted(status string) bool
- func WakeupEventTypes() []string
- func WakeupNextRun(w jobstore.WakeupRecord, afterUnix int64) (int64, error)
- func WrapUpText(reason string) string
- type AcceptMemoryCandidateInput
- type AdmissionPermit
- type AdoptBackend
- type AdoptedJob
- func (a *AdoptedJob) Finish(exitCode int, err error)
- func (a *AdoptedJob) Offsets() (stdoutOff, stderrOff int64)
- func (a *AdoptedJob) OnDisconnect(err error)
- func (a *AdoptedJob) OnInteraction(action string, raw json.RawMessage)
- func (a *AdoptedJob) OnJobEvent(eventType string, detail map[string]any)
- func (a *AdoptedJob) OnOutcome(o runner.Outcome)
- func (a *AdoptedJob) OnSessionStatus(status, sessionStatus string, turnNo int, idleDeadlineAt int64)
- func (a *AdoptedJob) Resume()
- func (a *AdoptedJob) Suspend(reason string) (int64, int64)
- func (a *AdoptedJob) WriteLog(stream string, _ int, text string)
- type AgentBrief
- type ArtifactItem
- type ArtifactManifest
- type BackfillOptions
- type BackfillResult
- type Budget
- type CollectLimits
- type CollectedPull
- type CommentDispatch
- type Commit
- type DecisionTrial
- type DeliverOptions
- type DeliveryPreview
- type DeliveryResult
- type EventTap
- type FallbackState
- type HoldState
- type ImportTodo
- type Interaction
- type InteractionInput
- type InteractionOption
- type InteractionToolCall
- type IssueLinker
- type JobEndedHook
- type JobEventObserver
- type JobRequest
- type JobResult
- type JobTerminalHook
- type JobTokenLookup
- type LeaderStatus
- type ListOpts
- type MemoryCandidateDecision
- type MergeOptions
- type MergeResult
- type MessengerMeta
- type MetricsSink
- type PlanTodoSpec
- type RebuildOverrides
- type ResumeOptions
- type RetryPolicy
- type ReviewOutcome
- type RuleInfo
- type RuleLibrary
- type RuleRef
- type Service
- func (s *Service) AcceptJob(jobID, by, note string) (ReviewOutcome, error)
- func (s *Service) AcceptJobWithoutDelivery(jobID, by, note string) (ReviewOutcome, error)
- func (s *Service) AcceptMemoryCandidate(id int64, in AcceptMemoryCandidateInput, by string) (MemoryCandidateDecision, error)
- func (s *Service) AddEventObserver(fn JobEventObserver)
- func (s *Service) AdoptionWake() <-chan struct{}
- func (s *Service) AnswerInteraction(jobID, interactionID, answer string) (Interaction, error)
- func (s *Service) AnswerInteractionAuto(jobID, interactionID, answer, policy string) (Interaction, error)
- func (s *Service) AnswerInteractionByHuman(jobID, interactionID, answer, callerID string) (Interaction, error)
- func (s *Service) AnswerInteractionByPush(jobID, interactionID, answer string) (Interaction, error)
- func (s *Service) ApproveJob(jobID, by, note string) (JobResult, error)
- func (s *Service) AttachJobToPlan(jobID, planID string) (bool, error)
- func (s *Service) BackfillMetrics(opt BackfillOptions) (BackfillResult, error)
- func (s *Service) BeginUpgradeWork() (*AdmissionPermit, error)
- func (s *Service) CallerRate(callerID string) (rps float64, burst int)
- func (s *Service) Cancel(id string) error
- func (s *Service) CancelLeaderWakesForPlan(planID, by string) int
- func (s *Service) CancelRetry(id string) error
- func (s *Service) CloseUpgradeAdmission(ctx context.Context, upgradeID string) error
- func (s *Service) Comment(scope, scopeID, author, authorKind, body string) (jobstore.Comment, []CommentDispatch, error)
- func (s *Service) CommentAsJob(scope, scopeID, asJob, body string) (jobstore.Comment, []CommentDispatch, error)
- func (s *Service) CommentAsJobWouldDispatch(scope, scopeID, asJob, body string) ([]string, error)
- func (s *Service) CommentWouldDispatch(scope, scopeID, author, authorKind, body string) ([]string, error)
- func (s *Service) Config() *config.Config
- func (s *Service) CountRecoveringJobs() (int, error)
- func (s *Service) CountUpdatePaused() (int, error)
- func (s *Service) CountUpgradeRestartBlockers(excludedIDs []string) (int, error)
- func (s *Service) CreateInteraction(jobID string, in InteractionInput) (Interaction, error)
- func (s *Service) CreateWakeup(spec WakeupSpec, by string, gate WakeupGate) (jobstore.WakeupRecord, error)
- func (s *Service) DeleteJob(id, by string) error
- func (s *Service) DeleteWakeup(id, by string, gate WakeupGate) error
- func (s *Service) Deliver(jobID string, opts DeliverOptions) (DeliveryResult, error)
- func (s *Service) DeliverDue(ctx context.Context) int
- func (s *Service) DeliveryModeOf(snap JobResult) string
- func (s *Service) DispatchTodo(todoID, by string) (TodoDispatch, error)
- func (s *Service) Drain(ctx context.Context) error
- func (s *Service) EndSession(id string) error
- func (s *Service) ExpireHold(jobID string) (JobResult, error)
- func (s *Service) ExpireWakeup(id string)
- func (s *Service) FailRecoveringJobs(reason string) (int, error)
- func (s *Service) FireWakeup(id, reason string)
- func (s *Service) FireWakeupWithPermit(permit *AdmissionPermit, id, reason string)
- func (s *Service) Get(id string) (JobResult, bool)
- func (s *Service) GetArtifactManifest(id string) (ArtifactManifest, bool)
- func (s *Service) GetInteractions(jobID string) ([]Interaction, error)
- func (s *Service) GetPersisted(_ string, id string) (JobResult, bool)
- func (s *Service) GetPersistedInteractions(_ string, jobID string) ([]Interaction, error)
- func (s *Service) GetRetry(id string) (jobstore.RetryRecord, bool, error)
- func (s *Service) GetWakeup(id string) (jobstore.WakeupRecord, bool, error)
- func (s *Service) GoBackground(fn func()) bool
- func (s *Service) IsLeaderJob(jobID string) bool
- func (s *Service) LeaderStatus(planID string) LeaderStatus
- func (s *Service) ListComments(scope, scopeID string) ([]jobstore.Comment, error)
- func (s *Service) ListDeliveriesByJob(jobID string) ([]jobstore.Delivery, error)
- func (s *Service) ListJobEvents(jobID string, sinceSeq int64) ([]jobstore.JobEvent, error)
- func (s *Service) ListJobs(opts ListOpts) ([]JobResult, error)
- func (s *Service) ListMemoryCandidates(f jobstore.MemoryCandidateFilter) ([]jobstore.MemoryCandidate, error)
- func (s *Service) ListPendingInteractions() ([]Interaction, error)
- func (s *Service) ListRetries(jobID string) ([]jobstore.RetryRecord, error)
- func (s *Service) ListScopedEventsDesc(scope string, before int64, limit int) ([]jobstore.JobEvent, error)
- func (s *Service) ListTemplates(projectKey string) ([]template.Info, error)
- func (s *Service) ListUpdatePaused(limit int) ([]JobResult, error)
- func (s *Service) ListUpgradeRestartBlockers(excludedIDs []string, limit int) ([]UpgradeRestartBlocker, error)
- func (s *Service) ListWakeups(jobID string) ([]jobstore.WakeupRecord, error)
- func (s *Service) LookupJobToken(token string) (JobTokenLookup, bool)
- func (s *Service) MarkInteractionNeedsHuman(jobID, interactionID string) error
- func (s *Service) MarkInteractionNeedsHumanBy(jobID, interactionID, callerID string) error
- func (s *Service) MaybeDispatchTodo(todoID, by string) (TodoDispatch, error)
- func (s *Service) MergeWorktree(jobID string, opts MergeOptions) (MergeResult, error)
- func (s *Service) Meta() *jobstore.Store
- func (s *Service) Metrics() MetricsSink
- func (s *Service) NotifyEvent(eventType, projectKey string, msg notify.Message) int
- func (s *Service) NotifySessionAttention(sessionID, projectKey, title, detail string)
- func (s *Service) NotifySessionHandedOff(sessionID, projectKey, title, jobID string)
- func (s *Service) NotifySessionNudgePaused(sessionID, projectKey, title, nudgeID, reason string)
- func (s *Service) NotifySessionTakeoverReleased(sessionID, projectKey, title, jobID, reason string)
- func (s *Service) NotifySessionWaiting(sessionID, projectKey, title, lastMessage string, turn int64)
- func (s *Service) NotifyUpdateAvailable(current, latest, description string) int
- func (s *Service) NotifyWork(eventType, projectKey, title, text, link, linkLabel string) int
- func (s *Service) Now() time.Time
- func (s *Service) OnJobEnded(fn JobEndedHook)
- func (s *Service) OnTerminal(fn JobTerminalHook)
- func (s *Service) OpenUpgradeAdmission(upgradeID string) error
- func (s *Service) PausePlan(planID string) (jobstore.Plan, error)
- func (s *Service) PauseStartsForUpdate(applyID string)
- func (s *Service) PlanTodoChanged(todoID, status, by string)
- func (s *Service) PreviewDelivery(jobID string, opts DeliverOptions) (DeliveryPreview, error)
- func (s *Service) PreviewTemplate(projectKey, name string, vars map[string]string) (template.Preview, error)
- func (s *Service) Prune() (int, error)
- func (s *Service) Ran(id string) (bool, error)
- func (s *Service) RebuildJob(jobID string, ov RebuildOverrides, callerID, clientIP string) (JobResult, error)
- func (s *Service) ReconcileAdoption(workerID, instanceID string, inflight []WorkerInflightJob, ...) (map[string]*AdoptedJob, []string)
- func (s *Service) ReconcileOrphanInteractions() (int, error)
- func (s *Service) ReconcileOrphanJobs() (int, error)
- func (s *Service) ReconcileSessionState(workerID string, inflight []WorkerInflightJob)
- func (s *Service) RecordJobEvent(jobID, eventType string, detail map[string]any)
- func (s *Service) RecordScopedEvent(scope, eventType, projectKey string, detail map[string]any)
- func (s *Service) RedactedRequest(id string) (JobRequest, bool, bool, error)
- func (s *Service) RejectJob(jobID, by, note string, resume bool) (ReviewOutcome, error)
- func (s *Service) RejectMemoryCandidate(id int64, by string) (jobstore.MemoryCandidate, error)
- func (s *Service) Reload(newCfg *config.Config)
- func (s *Service) ReloadRunners(runners map[string]runner.Runner)
- func (s *Service) RemoveWorktree(jobID string, force, deleteBranch bool) (WorktreeStatus, error)
- func (s *Service) ResumeJob(jobID, prompt, runner, callerID string) (JobResult, error)
- func (s *Service) ResumeJobWith(jobID, prompt, runner, callerID string, opts ResumeOptions) (JobResult, error)
- func (s *Service) ResumePlan(planID, by string) (jobstore.Plan, error)
- func (s *Service) ResumeStartsForUpdate() (int, error)
- func (s *Service) RunPlan(planID, by string) (jobstore.Plan, error)
- func (s *Service) SaySession(id, message string) error
- func (s *Service) SetEventObserver(fn JobEventObserver)
- func (s *Service) SetEventTap(fn EventTap)
- func (s *Service) SetIssueLinker(linker IssueLinker)
- func (s *Service) SetMetrics(m MetricsSink)
- func (s *Service) SetRuleLibrary(l RuleLibrary)
- func (s *Service) SetSessionID(id, sessionID string)
- func (s *Service) SetSkillLibrary(l SkillLibrary)
- func (s *Service) SetTitle(id, title, operator string) (JobResult, error)
- func (s *Service) SetUncommittedDecisionOnly(enabled bool)
- func (s *Service) SetWakeupEnabled(id, by string, enabled bool, gate WakeupGate) (jobstore.WakeupRecord, error)
- func (s *Service) SetWorkflow(w WorkflowAdvancer)
- func (s *Service) SetXferBridge(b XferBridge)
- func (s *Service) Shutdown(ctx context.Context) error
- func (s *Service) ShutdownResidentSessions(ctx context.Context) error
- func (s *Service) Stats() ServiceStats
- func (s *Service) Submit(req JobRequest) (JobResult, error)
- func (s *Service) SubmitSync(req JobRequest, sync bool) (out JobResult, async bool, err error)
- func (s *Service) SubmitWithPermit(permit *AdmissionPermit, req JobRequest) (JobResult, error)
- func (s *Service) SweepDueLeaderWakes(now int64) (int, error)
- func (s *Service) SweepDueRetries(now int64, limit int, lease int64) (started, failed int, err error)
- func (s *Service) SweepExpiredHolds(now int64) (int, error)
- func (s *Service) TailLog(id string, stream store.Stream, maxBytes int64) ([]byte, error)
- func (s *Service) UpdatePauseOwner() string
- func (s *Service) UpgradeAdmissionOwner() string
- func (s *Service) UpgradeIdleSessionIDs() ([]string, error)
- func (s *Service) Validate(cfg *config.Config, req JobRequest, remote bool) (config.ProjectConfig, error)
- func (s *Service) ValidateUpgradeSource(jobID string, initiatorPID int) error
- func (s *Service) Wait(id string) (JobResult, bool)
- func (s *Service) WaitAnswer(ctx context.Context, jobID, interactionID string) (Interaction, error)
- func (s *Service) WaitEndedHooks(timeout time.Duration) bool
- func (s *Service) WaitFor(id string, timeout time.Duration) (JobResult, bool)
- func (s *Service) WaitTerminalHooks(timeout time.Duration) bool
- func (s *Service) WatchJob(id string) (<-chan struct{}, func())
- func (s *Service) WebURL(path string) string
- func (s *Service) WorktreeStatus(jobID string) (WorktreeStatus, error)
- type ServiceStats
- type SessionCommandSender
- type SkillFile
- type SkillInfo
- type SkillLibrary
- type TodoDispatch
- type UpgradeRestartBlocker
- type UploadSpec
- type Usage
- type VerifyResult
- type WakeupGate
- type WakeupSpec
- type WorkerCandidate
- type WorkerInflightJob
- type WorkerSelector
- type WorkflowAdvancer
- type WorktreeMergeError
- type WorktreeStatus
- type XferBridge
- type XferFile
- type XferSkipped
- type XferSummary
- type XferUploadResult
Constants ¶
const ( EventJobDelivered = "job.delivered" EventJobDeliveryFailed = "job.delivery_failed" EventJobDeliverySkipped = "job.delivery_skipped" )
Delivery events.
const ( EventCommentCreated = "comment.created" EventCommentTriggered = "comment.triggered" EventCommentTriggerThrottled = "comment.trigger_throttled" EventCommentMentionRejected = "comment.mention_rejected" )
Comment event types (MCP-05 阶段 A, design §二.A.5). None of them is in the default notification set (notify.DefaultTriggerEvents): a comment is conversation, not a "a human must act" signal, so a subscriber lists them explicitly.
- comment.created {comment_id,scope,scope_id,author,author_kind,mentions} one row per comment, whatever its author and whatever it triggers.
- comment.triggered {comment_id,job_id,mention,kind} one row per job an @-mention started — the receipt that a comment spent money.
- comment.trigger_throttled {comment_id,reason,scope,scope_id,count,last_at} the throttle refused the whole comment (reason: min_interval|max_per_scope).
- comment.mention_rejected {comment_id,mention,reason,error?} one mention started nothing (reason: unknown|not_allowed|submit_failed); the thread also carries a system comment saying so.
const ( // JobTokenPrefix marks a job credential on the wire. authMiddleware only consults // the job_tokens table for a bearer token with this prefix, so the overwhelmingly // common (user/worker) path keeps its single constant-time scan. JobTokenPrefix = "gjt_" // EnvJobToken is the variable the credential is injected as. The CLI and the gofer // MCP default their bearer token to it, so `gofer job comment …` typed by an agent // inside a job authenticates as that job. The name lives in config because the // dotenv loader keys off it too (a process carrying it is a JOB, and the .env it // would otherwise load is the server's). EnvJobToken = config.EnvJobToken // EnvServerAddr tells a job which hub to talk to. A hub-local job gets the address // this serve listens on; a dispatched job gets the hub address its worker is // connected to. It exists because `GOFER_SERVER_ADDR` (the CLI's own default) is a // client-node setting that a job cannot be expected to inherit. EnvServerAddr = "GOFER_SERVER_ADDR" // EnvWorkerID names the worker a dispatched job runs on (CFG-16). Only a worker // sets it (on the dispatch it re-submits locally); a server-local job has none. EnvWorkerID = "GOFER_WORKER_ID" // EnvJobBin is the absolute path of the gofer executable RUNNING the job, exported // alongside the PATH entry that makes `gofer` resolve to it (see jobBinaryEnv). EnvJobBin = "GOFER_BIN" )
SEC-01 job-scoped credentials.
A job process used to inherit the whole serve process environment, which included its bearer token (`server.token_env`) — so an agent inside a job could call the API as the human who started the server. The v0.57 leader field trial made that concrete: a leader job with no gofer MCP fell back to the inherited server token, reviewed work as a user and released a todo through a path the leader gate does not police (design §背景).
The fix is two-sided:
- the job environment no longer inherits the server's token — util.EnvironWithout plus the deny list below, applied by every runner — and
- the job gets a credential of its own, narrow in both TIME and SCOPE: minted when the job starts executing, dead the moment it reaches a terminal state (or at a fallback deadline), and accepted by the API only for the actions the design's permission table allows a job caller.
const ( EnvHookEventType = "GOFER_EVENT_TYPE" EnvHookEventSeq = "GOFER_EVENT_SEQ" EnvHookDeliveryID = "GOFER_DELIVERY_ID" EnvHookJobID = "GOFER_JOB_ID" EnvHookName = "GOFER_HOOK_NAME" )
Environment variables gofer sets for a hook process (before the hook's own env).
const ( // EventJobAwaitingApproval is a held job parking for a decision: // {reason, timeout_sec, expires_at, origin}. EventJobAwaitingApproval = "job.awaiting_approval" // EventJobHoldApproved is a human approving it: {by, note?}. The job's own // job.running / job.terminal follow as for any job. EventJobHoldApproved = "job.hold_approved" // EventJobHoldRejected is a human rejecting it: {by, note?}; job.terminal{cancelled} // follows. EventJobHoldRejected = "job.hold_rejected" // EventJobHoldExpired is the expiry sweep cancelling it: {expires_at}; // job.terminal{cancelled} follows. EventJobHoldExpired = "job.hold_expired" )
Hold lifecycle events. The `hold_` prefix keeps them apart from the review verdicts (`rejected` status, job.reviewed{verdict:rejected}), which mean something else.
const ( HoldDecisionApproved = "approved" HoldDecisionRejected = "rejected" HoldDecisionExpired = "expired" HoldDecisionCancelled = "cancelled" )
Hold decisions (HoldState.Decision).
const ( // HoldKindHuman is a `--hold` submit: it waits for a person to approve it. HoldKindHuman = "" // HoldKindUpdate is a job a one-click update parked while it waited for idle // (StatusPausedForUpdate): it waits for the UPDATE, which releases it itself. HoldKindUpdate = "update" )
The two reasons a job can be parked as a row without running (gofer-dzv3). Both use the same record, the same release-by-re-submit path and the same digest, but only HoldKindHuman is a decision somebody has to make: the hold list, the approval panel, the批准 notifications and the expiry sweep must never see an update park.
const ( InteractionPending = "pending" InteractionAnswered = "answered" InteractionCancelled = "cancelled" )
Interaction status values.
const ( InteractionTypeQuestion = "question" InteractionTypeChoice = "choice" InteractionTypeConfirmation = "confirmation" // InteractionTypePermission is an approval gate request (GATE-01 §1): an ACP // session/request_permission parked until a human picks one of the agent's own // options. It carries ToolCall + PolicyHint and is answered with an option id. InteractionTypePermission = "permission" )
Interaction type values.
const ( // EventPlanLeaderWoken: a leader job was started for a finished member job. EventPlanLeaderWoken = "plan.leader_woken" // EventPlanLeaderSkipped: a round was armed but not started (reason: paused | // submit_failed | unknown_plan | budget). EventPlanLeaderSkipped = "plan.leader_skipped" // EventPlanLeaderCancelled: a human spoke inside the wake window (by: the author). EventPlanLeaderCancelled = "plan.leader_cancelled" // EventPlanLeaderExhausted: the plan's round budget is spent — the chain goes back // to a human (design §二.B.3). EventPlanLeaderExhausted = "plan.leader_exhausted" )
Leader-round event types (MCP-05 阶段 B, design §二.B.5). They are recorded on the PLAN's scope (PlanEventScope), like plan.blocked: there is no job to hang them on. Only plan.leader_exhausted is in the notification default set — a leader that hands the plan back to a human is the "someone must act" signal the others are not.
const ( // FailureClassTransient marks a provider-side error (see the agent's // transient_error_patterns): a retry in a fresh process may well succeed. FailureClassTransient = "transient" // FailureClassOther marks every other failure — a real bug, a bad command, a // verify step that did not pass. Another agent would not fix it. FailureClassOther = "other" // FailureClassBudget marks a job the budget meter killed for crossing its max_tokens / // max_cost_usd / max_turns (N2 §B). It is neither transient (a retry would burn the // same budget again) nor "other" bug: no auto-resume, no failover, no health penalty // for the provider. FailureClassBudget = "budget" )
Failure classes (SUP-01 P3). Every FAILED job is classified from the same pattern match that decides continuation/transfer, INDEPENDENTLY of whether either is enabled — health must reflect the provider, not the job's policy.
const ( VerifyPassed = runner.VerifyPassed VerifyFailed = runner.VerifyFailed VerifyTimeout = runner.VerifyTimeout VerifySkipped = runner.VerifySkipped )
Verify step statuses (mirrored from runner so callers spell job.VerifyPassed).
const ( StatusQueued = "queued" StatusRunning = "running" StatusAwaitingInput = "awaiting_input" StatusDone = "done" StatusFailed = "failed" StatusCancelled = "cancelled" StatusTimeout = "timeout" // StatusPendingInteraction is reserved for P9 (running-agent two-way // interaction). Declared here so the status set is documented in one place; // P4 never sets it. StatusPendingInteraction = "pending_interaction" // StatusRecovering (RECOV-01) is a NON-terminal holding state: a worker job // whose worker connection dropped but whose worker process may still be running // it. It is entered when the hub suspends the job's sink (the connection died // with the job in flight and recovery is enabled) and left either back to // StatusRunning (the same worker process reconnected and proved it still has the // job) or to StatusFailed / the job's own terminal state (the recovery window // expired → worker_lost, or the worker replayed the real Result). A recovering // job keeps its timeout running: a job that hangs in recovering still ends by // timeout. Appended to the END of the enum so existing values never shift. StatusRecovering = "recovering" // StatusNeedsReview (GATE-01 S3) is the人工验收 holding state: the agent finished // NORMALLY (a `done` run of a job that asked for review) but the delivery is not // accepted yet. It is NON-terminal (IsTerminal false): retention must not evict // the job a human still has to rule on, and `job resume` demands accept/reject // first. The PROCESS is over, though, so the finished-vs-live question is answered // by IsFinished (true here) — that is what closes the log stream/SSE, evicts the // in-memory entry and keeps crash recovery from treating it as a running job. StatusNeedsReview = "needs_review" // StatusRejected (GATE-01 S3) is the terminal outcome of a human REJECTING a // needs_review job: the work was delivered but not accepted. It is terminal // (retention collects it; a workflow step aggregates it as a failure, like failed) // — but it never triggers a job-level retry or an automatic continuation, because // only a human's `reject --resume` decides whether the work is continued. // Appended to the END of the enum so existing values never shift. StatusRejected = "rejected" // StatusWaitingDir (JOB-11) is the NON-terminal state of an exclusive job that is // parked on the same-directory lock: another job holds it for a directory that is // this one's cwd, an ancestor or a descendant of it. Like the concurrency gates it // replaces, waiting is QUEUING, not failure — the job keeps `IsFinished` false, is // counted with `queued` everywhere (statistics, in-flight gauge), is cancellable, // and leaves as soon as the holder releases the directory. Appended to the END of // the enum so existing values never shift. StatusWaitingDir = "waiting_dir" // StatusAwaitingApproval (gofer-9b1b) is the NON-terminal state of a job submitted // with --hold: admitted (every validation ran) but not started, waiting for a human // to approve (→ queued, then it runs under the same id) or reject it / let it expire // (→ cancelled). Unlike queued it has NO in-memory entry — it is pure database state, // so a restart keeps it, it takes no concurrency slot or directory lock, and // IsFinished is false (the job will still run). Appended to the END of the enum so // existing values never shift. StatusAwaitingApproval = "awaiting_approval" // StatusPausedForUpdate (gofer-dzv3) is the NON-terminal state of a job a one-click // update PARKED while it waited for the machine to go idle, so the restart that // follows does not have to kill in-flight work. It is deliberately a state of its // own rather than a flavour of awaiting_approval: nobody decides anything about // such a job, so the hold surfaces (the待批准 list, the approval panel, the批准 // notifications, the expiry sweep) must never see it. Everything else is the same // as a held job — ONE database row, no in-memory entry, no concurrency slot, no // directory lock, no dispatch, IsFinished false — and it leaves the state the same // way: the update releases it (same id, the original request submitted again). // Appended to the END of the enum so existing values never shift. StatusPausedForUpdate = "paused_for_update" )
Job status values (plan §6.2).
const ( EventJobSubmitted = "job.submitted" // {project,agent,runner,caller_id,tags} EventJobTitleChanged = "job.title_changed" // {old_title,new_title,operator} EventJobDispatched = "job.dispatched" // {runner,worker_id} (remote only) EventJobRunning = "job.running" // nil EventJobTurnStarted = "job.turn_started" // {turn_no} EventJobTurnEnded = "job.turn_ended" // {turn_no,stop_reason} EventJobAwaitingInput = "job.awaiting_input" // {turn_no,idle_deadline_at} EventSessionAwaitingReply = "session.awaiting_reply" // delayed continuous-session reminder EventJobTerminal = "job.terminal" // {status,exit_code,error} EventJobUncommitted = "job.uncommitted" // {count,files(first 20)} EventJobCancelled = "job.cancelled" // {was_terminal} EventInteractionCreated = "interaction.created" // {interaction_id,type,prompt} EventInteractionAnswered = "interaction.answered" // {interaction_id,answer} EventInteractionPunted = "interaction.punted" // {interaction_id,caller_id} // EventJobACPSummary is the ONE row an acp-agent turn contributes to the timeline // (bd h-aii-rnxk): {tool_calls,thoughts,permissions,permissions_auto,stop_reason}, // recorded when the prompt turn ends (permissions_auto = the requests gofer answered // without a human, which have no job.permission_answered row of their own, F4). The // per-tool-call detail it replaces now goes to the job's stderr as compact events // (bd h-aii-7kja), where NdjsonTimeline renders it. The literal lives in the runner // package (which emits it and cannot import this one — G022) and is aliased here so // the job event vocabulary has ONE definition. EventJobACPSummary = runner.EventACPSummary // EventJobNeedsReview is a reviewed job finishing NORMALLY and parking for人工 // 验收 (GATE-01 S3): {job_id, exit_code}. It REPLACES job.terminal for that // transition (the job is not终态 yet), and it is a notification DEFAULT trigger // (it is a "a human must act" signal, exactly like interaction.created). EventJobNeedsReview = "job.needs_review" // EventJobReviewed is a human's accept/reject decision on a needs_review job: // {verdict, by, note, resume_job_id?}. It is followed by the job.terminal event of // the state the decision produced (done / rejected). EventJobReviewed = "job.reviewed" // EventJobCancelRequested is a cancel frame for a worker-run job that could not be // DELIVERED to that worker (F3, bd h-aii-tcpm): {delivered:false, worker_id, error}. // The host job is finished as cancelled regardless, so this is the only row that // says the worker may still be running it. The literal lives in the runner package // (which emits it and cannot import this one — G022); it is aliased here so the job // event vocabulary has ONE definition. EventJobCancelRequested = runner.EventCancelRequested // EventJobInputInjected is the pty runner writing priming text into an // interactive child's stdin once its terminal settled (session relay §9.1 B): // {bytes, written, quiet_ms, error?}. The literal lives in the runner package // (which emits it and cannot import this one — G022); it is aliased here so the // job event vocabulary has ONE definition and a caller may read it by name. EventJobInputInjected = runner.EventInputInjected // EventJobVerifyStarted is the verify step starting on the executing machine: // {command} (the argv, space-joined for reading). Recorded just before the child // is spawned, so a step that hangs is visible as a started-without-finished pair. EventJobVerifyStarted = "job.verify_started" // EventJobVerifyFinished is that step ending: {status, exit_code, duration_ms} // (status is passed|failed|timeout|skipped) — the evidence behind the job's own // terminal status, and the event a notification subscriber watches for a red build. EventJobVerifyFinished = "job.verify_finished" // EventJobUploadFailed is a job's upload step failing (XFER-01 X2): // {dest, xfer_id, error}. It is recorded BEFORE the agent would have started, so a // subscriber sees the failure as its own event rather than only as the job's error. // The job then fails with "upload <dest>: <reason>" and no agent process is spawned. EventJobUploadFailed = "job.upload_failed" // EventJobFilesCollected is the collect step's result (XFER-01 X2): // {count, bytes, skipped}. It is recorded on the EXECUTING machine after the job's // (and verify's) outcome, so a subscriber learns what the job delivered without // fetching the summary. EventJobFilesCollected = "job.files_collected" // EventJobSkillsMounted is a job's skills being mounted (JOB-10): {names, bytes, // dir} when the machine that RUNS the job placed the files itself (mountSkills), // {names, via:"uploads"} when they travelled to a ws-worker as uploads (raised by // the worker runner on the host row, S4). Either way it is the receipt that the // knowledge the job was promised reached the machine that reads it. The literal // lives in the runner package (which emits the uploads half and cannot import this // one — G022), aliased here so the vocabulary has ONE definition. EventJobSkillsMounted = runner.EventSkillsMounted // EventJobSkillsSkipped is a job that WOULD have carried skills but does not // (JOB-10): {reason, names, count}. "worker_protocol" means the target worker // speaks a protocol below wsproto.SkillsMinProtocolVersion and cannot be trusted // with the upload base — the hub drops the mount rather than let an old worker // write the files into the working tree, and the job still runs (design §横切). // The literal lives in the runner package (which emits it and cannot import this // one — G022); it is aliased here so the job event vocabulary has ONE definition. EventJobSkillsSkipped = runner.EventSkillsSkipped // EventJobRulesInjected is a job's MANDATORY rules being injected at submit // (JOB-06①): {names, bytes}. It is recorded by the SUBMITTING machine right after // the job's result dir exists, and it is the receipt that this run's prompt // actually opened with the discipline the config bound to it — `job show`'s // `rules:` line reads the row, this reads the timeline. EventJobRulesInjected = "job.rules_injected" // EventJobRulesSkipped is a rule source that could not be read (JOB-06①): // {reason}. "project_file_unreachable" means the project's `.gofer/RULES.md` was // not readable from the machine that submitted (typically a worker-hosted project // whose tree this hub cannot see). The job still runs — the omission is visible // here rather than silently dropped. EventJobRulesSkipped = "job.rules_skipped" // EventNotifyDropped is an end-notification gofer DROPPED instead of refusing the // submit (gofer-3db4): {reason, target}. Only an internal producer may degrade — // a scheduled run, a plan dispatch, a workflow step, a wakeup / auto-resume / rerun // continuation whose stored request asked to notify a session that is gone (or never // existed, or belongs to another caller). The work still runs; this event is where // "why was I not told?" is answered, instead of the job surprising its sender with // silence. A caller who named the flag directly still gets a 400 at submit. EventNotifyDropped = "job.notify_dropped" // The permission events are emitted by the acp runner (internal/runner/acp), whose // gated calls cannot reach this package (G022). Their literals live in the runner // package — the same single-definition rule as EventJobInputInjected — and are // aliased here for the mirror whitelist and for callers that read them by name. EventJobPermissionRequested = runner.EventPermissionRequested EventJobPermissionAnswered = runner.EventPermissionAnswered EventJobPermissionTimedOut = runner.EventPermissionTimedOut // EventJobFellBack is a transient failure taken over by the next candidate agent // (SUP-01 P3): {to_job, agent, reason} where reason is the matched provider-error // text. It REPLACES job.terminal for that transition (the failure is about to be // continued by another agent, so an IM subscriber must not be told it is over) — // exactly like job.auto_resumed; when the takeover cannot be submitted, the // job.terminal event is recorded late instead. EventJobFellBack = "job.fell_back" // EventJobAgentSubstituted is a degraded agent replaced BEFORE dispatch // (SUP-01 P3, server.agent_fallback.pre_dispatch): {from, to, reason}. The job row // keeps the requested agent in requested_agent, so "why did this run on another // agent?" is answered from the job itself. EventJobAgentSubstituted = "job.agent_substituted" // EventJobWaitingDir is an exclusive job parking on the same-directory lock // (JOB-11): {holder_job, dir} — WHO holds the directory this job needs and which // directory that is. It is recorded once, as the job enters `waiting_dir`; the // job's own job.running event later says it got in. A subscriber sees the queue // without polling the row. EventJobWaitingDir = "job.waiting_dir" // EventJobDirWaitTimeout is a job whose wait for the same-directory lock exceeded // server.dir_lock_max_wait_sec (JOB-11, F12 fix 2026-09-25): {holder_job, dir, // wait_sec}. The job is FAILED by that wait (it never ran at all), and this row is // what tells its timeline that the queue — not the work — is what ended it. EventJobDirWaitTimeout = "job.dir_wait_timeout" // SEC-01 job-scoped credentials, recorded on the job they describe: // - job.env_allowed {keys:[...]} a project's job_env_allow re-admitted // inherited variables the denylist would otherwise strip. It is recorded per // job that ACTUALLY inherited one (a key the process environment does not // carry is not an allowance in force), so the job detail answers "what did // this run get to see that it normally would not" without reading config. // - job.credential_skipped {reason:"worker_protocol"} the job was dispatched to // a worker that predates the credential frame, so it runs WITHOUT a job token // (it can read nothing back). The literal lives in the runner package, which // emits it and cannot import this one (G022); aliased here like the skills // skip above. // A revocation records NO event (F9): it is implied by the terminal state the job // just reached, and a row after `job.terminal` would break the "the terminal event // is the last one" invariant the stream, the review console and `job watch` all // rely on. Its trace is the credential row's own revoked_at. // None is in the notification default set — they are facts about a run, not an // "a human must act" signal. EventJobEnvAllowed = "job.env_allowed" EventJobCredentialSkipped = runner.EventCredentialSkipped // R2/AUTO-03 durable job retry, recorded on the SOURCE job (the one that failed) // for the first two and on the retried job for the third: // - job.retry_scheduled {retry_id, attempt, next_run_at, reason} a retry ROW was // written; the re-run happens when the serve sweeper picks it up, so this is // the row's own "I will run again" statement (and it survives a restart); // - job.retry_started {retry_id, new_job_id} the sweeper submitted it — the // attempt is now a real job; // - job.retry_exhausted {attempts} the LAST attempt failed: the budget is spent // and nothing more will be tried. This one IS in the notification default set // (design §二.3): retries running out is exactly the "a human must act" signal // plan.blocked and job.needs_review are. EventJobRetryScheduled = "job.retry_scheduled" EventJobRetryStarted = "job.retry_started" EventJobRetryExhausted = "job.retry_exhausted" // EventJobStalled is the AUTO-05 watchdog killing a job that produced no output for // its whole stall window: {silent_sec, stall_timeout_sec}. It is recorded just // before the runner's context is cancelled, so the timeline shows WHY the job ended // before its deadline; the failure itself lands in the job's error as // "stalled: no output for <N>s" (a transient failure — the chain continues). EventJobStalled = "job.stalled" // EventJobBudgetExceeded is the budget meter killing a job that crossed one of its // limits (N2 §B GATE-02): {limit, max, used}, where limit is max_tokens | // max_cost_usd | max_turns. Recorded just before the terminal event (the failure // itself reads "budget exceeded: <limit> <max> (used <n>)", failure_class=budget). // It IS in the notification default set: a budget stop is a "a human decides whether // to raise it" signal. EventJobBudgetExceeded = "job.budget_exceeded" // EventJobSessionCaptured is a session id captured AFTER the fact (AGT-04): // {agent, by, source}, where `by` is "agent_config" when the agent's own // session_capture regex produced it (built-in or explicitly configured) and // "fallback" when gofer's generic fallback did, and `source` is where it was read // from (stdout | stderr | pty | file). It is recorded on both capture paths — the // terminal scan of the logs and the live pty observer — and it is NOT in the // notification default set: a captured id is a fact about the job, not a "a human // must act" signal. Its real use is discovery: `by: "fallback"` says the agent has // no session_capture of its own yet. EventJobSessionCaptured = "job.session_captured" // EventConfigUpdated is a successful write through the config write API // (WEB-04③ V1.1 R3): {section, key, by, fields} — WHAT was written, by WHICH // caller, and which FIELD NAMES changed. It carries no values on purpose: config // values are host paths and host names (SR403), and the audit question is "who // changed what", not "what is it now" (the row is immutable, the value is in the // file). For a delete, fields is ["*"] — the whole definition went away. // // It is NOT in the notification default set (notify.DefaultTriggerEvents): an // operator editing config is not an "a human must act" signal for whoever watches // job.terminal. A subscriber that wants it lists it explicitly. EventConfigUpdated = "config.updated" // ConfigEventScope is the synthetic event-scope id config writes are recorded on // (config.updated belongs to no job, exactly like xfer:<id> belongs to no job), so // the whole config audit trail is one readable stream: ListJobEvents(ConfigEventScope). ConfigEventScope = "config" // PLAN-02 P2 plan-todo dispatch. plan.todo_dispatched is recorded ON THE JOB a // ready+assigned todo started ({todo_id, job_id, agent}), so the item's history // says who started what; plan.todo_dispatch_failed is recorded on the PLAN's own // scope (`plan:<id>`, see PlanEventScope) when the submit was REFUSED // ({todo_id, reason}) — there is no job to hang that one on, and a plan-level // subscriber is exactly who wants to hear that nothing started. Neither is in the // default notification set: a plan item starting is not an "a human must act" // signal (design §四.2). EventPlanTodoDispatched = "plan.todo_dispatched" EventPlanTodoDispatchFailed = "plan.todo_dispatch_failed" // PLAN-03 chain events, all recorded on the PLAN's own scope (`plan:<id>`, see // PlanEventScope) because none of them belongs to a job that ran: // - plan.todo_advanced {todo_id, after} a pending item whose dependencies are // satisfied was queued (and, right after, dispatched); // - plan.todo_unassigned{todo_id} an item came due but nobody is // assigned to run it — the human's cue, and the reason a chain can stall // silently otherwise; // - plan.blocked {todo_id, job, reason} a chain job FAILED and parked // the plan on its item. The ONLY plan event in the notification default set // (design §六, decision 1): like job.needs_review it is a "a human must act" // signal, and it can only happen on a plan that uses dependencies; // - plan.completed {plan_id} every item is done or skipped; // - plan.advance_paused {plan_id} a chain move was due while the plan is // paused (the item stays where it is — the event says why nothing started). EventPlanTodoAdvanced = "plan.todo_advanced" EventPlanTodoUnassigned = "plan.todo_unassigned" EventPlanBlocked = "plan.blocked" EventPlanCompleted = "plan.completed" EventPlanAdvancePaused = "plan.advance_paused" // EventPlanHandoffUpdated records a new version of a plan's handoff note. It // is intentionally absent from notify.DefaultTriggerEvents: a handoff is // durable context, not a default human-action alert. EventPlanHandoffUpdated = "plan.handoff_updated" // JOB-09 wakeup lifecycle events, all recorded on the wakeup's TARGET job (the // one a fire resumes), so the job's own timeline answers "why did this job run // again" and the web 唤醒 block reads its trigger history from them: // - job.wakeup_fired {wakeup_id, kind, reason, continuation_job} // - job.wakeup_coalesced {wakeup_id, reason} (a trigger that found the single // continuation slot busy — counted, not dispatched) // - job.wakeup_expired {wakeup_id, kind} (TTL passed; disabled) // - job.wakeup_failed {wakeup_id, kind, reason, error} (the continuation // could not be started; not part of the design's list, but a wakeup that // silently never resumes is indistinguishable from a healthy idle one) // None is in the default notification set. EventJobWakeupFired = "job.wakeup_fired" EventJobWakeupCoalesced = "job.wakeup_coalesced" EventJobWakeupExpired = "job.wakeup_expired" EventJobWakeupFailed = "job.wakeup_failed" // EventScheduleTriggered is recorded ON THE JOB an external webhook started // (AUTO-02b): {source:"webhook"}. The submission itself is the schedule's // run-now, so the event is what says WHY that job exists — the job's own timeline // answers "nobody typed this". EventScheduleTriggered = "schedule.triggered" // Agent health transitions (design §六), recorded on the AGENT's own scope // (`agent:<key>`, see AgentEventScope) because they belong to no job: // - agent.degraded {agent, transient_fail, window_sec, last_error} // - agent.recovered {agent, window_sec} // Both are subscribable but NOT in the notification default set: a flaky provider // is worth telling an on-call channel about, but it must not page everyone who // asked for job terminals. EventAgentDegraded = "agent.degraded" EventAgentRecovered = "agent.recovered" )
Job lifecycle event types (E13, design §5.2). Each is recorded append-only via recordEvent at the corresponding state transition's persist-success point. The detail payload per type is documented at each insertion site.
const ( EventWorkflowSubmitted = "workflow.submitted" // {title,total_steps,caller_id} EventStepStarted = "step.started" // {step,attempt,job_id} (single-job step) EventStepFanout = "step.fanout" // {step,attempt,fan_out,join,job_ids} (P2 fan-out step) EventStepRetry = "step.retry" // {step,attempt,next_attempt,backoff_sec,next_step_at} EventStepSkipped = "step.skipped" // {step,attempt,status} (on_failure=continue) EventStepPicked = "step.picked" // {step,fan} (join=pick human choice) EventSubworkflowStarted = "subworkflow.started" // {step,child_workflow_id,total_steps} (P3, type=workflow step) EventWorkflowTerminal = "workflow.terminal" // {status,error} EventWorkflowCancelled = "workflow.cancelled" // {was_terminal} )
Workflow lifecycle event types (P1, design §5.4). Recorded append-only via recordWorkflowEvent at the corresponding workflow-engine transition. The detail payload per type is documented at each insertion site.
const ( // EventSessionWaiting fires when a relayed terminal session stops and opens a // turn waiting for a human reply (session relay, SESS-01). EventSessionWaiting = "session.waiting" // EventSessionAttention fires when a relayed session needs a human at the // TERMINAL — a permission prompt or a built-in question the agent raised. // Unlike session.waiting this cannot be answered on the web (it is Claude // Code's own dialog, not a relay turn), so the notification exists to get the // human back to the keyboard, not to hand them a reply box. EventSessionAttention = "session.attention" // EventSessionHandedOff fires when a session is taken over by a new interactive // pty job (session relay §9.1 B, `--resume`): the conversation continues in that // job's terminal, so the notification carries the link to it. Like the other two // session events it is NOT a default trigger — a webhook subscribes explicitly. EventSessionHandedOff = "session.handed_off" // EventSessionTakeoverReleased fires when the takeover job ends and the session // goes back to its ORIGINAL terminal (SUP-02 R1) — the dual of the event above: // whoever was told the conversation had moved learns it moved back. reason names // why the job ended ("job_done" / "job_failed" / …). EventSessionTakeoverReleased = "session.takeover_released" // EventSessionNudgePaused fires when a session nudge (N2 §E, `gofer session nudge`) // paused itself after 3 consecutive delivery failures, so the person learns the // reminders stopped reaching the session. NOT a default trigger: a webhook subscribes // by listing the type in its `events`. EventSessionNudgePaused = "session.nudge_paused" )
Notification event types that are NOT job lifecycle events (OBS-07a). They never appear in DefaultTriggerEvents, so an existing webhook that omits its `events` filter keeps its current traffic: subscribing is opt-in by listing the type explicitly.
const ( // ResumeModeSession continues as a resident ACP session (needs an acp-agent). ResumeModeSession = "session" // ResumeModeInteractive continues as a pty job running the agent's interactive // resume argv (needs a cli-agent with a session_resume_interactive template). ResumeModeInteractive = "interactive" // ResumeModeBatch continues as a one-shot `--resume -p <prompt>` job (needs a // cli-agent with a session_resume template and a prompt). ResumeModeBatch = "batch" )
Resume modes: how the continuation is started. Empty keeps the form the source job implies (ACP -> resident ACP session, cli batch -> `--resume -p`, cli pty -> pty), which is the only behaviour ResumeJob offers.
const ( DefaultTimeoutSec = 300 DefaultAgentTimeoutSec = 1200 // DefaultMaxTimeoutSec is the clamp ceiling for a caller that configured none // (normalizeTimeout's max <= 0). It is aliased to config.DefaultMaxJobTimeoutSec // so both layers agree on one literal — the value this clamp used to be // hard-coded to — and a ceiling-less caller still cannot run a job unbounded. DefaultMaxTimeoutSec = config.DefaultMaxJobTimeoutSec )
Timeout bounds (plan §9 P4, §11; bd h-aii-s9ck). TimeoutSec defaults to DefaultTimeoutSec when unset and is clamped to the ceiling the CALLER resolves (config.Config.EffectiveMaxTimeoutSec — server.max_job_timeout_sec, overridable per project by max_timeout_sec). AI agent jobs (cli-agent / acp-agent — a model turn runs long) get their own larger default DefaultAgentTimeoutSec.
const ( DefaultWaitSec = 30 MaxWaitSec = 60 )
Synchronous-submit wait caps (design §6.1 / P1-a): a sync submit blocks at most DefaultWaitSec when no explicit wait_timeout_sec is given, and never longer than MaxWaitSec, after which the caller falls back to async semantics (the HTTP layer maps this to 202 + X-Gofer-Async). These were the httpapi handler's defaultWaitSec/maxWaitSec, moved here with the wait policy.
const ( // EventJobPausedForUpdate is a job parked by an update waiting for idle: // {apply_id, reason}. EventJobPausedForUpdate = "job.paused_for_update" // EventJobUpdateResumed is the update releasing it: {by, count?}. The job's own // job.running / job.terminal follow as for any job. EventJobUpdateResumed = "job.update_resumed" )
Lifecycle events of an update park. Both names are separate from the hold_* family: an update park is not a decision anybody makes.
const DeliveryJobTag = jobstore.TagDelivery
DeliveryJobTag marks the internal job delivering a worker's worktree job (GIT-02).
const (
EnvDecisionPoint = "GOFER_DECISION_POINT"
)
Environment variables gofer sets for a decision hook process.
const EventJobDecisionHook = "job.decision_hook"
EventJobDecisionHook records one hook decision on the job it shaped: {point, hook, decision, reason?, patch?, error?}.
const EventJobMCPInjected = "job.mcp_injected"
EventJobMCPInjected records which registry MCP servers a job's agent was given and any limitation worth knowing (MCP-06).
const EventJobSecretsGranted = "job.secrets_granted"
EventJobSecretsGranted records which secrets a job was given: {names}.
const FindingsSectionTitle = "发现但不碰"
FindingsSectionTitle is the report section an agent lists what it found outside its scope but did not touch (gofer-3nxa.3, the 「交付约定」 section asks for it).
const JobIDLayout = "20060102-150405"
JobIDLayout is the time prefix for a job id (no separators that would clash with directory names). A random suffix makes it unique across process restarts (plan §9 P4: a seconds+seq scheme collides after a restart).
const KnowledgeSectionTitle = "可复用经验"
KnowledgeSectionTitle is the report section an agent lists reusable lessons in.
const MaxEventDetailBytes = 8 * 1024
MaxEventDetailBytes caps a recorded event's detail_json. A detail larger than this is dropped (the event is still recorded with an empty detail) so a pathological payload never bloats the stream — events are an audit trail, not a data channel.
const MessengerJobTag = jobstore.TagSessionMessenger
MessengerJobTag marks the delivery record created when the web console sends a message to an existing terminal session. It is an internal implementation tag: ordinary job lists hide it, while --all and job details retain it.
const PlanRules = `` /* 652-byte string literal not displayed */
PlanRules are the six rules a plan follows.
const PlanTodosFence = "gofer-todos"
PlanTodosFence is the info string of the fenced block a plan ends with.
const PlanTodosFormat = "输出格式:方案末尾附一个 ```" + PlanTodosFence + "``` 围栏块,内容是 YAML 列表,每个元素一步:\n" + "- `title`:步骤标题(必填);\n" + "- `after`:依赖的前序步骤(标题或从 1 起的序号,可写列表);省略 = 依赖上一步,`[]` = 无依赖;\n" + "- `acceptance`:验收标准;\n" + "- `scope`:改动范围(路径 glob 列表,相对仓库根);\n" + "- `check`:检查点命令(可选;生成一个 exec 复核项,后续步骤等它通过)。\n\n" + "```" + PlanTodosFence + "\n" + "- title: 存储层加字段与迁移\n" + " acceptance: 迁移可重复执行;旧数据可读\n" + " scope: [src/storage/**]\n" + "- title: 接口暴露新字段\n" + " scope: [src/api/**]\n" + " check: <项目的测试命令>\n" + "```"
PlanTodosFormat describes the gofer-todos block (`gofer plan import` reads it).
const PlannerGuidance = PlanRules + "\n\n" + PlanTodosFormat
PlannerGuidance is what the plan-implement planner prompt carries: the rules, then the output format.
const (
// ProjectRulePrefix names that auto-included rule: `project:<key>`.
ProjectRulePrefix = "project:"
)
const SessionCaptureByNDJSON = "agent_config"
SessionCaptureByNDJSON is the `by` value for an id the agent's own structured stream carried (F11): the ndjson projector reads the agent's session row itself, so this is the agent-config side of SessionCaptureBy's distinction (the agent declared the shape) — never the generic fallback, which exists for an agent whose banner gofer has to guess at.
const ( // SkillBaseResultDir is the UploadSpec.Base value that places a file relative to // the job's RESULT dir instead of its cwd (design §一.4). A worker below // wsproto.SkillsMinProtocolVersion would ignore it and write into the working // tree, so the hub must never send one to such a worker. SkillBaseResultDir = "result_dir" )
const StewardTag = "steward"
StewardTag labels the steward's session job (Sessions and the work page show it).
const TitleMaxRunes = 200
TitleMaxRunes caps an explicit job title (submit and later edits). It is generous on purpose: before titles became editable any length was accepted.
const TrackerSyncJobTag = jobstore.TagTrackerSync
TrackerSyncJobTag marks a server-dispatched `gofer repo sync` job (web Issues page sync button): hidden from ordinary lists and the Board like the others.
const WorkSummarizerJobTag = jobstore.TagWorkSummarizer
WorkSummarizerJobTag marks a work-item summarizer (tidy-up) job, which gofer submits on its own: hidden from ordinary job lists and the Board like the messenger record, visible with --all and in job detail.
Variables ¶
var ( // ErrUnknownCommentTarget means the scope/scope_id names no job, plan or todo. ErrUnknownCommentTarget = errors.New("unknown comment target") // ErrInvalidComment means the scope, body or author is unusable. ErrInvalidComment = errors.New("invalid comment") )
Comment errors. Both are sentinels so the entry layers map them without string matching: an unknown target is a 404, a malformed comment a 400.
var ( // ErrUnknownProjectOnRunner is returned when the target worker is resolvable and // online but does not report the requested project. (An unknown project on a // local/peer runner stays ErrUnknownProject — see validate.) ErrUnknownProjectOnRunner = fmt.Errorf("%w: project not available on target runner", ErrInvalidRequest) // ErrAgentNotOnRunner is returned when the target worker is resolvable and online // but does not report the requested agent (the resume SOURCE agent for a resume). ErrAgentNotOnRunner = fmt.Errorf("%w: agent not available on target runner", ErrInvalidRequest) // ErrNoCapableWorker is returned by the label auto-select path when no connected // worker satisfies the request's labels/pty AND its project+agent (G2). ErrNoCapableWorker = fmt.Errorf("%w: no online worker satisfies the required project+agent", ErrNoEligibleWorker) )
Federation admission sentinels (config-federation P3, design §10). They extend the Submit validation set defined in service.go (ErrUnknownProject / ErrInvalidRequest / ErrNoEligibleWorker) with the runner-scoped capability checks: a job is validated against the capability view of the side that will EXECUTE it (capabilitiesFor, P2), not against the host's own config.
Each sentinel WRAPS the pre-federation error whose HTTP status it must keep, so the httpapi mapping (submitStatus) stays correct without a new mapping rule and errors.Is on the coarse sentinel keeps working for existing callers/tests:
- the two validate-time rejections wrap ErrInvalidRequest → 400 (the request names a project/agent the target runner cannot serve; retrying it verbatim will not help).
- ErrNoCapableWorker wraps ErrNoEligibleWorker → 503 (transient: no ONLINE worker qualifies right now; another may connect / free up).
var ( // ErrJobNotAwaitingApproval — approve/reject-as-hold of a job that is not (or no // longer) awaiting approval, including the loser of a decision race. HTTP: 409. ErrJobNotAwaitingApproval = errors.New("job is not awaiting approval") // ErrHoldDrift — the approved request no longer resolves to the work the human // saw (config, role, template or rules changed while it waited). The job is // failed rather than run. HTTP: 409. ErrHoldDrift = errors.New("the request changed while awaiting approval; submit it again") // ErrHoldResume — `reject --resume` of a held job: nothing ran, so there is // nothing to continue. HTTP: 400. ErrHoldResume = fmt.Errorf("%w: a job awaiting approval never ran, so it cannot be resumed; reject it without --resume", ErrInvalidRequest) )
var ( // ErrUnknownJob — no job with the given id is tracked. HTTP: 404. ErrUnknownJob = errors.New("unknown job") // ErrUnknownInteraction — the job has no interaction with the given id. HTTP: 404. ErrUnknownInteraction = errors.New("unknown interaction") // ErrJobTerminal — the job already reached a terminal state, so there is no // live agent to consume an interaction/answer. HTTP: 409. Do not confuse with // ErrJobNotTerminal (derive operations require the source job to be terminal). ErrJobTerminal = errors.New("job is terminal") // ErrInteractionState — answering an interaction that is not pending (already // answered/cancelled). HTTP: 400. ErrInteractionState = errors.New("interaction not pending") // ErrInvalidInteraction — the create payload failed basic validation (bad type // or empty prompt). HTTP: 400. ErrInvalidInteraction = errors.New("invalid interaction") )
Interaction error sentinels. The interaction methods wrap these (via fmt.Errorf("%w: ...")) so the HTTP layer can map each failure to a stable status code with errors.Is, without string-matching the message.
var ( // ErrNoSession marks a resume of a source job that never captured a session // id (claude not injected / codex regex未命中 / unsupported agent). HTTP: 400. ErrNoSession = errors.New("job has no captured session_id") // ErrJobNotTerminal marks a derive attempt (resume / rebuild) whose SOURCE job is // still queued/running. Resuming a live job would hand the SAME session_id to a // second process while the source still holds it (concurrent writes to one agent // session). Rebuild of a live job is technically harmless but rejected too, for a // consistent rule (P6/D2 — this intentionally changes `job rerun <running-id>`, // which historically ignored the source status, to a 400). // Do not confuse with ErrJobTerminal (terminal jobs cannot take interactions). ErrJobNotTerminal = errors.New("source job is not in a terminal state") // ErrResumeUnsupported marks a source job whose agent has no SessionResume // template (it cannot be续接). HTTP: 400. ErrResumeUnsupported = errors.New("agent does not support resume") // ErrCrossRunner marks a resume that asks for a runner different from the // source job's. Session state lives on the original runner's filesystem // (design §8 同 runner 约束), so续接必须落同一 runner. HTTP: 400. ErrCrossRunner = errors.New("resume must use the same runner") )
Resume-path sentinels (session-capture P2, design §5.2 / §8). They wrap the well-formed-but-not-permitted cases so the HTTP layer can errors.Is them to a status (400) instead of string-matching. ErrUnknownJob (404) is reused from interaction.go for an absent source job.
var ( // ErrJobNotNeedsReview — accept/reject was asked of a job that is not awaiting // review (queued/running/done/failed/...). HTTP: 409. ErrJobNotNeedsReview = errors.New("job is not awaiting review") // ErrReviewNoteRequired — a reject carried no note. The note IS the reason the // agent is told to fix on --resume and the audit trail of the decision, so it is // required. HTTP: 400. ErrReviewNoteRequired = errors.New("reject requires a note") // ErrJobNotRunning — an operation that needs a LIVE job (cancel) was asked of a // job whose process already ended but which is not terminal (needs_review: the // caller wants reject). HTTP: 409. ErrJobNotRunning = errors.New("job is not running") )
人工验收 (GATE-01 S3) sentinels. Like the resume/interaction ones they are wrapped so the entry layers map each failure to a stable status code with errors.Is.
var ( // ErrUnknownProject is returned (wrapped) when the project_key is not // registered. HTTP layer maps it to 404. ErrUnknownProject = errors.New("unknown project") // ErrInvalidRequest marks a request that is well-formed but not permitted // (agent not allowed, exec gate, runner not allowed, missing fields). HTTP // layer maps it to 400. ErrInvalidRequest = errors.New("invalid request") // ErrSourceSessionElsewhere: the source session is the caller's, but it runs in // another project / runner / directory than the job, so the job cannot claim it as // its trusted source (ownership failures are plain ErrInvalidRequest). ErrSourceSessionElsewhere = errors.New("source session runs elsewhere") // ErrUnknownRole is returned when JobRequest.Role references a role not present // in cfg.Roles (E35). HTTP layer maps it to 400 (via submitStatus default). ErrUnknownRole = errors.New("unknown role") // ErrNoEligibleWorker is returned when a worker job supplies worker_labels but // no connected worker advertises all of them (or all such workers are stale). // HTTP layer maps it to 503 (temporarily unavailable — retry / pick another). ErrNoEligibleWorker = errors.New("no eligible worker") // ErrJobNotFound is returned by the job-scoped management helpers (WT-01 // WorktreeStatus / RemoveWorktree) for an id that no job has. The HTTP layer maps // it to 404 (the Get-based read paths signal the same condition with ok=false; a // helper that must distinguish "no such job" from "no worktree" needs a sentinel). ErrJobNotFound = errors.New("unknown job") )
Submit validation sentinels. They let the HTTP layer (internal/httpapi) map a rejected Submit to the right status code without string-matching: an unknown project is a 404, everything else (agent not allowed / exec gate / runner not allowed / bad request) is a 400. validate wraps these so errors.Is works.
var ( // ErrNoManagedWorktree: the job carries no WT-01 managed worktree (nothing to // list or remove). The HTTP layer maps it to 404. ErrNoManagedWorktree = errors.New("job has no managed worktree") // ErrWorktreeDirty: removal refused because the worktree still has uncommitted // changes — deleting it would throw away work the job left behind. Re-run with // --force to discard it. The HTTP layer maps it to 409. ErrWorktreeDirty = errors.New("worktree has uncommitted changes; re-run with --force to discard them") // ErrWorktreeGone: the recorded worktree directory is not there anymore (deleted // by hand / the job ran on another machine). The row may still be cleaned up by // `git worktree prune` on the owning machine. ErrWorktreeGone = errors.New("worktree directory is not present on this machine") ErrWorktreeMergeConflict = delivery.ErrMergeConflict ErrWorktreeMainNotReady = delivery.ErrMainNotReady ErrWorktreeMergeUnsupported = errors.New("worktree merge is supported only for a local runner") )
var DefaultJobEnvDeny = []string{"GOFER_TOKEN", "GOFER_SERVER_TOKEN", "GOFER_WORKER_TOKEN", config.EnvConfigDir,
"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_CHILD_SESSION", "CLAUDE_CODE_SESSION_ID",
"CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_MESSAGING_TOKEN", "CLAUDE_PID", "CLAUDE_CODE_SESSION_ATTENDED",
"CLAUDE_CODE_STOP_HOOK_BLOCK_CAP",
"GOFER_SESSION_ID", "CODEX_THREAD_ID", "CODEX_SESSION_ID"}
DefaultJobEnvDeny is the baseline denylist of inherited environment keys: the credentials gofer's own processes carry, plus the pointer to the config dir they are read from. `server.job_env_denylist` ADDS to it (a deployment may name more), and a project's `job_env_allow` can re-admit any of them deliberately.
GOFER_CONFIG_DIR is here because it is a credential pointer, not a setting: a job that inherits it hands the next `gofer` invocation the SERVER's <config-dir>/.env, which holds the operator's own token. That is not theoretical — it is leak 1 of the v0.60 field trial (design §v0.60 真机验收与 F10): the host's 0.53.1 CLI (which knows nothing about job credentials) loaded that file and called the API as the user.
The Claude Code session markers are here for a related reason (tools-b5t): a serve or worker started from inside a Claude Code session inherits them, and a claude job that sees them runs as that session's child — transcript saving off (so it cannot be resumed), nested-session detection, and the parent's messaging credentials in the job. User settings such as CLAUDE_CODE_MAX_RETRIES are not markers and pass.
The SESSION variables are here because a request can name a terminal session (design 2026-10-14-db-capabilities-and-session-grants §4「会话 id 的携带」): the CLI attaches `X-Gofer-Session-Id` from exactly these variables, and a session grant is judged by the session the request names. A job that inherited its parent terminal's id would let every command run inside it claim that terminal's session grants. The job is a DIFFERENT life: it must name nothing and hold only what its own job credential holds.
var ErrDecisionDenied = errors.New("denied by decision hook")
ErrDecisionDenied is a decision hook's refusal. HTTP: 403.
var (
ErrDeliveryNotApplicable = errors.New("job cannot be delivered")
)
Delivery errors.
var ErrJobFinishing = errors.New("job is still finishing")
ErrJobFinishing is returned (wrapped) by DeleteJob when the job already reads as finished in memory but its finish has not completed within deleteFinishWait. The message keeps the jobstore delete prefix, so the HTTP layer answers it with 409 like any other "not deletable yet" refusal.
var ErrJobNotPausedForUpdate = errors.New("job is not paused for an update")
ErrJobNotPausedForUpdate — the release of a job that is not (or no longer) parked by an update, including the loser of a race with a cancel or another release.
var ErrMemoryCandidateKeyExists = errors.New("memory key already exists in that scope")
ErrMemoryCandidateKeyExists is an accept whose key already names a live memory in the target scope: accepting never overwrites a memory.
var ErrNoMetaStore = errors.New("job metadata store not configured")
ErrNoMetaStore is returned by BackfillMetrics on a service without a store.
var ErrRedactedPlaceholder = errors.New("override still contains the redaction placeholder; replace it")
ErrRedactedPlaceholder marks a rebuild whose override still carries the redaction placeholder — the user viewed a redacted field and re-submitted it without replacing the secret. HTTP: 400 (defence-in-depth; unedited fields are never sent, so a placeholder here means an edited-but-unreplaced value). ErrUnknownJob (404) is reused for an absent source job; "no request" is a 404 too.
var ErrUpgradeDraining = errors.New("server upgrade is draining new work")
var ErrWakeupForbidden = errors.New("caller may not wake this job")
ErrWakeupForbidden marks a wakeup request from a caller that may not act on the target job (design §五.1 权限): the job's own caller, or a caller holding the answer capability, may. HTTP: 403.
var WakeupKinds = []string{ jobstore.WakeupKindAt, jobstore.WakeupKindEvery, jobstore.WakeupKindCron, jobstore.WakeupKindEvent, }
WakeupKinds lists the four registration shapes in documentation order.
Functions ¶
func AgentEventScope ¶
AgentEventScope is the synthetic event-scope id of an agent (`agent:<key>`).
func AllowAllWakeups ¶ added in v0.161.0
AllowAllWakeups is the gate of a TRUSTED LOCAL entry: `gofer mcp --standalone` operates the database in-process without an authz decision, and the design calls it 「受信的本地入口」 (design「非目标」/ T1.7). Any caller identity it carries is the operator's own.
func BackoffForPolicy ¶
func BackoffForPolicy(p *RetryPolicy, attempt int) int
BackoffForPolicy returns the backoff (seconds) before re-running an attempt that just failed. attempt is the 1-based number of the run that just failed; the backoff table is indexed by attempt-1 (attempt 1 → table[0]), clamped to the last entry past the end (SR606). An empty/absent BackoffSec falls back to the SR606 defaultBackoffSec. Shared by step-level and job-level retry (one semantics).
func CaptureSessionIDBytes ¶
CaptureSessionIDBytes extracts the session id from b using the same cached regex path as terminal log capture (the first NON-EMPTY capture group). It is exported for PTY relay output observation, where interactive agent output does not enter stdout/stderr logs.
b is scanned AS GIVEN — the caller owns the window (the pty observer hands over its tail window; that is where AGT-04's "fallback reads only the tail" rule is enforced for a live stream). The placeholder guard still applies.
func CheckBudget ¶
CheckBudget validates a requested budget (N2 §B): a limit is a finite number >= 0.
func CheckFromSession ¶
CheckFromSession validates the SHAPE of a requested source session (gofer-f4z8). It is rendered as ONE argv element into from_session_args, so the hazards are an id that reads as a flag (leading "-") or carries whitespace / control characters. Empty = unset = fine.
func CheckModel ¶
CheckModel validates a requested model id (N1 §B). It is rendered as ONE argv element into model_args, so the only hazards are an id that reads as a flag (leading "-") or carries whitespace / control characters, which no model id has. Empty = unset = fine.
func CheckProjectKey ¶
CheckProjectKey is the exported reuse of checkProjectKey for the SINGLE project-key charset rule (one source of truth for projectKeyRe). core.computePolicy calls it before pushing a project in a Policy: the key becomes a directory name on the worker (<storage.root>/<key>/<job_id>), so an unsafe key must be excluded there exactly as it is rejected here.
func DiffFiles ¶
DiffFiles lists the files a unified diff (a job's changes.diff, worktree sections included) touches, in first-seen order without duplicates. A rename contributes its new path; a deleted file its old one. A diff truncated at the size cap ends with a "=== changed files ===" name list (one path per line), which is read too.
func EffectiveDeliveryMode ¶ added in v0.146.0
func EffectiveDeliveryMode(cfg *config.Config, req JobRequest) string
EffectiveDeliveryMode is the mode a job delivers with: the job's own --deliver, else its project's delivery.mode, else none.
func EstimateJobCost ¶ added in v0.146.0
EstimateJobCost prices a job's usage with the pricing table when the agent reported no cost itself (gofer-2ldy): the model is the one the job asked for (--model). 0 when there is nothing to price (reported cost, no model, no split counts, unpriced).
func ExtractPlanTodosBlock ¶
ExtractPlanTodosBlock returns the body of the LAST gofer-todos fenced block of text (a plan report may quote the format earlier), and whether one was found.
func FormatTokens ¶
FormatTokens renders a token count at a glance: three significant digits behind a k/M suffix once it is large enough to need one (12.3k, 305k, 1.2M), the exact number below a thousand. It is what `job show` prints inside the usage line and what `agent status` prints in its 24h column, so both read the same way.
func FormatUsage ¶
FormatUsage renders a job's token/cost accounting as the ONE line `job show` prints (and the web detail mirrors):
in 12.3k / out 3.8k / cache 289k / total 305k / $0.0032 (ndjson:omp)
A counter the agent never reported is omitted rather than printed as 0, the two cache counters are one `cache` figure (a reader does not care which side of the cache the tokens were on), and the source trails the line in parentheses — it is what makes the numbers auditable. nil (or a tally with no numbers at all) renders as "", so a caller can print the line unconditionally.
func IsFinished ¶
IsFinished reports whether a job's PROCESS has ended — the question every "is there anything left to watch/attach to?" decision asks. It is IsTerminal OR needs_review (GATE-01 S3): a needs_review job is deliberately NOT terminal (it awaits a human, so retention keeps it and `job resume` refuses it) but its agent process is gone, so the log tail/SSE stream must close, the in-memory entry must be evicted, an attach must be refused, and crash recovery must not treat it as a running job to recover.
func IsRemoteRunner ¶
IsRemoteRunner reports whether name is any remote runner (peer-http or ws-worker); both share the host-side "skip local resolution + set Forward" path in Submit.
func IsRemoteSource ¶
IsRemoteSource reports whether a job's Source marks a remote execution machine (worker:<id> / peer:<name>), i.e. its artifact files live on that machine, not on this host (P4 / D6). An empty source is local. Exported so the artifact download path can do the remote-artifact 409 check without resolving the full manifest (it was httpapi.remoteSource).
func IsTerminal ¶
IsTerminal reports whether status is a finished state. It is the exported counterpart of isTerminal, used by callers outside the package (e.g. the SSE stream handler) to decide when to stop polling.
func JobTokenLooksLikeCredential ¶
JobTokenLooksLikeCredential reports whether a presented bearer token is shaped like a job credential. The HTTP layer uses it to decide whether the job_tokens table is worth consulting at all.
func LoadEnvFilesMap ¶
func LoadEnvFilesMap(paths []string, cfg *config.Config, proj config.ProjectConfig) (map[string]string, error)
LoadEnvFilesMap loads declared dotenv-style files into a fresh map without mutating os.Environ. Paths are resolved by resolveEnvFilePath.
func MCPFormatOf ¶ added in v0.144.0
func MCPFormatOf(ac config.AgentConfig) string
MCPFormatOf is how MCP servers reach agent ac: an acp-agent always takes them over the protocol; any other agent uses its mcp_format ("" = it cannot).
func MCPNamesFromWire ¶ added in v0.144.0
MCPNamesFromWire is the binding order of a dispatch's MCP list.
func MCPSpecsFromWire ¶ added in v0.144.0
func MCPSpecsFromWire(in []wsproto.MCPSpec) map[string]config.MCPServerConfig
MCPSpecsFromWire turns a dispatch's MCP list back into declarations by name.
func MaxAttemptsPolicy ¶
func MaxAttemptsPolicy(p *RetryPolicy) int
MaxAttemptsPolicy returns a RetryPolicy's attempt ceiling (MaxAttempts), or 1 (no retry) when the policy is nil / unset. Shared by step-level and job-level retry.
func OutOfScope ¶
OutOfScope returns the files matching none of the scope globs (nil when scope is empty: no declaration, nothing is out of scope). See ScopeMatch for the glob rules.
func ParseFindings ¶
ParseFindings extracts the list items of the LAST 「发现但不碰」 section of an agent's markdown report (also accepted: "Out of scope" / "Out-of-scope findings", any case, any heading level) — see ParseReportSection. The web console has the same parser in web/src/utils/findings.ts — their tests share cases.
func ParseKnowledge ¶
ParseKnowledge extracts the items of the LAST 「## 可复用经验」 section of a report (same rules as ParseFindings, see ParseReportSection).
func ParseMentions ¶
ParseMentions returns the @-names a comment body mentions, in first-seen order and deduplicated.
The grammar is deliberately conservative, because a false positive here starts a job:
- a mention is `@` followed by [A-Za-z0-9_-]+ and NOT preceded by a word character (so `email@x.com` and `foo-@bar` are not mentions, `(@omp)` and `@omp.` are);
- anything inside a fenced code block (```) or an inline code span (`…`) is code being DISCUSSED, not an instruction, and is skipped.
func ParseReportSection ¶
ParseReportSection extracts the list items of the LAST section of an agent's markdown report whose heading names one of titles (gofer-3nxa.3 「发现但不碰」, gofer-3nxa.2 「可复用经验」). A heading matches after dropping emphasis / quote marks and a trailing colon, either exactly or case-insensitively with '-' read as a space; any heading level counts. The section runs to the next heading of the same or a higher level; an item's indented continuation lines are joined to it with a space. Headings inside fenced code blocks are ignored, and a later section replaces an earlier one (the report's end is the answer).
func PlanEventScope ¶
PlanEventScope is the synthetic event-scope id of a plan (`plan:<id>`), mirroring xfer.EventJobID: an event that belongs to no job is still recorded in the shared event log, and its scope is what a reader filters on.
func RandomSuffix ¶
func RandomSuffix() string
RandomSuffix returns 8 lowercase hex chars from crypto/rand, falling back to a nanosecond-derived value if the RNG is unavailable.
func RetryMaxAttempts ¶
func RetryMaxAttempts(rec jobstore.RetryRecord) int
RetryMaxAttempts returns the attempt ceiling a retry row was scheduled under — the M in the `attempt N/M` a human reads — by decoding the policy maybeRetryJob stamped on the row's request. 0 means the row carries no policy (a hand-written row, or one written before the stamp existed), and callers render the attempt without a ceiling rather than inventing one.
func RetryableExitPolicy ¶
func RetryableExitPolicy(p *RetryPolicy, exitCode int) bool
RetryableExitPolicy reports whether a failure with exitCode is retryable under a RetryPolicy.OnExitCodes. An empty/absent OnExitCodes means "retry on any non-zero exit" (the default). When OnExitCodes is set, only those exit codes are retried. Shared by step-level and job-level retry (one semantics).
func ScopeMatch ¶
ScopeMatch reports whether file (a repo-root-relative slash path) is covered by glob: `**` spans any number of path segments, `*` and `?` stay within one segment, and a glob without wildcards also covers everything under it as a directory (`internal/job` = `internal/job/**`). A leading `./` and a trailing `/` are ignored.
func SessionCaptureBy ¶
SessionCaptureBy names WHERE a captured session id came from, for the job.session_captured detail: "agent_config" when the agent's own session_capture produced it (built-in default or explicit config), "fallback" when gofer's generic AGT-04 path did — the generic regex, or the <result_dir>/session_id file. The live pty capture (internal/httpapi) records the same event, so both paths must agree on the literal.
func SkillDest ¶
SkillDest is the result-dir-relative destination of one skill file, e.g. skills/house-rules/SKILL.md. It is exported because the STAGING side (which lives outside this package, next to the transfer manager) must derive the same path the mounting side uses — one definition, no drift.
func SplitInjectedRules ¶ added in v0.162.0
SplitInjectedRules separates the section the server injected from the text the caller actually wrote: body is the prompt with the section removed, injected is the removed section (empty when the prompt carries none).
It exists for the read paths that must show a caller WHAT WAS SENT without drowning it in the rules frame (job detail 消息 list, gofer-chd9): the stripped body is the caller's own words, and the injected text stays available so the UI can offer the full injected text behind a toggle instead of dropping it. Both halves are returned byte for byte, so concatenating them reproduces the prompt (modulo the newline stripRulesSection trims).
func StatusLabelZH ¶ added in v0.163.0
StatusLabelZH is a short Chinese label of a job status, for places that show the status inside a sentence to a person — a delivery that never happened says WHY the machine was not running its job («升级等待(新任务暂停启动)») instead of quoting a status token nobody can read. Unknown values pass through unchanged.
func SyncWaitDuration ¶
SyncWaitDuration is the longest the server may hold a synchronous submit open for a request with wait_timeout_sec=sec (default and hard cap applied). Clients size their HTTP deadline from it (gofer-5foz).
func TitleFromRequestJSON ¶
TitleFromRequestJSON recovers the optional job Title from the persisted request_json blob. The jobs table has no title column (SP5), so the DB read path (fromRecord) parses it back out of the stored JobRequest to keep Title round-tripping through Get/ListJobs.
func Unstarted ¶ added in v0.163.0
Unstarted reports whether a job has NOT begun executing yet: it is waiting for a concurrency slot, a directory lock, an approval, an update's release or crash recovery. Nothing of it has run, so it is the one state a caller may withdraw and still promise that no side effect can arrive later (gofer-qzv5 uses it to make a retry safe: a delivery job that never started cannot deliver the text late).
func WakeupEventTypes ¶
func WakeupEventTypes() []string
WakeupEventTypes returns the v1 event catalog in a stable order (for error messages, the CLI's help text and the MCP tool description).
func WakeupNextRun ¶
func WakeupNextRun(w jobstore.WakeupRecord, afterUnix int64) (int64, error)
WakeupNextRun returns the next fire instant (unix seconds) for a timer wakeup strictly after afterUnix, or 0 for a wakeup that does not repeat (`at`, and every event subscription). An `every` timer counts from the sweep instant — a missed tick is never replayed (design §五.1) — and a cron expression is evaluated in the wakeup's own timezone. The schedule sweep in serve is its only caller.
func WrapUpText ¶ added in v0.158.0
WrapUpText renders a wrap-up reason as the human line `job show` / `job review` / the web detail print. An unknown reason is shown verbatim: a future agent ceiling must still be visible.
Types ¶
type AcceptMemoryCandidateInput ¶
type AcceptMemoryCandidateInput struct {
Key string `json:"key"`
Kind string `json:"kind,omitempty"`
Summary string `json:"summary,omitempty"`
Global bool `json:"global,omitempty"`
Project string `json:"project,omitempty"`
}
AcceptMemoryCandidateInput is how a person files a candidate as a memory. Key is required; Kind is rule | note (default note); the scope is the candidate's project unless Global or Project names another one.
type AdmissionPermit ¶
type AdmissionPermit struct {
// contains filtered or unexported fields
}
AdmissionPermit protects an entire internal claim/advance plus its resulting Submit. A permit belongs to one Service and cannot be serialized or forged by a job request. Call Release once the durable producer transition is complete.
func (*AdmissionPermit) Release ¶
func (p *AdmissionPermit) Release()
func (*AdmissionPermit) Released ¶
func (p *AdmissionPermit) Released() bool
Released lets an asynchronous workflow callback discard an expired admitted view and acquire a fresh permit through its original engine.
type AdoptBackend ¶
type AdoptBackend struct {
// Answer sends a host-side interaction answer for jobID back to the worker process
// so its local job resumes (P2). nil-safe.
Answer func(jobID, interactionID, answer string)
// Cancel tells the worker process to tear down jobID: the host cancelled the job
// while it was adopted, and there is no runner Run left to relay that (RECOV-01 R4).
// nil-safe.
Cancel func(jobID string)
}
AdoptBackend is the transport half of an adopted job, supplied by the assembly layer that owns the hub connection. The host-side half (log files, status, classify/finish) stays in this package; only what needs the wire is injected.
type AdoptedJob ¶
type AdoptedJob struct {
// contains filtered or unexported fields
}
AdoptedJob is the live handle of one job the server adopted after a serve restart (RECOV-01 R4). It plays the same role for an adopted job that internal/runner/worker's sink plays for a dispatched one — the hub demuxes that job's frames into it — but there is no Run goroutine behind it, so the handle itself owns the pieces Run would have: the cancellable context (host cancel), the terminal classify/finish (worker Result or worker-lost), and the log file writers the previous process left behind.
func (*AdoptedJob) Finish ¶
func (a *AdoptedJob) Finish(exitCode int, err error)
Finish delivers the worker's authoritative terminal result for an adopted job: it collects产出, classifies the outcome against the host context and finishes the job. Duplicate results (the worker replays its result after reconnecting) are dropped.
exitCode/err come from the wire projection the assembly layer did (worker status → error), mirroring internal/runner/worker's sink exactly.
func (*AdoptedJob) Offsets ¶
func (a *AdoptedJob) Offsets() (stdoutOff, stderrOff int64)
Offsets returns the byte counts already persisted for each stream — what the hub echoes in the resume ack so the worker replays from exactly the right place.
func (*AdoptedJob) OnDisconnect ¶
func (a *AdoptedJob) OnDisconnect(err error)
OnDisconnect finishes an adopted job failed with err: the worker's recovery window expired, the worker restarted, or the job is otherwise lost. It runs through the same classify/finish path a dispatched job uses, so outcomes, notifications, the jobstore row and workflow advancement all behave identically.
func (*AdoptedJob) OnInteraction ¶
func (a *AdoptedJob) OnInteraction(action string, raw json.RawMessage)
OnInteraction bridges one worker-raised interaction frame onto the adopted job (RECOV-01 R4: the worker keeps running and keeps asking). It mirrors the dispatched path: an `open` injects the interaction on the host job (→ pending_interaction) and a goroutine waits for the host answer to send it back over the wire via the backend. answered/cancelled are state-cleanup actions the host owns; they are ignored.
func (*AdoptedJob) OnJobEvent ¶
func (a *AdoptedJob) OnJobEvent(eventType string, detail map[string]any)
OnJobEvent records one worker-mirrored job event (SUP-01 G) on the adopted job: the worker keeps running it, so its approval gate and verify step keep producing events the host row must record (detail already carries the worker origin).
func (*AdoptedJob) OnOutcome ¶
func (a *AdoptedJob) OnOutcome(o runner.Outcome)
OnOutcome stashes the worker-captured产出 (P4) so the terminal path applies it before finishing the job (nil when the worker sent no outcome frame), latest-wins, and mirrors the dispatched path's G1 behaviour: the first frame carrying a rendered command is pushed onto the running job at once.
func (*AdoptedJob) OnSessionStatus ¶
func (a *AdoptedJob) OnSessionStatus(status, sessionStatus string, turnNo int, idleDeadlineAt int64)
OnSessionStatus applies a later v13 status frame to an adopted job. The hub invokes this on the single read loop, so it shares the same persisted-event deduplication path as the initial register.inflight snapshot.
func (*AdoptedJob) Resume ¶
func (a *AdoptedJob) Resume()
Resume implements the sink contract: the worker process proved it still runs the job, so the job returns to `running` and — for an adopted job — the adoption itself is logged as the reason it is alive again.
func (*AdoptedJob) Suspend ¶
func (a *AdoptedJob) Suspend(reason string) (int64, int64)
Suspend implements the sink contract for an adopted job whose worker connection dropped AGAIN: the job returns to `recovering` under its worker's window and the current offsets travel back to the hub. Idempotent for an already-terminal job.
func (*AdoptedJob) WriteLog ¶
func (a *AdoptedJob) WriteLog(stream string, _ int, text string)
WriteLog appends one mirrored log frame to the adopted job's stdout/stderr file and advances the server-side offset the hub hands the worker on the next reconnect. A failed/short write advances the offset by what actually landed — the offsets must never claim bytes the host does not have.
type AgentBrief ¶
AgentBrief is job's local typed agent capability (key + interactive), the worker-reported detail the G2 admission gate (config.go) needs to judge an agent's interactive-only-ness against the WORKER's OWN definition rather than the host's (tools-c9v — same federation reasoning as Projects/Agents below: the worker's identically-named agent can differ, or not even exist, on the host). Mirrors wsproto.AgentBrief but is redeclared here — and only carries the fields G2 actually gates on — so the job package never imports wshub/wsproto (G022).
type ArtifactItem ¶
type ArtifactItem struct {
Name string `json:"name"` // artifacts/ 下相对路径(可含子目录,'/' 分隔)
Size int64 `json:"size"` // 字节
Mtime int64 `json:"mtime"` // unix 秒
}
ArtifactItem is one entry in a job's产物清单 (E1): a regular file under <result_dir>/artifacts/. Name is the path relative to the artifacts dir (may contain subdir segments, slash-separated); only metadata is captured — the file itself stays on disk and is fetched via the download endpoint.
func ScanArtifacts ¶
func ScanArtifacts(resultDir string) []ArtifactItem
ScanArtifacts is the exported entry point for the live-scan fallback used by the HTTP list endpoint when a job has no persisted manifest (ArtifactsJSON empty). It shares scanArtifacts' semantics (recursive, slash-relative names, skip dirs/symlinks, cap maxArtifacts, missing dir → nil).
type ArtifactManifest ¶
type ArtifactManifest struct {
Items []ArtifactItem
Remote bool
// Source echoes the job's execution location (""=local / worker:<id> /
// peer:<name>) so the caller can build the remote-artifact message.
Source string
}
ArtifactManifest is the resolved artifact view for a job: the manifest items (always non-nil) plus whether the job ran on a remote machine (worker/peer), where its artifact files live — so a byte download from this host is not served (P4 / D6). The HTTP/MCP layers map Remote to a 409.
type BackfillOptions ¶
type BackfillOptions struct {
// Since limits the walk to jobs that ended at or after it (unix seconds; 0 = all).
Since int64
// AfterEnded / AfterID is the cursor the previous batch returned.
AfterEnded int64
AfterID string
// Limit caps the jobs examined in this batch (<= 0 = 100, max 1000).
Limit int
// Force recomputes rows that already exist at the current formula version.
Force bool
// Budget caps the batch's wall time (<= 0 = 15s): the batch stops early and
// returns its cursor, so one HTTP call never outlives the client's deadline.
Budget time.Duration
}
BackfillOptions drives one backfill batch (`gofer tool stats-backfill`).
type BackfillResult ¶
type BackfillResult struct {
Scanned int `json:"scanned"`
Written int `json:"written"`
Failed int `json:"failed"`
WithSignal int `json:"with_signal"`
WithGit int `json:"with_git"`
AfterEnded int64 `json:"after_ended"`
AfterID string `json:"after_id"`
Done bool `json:"done"`
}
BackfillResult is one batch's outcome. Done=false means call again with the cursor.
type Budget ¶
Budget is the config package's spend ceiling, aliased for the job API (JobRequest / JobResult / ResumeOptions) the same way Usage aliases the runner's tally.
type CollectLimits ¶
CollectLimits are the `--collect` byte caps: one file, and the job's total. A zero field means the bridge has no cap for it.
type CollectedPull ¶
type CollectedPull struct {
// JobID is the job the file belongs to (journaled on the transfer, so the audit
// trail says which job a transfer served).
JobID string
// Runner is the EXECUTING machine's transfer runner: the resolved worker id of a
// runner=worker job (the same key the transfer journal routes on).
Runner string
// ProjectKey is the project whose root the name is relative to on that machine.
ProjectKey string
// Name is the file's path relative to the project root ON THE EXECUTING MACHINE.
Name string
// Dst is where THIS machine wants the bytes (absolute, already inside the job's
// artifact directory).
Dst string
}
CollectedPull is one "fetch this collected file" request for the bridge.
type CommentDispatch ¶
type CommentDispatch struct {
Mention string `json:"mention"`
Kind string `json:"kind"`
JobID string `json:"job_id"`
}
CommentDispatch is one job a comment's @-mention started (MCP-05 阶段 A). Kind is "agent" (the mention named an agent) or "role" (it named a role, whose agent the submit resolved) — the caller-facing receipt the CLI, the web thread and MCP all render as "→ 已派发 job <id>".
type Commit ¶
Commit is one commit a job produced (SUP-01 C): the abbreviated sha git prints and its subject line. It is what the todo note quotes and the JobDetail block lists.
type DecisionTrial ¶ added in v0.149.0
type DecisionTrial struct {
Hook string `json:"hook"`
Point string `json:"point"`
Decision string `json:"decision,omitempty"`
Reason string `json:"reason,omitempty"`
Patch json.RawMessage `json:"patch,omitempty"`
// Error is why the run counts as failed (the process, the answer or the patch).
Error string `json:"error,omitempty"`
// Outcome is what gofer would do: the decision, or on_error after a failure.
Outcome string `json:"outcome"`
}
DecisionTrial is one test run of a decision hook (`gofer tool hook-test`).
func TryDecisionHook ¶ added in v0.149.0
TryDecisionHook runs the named hook once with input (a sample stdin) and reports how gofer would read its answer. It changes nothing; the patch is checked for fields and values the point accepts, not against a concrete job.
type DeliverOptions ¶ added in v0.146.0
type DeliverOptions struct {
Mode string // "" = the job's / project's mode
Draft *bool
Branch string // remote branch name ("" = the template)
DryRun bool
}
DeliverOptions overrides a delivery (manual `gofer job deliver`).
type DeliveryPreview ¶ added in v0.148.0
type DeliveryPreview struct {
Mode string `json:"mode"`
Branch string `json:"branch"`
RemoteBranch string `json:"remote_branch"`
Remote string `json:"remote"`
Base string `json:"base"`
Draft bool `json:"draft"`
Labels []string `json:"labels"`
AllowPush bool `json:"allow_push"`
Title string `json:"title"`
Body string `json:"body"`
}
DeliveryPreview contains only the operator-facing fields of a delivery plan.
type DeliveryResult ¶ added in v0.146.0
DeliveryResult is a job's delivery outcome (jobs.delivery_json).
func DeliveryFromJSON ¶ added in v0.152.0
func DeliveryFromJSON(s string) *DeliveryResult
DeliveryFromJSON decodes a stored delivery outcome (jobstore.JobRecord.DeliveryJSON) for read views that only hold the record; nil when empty or undecodable.
type EventTap ¶
EventTap receives EVERY recorded event with its durable row (seq included), for the browser push hub (Q2). It runs synchronously on the recording goroutine, so an implementation must only enqueue: a slow tap would stall recordEvent.
type FallbackState ¶
type FallbackState struct {
Candidates []string `json:"candidates,omitempty"`
Depth int `json:"depth,omitempty"`
}
FallbackState is a job's resolved failover plan (SUP-01 P3), persisted as jobs.fallback_json at submit time: the ordered candidate agents and how many links of the chain are already used. The NEXT candidate is Candidates[Depth]; a Depth of len(Candidates) means the chain is exhausted and the failure is simply terminal.
type HoldState ¶ added in v0.137.0
type HoldState struct {
// Reason is the submitter's why (JobRequest.HoldReason); for an update park it
// names the update the job is waiting for.
Reason string `json:"reason,omitempty"`
// Kind is who the job waits for: "" (a person approving a --hold submit) or
// HoldKindUpdate (the update's own release, see StatusPausedForUpdate).
Kind string `json:"kind,omitempty"`
// TimeoutSec / ExpiresAt: the resolved wait and the deadline fixed at submit.
TimeoutSec int `json:"timeout_sec"`
ExpiresAt int64 `json:"expires_at"`
// Origin says who submitted it: job:<id> (a job credential), agent-session:<id>
// (an agent session), or the submit channel (cli / web / mcp / ...).
Origin string `json:"origin,omitempty"`
// Command is an exec job's argv; PromptPreview the head of an agent job's prompt
// (the caller's text, without the injected rules). Both secret-redacted.
Command []string `json:"command,omitempty"`
PromptPreview string `json:"prompt_preview,omitempty"`
// Decision / DecidedBy / DecidedAt / Note record the outcome once there is one.
Decision string `json:"decision,omitempty"`
DecidedBy string `json:"decided_by,omitempty"`
DecidedAt int64 `json:"decided_at,omitempty"`
Note string `json:"note,omitempty"`
}
HoldState is the public hold record of a job (JobResult.Hold, jobs.hold_json).
type ImportTodo ¶
type ImportTodo struct {
Title string `json:"title"`
Assignee string `json:"assignee,omitempty"`
Cmd string `json:"cmd,omitempty"`
Acceptance string `json:"acceptance,omitempty"`
Scope []string `json:"scope,omitempty"`
After []int `json:"after,omitempty"`
// Step is the 1-based gofer-todos step this item comes from.
Step int `json:"step"`
}
ImportTodo is one todo `plan import` creates, in creation order. After are indexes into the same slice (always earlier ones). A step's check becomes its own exec item (Assignee exec, Cmd the command line) right after it.
func BuildTodoImport ¶
func BuildTodoImport(specs []PlanTodoSpec, assign string) ([]ImportTodo, error)
BuildTodoImport turns parsed steps into the todos to create, in order: each step one item (assigned to assign, "" = nobody yet), then — when it has a check — an exec item running the check after it. A reference to an earlier step (its title or 1-based number) resolves to that step's check item when it has one, so a checkpoint gates everything after it. An omitted `after` means the previous step; a reference to the step itself or a later one is refused (a step never uses what a later step creates).
type Interaction ¶
type Interaction struct {
ID string `json:"id"`
JobID string `json:"job_id"`
Type string `json:"type"` // question | choice | confirmation | permission
Prompt string `json:"prompt"`
Options []InteractionOption `json:"options,omitempty"`
Status string `json:"status"` // pending | answered | cancelled
Answer string `json:"answer,omitempty"`
CreatedAt int64 `json:"created_at"`
AnsweredAt int64 `json:"answered_at,omitempty"`
// ToolCall and PolicyHint describe a type=permission interaction (GATE-01 §1): the
// tool call awaiting approval and the policy that stopped it ("ask: kind=edit").
// Both are absent on every other interaction type.
ToolCall *InteractionToolCall `json:"tool_call,omitempty"`
PolicyHint string `json:"policy_hint,omitempty"`
// ExpiresAt is the unix-second deadline of a type=permission interaction — when the
// approval gate stops waiting and applies on_timeout. 0 = no deadline (every other
// interaction type, and a request the runner raised without one).
ExpiresAt int64 `json:"expires_at,omitempty"`
// AnsweredBy 记录"谁应答了该 interaction"(监督分层升级路由 P3.2, design §10 审计区分):
// auto:<policy>(L0 内置规则器) / agent:<id>(L1 owner / L2 sup) / human(L3 web/CLI)。
// "" 表示尚未应答或未归因(内部 relay)。gofer_get_interactions / 查询接口可见。
AnsweredBy string `json:"answered_by,omitempty"`
// NeedsHuman 标记该 interaction 已被通用 sup 判为高危/拿不准、显式留给人处理(事件驱动按需
// 派发 y5wt):1=留给人。0=未标记。interaction 仍 pending(待人应答)。
NeedsHuman int64 `json:"needs_human,omitempty"`
}
Interaction is one running-job interaction event (plan §P9). Persisted (SP4) as a single upserted row in the SQLite interactions table (the latest snapshot per id wins); the live in-memory state in jobEntry is authoritative while the job is tracked.
type InteractionInput ¶
type InteractionInput struct {
Type string
Prompt string
Options []InteractionOption
// ToolCall / PolicyHint are carried onto a type=permission interaction (GATE-01
// §1) and ignored by every other type.
ToolCall *InteractionToolCall
PolicyHint string
// ExpiresAt is the permission interaction's answer deadline (unix seconds, 0 =
// none) — the callers' own deadline, carried through so answerers can show it.
ExpiresAt int64
}
InteractionInput is the create-interaction payload (Type/Prompt/Options, plus the approval detail of a type=permission interaction).
type InteractionOption ¶
type InteractionOption struct {
Value string `json:"value"`
Label string `json:"label,omitempty"`
// ID is the ACP optionId of a permission interaction's option. It mirrors Value
// (the answer token every generic path — web button, CLI, MCP, the answer guard —
// already round-trips) so a consumer that speaks ACP can address the option by its
// protocol id. "" for non-permission interactions.
ID string `json:"id,omitempty"`
// Kind is the ACP option kind (allow_once|allow_always|reject_once|reject_always)
// the approval card groups its buttons by. "" for non-permission interactions.
Kind string `json:"kind,omitempty"`
}
InteractionOption is one selectable option for a choice/confirmation — or, for a permission interaction, one option the ACP agent offered (GATE-01 §1).
type InteractionToolCall ¶
type InteractionToolCall struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Kind string `json:"kind,omitempty"`
Locations []string `json:"locations,omitempty"`
// RawInputSummary is the agent's rawInput, summarised and capped (the full input
// can be megabytes; an approver needs the shape, not the payload).
RawInputSummary string `json:"raw_input_summary,omitempty"`
}
InteractionToolCall is the tool call a permission interaction is about: the agent's ACP toolCall, reduced to what an approver needs to judge it (GATE-01 §1).
type IssueLinker ¶
IssueLinker mirrors the todo lifecycle for repository tracker issues. The job service owns ordering; transports only bind request fields and permissions.
type JobEndedHook ¶ added in v0.160.0
type JobEndedHook func(JobResult)
JobEndedHook observes a job that has ENDED — a terminal state (done / failed / timeout / cancelled / rejected), or a delivery PARKED for a human's review (needs_review), which the terminal hook below deliberately does not see.
It exists for the end-notification (gofer-3db4): whoever sent a job wants to hear that it stopped, and "it stopped, waiting for your review" is exactly the case they must not miss. Unlike JobTerminalHook the hook therefore fires for needs_review too, and a later accept/reject fires it AGAIN — the notification itself is deduplicated by its own durable record (see sessionrelay.NotifyJobEnded), so a hook must not assume it runs once per job.
Like the terminal hook it runs after the outcome is durable, in its own goroutine: it can neither delay nor change the job's ending, and a panicking or slow hook is logged and swallowed.
type JobEventObserver ¶
JobEventObserver receives the events a REMOTE executor mirrors to the machine that submitted the job (SUP-01 G). The worker client installs one (see worker.Client) so the events its local job service records for a DISPATCHED job ride the hub connection back to the host job, which would otherwise never see them. It must never block the job: an implementation is a bounded queue that drops on overflow.
type JobRequest ¶
type JobRequest struct {
ProjectKey string `json:"project_key" yaml:"project_key"`
Agent string `json:"agent" yaml:"agent"`
Runner string `json:"runner" yaml:"runner"`
Prompt string `json:"prompt,omitempty" yaml:"prompt,omitempty"`
// AgentArgs are extra CLI flags appended to a cli-agent's argv at build time.
// Ignored for exec agents (§14). Persisted in request_json for rerun/replay.
AgentArgs []string `json:"agent_args,omitempty" yaml:"agent_args,omitempty"`
Cmd []string `json:"cmd,omitempty" yaml:"cmd,omitempty"`
// Model names the model the agent should use (N1 §B; `job run --model`, task-book
// `model`, plan todo model, HTTP/MCP `model`). A cli-agent renders its model_args
// ({{model}}) before the prompt argument; an acp-agent picks it over the protocol
// after the session opens (session config option / set_model). Empty = the agent's
// own default, with the argv exactly as before. Recorded in request_json, mirrored
// on JobResult.Model, and inherited by a resume (which may override it).
Model string `json:"model,omitempty" yaml:"model,omitempty"`
// FromSession (gofer-f4z8, `job run --from-session`, HTTP/MCP `from_session`) opens a
// NEW agent session that inherits an earlier session's context — a light
// alternative to resume, which continues the SAME session. A cli-agent appends its
// from_session_args ({{from_session}}) to the argv; the new session id is still
// injected/captured as for any job. An agent without from_session_args, and any
// continuation (session_id / resumed_from), refuse it. Recorded in request_json and
// mirrored on JobResult.FromSession; a resume of the new session does not carry it.
FromSession string `json:"from_session,omitempty" yaml:"from_session,omitempty"`
// Acceptance is the job's acceptance criteria (free text, usually a markdown list;
// `job run --acceptance`, a plan todo's acceptance, HTTP/MCP `acceptance`). Submit
// appends it to a non-exec agent's prompt as a 「## 验收标准」 section (once — see
// injectPromptSections); the review panel shows it next to the report. Recorded in
// request_json and mirrored on JobResult.Acceptance.
Acceptance string `json:"acceptance,omitempty" yaml:"acceptance,omitempty"`
// Scope are the path globs (relative to the repository root of the job's cwd) this
// job is expected to change (gofer-3nxa.3; `job run --scope`, a plan todo's scope,
// HTTP/MCP `scope`). They are named in the 「交付约定」 section, and the review marks
// changed files outside them — advisory only, never blocking an accept.
Scope []string `json:"scope,omitempty" yaml:"scope,omitempty"`
// NoScopeDiscipline turns the project's scope_discipline off for this job
// (`--no-scope-discipline`): no 「交付约定」 section is appended.
NoScopeDiscipline bool `json:"no_scope_discipline,omitempty" yaml:"no_scope_discipline,omitempty"`
// KnowledgeCapture records that the 「交付约定」 section asked this job for a
// 「## 可复用经验」 report section (gofer-3nxa.2, project knowledge_capture), so its
// finish parses the report into memory candidates. Decided by Submit (a caller's
// value is overwritten), recorded in request_json, inherited by a continuation and
// mirrored on JobResult.KnowledgeCapture.
KnowledgeCapture bool `json:"knowledge_capture,omitempty" yaml:"-"`
// Budget is the job's spend ceiling (N2 §B GATE-02; `job run --max-tokens /
// --max-cost / --max-turns`, task-book `budget`, plan todo, HTTP/MCP `budget`). The
// EXECUTING machine meters the agent's streamed accounting against it and kills the
// job (failed, failure_class=budget) the moment a limit is crossed. Submit resolves
// the layered defaults (agent < project < this) into it, so request_json records
// the decided value; a resume inherits it (and may override it). nil = unlimited.
Budget *Budget `json:"budget,omitempty" yaml:"budget,omitempty"`
// BudgetFixed marks a budget that is already the decided value (a worker's copy of a
// dispatch whose hub resolved the layered defaults): Submit then does not merge this
// machine's agent / project defaults into it. Internal; never on the wire.
BudgetFixed bool `json:"-" yaml:"-"`
// Cwd is the job's working directory, relative to the project root. Under
// --worktree it is mapped into the job's worktree (see Worktree).
Cwd string `json:"cwd,omitempty" yaml:"cwd,omitempty"`
// LockPaths narrows the directory lock to project-relative paths. Empty keeps
// the existing cwd lock behavior. ResolvedLockPaths is server-side only.
LockPaths []string `json:"lock_paths,omitempty" yaml:"lock,omitempty"`
ResolvedLockPaths []string `json:"-" yaml:"-"`
// Worktree (WT-01) runs the job in a MANAGED git worktree of the project
// checkout instead of the checkout itself: gofer creates
// <repo top>/tmp/gofer/wt/<job-id> on a fresh branch gofer/<job-id> at
// WorktreeBase, runs the whole job there (cwd mapped by the same relative
// sub-path, env GOFER_WORKTREE/_BRANCH/_BASE exported) and KEEPS it afterwards
// (the branch is the deliverable). It is what lets several agent jobs edit and
// commit in one checkout in parallel without fighting over .git/index.lock.
// Rejected when the resolved cwd is not inside a git checkout. A project may
// turn it on for every job with worktree_default: true.
Worktree bool `json:"worktree,omitempty" yaml:"worktree,omitempty"`
// WorktreeBase is the ref the worktree branch starts at (WT-01). Empty = the
// checkout's current HEAD. Only meaningful together with Worktree.
WorktreeBase string `json:"worktree_base,omitempty" yaml:"worktree_base,omitempty"`
TimeoutSec int `json:"timeout_sec,omitempty" yaml:"timeout_sec,omitempty"`
// Session keeps an ACP agent process alive across prompt turns.
Session bool `json:"session,omitempty" yaml:"session,omitempty"`
IdleTimeoutSec int `json:"idle_timeout_sec,omitempty" yaml:"idle_timeout_sec,omitempty"`
MaxSessionSec int `json:"max_session_sec,omitempty" yaml:"max_session_sec,omitempty"`
// Messenger is an internal worker dispatch hint. Cmd remains populated so a
// v13 worker executes the marked one-shot fallback while v14 handles this
// payload with its resident process.
Messenger *runner.MessengerDispatch `json:"-" yaml:"-"`
// MessengerMeta is the audit projection for a web-to-agent messenger job.
// It contains no credentials and is persisted in request_json so job detail
// can show what was sent even after the in-memory job is gone.
MessengerMeta *MessengerMeta `json:"messenger,omitempty" yaml:"-"`
Title string `json:"title,omitempty" yaml:"title,omitempty"`
// Template is the task-book template this job's prompt is rendered from
// (SUP-01 P5, design §六): a <name>.md under <project>/.gofer/templates/ or
// <config-dir>/templates/ that the SERVER resolves and renders at submit. Prompt
// then holds the RENDERED text — the only thing an executing machine (or a rerun)
// ever needs — while Template/TemplateVars ride along in request_json so the
// audit trail says which task book (and which variable values) produced it.
Template string `json:"template,omitempty" yaml:"template,omitempty"`
// TemplateVars are the {{var}} values supplied with Template (`job run --var k=v`,
// HTTP/MCP `vars`). A declared var the submitter omits falls back to its default;
// a REQUIRED one with neither rejects the submit.
TemplateVars map[string]string `json:"vars,omitempty" yaml:"vars,omitempty"`
// Interactive requests a pty-attached run (WEB-03, design §5/§8): the job
// service routes an interactive job to the pty runner variant (when a pty
// backend is registered) instead of req.Runner, so its stdin/stdout is a raw
// terminal a browser can attach to. Non-interactive (the default false) is
// byte-for-byte the existing path (G023). Cols/Rows are the INITIAL terminal
// size (default 80x24). NOTE (spike): admission gating (interactive白名单 /
// no-raw-cmd / reject exec+workflow+schedule) and threading Cols/Rows through
// runner.Request land in P1 — P0 only wires the runner-selection seam.
Interactive bool `json:"interactive,omitempty" yaml:"interactive,omitempty"`
// ReadOnly (bd h-aii-0ql3) asks for a job that cannot write: a cli-agent gets its
// read-only argv suffix (config read_only_args, built-in for codex/claude), an
// acp-agent gets session/set_mode with the id mapped by acp.modes.read_only, and
// an exec agent is refused (its argv is whatever the caller wrote). It is
// persisted (jobs.read_only) and inherited by a resume — a continuation cannot be
// upgraded to writable, only a new job can.
ReadOnly bool `json:"read_only,omitempty" yaml:"read_only,omitempty"`
// Review (GATE-01 S3) asks for人工验收: when the agent finishes NORMALLY (done),
// the job parks in `needs_review` instead of done until a HUMAN accepts (→done)
// or rejects (→rejected) it — an agent never signs off its own work. Set by
// `job run --review` / the HTTP body's review field, or resolved from the
// project's require_review default at submit (see ReviewFixed). A failure
// (failed/cancelled/timeout) never enters review.
Review bool `json:"review,omitempty" yaml:"review,omitempty"`
// ReviewFixed marks Review as FINAL: it was set by an explicit workflow-step
// override (StepSpec.Review), which must beat the project's require_review default
// for a `review: false` step too — a plain bool cannot tell "explicitly off" from
// "unset". Internal: json/yaml "-" keeps it off the wire and out of request_json,
// mirroring WorkflowID/StepIndex.
ReviewFixed bool `json:"-" yaml:"-"`
// Hold (gofer-9b1b, `job run --hold`) parks the admitted job in awaiting_approval
// instead of starting it: nothing runs, no concurrency slot or directory lock is
// taken, until a HUMAN approves it (it then runs under the same id) or rejects it /
// lets it expire (cancelled). It rides request_json, so a rebuild, a retry, a
// schedule or a resume of a held job is held again — an approval covers one run.
Hold bool `json:"hold,omitempty" yaml:"hold,omitempty"`
// HoldReason is the submitter's why ("push the release branch"), shown to the
// approver. Only meaningful with Hold.
HoldReason string `json:"hold_reason,omitempty" yaml:"hold_reason,omitempty"`
// HoldTimeoutSec bounds the wait for a decision: 0 takes server.hold.default_timeout_sec,
// a value above server.hold.max_timeout_sec (or a negative one) is refused. The
// deadline is fixed at submit; the expiry sweep cancels the job when it passes.
HoldTimeoutSec int `json:"hold_timeout_sec,omitempty" yaml:"hold_timeout_sec,omitempty"`
// Verify is the job's验证步骤 (SUP-01 B): an argv run AFTER the agent finishes
// normally (exit 0), on the same machine, in the job's cwd/env — the check that
// turns "the agent says it worked" into evidence. It is resolved at submit from
// --verify or the project's `verify` default, so the Forward, request_json and
// the persisted row all carry ONE decided value (an empty slice = no step, which
// is what --no-verify leaves behind). The argv is executed verbatim, never through
// a shell (write `bash -lc '…'` if you need one, exactly like an exec job), and
// its exit status decides the job's when it fails.
Verify []string `json:"verify,omitempty" yaml:"verify,omitempty"`
// VerifyTimeoutSec bounds that step, independently of the job's own deadline
// (0 = resolved at submit: the project's verify_timeout_sec, else 600s).
VerifyTimeoutSec int `json:"verify_timeout_sec,omitempty" yaml:"verify_timeout_sec,omitempty"`
// NoVerify turns the PROJECT's verify default off for this job (SUP-01 B).
// It only means something when the project declares one; combined with an
// explicit Verify it is a contradiction and the submit is rejected.
NoVerify bool `json:"no_verify,omitempty" yaml:"no_verify,omitempty"`
// Uploads are files that travel WITH this job (XFER-01 X2): each names a transfer
// already staged in the server's transfer area and the path the EXECUTING machine
// must place it at, relative to the job's cwd. They are materialized BEFORE the
// agent starts; a failed upload fails the job (the agent never runs on a cwd the
// caller did not describe). `job run --upload ./a.bin:tmp/in/a.bin` stages the
// file and fills this in; the HTTP/MCP surfaces accept only staged transfer ids —
// never a client-side path.
Uploads []UploadSpec `json:"uploads,omitempty" yaml:"uploads,omitempty"`
// Collect are globs matched against the job's cwd AFTER it ends (on failure too,
// and after the verify step): every match is uploaded to the server and lands in
// this job's artifacts as collected/<project-root-relative path>, so
// `GET /v1/jobs/{id}/artifacts/collected/...` and the web preview serve it. A file
// over the transfer's byte cap is skipped and listed rather than dropped silently.
Collect []string `json:"collect,omitempty" yaml:"collect,omitempty"`
// Skills are the working-method documents this job carries (JOB-10). Submit
// resolves them from the four binding levels — server.skills, the agent's skills,
// the project's skills and this request's own `--skill` — as a UNION (decision 2:
// skills stack, unlike the retry policy's nearest-level override) and writes the
// result back here, so request_json, the persisted row, the Forward and the
// executing machine all carry ONE decided list and a rerun repeats it.
Skills []string `json:"skills,omitempty" yaml:"skills,omitempty"`
// NoSkills turns every binding off for this job (`--no-skills`, decision 2): an
// empty result is a decision, not an omission.
NoSkills bool `json:"no_skills,omitempty" yaml:"no_skills,omitempty"`
// SkillsResolved marks Skills as FINAL: the SUBMITTING machine already resolved
// the union, so the machine that runs the job must mount exactly this list and
// never re-derive one from its own config (which may name a different library).
// The worker dispatch path sets it; internal, so it stays off the wire, out of
// request_json and out of a client-supplied body.
SkillsResolved bool `json:"-" yaml:"-"`
// MCP are the registry MCP servers this job is bound to (MCP-06): Submit resolves
// the union of server.mcp, the agent's and project's lists and this request's own
// `--mcp` names, and writes the final list back here (names only — never values).
MCP []string `json:"mcp,omitempty" yaml:"mcp,omitempty"`
// Secrets names the secrets (top-level `secrets`, allowed by projects.<p>.secrets)
// the job receives in its environment (JOB-06②). Only the names are recorded; the
// executing machine resolves the values and masks them in the job's logs.
Secrets []string `json:"secrets,omitempty" yaml:"secrets,omitempty"`
// NoMCP turns every registry binding off for this job (`--no-mcp`). gofer's own
// MCP for the steward / leader jobs is not affected.
NoMCP bool `json:"no_mcp,omitempty" yaml:"no_mcp,omitempty"`
// MCPResolved marks MCP as FINAL and MCPSpecs as its declarations: set on a
// dispatched job, whose executing machine has no registry of its own. Internal.
MCPResolved bool `json:"-" yaml:"-"`
MCPSpecs map[string]config.MCPServerConfig `json:"-" yaml:"-"`
// Deliver overrides the project's delivery mode for this worktree job (GIT-02):
// none | merge | push | pr. DeliverDraft / DeliverBranch override the request's
// draft flag and the pushed branch name.
Deliver string `json:"deliver,omitempty" yaml:"deliver,omitempty"`
DeliverDraft *bool `json:"deliver_draft,omitempty" yaml:"deliver_draft,omitempty"`
DeliverBranch string `json:"deliver_branch,omitempty" yaml:"deliver_branch,omitempty"`
// Rules are the MANDATORY rules this job carries (JOB-06①, design §一.2). Submit
// resolves them from the four binding levels — server.rules, the agent's rules, the
// project's rules and this request's own `--rule` — as a UNION (like skills, unlike
// the retry policy's nearest-level override), appends the project's `.gofer/RULES.md`
// as `project:<key>`, writes the result back here, and injects the rendered section
// into Prompt. So request_json, the persisted row, the Forward and the executing
// machine all carry ONE decided set, and a rerun re-reads the current text.
Rules []string `json:"rules,omitempty" yaml:"rules,omitempty"`
// NoRules turns every binding off for this job (`--no-rules`): an empty result is a
// decision, not an omission. Only a user caller may set it — a job credential
// submitting a job cannot switch off the discipline that governs it (design 决策 4;
// enforced at the HTTP boundary).
NoRules bool `json:"no_rules,omitempty" yaml:"no_rules,omitempty"`
// PrimeKeywords names the subsystems / languages / modules this task touches
// (gofer-11tz): the tracker-prime the server injects matches them — together with
// the job's title and the head of its prompt — against the memories' when.keywords,
// keys, tags and summaries, so the material for this task is injected in full and
// ranked first while everything else stays listed. Set by `--prime-keywords`, or by
// GOFER_PRIME_KEYWORDS when the flag is absent; empty = the plain cwd-scoped prime.
PrimeKeywords []string `json:"prime_keywords,omitempty" yaml:"prime_keywords,omitempty"`
// RulesResolved marks the rules as FINAL and NOT to be resolved (or injected)
// here: set by the worker dispatch re-entry and by a resume's continuation (whose
// session already carries the rules the source job was given). Internal — json/
// yaml "-" keeps it off the wire so no caller can skip the injection or its size
// check by forging it.
RulesResolved bool `json:"-" yaml:"-"`
// LeaderOfPlan marks this job as the LEADER of that plan (MCP-05 阶段 B): the leader
// round sets it, and it is what makes the job's @-comments dispatchable, keeps its
// own terminal state from waking another leader, and bars it from accepting or
// rejecting a delivery. Internal and server-set — json/yaml "-" keeps it off the
// wire and out of request_json, exactly like ReviewFixed/WorkflowID, so no caller
// can promote itself to leader.
LeaderOfPlan string `json:"-" yaml:"-"`
// Steward marks this job as the W2b STEWARD's resident session: it gets the steward
// credential kind (a narrow, default-deny route allowlist) and the gofer MCP injected
// into its ACP session. Internal and server-set — json/yaml "-" keeps it off the wire
// and out of request_json, so no caller can promote a job to steward; the durable
// marker is jobstore's steward_jobs row (read back when a session is recovered).
Steward bool `json:"-" yaml:"-"`
// JobToken is the job-scoped credential (SEC-01) the executing process injects as
// GOFER_JOB_TOKEN. It is server-set on both paths and never a client input:
// - a hub-local job is minted one by Submit itself (issueJobToken);
// - a dispatched job receives the hub's token on the dispatch frame, and the
// worker's Submit injects that one (CredentialExternal below).
// json/yaml "-" keeps it off the wire (the dispatch frame has its own field) and,
// critically, OUT of request_json: the credential must never be persisted or
// echoed back by `job show --request`.
JobToken string `json:"-" yaml:"-"`
// CredentialExternal marks a Submit that is RE-ENTERING from another machine — the
// worker's dispatch handler. The credential was minted by the HUB and arrived in
// JobToken above, so this process must not mint one of its own: it has no authority
// over a job id that lives in someone else's store, and a second credential for the
// same job would be one nobody can revoke. Empty JobToken + this flag is the
// pre-v11 worker case: the job simply runs without a credential.
CredentialExternal bool `json:"-" yaml:"-"`
// ExclusiveDir overrides the same-directory lock rule for this job (JOB-11): nil
// (the default) applies the rule — a WRITABLE agent job (cli/acp, not read-only,
// not interactive) takes the exclusive lock of its working directory, while exec
// and read-only jobs share it. `--exclusive-dir` forces the lock (an exec job
// included), `--shared-dir` gives it up. Submit resolves it ONCE and persists the
// decided value (request_json + jobs.dir_exclusive), so a reload cannot change
// what an already-submitted job does — and a remote executor applies the hub's
// decision instead of re-deriving one from its own config.
ExclusiveDir *bool `json:"exclusive_dir,omitempty" yaml:"exclusive_dir,omitempty"`
// StallTimeoutSec is the AUTO-05 output-stall window in seconds for THIS job: a
// non-interactive job that produces no stdout/stderr (and no acp update) for that
// long is killed and failed as stalled. nil = resolve the default (agent override
// > server.stall_timeout_sec > 900s for an agent job, 0 = OFF for an exec job —
// builds and test suites are silent for long stretches by nature). 0 = explicitly
// off. `job run --stall-timeout <sec>` sets it; an interactive job is never
// watched. Resolved at submit and carried to the execution machine, which applies
// the decision instead of re-deriving one from its own config.
StallTimeoutSec *int `json:"stall_timeout_sec,omitempty" yaml:"stall_timeout_sec,omitempty"`
// LockWaitSec overrides the server's directory-lock wait cap for this job.
// nil inherits the server value; 0 waits until unlocked or cancelled.
LockWaitSec *int `json:"lock_wait_sec,omitempty" yaml:"lock_wait_sec,omitempty"`
// DEPRECATED(v0.83): remove in v0.86. This field remains for the existing
// server-to-worker dispatch wire until that wire is renamed; new callers use
// lock_wait_sec. The submit path rejects conflicting values.
// DirWaitMaxSec is how long THIS job may queue for the same-directory lock before
// it is failed, in seconds (JOB-11, F12 fix): nil = resolve (server.dir_lock_max_wait_sec
// > 3600s), 0 = wait until the lock is free or the job is cancelled. Resolved at
// submit and carried to the execution machine, which applies the decision instead
// of re-deriving one from its own config — the same rule as ExclusiveDir and
// StallTimeoutSec above.
DirWaitMaxSec *int `json:"dir_wait_max_sec,omitempty" yaml:"dir_wait_max_sec,omitempty"`
Cols int `json:"cols,omitempty" yaml:"cols,omitempty"`
Rows int `json:"rows,omitempty" yaml:"rows,omitempty"`
// InitialInput is text the pty runner types into an INTERACTIVE job's stdin
// once its terminal has settled (session relay §9.1 B: the first message of a
// `--resume` takeover). Internal: json/yaml "-" keeps it off the wire and out
// of request_json (it is one-shot text, not a reusable request property); the
// worker path carries it in wsproto.Dispatch.InitialInput instead. Renaming a
// request property would be the caller's fault, so the value is never rendered
// into argv — it goes to the child as terminal INPUT.
InitialInput string `json:"-" yaml:"-"`
// InitialInputQuietMs is the quiet window that decides when that text is
// written (see runner.Request.InitialInputQuietMs). Internal for the same
// reason; a dispatched worker receives the hub's resolved value.
InitialInputQuietMs int `json:"-" yaml:"-"`
// Stdin is text piped to a NON-interactive job's standard input (the relay's
// deliver_command with deliver_stdin: the reply text, kept out of argv). Internal
// like InitialInput: never on the wire or in request_json; a dispatched worker gets
// it in wsproto.Dispatch.Stdin (protocol v18).
Stdin string `json:"-" yaml:"-"`
// RecordPty requests asciinema recording for this interactive pty session.
// It is a per-job opt-in layered under the serve-wide storage.cast.enabled
// capability; false means "track session metadata only, do not write pty.cast".
RecordPty bool `json:"record_pty,omitempty" yaml:"record_pty,omitempty"`
// Role is an OPTIONAL E35 role-preset reference (design §8.5). When set, submit
// resolves it from cfg.Roles to fill empty Agent/SystemPrompt/ProjectKey/Tags
// (explicit request fields win). An unknown role is rejected (ErrUnknownRole).
Role string `json:"role,omitempty" yaml:"role,omitempty"`
// SystemPrompt is the resident system prompt injected via the agent's
// SystemInject template (E35). Set directly, or filled from the role preset; on
// submit it is rendered into argv (e.g. claude --append-system-prompt). It is
// persisted in request_json so resume can re-apply it (review #5).
SystemPrompt string `json:"system_prompt,omitempty" yaml:"system_prompt,omitempty"`
// Env is OPTIONAL per-job env layered onto the agent process env: it sits ON TOP
// of the agent-config env (AgentConfig.Env) but UNDER the gofer-owned job
// metadata (GOFER_JOB_ID/CWD/RESULT_DIR), so a job can pass extra vars to its
// agent process (local runner; see Submit). A role preset (RoleConfig.Env) fills
// it as a DEFAULT — an explicit per-job key wins (resolveRole). The main use is
// `--role supervisor` injecting GOFER_AGENT_ROLE=supervisor for the MCP
// self-register (P3). 勿放 secret:本字段随 request_json 落库(SR403/SR805),secret
// 应改走 agent.env / K8s secret 注入(不入 request_json)。
Env map[string]string `json:"env,omitempty" yaml:"env,omitempty"`
// EnvDenyExtra is an internal execution policy extension. It is never caller
// supplied or persisted; internal bridge jobs use it to remove nested-agent
// detection variables from the child environment.
EnvDenyExtra []string `json:"-" yaml:"-"`
// EnvFiles declares non-sensitive dotenv file paths whose loaded values are
// injected only into the execution env. The file list itself may be persisted
// in request_json; loaded values must never be written back to Env/request_json.
EnvFiles []string `json:"env_files,omitempty" yaml:"env_files,omitempty"`
// WorkerID selects which registered worker a runner=worker job dispatches to
// (ws-worker §8). When set it must be a known server.workers entry (explicit
// routing wins); ignored for local/peer-http runners. When empty for a worker
// runner, WorkerLabels (if any) drives auto-selection (D3), else the runner's
// configured default worker is used (D4 fallback).
WorkerID string `json:"worker_id,omitempty" yaml:"worker_id,omitempty"`
// WorkerLabels auto-selects a worker by labels when runner=worker and WorkerID
// is empty (D3): a candidate worker must advertise ALL these labels. Ignored
// when WorkerID is set (explicit routing wins).
WorkerLabels []string `json:"worker_labels,omitempty" yaml:"worker_labels,omitempty"`
// Sync requests synchronous submit: the HTTP handler blocks until the job is
// terminal (capped server-side) and returns the final JobResult. Can also be
// set via ?wait=1. WaitTimeoutSec overrides the default wait cap (clamped).
Sync bool `json:"sync,omitempty" yaml:"sync,omitempty"`
WaitTimeoutSec int `json:"wait_timeout_sec,omitempty" yaml:"wait_timeout_sec,omitempty"`
// CallerID is the authenticated submitter id (C2). It is set server-side by
// the HTTP layer from the auth context (any client-supplied value is
// overwritten); it is not part of the client-facing contract. yaml:"-" keeps
// md frontmatter from forging the caller id (design §9).
CallerID string `json:"caller_id,omitempty" yaml:"-"`
// SourceSessionID is the authenticated terminal session that submitted this job.
// It is distinct from SessionID, which selects the agent's own resumable session.
SourceSessionID string `json:"source_session_id,omitempty" yaml:"source_session_id,omitempty"`
// Notify (gofer-3db4, `job run --notify`, `plan create --notify`, HTTP/MCP `notify`)
// asks gofer to TELL the submitting session when this job ends, through the session
// messenger (sessionrelay.SendMessage) instead of waiting for that session's hook to
// notice. It is off by default on purpose: every notice starts one messenger process,
// so it is paid for only where a caller asked for it. The target is NotifySession when
// set, else SourceSessionID; with neither, Submit refuses (gofer cannot guess whom to
// tell). Recorded in request_json, inherited by a continuation.
Notify bool `json:"notify,omitempty" yaml:"notify,omitempty"`
// NotifySession names the session to notify (`job run --notify-session <sid>`, HTTP/MCP
// `notify_session`). It IMPLIES Notify and is the way to notify a session that is not
// the job's trusted source: the CLI's env-detected session, a supervisor whose terminal
// is on another machine, or a continuation (whose source link is dropped).
NotifySession string `json:"notify_session,omitempty" yaml:"notify_session,omitempty"`
// UpdateExempt marks gofer's own short control-plane work — a session-relay
// delivery / injection, a session messenger — which must keep running while an
// update waits for the server to go idle. Parking it would lose exactly what the
// pause protects (a web reply that never lands, gofer-3db4's job-ended notice),
// and the job is too short to stand in the way of the restart the update wants.
// Human work still parks. Server-set, never on the wire (json/yaml "-"), like
// NotifyDegradable.
UpdateExempt bool `json:"-" yaml:"-"`
// NotifyDegradable marks an end-notification that gofer itself asked for on somebody
// else's behalf: a scheduled run, a plan dispatch, a workflow step, a wakeup / auto-
// resume / rerun continuation. For such a submit an unusable target (an unknown
// session, one owned by another caller, or none at all) DROPS the notification —
// recorded as a job.notify_dropped event — and the work is submitted anyway;
// refusing it would lose a job nobody was asked about because a notice could not be
// addressed. A caller naming the flag itself (CLI `job run`, POST /v1/jobs, the MCP
// submit tool) is NOT degradable: their mistake is reported as a 400. Server-set,
// never on the wire (json/yaml "-"), like ReviewFixed / SkillsResolved.
NotifyDegradable bool `json:"-" yaml:"-"`
// RequestID is the optional client-supplied idempotency key (C5, e.g. a
// UUID). When set, re-submitting the same RequestID returns the existing job
// instead of creating a new one (deduped by the jobs.request_id unique index).
RequestID string `json:"request_id,omitempty" yaml:"request_id,omitempty"`
// PlanID is the client-settable grouping key (plan-orchestration P1). Unlike
// WorkflowID/StepIndex, it is not engine-private: clients may attach a job to a
// plan at submit time via JSON, YAML, CLI, or future MCP inputs.
PlanID string `json:"plan_id,omitempty" yaml:"plan_id,omitempty"`
// TodoID is the client-settable checklist key (SUP-01 C): the plan todo this job
// is run for. Submit resolves the plan FROM the todo when PlanID is empty (and
// refuses a contradiction), marks the todo `doing`, and the terminal hooks write
// the outcome back into its note. Empty == not attached to a checklist item.
TodoID string `json:"todo_id,omitempty" yaml:"todo_id,omitempty"`
IssueID string `json:"issue_id,omitempty" yaml:"issue_id,omitempty"`
TrackerID string `json:"tracker_id,omitempty" yaml:"tracker_id,omitempty"`
// TodoForeign marks a todo that belongs to the FORWARDING hub rather than this
// process's store (set only by the worker's dispatch re-entry): plan todos are
// hub-managed, so this side displays the id and links nothing — the hub applies
// the outcome to its own row.
TodoForeign bool `json:"-" yaml:"-"`
// SourceJobID is the lineage key set ONLY by ResumeJob / RebuildJob (P5): it points
// the new job back to its SOURCE job id. Like ResumeSourceAgent (model.go:163) it is
// json/yaml "-": it is NEVER written from a client body (c.BindJSON can't set it) nor
// from md frontmatter, and it does NOT round-trip through request_json. UNLIKE
// ResumeSourceAgent (whose "-" is a SECURITY requirement — it exempts allow_exec),
// here "-" is chosen to ELIMINATE the forge surface: the URL /jobs/{id}/rebuild
// already carries the authoritative source id, so the server stamps it internally
// (submit copies it into the JobResult → jobs.source_job_id via a plain Go assignment,
// which the json tag does not affect). Empty == not derived.
SourceJobID string `json:"-" yaml:"-"`
// Tags are free-form labels for the job (E5). They are persisted (jobs.tags_json)
// and queryable via ?tag= (exact element match). Unlike WorkerLabels (routing,
// not stored), Tags are索引/检索维度。
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`
// Retry is the OPTIONAL per-job retry policy (E24 unified retry, P1, design
// §6.2). nil == no retry (the v1 default,向后兼容). When set on a non-workflow
// job, finish re-runs the job on a retryable failure (attempt+1, same request_json)
// up to RetryPolicy.MaxAttempts, with backoff per the policy. It shares the SAME
// RetryPolicy / backoffFor / retryableExit as the step-level retry (one semantics,
// roadmap横切). P1 uses an in-process delay (time.AfterFunc): a process restart
// loses a pending job-level retry — the可靠版 (sweeper-driven next_retry_at) is
// left for后续; the reliable path today is a single-step workflow + step retry.
Retry *RetryPolicy `json:"retry,omitempty" yaml:"retry,omitempty"`
// WorkflowID / StepIndex are INTERNAL fields set ONLY by the workflow engine
// (SubmitWorkflow / advanceWorkflow) when starting a step-job; they bind the job
// to its workflow + 1-based step. json/yaml tag "-" keeps clients (HTTP body / md
// frontmatter) from forging them — a plain POST /v1/jobs never sets a workflow.
WorkflowID string `json:"-" yaml:"-"`
StepIndex int `json:"-" yaml:"-"`
// Attempt is the 1-based retry attempt of a step-job (P1, design §5.3). It is
// set by the workflow engine (stepToRequest) and persisted to jobs.attempt so a
// retried step's distinct runs are distinguishable. A non-workflow job (or a v1
// step) leaves it 0; the persist path COALESCEs that to 1. json/yaml "-" keeps
// clients from forging it.
Attempt int `json:"-" yaml:"-"`
// FanIndex is the 1-based parallel index of a fan-out step-job (P2, design §5.3):
// a FanOut>1 step starts N jobs sharing (step_index, attempt), distinguished by
// FanIndex=1..N. Set ONLY by the workflow engine (stepToRequest); a non-fan-out
// job (single-job path, v1/P1) leaves it 0. Persisted to jobs.fan_index and forms
// the f<fanIndex> segment of the deterministic request_id. json/yaml "-" keeps
// clients from forging it.
FanIndex int `json:"-" yaml:"-"`
// SessionID, when non-empty, is the底层 agent CLI 会话标识 to bind this job to
// (session-capture, resume path P2): it wins over auto-injection (the job uses
// this exact id instead of generating a new uuid) and suppresses capture. It is
// persisted onto the JobResult so the session链 round-trips. Empty == let submit
// inject (claude) or capture (codex) decide.
SessionID string `json:"session_id,omitempty" yaml:"session_id,omitempty"`
// Channel is the submission CHANNEL — which interface the job was submitted
// through: "cli" / "web" / "mcp" / "im" (future). Client-declared (CLI stamps
// "cli", the web console "web", the MCP server "mcp"); informational provenance,
// not an auth identity (that is CallerID). yaml tag so an md+yaml task file may
// set it too. Empty for legacy / raw-API submits.
Channel string `json:"channel,omitempty" yaml:"channel,omitempty"`
// Client is the ORIGINATING client of the submission: the CLI stamps its
// os.Hostname(); for an HTTP submit with no client given, the server stamps the
// remote IP. Together with Channel and CallerID it answers "who/where submitted
// this". Informational (forgeable) — not used for access control.
Client string `json:"client,omitempty" yaml:"client,omitempty"`
// ResumeSourceAgent is an INTERNAL marker set ONLY by ResumeJob (session-capture
// P2, 2026-06-26 decision). A resume mechanically carries Agent="exec" (the
// resume argv runs as the built-in exec carrier), but its REAL identity for
// access control is the SOURCE agent whose session is being续接. When set,
// validate gates BOTH the allowed_agents check and the exec security gate on
// THIS source agent instead of the "exec" carrier: resume only re-runs the
// source agent's CLI in a constrained, templated form (argv = [agent.Command] +
// SessionResume + prompt), so it must NOT demand the broad allow_exec that an
// arbitrary exec job would. json/yaml "-": this exemption is a property of the
// `resume` entrypoint, NOT of the persisted job — it is never written to
// request_json and clients cannot forge it via the public submit API (a forged
// value would otherwise bypass allow_exec to run arbitrary exec). A `job rerun`
// of a resume job replays the stored exec request through the public path and is
// therefore (correctly) gated as a plain exec job — re-resume via the `resume`
// command instead.
ResumeSourceAgent string `json:"-" yaml:"-"`
// ResumedFrom is the CONTINUATION marker: the source job id whose agent session
// this job continues, stamped by ResumeJob and by nobody else (an empty value
// means a plain job). Together with SessionID it is what makes an acp-agent
// runner LOAD the source session (submit.resumeLoadSessionID) instead of opening
// a fresh one (ACP-01 S2).
//
// It IS a wire field (json/yaml round-trip, and it rides a peer/worker forward):
// the one thing it can do is ask an agent to session/load ITS OWN session id,
// which an agent that does not know that session refuses on its own — so it is
// not an access-control marker, unlike ResumeSourceAgent / ReviewFixed /
// TodoForeign below, which stay json:"-". It also makes `job rerun` of a
// continuation re-continue the same session (decided 2026-09-18, SUP-02 R1).
ResumedFrom string `json:"resumed_from,omitempty" yaml:"resumed_from,omitempty"`
// InheritWorktree: this continuation (stamped by ResumeJob only, never from a
// client body) runs in and owns its source's managed worktree, so its commits,
// review and delivery cover that branch (gofer-glyo).
InheritWorktree bool `json:"-" yaml:"-"`
AutoResumeAttempt int `json:"-" yaml:"-"`
// FallbackAgents is the per-JOB candidate list (SUP-01 P3, `job run --fallback`):
// it wins over the project's agent_fallbacks and over the agent's own
// fallback_agents. Submit resolves the effective list from it and persists the
// RESULT (jobs.fallback_json), so a config change while the job runs cannot make
// the chain drift.
FallbackAgents []string `json:"fallback_agents,omitempty" yaml:"fallback_agents,omitempty"`
// NoFallback turns the transfer off for THIS job whatever the config says
// (SUP-01 P3, `job run --no-fallback`).
NoFallback bool `json:"no_fallback,omitempty" yaml:"no_fallback,omitempty"`
// FellBackFrom is the INTERNAL marker of a transfer (SUP-01 P3): the id of the
// job this one took over from. json/yaml "-" like ResumedFrom — a client cannot
// claim lineage, and it does not round-trip through request_json.
FellBackFrom string `json:"-" yaml:"-"`
// Fallback is the transfer plan this job INHERITS (SUP-01 P3): the candidate list
// resolved for the chain's root plus how many links are already used, carried
// verbatim so the whole chain follows ONE frozen plan. Internal (json:"-"); a
// plain submit has it resolved by Submit from the config.
Fallback *FallbackState `json:"-" yaml:"-"`
// RequestedAgent is the agent the CALLER asked for, kept when pre-dispatch
// substituted a degraded one (SUP-01 P3). Internal: the server stamps it from the
// request it received, so a client body cannot claim one.
RequestedAgent string `json:"-" yaml:"-"`
// contains filtered or unexported fields
}
JobRequest is the create-job payload. JSON tags are snake_case (plan §6.2). yaml tags mirror the json names so the md+yaml frontmatter submit path (design §6.2 / P1-b) reuses the same struct via goccy/go-yaml.
type JobResult ¶
type JobResult struct {
ID string `json:"id"`
ProjectKey string `json:"project_key"`
Agent string `json:"agent"`
ResumeAgent string `json:"resume_agent,omitempty"`
Runner string `json:"runner"`
Messenger *MessengerMeta `json:"messenger,omitempty"`
Interactive bool `json:"interactive,omitempty"`
// Model mirrors JobRequest.Model (N1 §B): the model this job asked for; empty = the
// agent's own default. Derived from request_json, so it needs no column.
Model string `json:"model,omitempty"`
// FromSession mirrors JobRequest.FromSession (gofer-f4z8): the earlier session this
// job's NEW session inherited its context from. Derived from request_json.
FromSession string `json:"from_session,omitempty"`
// Acceptance mirrors JobRequest.Acceptance: the criteria the review checks the
// report against. Derived from request_json, so it needs no column.
Acceptance string `json:"acceptance,omitempty"`
// Scope mirrors JobRequest.Scope: the declared change scope the review checks the
// diff's files against. Derived from request_json.
Scope []string `json:"scope,omitempty"`
// KnowledgeCapture mirrors JobRequest.KnowledgeCapture: the report's 「## 可复用经验」
// items become memory candidates. Derived from request_json.
KnowledgeCapture bool `json:"knowledge_capture,omitempty"`
// Budget mirrors JobRequest.Budget (N2 §B): the decided ceiling the job runs under;
// what it has spent is in Usage (tokens / cost / turns). nil = unlimited.
Budget *Budget `json:"budget,omitempty"`
// ReadOnly mirrors JobRequest.ReadOnly and is persisted to jobs.read_only (bd
// h-aii-0ql3): whether THIS job ran under a read-only sandbox, inheritable by a
// resume and visible in `job show` / the web console after the fact.
ReadOnly bool `json:"read_only,omitempty"`
// Hold is the hold-for-approval state (gofer-9b1b): set on a job submitted with
// --hold — the reason, the deadline, who submitted it and, once decided, the
// decision. nil for a job that was never held. Stored in jobs.hold_json.
Hold *HoldState `json:"hold,omitempty"`
// RequireReview / ReviewedBy / ReviewedAt / ReviewNote are the人工验收 (GATE-01
// S3) audit fields. RequireReview mirrors JobRequest.Review (resolved: --review or
// the project's require_review) and stays true after a review, so a finished job
// still answers "was this delivery gated on a human?". ReviewedBy/At/Note record
// the DECISION (who accepted/rejected, when, why) and are empty until one is made;
// ReviewedBy is the caller id ("anonymous" for an empty/allow_empty_token caller,
// "mcp:<agent>" for the MCP tool). Persisted to jobs.require_review/reviewed_by/
// reviewed_at/review_note.
RequireReview bool `json:"require_review,omitempty"`
ReviewedBy string `json:"reviewed_by,omitempty"`
ReviewedAt int64 `json:"reviewed_at,omitempty"`
ReviewNote string `json:"review_note,omitempty"`
// DirExclusive is the job's RESOLVED same-directory lock policy (JOB-11),
// persisted to jobs.dir_exclusive: true means this job holds (or would hold) the
// exclusive lock of its working directory, so no other exclusive job runs in that
// directory, an ancestor or a descendant of it at the same time. It explains why
// a job waited, and after the fact it answers "was this run allowed to share the
// tree?" for a finished row.
DirExclusive bool `json:"dir_exclusive,omitempty"`
LockPaths []string `json:"lock_paths,omitempty"`
HeldLockPaths []string `json:"held_lock_paths,omitempty"`
// WaitingOnJob is the job currently HOLDING the directory lock this one waits
// for (JOB-11): set only while Status is StatusWaitingDir and cleared the moment
// the lock is taken. It is live-only state (no column): a job that is not waiting
// has no holder to report, and the terminal row must not keep claiming one.
WaitingOnJob string `json:"waiting_on_job,omitempty"`
// TimeoutSec is the EFFECTIVE job deadline in seconds AFTER the configured
// ceiling clamp (bd h-aii-s9ck), persisted to jobs.timeout_sec so a post-mortem
// answers "why did my 2h request die at 1h?" without replaying config history.
// 0 = no deadline (an interactive session submitted without an explicit timeout).
TimeoutSec int `json:"timeout_sec,omitempty"`
// Session metadata is persisted together as session_state_json. The job status
// remains the authoritative lifecycle state.
Session bool `json:"session,omitempty"`
TurnNo int `json:"turn_no,omitempty"`
IdleTimeoutSec int `json:"idle_timeout_sec,omitempty"`
MaxSessionSec int `json:"max_session_sec,omitempty"`
IdleDeadlineAt int64 `json:"idle_deadline_at,omitempty"`
MaxSessionDeadlineAt int64 `json:"max_session_deadline_at,omitempty"`
SessionEndReason string `json:"session_end_reason,omitempty"`
SessionEnding bool `json:"session_ending,omitempty"`
// RequestedTimeoutSec is the timeout_sec the caller actually asked for (0 =
// unset, the server default applies). It differs from TimeoutSec only when the
// ceiling truncated it.
RequestedTimeoutSec int `json:"requested_timeout_sec,omitempty"`
// TimeoutClamped reports that the REQUEST was truncated to the ceiling, i.e. the
// job will be killed earlier than asked. It exists so the clamp is never silent:
// the CLI warns on submit, and an API/Web caller can see why. A server-side
// default that merely happens to exceed the ceiling is not a clamp (nothing was
// requested), so it stays false.
TimeoutClamped bool `json:"timeout_clamped,omitempty"`
// Title is the optional human-readable job name from the original JobRequest.
// The jobs table has no title column; it persists inside request_json and is
// recovered on the DB read path (fromRecord) so it round-trips, not just on
// the live in-memory path.
Title string `json:"title"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
Cwd string `json:"cwd"`
ResultDir string `json:"result_dir"`
// WorkerID is the worker that executed a runner=worker job (ws-worker §8),
// persisted to jobs.worker_id and echoed for audit / filtering. Empty for
// local/peer-http jobs.
WorkerID string `json:"worker_id,omitempty"`
// WorkerInstanceID is the PROCESS nonce of the worker connection this job was
// dispatched to (RECOV-01 R4, wsproto.Register.InstanceID), persisted to
// jobs.worker_instance_id. It is what makes adoption decidable after a serve
// restart: a re-registering worker may only take a store-held `recovering` job
// over when its instance matches this value (the very process that ran it).
// Empty for local/peer jobs and for jobs dispatched before R4.
WorkerInstanceID string `json:"worker_instance_id,omitempty"`
StartedAt int64 `json:"started_at"`
EndedAt int64 `json:"ended_at,omitempty"`
// RecoveringSince is the unix time the job entered `recovering` (RECOV-01); 0
// when the job is not (or no longer) recovering. It is persisted so the window
// a job spent waiting for its worker is visible after the fact in `job show` /
// the web detail, not just in the live event log.
RecoveringSince int64 `json:"recovering_since,omitempty"`
// UpdatedAt is the unix time of the last persisted snapshot. It is stamped by
// the metadata store write path (Service.persist) so listing/retention always
// have a monotonic ordering value; it is not set by the runner state machine.
UpdatedAt int64 `json:"updated_at,omitempty"`
Error string `json:"error,omitempty"`
// CallerID is the authenticated submitter id (C2), persisted to
// jobs.caller_id and echoed in responses for audit / per-caller filtering.
CallerID string `json:"caller_id,omitempty"`
// SourceSessionID is the trusted caller-side session provenance, not the agent session.
SourceSessionID string `json:"source_session_id,omitempty"`
// Notify / NotifySession mirror JobRequest (gofer-3db4): this job asks gofer to tell a
// session when it ends, and NotifySession names that session ("" = the source
// session). Like Title they live in request_json — the terminal notify reads them off
// the finished job's snapshot, so they need no column of their own.
Notify bool `json:"notify,omitempty"`
NotifySession string `json:"notify_session,omitempty"`
// Channel / Client are the submission provenance (mirrors JobRequest): which
// interface (cli/web/mcp/im) and which originating host/addr the job came from.
// Persisted to jobs.channel / jobs.client; surfaced in show/list so DB records
// answer "who/where/how submitted" alongside CallerID.
Channel string `json:"channel,omitempty"`
Client string `json:"client,omitempty"`
// Role is the E35 role-preset name this job was launched with (mirrors
// JobRequest.Role). It is persisted to jobs.role so the supervisor router can
// identify a job that is ITSELF a supervisor (Role=="supervisor") and refuse to
// auto-answer or re-escalate its interactions (套娃防护, supervisor-routing P2.2,
// design §8.4) — those go straight to a human (L3). Empty for a roleless job.
Role string `json:"role,omitempty"`
// PlanID is the client-settable plan grouping key persisted to jobs.plan_id.
// Empty means this job is not grouped under a plan.
PlanID string `json:"plan_id,omitempty"`
// SourceJobID is the lineage key (P5): the source job this one was resumed/rebuilt
// from. Persisted to jobs.source_job_id (single source of truth — it is NOT in
// request_json, see JobRequest.SourceJobID). Surfaced in show/list and via
// ?source_job= for bidirectional lineage nav. Empty == not derived (omitempty).
SourceJobID string `json:"source_job_id,omitempty"`
// RequestID is the idempotency key (C5) this job was created with; it is
// persisted (jobs.request_id) and echoed so the idempotent-reuse path returns
// it and it round-trips through persist.
RequestID string `json:"request_id,omitempty"`
// RequestJSON is the original JobRequest marshalled to JSON, kept for audit /
// re-submit. It is persisted to the jobs.request_json column (SP5 replaces the
// on-disk request.json file). json:"-" keeps it out of API responses — it is an
// internal/audit field, not part of the queryable job state.
RequestJSON string `json:"-"`
// 产出与审计(job-outcomes-audit):job 终态时 captureOutcomes 采集的产出字段。
// 全部 best-effort(采集失败为空),omitempty 保证旧 job/未捕获时不出现在响应里。
// RenderedCommand 是 {command,args,env_keys} 的 JSON 字符串(E15),前端 JSON.parse。
RenderedCommand string `json:"rendered_command,omitempty"`
// ResultJSON 是 <result_dir>/result.json 原文(已是合法 JSON 字符串),前端 JSON.parse(E6)。
ResultJSON string `json:"result_json,omitempty"`
// ArtifactsJSON 产物清单(E1):不进 get_job(清单走专门端点,P2),仅入库 + 透传。
ArtifactsJSON string `json:"-"`
// DiffSummary git diff --stat 截断摘要(E12,P3)。
DiffSummary string `json:"diff_summary,omitempty"`
// UncommittedFiles is the first 200 cwd-relative dirty paths attributable to
// this agent job. UncommittedCount retains the full count for truncated lists.
UncommittedFiles []string `json:"uncommitted_files,omitempty"`
UncommittedCount int `json:"uncommitted_count,omitempty"`
// NDJSONKept / NDJSONDropped / NDJSONTruncated 是采集期 NDJSON 投影器的行数审计
// (bd h-aii-rpky / bd h-aii-525u):该 job 的 stderr.log 写入了多少行紧凑事件、丢掉了
// 多少行逐 token 增量事件、有多少行因超过单行上限被截断(标 `…(truncated)`)。文本
// agent、远端执行(执行机自己计数)或过滤未启用的 job 恒为 0(omitempty 不出现在响应里)。
NDJSONKept int `json:"ndjson_kept,omitempty"`
NDJSONDropped int `json:"ndjson_dropped,omitempty"`
NDJSONTruncated int `json:"ndjson_truncated,omitempty"`
// Source 标记 job 实际执行位置(P4):""(local) / worker:<id> / peer:<name>。
// 远端 runner 回传时填充并入库,详情据此标注执行来源(P4-c)。
Source string `json:"source,omitempty"`
// Tags 是 job 的自由标签(E5),持久化到 jobs.tags_json,支持 ?tag= 检索。
// omitempty 保证无标签的 job 响应里不出现该字段。
Tags []string `json:"tags,omitempty"`
// WorkflowID / StepIndex 标记此 job 属于哪个工作流的第几步(1-based)。普通 job 为
// ""/0(omitempty 不出现在响应里)。持久化到 jobs.workflow_id/step_index,
// finish 钩子据 WorkflowID 决定是否异步推进所属工作流。
WorkflowID string `json:"workflow_id,omitempty"`
StepIndex int `json:"step_index,omitempty"`
// Attempt 是此 step-job 的 1-based 重试尝试号(P1)。首次运行=1;重试起的新 job
// attempt+1。持久化到 jobs.attempt(旧库 COALESCE 成 1)。普通 job 为 0(omitempty)。
Attempt int `json:"attempt,omitempty"`
// FanIndex 是 fan-out step 内此并行 job 的 1-based 序号(P2)。FanOut>1 的 step 起
// N 个 job,以 FanIndex=1..N 区分;非 fan-out(单 job 路径)为 0(omitempty)。
// 持久化到 jobs.fan_index。
FanIndex int `json:"fan_index,omitempty"`
// SessionID 底层 agent CLI 会话标识(claude/codex)。注入(提交时 gofer 生成)或捕获(终态从输出)。
// 空=无/未捕获。持久化 jobs.session_id,供 show/list/resume。
SessionID string `json:"session_id,omitempty"`
// StopReason 是 acp-agent job 的 session/prompt stopReason(ACP-01 S0):
// end_turn / max_tokens / max_turn_requests / refusal / cancelled。其余 agent 类型恒为空
// (omitempty 不出现在响应里)。它解释"agent 为何停下"——尤其是 max_tokens/max_turn_requests
// 这类 status 仍为 done 的提前结束。持久化 jobs.stop_reason。
StopReason string `json:"stop_reason,omitempty"`
// WrapUp is the agent's OWN reason for ending the run early instead of answering
// (gofer-gk74): `max_steps` / `max_tokens` / `timeout`, as reported by the agent's
// stream (suga's result row's wrap_up field, or its `max steps exceeded` error row).
// Empty = the agent answered, or this dialect reports no such reason. It differs
// from StopReason: that one is the ACP protocol's stopReason for an acp-agent job,
// this is a CLI agent's own ceiling — and unlike a timeout the job was killed for,
// the agent stopped itself and its report is still worth reading.
// Persisted to jobs.wrap_up.
WrapUp string `json:"wrap_up,omitempty"`
ResumedFrom string `json:"resumed_from,omitempty"`
AutoResumeAttempt int `json:"auto_resume_attempt,omitempty"`
AutoResumedBy string `json:"auto_resumed_by,omitempty"`
// WT-01 受管 worktree:该 job 在独立 worktree 中执行时,记录交付物位置与分支状态。
// WorktreePath=<repo top>/tmp/gofer/wt/<job-id>(默认保留,分支上的提交即交付物),
// WorktreeBranch=gofer/<job-id>,WorktreeBaseSHA=基线提交,WorktreeHeadSHA=终态时该分支
// HEAD(git rev-parse HEAD),CommitsAhead=领先基线的提交数(git rev-list --count
// base..HEAD)。非 worktree job 全为空/0(omitempty 不出现);一并入库 jobs 表,供
// `job show` / web 详情 / `job worktree ls|rm` 与 retention 使用。
WorktreePath string `json:"worktree_path,omitempty"`
WorktreeBranch string `json:"worktree_branch,omitempty"`
WorktreeBaseSHA string `json:"worktree_base_sha,omitempty"`
WorktreeHeadSHA string `json:"worktree_head_sha,omitempty"`
CommitsAhead int `json:"commits_ahead,omitempty"`
// TodoID is the plan todo this job was submitted for (SUP-01 C); the terminal
// hooks write the outcome back into that todo. Empty = not a checklist job.
TodoID string `json:"todo_id,omitempty"`
IssueID string `json:"issue_id,omitempty"`
TrackerID string `json:"tracker_id,omitempty"`
// TodoForeign mirrors JobRequest.TodoForeign for a continuation: the todo belongs
// to the store that submitted the job, not to this one (a worker's local copy),
// so the continuation must not try to resolve or link it either.
TodoForeign bool `json:"-"`
// LeaderOfPlan is the plan this job leads (MCP-05 阶段 B), "" on every ordinary job.
// Server-set (never on the wire), persisted as jobs.leader_of_plan so the marker
// survives a restart and a read from the store alone.
LeaderOfPlan string `json:"-"`
// BaseSHA / Commits are the提交采集 (SUP-01 C): BaseSHA is the commit the job
// STARTED from — captured on the executing machine when it turns `running`, and
// for a worktree job simply its baseline — and Commits lists what it produced
// between that base and HEAD at its terminal, newest first (capped). Both stay
// empty outside a git checkout / when git is unavailable. Persisted as
// jobs.base_sha / jobs.commits_json; `job show`, the web detail and the todo
// note read them.
BaseSHA string `json:"base_sha,omitempty"`
Commits []Commit `json:"commits,omitempty"`
// Verify is the outcome of the job's verification step (SUP-01 B), nil when the
// job had none. A failed/timed-out step is why such a job is failed (or parked in
// needs_review when a human reviews it), so this is the field that explains the
// status; it is persisted as jobs.verify_json. The type is runner's — the step's
// result also travels on the remote Outcome channel, and one definition keeps the
// two in step.
Verify *VerifyResult `json:"verify,omitempty"`
// FailureClass is why a FAILED job is classified the way it is (SUP-01 P3):
// "transient" (a provider error — the health aggregation counts it) or "other".
// Empty for anything that is not a failure. Persisted as jobs.failure_class.
FailureClass string `json:"failure_class,omitempty"`
// FellBackFrom / FellBackTo are the two ends of a failover link (SUP-01 P3):
// FellBackFrom names the job this one took over from, FellBackTo the job that took
// THIS one over after it failed. Both empty outside a transfer chain (a resubmitted
// job never invents one). Persisted as jobs.fell_back_from / fell_back_to.
FellBackFrom string `json:"fell_back_from,omitempty"`
FellBackTo string `json:"fell_back_to,omitempty"`
// RequestedAgent is the agent the CALLER asked for, kept when Submit substituted a
// degraded one (SUP-01 P3) and inherited by every takeover on the chain. Empty
// when the job ran exactly the agent it was submitted with. Persisted as
// jobs.requested_agent.
RequestedAgent string `json:"requested_agent,omitempty"`
// Fallback is the frozen failover plan (candidates + used depth) this job runs
// under (SUP-01 P3), resolved once at submit and carried by every takeover.
// Persisted as jobs.fallback_json; nil for a job with no candidates.
Fallback *FallbackState `json:"fallback,omitempty"`
// Usage is what the agent reported about the work's cost (SUP-01 E): tokens in /
// out / cached and, where the agent prices its run, the cost. It is captured
// best-effort from the source that carries it — the projected ndjson stream, the
// agent's stderr tail (codex), or the acp runner — or回传 by the execution machine
// for a remote job. Nil = nothing was captured (never an invented zero tally).
// Persisted as jobs.usage_json; the Source field says where the numbers came from.
Usage *Usage `json:"usage,omitempty"`
// Xfer is the job's file-transfer summary (XFER-01 X2): what `--upload` placed on
// the executing machine before the agent started and what `--collect` matched when
// the job ended. Nil for a job that carried no files (never an empty shell for a
// job that never asked for one). Persisted as jobs.xfer_json; the collected files
// themselves live under the job's result dir as artifacts/collected/...
Xfer *XferSummary `json:"xfer,omitempty"`
// Skills are the working-method documents this job ran with (JOB-10), decided at
// submit by the four-level union. Persisted as jobs.skills_json so `job show`, the
// web detail and a post-mortem answer "which rules did this run actually have?"
// without re-reading a config that may have changed since.
Skills []string `json:"skills,omitempty"`
// MCP are the registry MCP servers this job was bound to (MCP-06). Persisted as
// jobs.mcp_json.
MCP []string `json:"mcp,omitempty"`
// Delivery is the outcome of handing the worktree branch over (GIT-02): merged /
// pushed / pr_opened / failed / skipped, with the branch and request URL.
// Persisted as jobs.delivery_json.
Delivery *DeliveryResult `json:"delivery,omitempty"`
// Rules are the MANDATORY rules this job was injected with (JOB-06①), each with
// the sha256 of the text that went into its prompt. Persisted as jobs.rules_json:
// the prompt itself (request_json) shows WHAT the agent read, this column shows
// WHICH LIBRARY VERSION it read — the pair a post-mortem needs after the library
// was edited. Nil for a job that carried no rules.
Rules []RuleRef `json:"rules,omitempty"`
// contains filtered or unexported fields
}
JobResult is the persisted/queryable job state (plan §6.2).
type JobTerminalHook ¶
type JobTerminalHook func(JobResult)
JobTerminalHook observes a job the moment it reaches a TERMINAL state (SUP-02 R1). It is the reverse seam the assembled hub uses to react to an outcome the job service itself has no business knowing about: a finished path-B takeover job hands its session back (sessionrelay.ReleaseTakeoverForJob).
The hook runs AFTER the terminal state is durable and the entry is evicted, in its own goroutine: it can neither delay finish nor change the job's outcome, and a slow or panicking one is that hook's own problem (the panic is recovered and logged, and the other hooks still run).
type JobTokenLookup ¶
type JobTokenLookup struct {
JobID string
Kind string // jobstore.JobCredentialMember | JobCredentialLeader | JobCredentialSteward
PlanID string
}
JobTokenLookup is the resolved identity of a presented job credential: which job it is, and which half of the permission table applies to it.
type LeaderStatus ¶
LeaderStatus is what a plan page shows about its leader rounds: whether the round is on, how many rounds are spent against the cap, and the last leader job started.
type ListOpts ¶
type ListOpts struct {
// Project, when non-empty, restricts the result to a single project_key.
Project string
// Status, when non-empty, keeps only jobs whose status matches exactly.
Status string
// Caller, when non-empty, keeps only jobs submitted by that caller id (C2).
Caller string
// Tag, when non-empty, keeps only jobs carrying that exact tag element (E5).
Tag string
// Agent, when non-empty, matches the physical or original resumed agent.
Agent string
// Runner, when non-empty, keeps only jobs run on that runner (E5).
Runner string
// Session, when non-empty, keeps only jobs whose session_id matches exactly
// (P3, list --session:列出某 agent 会话链的所有 turn)。
Session string
// Plan, when non-empty, keeps only jobs whose plan_id matches exactly.
Plan string
// SourceJob, when non-empty, keeps only jobs whose source_job_id matches exactly
// (P5, ?source_job=:列出某 job 直接派生出的所有 job)。
SourceJob string
// All includes internal delivery jobs such as web session messenger records.
All bool
// Since, when > 0, keeps only jobs with started_at >= Since (E5; unix 秒)。
Since int64
// Limit caps the number of returned jobs; <= 0 means defaultListLimit.
Limit int
// Offset skips the first Offset rows after sorting; <= 0 means no offset.
Offset int
}
ListOpts filters/bounds a ListJobs query. A zero value lists every project's jobs (no status filter) up to defaultListLimit.
type MemoryCandidateDecision ¶
type MemoryCandidateDecision struct {
Candidate jobstore.MemoryCandidate `json:"candidate"`
Memory *jobstore.ScopedMemory `json:"memory,omitempty"`
}
MemoryCandidateDecision is the outcome of accepting a candidate: the decided row and the memory it became.
type MergeOptions ¶
type MergeOptions struct {
// Squash merges the branch as a single commit instead of a --no-ff merge commit.
Squash bool
// CleanupOthers removes (force, with branch) the worktrees of the other fan jobs
// of the same workflow step/attempt once the merge succeeded.
CleanupOthers bool
}
MergeOptions tunes MergeWorktree.
type MergeResult ¶
type MergeResult struct {
WorktreeStatus
Cleaned []string `json:"cleaned,omitempty"`
}
MergeResult is the merge response: the merged worktree plus the siblings that were cleaned up (CleanupOthers).
type MessengerMeta ¶
type MessengerMeta struct {
TargetSession string `json:"target_session,omitempty"`
Message string `json:"message,omitempty"`
Channel string `json:"channel,omitempty"`
}
MessengerMeta describes the user-visible part of a session messenger job. Channel is "resident" for the v14 worker dispatch path and "one-shot" for the exec fallback.
type MetricsSink ¶
type MetricsSink interface {
// JobSubmitted is called once per accepted Submit.
JobSubmitted(caller, project, agent, runner string)
// JobTerminal is called once when a job reaches a terminal state, with the
// end-to-end (submit→terminal) duration in seconds.
JobTerminal(status, caller, project, agent, runner string, durationSec float64)
// WorkflowTerminal is called once when a workflow (job chain) reaches a terminal
// state (done/failed/cancelled), with its submit→terminal duration in seconds
// (P4 / T4.3, design §9). It is the workflow analogue of JobTerminal; the job
// package records it through this narrow interface so it never imports prometheus.
WorkflowTerminal(status string, durationSec float64)
}
MetricsSink receives job lifecycle counters (E16, design §6). The job package records through this narrow interface so it never imports prometheus; the metrics package implements it and commands.buildCore injects it via SetMetrics. Every call site guards `if s.metrics != nil`, so a service with no sink wired is a clean no-op.
type PlanTodoSpec ¶
type PlanTodoSpec struct {
Title string
After []string
AfterSet bool
Acceptance string
Scope []string
Check string
}
PlanTodoSpec is one step of a gofer-todos block. After holds the raw references (titles or 1-based step numbers); AfterSet distinguishes "omitted" (= the previous step) from an explicit empty list (= no dependency).
func ParsePlanTodos ¶
func ParsePlanTodos(text string) ([]PlanTodoSpec, error)
ParsePlanTodos parses the last gofer-todos block of text into steps. Unknown keys are an error (a typo would otherwise drop a field silently).
type RebuildOverrides ¶
type RebuildOverrides struct {
ProjectKey *string `json:"project_key,omitempty"`
Agent *string `json:"agent,omitempty"`
Runner *string `json:"runner,omitempty"`
Prompt *string `json:"prompt,omitempty"`
SystemPrompt *string `json:"system_prompt,omitempty"`
Cmd *[]string `json:"cmd,omitempty"`
AgentArgs *[]string `json:"agent_args,omitempty"`
Model *string `json:"model,omitempty"`
FromSession *string `json:"from_session,omitempty"` // gofer-f4z8; "" clears the inherited value
Budget *Budget `json:"budget,omitempty"`
Cwd *string `json:"cwd,omitempty"`
Title *string `json:"title,omitempty"`
// LockPaths / LockWaitSec / Worktree are the gofer-jkd2 overrides of what a rebuild
// inherits from its source: a pointer distinguishes "not provided (inherit the source
// request)" from an explicit value, so `lock_paths: []` clears the inherited lock
// declaration (the job then locks its whole cwd, the submit default).
LockPaths *[]string `json:"lock_paths,omitempty"`
LockWaitSec *int `json:"lock_wait_sec,omitempty"`
Worktree *bool `json:"worktree,omitempty"`
Tags *[]string `json:"tags,omitempty"`
TimeoutSec *int `json:"timeout_sec,omitempty"`
Interactive *bool `json:"interactive,omitempty"`
Cols *int `json:"cols,omitempty"`
Rows *int `json:"rows,omitempty"`
WorkerID *string `json:"worker_id,omitempty"`
WorkerLabels *[]string `json:"worker_labels,omitempty"`
PlanID *string `json:"plan_id,omitempty"`
Channel *string `json:"channel,omitempty"`
EnvSet map[string]string `json:"env_set,omitempty"`
EnvUnset []string `json:"env_unset,omitempty"`
// contains filtered or unexported fields
}
RebuildOverrides is the POST /v1/jobs/{id}/rebuild body: ONLY user-edited fields. Pointer scalars distinguish "not provided (nil → inherit source)" from "explicit set (incl. empty)". env_set adds/overrides env keys (value "" = set to empty string, NOT delete); env_unset deletes keys; untouched keys keep the SOURCE value (env plaintext never leaves the server). Fields NOT here (request_id/session_id/caller_id/ source_job_id/workflow_id/role/retry/…) are server-controlled or silently inherited.
type ResumeOptions ¶
type ResumeOptions struct {
Mode string
Agent string
// Model overrides the model the continuation inherits from its source (N1 §B).
// Empty keeps the source's model; the continuation cannot be reset to "agent
// default" this way (start a new job for that).
Model string
// Budget overrides, per dimension, the budget the continuation inherits from its
// source (N2 §B). A resume is a NEW job: its meter starts from zero.
Budget *Budget
// Env is the continuation's OWN explicit env: it overrides everything the
// continuation inherits (source agent env, source job env) and, like a plain
// submit's env, is recorded in the new request_json. Inherited values are never
// copied there (see resume_env.go).
Env map[string]string
// Plan overrides the plan the continuation is grouped under. nil (the default)
// keeps the source job's plan, an explicit id moves the continuation to that
// plan, and an explicit empty string detaches it (`job resume --no-plan`).
// It carries the checklist link with it: see applyResumePlan.
Plan *string
// NoNotify drops the end-notification the continuation would inherit from its
// source (gofer-3db4, `job resume --no-notify`). The default is to inherit it: a
// caller who asked to be told when the work ends is asking about the WORK, not
// about one run of it — continuing a long job silently would lose exactly the
// notice they set up.
NoNotify bool
// LockPaths REPLACES the directory lock set the continuation would inherit from
// its source (gofer-jkd2, `job resume --lock`). A resident ACP session locks the
// whole directory it was started in, so continuing it for work that only touches
// one sub-module made every job of that sub-tree queue behind the project root.
//
// Only a NON-EMPTY set is an override: an empty declaration means "lock my working
// directory" (see JobRequest.LockPaths), so a resume cannot clear the lock into
// something wider than the source had. Declaring paths also asks for the lock, so
// the override re-enables exclusivity when the source ran shared (the same reading
// resolveDirExclusive gives a submit's --lock). The cwd is NOT overridable: an ACP
// continuation must load its session from the directory that session was created
// in, and a batch/pty continuation works in the same checkout that holds the work.
LockPaths []string
// Internal marks a continuation gofer started on its own (a wakeup firing, an
// auto-resume, a rerun): an end-notification it cannot address is dropped (with a
// job.notify_dropped event) instead of refusing the continuation. A caller's own
// `job resume` keeps its notification strict — their mistake is reported to them.
Internal bool
// contains filtered or unexported fields
}
ResumeOptions are the optional knobs of ResumeJobWith. Agent switches the continuation to another agent, but only inside the source agent's session family (agent.SessionCompatible): e.g. a claude-acp session continued by the claude CLI.
type RetryPolicy ¶
type RetryPolicy = config.RetryPolicy
RetryPolicy is the retry policy shared by single-job retry (execute.go + retry_sweep.go), workflow step retry (internal/job/workflow) and the config layers (R2/AUTO-03: server.retry / agents.<k>.retry / projects.<k>.retry — config.EffectiveRetryPolicy). The STRUCT lives in internal/config so the config file, the wire (JobRequest.Retry) and the four layers decode from one definition; this alias keeps the job-model name every call site already uses.
It is a job-model type (JobRequest.Retry), so the workflow sub-package references it as job.RetryPolicy (layering design §13.4). The SEMANTICS — the attempt ceiling, the退避表 and the exit-code filter — stay here as the three pure functions below, which every retry path shares.
type ReviewOutcome ¶
type ReviewOutcome struct {
JobResult
// ResumeJobID is the continuation started by reject+resume ("" = none).
ResumeJobID string `json:"resume_job_id,omitempty"`
}
ReviewOutcome is the result of a human accept/reject: the job's new snapshot plus, for a `reject --resume`, the id of the continuation it started. The embedded JobResult keeps the HTTP/MCP body the job's own shape (the detail view is flattened) with one extra field, so a caller that ignores review still parses it as a job.
type RuleInfo ¶
RuleInfo is what the job package needs to know about one library entry: the digest the row records. The text is fetched separately (RuleLibrary.Body) because only the resolving machine needs the bytes.
type RuleLibrary ¶
type RuleLibrary interface {
// Get returns one entry's metadata; ok=false means the name is unknown (a submit
// naming it is rejected rather than run without its rules).
Get(name string) (RuleInfo, bool)
// Body returns the text to INJECT: the rule file with its frontmatter stripped.
Body(name string) (string, error)
}
RuleLibrary is the server's rule asset library as this package needs it. *rule.Store-backed adapter is wired at assemble time (core.Build).
type RuleRef ¶
RuleRef is one rule as a job RECORDS it: the name plus the sha256 of the text that was injected. It is what `job show` / the web detail prints and what makes "which version of house-rules did this run carry?" answerable after the library changed.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service accepts job requests, runs them asynchronously and tracks their state. It is safe for concurrent use.
func NewService ¶
func NewService(cfg *config.Config, projects *project.Registry, agents *agent.Registry, runners map[string]runner.Runner, meta *jobstore.Store, sel WorkerSelector) *Service
NewService builds a job service. runners is the set of usable runners keyed by name (at least "local"). project/agent registries and config come from the loaded config. meta is the SQLite metadata store (job index/persistence); it must be non-nil — the caller (commands.buildCore / tests) opens it. sel supplies connected-worker candidates for label-based auto-selection (P2); it may be nil (the non-worker paths never touch it).
func (*Service) AcceptJob ¶
func (s *Service) AcceptJob(jobID, by, note string) (ReviewOutcome, error)
AcceptJob records a human's接受 of a needs_review job: needs_review -> done, with the reviewer/note in the audit fields, the job.reviewed{accepted} + job.terminal{done} events, and the same post-finish hook a normally-completed job runs (a workflow step's chain advances now). by is the authenticated caller; an empty id is recorded as "anonymous". Only a needs_review job may be accepted (ErrJobNotNeedsReview otherwise).
func (*Service) AcceptJobWithoutDelivery ¶ added in v0.146.0
func (s *Service) AcceptJobWithoutDelivery(jobID, by, note string) (ReviewOutcome, error)
AcceptJobWithoutDelivery accepts a job but records that its worktree branch is not to be delivered (GIT-02: 「通过但不交付」), so the terminal hook leaves it alone.
func (*Service) AcceptMemoryCandidate ¶
func (s *Service) AcceptMemoryCandidate(id int64, in AcceptMemoryCandidateInput, by string) (MemoryCandidateDecision, error)
AcceptMemoryCandidate writes candidate id as a scoped memory (content = the candidate's text, source = job:<id>) and marks it accepted. The candidate is claimed first (pending → accepted, a compare-and-set), so two concurrent accepts cannot both write; a failed memory write puts it back to pending. A key that already names a live memory in the target scope is refused (ErrMemoryCandidateKeyExists).
func (*Service) AddEventObserver ¶
func (s *Service) AddEventObserver(fn JobEventObserver)
AddEventObserver registers an ADDITIONAL in-process observer that sees EVERY recorded event (JOB-09). SetEventObserver keeps its original single-slot, whitelist-filtered meaning for the worker mirror; this is the multi-subscriber seam the wakeup matcher hangs on, because a wakeup subscribes to event types the mirror deliberately never carries (job.terminal, interaction.answered, …). The slice is copied under observersMu, so registering one never races a recording.
func (*Service) AdoptionWake ¶
func (s *Service) AdoptionWake() <-chan struct{}
AdoptionWake is signalled (non-blocking, capacity 1) whenever an adoption runs, so serve's one-shot recovery window can stop early instead of failing jobs a reconnecting worker has already taken back.
func (*Service) AnswerInteraction ¶
func (s *Service) AnswerInteraction(jobID, interactionID, answer string) (Interaction, error)
AnswerInteraction marks a pending interaction answered WITHOUT attribution — the internal / relay path (worker→local resume, peer-http relay) where the answer was already decided upstream, so answered_by stays "". For an ATTRIBUTED answer (web / CLI / MCP) use AnswerInteractionByHuman; for the L0 rule answerer use AnswerInteractionAuto.
func (*Service) AnswerInteractionAuto ¶
func (s *Service) AnswerInteractionAuto(jobID, interactionID, answer, policy string) (Interaction, error)
AnswerInteractionAuto answers an interaction as the L0 built-in rule answerer (监督分层升级路由 P3.2). It is NEVER gated (the rule answerer has its own decide() gate) and stamps answered_by=auto:<policy> (e.g. auto:choice). policy names the rule that fired.
func (*Service) AnswerInteractionByHuman ¶
func (s *Service) AnswerInteractionByHuman(jobID, interactionID, answer, callerID string) (Interaction, error)
AnswerInteractionByHuman answers an interaction as a web/CLI human operator. It stamps the server-authenticated caller id without an agent: prefix. Empty caller ids retain the legacy "human" attribution for allow_empty_token / anonymous deployments.
func (*Service) AnswerInteractionByPush ¶
func (s *Service) AnswerInteractionByPush(jobID, interactionID, answer string) (Interaction, error)
AnswerInteractionByPush answers through a one-time Web Push action token. Token validation and option binding live in internal/webpush; the authoritative pending->answered transition and waiter wake-up remain owned here.
func (*Service) ApproveJob ¶ added in v0.137.0
ApproveJob is a human's approval of a held job: awaiting_approval -> queued, the job.hold_approved event, then the ORIGINAL request is submitted again under the same id and runs like any job (credential, worktree, worker dispatch and all happen now, not at hold time). by is the authenticated caller ("" = anonymous).
It takes an upgrade-admission permit first, so a draining server refuses the approval (ErrUpgradeDraining) and the job keeps waiting. A job that is not awaiting approval — including one somebody else decided a moment earlier — is ErrJobNotAwaitingApproval. When the approved request cannot be started (it no longer validates, or ErrHoldDrift) the job is failed with the reason and the error is returned.
func (*Service) AttachJobToPlan ¶ added in v0.157.0
planattach.go binds an EXISTING job to a plan (`gofer plan attach <plan> <job>`, POST /v1/plans/{id}/jobs). It lives in the job Service rather than being a bare metadata UPDATE because the durable row is a PROJECTION of the in-memory entry: a write that only touches the store is invisible to every reader this process serves (Get/ListJobs return the entry) and is undone by the next persist — the finish write carries plan_id from the snapshot. gofer-z414 hit exactly that: a job attached while it was still tracked kept running "in no plan", and a continuation of it (ResumeJob inherits src.PlanID) inherited nothing.
func (*Service) BackfillMetrics ¶
func (s *Service) BackfillMetrics(opt BackfillOptions) (BackfillResult, error)
BackfillMetrics computes job_metrics rows for jobs that ended before the live write existed. It is idempotent: without Force only jobs lacking a current-version row are visited, and a row is an UPSERT keyed by job id. Sources, in addition to what the live path uses: the compact stderr.log for claude / omp turn and tool counts, and for git line counts the stored diff summary plus `git diff --shortstat base head` when the checkout still has those commits. Anything else stays nil.
func (*Service) BeginUpgradeWork ¶
func (s *Service) BeginUpgradeWork() (*AdmissionPermit, error)
func (*Service) CallerRate ¶
CallerRate exposes the effective per-caller submit rate for the HTTP rate-limit middleware (E17, design §7.3). It reads the CURRENT config snapshot (s.config(), the atomic.Pointer that Reload swaps), so a SIGHUP change to a caller's rate_limit / rate_burst is observed on the very next request — the rate-limit config真源 is here, NOT a copy held by httpapi.Server (which is not on the reload path). Returns (0, 0) when the caller has no rate gating.
func (*Service) Cancel ¶
Cancel requests cancellation of a running job. It is a stable no-op (returns nil) for an already-terminal job, so callers/tests get deterministic behaviour. It returns an error only when the job id is unknown.
After SP3 a finished job is evicted from the in-memory map, so an entry==nil can mean "never existed" OR "already terminal and evicted". The metadata store disambiguates: a known (terminal) job cancels as a no-op (nil); only a truly unknown id is an error.
func (*Service) CancelLeaderWakesForPlan ¶
CancelLeaderWakesForPlan stops every round of a plan that has not started a leader job yet and reports how many it stopped (MCP-05 阶段 B: a human speaking in the thread takes the round over). It is called from the comment path with the author as `by`; the plan's event stream records who intervened.
func (*Service) CancelRetry ¶
CancelRetry drops a PENDING (or currently claimed) retry, so the sweeper will not submit it — the `job retry cancel <retry-id>` path. A row that already ran or was already cancelled is terminal and reports an error rather than pretending to have cancelled something.
func (*Service) CloseUpgradeAdmission ¶
CloseUpgradeAdmission prevents new producers and waits for every accepted submission/claim to finish. A timeout leaves admission closed until the bridge explicitly reopens it after its failed upgrade transaction is reconciled.
func (*Service) Comment ¶
func (s *Service) Comment(scope, scopeID, author, authorKind, body string) (jobstore.Comment, []CommentDispatch, error)
Comment records a comment on a job, plan or plan-todo and, when a HUMAN wrote it, dispatches one job per @-mention through the SAME Submit entry every other caller uses (MCP-05 阶段 A, design §二.A.2/A.3).
authorKind is decided by the entry layer (callerKind for HTTP, the calling job for MCP), never by the body. The gates, in order:
author kind only "user" triggers (agent comments are recorded; the leader
whitelist of 阶段 B extends this — see commentAuthorMayTrigger)
existence the mention must name a configured agent or a configured role
allowlist that agent must be allowed in the target's project
throttle one dispatching comment per scope per interval, and a per-scope
lifetime cap (server.comment_trigger)
A refused mention is never silent: the comment is kept and a `system` comment says why. The returned []CommentDispatch is empty when nothing was started.
func (*Service) CommentAsJob ¶
func (s *Service) CommentAsJob(scope, scopeID, asJob, body string) (jobstore.Comment, []CommentDispatch, error)
CommentAsJob records a comment written BY the agent of asJob — the in-job identity (MCP's GOFER_JOB_ID, the CLI's own env) that the entry layers resolve. The author is DERIVED from that job (its agent key) and the row is authored `agent`; the job id itself is what the 阶段 B leader gate reads (a leader job of THIS plan may @-mention and dispatch; every other agent comment is recorded only).
func (*Service) CommentAsJobWouldDispatch ¶ added in v0.161.0
CommentAsJobWouldDispatch is CommentWouldDispatch for a comment written BY the agent of asJob (the CommentAsJob entry point, whose author is derived from that job).
func (*Service) CommentWouldDispatch ¶ added in v0.161.0
func (s *Service) CommentWouldDispatch(scope, scopeID, author, authorKind, body string) ([]string, error)
CommentWouldDispatch reports the @-mentions of body that WOULD start a job if `author` (a caller of kind authorKind) comments on the object (scope, scopeID) — the question `Comment` answers with its []CommentDispatch, asked WITHOUT writing anything: no comment row, no event, no job.
It is the seam an ENTRY layer uses to decide something before the comment exists (plan T1.5a: a comment that dispatches needs `job.submit`, and the permission must be asked before the comment is recorded so a refused request changes nothing). The permission itself is the entry layer's: the job package never reads one (AGENTS.md G022).
The gates are the pre-dispatch ones of dispatchCommentMentions — a valid scope, a non-empty body, a resolvable target, the author gate (commentAuthorMayTrigger) and, per mention, resolution plus the project allowlist. An error is what `Comment` would answer for the same input (an unknown target, an unusable as_job); the caller keeps its own answer for it.
The THROTTLE is deliberately NOT part of the question: commentThrottleReason can only keep a dispatch that would otherwise happen from happening, so a request it narrows still needed the permission — while leaving it out keeps this a pure function of the configuration and target.
func (*Service) CountRecoveringJobs ¶
CountRecoveringJobs reports how many jobs the store still holds in `recovering`. Serve's one-shot startup window uses it to decide whether anything is left to end after an adoption (RECOV-01 R4).
func (*Service) CountUpdatePaused ¶ added in v0.156.0
CountUpdatePaused reports how many jobs an update has parked right now.
func (*Service) CountUpgradeRestartBlockers ¶ added in v0.156.0
CountUpgradeRestartBlockers counts the jobs that keep a server restart from being safe. excludedIDs are rows the caller verified itself (the idle ACP sessions the shutdown path preserves, the upgrade's own source job).
func (*Service) CreateInteraction ¶
func (s *Service) CreateInteraction(jobID string, in InteractionInput) (Interaction, error)
CreateInteraction raises a new interaction on a LIVE job: it records a pending Interaction, flips the job status to pending_interaction and persists. Errors if the job is unknown or already terminal.
func (*Service) CreateWakeup ¶
func (s *Service) CreateWakeup(spec WakeupSpec, by string, gate WakeupGate) (jobstore.WakeupRecord, error)
CreateWakeup validates and stores a wakeup on spec.JobID (design §五.1). `by` is the authenticated caller the HTTP/CLI/MCP entry stamped; it must be allowed to resume the target job and becomes the continuation's CallerID.
gate is the ENTRY layer's decision for a caller that is not the job's own (design 架构: 「job 层:wakeup.go 不再读配置,由入口层传入判定结果」): it answers whether such a caller may act on this job's wakeups. The job layer keeps only the ownership rules (callerMayActOnWakeup).
func (*Service) DeleteJob ¶
DeleteJob removes a terminal job's durable record (jobstore.DeleteJob keeps the job.deleted audit) and then drops its in-memory entry.
finish flips the in-memory status to terminal BEFORE the row is durable, and keeps writing for the job after that (credential revoke, metrics, todo, knowledge, agent health, hooks). A delete landing in that window used to be refused as "not terminal" while GET already answered done, and a delete just after the row landed left those trailing writes recreating rows for a job that no longer existed. So when the entry reads as finished, DeleteJob first waits (bounded) for its execute goroutine to end; a finish that outlasts the bound is answered with ErrJobFinishing.
func (*Service) DeleteWakeup ¶
func (s *Service) DeleteWakeup(id, by string, gate WakeupGate) error
DeleteWakeup removes a wakeup (`job wakeup rm`).
func (*Service) Deliver ¶ added in v0.146.0
func (s *Service) Deliver(jobID string, opts DeliverOptions) (DeliveryResult, error)
Deliver hands the job's worktree branch over and records the outcome on the job. A job run on this machine is delivered here; a job on a worker is delivered on that worker (deliverRemote).
func (*Service) DeliverDue ¶
DeliverDue runs one sweep of the E14 delivery queue (design §5.6): it claims the due pending deliveries (SR303 single-claim via ClaimDueDeliveries), POSTs each webhook row to its target, and records the outcome:
- 2xx => MarkDelivered;
- non-2xx / network / timeout => attempts++, and either MarkRetry with the backoff next_retry_at (SR606) or, once attempts >= MaxAttempts, MarkFailed.
Event hook rows (target "hook:<name>", AUTO-04) are handed to the hook executor, which runs them CONCURRENTLY (at most eventHookParallel at a time) beside the serial webhook POSTs, so a slow hook never delays an IM notification. The sweep waits for its hooks before returning (each bounded by its timeout). The lease semantics are unchanged (at-least-once): the serve loop runs one sweep at a time, so a row is never re-claimed while its own sweep is still running it; the lease only brings a row back after a crash.
It returns the number of deliveries processed (claimed) this sweep. With neither a webhook nor an event hook configured there is nothing to do (returns 0). ctx bounds the whole sweep; each POST / hook run additionally gets its own timeout. The clock is taken from s.nowFn so tests can pin time.
func (*Service) DeliveryModeOf ¶ added in v0.146.0
DeliveryModeOf is the mode a worktree job delivers with under the current config.
func (*Service) DispatchTodo ¶
func (s *Service) DispatchTodo(todoID, by string) (TodoDispatch, error)
DispatchTodo is the EXPLICIT dispatch (`plan dispatch <todo>`, gofer_dispatch_todo): it ignores the todo's status (a `pending` item is a legitimate target — that is the whole point of the fallback) but still requires an assignee and no live job, and it reports a missing assignee as ErrInvalidRequest rather than dispatching nothing.
func (*Service) Drain ¶
Drain is Shutdown that also ends the jobs a worker executes. It is for a process whose remote jobs nobody adopts afterwards — a test tearing down its TempDir.
func (*Service) EndSession ¶
EndSession lets the current turn finish, then closes the resident ACP process.
func (*Service) ExpireHold ¶ added in v0.137.0
ExpireHold cancels a held job whose deadline passed (the expiry sweep's per-job step): awaiting_approval -> cancelled with "hold expired" and job.hold_expired. A job somebody decided first is ErrJobNotAwaitingApproval.
func (*Service) ExpireWakeup ¶
ExpireWakeup disables a wakeup whose TTL has passed and records job.wakeup_expired on the target job. The schedule sweep calls it for every expired row it finds (design §五.1 到期).
func (*Service) FailRecoveringJobs ¶
FailRecoveringJobs fails every job still held in `recovering` — RECOV-01's one-shot window (armed by serve after ReconcileOrphanJobs, or by the hub for a live disconnect) elapsed without the worker proving it still runs the job, so the job can never reach a real terminal state. reason (RECOV-01 uses "worker lost: ...") is what CLI/web then show as the job's error. Best-effort at the caller: serve logs a failure and carries on. Returns the rows failed.
func (*Service) FireWakeup ¶
FireWakeup runs one wakeup trigger (design §五.1). It is the single place a continuation is started, called by the event matcher and by the schedule sweep.
Coalescing (决策 6): a wakeup has ONE continuation slot. A trigger that finds it held by an unfinished continuation only counts a coalesce; the slot is freed when that continuation reaches a terminal state, so a continuous timer keeps working across turns without ever stacking them.
func (*Service) FireWakeupWithPermit ¶
func (s *Service) FireWakeupWithPermit(permit *AdmissionPermit, id, reason string)
func (*Service) Get ¶
Get returns the current snapshot of a job. The in-memory map is authoritative for live jobs; when the id is not tracked in this process (e.g. after a restart, or — from SP3 — a finished job evicted from memory) it falls back to the metadata store. The boolean is false only when neither has the job.
func (*Service) GetArtifactManifest ¶
func (s *Service) GetArtifactManifest(id string) (ArtifactManifest, bool)
GetArtifactManifest resolves a job's artifact manifest and remote-source status. It collects the data-plane logic that previously lived in httpapi.manifestFor + remoteSource: prefer the persisted manifest (ArtifactsJSON, captured at finish), else a live scan of the result dir (always non-nil); and report whether the job ran on a remote machine. An unknown id returns ok=false (handler maps to 404). The HTTP/MCP layers keep the status mapping (404/409).
func (*Service) GetInteractions ¶
func (s *Service) GetInteractions(jobID string) ([]Interaction, error)
GetInteractions returns the job's interactions (latest snapshot per id, in creation order). When the job is still in memory (live) the in-process state is authoritative — it carries the pending-channel state WaitAnswer relies on. Otherwise (evicted after finishing, or never tracked in this process) it falls back to the SQLite interactions table via ListInteractions, which surfaces the terminal job's answered history. An unknown job yields an empty slice.
func (*Service) GetPersisted ¶
GetPersisted returns a job snapshot. The metadata-store fallback now lives in Get (so the after-restart path is covered for every caller), making this a thin alias kept for the existing call sites. base is unused.
func (*Service) GetPersistedInteractions ¶
func (s *Service) GetPersistedInteractions(_ string, jobID string) ([]Interaction, error)
GetPersistedInteractions returns a job's interactions, preferring the live in-memory state and falling back to the SQLite interactions table when the job is not tracked in this process (evicted/after a restart). The SQLite store is a single global DB, so base is no longer needed (kept in the signature to avoid touching callers); this simply delegates to GetInteractions.
func (*Service) GetRetry ¶ added in v0.161.0
GetRetry returns one retry row, ok=false when there is no such row. The HTTP layer reads it to apply the retry's permission rule to the SOURCE job (plan T1.5a).
func (*Service) GetWakeup ¶
GetWakeup returns one wakeup row; ok=false when the id is unknown. Reads are not gated (see ListWakeups).
func (*Service) GoBackground ¶
GoBackground runs fn on its own goroutine as tracked background work, unless Shutdown has started (then fn is dropped and false is returned). It is the seam the workflow engine uses for its asynchronous advances, so Shutdown waits for them too.
func (*Service) IsLeaderJob ¶
IsLeaderJob reports whether jobID is a plan's leader job (MCP-05 阶段 B): the row's server-set marker is the authority — an unknown id is simply not one. The HTTP review gate and the MCP tool surface read it; the job's own agent cannot clear it.
func (*Service) LeaderStatus ¶
func (s *Service) LeaderStatus(planID string) LeaderStatus
LeaderStatus reads a plan's round state: the configured cap, the rounds already spent (the rows that started a leader job) and the most recent one's job id. It never fails: a store error reads as "no rounds", which is what a plan without any looks like.
func (*Service) ListComments ¶
ListComments returns one object's thread, oldest first. An unknown target is ErrUnknownCommentTarget (a 404, not an empty thread).
func (*Service) ListDeliveriesByJob ¶
ListDeliveriesByJob returns a job's webhook deliveries (E14) for the read-only deliveries view, forwarding to the metadata store.
func (*Service) ListJobEvents ¶
ListJobEvents returns a job's append-only lifecycle events in seq order (E13), forwarding to the metadata store. sinceSeq > 0 returns only events after that cursor (the HTTP ?since / SSE incremental path). It does not consult in-memory state: events are durable-only (recordEvent writes them straight to the DB).
func (*Service) ListJobs ¶
ListJobs returns job snapshots across one or all projects, merging the DB-persisted index (metadata store, DB-side filtered/sorted/paginated) with the in-memory live state. The in-memory snapshot wins for any job present in both (it reflects the latest status of a running job). Results are sorted by started_at desc (id desc as tiebreaker) and truncated to opts.Limit.
DB I/O happens without holding s.mu; the in-memory pass copies entry pointers under s.mu and snapshots them after unlocking to avoid taking entry.mu while holding s.mu.
func (*Service) ListMemoryCandidates ¶
func (s *Service) ListMemoryCandidates(f jobstore.MemoryCandidateFilter) ([]jobstore.MemoryCandidate, error)
ListMemoryCandidates lists memory candidates (status "" = pending, "all" = every state).
func (*Service) ListPendingInteractions ¶
func (s *Service) ListPendingInteractions() ([]Interaction, error)
ListPendingInteractions returns the pending interactions across all ACTIVE jobs (E25 监督发现): the data-plane read straight from the metadata store, filtered to non-terminal jobs (jobstore JOINs jobs). Each carries its job_id so the caller can route an answer/escalation. It reads the DB (not the in-memory entries) so it is consistent across the whole serve, not just jobs live in this process.
func (*Service) ListRetries ¶
func (s *Service) ListRetries(jobID string) ([]jobstore.RetryRecord, error)
ListRetries returns a job's durable retry chain (oldest attempt first). Reads are not gated: a retry is job metadata, exactly like the job's events or wakeups.
func (*Service) ListScopedEventsDesc ¶
func (s *Service) ListScopedEventsDesc(scope string, before int64, limit int) ([]jobstore.JobEvent, error)
ListScopedEventsDesc returns a NON-JOB scope's events newest first (LEAD-02): the plan event area walks the stream backwards from a `before` seq cursor. The scope id is the synthetic one the recorders use (PlanEventScope / AgentEventScope / …), the same id RecordScopedEvent writes under.
func (*Service) ListTemplates ¶
ListTemplates lists the templates a project can be driven with: the project's own directory first (shadowing same-named global ones), then <config-dir>/templates. An empty projectKey lists the global directory only; an unknown key is ErrUnknownProject (the HTTP layer maps it to 404).
func (*Service) ListUpdatePaused ¶ added in v0.156.0
ListUpdatePaused returns the parked jobs, newest first (the apply progress names them so a reader can tell "waiting" from "parked").
func (*Service) ListUpgradeRestartBlockers ¶ added in v0.156.0
func (s *Service) ListUpgradeRestartBlockers(excludedIDs []string, limit int) ([]UpgradeRestartBlocker, error)
ListUpgradeRestartBlockers names up to limit of them (oldest first), for the drain log line and for the update progress a person watches. The title is resolved through Get (the jobs table has no title column: it lives in request_json).
func (*Service) ListWakeups ¶
func (s *Service) ListWakeups(jobID string) ([]jobstore.WakeupRecord, error)
ListWakeups returns a job's wakeups (oldest first). Reads are not gated: a wakeup is job metadata, exactly like the job's events or deliveries.
func (*Service) LookupJobToken ¶
func (s *Service) LookupJobToken(token string) (JobTokenLookup, bool)
LookupJobToken resolves a presented credential to its job and kind, and reports whether it is still usable. It is the whole of the server-side credential check: unknown (no row), revoked, or past its fallback deadline all answer false, and the HTTP layer turns that into the same 401 an unknown bearer token gets — a job token that stopped working must not be distinguishable from one that never existed.
func (*Service) MarkInteractionNeedsHuman ¶
MarkInteractionNeedsHuman flags a pending interaction as "punted to a human" by the通用 sup (高危/拿不准, 事件驱动按需派发 y5wt). Like MarkInteractionEscalated it updates the live in-memory rec when the job is still tracked here (so a later upsert preserves the flag instead of resetting it to 0), and always writes the DB row so the cross-process demand read sees it. The interaction stays pending — a human answers it via web/CLI later.
func (*Service) MarkInteractionNeedsHumanBy ¶
MarkInteractionNeedsHumanBy marks an interaction as needing a human and records the authenticated caller that punted it. The metadata update remains the same operation as MarkInteractionNeedsHuman so MCP/agent callers can keep using the original unattributed path.
func (*Service) MaybeDispatchTodo ¶
func (s *Service) MaybeDispatchTodo(todoID, by string) (TodoDispatch, error)
MaybeDispatchTodo dispatches a todo that is BOTH ready and assigned and has no live job (PLAN-02 P2, decision 5). It is what a todo WRITE path calls after storing what the caller sent, so the two conditions may arrive in either order. An unknown todo id is ErrInvalidRequest; everything else (not ready yet, nobody assigned, a job already running) is a normal "nothing to do" result with Reason set and no side effect.
func (*Service) MergeWorktree ¶
func (s *Service) MergeWorktree(jobID string, opts MergeOptions) (MergeResult, error)
MergeWorktree merges a managed local worktree branch into the project's main checkout. The main checkout must be clean and attached to a named branch. A conflict is fully aborted before the typed error is returned; no push occurs.
func (*Service) Meta ¶
Meta / Now / Config / Metrics / Validate are the narrow accessor surface the workflow sub-package consumes through its JobOps interface (layering design §13.3). They expose existing private state/behaviour read-only without widening it further; Service thereby satisfies workflow.JobOps structurally (no workflow import here).
func (*Service) Metrics ¶
func (s *Service) Metrics() MetricsSink
func (*Service) NotifyEvent ¶
NotifyEvent enqueues a pre-rendered notification for every webhook subscribed to eventType (and to projectKey, when the webhook filters projects). Unlike the job-event path it needs neither a job nor a row in `events`: the body is rendered per webhook kind now and stored on the delivery, so the queue's retry/backoff/audit apply unchanged.
Every matching event hook (AUTO-04) gets a row too, carrying the GENERIC JSON rendering (the same body a generic webhook receives), and — like the job-event path — without the notification pause switches or the project's notify_enabled.
It is best-effort and never fails the caller: notification is a side channel, so every problem is logged and swallowed. Returns how many deliveries were enqueued (0 when nothing subscribes — the common case).
func (*Service) NotifySessionAttention ¶
NotifySessionAttention is raised when a relayed session enters needs_attention (SESS-01 → OBS-07a). The link goes to the session page so the human can see WHICH session is blocked, but the answer has to happen in the terminal — the message says so.
func (*Service) NotifySessionHandedOff ¶
NotifySessionHandedOff is raised when a session is taken over by a new interactive pty job (SESS-01 §9.1 B, the `--resume` path): the conversation continues in THAT job's terminal, so the link goes to the job (which attaches the pty), not back to the session drawer that has nothing left to answer.
func (*Service) NotifySessionNudgePaused ¶
NotifySessionNudgePaused tells the person a session nudge stopped itself after repeated delivery failures (sessionrelay.NudgeNotifier). The link opens the session drawer, where the nudge can be resumed once the session is reachable again.
func (*Service) NotifySessionTakeoverReleased ¶
NotifySessionTakeoverReleased is the DUAL of NotifySessionHandedOff (SUP-02 R1): the pty job that held the session ended, so the conversation is back with the terminal that registered it — the web can answer it again and a human who was told to move to the job's terminal can come back. reason is why the job ended ("job_done" / "job_failed" / …), which the message states so an operator can tell "the work finished" from "the takeover crashed".
func (*Service) NotifySessionWaiting ¶
func (s *Service) NotifySessionWaiting(sessionID, projectKey, title, lastMessage string, turn int64)
NotifySessionWaiting is the session-relay notifier (SESS-01 → OBS-07a): a relayed session stopped and is waiting for a human reply. It satisfies the sessionrelay.Notifier seam, so that package stays free of notification and config concerns.
func (*Service) NotifyUpdateAvailable ¶ added in v0.154.0
NotifyWork is the work-item notifier (W1): work.remind and work.digest. It renders like every other IM notification (so max_text_runes applies) and is a no-op when no webhook subscribes. NotifyUpdateAvailable sends update.available (gofer-29gi): a newer gofer release was found. It is a server-wide event, so no project filter applies.
func (*Service) NotifyWork ¶
func (*Service) OnJobEnded ¶ added in v0.160.0
func (s *Service) OnJobEnded(fn JobEndedHook)
OnJobEnded registers an ended-hook (see JobEndedHook). Called once at assemble time; safe for concurrent use with running jobs (the list is copied under the mutex before any hook starts).
func (*Service) OnTerminal ¶
func (s *Service) OnTerminal(fn JobTerminalHook)
OnTerminal registers a terminal hook (see JobTerminalHook). It is called once at assemble time, may be called more than once, and is safe for concurrent use with running jobs: the hook list is copied under a mutex before any hook is started.
func (*Service) OpenUpgradeAdmission ¶
func (*Service) PausePlan ¶
PausePlan holds a plan's automatic chain advance: a todo that finishes while paused stays finished, but nothing after it starts (PLAN-03). advancePlan records plan.advance_paused instead of moving, so the pause is visible in the event stream.
func (*Service) PauseStartsForUpdate ¶ added in v0.156.0
PauseStartsForUpdate stops every NEW job from starting until ResumeStartsForUpdate: the update that owns applyID is waiting for the machine to go idle before it restarts the server. Jobs already running are untouched, and the submit still answers normally (the job is admitted and parked, never refused).
The pause belongs to the PROCESS. It is not persisted, so a server that restarts does not resume a pause whose update is gone — it releases the parked jobs instead.
func (*Service) PlanTodoChanged ¶
PlanTodoChanged reacts to a todo STATUS write (PLAN-03). Every write path that moves an item calls it after storing what the caller sent, because the two things it does depend on the item having moved:
- an item that was the one a plan blocked on releases the block (ready/skipped/done are all a human's answer — "I fixed it", "skip it", "it is done after all");
- the chain then advances, so `plan set-todo <todo> --status done|skipped` moves the plan exactly like a job's terminal hook does.
It never fails its caller: a todo write must not be undone by a plan write.
func (*Service) PreviewDelivery ¶ added in v0.148.0
func (s *Service) PreviewDelivery(jobID string, opts DeliverOptions) (DeliveryPreview, error)
PreviewDelivery plans a delivery without executing or recording it.
func (*Service) PreviewTemplate ¶
func (s *Service) PreviewTemplate(projectKey, name string, vars map[string]string) (template.Preview, error)
PreviewTemplate resolves ONE template for a projectKey (same lookup order as a submit) and renders it with vars — the read-only preview behind `template show` and the console's submit form. Rendering here (rather than in the client) is what makes the preview show the same text a submit would send: includes are expanded and {{head}} is the SERVER's project checkout. A missing required var is reported in Render.Missing, not as an error: a preview of an incomplete invocation is exactly what a reader is asking for.
func (*Service) Prune ¶
Prune enforces the configured retention policy (storage.retention): it evicts terminal jobs from the metadata store per the policy and best-effort removes each evicted job's on-disk log directory. It returns the number of jobs deleted.
Only terminal jobs are touched (PruneJobs guarantees this); live jobs in memory are unaffected — an evicted job is, by definition, already terminal and no longer in s.jobs. When retention is unconfigured the policy is zero and PruneJobs is a no-op, so Prune is safe to call unconditionally.
It ALSO prunes terminal workflows past their (independent) age (P1, design §5.4 / D22) — connected step-jobs + workflow_events are removed连带 (PruneWorkflows), then their result dirs are best-effort cleaned. The returned count is the JOB count (the loose-job prune); the workflow prune's own count is logged separately (PruneWorkflowsCount). Standalone jobs that happen to belong to a NOT-yet-aged workflow are not double-counted: the job age policy and the workflow age policy are independent and each removes its own victims (a step-job is removed either by its workflow's prune or by the loose-job prune, whichever first selects it; the deletes are id-keyed and idempotent across passes).
func (*Service) Ran ¶ added in v0.163.0
Ran reports whether a job ever BEGAN executing. EventJobRunning is appended exactly once — by the process that starts the job, or by a worker's own started callback for a forwarded one — and a job withdrawn, released or rejected before that point ends without it, so this is the one question a caller can ask before stating that nothing of the job can still happen. gofer-qzv5 asks it about a delivery job it withdraws: only a job that never ran lets the message it carried be retried safely.
func (*Service) RebuildJob ¶
func (s *Service) RebuildJob(jobID string, ov RebuildOverrides, callerID, clientIP string) (JobResult, error)
RebuildJob starts a NEW job from the SOURCE job's persisted request_json (P5, D1). It takes that request as the base, applies the caller's edited overrides + env merge, then STAMPS the lineage/identity fields server-side and Submits. The base env (real values, from request_json) is merged in memory and is never serialized back out of gofer: only env_set/env_unset touch it. Default async (like ResumeJob); the caller watches the new job. callerID/clientIP are stamped by the HTTP entry (anti-spoof), mirroring Submit.
SECURITY (accepted, P5 v0.3 §安全声明): overrides may edit the EXECUTION BODY (prompt/cmd/agent/agent_args/system_prompt) while the source env is inherited. A caller holding a token can therefore make the new job print the inherited env to stdout and read it back via the job log endpoints. Redacting GET /request stops the ACCIDENTAL exposure (env in UI prefill / screenshots / API responses), NOT a malicious caller — gofer is single-trust-tier: a token means "may run arbitrary commands". Audit relies on the lineage columns: the new job records source_job_id plus the initiator's caller_id.
func (*Service) ReconcileAdoption ¶
func (s *Service) ReconcileAdoption(workerID, instanceID string, inflight []WorkerInflightJob, backend AdoptBackend) (map[string]*AdoptedJob, []string)
ReconcileAdoption implements the hub's RECOV-01 R4 adoption seam: it reconciles the jobs THIS store holds in `recovering` for workerID against a worker process that just registered with instanceID and reported inflight.
Per store-held row:
- the row records exactly this process instance AND the worker still reports the job in flight ⇒ ADOPT it: a live handle (log writers + entry) is rebuilt and returned so the hub can attach it to the new connection, hand back the offsets it must rewind to, and return the job to `running`.
- anything else (a different/absent instance, or a job the reconnecting worker no longer tracks) ⇒ FAIL it here and now with adoptLostReason. Waiting out the window would only delay a foregone conclusion: no process can ever finish that job. The failed ids are returned for the hub to log.
Adoption also wakes serve's one-shot startup window (AdoptionWake) so the window can see whether anything is still unclaimed.
func (*Service) ReconcileOrphanInteractions ¶
ReconcileOrphanInteractions flips pending interactions of already-terminal jobs to cancelled (crash-recovery backstop for finish()'s in-memory reconciliation, 复审 #4). Returns the rows fixed. Serve calls it once at startup.
func (*Service) ReconcileOrphanJobs ¶
ReconcileOrphanJobs resolves the jobs left non-terminal (queued/running) in the store by a serve that died / restarted mid-flight — their in-memory orchestration (dispatch entry / worker sink) did not survive. Two outcomes (RECOV-01):
- worker job: HELD in `recovering` with recovering_since stamped, because the worker process may still be running it and reconnect within the recovery window. "Worker job" covers both a non-empty worker_id and a runner=worker row whose worker_id is empty (the D4 default-worker fallback is resolved at dispatch time, so such a row is classified by its runner). The new serve's hub ADOPTS the row when the same worker process reconnects and reports it in `inflight` (R4); the one-shot window only ends whatever nobody claimed.
- local/peer job: failed, as before — no in-process registry entry survived, so nothing could ever finish it and it would hang "running" forever.
Mirrors ReconcileOrphanInteractions; serve calls it once at startup, before new work is accepted (the in-memory map is empty, so no live job is touched). Returns the rows resolved (held + failed).
func (*Service) ReconcileSessionState ¶
func (s *Service) ReconcileSessionState(workerID string, inflight []WorkerInflightJob)
ReconcileSessionState applies the worker's authoritative resident-session snapshot after a reconnect or server restart. The persisted event stream is the deduplication source: a missing job+turn+state event is written once with replayed=true, then later reconnects observe it and do nothing.
func (*Service) RecordJobEvent ¶
recordEvent appends one append-only lifecycle event for a job (E13, design §5.2). It is BEST-EFFORT: a marshal failure, an oversized detail or a write error only logs a warning — it MUST NOT panic and MUST NOT influence the job's terminal state (the same iron rule as captureOutcomes). detail must not carry secrets (SR403); callers pass only descriptive metadata.
detail is marshalled to JSON; a nil detail or a payload exceeding MaxEventDetailBytes records an empty detail rather than failing. RecordJobEvent records an event on a JOB's timeline from a write path that is not the job's own execution (the schedule webhook, AUTO-02b): the same table row and the same webhook fan-out as the internal recordEvent, exposed because the HTTP layer knows something the job does not.
func (*Service) RecordScopedEvent ¶
RecordScopedEvent appends one event on behalf of a NON-JOB scope (XFER-01 X2): a transfer's audit event is recorded under the synthetic id `xfer:<id>` and then runs through the SAME pipeline a job event does — the durable log, the E14 webhook enqueue (matched by projectKey, which a scope id cannot resolve back to a project on its own) and the mirror observer. It is the seam internal/xfer's EventSink is wired to at assembly, so a transfer subscriber sees xfer.put|xfer.get without the xfer package knowing anything about notifications or jobs.
Best-effort exactly like recordEvent: a failed audit/notification write must never affect the transfer.
func (*Service) RedactedRequest ¶
RedactedRequest returns the JobRequest a job was created from, SECRET-STRIPPED for safe read (P5, h-aii-xqe1): this is the DEFAULT and ONLY shape GET /request returns (there is no verbatim path — the rerun re-submit went server-side to RebuildJob). env values → Placeholder (wholesale — env is the main leak surface; a redacted read only SHOWS keys, values never leave the server), and prompt/cmd/cwd/system_prompt/agent_args run through secret.RedactString (workflow parity; agent_args is the --flag secret vector, v0.3). It also CLEARS read-noise: RequestID, CallerID, SessionID (a request read must not resurrect an idempotency key or a session binding). The second bool reports whether anything was redacted (surfaced via X-Gofer-Redacted so a UI marks fields as "originals kept server-side").
Cwd is already the ORIGINAL RELATIVE path (parsed out of request_json, marshalled pre-resolution submit.go:110 — NOT reconstructed from JobResult.Cwd's absolute path). ok=false when the job is unknown or has no stored request.
func (*Service) RejectJob ¶
func (s *Service) RejectJob(jobID, by, note string, resume bool) (ReviewOutcome, error)
RejectJob records a human's拒绝 of a needs_review job: needs_review -> the terminal rejected (a workflow aggregates it as a failure; retention collects it; nothing retries or auto-continues it). note is REQUIRED — it is the reason recorded in the audit trail and, with resume, the continuation's prompt. resume starts that continuation (ResumeJob with the note as its prompt) and reports it in ReviewOutcome.ResumeJobID + the job.reviewed detail; when the continuation cannot be started the rejection still stands and the returned error says why.
gofer-9b1b: a job awaiting approval is rejected as a HOLD instead (rejectHold) — it never ran, so the note is optional and there is nothing to resume (resume → ErrHoldResume). The dispatch is by the job's current state, so one reject endpoint serves both.
func (*Service) RejectMemoryCandidate ¶
RejectMemoryCandidate marks a pending candidate rejected (nothing is written anywhere else).
func (*Service) Reload ¶
Reload atomically swaps the service's config to newCfg (C3 SIGHUP hot-reload). It is safe to call concurrently with Submit/ListJobs/Prune; in-flight calls keep using the snapshot they already loaded.
func (*Service) ReloadRunners ¶
ReloadRunners atomically replaces the concrete runner registry used by new submissions. In-flight jobs keep their already selected runner instance; additions and removals therefore take effect without disturbing work that is already running.
func (*Service) RemoveWorktree ¶
func (s *Service) RemoveWorktree(jobID string, force, deleteBranch bool) (WorktreeStatus, error)
RemoveWorktree removes a job's managed worktree (WT-01 `job worktree rm`). It refuses when the worktree still has uncommitted changes unless force is set, and optionally deletes the branch (the deliverable — hence opt-in). The job row's worktree_path is cleared on success so `ls` stops advertising a checkout that is gone; branch/base/head stay for audit.
func (*Service) ResumeJob ¶
ResumeJob starts a NEW job that续接 the底层 agent CLI 会话 of an existing job (session-capture P2, design §5.2). It looks up the source job's captured SessionID / agent / runner / cwd, renders the agent's SessionResume template into an exec argv ([command] + resume args), and submits it as an exec job on the SAME runner with SessionID set so the new job链 round-trips to the same session. The编排 lives here in the job Service (G021): HTTP/CLI入口 only bind + 转发 + map the sentinels below to status codes.
callerID is the authenticated submitter (stamped by the入口 from its auth context, anti-spoof, mirroring Submit). runner is the OPTIONAL caller-supplied target runner: when empty the source runner is used; when non-empty it must equal the source runner (同 runner 约束) — a mismatch is ErrCrossRunner.
func (*Service) ResumeJobWith ¶
func (s *Service) ResumeJobWith(jobID, prompt, runner, callerID string, opts ResumeOptions) (JobResult, error)
ResumeJobWith is ResumeJob with an explicit continuation form (opts.Mode) and/or target agent (opts.Agent). A zero ResumeOptions is exactly ResumeJob.
func (*Service) ResumePlan ¶
ResumePlan releases a pause AND a block, then advances: it is the human's "carry on" for a plan that stopped for either reason (PLAN-03). The item a block named keeps its status — resume continues from wherever the chain is, it does not re-run the failed item (that is `plan set-todo <todo> --status ready`).
func (*Service) ResumeStartsForUpdate ¶ added in v0.156.0
ResumeStartsForUpdate ends the pause (if any) and releases every job it parked: the original request runs again under the job's own id. It is called by the new server at startup (the previous process parked rows and died / was replaced), by the apply when it fails, times out or is cancelled, and by `update cancel`.
It is idempotent and safe on a server that never paused anything: no flag, no parked rows, nothing to do. Returns how many jobs it released.
func (*Service) RunPlan ¶
RunPlan starts a plan's chain: `plan run <plan>` (PLAN-03). It releases a pause and a block, then queues every pending item whose dependencies are satisfied AND that has an assignee — roots included, which is exactly what advancePlan refuses to do on its own. The auto flag is NOT consulted here: a human typing `plan run` is asking for the ready work to start, and `--no-auto` exists to keep the CHAIN from starting an item, not to stop an explicit run.
func (*Service) SaySession ¶
SaySession queues the next prompt on the same resident ACP job.
func (*Service) SetEventObserver ¶
func (s *Service) SetEventObserver(fn JobEventObserver)
SetEventObserver installs (or with nil, clears) the mirror observer. It is called once by the worker client before it starts running jobs; recordEvent reads it on every event, so the two are ordered by the atomic swap rather than by a lock the event path would have to take.
func (*Service) SetEventTap ¶
SetEventTap installs (nil clears) the single push tap. Unlike AddEventObserver it is handed the seq and the raw detail string, which the hub forwards verbatim.
func (*Service) SetIssueLinker ¶
func (s *Service) SetIssueLinker(linker IssueLinker)
func (*Service) SetMetrics ¶
func (s *Service) SetMetrics(m MetricsSink)
SetMetrics injects the E16 lifecycle-counter sink (design §6). It is called once at assemble time (commands.buildCore) before the service starts handling jobs; passing nil leaves metrics disabled (every埋点 is a no-op).
func (*Service) SetRuleLibrary ¶
func (s *Service) SetRuleLibrary(l RuleLibrary)
SetRuleLibrary installs the rule-library seam. Without one, a job that binds a rule fails validation with an explanation instead of running without it.
func (*Service) SetSessionID ¶
SetSessionID records a newly observed underlying agent CLI session id for a job. It is best-effort and additive: an existing session_id is never replaced. The PTY relay uses this for interactive agents whose session id is printed to terminal output instead of stdout/stderr logs.
func (*Service) SetSkillLibrary ¶
func (s *Service) SetSkillLibrary(l SkillLibrary)
SetSkillLibrary installs the skill-library seam. Without one, a job that binds a skill fails validation with an explanation instead of running without it.
func (*Service) SetTitle ¶
SetTitle changes only the human-readable title. It works for live entries and for terminal jobs that have already been evicted from memory.
func (*Service) SetUncommittedDecisionOnly ¶
SetUncommittedDecisionOnly is set during worker assembly, before jobs start. The worker still detects with the pushed policy; the hub owns transitions.
func (*Service) SetWakeupEnabled ¶
func (s *Service) SetWakeupEnabled(id, by string, enabled bool, gate WakeupGate) (jobstore.WakeupRecord, error)
SetWakeupEnabled flips a wakeup's switch (`job wakeup enable|disable`). Enabling a TIMER re-arms it from now (design §五.1: every 从创建/启用时起算, 不补发), so a wakeup that was off for a week does not fire a week of missed ticks; enabling an `at` keeps its instant (an already-past one fires on the next sweep — the operator asked for it again).
func (*Service) SetWorkflow ¶
func (s *Service) SetWorkflow(w WorkflowAdvancer)
SetWorkflow injects the workflow engine (the WorkflowAdvancer seam). It is called once at assemble time (internal/core) after the service is built; passing nil (or never calling it) leaves workflow advancement disabled (finish is a no-op for the workflow path).
func (*Service) SetXferBridge ¶
func (s *Service) SetXferBridge(b XferBridge)
SetXferBridge installs the job file-transfer seam. It is wired at assemble time (core.Build for a hub, the worker command for a worker); without one a job that asks for uploads fails cleanly with an explanation and a collect-only job records its matches without moving bytes.
func (*Service) Shutdown ¶
Shutdown is the job service's close protocol (design §2.2). After it returns, no job this process executes and no background work of the service touches the store, so the caller may close it:
- admission closes for good — Submit, workflow advances and wakeups are refused — and the producers already admitted are waited for;
- every job this process executes is cancelled; the jobs a worker executes are left alone (see below);
- the cancelled jobs are waited for until their execute goroutine has returned (entry.done), not merely until their status reads terminal;
- the background work (finish, terminal hooks, advances, timers) is waited for.
A job cancelled here keeps the nonterminal row it had, exactly as if the process had exited: the next serve's startup reconcile settles it as it always did (a local job fails as orphaned, a resident ACP session is resumed). Finishing it as cancelled instead would read as a user's cancel — no retry, the workflow and plan would follow it — on every restart.
A job a worker executes (the set ReconcileOrphanJobs holds in `recovering`) is not cancelled: that would send the worker a cancel frame and end work the next serve adopts. It is not waited for either. Drain also ends those, for a teardown no later serve follows.
ctx bounds the whole protocol; on expiry the error says which phase was left unfinished. Shutdown is idempotent.
func (*Service) ShutdownResidentSessions ¶
ShutdownResidentSessions stops local ACP processes while leaving their persisted jobs recoverable. It runs after HTTP admission closes and before the store closes.
func (*Service) Stats ¶
func (s *Service) Stats() ServiceStats
Stats returns a live snapshot of the in-flight job set for the metrics GaugeFuncs (design §6.4). It is evaluated at scrape time, so the critical section is kept short. Lock order is s.mu THEN entry.mu, matching every other Service path (Submit/finish) so there is no reverse-hold deadlock.
func (*Service) Submit ¶
func (s *Service) Submit(req JobRequest) (JobResult, error)
Submit validates the request, creates the result dir, persists the request and starts the job asynchronously. It returns the initial JobResult (status running) once the goroutine is launched. Validation/setup failures return an error and no job.
func (*Service) SubmitSync ¶
SubmitSync submits a job and, when synchronous semantics are requested, blocks until it reaches a terminal state (capped). It collects the sync-wait policy that previously lived in httpapi.handleCreateJob (Submit + WaitFor + clampWait + async fallback判定), so the handler only maps the outcome to HTTP表现 (200 / 202 + X-Gofer-Async). The wantSync decision (?wait=1 query param) stays in the handler — it is an HTTP-transport concern — and is passed in via sync.
Returns:
- out: the JobResult to hand back to the client — the terminal result when a sync wait succeeded, otherwise the initial submit snapshot (also the snapshot to return when async fallback kicks in);
- async: true when the wait exceeded the server cap while still running (the job keeps running in the background; the client should switch to polling);
- err: a Submit rejection (handler maps via submitStatus).
func (*Service) SubmitWithPermit ¶
func (s *Service) SubmitWithPermit(permit *AdmissionPermit, req JobRequest) (JobResult, error)
SubmitWithPermit continues an already admitted internal producer. Callers must hold the permit across their prior durable claim and this submission.
func (*Service) SweepDueLeaderWakes ¶
SweepDueLeaderWakes starts the leader job of every armed round that has come due, and reports how many it started. It is the ONLY place a leader job is submitted (mirroring SweepDueRetries): the row is what makes a pending round survive a restart, and the claim is what keeps two sweeps (or a sweep and a reload) from starting the same round twice.
A round that cannot start is never silent: the reason goes to the plan's event stream and the round is released (transient: a submit failure) or cancelled (terminal: the plan vanished, or its budget was spent in the meantime).
func (*Service) SweepDueRetries ¶
func (s *Service) SweepDueRetries(now int64, limit int, lease int64) (started, failed int, err error)
SweepDueRetries runs ONE pass of the durable retry queue (R2/AUTO-03): claim up to limit due rows with a lease, and submit each as its own new job. internal/serve's retry loop calls it every tick; tests drive the same function directly.
Per claimed row:
- submit the stored request as attempt rec.Attempt (no idempotency key, always async), tagged `retry` / `retry_of:<source job>` so the re-run is findable;
- on success mark the row done (recording new_job_id) and record job.retry_started on the SOURCE job's timeline;
- on failure RELEASE the row with the next backoff step, so the retry is late by one step instead of lost, and count it as failed.
A row whose request_json cannot be decoded can never be submitted: it is cancelled (with a warning) rather than re-claimed on every tick forever.
The fields request_json cannot carry are restored here: JobRequest.Attempt comes from the row's own column (it is json:"-"), and CallerID / SourceJobID from the source job's row — exactly the values the in-process path restored from the snapshot before submission.
started/failed count the rows submitted and the rows that could not be, so the caller can log a tick without parsing anything; a store-level failure (the claim query itself) is returned as err and nothing is submitted.
func (*Service) SweepExpiredHolds ¶ added in v0.137.0
SweepExpiredHolds cancels every held job whose deadline is at or before now (unix seconds) and reports how many it expired. A job decided between the scan and its CAS is skipped silently — that decision won. Called by serve once at startup and then periodically, so holds that expired while the server was down end on boot.
func (*Service) TailLog ¶
TailLog returns the last maxBytes of a job's stdout/stderr (whole file when maxBytes<=0). It locates the FileStore base from the job's ResultDir, mirroring httpapi serveLog. Returns an error if the job id is unknown.
func (*Service) UpdatePauseOwner ¶ added in v0.156.0
UpdatePauseOwner is the apply id of the update currently pausing new jobs ("" = none). Also the switch Submit reads while the server is draining for that update.
func (*Service) UpgradeAdmissionOwner ¶
func (*Service) UpgradeIdleSessionIDs ¶
UpgradeIdleSessionIDs returns the resident ACP jobs that may stay open across a server restart, so the upgrade drain does not wait for them:
- local sessions the shutdown path preserves and recovers with session/load;
- worker sessions: the ACP process belongs to the worker, which keeps it across a server restart; the row is held as recovering and adopted when the same worker process reconnects (it needs a recorded instance id).
Only idle sessions qualify (awaiting input, nothing queued, not ending). The bridge calls this after closing admission, so SaySession cannot queue another turn during the census.
func (*Service) Validate ¶
func (s *Service) Validate(cfg *config.Config, req JobRequest, remote bool) (config.ProjectConfig, error)
Validate exposes the single-job admission check (project/agent/runner allowlist + exec gate) so the workflow engine validates every step through the SAME gate (安全要点). It wraps the private validate unchanged, after normalizing the runner spelling exactly as Submit does — a workflow step (or the schedule validator at internal/httpapi/schedule_handler.go) may name the built-in runner with either spelling, and it must not be admitted any differently.
func (*Service) ValidateUpgradeSource ¶
ValidateUpgradeSource binds a direct local exec job to the CLI process that requested an upgrade. The control file's SourceJobID is never trusted alone. A wrapper or descendant cannot be excluded from drain with this seam.
func (*Service) Wait ¶
Wait blocks until the job reaches a terminal state, then returns its final snapshot. It is primarily a test/HTTP helper. The boolean is false for an unknown job id.
After SP3 a finished job is evicted from the in-memory map. A Wait caller that grabbed the live entry before eviction still unblocks on entry.done (the execute goroutine closes it after finish returns) and returns the terminal snapshot. A Wait that arrives only after eviction sees entry==nil and falls back to the metadata store: a known job is already terminal, so its persisted record is returned immediately without blocking; an unknown id returns false.
func (*Service) WaitAnswer ¶
WaitAnswer blocks until the interaction is answered/cancelled or ctx is done, returning the final Interaction. Used by in-process wrappers/tests.
func (*Service) WaitEndedHooks ¶ added in v0.160.0
WaitEndedHooks waits up to timeout for the service's background work to return — ended-hooks included, since they run through the same background group as the terminal hooks (WaitTerminalHooks). Whoever closes the store waits here first.
func (*Service) WaitFor ¶
WaitFor blocks until the job reaches a terminal state OR timeout elapses. It is the bounded counterpart of Wait used by the synchronous-submit HTTP path (design §6.1 / P1-a).
ok=false means the wait timed out (the job is still running in the background — it is NOT cancelled) or the id is unknown. A job already evicted to a terminal DB record returns ok=true immediately via the metadata-store fallback (mirrors Wait). timeout<=0 degrades to Wait (block forever; test-only).
func (*Service) WaitTerminalHooks ¶
WaitTerminalHooks waits up to timeout for the service's background work — the terminal hooks started so far, and the finishes still dispatching theirs — and reports whether it all returned. A hook may still touch the store after the job is terminal, so whoever closes the store waits here (or in Shutdown) first.
func (*Service) WatchJob ¶
WatchJob subscribes to change signals of one job (status persisted, lifecycle event recorded, interaction raised/answered — every one of those writes an event or persists the job). The returned cancel func unsubscribes and must be called. It is the event-driven replacement of the SSE stream's former DB polling.
func (*Service) WebURL ¶
WebURL resolves a console path against server.web_base_url ("" when unset), so other services (the work-item reminders) can put a tappable link in a notification.
func (*Service) WorktreeStatus ¶
func (s *Service) WorktreeStatus(jobID string) (WorktreeStatus, error)
WorktreeStatus returns the live state of the job's managed worktree. It is a read-only probe: git failures downgrade to "not a live worktree" (Exists=false) rather than erroring, so `job worktree ls` still lists the branch a job delivered even when its checkout is gone.
type ServiceStats ¶
ServiceStats is the live in-memory job snapshot the metrics GaugeFuncs read at scrape time (design §6.4): InFlight = entries currently tracked in s.jobs (queued+running+pending, since terminal jobs are evicted in finish), Queued / Running break that down by status.
type SessionCommandSender ¶
type SessionCommandSender interface {
SendSessionCommand(workerID, jobID, cmdID, action, prompt string) error
IsWorkerOnline(workerID string) bool
}
SessionCommandSender is an optional transport seam implemented by the live worker selector. It keeps job command handling independent from wshub while allowing remote say/end requests to use the same job service API.
type SkillInfo ¶
type SkillInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Files []SkillFile `json:"files,omitempty"`
Size int64 `json:"size,omitempty"`
}
SkillInfo is what the job package needs to know about one library entry: what to put in the prompt list and which files to carry to a worker.
type SkillLibrary ¶
type SkillLibrary interface {
// Get returns one entry's metadata; ok=false means the name is unknown (a submit
// naming it is rejected rather than run without its rules).
Get(name string) (SkillInfo, bool)
// Mount copies the whole skill under dstDir (the result dir's `skills/`) and
// returns the bytes written. It is how a LOCAL job gets its files.
Mount(name, dstDir string) (int64, error)
// Stage turns each of the skill's files into a staged put transfer targeting
// runner and returns one UploadSpec per file, all with Base=result_dir — the
// worker fetches the bytes over its own authenticated HTTP session. It is how a
// WORKER job gets its files.
Stage(ctx context.Context, name, runner, projectKey, caller string) ([]UploadSpec, error)
}
SkillLibrary is the server's skill asset library as this package needs it. *skill.Store-backed adapter is wired at assemble time (core.Build for a hub, the worker command for a worker).
type TodoDispatch ¶
TodoDispatch is the outcome of one dispatch attempt. Job is nil when no job was created — Reason then says whether a precondition was simply not met yet (the todo was not ready, nobody was assigned, a job is already running) or the Submit itself was refused (and the same text is stored on the todo as dispatch_error).
type UpgradeRestartBlocker ¶ added in v0.156.0
type UpgradeRestartBlocker struct {
ID string
Title string
Status string
Runner string
StartedAt int64
}
UpgradeRestartBlocker is one job the census is waiting for, as the update progress reports it to a person: the id to click, a title to recognise it by, and what it is doing.
type UploadSpec ¶
type UploadSpec struct {
XferID string `json:"xfer_id" yaml:"xfer_id"`
Dest string `json:"dest" yaml:"dest"`
// Base picks the directory on the EXECUTING machine that Dest is relative to:
// "" / "cwd" = the job's working directory (the pre-JOB-10 reading, unchanged),
// SkillBaseResultDir = the job's private result dir (the skills mount). The wire
// and yaml tags mirror each other so the md+yaml task-file path can carry one too.
Base string `json:"base,omitempty" yaml:"base,omitempty"`
}
UploadSpec is one file that travels with a job (XFER-01 X2): a staged transfer id plus the destination on the EXECUTING machine, relative to the job's cwd. The wire and yaml tags mirror each other so the md+yaml task-file path can carry one too.
type Usage ¶
Usage is the runner package's token/cost accounting (SUP-01 E), aliased for the same reason as VerifyResult: one definition describes a local capture and a remote machine's回传 value. See runner.Usage for the field meanings.
type VerifyResult ¶
type VerifyResult = runner.VerifyResult
VerifyResult / the verify statuses are the runner package's types, aliased here: the same value describes a local run and a worker's回传 result, and job already imports runner. See runner.VerifyResult for the field meanings.
type WakeupGate ¶ added in v0.161.0
WakeupGate is the entry layer's answer to "may a caller that is NOT this job's own caller act on its wakeups?" — the permission job.wake.others of the request (design §五.1 权限, migrated to the permission model in plan T1.5a). It is a parameter rather than a field so the decision stays per request and the job layer never reads the caller configuration.
A nil gate refuses (fail closed): an entry that cannot decide must not open the bypass.
type WakeupSpec ¶
type WakeupSpec struct {
// JobID is the job the wakeup is registered on: the job a fire CONTINUES. It is
// taken from the request path (HTTP) / the CLI's <job> argument and is ignored
// when the caller passes one in the body.
JobID string `json:"job_id,omitempty"`
// Kind is one of jobstore.WakeupKind* (required).
Kind string `json:"kind"`
// At is the absolute fire instant for kind=at; it must be in the future.
At int64 `json:"at,omitempty"`
// EverySec is the repeat interval for kind=every (>= 60).
EverySec int64 `json:"every_sec,omitempty"`
// Cron / Timezone describe the schedule for kind=cron (a standard five-field
// expression; an empty timezone means the server's local time).
Cron string `json:"cron,omitempty"`
Timezone string `json:"timezone,omitempty"`
// EventTypes are the subscribed event types for kind=event (catalog-checked).
EventTypes []string `json:"event_types,omitempty"`
// FilterJobID is the SOURCE job whose events are watched; empty means the job
// the wakeup is registered on (the common case: "warn me when I finish").
FilterJobID string `json:"filter_job_id,omitempty"`
// FilterStatus narrows kind=event + job.terminal to these terminal statuses
// (done/failed/cancelled/rejected); empty means every terminal status.
FilterStatus []string `json:"filter_status,omitempty"`
// Mode is jobstore.WakeupModeOnce / Continuous; empty defaults to once for
// at/event and continuous for every/cron.
Mode string `json:"mode,omitempty"`
// Instruction is the prompt the continuation receives (design §五.1).
Instruction string `json:"instruction,omitempty"`
// ExpiresAt overrides the configured TTL (0 = now + wakeup.ttl_sec).
ExpiresAt int64 `json:"expires_at,omitempty"`
}
WakeupSpec is the (client-settable) shape of one wakeup registration. It is the JSON body of POST /v1/jobs/{id}/wakeups, the CLI's flag set and the MCP tool's arguments — one type, so the three surfaces cannot drift.
Every instant is unix SECONDS (the wire/time convention of this project): the CLI turns `--after 10m` / `--at <RFC3339>` into an absolute At, so the server never has to guess a client's clock offset from a duration.
type WorkerCandidate ¶
type WorkerCandidate struct {
WorkerID string
Labels []string
// Projects / Agents are the capability keys the worker reported on register
// (authoritative, P1). They carry the worker's own view of what it can run so
// the host can validate/filter against it without importing wshub.
Projects []string
Agents []string
// AgentCaps is the worker-reported typed agent capability list (P2 register),
// keyed the same as Agents. nil on an old worker that predates agent_caps
// (or on the local runner, which never populates this field) — the G2 gate
// must fall through unchanged in that case, not reject.
AgentCaps []AgentBrief
// InteractiveProjects is the worker's effective project policy. A nil slice
// means the worker did not report this capability.
InteractiveProjects []string
ProtocolVersion int
ProtocolKnown bool
InFlight int
PtyCapable bool
// Draining is true while the worker is upgrading itself: it finishes what it runs
// but takes no new job, so label selection skips it.
Draining bool
// HeartbeatAge is the time since the worker's most recent inbound frame
// (smaller = fresher). A candidate older than workerStaleAfter is excluded.
HeartbeatAge time.Duration
// PolicyPending is true when the worker negotiated server-side policy push (P3 T4)
// and the hub pushed a policy rev the worker has not yet reported applied. It NEVER
// adds a rejection: a pending worker is still running its previous, fully valid config
// and dispatch keeps working, so admission uses it ONLY to swap in a clearer error
// message when the requested project happens not to be in the reported caps yet.
// PolicyRev/AppliedRev are the pushed/applied revs (diagnostics for the message).
PolicyPending bool
PolicyRev int64
AppliedRev int64
}
WorkerCandidate is the neutral, point-in-time snapshot selectWorker scores. It is populated by the commands layer from the hub registry (see commands.hubWorkerSelector) so the job package never imports wshub.
type WorkerInflightJob ¶
type WorkerInflightJob struct {
JobID string
Status string
TurnNo int
SessionStatus string
IdleDeadlineAt int64
SessionID string
}
WorkerInflightJob is one entry of a worker's re-register `inflight` report, projected onto the job package's vocabulary: the hub job id the worker still holds and the status it reports for it. The projection exists so this package never imports wsproto (the assembly layer converts).
type WorkerSelector ¶
type WorkerSelector interface {
Candidates() []WorkerCandidate
Candidate(workerID string) (WorkerCandidate, bool)
}
WorkerSelector exposes the currently-connected worker candidates for label-based auto-selection (D3) and exact worker lookup for admission-time capability checks. The commands layer injects a hub-backed implementation; Submit only consults it on worker-runner paths, so a nil selector is safe for every other runner.
type WorkflowAdvancer ¶
type WorkflowAdvancer interface{ Advance(wfID string) }
WorkflowAdvancer is the job→workflow seam (layering design §13.4, D-B9): the job package defines it so it never imports the workflow sub-package; the workflow Engine implements it and core injects it via SetWorkflow. finish calls Advance when a step-job reaches a terminal state.
type WorktreeMergeError ¶
type WorktreeMergeError = delivery.MergeConflictError
WorktreeMergeError reports a conflict after the main checkout has been restored.
type WorktreeStatus ¶
type WorktreeStatus struct {
JobID string `json:"job_id"`
Project string `json:"project,omitempty"`
Path string `json:"path,omitempty"`
Branch string `json:"branch,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
// HeadSHA/CommitsAhead are probed live (and fall back to the recorded terminal
// values when the worktree is gone), so `ls` answers "did this branch deliver
// anything, and is it still there?".
HeadSHA string `json:"head_sha,omitempty"`
CommitsAhead int `json:"commits_ahead"`
// Dirty reports uncommitted changes (tracked or untracked) in the worktree:
// removing it would lose them, so `rm` refuses without --force.
Dirty bool `json:"dirty"`
// Merged reports that the branch's commits are contained in the base branch's
// current tip, i.e. nothing is lost by deleting the branch (see worktreeMerged).
Merged bool `json:"merged"`
// Exists reports that the worktree directory is present on THIS machine.
Exists bool `json:"exists"`
}
WorktreeStatus is the LIVE state of one job's managed worktree (WT-01), as the `job worktree ls/rm` commands and GET /v1/jobs/{id}/worktree report it. The path/branch/base come from the JOB ROW (recorded at submit) while head/commits/ dirty/merged are probed from the checkout on the machine serving the request — so a row whose worktree was already removed (or whose path lives on another machine, e.g. a worker job) reports Exists=false and carries no live state.
type XferBridge ¶
type XferBridge interface {
// FetchUpload places the staged transfer xferID at dst — an absolute path this
// machine resolved (the job's cwd + the request's Dest) — and returns an error
// describing why it could not (the job then fails with it).
FetchUpload(ctx context.Context, xferID, projectKey, dst string) error
// PullCollected fetches one file the EXECUTING machine matched for collection into
// dst (an absolute path in the job's artifact directory on THIS machine) and
// returns its size. Only a machine that OWNS the job's result dir implements it;
// see OwnsArtifacts.
PullCollected(ctx context.Context, p CollectedPull) (int64, error)
// CollectLimits are the collect caps in force (per file, and per job in total).
// Zero means "no cap" — a bridge that has no transfer configuration says so.
CollectLimits() CollectLimits
// OwnsArtifacts reports whether the JOB ROW's result dir is on this machine. The
// hub says true: a collected file is copied straight into the artifacts (and a
// worker's collected files are PULLED back here). A worker says false: it reports
// what it matched, and the hub pulls the bytes once the outcome arrives.
OwnsArtifacts() bool
}
xfer.go is XFER-01 X2's job-side half: the file steps a job carries with it.
- Uploads are staged transfers the EXECUTING machine places in the job's cwd BEFORE the agent starts (a failed upload fails the job — the agent must never run on a cwd the caller did not describe). The payload bytes always travel HTTP, never here.
- Collect globs are matched in that same cwd AFTER the job ends (on failure too, and after the verify step): each match becomes an artifact of the job (artifacts/collected/<project-root-relative path>), so the existing artifact download/preview surface serves it.
Which machine moves the bytes is the XferBridge seam: the hub copies from its own staging area and PULLS a worker's collected files back through the transfer manager; a worker fetches an upload over HTTP with its own token and lets the hub pull what it collected (it cannot write the hub's result dir). The job package therefore stays free of HTTP, of the wire and of internal/xfer (G022).
type XferSkipped ¶
type XferSkipped struct {
Pattern string `json:"pattern,omitempty"`
Name string `json:"name,omitempty"`
Reason string `json:"reason"`
}
XferSkipped is one file a collect pattern matched but that was not collected.
type XferSummary ¶
type XferSummary struct {
// Uploads is one entry per --upload, in request order, with the outcome of
// placing it on the executing machine.
Uploads []XferUploadResult `json:"uploads,omitempty"`
// Collected is one entry per file the collect globs matched, with its path
// relative to the PROJECT ROOT (the coordinate the artifacts and the transfer
// journal use).
Collected []XferFile `json:"collected,omitempty"`
// Skipped is what collect deliberately left out, with the reason ("too large", a
// failed pull, a file that vanished between the match and the read).
Skipped []XferSkipped `json:"skipped,omitempty"`
}
XferSummary is what a job's file steps did (XFER-01 X2), persisted as jobs.xfer_json and shown by `job show` / the web detail. It is nil for a job that carried no files (an empty summary would be a claim the job never made).
type XferUploadResult ¶
type XferUploadResult struct {
Dest string `json:"dest"`
Size int64 `json:"size,omitempty"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
XferUploadResult is one upload's outcome. Dest is the request's destination as given (cwd-relative); Size is what landed there.
Source Files
¶
- adddir.go
- adopt.go
- agenthealth.go
- approval.go
- branch_delivery.go
- budget.go
- cancel.go
- capabilities.go
- comment.go
- concurrency.go
- config.go
- credential.go
- decision_hooks.go
- delete.go
- delivery.go
- dirlock.go
- env_files.go
- errors.go
- event_hooks.go
- events.go
- execute.go
- fallback.go
- findings.go
- from_session.go
- gitdiff.go
- hold.go
- interaction.go
- internal_tags.go
- job_metrics.go
- jobwatch.go
- knowledge.go
- leader.go
- list.go
- mcp.go
- mcp_inject.go
- model.go
- ndjson.go
- notify.go
- notify_dispatch.go
- onended.go
- onterminal.go
- outcomes.go
- persistence.go
- plan_rules.go
- planadvance.go
- planattach.go
- plandispatch.go
- prompt_sections.go
- prune.go
- rebuild.go
- remote_interaction.go
- resume.go
- resume_env.go
- retry.go
- retry_sweep.go
- review.go
- rules.go
- scope_check.go
- secrets.go
- selector.go
- service.go
- session_commands.go
- session_notify.go
- session_recovery.go
- session_shutdown.go
- session_state.go
- session_store.go
- session_stream.go
- shutdown.go
- skills.go
- stall.go
- steward.go
- submit.go
- submit_timing.go
- sync_artifacts.go
- taillog.go
- template.go
- title.go
- todolink.go
- tools.go
- uncommitted.go
- update_pause.go
- upgrade_admission.go
- upgrade_drain.go
- upgrade_source.go
- usage.go
- verify.go
- wakeup.go
- worktree.go
- wrapup.go
- xfer.go