Documentation
¶
Overview ¶
Package jobstore is the SQLite-backed metadata/index store for gofer jobs. It is the C1 fix (see docs/design/2026-06-18-sqlite-store-design.md): the in-memory job table, jobs.jsonl index and result.json metadata all grow without bound on a long-running server. This package moves that state into a single SQLite database so listing is one filtered/paginated SQL query and terminal jobs no longer have to live in memory.
Job logs (stdout.log/stderr.log) stay as files in the per-job result dir; only metadata/index (and, from SP4, interactions) live here.
The package uses modernc.org/sqlite (pure Go, no cgo) so the binary still builds in the gcc-less container. It depends on no other internal package but internal/util (leaf helpers), internal/skill (whose Repo interface the skills table implements) and internal/authz (whose permission catalog the auth migration plants for the `users` subject) — in particular NOT internal/job — so that the job service can adopt it (SP2/SP3) without forming a job -> jobstore -> job import cycle; JobRecord is therefore a neutral struct rather than job.JobResult.
Index ¶
- Constants
- Variables
- func DecodeStringList(s string) []string
- func DefaultWorkJournalLevel(kind, by string) string
- func EncodeStringList(vals []string) string
- func FirstLine(s string, max int) string
- func IsReservedTracker(trackerID string) bool
- func JobSubmitAt(j JobRecord) int64
- func NewRetryID() string
- func NextCronRun(expr string, after time.Time) (int64, error)
- func NormalizePlanLimit(n int) int
- func NormalizePlanTags(tags []string) []string
- func NormalizeScopedMemoryScope(scope, scopeKey string) (string, string, error)
- func ParseSessionUsage(raw string) runner.SessionUsage
- func SessionUsageDay(unix int64) string
- func ValidCommentAuthorKind(kind string) bool
- func ValidCommentScope(scope string) bool
- func ValidDecisionState(s string) bool
- func ValidJobCredentialKind(k string) bool
- func ValidPlanLeader(s string) bool
- func ValidPlanNotify(s string) bool
- func ValidRelayMode(m string) bool
- func ValidSessionState(s string) bool
- func ValidSuggestionField(f string) bool
- func ValidTodoStatus(s string) bool
- func ValidWorkKind(k string) bool
- func ValidWorkLevel(s string) bool
- func ValidWorkStatus(s string) bool
- func ValidWorkStatusOrCaptured(s string) bool
- func WorkRequestActive(state string) bool
- func WorkStatusFinal(s string) bool
- type AgentHealth
- type AgentSession
- type AuditEvent
- type AuditEventDetail
- type AuthAuditEntry
- type AuthAuditFilter
- type AuthGrant
- type CaptureInput
- type Change
- type ChangeHook
- type ChangeKind
- type Comment
- type DBStats
- type DecisionAdvice
- type Delivery
- type HoldDecision
- type InteractionRecord
- type JobEvent
- type JobMetrics
- type JobOutcomeCounts
- type JobRecord
- type JobTokenRecord
- type LeaderWake
- type ListQuery
- type ListSessionsOpts
- type MemoryCandidate
- type MemoryCandidateFilter
- type MemorySuggestion
- type MetricsEvidence
- type OrphanSessionCandidate
- type OverviewJobRow
- type OverviewReviewRow
- type Plan
- type PlanCompletion
- type PlanCounts
- type PlanDecision
- type PlanFilter
- type PlanHandoff
- type PlanSessionUsage
- type PlanTodo
- type PlanTodoCounts
- type PlanUsage
- type PtySessionRecord
- type PushSubscription
- type RedactReport
- type RetentionPolicy
- type RetryRecord
- type ScheduleRecord
- type ScopedMemory
- type ScopedMemoryMetaPatch
- type SecretBatchRedact
- type SecretBatchRedactReport
- type SecretScanFilter
- type SecretScanJob
- type SecretScanLocation
- type SecretScanReport
- type SessionDecisionPage
- type SessionGrantAnchor
- type SessionHeartbeat
- type SessionJobWatch
- type SessionMessage
- type SessionModelUsage
- type SessionNudge
- type SessionStats
- type SessionUsageStats
- type SessionUsageWindow
- type SplitWorkItemInput
- type StewardEvent
- type StewardReview
- type Store
- func (s *Store) AckDecision(id, ackedBy string) (bool, error)
- func (s *Store) ActivateAuthGrant(id string) (AuthGrant, bool, error)
- func (s *Store) ActiveACPSessionCounts() (map[string]int, error)
- func (s *Store) AddMemoryCandidates(jobID, projectKey string, texts, whenPaths []string) (int, error)
- func (s *Store) AddMemorySuggestion(m MemorySuggestion) (MemorySuggestion, bool, error)
- func (s *Store) AddSessionJobWatch(sessionID, jobID string) (SessionJobWatch, error)
- func (s *Store) AddSessionUsage(sid string, delta runner.SessionUsage) (bool, error)
- func (s *Store) AddStewardEvent(kind, ref, detail string) (bool, error)
- func (s *Store) AddWorkLink(id, kind, ref, by string) (WorkLink, error)
- func (s *Store) AddWorkMergeSuggestion(targetID, sourceID, reason, by string) (WorkMergeSuggestion, bool, error)
- func (s *Store) AdvanceCurrentStep(id string, from, to int) (bool, error)
- func (s *Store) AdvanceSchedule(id string, oldNext, newNext, now int64) (bool, error)
- func (s *Store) AdvanceStep(id string, fromStep, fromAtt, toStep, toAtt int, nextStepAt int64) (bool, error)
- func (s *Store) AdvanceWakeup(id string, oldNext, newNext, now int64) (bool, error)
- func (s *Store) AgentHealth(agent string, since int64) (AgentHealth, error)
- func (s *Store) AgentHealthAll(since int64) (map[string]AgentHealth, error)
- func (s *Store) AnswerDecision(id, answer, answeredBy string) (bool, error)
- func (s *Store) AppendAuditEvent(kind, targetID, actor, detailJSON string) (int64, error)
- func (s *Store) AppendSessionOutbox(m SessionMessage) error
- func (s *Store) AppendTodoNote(todoID, note string) (bool, error)
- func (s *Store) AppendWorkJournal(id, kind, text, by string) (WorkJournalEntry, error)
- func (s *Store) AppendWorkJournalLevel(id, kind, text, by, level string) (WorkJournalEntry, error)
- func (s *Store) AttachJobToPlan(jobID, planID string) (bool, error)
- func (s *Store) AttachWorkSession(id, sid, by string) error
- func (s *Store) AuthGrantsVersion() (int64, error)
- func (s *Store) AuthSeedVersion() (int64, error)
- func (s *Store) BatchPatchTrackerIssues(trackerID string, ids []string, set TrackerBatchSet, now, by string) []TrackerBatchResult
- func (s *Store) BeginStewardReview(day, trigger string, itemIDs []string) (int64, error)
- func (s *Store) BeginWorkSummary(itemID, sessionID string, activityAt int64, cause string) (int64, error)
- func (s *Store) CancelLeaderWake(id, by string, now int64) (bool, error)
- func (s *Store) CancelLeaderWakesForPlan(planID, by string, now int64) (int64, error)
- func (s *Store) CancelRetry(id string) error
- func (s *Store) CaptureWorkItem(in CaptureInput) (WorkItem, error)
- func (s *Store) ClaimAgentSessionOwner(sessionID, callerID string) (AgentSession, bool, error)
- func (s *Store) ClaimDueDeliveries(now int64, limit int, lease int64) ([]Delivery, error)
- func (s *Store) ClaimDueRetries(now int64, limit int, lease int64) ([]RetryRecord, error)
- func (s *Store) ClaimLeaderWake(id string) (bool, error)
- func (s *Store) ClaimLocalSessionsForRecovery(ts int64) ([]JobRecord, error)
- func (s *Store) ClaimUnwatchedSourceJobs(sessionID string, since int64) (int64, error)
- func (s *Store) ClaimWakeupFire(id, continuationJobID string) (bool, error)
- func (s *Store) ClearPlanBlocked(id string) error
- func (s *Store) ClearServerCreatedPulled(trackerID string, cursor int64) error
- func (s *Store) ClearSessionJobWatches(sessionID string) error
- func (s *Store) Close() error
- func (s *Store) CoalesceWakeup(id string, now int64) error
- func (s *Store) CommentTriggerStats(scope, scopeID string) (triggered int, lastAt int64, err error)
- func (s *Store) CountActiveJobsByCaller(callerID string, since int64) (int, error)
- func (s *Store) CountAuditTargetsSince(kind, actorPrefix string, since int64) (int, error)
- func (s *Store) CountAutoWorkSummaries(since int64) (int, error)
- func (s *Store) CountJobsByStatus() (map[string]int, error)
- func (s *Store) CountMemorySuggestionsSince(since int64) (int, error)
- func (s *Store) CountPausedForUpdate() (int, error)
- func (s *Store) CountPlans(f PlanFilter) (int, error)
- func (s *Store) CountRecoveringJobs() (int, error)
- func (s *Store) CountUpgradeRestartBlockers(excludedIDs, workerRunners []string) (int, error)
- func (s *Store) CreateAuthGrant(g AuthGrant) (AuthGrant, error)
- func (s *Store) CreateServerTrackerIssue(trackerID string, in tracker.Issue, by string) (TrackerRecord, error)
- func (s *Store) CreateSessionNudge(n SessionNudge) (SessionNudge, error)
- func (s *Store) CreateWorkItem(in WorkItemInput) (WorkItem, error)
- func (s *Store) CreateWorkRequest(in WorkRequestInput) (WorkRequest, error)
- func (s *Store) CurrentWorkSessionIDs(ids []string) (map[string][]string, error)
- func (s *Store) DBStats(budget time.Duration) (DBStats, error)
- func (s *Store) DecideHold(d HoldDecision) (bool, error)
- func (s *Store) DecideMemoryCandidate(id int64, from, to, memoryKey, by string) (MemoryCandidate, error)
- func (s *Store) DecideMemorySuggestion(id int64, state, by, note string) (MemorySuggestion, error)
- func (s *Store) DeleteAgentSession(sid string) (bool, error)
- func (s *Store) DeleteCommentsForScope(scope, scopeID string) (int64, error)
- func (s *Store) DeleteDecisionAdvice(cardKeys ...string) error
- func (s *Store) DeleteJob(jobID, actor string) error
- func (s *Store) DeletePushSubscription(callerID, endpoint string) (bool, error)
- func (s *Store) DeletePushSubscriptionEndpoint(endpoint string) error
- func (s *Store) DeleteRule(name string) error
- func (s *Store) DeleteSchedule(id string) error
- func (s *Store) DeleteScopedMemory(scope, scopeKey, key, updatedBy string) error
- func (s *Store) DeleteSessionNudge(id string) (bool, error)
- func (s *Store) DeleteSkill(name string) error
- func (s *Store) DeleteTodaySnoozes(cardKeys ...string) (int, error)
- func (s *Store) DeleteTodo(todoID string) (bool, error)
- func (s *Store) DeleteTracker(trackerID string) (TrackerDeleteResult, error)
- func (s *Store) DeleteTunnelPreset(name string) error
- func (s *Store) DeleteWakeup(id string) error
- func (s *Store) DeleteWorkItem(id, actor string) error
- func (s *Store) DeleteWorkSuggestion(id, field string) error
- func (s *Store) DeleteXfer(id string) error
- func (s *Store) DetachWorkSession(id, sid, by string) error
- func (s *Store) DismissWorkSuggestion(id, field string) error
- func (s *Store) DoneJobsByDay(from int64, tzSec int) (map[string]int, error)
- func (s *Store) DueLeaderWakes(now int64) ([]LeaderWake, error)
- func (s *Store) DueSchedules(now int64) ([]ScheduleRecord, error)
- func (s *Store) DueWakeups(now int64) ([]WakeupRecord, error)
- func (s *Store) EndSessionNudge(id, reason string) (bool, error)
- func (s *Store) EnsureDraftWorkItemForSession(a AgentSession, prompt string) (WorkItem, bool, error)
- func (s *Store) ExpireCastRecordings(now, ttlSeconds int64) (uris []string, err error)
- func (s *Store) ExpireDueDecisions() error
- func (s *Store) ExpireSessionDecisions(sessionID string) (int64, error)
- func (s *Store) ExpiredXfers(now int64) ([]XferRecord, error)
- func (s *Store) ExtendJobTokenExpiry(jobID string, expiresAt int64) error
- func (s *Store) FailRecoveringJob(id string, ts int64, reason string) (int, error)
- func (s *Store) FailRecoveringJobs(ts int64, reason string) (int, error)
- func (s *Store) FailStaleStewardReviews(cutoff int64) error
- func (s *Store) FailStaleWorkSummaries(cutoff int64) error
- func (s *Store) FindChildWorkflow(parentID string, parentStep int) (Workflow, bool, error)
- func (s *Store) FindTrackerIssues(issueID string) ([]TrackerRecord, error)
- func (s *Store) FinishStewardReview(id int64, state, summary, jobID, errText string) error
- func (s *Store) FinishWorkSummary(id int64, state, jobID, errText string) error
- func (s *Store) FinishWorkflowStep(id string, fromStep, fromAtt, toStep int, status, errMsg string, ...) (bool, error)
- func (s *Store) FirstJobAt() (int64, error)
- func (s *Store) FlagScopedMemory(scope, scopeKey, key string, flag *tracker.MemoryFlag) (ScopedMemory, error)
- func (s *Store) GetAgentSession(sid string) (AgentSession, bool, error)
- func (s *Store) GetAuthGrant(id string) (AuthGrant, bool, error)
- func (s *Store) GetComment(id string) (Comment, bool, error)
- func (s *Store) GetDecision(id string) (PlanDecision, bool, error)
- func (s *Store) GetDecisionAdvice(cardKey string) (DecisionAdvice, bool, error)
- func (s *Store) GetEvent(seq int64) (JobEvent, bool, error)
- func (s *Store) GetJob(id string) (JobRecord, bool, error)
- func (s *Store) GetJobByRequestID(reqID string) (JobRecord, bool, error)
- func (s *Store) GetJobMetrics(jobID string) (JobMetrics, bool, error)
- func (s *Store) GetJobToken(jobID string) (JobTokenRecord, bool, error)
- func (s *Store) GetJobTokenByHash(hash string) (JobTokenRecord, bool, error)
- func (s *Store) GetJobsByIDs(ids []string) (map[string]JobRecord, error)
- func (s *Store) GetLeaderWake(id string) (LeaderWake, bool, error)
- func (s *Store) GetMemoryCandidate(id int64) (MemoryCandidate, error)
- func (s *Store) GetMemorySuggestion(id int64) (MemorySuggestion, error)
- func (s *Store) GetOrCreateWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
- func (s *Store) GetPlan(id string) (Plan, bool, error)
- func (s *Store) GetPlanHandoff(planID string, version int) (PlanHandoff, bool, error)
- func (s *Store) GetPtySessionByJob(jobID string) (PtySessionRecord, bool, error)
- func (s *Store) GetRetry(id string) (RetryRecord, bool, error)
- func (s *Store) GetRule(name string) (rule.Rule, bool, error)
- func (s *Store) GetSchedule(id string) (ScheduleRecord, bool, error)
- func (s *Store) GetScopedMemory(scope, scopeKey, key string) (ScopedMemory, error)
- func (s *Store) GetSessionByHandedOffJob(jobID string) (AgentSession, bool, error)
- func (s *Store) GetSessionNudge(id string) (SessionNudge, bool, error)
- func (s *Store) GetSkill(name string) (skill.Skill, bool, error)
- func (s *Store) GetTodaySnooze(cardKey string) (TodaySnooze, bool, error)
- func (s *Store) GetTodo(id string) (PlanTodo, bool, error)
- func (s *Store) GetTrackerMemory(trackerID, key string) (TrackerRecord, bool, error)
- func (s *Store) GetTunnelPreset(name string) (TunnelPresetRecord, bool, error)
- func (s *Store) GetWakeup(id string) (WakeupRecord, bool, error)
- func (s *Store) GetWorkItem(id string) (WorkItem, bool, error)
- func (s *Store) GetWorkKV(k string) (string, error)
- func (s *Store) GetWorkMergeSuggestion(id int64) (WorkMergeSuggestion, error)
- func (s *Store) GetWorkRequest(id string) (WorkRequest, bool, error)
- func (s *Store) GetWorkSuggestion(id, field string) (WorkSuggestion, bool, error)
- func (s *Store) GetWorkbenchLayout(callerID string) (layout WorkbenchLayout, ok bool, err error)
- func (s *Store) GetWorkbenchSeenBaseline(callerID string) (int64, bool, error)
- func (s *Store) GetWorkbenchThreadPref(callerID, threadID string) (WorkbenchThreadPref, bool, error)
- func (s *Store) GetWorkflow(id string) (Workflow, bool, error)
- func (s *Store) GetXfer(id string) (XferRecord, bool, error)
- func (s *Store) IncrSessionTurn(sid string) (int64, bool, error)
- func (s *Store) InsertAuthAudit(e AuthAuditEntry) error
- func (s *Store) InsertComment(c Comment) error
- func (s *Store) InsertDecision(d *PlanDecision) error
- func (s *Store) InsertDelivery(d Delivery) (int64, error)
- func (s *Store) InsertJobEvent(e JobEvent) (int64, error)
- func (s *Store) InsertLeaderWake(w LeaderWake) error
- func (s *Store) InsertPlan(p Plan) error
- func (s *Store) InsertRetry(r RetryRecord) error
- func (s *Store) InsertSchedule(r ScheduleRecord) error
- func (s *Store) InsertSkill(k skill.Skill) error
- func (s *Store) InsertTodo(t PlanTodo) error
- func (s *Store) InsertWakeup(r WakeupRecord) error
- func (s *Store) InsertWorkflow(w Workflow) error
- func (s *Store) InsertWorkflowEvent(e WorkflowEvent) (int64, error)
- func (s *Store) InsertXfer(r XferRecord) error
- func (s *Store) IsStewardJob(jobID string) bool
- func (s *Store) JobMetricsEvidence(jobID string) (MetricsEvidence, error)
- func (s *Store) JobOutcomesSince(since int64) (JobOutcomeCounts, error)
- func (s *Store) JobTitles(ids []string) (map[string]string, error)
- func (s *Store) LastStewardReview() (StewardReview, bool, error)
- func (s *Store) LastWorkSummary(sessionID string) (WorkSummaryRun, bool, error)
- func (s *Store) LatestAuditEvent(kind, targetID string) (AuditEventDetail, bool, error)
- func (s *Store) LatestLeaderJob(planID string) (string, error)
- func (s *Store) LatestWorkJournalAt(id string) (int64, error)
- func (s *Store) LeaderRoundsSpent(planID string) (int, error)
- func (s *Store) LeaderWakeArmedForMember(memberJobID string) (bool, error)
- func (s *Store) ListActiveAuthGrants(subject string) ([]AuthGrant, error)
- func (s *Store) ListActiveAuthGrantsAll() ([]AuthGrant, error)
- func (s *Store) ListActiveNudges() ([]SessionNudge, error)
- func (s *Store) ListAgentSessions(opts ListSessionsOpts) ([]AgentSession, error)
- func (s *Store) ListAuditEvents(kind, targetID string) ([]AuditEvent, error)
- func (s *Store) ListAuditEventsSince(kind string, since int64, limit int) ([]AuditEventDetail, error)
- func (s *Store) ListAuthAudit(f AuthAuditFilter) ([]AuthAuditEntry, error)
- func (s *Store) ListAuthGrants() ([]AuthGrant, error)
- func (s *Store) ListComments(scope, scopeID string) ([]Comment, error)
- func (s *Store) ListDecisionAdvice() ([]DecisionAdvice, error)
- func (s *Store) ListDecisions(state, planID string) ([]*PlanDecision, error)
- func (s *Store) ListDeliveriesByJob(jobID string) ([]Delivery, error)
- func (s *Store) ListDueHolds(now int64, limit int) ([]JobRecord, error)
- func (s *Store) ListDueWorkItems(now int64) ([]WorkItem, error)
- func (s *Store) ListFinalWorkItemIDs(status string) ([]string, error)
- func (s *Store) ListInteractions(jobID string) ([]InteractionRecord, error)
- func (s *Store) ListJobEvents(jobID string, sinceSeq int64) ([]JobEvent, error)
- func (s *Store) ListJobEventsDesc(scope string, before int64, limit int) ([]JobEvent, error)
- func (s *Store) ListJobs(q ListQuery) ([]JobRecord, error)
- func (s *Store) ListJobsByTodo(todoID string, limit int) ([]JobRecord, error)
- func (s *Store) ListJobsForMetrics(since, afterEnded int64, afterID string, limit int, onlyStale bool) ([]JobRecord, error)
- func (s *Store) ListLeaderWakesForPlan(planID string) ([]LeaderWake, error)
- func (s *Store) ListMemoryCandidates(f MemoryCandidateFilter) ([]MemoryCandidate, error)
- func (s *Store) ListMemorySuggestions(state string) ([]MemorySuggestion, error)
- func (s *Store) ListOpenSessionPermissions(sessionID string, limit int) ([]*PlanDecision, error)
- func (s *Store) ListOpenSessionTurns(sessionID string, limit int) ([]*PlanDecision, error)
- func (s *Store) ListOrphanSessionCandidates(workerRunners []string) ([]OrphanSessionCandidate, error)
- func (s *Store) ListOverdueWorkRequests(now int64) ([]WorkRequest, error)
- func (s *Store) ListPausedForUpdate(limit int) ([]JobRecord, error)
- func (s *Store) ListPendingInteractions() ([]InteractionRecord, error)
- func (s *Store) ListPendingWorkSuggestionsFor(fields []string) ([]WorkSuggestion, error)
- func (s *Store) ListPlanHandoffHistory(planID string) ([]PlanHandoff, error)
- func (s *Store) ListPlans(f PlanFilter) ([]Plan, error)
- func (s *Store) ListPtySessionsByJob(jobID string) ([]PtySessionRecord, error)
- func (s *Store) ListPushSubscriptions(callerID string) ([]PushSubscription, error)
- func (s *Store) ListRecentPtySessions(limit int) ([]PtySessionRecord, error)
- func (s *Store) ListRecentWorkJournal(since int64, limit int) ([]WorkJournalEntry, error)
- func (s *Store) ListRecoveringJobs(workerID string) ([]JobRecord, error)
- func (s *Store) ListRetriesByJob(jobID string) ([]RetryRecord, error)
- func (s *Store) ListRules() ([]rule.Rule, error)
- func (s *Store) ListSchedules(projectFilter string, enabledOnly bool) ([]ScheduleRecord, error)
- func (s *Store) ListScopedMemories(scope, scopeKey, keyword string, tags []string) ([]ScopedMemory, error)
- func (s *Store) ListSessionDecisions(sessionID, state string, limit int, before string) (SessionDecisionPage, error)
- func (s *Store) ListSessionJobWatches(sessionID string) ([]SessionJobWatch, error)
- func (s *Store) ListSessionNudges(sid string, includeEnded bool) ([]SessionNudge, error)
- func (s *Store) ListSkills() ([]skill.Skill, error)
- func (s *Store) ListStewardReviews(limit int) ([]StewardReview, error)
- func (s *Store) ListTodaySnoozes() ([]TodaySnooze, error)
- func (s *Store) ListTodosByPlan(planID string) ([]PlanTodo, error)
- func (s *Store) ListTrackerIssues(trackerID string, sinceRev int64) ([]TrackerRecord, error)
- func (s *Store) ListTrackerMemories(trackerID string, sinceRev int64) ([]TrackerRecord, error)
- func (s *Store) ListTrackerRepos() ([]TrackerRepo, error)
- func (s *Store) ListTrackerSyncClients(trackerID string) ([]TrackerSyncClient, error)
- func (s *Store) ListTunnelPresets() ([]TunnelPresetRecord, error)
- func (s *Store) ListUpgradeRestartBlockers(excludedIDs, workerRunners []string, limit int) ([]UpgradeBlocker, error)
- func (s *Store) ListWakeups(jobID string) ([]WakeupRecord, error)
- func (s *Store) ListWorkItemSessions(id string) ([]WorkItemSession, error)
- func (s *Store) ListWorkItems(o WorkListOpts) ([]WorkItem, error)
- func (s *Store) ListWorkJournal(id string, limit int, before int64) ([]WorkJournalEntry, error)
- func (s *Store) ListWorkJournalLevel(id string, limit int, before int64, level string) ([]WorkJournalEntry, error)
- func (s *Store) ListWorkLinks(id string) ([]WorkLink, error)
- func (s *Store) ListWorkMergeSuggestions(state string) ([]WorkMergeSuggestion, error)
- func (s *Store) ListWorkRequests(workItemID string, activeOnly bool, limit int) ([]WorkRequest, error)
- func (s *Store) ListWorkSuggestions(id string) ([]WorkSuggestion, error)
- func (s *Store) ListWorkSummaries(itemID string, limit int) ([]WorkSummaryRun, error)
- func (s *Store) ListWorkbenchThreadPrefs(callerID string) ([]WorkbenchThreadPref, error)
- func (s *Store) ListWorkflowEvents(wfID string, sinceSeq int64) ([]WorkflowEvent, error)
- func (s *Store) ListWorkflowJobs(id string) ([]JobRecord, error)
- func (s *Store) ListWorkflows(status string, limit int) ([]Workflow, error)
- func (s *Store) ListWorktrees() ([]WorktreeRecord, error)
- func (s *Store) ListXfers(f XferFilter) ([]XferRecord, error)
- func (s *Store) LoadWorkbenchSnapshot(callerID string, since int64, includeInternal bool) (WorkbenchSnapshot, error)
- func (s *Store) MarkAuthGrantUsed(id string, at int64) error
- func (s *Store) MarkDelivered(id int64, now int64) error
- func (s *Store) MarkFailed(id int64, attempts int, lastErr string, now int64) error
- func (s *Store) MarkInteractionNeedsHuman(jobID, interactionID string) error
- func (s *Store) MarkPushSubscriptionOK(endpoint string, at int64) error
- func (s *Store) MarkRetry(id int64, attempts int, nextRetryAt int64, lastErr string, now int64) error
- func (s *Store) MarkRetryDone(id, newJobID string) error
- func (s *Store) MarkStaleSessionsOffline(cutoff int64) (int64, error)
- func (s *Store) MarkStewardEventsHandled(ids []int64, at int64) error
- func (s *Store) MarkStewardJob(jobID string) error
- func (s *Store) MarkWorkItemReminded(id string, due int64, text string) error
- func (s *Store) MarkWorkRequest(id, state, channel, errText string, from ...string) (WorkRequest, bool, error)
- func (s *Store) MatchingEventWakeups(sourceJobID, eventType string) ([]WakeupRecord, error)
- func (s *Store) MemorySuggestionDismissedSince(trackerID, key, action string, since int64) (bool, error)
- func (s *Store) MergeWorkItems(targetID string, sourceIDs []string, by string) (WorkItem, error)
- func (s *Store) OpenWorkItemsFor(r WorkRefs) ([]string, error)
- func (s *Store) OrphanAuthGrants(ids []string) (int, error)
- func (s *Store) OverviewJobs(from int64) ([]OverviewJobRow, error)
- func (s *Store) OverviewPlans(from int64) (plansDone, todosDone int, err error)
- func (s *Store) OverviewReviews(from int64) ([]OverviewReviewRow, error)
- func (s *Store) OverviewSessionUsage(fromDay string) ([]SessionModelUsage, int, error)
- func (s *Store) PatchTrackerIssue(trackerID, id string, expected int64, patch map[string]json.RawMessage, ...) (TrackerRecord, error)
- func (s *Store) PatchTrackerMemory(trackerID, id string, expected int64, patch map[string]json.RawMessage, ...) (TrackerRecord, error)
- func (s *Store) PauseSessionNudge(id, reason string) (bool, error)
- func (s *Store) PendingStewardEvents(limit int) ([]StewardEvent, error)
- func (s *Store) PlanJobStatusCounts(planID string) (map[string]int, error)
- func (s *Store) PlanSessionUsage(planID string) (PlanSessionUsage, error)
- func (s *Store) PlanTodoCountsByPlan(planIDs []string) (map[string]PlanTodoCounts, error)
- func (s *Store) PlanUsage(planID string) (PlanUsage, error)
- func (s *Store) PruneAuthAudit(now int64) error
- func (s *Store) PruneJobTokens(cutoff int64) (int, error)
- func (s *Store) PruneJobs(policy RetentionPolicy, now int64) (deleted int, prunedDirs []string, err error)
- func (s *Store) PruneWorkflows(policy WorkflowRetentionPolicy, now int64) (deleted int, prunedDirs []string, err error)
- func (s *Store) PutScopedMemory(scope, scopeKey, key, content string, tags []string, updatedBy string) (ScopedMemory, error)
- func (s *Store) PutScopedMemoryPatch(scope, scopeKey, key, content string, tags []string, ...) (ScopedMemory, error)
- func (s *Store) PutWorkbenchLayout(callerID string, expectedVersion int64, bodyJSON string, updatedAt int64) (layout WorkbenchLayout, updated bool, err error)
- func (s *Store) ReadSessionMessageLog(sid string) ([]byte, error)
- func (s *Store) ReadSessionOutbox(sid string) ([]SessionMessage, error)
- func (s *Store) RecentWorkRequests(workItemID string, finishedSince int64) ([]WorkRequest, error)
- func (s *Store) ReconcileOrphanInteractions(ts int64) (int, error)
- func (s *Store) ReconcileOrphanJobs(ts int64, reason string, workerRunners []string) (int, error)
- func (s *Store) RecordNudgeAttempt(id string, now int64, ok bool, errText string, nextRun int64, maxFails int) (n SessionNudge, paused bool, err error)
- func (s *Store) RecordTrackerSyncClient(c TrackerSyncClient) error
- func (s *Store) RedactJob(jobID string, literals, patterns []string) (RedactReport, error)
- func (s *Store) RedactSecrets(literals, patterns []string, filter SecretScanFilter, vacuum bool) (SecretBatchRedactReport, error)
- func (s *Store) ReleaseDecision(id, releasedBy string) (bool, error)
- func (s *Store) ReleaseRetry(id string, nextRunAt int64) error
- func (s *Store) ReleaseSessionHandedOff(sid string) (bool, error)
- func (s *Store) ReleaseWakeupClaim(id, continuationJobID string) error
- func (s *Store) RemoveSessionJobWatch(sessionID, jobID string) (bool, error)
- func (s *Store) RemoveWorkLink(id, kind, ref, by string) (bool, error)
- func (s *Store) RenameTracker(oldID, newID string) (renamed bool, err error)
- func (s *Store) ResolveWorkMergeSuggestion(id int64, state string) error
- func (s *Store) ResumeSessionNudge(id string) (bool, error)
- func (s *Store) RevokeAuthGrant(id, by string) (AuthGrant, bool, error)
- func (s *Store) RevokeJobToken(jobID string, now int64) (bool, error)
- func (s *Store) ScanSecrets(literals, patterns []string, filter SecretScanFilter) (SecretScanReport, error)
- func (s *Store) SessionGrantAnchor(sid string) (SessionGrantAnchor, bool, error)
- func (s *Store) SessionStats(now int64) (SessionStats, error)
- func (s *Store) SessionUsageStats(now int64, windows []time.Duration) (SessionUsageStats, error)
- func (s *Store) SetChangeHook(h ChangeHook)
- func (s *Store) SetClock(fn func() time.Time)
- func (s *Store) SetCommentTriggeredJob(id, jobID string) (bool, error)
- func (s *Store) SetJobSessionID(jobID, sessionID string) (bool, error)
- func (s *Store) SetLeaderWakeFired(id, jobID string, round int) (bool, error)
- func (s *Store) SetPlanBlocked(id, todoID string) error
- func (s *Store) SetPlanHandoff(planID, body, by string, expectedVersion int) (PlanHandoff, error)
- func (s *Store) SetPlanLeader(id, leader string) error
- func (s *Store) SetPlanNotify(id, notify string) error
- func (s *Store) SetPlanPaused(id string, paused bool) error
- func (s *Store) SetPlanStatus(id, status string, progress int) error
- func (s *Store) SetPlanSupervisorSessionID(id, sessionID string) error
- func (s *Store) SetScheduleEnabled(id string, enabled int) error
- func (s *Store) SetScheduleLastJob(id, jobID string) error
- func (s *Store) SetScheduleTriggerToken(id, token string) error
- func (s *Store) SetSessionHandedOff(sid, jobID string) (AgentSession, error)
- func (s *Store) SetSessionMessageLogRoot(root string)
- func (s *Store) SetSessionRelayMode(sid, mode string) (bool, error)
- func (s *Store) SetSessionState(sid, state string) (bool, error)
- func (s *Store) SetSessionTopic(sid string, topic *string, scope *[]string, source string) (a AgentSession, ok, ended bool, err error)
- func (s *Store) SetStewardReviewSummary(day, summary string) (StewardReview, error)
- func (s *Store) SetTodoDispatchError(todoID, msg string) (bool, error)
- func (s *Store) SetTodoDone(todoID string, done bool) (bool, error)
- func (s *Store) SetTodoJob(todoID, jobID string) (bool, error)
- func (s *Store) SetTodoReadyIfPending(todoID string) (bool, error)
- func (s *Store) SetWakeupContinuation(id, jobID string) (bool, error)
- func (s *Store) SetWakeupEnabled(id string, enabled int) error
- func (s *Store) SetWorkItemAutoStatus(id, status, reason string) (bool, error)
- func (s *Store) SetWorkKV(k, v string) error
- func (s *Store) SetWorkbenchSeenBaseline(callerID string, observedAt int64) (int64, error)
- func (s *Store) SetWorkflowStatus(id, status, errMsg string) error
- func (s *Store) SetXferContent(id string, size int64, sha256 string) error
- func (s *Store) SplitWorkItem(id string, in SplitWorkItemInput) (WorkItem, WorkItem, error)
- func (s *Store) StatsGen() uint64
- func (s *Store) StewardReviewComment(day string) (string, error)
- func (s *Store) SyncTrackerIssue(rec TrackerRecord, baseRev int64) (TrackerSyncResult, error)
- func (s *Store) SyncTrackerMemory(rec TrackerRecord, baseRev int64) (TrackerSyncResult, error)
- func (s *Store) TombstoneTrackerMemoryAt(trackerID, key string, expected int64, body []byte, now, deletedBy string) (TrackerRecord, error)
- func (s *Store) TouchAgentSession(sid string, hb SessionHeartbeat) (AgentSession, bool, error)
- func (s *Store) TouchPlan(id string) error
- func (s *Store) TransferAgentSessionOwner(sessionID, callerID, by string) (a AgentSession, from string, ok bool, err error)
- func (s *Store) UnackDecision(id string) (bool, error)
- func (s *Store) UpdatePlanTags(id string, tags *[]string, untag []string) (Plan, bool, error)
- func (s *Store) UpdateSkill(k skill.Skill) error
- func (s *Store) UpdateTodoPatch(todoID string, p TodoPatch) (bool, error)
- func (s *Store) UpdateTodoStatus(todoID, status string, note *string) (bool, error)
- func (s *Store) UpdateWakeup(r WakeupRecord) error
- func (s *Store) UpdateWorkItem(id string, p WorkItemPatch, expectedRev int64, by string) (WorkItem, string, error)
- func (s *Store) UpdateWorkflowSpec(id, specJSON string) error
- func (s *Store) UpdateXferState(id, state, errMsg string, finishedAt int64) error
- func (s *Store) UpsertAgentSession(in AgentSession) (AgentSession, error)
- func (s *Store) UpsertAgentSessionForOwner(in AgentSession) (AgentSession, bool, error)
- func (s *Store) UpsertDecisionAdvice(a DecisionAdvice) (DecisionAdvice, error)
- func (s *Store) UpsertInteraction(rec InteractionRecord) error
- func (s *Store) UpsertJob(rec JobRecord) error
- func (s *Store) UpsertJobMetrics(m JobMetrics) error
- func (s *Store) UpsertJobToken(rec JobTokenRecord) error
- func (s *Store) UpsertPtySession(rec PtySessionRecord) error
- func (s *Store) UpsertPushSubscription(sub PushSubscription) error
- func (s *Store) UpsertRule(r rule.Rule) error
- func (s *Store) UpsertTodaySnooze(in TodaySnooze) (TodaySnooze, error)
- func (s *Store) UpsertTrackerIssue(rec TrackerRecord) error
- func (s *Store) UpsertTrackerMemory(rec TrackerRecord) error
- func (s *Store) UpsertTrackerRepo(repo TrackerRepo) error
- func (s *Store) UpsertTunnelPreset(rec TunnelPresetRecord) error
- func (s *Store) UpsertWorkSuggestion(sg WorkSuggestion) (stored bool, err error)
- func (s *Store) UpsertWorkbenchThreadPref(pref WorkbenchThreadPref) error
- func (s *Store) UsageStats(now int64, windows []time.Duration, budget time.Duration) (UsageStats, error)
- func (s *Store) WakeTodaySnooze(cardKey, reason string) error
- func (s *Store) WorkCounts() (map[string]int, error)
- func (s *Store) WorkFieldSources(id string) (map[string]WorkFieldSource, error)
- func (s *Store) WorkItemLinkedJobs(itemID string, limit, perPlan int) ([]JobRecord, error)
- type TodaySnooze
- type TodoPatch
- type TrackerBatchResult
- type TrackerBatchSet
- type TrackerDeleteResult
- type TrackerRecord
- type TrackerRename
- type TrackerRepo
- type TrackerSyncClient
- type TrackerSyncResult
- type TunnelPresetRecord
- type UpgradeBlocker
- type UsageAgent
- type UsageStats
- type UsageWindow
- type WakeupRecord
- type WorkFieldSource
- type WorkItem
- type WorkItemInput
- type WorkItemPatch
- type WorkItemSession
- type WorkJournalEntry
- type WorkLink
- type WorkListOpts
- type WorkMergeSuggestion
- type WorkRefs
- type WorkRequest
- type WorkRequestInput
- type WorkSuggestion
- type WorkSummaryRun
- type WorkbenchLayout
- type WorkbenchSnapshot
- type WorkbenchThreadPref
- type Workflow
- type WorkflowEvent
- type WorkflowRetentionPolicy
- type WorktreeRecord
- type XferFilter
- type XferRecord
Constants ¶
const ( // AuthMetaSeedVersion 是让种入「只做一次」的持久标记(设计 §3):这个数据库已经为 // `users` 主体种到的最高种入版本。它和种入的行在同一个事务里写,所以它不会撒谎。 AuthMetaSeedVersion = "seed_version" // AuthMetaGrantsVersion 是授权表的代号。入口层的授权缓存按它判断是否失效(设计 // 「一致性」:本进程写入后立即刷新,其他进程按 5 秒 TTL 失效);每次改动授权的写接口 // 都要递增它,本批只负责把这个键建出来。 AuthMetaGrantsVersion = "grants_version" )
auth_meta 键(设计「数据层」)。
const ( DefaultAuthAuditLimit = 100 MaxAuthAuditLimit = 500 )
审计查询的条数边界:默认与上限都在存储层,入口层不写数字。
const ( CommentScopeJob = "job" CommentScopePlan = "plan" CommentScopeTodo = "todo" )
Comment scopes: what a comment is written ON. A comment belongs to exactly one job, plan or plan-todo (MCP-05 阶段 A); `scope_id` names the object.
const ( CommentAuthorUser = "user" CommentAuthorAgent = "agent" CommentAuthorSystem = "system" )
Comment author kinds. The kind is decided by the ENTRY that records the comment, never by the comment body: a human caller writes `user`, an agent speaking through MCP writes `agent`, and gofer's own explanation (an undispatchable @mention, say) writes `system`. The dispatch gate keys on it — only `user` starts work in 阶段 A.
const ( DecisionOpen = "OPEN" DecisionAnswered = "ANSWERED" DecisionExpired = "EXPIRED" )
Decision lifecycle states (decision channel, Part C §C3). A decision starts OPEN; a human answer moves it to ANSWERED; a timeout moves it to EXPIRED. Expiry is LAZY: nothing sweeps the table; every read/answer path first runs expireDueDecisions so a past-deadline OPEN row surfaces as EXPIRED (plan D2).
const ( MinDecisionTimeoutSec = 2 MaxDecisionTimeoutSec = 86400 DefaultDecisionTimeoutSec = 1800 )
Decision timeout bounds (plan D4). The authoritative clamp lives in InsertDecision so every entry face (HTTP/CLI/MCP) is covered; entry faces may additionally clamp for early failure. DefaultDecisionTimeoutSec applies when timeout_sec <= 0 is passed.
const ( DeliveryPending = "pending" DeliveryDelivered = "delivered" DeliveryFailed = "failed" )
Delivery status values (design §5.6). A delivery starts pending, then either reaches delivered (a 2xx webhook response) or failed (the retry cap is hit). While pending it may be re-claimed by the sweeper on each due tick.
const ( // TagSessionMessenger marks a web-to-terminal message delivery job. TagSessionMessenger = "session-messenger" // TagWorkSummarizer marks a work-item summarizer (tidy-up) job. TagWorkSummarizer = "work-summarizer" // TagTrackerSync marks a server-dispatched `gofer repo sync` job (TRK-05). TagTrackerSync = "tracker-sync" // TagDelivery marks the job that delivers a worker's worktree job (GIT-02). TagDelivery = "delivery" )
Internal job tags: records gofer itself creates on the user's behalf. Ordinary job lists (and the Board / workbench) hide them; `--all` and job detail keep them.
const ( JobCredentialMember = "member" JobCredentialLeader = "leader" // JobCredentialSteward is the W2b steward's credential: reads the work surface, // writes only the descriptive / scheduling side of it (never a final status, never a // job, never config). Its route allowlist lives in httpapi (stewardReadAllow / // stewardWriteAllow). JobCredentialSteward = "steward" )
JobCredentialKinds are the kinds of job-scoped credential (SEC-01): a member job's, a leader job's and (W2b) the steward's. The kind is what the hub's permission table keys on — a leader may move its own plan's checklist items and @-dispatch from a plan comment, a member may not do either.
const ( LeaderWakePending = "pending" LeaderWakeFiring = "firing" LeaderWakeFired = "fired" LeaderWakeCancelled = "cancelled" )
LeaderWake states (see the file comment).
const ( MemoryCandidatePending = "pending" MemoryCandidateAccepted = "accepted" MemoryCandidateRejected = "rejected" )
Memory candidate states.
const ( MemorySuggestPending = "pending" MemorySuggestAdopted = "adopted" MemorySuggestDismissed = "dismissed" // MemorySuggestStale: the memory changed under the suggestion (deleted, or the merge // target is gone) before anyone decided; it leaves the queue. MemorySuggestStale = "stale" )
Memory suggestion states.
const ( PlanIDMinLength = 9 PlanOpen = "open" PlanDone = "done" PlanArchived = "archived" // PlanBlocked is NOT terminal: a failed chain job parked the plan, and a human // releasing the item (set it ready/skipped) or `plan run|resume` puts it back to // PlanOpen and continues the chain. PlanBlocked = "blocked" )
Plan status values. A plan is a lightweight grouping header; it does not advance jobs itself — except through the PLAN-03 chain advance, which only ever moves it to PlanDone (all items finished) or PlanBlocked (a chain job failed).
const ( PlanLeaderOff = "off" PlanLeaderOn = "on" )
Plan leader switch values (LEAD-02). `leader` is a STRING on the plan rather than a bool so the zero value (an old row, or a caller that never set it) is the safe default: `off`. The global leader block only carries the parameters (agent/delay/rounds) and the master switch, so a plan that wants rounds must opt in.
const ( PlanNotifyOff = "off" PlanNotifyOn = "on" )
Plan notify switch values (gofer-3db4): does this plan's dispatches tell the supervising session when their job ends? A STRING like the leader switch, and for the same reason: the zero value of an old row (and of a PATCH that does not mention it) must mean `off`, so a plan never starts notifying because a caller left a bool untouched. The notification itself is opt-in per job; this switch is what makes "every job this plan dispatches" one decision instead of one per todo.
const ( PlanListDefaultLimit = 20 PlanListMaxLimit = 100 )
Plan page sizes (F-d): what a caller that names no limit gets, and the ceiling one page may ask for — a 10k-row request must not make the server build a 10k-row page (and the CLI's --all pages through instead).
const ( CompletionTodos = "todos" CompletionJobs = "jobs" CompletionNone = "none" )
PlanCompletion.Basis values.
const ( RetryPending = "pending" RetryClaimed = "claimed" RetryDone = "done" RetryCancelled = "cancelled" )
Retry states (R2/AUTO-03, design §二.1). A row is created PENDING by the failing job's finish path, moves to CLAIMED while a sweeper owns it for one submit attempt, and ends DONE (submitted, new_job_id recorded) or CANCELLED (an operator dropped it). A claimed row whose process died is NOT lost: its lease lapses and a later sweep claims it again (at-least-once, see ClaimDueRetries).
const ( ScopedMemoryGlobal = "global" ScopedMemoryProject = "project" )
const ( NudgeEvery = "every" NudgeStalled = "stalled" NudgeActive = "active" NudgePaused = "paused" NudgeEnded = "ended" )
Nudge kinds and states.
const ( NudgeEndedUntil = "until" NudgeEndedSessionEnd = "session_ended" NudgeEndedHandedOff = "session_handed_off" NudgeEndedManual = "removed" )
Nudge ended reasons (ended_reason).
const ( SessionRunning = "running" SessionIdle = "idle" SessionWaitingReply = "waiting_reply" SessionNeedsAttention = "needs_attention" SessionHandedOff = "handed_off" SessionEnded = "ended" // SessionOffline is set by the staleness sweep (MarkStaleSessionsOffline): the // session stopped heart-beating without a SessionEnd, so its process may well be // dead. Unlike ended it is a guess — any later register/heartbeat revives it. SessionOffline = "offline" )
Agent-session states (session relay, design SESS-01 §5). A session is registered by the agent CLI's hooks (SessionStart) and moves between states as hook events arrive:
running ─Stop(relay off)─▶ idle ─UserPromptSubmit─▶ running running ─Stop(relay on)──▶ waiting_reply ─answer─▶ running running ─Notification────▶ needs_attention (display only) * ─SessionEnd──────▶ ended * ─silent too long─▶ offline ─any register/heartbeat─▶ running (or the event's state)
handed_off is path B's state (design §9.1 B): a pty job started with `--resume` continues THIS session, so the terminal that registered it stops relaying (its stops no longer open turns) until the takeover is released.
const ( RelayModeAuto = "auto" RelayModeOn = "on" RelayModeOff = "off" )
Relay modes (SESS-01 R1): the per-session switch that decides whether a Stop waits for a web reply. `on` waits on every Stop (the human flipped it on), `off` never waits, and `auto` (the default) leaves the decision to the server's rules — the keyboard idle probe, or the last-human-input fallback for a terminal that cannot be probed at all.
const ( SessionReplySourceSession = "session" SessionReplySourceMessenger = "messenger" )
Reply sources: the target session's own hook (its SendMessage, captured verbatim) or the resident messenger that received that SendMessage.
const ( SessionMessageQueued = "queued" SessionMessageDelivered = "delivered" SessionMessageFailed = "failed" // SessionMessageDelivering is a message handed to an internal delivery job that had // BEGUN but had not finished when gofer's wait window elapsed (an update waiting for // idle can hold such a job for minutes): it is on its way, and the record is written // back to delivered / failed when the job ends (gofer-qzv5). SessionMessageDelivering = "delivering" // SessionMessageUndelivered is a message whose delivery provably never happened // (the ladder never started it, or its job was cancelled before it ran), so // resending it cannot deliver the text twice — the web offers a retry for exactly // this state and for no other failure. SessionMessageUndelivered = "undelivered" )
const ( SessionTopicSelf = "self" SessionTopicHuman = "human" )
Who set a session's topic (AgentSession.TopicSource). The read view adds a third value, "inferred", for a session with no topic of its own; it is never stored.
const ( StewardEventSession = "session" // a session of an open item went offline / ended StewardEventDue = "due" // a reminder / park deadline came due StewardEventDrafts = "drafts" // many unsorted drafts piled up )
Steward event kinds.
const ( StewardReviewRunning = "running" StewardReviewDone = "done" StewardReviewSkipped = "skipped" StewardReviewFailed = "failed" )
Steward review states.
const ( MergeSuggestPending = "pending" MergeSuggestAccepted = "accepted" MergeSuggestDismissed = "dismissed" )
Merge suggestion states.
const ( TodoPending = "pending" TodoReady = "ready" TodoDoing = "doing" TodoDone = "done" TodoSkipped = "skipped" )
Todo lifecycle statuses (Part C §C2, PLAN-02 P2). Done bool is kept in lockstep for back-compat: Done ⟺ Status == TodoDone (skipped is terminal but NOT done).
TodoReady sits between pending and doing and is the DISPATCH trigger: a todo that is BOTH ready and assigned turns into a job on the spot (job.MaybeDispatchTodo). `pending` is the backlog — assigned or not, it never dispatches on its own.
const ( // WakeupKindAt fires once at an absolute instant. WakeupKindAt = "at" // WakeupKindEvery fires every EverySec seconds from the moment it was created // or last enabled, never replaying a tick it could not fire (design §五.1). WakeupKindEvery = "every" // WakeupKindCron fires on the next CronExpr instant in Timezone. WakeupKindCron = "cron" // WakeupKindEvent fires when another job's lifecycle event matches. WakeupKindEvent = "event" )
Wakeup KINDS (JOB-09, design §五.1). A wakeup is either a TIMER (at / every / cron) or an EVENT subscription; both start a continuation of the job it is registered on when they fire.
const ( WakeupModeOnce = "once" WakeupModeContinuous = "continuous" )
Wakeup MODES: once consumes the wakeup on its first fire (enabled -> 0); continuous keeps it armed. The default is once for event/at and continuous for every/cron (design §五.1).
const ( WorkActive = "active" WorkNeedsMe = "needs_me" WorkWaitingResource = "waiting_resource" WorkNeedsOnsite = "needs_onsite" WorkReview = "review" WorkParked = "parked" WorkDone = "done" WorkDropped = "dropped" )
Work-item statuses (design §5). active/needs_me/review can be derived from the sessions (status_source=auto); the rest are set by a person (or a session report).
const ( WorkKindIdea = "idea" WorkKindIssue = "issue" WorkKindRequest = "request" WorkKindNote = "note" )
Capture kinds (work_items.kind); empty for items that were not captured.
const ( WorkSourceAuto = "auto" WorkSourceHuman = "human" WorkSourceReport = "report" )
Who decided the current status (work_items.status_source). Only `auto` is overwritten by the session-derived mapping.
const ( WorkOriginAuto = "auto" WorkOriginHuman = "human" WorkOriginSteward = "steward" )
Work-item origins (work_items.source).
const ( WorkJournalReport = "report" WorkJournalNote = "note" WorkJournalStatus = "status" WorkJournalSteward = "steward" WorkJournalLink = "link" )
Journal kinds.
const ( WorkSessionCurrent = "current" WorkSessionPast = "past" )
Session roles on a work item.
const ( WorkLinkIssue = "issue" WorkLinkPlan = "plan" WorkLinkTodo = "todo" WorkLinkJob = "job" )
Link kinds.
const ( WorkLevelMilestone = "milestone" WorkLevelDetail = "detail" )
Journal levels (WORK-06, design 2026-10-09 §3.3). A milestone is a line worth seeing on the lane / the item's default timeline ("状态变了、汇报了、job 有结果、人拍板了"); a detail is the bookkeeping around it (auto-derived status, links, tidy-up flow).
const ( WorkRequestReport = "report" // ask a running session to report its progress WorkRequestHandoff = "handoff" // ask a running session to write a hand-over WorkRequestSummarize = "summarize" // tidy the work item up from the transcript )
Work request kinds (W2a, design §14.3): what was asked for.
const ( WorkRequestPending = "pending" WorkRequestSent = "sent" WorkRequestAnswered = "answered" WorkRequestFailed = "failed" WorkRequestExpired = "expired" )
Work request states.
const ( WorkFieldGoal = "goal" WorkFieldBlocker = "blocker" WorkFieldNext = "next" WorkFieldSummary = "summary" )
Tracked descriptive fields of a work item (W2a field-level source, design §14.1.5): each of them remembers WHO last wrote it and when, so a card can say "整理器 · 3 分钟前" next to the goal and a reader can judge how far to trust it.
const ( SuggestGoal = "goal" SuggestBlocker = "blocker" SuggestBlockerKind = "blocker_kind" SuggestNext = "next" SuggestSummary = "summary" SuggestStatusHint = "status_hint" )
Suggestion fields the summarizer may propose (W2a, design §14.2). The first five are descriptive fields; status_hint is only ever a hint, never applied to the status.
const ( SuggestionPending = "pending" SuggestionDismissed = "dismissed" )
Suggestion states.
const ( SummaryRunning = "running" SummaryOK = "ok" SummaryFailed = "failed" )
Summary run states.
const ( WorkflowRunning = "running" WorkflowDone = "done" WorkflowFailed = "failed" WorkflowCancelled = "cancelled" )
Workflow status values (工作流/job 链, design §5.1). A workflow starts running, then reaches one terminal state: done (every step done), failed (fail-fast: a step failed/timed out/was cancelled, or starting the next step errored) or cancelled (CancelWorkflow). Only a running workflow is advanced by the engine.
const ClaimLeaseSeconds = 60
ClaimLeaseSeconds is the default lease a claimed-but-not-yet-resolved delivery is pushed out of the due window for (see ClaimDueDeliveries). It must exceed the per-POST webhook timeout so a delivery still being attempted is never re-claimed; on a process crash mid-attempt the lease expires and the row becomes due again (at-least-once delivery).
const DecisionKindPermission = "permission"
DecisionKindPermission marks a decision that is a terminal agent's tool permission prompt (Claude Code's PermissionRequest hook) mirrored to the web: the hook waits on it while the person is away, and the answer (allow / allow-always / deny) becomes the hook's permission decision. It shares the session decision rows with relay turns (session_id set) but is never a turn: the relay's say / deliver paths skip it (ListOpenSessionTurns).
const DecisionKindRelay = "relay"
DecisionKindRelay marks a decision that is a session-relay turn (the hook posted the agent's last message; the human answer is injected back).
const ( // DefaultListLimit caps ListJobs when the caller passes Limit <= 0. Mirrors // the job package's list default so behaviour is unchanged after the cutover. DefaultListLimit = 200 )
const JobMetricsVersion = 1
JobMetricsVersion is the derivation formula generation stored on every row. Bump it when a formula changes; the backfill recomputes rows of an older version.
const MaxNudgeText = 2000
MaxNudgeText caps the stored nudge text.
const MaxStewardReviewSummary = 2000
MaxStewardReviewSummary caps the stored point-of-view text of one review.
const PlanHandoffMaxBytes = 16 << 10
const SessionMessageReply = "reply"
SessionMessageReply is the Direction of a session's reply to a web message.
const StewardNotesKey = "steward:notes"
StewardNotesKey is the plan_handoffs namespace the steward notes are versioned under: the same storage and optimistic lock as a plan handoff. The colon keeps it out of the plan id space.
const StewardNotesMaxBytes = PlanHandoffMaxBytes
StewardNotesMaxBytes is the hard cap of one notes version (PlanHandoffMaxBytes).
const SubjectUsers = "users"
SubjectUsers 是 `users` 主体(设计 §2):对所有 user 类调用方都成立的授权。另外两种主体拼写 `caller:<id>` 与 `session:<sid>` 由第二批的授权管理接口写入。
const TodayActionAudit = "today.action"
TodayActionAudit is the audit_events kind the home page records after a card action succeeded (design §2.3 「已处理」): target_id is the card key, detail_json carries the action id, the advice action id and the display title of the card at that moment.
const TodayAdviceAudit = "today.advice"
TodayAdviceAudit is the audit_events kind written each time advice is recorded: the status bar's 「管家今日」 counts the distinct cards advised today from it (the advice rows themselves are pruned as cards get handled).
const UnknownSyncClientHost = "unknown"
UnknownSyncClientHost is the client_host recorded when a sync request does not say which machine it came from.
const WakeupClaimPending = "pending"
WakeupClaimPending is the continuation_job_id SENTINEL a fire writes before it submits the continuation job (see Store.ClaimWakeupFire). The slot must read as taken while that submit is in flight: submitting records job.submitted, which runs through the SAME event path the wakeup matcher listens on, so a slot that still looked free would let one wakeup fire (and re-fire) itself.
const WorkCaptured = "captured"
WorkCaptured is the capture-box status (design 2026-10-16 §3). It is deliberately NOT in WorkStatuses (the board column order) and not accepted by ValidWorkStatus: only the capture-box entry points may move an item into or out of it (WorkItemPatch.FromCapture, CaptureWorkItem).
const WorkDeletedEvent = "work.deleted"
WorkDeletedEvent is the audit_events kind of the row DeleteWorkItem leaves behind (target_id holds the work item id; only the actor is recorded, never the title). Before v0.123 it was a job_events row; see migrateWorkDeletedAudit.
Variables ¶
var ( ErrPlanHandoffConflict = errors.New("plan handoff version conflict") ErrPlanHandoffTooLarge = errors.New("plan handoff body exceeds 16 KiB") )
var ( ErrNudgeInvalid = errors.New("invalid session nudge") ErrNudgeNotFound = errors.New("session nudge not found") )
ErrNudgeInvalid marks a rejected nudge input (maps to 400); ErrNudgeNotFound to 404.
var ( ErrWorkItemNotFound = errors.New("work item not found") ErrWorkItemConflict = errors.New("work item was changed by someone else (rev mismatch)") ErrWorkInvalid = errors.New("invalid work item input") )
Errors surfaced to the entry layers.
var ErrMemoryCandidateDecided = errors.New("memory candidate already decided")
ErrMemoryCandidateDecided is a decision on a candidate that is no longer pending.
var ErrMemoryCandidateNotFound = errors.New("memory candidate not found")
ErrMemoryCandidateNotFound is an unknown candidate id.
var ErrMemorySuggestionDecided = errors.New("memory suggestion already decided")
ErrMemorySuggestionDecided is a decision on a suggestion that is no longer pending.
var ErrMemorySuggestionNotFound = errors.New("memory suggestion not found")
ErrMemorySuggestionNotFound is an unknown suggestion id.
var ErrMergeSuggestionNotFound = errors.New("merge suggestion not found")
ErrMergeSuggestionNotFound is returned for an unknown suggestion id.
var ErrRequestIDConflict = errors.New("jobstore: request_id already exists")
ErrRequestIDConflict is returned by UpsertJob when an INSERT of a NEW job id violates the partial unique index on request_id — i.e. another job already claimed the same request_id (C5 idempotency race). The caller (job.Submit) recovers by looking up and returning the job that won the race. It is NOT raised when the same job's row is updated in place (same id), only on a competing insert.
var ErrReservedTracker = errors.New("the global memory tracker cannot be renamed or deleted")
ErrReservedTracker refuses repository-tracker operations on the global tracker.
var ErrScopedMemoryNotFound = errors.New("scoped memory not found")
var ErrStewardNoReview = errors.New("no steward review is running or finished for today")
ErrStewardNoReview is returned when a review summary arrives with no review to attach to.
var ErrSuggestionNotFound = errors.New("work suggestion not found")
ErrSuggestionNotFound is returned when there is no pending suggestion for a field.
var ErrTrackerConflict = errors.New("tracker revision conflict")
var ErrTrackerNoPrefix = errors.New("tracker repository has no issue id prefix recorded yet")
ErrTrackerNoPrefix means the repository has no issue id prefix recorded yet.
var ErrTrackerRenameConflict = errors.New("tracker rename: both ids exist")
ErrTrackerRenameConflict means both the old and the new tracker id already exist.
var ErrTrackerRepoUnknown = errors.New("tracker repository is not registered on this server")
ErrTrackerRepoUnknown means no repository is registered under the tracker id.
var ErrTunnelPresetNotFound = errors.New("jobstore: tunnel preset not found")
ErrTunnelPresetNotFound is what DeleteTunnelPreset reports for a name that was never stored. It is a sentinel (not a bare string) so the HTTP layer can answer 404 while a real storage failure stays a 500 — the two are different promises to the caller.
var ErrWorkRequestNotFound = errors.New("work request not found")
ErrWorkRequestNotFound is returned for an unknown request id.
var InternalJobTags = []string{TagSessionMessenger, TagWorkSummarizer, TagTrackerSync, TagDelivery}
InternalJobTags is every internal tag the lists hide by default.
var WorkStatuses = []string{WorkActive, WorkNeedsMe, WorkWaitingResource, WorkNeedsOnsite, WorkReview, WorkParked, WorkDone, WorkDropped}
WorkStatuses lists the valid statuses in board order.
Functions ¶
func DecodeStringList ¶
DecodeStringList parses such a column back; a blank/unreadable value yields nil, so a corrupt filter degrades to "no filter" instead of failing a read path.
func DefaultWorkJournalLevel ¶
DefaultWorkJournalLevel is the level a journal line gets when its writer does not name one: a session report is a milestone; a status line is one unless gofer wrote it itself (auto-derived status, reminders — `system`); a note is one when a person wrote it; steward / link lines are details. Writers that know better (a field-only edit, a job outcome, the summarizer's `milestone`) pass the level explicitly.
func EncodeStringList ¶
EncodeStringList marshals a string slice into the JSON array an event_types / filter_status column holds. A nil/empty slice yields "" — an empty column reads back as "no values" everywhere, which is also what an absent filter means.
func IsReservedTracker ¶ added in v0.150.0
IsReservedTracker reports whether trackerID is the global memory tracker.
func JobSubmitAt ¶
JobSubmitAt is jobSubmitOrder for a record already in memory.
func NewRetryID ¶
func NewRetryID() string
NewRetryID mints a retry id: `rt-` + 8 random hex chars, the XFER-02 short-id shape (2 letters + 8 hex, like the transfers' `xf-` and the wakeups' `wk-`). It is what a human reads in `job retry ls` / an event scope, so it stays short; the id is a PRIMARY KEY, so a collision is absorbed by the insert failing rather than by handing one row out twice.
func NextCronRun ¶
NextCronRun parses a standard five-field cron expression and returns the next unix-second run strictly after after.
func NormalizePlanLimit ¶
NormalizePlanLimit turns a caller-supplied page size into the one the store uses: <=0 becomes PlanListDefaultLimit, anything above PlanListMaxLimit is clamped.
func NormalizePlanTags ¶
NormalizePlanTags trims, drops empty values, and de-duplicates tags while preserving their first-seen order for stable API/CLI output.
func ParseSessionUsage ¶
func ParseSessionUsage(raw string) runner.SessionUsage
ParseSessionUsage reads a session's stored usage_json ("" or unreadable = zero).
func SessionUsageDay ¶
SessionUsageDay is the daily-tally bucket of a unix time: its UTC date.
func ValidCommentAuthorKind ¶
ValidCommentAuthorKind reports whether kind is one of the three author kinds.
func ValidCommentScope ¶
ValidCommentScope reports whether scope names a commentable object kind.
func ValidDecisionState ¶
ValidDecisionState reports whether s is one of the decision states.
func ValidJobCredentialKind ¶
ValidJobCredentialKind reports whether k is a known credential kind.
func ValidPlanLeader ¶
ValidPlanLeader reports whether s is a value the leader switch accepts.
func ValidPlanNotify ¶ added in v0.160.0
ValidPlanNotify reports whether s is a value the notify switch accepts.
func ValidRelayMode ¶
ValidRelayMode reports whether m is one of the relay modes.
func ValidSessionState ¶
ValidSessionState reports whether s is one of the agent-session states.
func ValidSuggestionField ¶
ValidSuggestionField reports whether f is a suggestion field.
func ValidTodoStatus ¶
ValidTodoStatus reports whether s is one of the todo lifecycle statuses.
func ValidWorkKind ¶ added in v0.166.0
ValidWorkKind reports whether k is a capture kind.
func ValidWorkLevel ¶
ValidWorkLevel reports whether s is a journal level ("" is not one).
func ValidWorkStatus ¶
ValidWorkStatus reports whether s is a board work-item status (captured excluded).
func ValidWorkStatusOrCaptured ¶ added in v0.166.0
ValidWorkStatusOrCaptured is ValidWorkStatus plus captured, for the capture-box entry points and list filters.
func WorkRequestActive ¶
WorkRequestActive reports whether the request is still in flight.
func WorkStatusFinal ¶
WorkStatusFinal reports whether s ends the work item.
Types ¶
type AgentHealth ¶
type AgentHealth struct {
Agent string
// Jobs is every job of the agent inside the window, whatever its status.
Jobs int
// OK counts delivered jobs (done or needs_review — see agentHealthSuccessSQL).
OK int
// TransientFail counts failures classified as provider errors, OtherFail every
// other failure. Cancelled/timeout/queued jobs count in neither.
TransientFail int
OtherFail int
// OKSinceTransient counts the successes AFTER the last transient failure — the
// recovery evidence HealthState needs (a configured recover_after_ok > 1 cannot
// be decided from LastOKAt alone).
OKSinceTransient int
// LastOKAt / LastTransientAt are the unix seconds of those last outcomes
// (0 = none inside the window).
LastOKAt int64
LastTransientAt int64
}
AgentHealth is the recent-job picture of ONE agent (SUP-01 P3): how many jobs it ran inside the health window, how they ended, and when the two kinds of outcome last happened. It is a pure aggregation of the jobs table — no separate health store, no background task, and every value is explainable from the job rows.
type AgentSession ¶
type AgentSession struct {
SessionID string
Agent string
ProjectKey string
Runner string
Cwd string
Title string
Transcript string
TmuxPane string
// CallerID is the AUTHENTICATED caller that registered this session (the
// bearer token's id, server-stamped — never client-supplied). It is the
// session's owner: SUP-01 D uses it to (a) refuse a reply from anybody else
// and (b) know whose live jobs mean the human is supervising rather than
// away. "" for a session registered before this column existed, or by a hook
// on a server with no tokens configured — there is nobody to compare against.
CallerID string
State string
// RelayMode is the switch itself (auto | on | off) and the source of truth
// for the relay rules (see RelayModeAuto).
RelayMode string
TurnNo int64
LastMessage string
LastEvent string
LastSeenAt int64
StartedAt int64
EndedAt int64
// IdleSec is the system input idle time (seconds) the hook reported last;
// -1 = unknown / never reported. The relay service derives its idle auto-arm
// from this value (it is NOT the session's own idle time).
IdleSec int64
// LastHumanAt is when a HUMAN last acted in this session (unix seconds):
// SessionStart / a UserPromptSubmit that was not injected. 0 = never seen.
// Where no keyboard probe exists (containers without X11), the relay's
// turn-age fallback anchors on this instead of IdleSec.
LastHumanAt int64
// HandedOffJobID / HandedOffAt describe path B's takeover (design §9.1 B):
// the interactive pty job that continues this session, and when the handoff
// happened. Both zero unless State is handed_off (cleared on release).
HandedOffJobID string
HandedOffAt int64
PeerName string
PeerNameSource string
PeerStatus string
PeerMessaging bool
ProgressText string
ProgressAt int64
// LastCwd is the directory the hook reported on its most recent heartbeat — for
// DISPLAY only ("current directory"). It never replaces Cwd (the registered
// directory) and takes no part in the wake-up directory decision.
LastCwd string
// UsageJSON is the session's accumulated token usage (N2 §A) as the marshalled
// runner.SessionUsage, "" when none was ever reported. Written only by
// AddSessionUsage (additive), never by the upsert/touch paths.
UsageJSON string
// UsageAt is when AddSessionUsage last grew the usage (unix seconds; 0 = never). It
// is one of the "last progress" signals the session nudge's stall check reads (N2 §E).
UsageAt int64
// RefusedCallerID / RefusedAt record the most recent hook report REFUSED because
// it came from a caller that is not this session's owner (gofer-eh53): after a
// token split the terminal keeps beating as the new identity, the owner check
// rightly refuses it, and — without these two columns — nothing anywhere said
// so (the state, the last message and the progress just froze). "" / 0 = nobody
// was ever refused. The owner's own successful report clears them, and so does
// an admin hand-over (TransferAgentSessionOwner).
RefusedCallerID string
RefusedAt int64
// Topic / Scope / TopicSource / TopicAt are the session's declared topic: one
// sentence on what it works on, the project-relative sub-paths it owns, who set
// them (SessionTopicSelf | SessionTopicHuman) and when (unix seconds). Written only
// by SetSessionTopic — never by the register / heartbeat paths — and never holding
// an inferred value (that one is derived at read time).
Topic string
Scope []string
TopicSource string
TopicAt int64
}
AgentSession is a terminal agent CLI session (Claude Code / Codex) registered with the hub so the web can observe it and relay replies into it. SessionID is the CLI's own session id (the hook stdin `session_id`). Timestamps are unix seconds.
type AuditEvent ¶
type AuditEvent struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
TargetID string `json:"target_id"`
Actor string `json:"actor,omitempty"`
At int64 `json:"at"`
}
AuditEvent is one row of audit_events: who did what to which (now possibly gone) target, and when. It deliberately carries no titles or other content.
type AuditEventDetail ¶
type AuditEventDetail struct {
AuditEvent
Detail string `json:"detail,omitempty"`
}
AuditEventDetail is an audit row with its detail blob.
type AuthAuditEntry ¶ added in v0.162.0
type AuthAuditEntry struct {
At int64 `json:"at"`
Actor string `json:"actor,omitempty"`
Action string `json:"action"`
Subject string `json:"subject,omitempty"`
Permission string `json:"permission,omitempty"`
SessionID string `json:"session_id,omitempty"`
GrantID string `json:"grant_id,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
}
AuthAuditEntry 是 auth_audit 的一行:授权的增删、只靠会话授权通过的请求、被拒的请求(含原因)。
存储层只追加、不改不删(保留期清理除外);何时记、记什么由入口层决定。「授权的增删」与「请求类 记录」的写入属于计划的 T2.4(审计与使用计数)—— 本任务只提供读路径与写入入口,好让接口与过滤 规则在同一个提交里完成并通过测试。
At 是 unix 秒;Method / Path / Status / Reason 只对请求类记录有意义(授权增删留空)。
type AuthAuditFilter ¶ added in v0.162.0
AuthAuditFilter 是审计读取的过滤条件(设计「接口」:按主体、权限、授权 id 过滤)。三个字段都为空 时不加过滤;Limit 留 0 用 DefaultAuthAuditLimit,超过 MaxAuthAuditLimit 时取上限。
type AuthGrant ¶ added in v0.161.0
type AuthGrant struct {
ID string `json:"id"`
Subject string `json:"subject"`
// Pattern 是权限名模式(`tunnel.*` / `job.*.others` / `*`)。
Pattern string `json:"pattern"`
// Scope 第一期恒为 `*`;第二期才允许 project:<glob> 这样的限定(设计决策 10)。
Scope string `json:"scope"`
// ExpiresAt 是到期时刻(unix 秒;0 = 不过期)。会话主体必填,最长 24 小时(设计 §4)。
ExpiresAt int64 `json:"expires_at,omitempty"`
// SessionOwner / SessionIncarnation 只对会话主体有值:授权时会话的 owner 与化身。会话的
// 当前 owner 或化身一变,这条授权就不再生效(设计 §4)。
SessionOwner string `json:"session_owner,omitempty"`
SessionIncarnation string `json:"session_incarnation,omitempty"`
// GrantedBy 是写入者:`seed` 表示迁移种入,其余是调用方 id(第二批的接口)。
GrantedBy string `json:"granted_by"`
GrantedAt int64 `json:"granted_at"`
// RevokedAt / RevokedBy 记录撤销(设计 §2:撤销后重启不还原);0 / "" 表示仍然生效。
RevokedAt int64 `json:"revoked_at,omitempty"`
RevokedBy string `json:"revoked_by,omitempty"`
// OrphanedAt 是授权被判为孤儿的时刻(caller:<id> 在配置里不存在时停用,设计 §2);0 表示
// 不是孤儿。
OrphanedAt int64 `json:"orphaned_at,omitempty"`
// ExpandSnapshot 是这条模式在保存时展开出的权限名(设计 §2)。目录升级后,如果模式能匹配到
// 快照里没有的新权限,web 上提示「有新权限待确认」。
ExpandSnapshot []string `json:"expand_snapshot"`
Note string `json:"note,omitempty"`
// LastUsedAt / UseCount 是使用计数(第二批写入、按设计「审计与使用计数」统计)。
LastUsedAt int64 `json:"last_used_at,omitempty"`
UseCount int64 `json:"use_count"`
}
AuthGrant 是 auth_grants 的一行:发给某一个主体的一条模式授权(设计 §2)。
存储层只报事实,不判定:到期要看调用方的时钟,会话授权还要比对会话当前的 owner 与化身,孤儿要 看配置里还有没有这个调用方 —— 这些都在入口层(第一批的解析器只读 subject=users 且未撤销的行)。
type CaptureInput ¶ added in v0.166.0
type CaptureInput struct {
Text string
Kind string
ProjectKey string
Workspace string
// SourceSession / SourceJob are stored as fields only (never attached).
SourceSession string
SourceJob string
By string
}
CaptureInput is the capture-box insert request.
type Change ¶
type Change struct {
Kind ChangeKind
ID string
Status string
}
Change is one write notification. ID is the job id for job and interaction writes (empty for bulk or id-less ones); Status is the job's new status for job writes that know it.
type ChangeHook ¶
type ChangeHook func(Change)
ChangeHook receives a Change after a write method returns (it runs from a defer, so after the store's write lock was released). It MUST be non-blocking: it is called on the writer's goroutine, which in the job service is the recordEvent/persist hot path.
type ChangeKind ¶
type ChangeKind string
ChangeKind names the table family a write touched. The set is exactly what the browser's push topics need to invalidate; it is deliberately coarse.
const ( ChangeJob ChangeKind = "job" ChangeDecision ChangeKind = "decision" ChangeInteraction ChangeKind = "interaction" ChangeSession ChangeKind = "session" ChangePlan ChangeKind = "plan" ChangeWorkflow ChangeKind = "workflow" ChangeSchedule ChangeKind = "schedule" ChangeWork ChangeKind = "work" )
type Comment ¶
type Comment struct {
ID string
Scope string
ScopeID string
Author string
AuthorKind string
Body string
// MentionsJSON is the parsed @-mention list as JSON (e.g. `["omp"]`), or "" when
// the body mentioned nobody. It is what the UI highlights and what an audit reads
// without re-parsing the body.
MentionsJSON string
CreatedAt int64
// TriggeredJobID is the job this comment dispatched ("" = none). A comment that
// mentioned several agents links the FIRST one here; the full set travels in the
// caller's return value and in the `comment.triggered` events.
TriggeredJobID string
}
Comment is one row of the comments thread (MCP-05 阶段 A). It is a neutral struct like JobRecord/PlanTodo so the table can be written without this package importing internal/job (see the package doc): MentionsJSON is the opaque JSON array of the @names the body mentioned, and TriggeredJobID links the comment to the job it started ("" = it started none).
type DBStats ¶
type DBStats struct {
Path string
SizeBytes int64
WALSizeBytes int64
PageSize int64
PageCount int64
Tables map[string]int64
Partial bool
}
DBStats is a point-in-time picture of the SQLite metadata database for the web console's "Server DB" card: the file sizes, the page geometry and the row count of every table the dashboard reports. Partial=true means the row-count pass ran out of its budget before visiting every table — the counts gathered so far are still returned (the cheap file/page info is always complete).
type DecisionAdvice ¶
type DecisionAdvice struct {
CardKey string `json:"card_key"`
Text string `json:"text"`
ActionID string `json:"action_id,omitempty"`
Digest string `json:"digest,omitempty"`
By string `json:"by,omitempty"`
At int64 `json:"at"`
JobID string `json:"job_id,omitempty"`
}
DecisionAdvice is one decision_advice row.
type Delivery ¶
type Delivery struct {
ID int64 `json:"id"`
EventSeq int64 `json:"event_seq"`
JobID string `json:"job_id"`
Target string `json:"target"`
Status string `json:"status"`
Attempts int `json:"attempts"`
NextRetryAt int64 `json:"next_retry_at"`
LastError string `json:"last_error,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
// Body / EventType carry a PRE-RENDERED delivery (OBS-07a). They are empty for
// the classic job-event path, whose body is rebuilt from the events table at
// post time. A delivery that has a Body is posted verbatim and needs neither a
// job nor a row in `events` — that is what lets non-job notifications (session
// relay turns) reuse this queue's retry/backoff/audit.
Body string `json:"-"`
EventType string `json:"event_type,omitempty"`
}
Delivery is the SQLite-persisted projection of one E14 webhook delivery (design §5.6): one event_seq aimed at one webhook target. Like JobEvent it is a neutral struct (no internal/job import) so the job package can enqueue/inspect it without forming an import cycle.
EventSeq links back to job_events.seq; Target is the webhook URL. Status is one of the Delivery* constants. Attempts counts POST tries so far; NextRetryAt is the unix-second time the row becomes due again (the sweeper claims pending rows whose NextRetryAt <= now). LastError holds the most recent failure message (for the deliveries view); it never carries a secret.
type HoldDecision ¶ added in v0.137.0
type HoldDecision struct {
ID string
// From is the state the row must still be in; "" means awaiting_approval.
From string
To string
// HoldJSON replaces the row's hold record (the decision, who, when, note).
HoldJSON string
// Error is written to the error column ("" keeps the column as it is).
Error string
// At stamps updated_at, and ended_at when To is not queued (a decision that ends
// the job without running it).
At int64
}
HoldDecision is one compare-and-set transition of a held job's row: the row moves From -> To only while it is still in From, so an approve, a reject, a cancel and the expiry sweep racing on the same job resolve to exactly one winner.
type InteractionRecord ¶
type InteractionRecord struct {
ID string
JobID string
Type string
Prompt string
OptionsJSON string
Status string
Answer string
CreatedAt int64
AnsweredAt int64
// AnsweredBy 记录"谁应答了该 interaction"(监督分层升级路由 P3.2, design §10 审计区分):
// auto:<policy>(L0 内置规则器) / agent:<id>(L1 owner / L2 sup) / human(L3 web/CLI)。
// "" 表示尚未应答或未归因(旧库/relay,COALESCE→"")。
AnsweredBy string
// NeedsHuman 标记该 interaction 已被通用 sup 判为高危/拿不准、显式留给人处理(事件驱动按需
// 派发 y5wt):1=留给人。0=未标记(旧库/未拒答,COALESCE→0)。
NeedsHuman int64
// ToolCallJSON holds the marshalled approval detail of a kind=permission
// interaction (toolCallId/title/kind/locations/rawInput 摘要) — "" for every other
// interaction (and for a row written by a pre-GATE gofer).
ToolCallJSON string
// PolicyHint is the approval gate's human-readable rationale for a permission
// interaction (e.g. "ask: kind=edit"); "" otherwise.
PolicyHint string
// ExpiresAt is a permission interaction's answer deadline (unix seconds, 0 = none):
// the gate stops waiting then and applies on_timeout. 0 for every other kind (and
// for a row written by a pre-GATE gofer, COALESCE→0).
ExpiresAt int64
}
InteractionRecord is the SQLite-persisted projection of one running-job interaction (SP4, design §8). Like JobRecord it is a neutral struct, decoupled from internal/job, so the interactions table can be populated without this package importing job (which would form a job -> jobstore -> job cycle).
OptionsJSON holds the marshalled []InteractionOption (the choice/confirmation options) as the job package serialises it; an empty string means "no options". Answer/AnsweredAt are unset (empty / 0) while the interaction is still pending; the nullable columns COALESCE to those zero values on read (see selectInterCols).
type JobEvent ¶
type JobEvent struct {
Seq int64 `json:"seq"`
JobID string `json:"job_id"`
Type string `json:"type"`
Detail string `json:"detail,omitempty"`
At int64 `json:"at"`
}
JobEvent is the SQLite-persisted projection of one append-only lifecycle event (E13, design §5.1). Like JobRecord/InteractionRecord it is a neutral struct, decoupled from internal/job, so the job_events table can be populated without this package importing job (which would form a job -> jobstore -> job cycle).
Detail holds the marshalled detail_json original (already a JSON string); an empty string means "no detail" (the column stays NULL/empty). Seq is the monotonic global insertion order assigned by SQLite (AUTOINCREMENT) and used as the SSE/poll cursor; it is 0 on a value being inserted and set on read.
type JobMetrics ¶
type JobMetrics struct {
JobID string
Model string
Turns *int64
ToolCalls *int64
HumanCount *int64
HumanWaitSec *int64
ActiveSec *int64
Commits *int64
FilesChanged *int64
Insertions *int64
Deletions *int64
InputTokens *int64
OutputTokens *int64
CacheRead *int64
CostUSD *float64
ComputedAt int64
Version int
}
JobMetrics is one job_metrics row.
type JobOutcomeCounts ¶
JobOutcomeCounts is the 「自上次打开」 line: jobs that ended since a moment, split into done and failed (failed + timeout), and the commits the ended jobs delivered.
type JobRecord ¶
type JobRecord struct {
ID string
ProjectKey string
Agent string
ResumeAgent string
Runner string
Interactive bool
// ReadOnly (bd h-aii-0ql3) records whether the job ran under a read-only sandbox
// (cli-agent read_only_args / acp-agent session/set_mode). Persisted so a finished
// job still answers "was this run allowed to write?".
ReadOnly bool
// DirExclusive records the job's RESOLVED same-directory lock policy (JOB-11):
// true means it held (or would hold) the exclusive lock of its working directory.
// Persisted so a finished job still answers "was this run allowed to share the
// tree, and why did it queue?".
DirExclusive bool
// RequireReview / ReviewedBy / ReviewedAt / ReviewNote are the人工验收 (GATE-01
// S3) audit fields: whether the job was gated on a human's accept/reject, and —
// once that decision exists — who made it, when, and why. They are persisted so a
// reviewed job still explains itself long after its process ended.
RequireReview bool
ReviewedBy string
ReviewedAt int64
ReviewNote string
WorkerID string // reserved for ws-worker; empty for local/peer jobs
// WorkerInstanceID is the process nonce (wsproto.Register.InstanceID) of the
// worker connection the job was dispatched to (RECOV-01 R4). Together with
// WorkerID it proves WHICH worker process owns the job, so a hub starting after a
// serve restart can ADOPT a store-held `recovering` job only when the
// re-registering process is the very one that was running it. Empty for
// local/peer jobs and for rows written before R4 (which are never adopted).
WorkerInstanceID string
Status string
ExitCode int
Cwd string
ResultDir string // per-job log/artifact directory (logs stay on disk)
RequestJSON string // original JobRequest JSON, for re-submit/audit
SessionStateJSON string // persistent ACP session turn/deadline metadata
Error string
StartedAt int64
EndedAt int64
UpdatedAt int64
// CallerID is the authenticated submitter id (C2). Empty for jobs created
// without a caller token (legacy / allow_empty_token).
CallerID string
// SourceSessionID is the trusted caller-side session provenance, separate from
// SessionID (the target agent's resumable session).
SourceSessionID string
// RequestID is the optional client-supplied idempotency key (C5). Empty means
// "no idempotency key"; only non-empty values are unique-constrained.
RequestID string
// 产出与审计(job-outcomes-audit):job 终态时捕获的产出字段,best-effort 写入。
RenderedCommand string // 渲染后实际 argv {command,args,env_keys} JSON(E15)
ResultJSON string // <result_dir>/result.json 内容(E6)
ArtifactsJSON string // [{name,size,mtime}] 产物清单(E1,P2)
DiffSummary string // git diff --stat 截断摘要(E12,P3)
UncommittedFilesJSON string // GIT-01 first 200 cwd-relative paths
UncommittedCount int // GIT-01 total, including paths beyond the stored cap
// NDJSONKept / NDJSONDropped / NDJSONTruncated 是采集期 NDJSON 投影器
// (bd h-aii-rpky / bd h-aii-525u)的行数审计:stderr.log 写入/丢弃/截断的行数。
// 旧行 COALESCE 成 0(文本 agent 也是 0,同义)。
NDJSONKept int
NDJSONDropped int
NDJSONTruncated int
// Source 标记 job 实际执行位置(P4):""(local) / worker:<id> / peer:<name>。
Source string
// TagsJSON 是 job 标签的 JSON 数组原文(E5),如 `["a","b"]`。空表示无标签。
// 入库后用于 tags_json LIKE 检索(ListQuery.Tag);与 job.JobResult.Tags 互转。
TagsJSON string
// WorkflowID 关联此 job 所属的 workflow(工作流/job 链)。空表示普通(非工作流)job。
// 由工作流引擎在起 step-job 时设置;ListWorkflowJobs 据此 + StepIndex 排序回取。
WorkflowID string
// StepIndex 是此 job 在工作流中的 1-based 步序号(第 1 步=1)。非工作流 job 为 0。
StepIndex int
// Attempt 是 step-job 的 1-based 重试尝试号(P1,工作流 v2)。首次=1;重试起的新 job
// attempt+1。持久化到 jobs.attempt;旧库/普通 job 经 selectCols COALESCE 成 1。
// 与 StepIndex 一起区分同一 step 的多次重试运行(确定性 request_id 的 a<attempt> 段)。
Attempt int
// FanIndex 是 fan-out step 内同一 (step,attempt) 的并行 job 1-based 序号(P2,工作流
// v2,design §5.3)。FanOut>1 的 step 起 N 个 job,以 FanIndex=1..N 区分;非 fan-out
// job(含 v1/P1 单 job 路径)为 0。持久化到 jobs.fan_index(旧库/普通 job 经 selectCols
// COALESCE 成 0)。与 StepIndex/Attempt 一起构成确定性 request_id 的 f<fanIndex> 段,
// 保证每个 (step,attempt,fan) 只起一个 job(C5 幂等延续)。
FanIndex int
// SessionID 是底层 agent CLI 的会话标识(claude/codex 等),注入或捕获得到。空表示
// 无/未捕获;持久化到 jobs.session_id(旧库经 selectCols COALESCE 成 "");与
// job.JobResult.SessionID 互转,供 show/list/resume 使用。
SessionID string
ResumedFrom string
AutoResumeAttempt int
AutoResumedBy string
// StopReason is the acp-agent session/prompt stopReason (ACP-01 S0). Empty for
// every other agent type and for rows written before the column existed
// (selectCols COALESCEs it to "").
StopReason string
// WrapUp is the reason the AGENT itself reported for ending the run early
// (gofer-gk74): `max_steps` / `max_tokens` / `timeout`, from its structured stream.
// Empty = it answered, or the dialect reports no such reason (old rows too:
// selectCols COALESCEs it to "").
WrapUp string
// Channel / Client 是提交来源(provenance):channel=cli/web/mcp/im(提交渠道),
// client=来源主机名(CLI)/IP(HTTP)。空表示旧库/未提供(selectCols COALESCE 成 "");
// 与 job.JobResult 互转,配合 CallerID 供 show/list 标识"谁/哪台/经哪渠道提交"。
Channel string
Client string
// Role 是该 job 的角色预设名(supervisor-routing P2.2 套娃防护):监督路由器据此识别
// "supervisor 自身产生的 interaction",对其永不自动答/回投 sup(防死循环),直接留 pending
// 等人(L3)。空表示旧库/未提供(selectCols COALESCE 成 "");与 job.JobResult.Role 互转。
Role string
// PlanID 是客户端可设的归组键,把此 job 归入某个 plan。区别于引擎私有
// WorkflowID;空表示不属任何 plan(旧库经 selectCols COALESCE 成 "")。
PlanID string
// TodoID 是客户端可设的 checklist 键(SUP-01 C):把此 job 挂到某个 plan todo 上,
// 终态时由 hub 把结果写回该 todo 的 note/status。空表示不挂 todo(旧库 COALESCE→"")。
// 与 job.JobResult.TodoID 互转;反查 ListJobsByTodo。
TodoID string
// BaseSHA / CommitsJSON 是提交采集(SUP-01 C):BaseSHA=执行机在 job 开跑时的 HEAD
// (worktree job 即其基线),CommitsJSON=终态时 base..HEAD 的提交列表(JSON 数组,
// 新→旧)。非 git 仓/采集失败留空(旧库 COALESCE→"");与 job.JobResult 互转。
BaseSHA string
CommitsJSON string
// VerifyJSON is the verify step's result (SUP-01 P2) as the marshalled
// job.VerifyResult, or "" when the job had no step. Persisted so a finished job
// still answers "what did we check, and did it pass?" long after its logs rotated.
VerifyJSON string
// FailureClass / FellBackFrom / FellBackTo / RequestedAgent / FallbackJSON are the
// agent-failover columns (SUP-01 P3). FailureClass is "transient" (a provider
// error) or "other" for a failed job and "" for anything else — the health
// aggregation groups by it. FellBackFrom/FellBackTo link the two ends of a
// transfer chain (a source row points at the job that took over, the takeover
// points back). RequestedAgent is the agent the caller actually asked for, kept
// when a degraded agent was substituted at submit time or the job is a fallback.
// FallbackJSON is the submitted-time freeze of the transfer plan (candidates +
// depth). Old rows COALESCE to "" ("never classified, not part of a chain").
FailureClass string
FellBackFrom string
FellBackTo string
RequestedAgent string
FallbackJSON string
// UsageJSON is the agent's token/cost accounting for the job (SUP-01 E) as the
// marshalled job.Usage, or "" when nothing was captured. Persisted so a finished
// job still answers "what did this run cost?" after its logs rotated, and so
// /v1/stats can aggregate it with SQL json_extract. Old rows COALESCE to "".
UsageJSON string
// XferJSON is the job's file-transfer summary (XFER-01 X2) as the marshalled
// job.XferSummary, or "" when the job carried no files. Persisted so `job show`,
// the web detail and a restarted serve still answer "which files did this job
// move?" after the in-memory entry is gone. Old rows COALESCE to "".
XferJSON string
// LeaderOfPlan is the plan a LEADER job belongs to (MCP-05 阶段 B) — "" on every
// ordinary job. It is set SERVER-SIDE when the leader round submits the job (the
// request field is not on the wire), and it is what the wake rules and the review
// gate read: a leader job never wakes another leader, and it never reviews.
LeaderOfPlan string
// SkillsJSON is the job's bound skill list (JOB-10) as JSON, or "" when the job
// carried none. Persisted so a finished job still answers "which skills was this
// agent told to read?" after its result dir is gone, and so the mounted-set
// (`job show`) survives a serve restart. Old rows COALESCE to "".
SkillsJSON string
// RulesJSON is the job's injected rule list (JOB-06①) as JSON — one
// {"name":…,"sha256":…} per rule — or "" when no rule was injected. It is what
// answers "which discipline did this run actually carry, and which version of it?"
// after the config changed or the result dir is gone. Old rows COALESCE to "".
RulesJSON string
// SourceJobID 是血缘键(P5):resume/rebuild 出的 job 指回源 job id(服务端盖章)。空=非
// 派生(旧库 COALESCE→"")。与 job.JobResult.SourceJobID 互转;反查 ?source_job=。
// 注意区别既有 Source 列(执行位置 worker:/peer:)。
SourceJobID string
// RecoveringSince is the unix time the job entered the RECOV-01 `recovering`
// state (0 = never / not recovering). Old rows COALESCE to 0, which reads as
// "not recovering" — exactly the pre-RECOV-01 meaning.
RecoveringSince int64
// TimeoutSec / RequestedTimeoutSec / TimeoutClamped 是 job 超时上限可配(bd h-aii-s9ck)
// 的三元组:生效 deadline 秒数(0=无 deadline)、调用方请求值(0=未指定)、请求是否被上限
// 截断。旧库/旧 job 经 selectCols COALESCE 成 0/0/false,含义是"未记录",不会被误判成
// "被截断"。与 job.JobResult 同名字段互转(post-mortem 据此解释 job 为何提前被杀)。
TimeoutSec int
RequestedTimeoutSec int
TimeoutClamped bool
// WT-01 受管 worktree:job 在 <repo top>/tmp/gofer/wt/<job-id> 的独立 worktree 中执行,
// 提交落在分支 gofer/<job-id> 上。WorktreePath/Branch 是交付物位置,BaseSHA=基线提交,
// HeadSHA/CommitsAhead=终态时该分支的 HEAD 与领先基线的提交数。非 worktree job 为空/0
// (旧库经 selectCols COALESCE 成 ""/0);与 job.JobResult 同名字段互转,供 job show /
// web 详情 / worktree ls 使用。
WorktreePath string
WorktreeBranch string
WorktreeBaseSHA string
WorktreeHeadSHA string
CommitsAhead int
// HoldExpiresAt / HoldJSON are the hold-for-approval state (gofer-9b1b): when an
// awaiting_approval job is cancelled as expired (unix seconds, fixed at submit) and
// the job package's hold record (reason, origin, decision, ...). Rows that were never
// held COALESCE to 0 / "". The column pair stays after a decision as its audit trail.
HoldExpiresAt int64
HoldJSON string
// MCPJSON is the job's bound MCP server names (MCP-06) as JSON, "" when none.
MCPJSON string
// DeliveryJSON is the job's delivery outcome (GIT-02) as JSON, "" when none.
DeliveryJSON string
}
JobRecord is the SQLite-persisted projection of a job: the queryable job metadata (== the job package's JobResult fields) plus submission/bookkeeping columns (WorkerID, RequestJSON, UpdatedAt). It is a neutral struct, decoupled from internal/job, to keep this package free of a job import (see package doc).
Zero values mean "unset": EndedAt == 0 is "not ended yet" and empty strings are stored/read as such (the SELECTs COALESCE NULLs to the zero value), matching JobResult's omitempty semantics.
type JobTokenRecord ¶
type JobTokenRecord struct {
// JobID is the HUB job id. A worker executing a dispatched job uses this id (not
// its own local id) because every credential check happens on the hub.
JobID string
// TokenHash is the hex sha256 of the token (the lookup key).
TokenHash string
// Kind is JobCredentialMember or JobCredentialLeader.
Kind string
// PlanID is the plan the job belongs to ("" for an unattached job). A leader job
// always carries one: its widened rights are scoped to it.
PlanID string
// ExpiresAt is the fallback deadline (unix seconds): a job whose terminal path
// never ran — a crashed hub, a killed process — still loses its credential.
ExpiresAt int64
// RevokedAt is when the terminal path revoked it; 0 while live.
RevokedAt int64
CreatedAt int64
}
JobTokenRecord is one row of job_tokens: the hub's record of the credential it minted for a job.
Only the sha256 of the token is stored — never the token itself (design §横切). The secret exists in exactly two places: the job process's environment, and the dispatch frame that carried it to a worker. A stolen database therefore yields no usable credential.
type LeaderWake ¶
type LeaderWake struct {
ID string
PlanID string
MemberJobID string
MemberStatus string
DueAt int64
State string
Round int
LeaderJobID string
CreatedAt int64
CancelledBy string
CancelledAt int64
}
LeaderWake is one row of plan_leader_wakes. It is a neutral struct (no internal/job import, like every other type here): MemberStatus is the member job's terminal status as a plain string, and Round is the 1-based leader round this wake belongs to.
type ListQuery ¶
type ListQuery struct {
Project string // exact project_key match when non-empty
Status string // exact status match when non-empty
Caller string // exact caller_id match when non-empty (C2)
Tag string // tags_json contains this tag element when non-empty (E5)
Agent string // physical agent or resume_agent match when non-empty
Runner string // exact runner match when non-empty (E5)
// RunnerAlt is a second accepted spelling of Runner (G043: rows written under the
// built-in runner's alias before every entry normalized it). Empty = none.
RunnerAlt string
Session string // exact session_id match when non-empty (P3, list --session)
Plan string // exact plan_id match when non-empty (plan-orchestration P1)
SourceJob string // exact source_job_id match when non-empty (P5, list ?source_job=)
ExcludeTags []string // hide jobs carrying any of these internal tags
Limit int // <= 0 => DefaultListLimit
Offset int // skip the first Offset rows (pagination); ignored when <= 0
Since int64 // when > 0, keep only jobs with started_at >= Since
}
ListQuery filters/bounds a ListJobs query. A zero value lists every project's jobs (no status filter), newest first, capped at DefaultListLimit.
type ListSessionsOpts ¶
type ListSessionsOpts struct {
Project string
State string
Agent string
Cwd string
IncludeEnded bool
Limit int
}
ListSessionsOpts filters ListAgentSessions. Cwd matches sessions whose cwd equals the given path OR is an ancestor of it (so `gofer session relay on` run from a sub-directory still finds the session started at the repo root). Ended sessions are excluded unless IncludeEnded. Limit <= 0 means 200.
type MemoryCandidate ¶
type MemoryCandidate struct {
ID int64 `json:"id"`
JobID string `json:"job_id"`
ProjectKey string `json:"project_key"`
Text string `json:"text"`
Status string `json:"status"`
MemoryKey string `json:"memory_key,omitempty"`
CreatedAt int64 `json:"created_at"`
DecidedAt int64 `json:"decided_at,omitempty"`
DecidedBy string `json:"decided_by,omitempty"`
WhenPaths []string `json:"when_paths,omitempty"`
}
MemoryCandidate is one memory_candidates row. MemoryKey is the key the accepted memory was written under ("" until accepted). WhenPaths is the `when.paths` the memory inherits on accept: the nested repository the job's cwd sits in, relative to its tracker root (gofer-opv5), so a lesson learned in one checkout of a workspace does not reach the jobs of the others.
type MemoryCandidateFilter ¶
MemoryCandidateFilter narrows ListMemoryCandidates. Status "" = pending; "all" = every state.
type MemorySuggestion ¶
type MemorySuggestion struct {
ID int64 `json:"id"`
TrackerID string `json:"tracker_id"`
MemoryKey string `json:"memory_key"`
Action string `json:"action"`
PayloadJSON string `json:"payload_json"`
Reason string `json:"reason"`
State string `json:"state"`
By string `json:"by,omitempty"`
JobID string `json:"job_id,omitempty"`
// BaseRev is the memory's rev when the suggestion was made; TargetRev the merge
// target's (0 for other actions and rows from before the column). Adoption only
// applies while the live revs still match.
BaseRev int64 `json:"base_rev"`
TargetRev int64 `json:"target_rev,omitempty"`
CreatedAt int64 `json:"created_at"`
DecidedAt int64 `json:"decided_at,omitempty"`
DecidedBy string `json:"decided_by,omitempty"`
Note string `json:"note,omitempty"`
}
MemorySuggestion is one memory_suggestions row. PayloadJSON is the action's proposed value (internal/today.MemoryPayload).
type MetricsEvidence ¶
type MetricsEvidence struct {
// ACPTurns / ACPToolCalls: one job.acp_summary per acp prompt turn, carrying that
// turn's distinct tool calls.
ACPTurns int64
ACPToolCalls int64
// SessionTurns counts job.turn_ended of a persistent session job; SessionSays the
// follow-up prompts (job.turn_started with turn_no > 1); SessionIdleSec the gaps
// from job.awaiting_input to the next job.turn_started (the session waited for
// someone to speak). Replayed recovery events are skipped.
SessionTurns int64
SessionSays int64
SessionIdleSec int64
// HumanAnswers counts interactions a person answered (answered_by human / push).
// InteractionWaitSec sums answered_at - created_at over every interaction that was
// not auto-answered (L0 rules answer at once; they are not a wait).
HumanAnswers int64
InteractionWaitSec int64
}
MetricsEvidence is what the database knows about a job's turns and human involvement: the acp per-turn summaries, the persistent-session turn events and the interactions.
type OrphanSessionCandidate ¶
OrphanSessionCandidate is one job ReconcileOrphanJobs is about to FAIL, reduced to the fields a session re-scan needs (F11).
type OverviewJobRow ¶
type OverviewJobRow struct {
ID string
Project string
Agent string
ResumeAgent string
Status string
StartedAt int64
EndedAt int64
CommitsLen int64
RequestModel string
HasUsage bool
UsageInput int64
UsageOutput int64
UsageCache int64
UsageCost float64
HasMetrics bool
MModel string
MTurns *int64
MToolCalls *int64
MHuman *int64
MHumanWait *int64
MActive *int64
MCommits *int64
MFiles *int64
MIns *int64
MDel *int64
}
OverviewJobRow is one ended job (ended_at in range, terminal or needs_review) joined with its job_metrics row. The Usage* fields come from jobs.usage_json (HasUsage = the job reported any); the M* pointers from job_metrics (nil = no row or no value).
type OverviewReviewRow ¶
OverviewReviewRow is one job a human ruled on (reviewed_at in range). Rerun = a later job names it as its source (a rejection that was resumed with the note).
type Plan ¶
type Plan struct {
PlanID string
Title string
Description string
Status string
Owner string
Progress int
// ProjectKey is the project this plan's todos are dispatched INTO (PLAN-02 P2,
// `plan create --project`). It is what makes "指派即派发" a one-liner: a todo
// without its own project_key runs in the plan's. Empty = the plan names none, so
// every todo must carry its own (and a dispatch without one is refused).
ProjectKey string
// SupervisorSessionID is the trusted source session bound to plan dispatches.
SupervisorSessionID string
// Paused holds the automatic chain advance (PLAN-03): a todo that finishes while
// the plan is paused does NOT start its dependents.
Paused bool
// BlockedTodo is the item a FAILED chain job parked the plan on ("" = not
// blocked). Status is PlanBlocked while it is set.
BlockedTodo string
// Leader is this plan's leader-round switch (LEAD-02): PlanLeaderOn arms a round
// when a member job of the plan finishes, PlanLeaderOff (the default) does not.
// The global leader block stays the master switch; this one decides
// WHICH plans the rounds run for.
Leader string
// Notify is this plan's end-notification switch (gofer-3db4): PlanNotifyOn makes
// every job the plan DISPATCHES tell the plan's supervisor session that it ended
// (through the session messenger). PlanNotifyOff (the default) leaves each job's own
// --notify to decide. A plan with the switch on and no supervisor session notifies
// nobody — there is no address — and `plan show` says so.
Notify string
Tags []string
CreatedAt int64
UpdatedAt int64
}
Plan is the SQLite-persisted plan grouping header. It is neutral (no internal/job import) so job/http layers can drive it without an import cycle.
type PlanCompletion ¶
type PlanCompletion struct {
Basis string `json:"basis"`
Done int `json:"done"`
Total int `json:"total"`
Percent *int `json:"percent"`
}
PlanCompletion is a plan's single progress figure. Todos are the planned work items, so they win whenever a plan has any (done + skipped count as complete). Only a todo-less plan falls back to its jobs (succeeded / all): jobs include retries and failed attempts, which makes them a poor primary measure. Percent is nil when there is nothing to measure, so clients show "—" rather than 0%.
func RollupPlanCompletion ¶
func RollupPlanCompletion(j PlanCounts, t PlanTodoCounts) PlanCompletion
RollupPlanCompletion applies the PlanCompletion rule to a plan's job and todo roll-ups. It is the only place the rule lives; API, CLI and web consume it.
type PlanCounts ¶
type PlanCounts struct {
Total int `json:"total"`
Queued int `json:"queued"`
Running int `json:"running"`
Done int `json:"done"`
Failed int `json:"failed"`
}
PlanCounts is the query-time live roll-up of a plan's jobs by status bucket.
func RollupPlanCounts ¶
func RollupPlanCounts(raw map[string]int) PlanCounts
RollupPlanCounts folds raw job statuses into the public five-bucket summary. Status strings stay hard-coded here so jobstore remains neutral and does not import internal/job.
type PlanDecision ¶
type PlanDecision struct {
RowID int64 `json:"-"`
ID string
PlanID string
Title string
Question string
OptionsJSON string
Answer string
State string
TimeoutSec int64
AskedAt int64
AnsweredAt int64
AnsweredBy string
// SessionID / Kind are the session-relay additive columns (SESS-01 D3): a
// relay turn is a decision with Kind = DecisionKindRelay owned by an agent
// session; plain gofer_ask_human decisions leave both empty.
SessionID string
Kind string
// ReleasedBy is set when the turn was closed WITHOUT an answer (SR-A5:
// "user_returned" = the hook saw the human come back and released the wait).
// Empty for answered / timed-out turns.
ReleasedBy string
// AckedAt/AckedBy mark an OPEN relay turn as read without answering it. The
// hook remains blocked and the turn can still be answered later.
AckedAt int64
AckedBy string
// Detail is the JSON audit blob of a delivery that was not a turn (design
// §9.1 A): path A's tmux injection records {"path":"tmux","job_id":"…"} — the
// internal job that typed the reply into the terminal. Empty for real turns.
Detail string
}
PlanDecision is an agent-raised question waiting for a human answer. PlanID "" is a global question (no plan attached); OptionsJSON "" means free-text answer (an empty JSON array "[]" is normalised to "" on insert so a zero-option choice card can never be projected). Timestamps are unix seconds.
type PlanFilter ¶
type PlanFilter struct {
// Status restricts to one plan status ("" = any).
Status string
// Statuses restricts to any of the named statuses (OR semantics).
Statuses []string
// ProjectKey restricts to plans created for that project ("" = any), exact match.
ProjectKey string
// Q matches the plan id by PREFIX or the title by SUBSTRING, case-insensitively
// ("" = any). LIKE's own wildcards are literal here: a `%` in the query searches for
// a percent sign, it does not match everything.
Q string
// Tags requires every named tag to be present (intersection semantics).
Tags []string
// Limit caps one page (see NormalizePlanLimit). Offset skips rows of the filtered,
// newest-first list.
Limit int
Offset int
}
PlanFilter selects and pages the plan list. The zero value means "every plan, newest first, one default-sized page".
type PlanHandoff ¶
type PlanHandoff struct {
PlanID string `json:"plan_id"`
Version int `json:"version"`
Body string `json:"body"`
By string `json:"by"`
At int64 `json:"at"`
}
PlanHandoff is one immutable version of a plan's Markdown handoff note.
type PlanSessionUsage ¶
type PlanSessionUsage struct {
Sessions int
Usage runner.SessionUsage
}
PlanSessionUsage is the supervising-session usage attributed to a plan: the sum over every session that supervised it while it was live (usually one; a rebinding adds a second), and how many sessions contributed.
type PlanTodo ¶
type PlanTodo struct {
TodoID string
PlanID string
JobID string
Title string
Done bool
Status string
StartedAt int64
DoneAt int64
Note string
Sort int
// Assignee is the agent key that runs this item ("" = nobody assigned yet, which
// is why a ready item is not dispatched).
Assignee string
// ProjectKey is the project this item runs in, overriding the plan's own.
ProjectKey string
// Template is the task book the job's prompt is rendered from ("" = the default
// plan/todo prompt), Vars its {{variable}} values.
Template string
Vars map[string]string
// Verify is the argv run after the agent finishes (SUP-01 B), Review asks for a
// human verdict (GATE-01 S3), Runner/Cwd/TimeoutSec are the job's execution knobs.
Verify []string
Review bool
Runner string
Cwd string
TimeoutSec int
// DispatchError is why the last dispatch attempt produced no job.
DispatchError string
// After lists the plan-todo ids this item WAITS for (PLAN-03): the chain starts
// it only once every one of them is done or skipped. Empty = a root item, which
// nothing starts automatically — `plan run` (or a human setting it ready) does.
After []string
// Auto allows the chain to start this item automatically once its dependencies
// are satisfied (default true). False parks it until a human moves it.
Auto bool
// Cmd is the argv an `exec` item runs (PLAN-03). Ignored for any other assignee,
// and required for exec — the dispatcher refuses an exec item without one.
Cmd []string
// Model is the model the dispatched job asks for (N1 §B); "" = the agent's own
// default. Handed to Submit verbatim as JobRequest.Model.
Model string
// Budget is the spend ceiling of the dispatched job (N2 §B); nil = unlimited. Handed
// to Submit verbatim as JobRequest.Budget.
Budget *config.Budget
// Acceptance is the item's acceptance criteria (free text, usually a markdown
// list). Copied to JobRequest.Acceptance on dispatch, where Submit appends it to an
// agent's prompt and the review panel shows it next to the report.
Acceptance string
// PrimeKeywords are the subsystems / languages / modules this item's job is about
// (gofer-11tz). Copied to JobRequest.PrimeKeywords on dispatch, where they select
// and rank the tracker-prime material the job's agent receives.
PrimeKeywords []string
// Scope are path globs (relative to the repository root of the job's cwd) the
// item's job is expected to change (gofer-3nxa.3). Copied to JobRequest.Scope; the
// review marks changed files outside them.
Scope []string
CreatedAt int64
UpdatedAt int64
}
PlanTodo is a plan-orchestration todo item. JobID "" is a plain checklist item; a non-empty JobID binds it to one job run as metadata. Done is exposed as bool while storage stays the 0/1 INTEGER column used by SQLite; Status is the richer lifecycle (Part C §C2), StartedAt/DoneAt are stamped automatically on status transitions, Note is a short outcome/remark (overwritten, not a process log — that belongs to job logs).
The PLAN-02 fields (Assignee … DispatchError) describe HOW and WHERE the item runs once it is dispatched: the assignee is the agent, ProjectKey overrides the plan's project, and Template/Vars/Verify/Review/Runner/Cwd/TimeoutSec are handed to Submit verbatim. DispatchError is the last FAILED attempt's message — a human reads it on the checklist instead of digging through a job that was never created; a successful dispatch clears it.
func (*PlanTodo) ApplyTodoPatch ¶
ApplyTodoPatch folds a caller's patch into a todo that is about to be inserted (the insert-path twin of UpdateTodoPatch): the entry points that CREATE a todo from a request body use it so "set on create" and "set on update" cannot drift. A nil entry means the field was not sent, so nothing is touched.
type PlanTodoCounts ¶
type PlanTodoCounts struct {
Total int `json:"total"`
Pending int `json:"pending"`
Doing int `json:"doing"`
Done int `json:"done"`
Skipped int `json:"skipped"`
}
PlanTodoCounts is the query-time roll-up of a plan's todos by lifecycle status.
func CountTodos ¶
func CountTodos(todos []PlanTodo) PlanTodoCounts
CountTodos rolls up already-loaded todos (the plan detail has them in hand).
type PlanUsage ¶
type PlanUsage struct {
Jobs int
TotalTokens int64
CostUSD float64
// ByAgent is keyed by agent key; a job with an empty agent is keyed by "".
ByAgent map[string]UsageAgent
}
PlanUsage is a plan's token/cost roll-up (PLAN-02 P2): what the jobs attached to it reported, in total and per agent. Jobs counts EVERY attached job — one that captured no usage still ran — while the sums only see the rows that reported numbers, exactly like UsageWindow (see usageStatsQuery for why the extraction is json_valid-guarded).
type PtySessionRecord ¶
type PtySessionRecord struct {
PtySessionID string
JobID string
WorkerID string
InstanceID string
Owner string
State string
Cols int
Rows int
RecordingURI string
Encrypted int
BytesIn int64
BytesOut int64
StartedAt int64
EndedAt int64
}
PtySessionRecord is the SQLite-persisted metadata of one established pty relay recording (WEB-03 P3, design §3). Like JobRecord it is a neutral struct so this package stays decoupled from internal/job / internal/httpapi. httpapi is the sole writer: it upserts an `open` row when the relay opens and a `closed` row (same PK) at finalize. Encrypted is 1 (yes) / 2 (no) per SR301; RecordingURI is <result_dir>/pty.cast, empty when the recording is absent / write-failed / TTL-expired. Times are unix seconds; EndedAt 0 means still open.
type PushSubscription ¶
type PushSubscription struct {
CallerID string `json:"caller_id,omitempty"`
Endpoint string `json:"endpoint"`
P256DH string `json:"p256dh,omitempty"`
Auth string `json:"auth,omitempty"`
UserAgent string `json:"user_agent"`
CreatedAt int64 `json:"created_at"`
LastOKAt int64 `json:"last_ok_at"`
}
PushSubscription is one browser endpoint owned by an authenticated user caller. The encryption key material is opaque to jobstore; internal/webpush is the only package that interprets it.
type RedactReport ¶
RedactReport contains only aggregate counts and skipped relative paths. It deliberately has no field that can carry a literal or a matched value.
func (RedactReport) String ¶
func (r RedactReport) String() string
type RetentionPolicy ¶
type RetentionPolicy struct {
// MaxAge, when > 0, deletes terminal jobs whose effective end time (ended_at,
// or updated_at when ended_at is 0) is older than now-MaxAge.
MaxAge time.Duration
// MaxCount, when > 0, keeps only the newest MaxCount terminal jobs (by
// started_at desc) and deletes the rest.
MaxCount int
}
RetentionPolicy bounds how many terminal jobs (and their logs) are kept, solving the disk side of C1 (design §13 SP5). A zero value (both fields <= 0) prunes nothing.
func (RetentionPolicy) IsZero ¶
func (p RetentionPolicy) IsZero() bool
IsZero reports whether the policy would prune nothing.
type RetryRecord ¶
type RetryRecord struct {
ID string `json:"id"`
SourceJobID string `json:"source_job_id"`
Attempt int `json:"attempt"`
RequestJSON string `json:"-"`
Reason string `json:"reason"`
NextRunAt int64 `json:"next_run_at"`
LeaseUntil int64 `json:"lease_until,omitempty"`
State string `json:"state"`
NewJobID string `json:"new_job_id,omitempty"`
CreatedAt int64 `json:"created_at"`
}
RetryRecord is the SQLite-persisted durable retry of ONE failed job (R2/AUTO-03, design §二.1). It is a neutral struct — this package must not import internal/job (G022) — so RequestJSON is the re-submittable JobRequest as an opaque string: the sweeper (the job package) unmarshals it and submits it.
SourceJobID is the job that FAILED (the row exists to re-run it); Attempt is the 1-based number of the attempt about to run (>= 2, the first run being attempt 1); Reason is why it was scheduled (`exit_code=N`); NextRunAt is the unix second the row becomes due; LeaseUntil is the claim lease (0 while pending, now+lease while claimed); NewJobID is the submitted job once done.
type ScheduleRecord ¶
type ScheduleRecord struct {
ID string
Name string
ScheduleType string
CronExpr string
RequestJSON string
Enabled int
NextRunAt int64
LastRunAt int64
LastJobID string
CatchUp int
ProjectKey string
// TriggerToken is the schedule's OWN webhook secret (AUTO-02b): the token
// `POST /v1/schedules/{id}/trigger` accepts. Empty = the webhook endpoint is not
// enabled for this schedule. It is NOT the caller bearer and never authenticates
// anything else.
TriggerToken string
CreatedAt int64
UpdatedAt int64
}
ScheduleRecord is the SQLite-persisted projection of one cron schedule (AUTO-02). RequestJSON holds the marshalled JobRequest; jobstore keeps it as an opaque string to avoid importing internal/job.
type ScopedMemory ¶
type ScopedMemory struct {
Scope string `json:"scope"`
ScopeKey string `json:"scope_key,omitempty"`
Key string `json:"key"`
Content string `json:"content"`
Tags []string `json:"tags,omitempty"`
UpdatedAt string `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
Deleted bool `json:"deleted,omitempty"`
// MemoryMeta (kind / summary / when / expires_at / source / created_at) is
// stored as JSON in scoped_memories.meta_json and flattened on the wire.
tracker.MemoryMeta
}
type ScopedMemoryMetaPatch ¶
type ScopedMemoryMetaPatch struct {
Kind *string
Summary *string
When *tracker.MemoryWhen
ExpiresAt *string
Source *string
}
ScopedMemoryMetaPatch carries the optional fields of a scoped memory write. Nil keeps the stored value (so web / MCP writes that only send content and tags never drop them); When replaces the whole trigger set.
type SecretBatchRedact ¶
type SecretBatchRedact struct {
JobID string `json:"job_id"`
Report RedactReport `json:"report"`
}
type SecretBatchRedactReport ¶
type SecretBatchRedactReport struct {
Scanned SecretScanReport `json:"scanned"`
Redacted []SecretBatchRedact `json:"redacted"`
WALPurged bool `json:"wal_purged"`
Vacuumed bool `json:"vacuumed,omitempty"`
}
type SecretScanFilter ¶
SecretScanFilter narrows a scan without carrying authorization policy into the store. HTTP callers set OwnerID for non-admin requests.
type SecretScanJob ¶
type SecretScanJob struct {
JobID string `json:"job_id"`
Project string `json:"project,omitempty"`
Status string `json:"status"`
Title string `json:"title,omitempty"`
Locations []SecretScanLocation `json:"locations"`
}
type SecretScanLocation ¶
SecretScanLocation identifies a matching text position without carrying the matched value back to the caller.
type SecretScanReport ¶
type SecretScanReport struct {
Jobs []SecretScanJob `json:"jobs"`
Running []SecretScanJob `json:"running,omitempty"`
}
SecretScanReport is aggregate-only: it intentionally contains no literal, regex body, matched text, or file contents.
func (SecretScanReport) String ¶
func (r SecretScanReport) String() string
type SessionDecisionPage ¶
type SessionDecisionPage struct {
Decisions []*PlanDecision
HasMore bool
NextBefore string
}
SessionDecisionPage is a stable newest-first page of decisions. NextBefore is an opaque cursor that can be sent back as the before query parameter.
type SessionGrantAnchor ¶ added in v0.163.0
SessionGrantAnchor 是会话登记授权要绑定的值,以及判定这条授权是否生效要看的会话事实 (设计「接口」:POST /v1/auth/grants「会话主体自动记下 owner 与化身」;§4「生效条件」):
- Owner / Incarnation:授权记下的就不再变,之后每次请求都要与会话**当前**的这两个值比对;
- State / EndedAt:会话结束(state=ended,或 ended_at 留着——接管一个已结束的终端就是 这种情况)后,它的授权一条也不再生效。
存储层只报事实(G022):怎么用这些值判定是入口层的事。会话不存在时 ok 为 false、err 为 nil。
func (SessionGrantAnchor) Ended ¶ added in v0.163.0
func (a SessionGrantAnchor) Ended() bool
Ended reports whether the session has ended: the state says so, or the terminal stamp is still there (a session taken over after it ended keeps ended_at — design §4「读时还要判定 ended_at 为 空,作为第二道保险」).
type SessionHeartbeat ¶
type SessionHeartbeat struct {
Event string
State string
LastMessage string
Title string
// IdleSec is the hook's system input idle reading. nil = this event carried
// none, so the stored value stays (a beat must never clear evidence the
// human is away, nor invent it).
IdleSec *int64
// HumanInput marks an event that PROVES a human acted in this session (a
// non-injected UserPromptSubmit, or the SessionStart registration): it stamps
// last_human_at = now, the anchor of the relay's turn-age fallback.
HumanInput bool
// CallerID fills an EMPTY caller_id (SUP-01 D): a session registered before
// the column existed, or by a hook that did not authenticate, gets its owner
// at the first beat that does. An owner already recorded is never replaced.
CallerID string
PeerName string
PeerNameSource string
PeerStatus string
PeerMessaging *bool
ProgressText string
ProgressAt int64
ClearProgress bool
// Cwd is the hook's current directory (display only → last_cwd). "" leaves the
// stored value alone.
Cwd string
}
SessionHeartbeat is the per-event update carried by TouchAgentSession. Empty fields are left unchanged; Title only fills an EMPTY stored title (the first user prompt names the session, later prompts do not rename it).
type SessionJobWatch ¶
SessionJobWatch is the short-lived relation between a terminal session and a job that session asked gofer to watch. Job state remains in jobs; this row only records the reference and registration time.
type SessionMessage ¶
type SessionMessage struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Text string `json:"text"`
Operator string `json:"operator,omitempty"`
Status string `json:"status"`
Channel string `json:"channel,omitempty"`
JobID string `json:"job_id,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
// Direction is "" for a web-to-session message and SessionMessageReply for the
// session's own answer to one (gofer-6er0). Source / Peer / ReplyTo only apply
// to replies: who reported it (SessionReplySource*), the Claude Code address it
// was sent to (or the peer name it came from), and the web message it follows.
Direction string `json:"direction,omitempty"`
Source string `json:"source,omitempty"`
Peer string `json:"peer,omitempty"`
ReplyTo string `json:"reply_to,omitempty"`
}
SessionMessage is one immutable state record in a web-to-agent outbox. Readers collapse records with the same ID to the newest status.
type SessionModelUsage ¶
type SessionModelUsage struct {
Model string
InputTokens int64
OutputTokens int64
CacheRead int64
CostUSD float64
}
SessionModelUsage is the terminal-session usage of one model inside a day range.
type SessionNudge ¶
type SessionNudge struct {
ID string
SessionID string
Kind string
IntervalSec int64
Text string
UntilAt int64
State string
PauseReason string
EndedReason string
CreatedBy string
CreatedAt int64
UpdatedAt int64
// NextRunAt is the next due instant of an "every" nudge (0 for "stalled").
NextRunAt int64
// LastFiredAt is the last delivery ATTEMPT (success or failure); a stalled nudge
// measures its next threshold from it so a failing or answered nudge never repeats
// faster than its own interval.
LastFiredAt int64
FireCount int64
// FailCount counts CONSECUTIVE failed deliveries; success resets it.
FailCount int64
LastError string
}
SessionNudge is one row of session_nudges. Timestamps are unix seconds.
type SessionStats ¶
type SessionStats struct {
Total int
ByState map[string]int
ByRelayMode map[string]int
WaitingTurns int
SeenWithin1h int
}
SessionStats is the agent-session aggregate behind the dashboard's "Sessions" card (session relay, SESS-01 §5): how many terminal sessions the hub knows, how they split by state and by relay mode, how many relay turns still wait for a human answer, and how many sessions were seen in the last hour.
type SessionUsageStats ¶
type SessionUsageStats struct {
Windows map[string]SessionUsageWindow
}
SessionUsageStats is SessionUsageWindow per window label ("24h", "7d"). The tally is per UTC day, so a window covers every day bucket from the day of (now - window) up to today: up to one extra day at the old edge.
type SessionUsageWindow ¶
type SessionUsageWindow struct {
Sessions int
Total runner.Usage
ByAgent map[string]runner.Usage
// ByModel is the same tally per model (the pricing estimate needs it, gofer-2ldy).
ByModel map[string]runner.Usage
}
SessionUsageWindow is the terminal-session usage inside one stats window.
type SplitWorkItemInput ¶
type SplitWorkItemInput struct {
Title string
Goal string
// SessionIDs of the source item to hand to the new item.
SessionIDs []string
// KeepSessions leaves them attached to the source as well (one session that did
// two things); false moves them (they become `past` on the source).
KeepSessions bool
By string
}
SplitWorkItemInput describes a split.
type StewardEvent ¶
type StewardEvent struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Ref string `json:"ref"`
Detail string `json:"detail,omitempty"`
At int64 `json:"at"`
HandledAt int64 `json:"handled_at,omitempty"`
}
StewardEvent is one thing the steward should look at: noted cheaply, handled by the next review (or an event-driven wake). (kind, ref) is unique, so the same occurrence is noted once.
type StewardReview ¶
type StewardReview struct {
ID int64 `json:"id"`
Day string `json:"day"`
State string `json:"state"`
Trigger string `json:"trigger,omitempty"`
ItemIDs string `json:"item_ids,omitempty"`
Summary string `json:"summary,omitempty"`
JobID string `json:"job_id,omitempty"`
StartedAt int64 `json:"started_at"`
EndedAt int64 `json:"ended_at,omitempty"`
Error string `json:"error,omitempty"`
}
StewardReview is one daily / manual / event review run of the steward.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a handle to the SQLite job database. It is safe for concurrent use: the underlying *sql.DB is a connection pool and SQLite (in WAL mode) lets readers and the single writer proceed concurrently.
writeMu serialises writes in-process so only one SQLite writer is ever active. WAL + busy_timeout alone proved insufficient under full-speed concurrent upserts (intermittent SQLITE_BUSY "database is locked"); since this is a single process owning a single db file, an in-process write lock removes the contention entirely while leaving reads (GetJob/ListJobs) free to run on the pool concurrently.
func Open ¶
Open opens (creating if absent) the SQLite database at path, applies the schema and returns a ready Store. The parent directory is created if needed; the db file is restricted to 0600 (private; see design §12). Callers must Close it.
func (*Store) AckDecision ¶
AckDecision marks an OPEN decision as read without changing its lifecycle. Repeating the operation is idempotent; non-OPEN decisions are not ackable.
func (*Store) ActivateAuthGrant ¶ added in v0.162.0
ActivateAuthGrant 恢复一条孤儿授权:清掉 orphaned_at(设计 §2「要根管理员在 web 上确认后才恢复」)。 不是孤儿的行是幂等的空操作,返回它现在的样子;不存在时 ok 为 false。
func (*Store) ActiveACPSessionCounts ¶
ActiveACPSessionCounts reports resident session processes per agent. Queued jobs have no process yet and terminal jobs no longer occupy a slot.
func (*Store) AddMemoryCandidates ¶
func (s *Store) AddMemoryCandidates(jobID, projectKey string, texts, whenPaths []string) (int, error)
AddMemoryCandidates records texts as pending candidates of jobID, skipping empty texts and ones this job already has. whenPaths (nil = none) is the `when.paths` the accepted memory inherits. It returns how many rows were new.
func (*Store) AddMemorySuggestion ¶
func (s *Store) AddMemorySuggestion(m MemorySuggestion) (MemorySuggestion, bool, error)
AddMemorySuggestion records a pending suggestion. The same (tracker, key, action) still pending is returned as is with recorded=false (no duplicate card).
func (*Store) AddSessionJobWatch ¶
func (s *Store) AddSessionJobWatch(sessionID, jobID string) (SessionJobWatch, error)
AddSessionJobWatch records a watch idempotently. The session must already exist; callers decide whether the referenced job is visible to them.
func (*Store) AddSessionUsage ¶
AddSessionUsage adds one reported delta to the session and to today's tally. A session unknown to the store, or an empty delta, is a no-op (ok=false for unknown).
func (*Store) AddStewardEvent ¶
AddStewardEvent notes an event; added=false when the same (kind, ref) was noted before.
func (*Store) AddWorkLink ¶
AddWorkLink links an issue / plan / todo / job (idempotent).
func (*Store) AddWorkMergeSuggestion ¶
func (s *Store) AddWorkMergeSuggestion(targetID, sourceID, reason, by string) (WorkMergeSuggestion, bool, error)
AddWorkMergeSuggestion records a pending suggestion (source into target). The same pending pair is not recorded twice (the existing one is returned, stored=false). It journals a line on both items so the card shows it.
func (*Store) AdvanceCurrentStep ¶
AdvanceCurrentStep is the v1推进屏障, retained as a thin AdvanceStep wrapper for the existing direct-claim tests and any single-attempt推进 (the workflow engine itself now calls AdvanceStep with the explicit二元组). It moves current_step from `from` to `to` for attempt 1, leaving the attempt at 1 and no pending backoff — equivalent to the v1 single-value conditional UPDATE. New code should call AdvanceStep directly with the (step,attempt)二元组.
func (*Store) AdvanceSchedule ¶
func (*Store) AdvanceStep ¶
func (s *Store) AdvanceStep(id string, fromStep, fromAtt, toStep, toAtt int, nextStepAt int64) (bool, error)
AdvanceStep is the推进幂等屏障 (SR303), upgraded for工作流 v2 retry (P1, plan ⭐节 2). It atomically moves a running workflow's (current_step, step_attempt) 二元组 from (fromStep,fromAtt) to (toStep,toAtt) via a conditional UPDATE, sets next_step_at (退避到点时间; 0=immediate), and returns true ONLY for the UPDATE that actually changed the row.
The WHERE re-checks current_step==fromStep AND step_attempt==fromAtt AND status=='running', so any two concurrent/repeated callers (the finish hook + the sweeper firing for the SAME finished (step,attempt)) can never both win: the first moves the二元组 off (fromStep,fromAtt), the second affects 0 rows and returns false. Every v2 transition is the same symmetric抢权:
- 推进下一步: (cur,att) → (cur+1, 1), nextStepAt=0
- 重试本步: (cur,att) → (cur, att+1), nextStepAt=now+backoff
- 继续(跳过): (cur,att) → (cur+1, 1), nextStepAt=0
so the赢家唯一 invariant ("一个 (step,attempt) 的状态转移绝不执行两次") holds for推进/重试/继续 alike. Layered on the deterministic request_id (⭐节 1) this is the double-safeguard that no (step,attempt) ever starts two jobs. Runs under writeMu (every writer's in-process lock).
func (*Store) AdvanceWakeup ¶
AdvanceWakeup moves a due timer's next_run_at with a compare-and-swap, so when two sweeps (or a sweep and an enable) race, exactly one of them fires that tick. newNext == 0 marks a consumed one-shot. It mirrors AdvanceSchedule.
func (*Store) AgentHealth ¶
func (s *Store) AgentHealth(agent string, since int64) (AgentHealth, error)
AgentHealth aggregates one agent's jobs with started_at >= since. An agent with no job in the window yields a zero record (Jobs == 0), which is what makes "no evidence" distinguishable from "healthy" upstream.
func (*Store) AgentHealthAll ¶
func (s *Store) AgentHealthAll(since int64) (map[string]AgentHealth, error)
AgentHealthAll aggregates every agent's jobs with started_at >= since in one query, keyed by agent key. Agents with no job in the window are simply absent from the map (callers substitute a zero record).
func (*Store) AnswerDecision ¶
AnswerDecision records a human answer. It first runs lazy expiry (plan M2: answering a past-deadline decision must not succeed), then a single conditional UPDATE gated on state='OPEN' — a second answer, or a race with expiry, affects 0 rows and reports ok=false (plan D3, 验收3).
func (*Store) AppendAuditEvent ¶
AppendAuditEvent appends one audit row and returns its id.
func (*Store) AppendSessionOutbox ¶
func (s *Store) AppendSessionOutbox(m SessionMessage) error
AppendSessionOutbox appends one immutable message state record.
func (*Store) AppendTodoNote ¶
AppendTodoNote atomically appends a line to the todo's note (newline-separated; empty/NULL note becomes the appended text). Single UPDATE, so concurrent appends cannot lose each other's lines.
func (*Store) AppendWorkJournal ¶
func (s *Store) AppendWorkJournal(id, kind, text, by string) (WorkJournalEntry, error)
AppendWorkJournal appends one journal line (at the default level for its kind and author) and refreshes the item's activity time.
func (*Store) AppendWorkJournalLevel ¶
func (s *Store) AppendWorkJournalLevel(id, kind, text, by, level string) (WorkJournalEntry, error)
AppendWorkJournalLevel is AppendWorkJournal with an explicit level ("" = the default for the kind and author, see DefaultWorkJournalLevel).
func (*Store) AttachJobToPlan ¶
AttachJobToPlan binds an existing job to a plan by setting jobs.plan_id. It returns false with nil error when the job id is unknown.
func (*Store) AttachWorkSession ¶
AttachWorkSession makes sid a current session of the item (idempotent; a past session comes back to current).
func (*Store) AuthGrantsVersion ¶ added in v0.161.0
AuthGrantsVersion 返回 auth_meta.grants_version:授权表的代号,入口层的缓存据此失效(设计 「一致性」)。没有这一行时读到 0(本版本打开的库一定有此行)。
func (*Store) AuthSeedVersion ¶ added in v0.161.0
AuthSeedVersion 返回 auth_meta.seed_version:这个数据库已经为 `users` 种到的最高种入版本, 从未种过时为 0。
func (*Store) BatchPatchTrackerIssues ¶
func (s *Store) BatchPatchTrackerIssues(trackerID string, ids []string, set TrackerBatchSet, now, by string) []TrackerBatchResult
BatchPatchTrackerIssues applies set to each id independently (one transaction per issue), so a missing or failing id never blocks the others. Results come back in request order with duplicates collapsed.
func (*Store) BeginStewardReview ¶
BeginStewardReview records a review run in state running and returns its id.
func (*Store) BeginWorkSummary ¶
func (s *Store) BeginWorkSummary(itemID, sessionID string, activityAt int64, cause string) (int64, error)
BeginWorkSummary records a tidy-up that is starting. activityAt is the session's last-seen time the run covers.
func (*Store) CancelLeaderWake ¶
CancelLeaderWake cancels ONE round by id (the sweep's plan-paused path). It is a conditional UPDATE, so a round that raced into `firing`/`fired` is not touched.
func (*Store) CancelLeaderWakesForPlan ¶
CancelLeaderWakesForPlan cancels every round of a plan that has not started a leader job yet (pending or firing) and reports how many it stopped. A `fired` round is history and is left alone: the leader job it started is already running, and cancelling the row would neither stop it nor explain it. by is the human who spoke. Skips (state cancelled with a reason instead of a person) go through the same write.
func (*Store) CancelRetry ¶
CancelRetry drops a retry an operator no longer wants: pending or claimed rows become cancelled. A row that already reached done/cancelled is terminal and this returns an error (the fixed choice — a rejected transition is reported).
func (*Store) CaptureWorkItem ¶ added in v0.166.0
func (s *Store) CaptureWorkItem(in CaptureInput) (WorkItem, error)
CaptureWorkItem inserts a captured item: status captured, status_source human, the kind and the source session / job. Kind must be idea|issue|request|note.
func (*Store) ClaimAgentSessionOwner ¶
func (s *Store) ClaimAgentSessionOwner(sessionID, callerID string) (AgentSession, bool, error)
ClaimAgentSessionOwner atomically pins an authenticated heartbeat to an ownerless legacy session. Existing owners are never replaced, and an empty caller cannot claim the row. A beat whose caller is NOT the stored owner is refused and noted on the row (RefusedCallerID / RefusedAt) so the web can say what is happening instead of showing a session that silently stopped moving; the owner's own beat clears that note.
func (*Store) ClaimDueDeliveries ¶
ClaimDueDeliveries atomically claims up to limit pending deliveries that are due (status='pending' AND next_retry_at <= now) and returns them for the sweeper to POST.
SR303 single-claim guarantee: the claim is a conditional UPDATE that moves the row's next_retry_at to a future lease time (now+lease) — only the UPDATE that actually affects the row (`... WHERE id=? AND status='pending' AND next_retry_at <= now`) wins it, so two concurrent claims can never hand the SAME delivery out twice. The row STAYS pending (the sweep marks it delivered/retry/failed after the POST); leasing it out of the due window is the dedup barrier. If the process crashes between claim and resolution the lease expires and the delivery becomes due again on a later tick (at-least-once).
All work runs under writeMu (the in-process write lock every writer uses) so the SELECT and the per-row UPDATEs never interleave with another writer. now/ limit/lease are injected so tests can pin the clock, batch size and lease. A non-positive limit yields no rows; a non-positive lease falls back to ClaimLeaseSeconds.
func (*Store) ClaimDueRetries ¶
ClaimDueRetries atomically claims up to limit retry rows that are due at now and returns them for the sweeper to submit, leasing each one for `lease` seconds (see retryDuePredicate for what "due" means).
The claim is a conditional UPDATE per candidate: only an UPDATE that still finds the row due (`... WHERE id = ? AND (<predicate>)`) affects a row and hands it out, so two concurrent claims (or a claim racing a lease lapse) can never submit the SAME row twice. Claiming moves the row to state=claimed with lease_until=now+lease, which takes it out of the due window until the lease lapses — and THAT is what makes a crash between claim and submit recoverable: the work is late by at most one lease, never lost (at-least-once, the mirror of ClaimDueDeliveries).
All work runs under writeMu so the SELECT and the per-row UPDATEs never interleave with another writer. now/limit/lease are injected so tests can pin the clock, batch size and lease; a non-positive limit yields no rows, and a non-positive lease falls back to ClaimLeaseSeconds.
func (*Store) ClaimLeaderWake ¶
ClaimLeaderWake takes a due round for THIS sweep, so two sweeps (or a sweep and a serve restart) can never start two leader jobs for one member terminal. It is a conditional UPDATE — whoever flips pending→firing owns the round.
func (*Store) ClaimLocalSessionsForRecovery ¶
ClaimLocalSessionsForRecovery moves resident local ACP jobs into a durable recovering state before the ordinary orphan sweep can fail running rows. Only rows with session state are candidates; one-shot local jobs keep the existing orphan behavior.
func (*Store) ClaimUnwatchedSourceJobs ¶
ClaimUnwatchedSourceJobs registers only jobs whose source_session_id is the exact registered session and whose authenticated caller, project, canonical runner, and effective cwd still match that session. Caller identity alone is not enough to transfer a Stop watch between two sessions.
func (*Store) ClaimWakeupFire ¶
ClaimWakeupFire takes the wakeup's single continuation slot: it writes continuationJobID (normally WakeupClaimPending — see that constant) and bumps the fire counters, but ONLY when the wakeup is enabled and its slot is free. The boolean reports whether THIS call won the slot; a caller that loses must not submit a continuation (and counts a coalesce instead).
func (*Store) ClearPlanBlocked ¶
ClearPlanBlocked releases a plan from a block: blocked_todo is emptied and a PlanBlocked status returns to PlanOpen. Any OTHER status (done, archived — a human's own choice) is left alone, and a plan that is not blocked is unchanged apart from updated_at. Idempotent: the unblock paths all call it unconditionally.
func (*Store) ClearServerCreatedPulled ¶ added in v0.166.0
ClearServerCreatedPulled clears the server_created flag of every record the client holding cursor has received (changed_seq <= cursor). cursor 0 clears nothing: a first sync pulls with no cursor and never proves a delivery.
func (*Store) ClearSessionJobWatches ¶
ClearSessionJobWatches removes all watches for a session. It is idempotent.
func (*Store) Close ¶
Close closes the underlying database. WAL auto-checkpoints on the final close, so no explicit checkpoint is needed for graceful shutdown (design §14).
func (*Store) CoalesceWakeup ¶
CoalesceWakeup counts one trigger that found the continuation slot occupied and therefore did NOT start a second continuation (design §五 决策 6). last_fired_at moves too: a reader asking "when did this wakeup last want to run" gets the trigger, not only the fires that produced a job.
func (*Store) CommentTriggerStats ¶
CommentTriggerStats reports how many comments in a thread have DISPATCHED a job and when the most recent one was written — the two numbers the @-mention throttle needs (MCP-05 阶段 A: one dispatching comment per scope per interval, and a cumulative cap per scope). A comment that mentioned several agents counts ONCE: the budget counts dispatching comments, and the mention fan-out inside one comment is already bounded by the mention list itself.
func (*Store) CountActiveJobsByCaller ¶
CountActiveJobsByCaller counts the caller's jobs that are still in flight and were submitted at or after `since` (unix seconds; 0 = no lower bound). It is the SUP-01 D supervision signal: the relay refuses to auto-arm a session whose caller is demonstrably watching live work, because an armed Stop would block the hook (and the job's completion notice) until the human came back. An empty callerID counts nothing — there is no one to attribute the work to.
func (*Store) CountAuditTargetsSince ¶
CountAuditTargetsSince counts the distinct targets of one audit kind written at or after since by an actor starting with actorPrefix ("" = anyone).
func (*Store) CountAutoWorkSummaries ¶
CountAutoWorkSummaries counts the runs started since `since` that were not a manual request (the daily cap applies to those).
func (*Store) CountJobsByStatus ¶
CountJobsByStatus returns a status->count map over all jobs.
func (*Store) CountMemorySuggestionsSince ¶
CountMemorySuggestionsSince counts the suggestions created at or after since (the daily cap).
func (*Store) CountPausedForUpdate ¶ added in v0.156.0
CountPausedForUpdate reports how many jobs an update currently holds parked.
func (*Store) CountPlans ¶
func (s *Store) CountPlans(f PlanFilter) (int, error)
CountPlans counts every plan matching f — the same conditions as ListPlans, without paging. It is the `total` a paging UI needs ("showing 1–20 of 57").
func (*Store) CountRecoveringJobs ¶
CountRecoveringJobs returns how many jobs are currently held in `recovering`. It is the RECOV-01 R4 check behind serve's one-shot startup window: once every held row has been ADOPTED (back to `running`) there is nothing left for the window to end, so the timer is cancelled instead of failing adopted work.
func (*Store) CountUpgradeRestartBlockers ¶ added in v0.156.0
CountUpgradeRestartBlockers counts the durable job rows that still carry work this server owns (see upgradeBlockerWhere). The caller may exclude ids it has separately verified (the idle ACP sessions that survive a restart, the upgrade's own source job).
func (*Store) CreateAuthGrant ¶ added in v0.162.0
CreateAuthGrant 写一条数据库授权(设计「接口」:新增)。存储层在这里收口三件事:
- 展开:模式按主体种类经 authz.Expand 展开(任何模式匹配不到 auth.manage、通配符不命中危险级、 会话主体只展开到可授予会话的项),**展开快照**与行一起写入 —— 设计 §2 要求「保存时模式必须至少 匹配一项」,所以展开不出任何权限时直接报错(authz.ErrNoMatch),入口层据此回 400;
- 代号:授权表代号与这一行在同一个事务里递增,入口层的缓存据此失效(设计「一致性」);
- id 与时间:id 为空时生成,granted_at 用存储自己的时钟。
scope 留空时写 `*`(第一期只允许 `*`,设计决策 10)。传入行的撤销 / 孤儿 / 使用计数各列不参与写入: 新行一定是生效、非孤儿、未使用。
func (*Store) CreateServerTrackerIssue ¶ added in v0.166.0
func (s *Store) CreateServerTrackerIssue(trackerID string, in tracker.Issue, by string) (TrackerRecord, error)
CreateServerTrackerIssue allocates an id (tracker.GenerateIssueID over the mirror's issues and the repository prefix), stores the issue as a new rev-1 record flagged server_created and returns it. Deps and parent are cleared: a server-created issue has none. Lookup, allocation and insert share one transaction.
func (*Store) CreateSessionNudge ¶
func (s *Store) CreateSessionNudge(n SessionNudge) (SessionNudge, error)
CreateSessionNudge validates and inserts an active nudge. kind, interval_sec and text are required; an "every" nudge's first run is now+interval.
func (*Store) CreateWorkItem ¶
func (s *Store) CreateWorkItem(in WorkItemInput) (WorkItem, error)
CreateWorkItem inserts a work item (rev 1) with its creation journal line and attaches the given sessions. An empty title is rejected.
func (*Store) CreateWorkRequest ¶
func (s *Store) CreateWorkRequest(in WorkRequestInput) (WorkRequest, error)
CreateWorkRequest records a new pending request.
func (*Store) CurrentWorkSessionIDs ¶
CurrentWorkSessionIDs maps work item id -> its current session ids, for the items in ids (every item when ids is empty).
func (*Store) DBStats ¶
DBStats reports the metadata db's file/page picture plus a COUNT(*) per reported table. budget caps the TOTAL row-count pass (the counts are per-table SELECTs, each fast, but a big or cold db must never stall the dashboard); when it is exhausted the remaining tables are skipped and Partial is set. The file and page queries always run — they are single pragmas/stat calls.
func (*Store) DecideHold ¶ added in v0.137.0
func (s *Store) DecideHold(d HoldDecision) (bool, error)
DecideHold applies d as a conditional UPDATE and reports whether this call won the transition (false: the row is gone or no longer in From — somebody else decided).
func (*Store) DecideMemoryCandidate ¶
func (s *Store) DecideMemoryCandidate(id int64, from, to, memoryKey, by string) (MemoryCandidate, error)
DecideMemoryCandidate moves a candidate from one state to another, recording the memory key (accepted) and who decided. It is a compare-and-set on the current state: a candidate not in `from` returns ErrMemoryCandidateDecided, so two concurrent decisions cannot both win. from = accepted / to = pending is the undo of a claim whose memory write failed.
func (*Store) DecideMemorySuggestion ¶
func (s *Store) DecideMemorySuggestion(id int64, state, by, note string) (MemorySuggestion, error)
DecideMemorySuggestion moves a pending suggestion to state (adopted / dismissed / stale). A suggestion that is no longer pending returns ErrMemorySuggestionDecided.
func (*Store) DeleteAgentSession ¶
DeleteAgentSession removes a session registration (its relay decisions stay for audit). ok is false when the session is unknown.
func (*Store) DeleteCommentsForScope ¶
DeleteCommentsForScope removes one object's whole thread and reports how many rows went. It is the cascade a job/plan/todo delete runs (PruneJobs and DeleteTodo call it); plans are never deleted in this product, so a plan thread lives as long as its plan.
func (*Store) DeleteDecisionAdvice ¶
DeleteDecisionAdvice removes the advice of the given cards (missing keys are ignored).
func (*Store) DeleteJob ¶
DeleteJob permanently removes one terminal job and its job-owned records. The job_events row inserted after the cleanup is the durable deletion audit; it contains no original title, command or prompt.
func (*Store) DeletePushSubscription ¶
DeletePushSubscription removes endpoint only when it belongs to caller. The boolean lets HTTP return 404 without exposing another caller's ownership.
func (*Store) DeletePushSubscriptionEndpoint ¶
DeletePushSubscriptionEndpoint removes an endpoint after its push service returns 404/410. It is intentionally not caller-scoped: the endpoint itself is the globally unique sender identity.
func (*Store) DeleteRule ¶
DeleteRule removes one index row. It reports no error for a name that is not indexed: the caller (rule.Store.Remove) already checked, and a concurrent delete is not a failure the operator needs to see.
func (*Store) DeleteSchedule ¶
func (*Store) DeleteScopedMemory ¶
func (*Store) DeleteSessionNudge ¶
DeleteSessionNudge removes a nudge row (false when unknown).
func (*Store) DeleteSkill ¶
DeleteSkill removes one skill row. A missing name is an error for the same reason UpdateSkill's is: the caller has already decided to delete this skill and drops its directory next, so a row that is not there means the index drifted.
func (*Store) DeleteTodaySnoozes ¶
DeleteTodaySnoozes removes rows by card key and returns how many went.
func (*Store) DeleteTodo ¶
DeleteTodo removes a todo. P3 keeps this store-only CRUD; no HTTP/MCP/CLI delete surface is exposed. The todo's comment thread (MCP-05) goes with it, so no thread is left pointing at a checklist item that no longer exists.
func (*Store) DeleteTracker ¶ added in v0.139.0
func (s *Store) DeleteTracker(trackerID string) (TrackerDeleteResult, error)
DeleteTracker removes one mirrored repository from the server: its repo row, every issue and memory row (tombstones included) and its memory suggestions, in one transaction. The local .gofer/tracker of that repository is untouched; a later `gofer repo sync` from it re-creates the mirror.
func (*Store) DeleteTunnelPreset ¶
DeleteTunnelPreset removes a preset, reporting a name that was never stored.
func (*Store) DeleteWakeup ¶
DeleteWakeup removes a wakeup row (the `job wakeup rm` path).
func (*Store) DeleteWorkItem ¶
DeleteWorkItem permanently removes one FINISHED (done / dropped) work item and every row that hangs off it, in a single transaction: attached sessions, links, the journal, field sources, the request ledger, suggestions, the summarizer run log, pending merge suggestions that name it, and the steward events noted about it.
Only a finished item may go: deleting something still open would silently throw away a live thread of work, and "dropped" is already the soft-delete step.
merged_into: other items that were merged INTO this one keep existing (they are finished records of their own); their merged_into pointer is cleared so it does not dangle. Refusing instead would make a merge target undeletable until every source is gone, and a cleanup of "all dropped" would then need an ordering. The journal lines that were moved to this item at merge time are deleted with it.
The audit row (audit_events, kind work.deleted) records the id and the actor only, the same shape as job.deleted: no title, goal or any other content survives.
func (*Store) DeleteWorkSuggestion ¶
DeleteWorkSuggestion removes a suggestion row outright (adopted, or superseded by a direct write).
func (*Store) DeleteXfer ¶
DeleteXfer removes a transfer row (the `xfer rm` path; the staging directory is removed by the caller).
func (*Store) DetachWorkSession ¶
DetachWorkSession moves a session to `past` (it stays in the history).
func (*Store) DismissWorkSuggestion ¶
DismissWorkSuggestion marks a pending suggestion dismissed (kept so the same idea is not proposed again).
func (*Store) DoneJobsByDay ¶
DoneJobsByDay counts done jobs per LOCAL day (tzSec = the viewer's UTC offset in seconds) for jobs that ended at or after from. Keys are YYYY-MM-DD.
func (*Store) DueLeaderWakes ¶
func (s *Store) DueLeaderWakes(now int64) ([]LeaderWake, error)
DueLeaderWakes returns the armed rounds that have come due at now. Only `pending` rows are returned: a `firing` one belongs to a sweep that is mid-submit, and a `fired`/`cancelled` one is history.
func (*Store) DueSchedules ¶
func (s *Store) DueSchedules(now int64) ([]ScheduleRecord, error)
func (*Store) DueWakeups ¶
func (s *Store) DueWakeups(now int64) ([]WakeupRecord, error)
DueWakeups returns the ENABLED wakeups the sweeper must act on at now: either a timer that has come due (next_run_at <= now) or one whose TTL has passed (expires_at <= now — the sweeper disables those and records the expiry). One query serves both passes, so a stop-the-world tick cannot miss an expiry behind a due timer.
func (*Store) EndSessionNudge ¶
EndSessionNudge ends an active or paused nudge for a reason (idempotent: false when it was already ended or unknown).
func (*Store) EnsureDraftWorkItemForSession ¶
func (s *Store) EnsureDraftWorkItemForSession(a AgentSession, prompt string) (WorkItem, bool, error)
EnsureDraftWorkItemForSession creates the auto draft for a session's first human prompt (design §4: "新会话第一次有人工提问时,自动生成一张草稿工作项"). It does nothing (created=false) when the session already belongs to any work item — even a past or merged one — so a prompt never spawns duplicates and a merge/split decision is never undone. The check and the insert are one transaction under the writer lock.
func (*Store) ExpireCastRecordings ¶
ExpireCastRecordings clears the recording of every closed pty session whose cast TTL has elapsed (retention regime 1, design §D-P3-6). It runs in one transaction: SELECT the expired recording_uris (so the caller can best-effort delete the cast files on disk), then UPDATE those rows to drop recording_uri and mark encrypted=2 — the session ROW is retained (owner/state/bytes/timestamps stay for audit), only the recording pointer is cleared. now / ttlSeconds are injected; a session is expired when ended_at is set (>0) and ended_at + ttlSeconds < now and it still has a recording_uri. A non-positive ttlSeconds prunes nothing. Signature matches the store-does-not-hold-config contract: the caller passes the TTL.
func (*Store) ExpireDueDecisions ¶
ExpireDueDecisions is the exported sweep of the lazy expiry: the serve loop calls it on a timer so a decision that ran past its deadline moves to EXPIRED (and notifies the browser's pending topic) even when nobody happens to read it.
func (*Store) ExpireSessionDecisions ¶
ExpireSessionDecisions moves every OPEN decision of a session to EXPIRED (relay switched off while a turn was waiting: the hook must stop waiting and let the agent stop normally). It returns the number of rows expired.
🔒 Takes writeMu itself; callers must not hold it.
func (*Store) ExpiredXfers ¶
func (s *Store) ExpiredXfers(now int64) ([]XferRecord, error)
ExpiredXfers returns the transfers whose TTL has passed (expires_at <= now). Rows already marked expired are excluded so the sweep never re-processes them.
func (*Store) ExtendJobTokenExpiry ¶
ExtendJobTokenExpiry keeps a resident job's existing credential usable for another turn without rotating the secret held by its live agent process.
func (*Store) FailRecoveringJob ¶
FailRecoveringJob fails ONE store-held recovering job: the worker process reconnected but did not prove it still runs this job (absent from its inflight report, or the row belongs to a different process instance), so RECOV-01 R4 ends it right away instead of leaving it held for a window that can no longer adopt it. The `status = 'recovering'` guard makes it a no-op for a row that has meanwhile become terminal (or was adopted). reason goes in the error column; ts stamps ended_at/updated_at. Returns rows affected (0 or 1).
func (*Store) FailRecoveringJobs ¶
FailRecoveringJobs fails every job still held in `recovering`: its reconnect window elapsed (or no window was armed at all) without the worker coming back, so the job can never reach a real terminal state. Called by serve when the RECOV-01 window armed by ReconcileOrphanJobs expires. ts stamps ended_at/updated_at; reason (which should name the cause, e.g. "worker lost") goes in the error column so CLI/web show WHY the job ended. Returns rows failed.
func (*Store) FailStaleStewardReviews ¶
FailStaleStewardReviews closes reviews left running by a restart (started before cutoff).
func (*Store) FailStaleWorkSummaries ¶
FailStaleWorkSummaries settles runs left `running` before cutoff (the process died under them).
func (*Store) FindChildWorkflow ¶
FindChildWorkflow returns the sub-workflow a parent step started, located by (parent_workflow_id, parent_step_index) (P3, D19). The bool is false (nil error) when no such child exists yet (the parent step has not started its sub-workflow, or the sub-workflow submit is still in flight). It is the parent advance's lookup for "is this workflow-type step terminal" = "is its child workflow terminal".
Pairs with the deterministic child-workflow id (the submit path derives a stable id from parent+step), but this query is the authoritative locator: it tolerates a child created with a different id scheme and never relies on the parent knowing the exact id. Newest first (a re-submit would only ever be an idempotent no-op via the deterministic id, so at most one row exists in practice).
func (*Store) FindTrackerIssues ¶
func (s *Store) FindTrackerIssues(issueID string) ([]TrackerRecord, error)
FindTrackerIssues returns the mirror rows of one issue id across every tracker repo (ids are only unique inside a repo, so the same id may exist twice). It is a read helper for the work service's completion write-back.
func (*Store) FinishStewardReview ¶
FinishStewardReview closes a review run. An empty summary keeps what the steward already wrote through SetStewardReviewSummary.
func (*Store) FinishWorkSummary ¶
FinishWorkSummary settles a run.
func (*Store) FinishWorkflowStep ¶
func (s *Store) FinishWorkflowStep(id string, fromStep, fromAtt, toStep int, status, errMsg string, evs ...WorkflowEvent) (bool, error)
FinishWorkflowStep is the terminal counterpart of AdvanceStep: it claims the (fromStep, fromAtt) generation of a RUNNING workflow and, in the same transaction, records the terminal event and flips the workflow to status (done/failed). The bool reports whether this caller won the claim.
Doing the claim and the terminal flip in one step closes a window the two-write sequence (AdvanceStep to cur+1, then SetWorkflowStatus) left open: between those writes the workflow read as running at a step with no jobs yet, so a concurrent Advance started that next step (after a fail-fast), or saw the pointer past the last step and failed an otherwise successful workflow. Writing the event inside the transaction also keeps the terminal event visible no later than the status.
func (*Store) FirstJobAt ¶
FirstJobAt is the start time of the oldest job (0 = no job yet).
func (*Store) FlagScopedMemory ¶
func (s *Store) FlagScopedMemory(scope, scopeKey, key string, flag *tracker.MemoryFlag) (ScopedMemory, error)
FlagScopedMemory adds flag to a live scoped memory, or clears every flag when flag is nil (the human review). Only meta_json changes: updated_at / updated_by stay, a flag is a report about the content, not a write of it.
func (*Store) GetAgentSession ¶
func (s *Store) GetAgentSession(sid string) (AgentSession, bool, error)
GetAgentSession returns one session; ok is false with nil error when absent.
func (*Store) GetAuthGrant ¶ added in v0.162.0
GetAuthGrant 读一条授权行;不存在时 ok 为 false、err 为 nil。
func (*Store) GetComment ¶
GetComment returns a comment by id. ok is false with nil error when absent.
func (*Store) GetDecision ¶
func (s *Store) GetDecision(id string) (PlanDecision, bool, error)
GetDecision returns a decision by id. ok is false with nil error when absent. Lazy expiry runs first (plan D2) so a past-deadline row reads back EXPIRED.
🔒 Lock discipline (plan HIGH-1, SetTodoDone precedent): expireDueDecisions takes writeMu itself; callers here must NOT hold writeMu when calling it (sync.Mutex is not re-entrant) and take their own lock afterwards if needed.
func (*Store) GetDecisionAdvice ¶
func (s *Store) GetDecisionAdvice(cardKey string) (DecisionAdvice, bool, error)
GetDecisionAdvice reads one card's advice; ok is false when there is none.
func (*Store) GetEvent ¶
GetEvent returns the single event with the given seq. The boolean is false when no such event exists (e.g. a pruned job's event). It is used by the E14 delivery sweeper to rebuild a webhook body (type/detail/at) for a queued delivery that only stores the event_seq.
func (*Store) GetJob ¶
GetJob returns the job by id. The bool is false (with a nil error) when no such job exists, distinguishing "not found" from a real query error.
func (*Store) GetJobByRequestID ¶
GetJobByRequestID returns the job carrying the given (non-empty) request_id, the idempotency lookup for C5. An empty reqID is treated as "no key" and returns (zero, false, nil) without touching the DB (matching the partial unique index, which does not constrain empty request_id). The bool is false (nil error) when no such job exists.
func (*Store) GetJobMetrics ¶
func (s *Store) GetJobMetrics(jobID string) (JobMetrics, bool, error)
GetJobMetrics reads a job's metrics row; ok=false when none was written.
func (*Store) GetJobToken ¶
func (s *Store) GetJobToken(jobID string) (JobTokenRecord, bool, error)
GetJobToken returns the credential row of a job ("" id, false when the job has none). It answers "does this job hold a credential, and is it still live" for the job detail/audit surface.
func (*Store) GetJobTokenByHash ¶
func (s *Store) GetJobTokenByHash(hash string) (JobTokenRecord, bool, error)
GetJobTokenByHash resolves a presented credential by its sha256. It returns ok=false when no row matches (an unknown token) and leaves the LIVE/expired/ revoked decision to the caller, which needs to distinguish "not a credential at all" from "a credential that no longer works" (bd-free: both are a 401, but the caller logs them differently).
func (*Store) GetJobsByIDs ¶
GetJobsByIDs reads several jobs in one query, keyed by id (unknown ids are absent).
func (*Store) GetLeaderWake ¶
func (s *Store) GetLeaderWake(id string) (LeaderWake, bool, error)
GetLeaderWake reads one row; ok=false (nil error) when the id is unknown.
func (*Store) GetMemoryCandidate ¶
func (s *Store) GetMemoryCandidate(id int64) (MemoryCandidate, error)
GetMemoryCandidate reads one candidate.
func (*Store) GetMemorySuggestion ¶
func (s *Store) GetMemorySuggestion(id int64) (MemorySuggestion, error)
GetMemorySuggestion reads one suggestion.
func (*Store) GetOrCreateWorkbenchSeenBaseline ¶
GetOrCreateWorkbenchSeenBaseline returns the caller-wide seen watermark. The reserved prefs row keeps this state caller-local without adding a second table; it is filtered from ListWorkbenchThreadPrefs and cannot be written as a thread.
func (*Store) GetPlanHandoff ¶
GetPlanHandoff returns the latest version when version <= 0, or one requested historical version. Missing versions return ok=false without an error.
func (*Store) GetPtySessionByJob ¶
func (s *Store) GetPtySessionByJob(jobID string) (PtySessionRecord, bool, error)
GetPtySessionByJob returns the most recent pty session for a job (the recording download gate looks it up by job id). "Most recent" is the latest started_at, then pty_session_id desc as a stable tiebreaker. The bool is false (nil error) when the job has no pty session.
func (*Store) GetRetry ¶ added in v0.161.0
func (s *Store) GetRetry(id string) (RetryRecord, bool, error)
GetRetry returns one retry row by id, ok=false when there is no such row. The entry layer reads it to apply the retry's permission rule to the job the retry continues (plan T1.5a: DELETE /v1/retries/{rid} is `InHandler(job.cancel.others, deny)` on the SOURCE job, which only the row knows).
func (*Store) GetRule ¶
GetRule reads one rule's index row. ok=false (nil error) means the library has no such rule.
func (*Store) GetSchedule ¶
func (s *Store) GetSchedule(id string) (ScheduleRecord, bool, error)
func (*Store) GetScopedMemory ¶
func (s *Store) GetScopedMemory(scope, scopeKey, key string) (ScopedMemory, error)
func (*Store) GetSessionByHandedOffJob ¶
func (s *Store) GetSessionByHandedOffJob(jobID string) (AgentSession, bool, error)
GetSessionByHandedOffJob finds the session path B's takeover job HOLDS (SUP-02 R1): the job continues that CLI conversation, so a job id names at most one session and only while it is actually handed off. A job that is not a takeover (or one whose session a human already released) answers ok=false — the caller then does nothing, which is the common case for every other finished job.
func (*Store) GetSessionNudge ¶
func (s *Store) GetSessionNudge(id string) (SessionNudge, bool, error)
GetSessionNudge reads one nudge.
func (*Store) GetSkill ¶
GetSkill returns one skill by name. The bool is false (with a nil error) when the library has no such skill, distinguishing "not imported" from a real query error.
func (*Store) GetTodaySnooze ¶
func (s *Store) GetTodaySnooze(cardKey string) (TodaySnooze, bool, error)
GetTodaySnooze reads one row; ok is false when the card is not snoozed.
func (*Store) GetTrackerMemory ¶
func (s *Store) GetTrackerMemory(trackerID, key string) (TrackerRecord, bool, error)
GetTrackerMemory reads one mirrored memory (tombstones included); ok is false when the key was never mirrored.
func (*Store) GetTunnelPreset ¶
func (s *Store) GetTunnelPreset(name string) (TunnelPresetRecord, bool, error)
GetTunnelPreset reads one preset; ok=false means the name is not stored.
func (*Store) GetWakeup ¶
func (s *Store) GetWakeup(id string) (WakeupRecord, bool, error)
GetWakeup returns one wakeup row; ok=false when the id is unknown.
func (*Store) GetWorkItem ¶
GetWorkItem reads one work item.
func (*Store) GetWorkKV ¶
WorkKV is a tiny key/value store for work bookkeeping (digest de-duplication).
func (*Store) GetWorkMergeSuggestion ¶
func (s *Store) GetWorkMergeSuggestion(id int64) (WorkMergeSuggestion, error)
GetWorkMergeSuggestion reads one suggestion.
func (*Store) GetWorkRequest ¶
func (s *Store) GetWorkRequest(id string) (WorkRequest, bool, error)
GetWorkRequest reads one request.
func (*Store) GetWorkSuggestion ¶
func (s *Store) GetWorkSuggestion(id, field string) (WorkSuggestion, bool, error)
GetWorkSuggestion reads one pending suggestion.
func (*Store) GetWorkbenchLayout ¶
func (s *Store) GetWorkbenchLayout(callerID string) (layout WorkbenchLayout, ok bool, err error)
GetWorkbenchLayout returns the saved layout for caller. ok=false means the caller has never saved one; callers project that as version 0 with body {}.
func (*Store) GetWorkbenchSeenBaseline ¶
GetWorkbenchSeenBaseline reads the caller-wide F16 watermark without creating it. Event-side notification projection must not make a caller's first page view appear to have happened.
func (*Store) GetWorkbenchThreadPref ¶
func (s *Store) GetWorkbenchThreadPref(callerID, threadID string) (WorkbenchThreadPref, bool, error)
GetWorkbenchThreadPref reads one caller/thread preference without creating it.
func (*Store) GetWorkflow ¶
GetWorkflow returns the workflow by id. The bool is false (nil error) when no such workflow exists, distinguishing "not found" from a real query error.
func (*Store) GetXfer ¶
func (s *Store) GetXfer(id string) (XferRecord, bool, error)
GetXfer returns one transfer row; ok=false when the id is unknown.
func (*Store) IncrSessionTurn ¶
IncrSessionTurn increments turn_no and returns the new value. ok is false when the session is unknown.
func (*Store) InsertAuthAudit ¶ added in v0.162.0
func (s *Store) InsertAuthAudit(e AuthAuditEntry) error
InsertAuthAudit 追加一条审计记录。存储层不判断该不该记,只保证行与字段落地。
func (*Store) InsertComment ¶
InsertComment persists one comment. It is the single收口 point for the invariants every entry face relies on: the ID is caller-supplied (the `cm-<8hex>` grammar belongs to the caller, like every other id in this package), the scope must be one of the three commentable kinds, the author must be non-empty and the author kind must be one of the three (an unknown kind would silently disable the dispatch gate).
func (*Store) InsertDecision ¶
func (s *Store) InsertDecision(d *PlanDecision) error
InsertDecision persists a new decision. It is the single收口 point for the invariants every entry face relies on (plan HIGH-2 + 二审补丁③④):
- an empty ID is generated here ("dec-<ts>-<rand>") because the MCP standalone deployment reaches the store directly, bypassing httpapi;
- TimeoutSec is clamped to [2, 86400]; <= 0 falls back to the 1800s default;
- an empty OptionsJSON array "[]" is normalised to NULL (= free-text) so a zero-option choice card (dead UI) can never be projected;
- AskedAt 0 is stamped with now (seconds); State "" defaults to OPEN.
func (*Store) InsertDelivery ¶
InsertDelivery enqueues one pending webhook delivery (E14). It stamps created_at/updated_at to d.CreatedAt (the caller passes the current time so the store stays clock-free / testable) and returns the assigned row id. Status and NextRetryAt are taken from d as given (the enqueue path passes pending + next_retry_at=now so the row is immediately due). Writes go through s.writeMu (like every other writer) so SQLite never sees two concurrent writers.
func (*Store) InsertJobEvent ¶
InsertJobEvent appends one lifecycle event row (append-only — INSERT only, never update/upsert: the stream is the immutable history). It returns the assigned seq (lastInsertId), which P2 (notify dispatch) uses as the queue cursor. Writes go through s.writeMu (like UpsertJob/UpsertInteraction) so SQLite never sees two concurrent writers and cannot return SQLITE_BUSY.
func (*Store) InsertLeaderWake ¶
func (s *Store) InsertLeaderWake(w LeaderWake) error
InsertLeaderWake arms one pending round. It refuses a half-built row (no id / plan / member job) — a row nobody can fire or cancel is worse than no row at all.
func (*Store) InsertPlan ¶
InsertPlan persists a new plan header. The caller must generate a non-empty id; jobstore stays job-import-free.
func (*Store) InsertRetry ¶
func (s *Store) InsertRetry(r RetryRecord) error
InsertRetry records one pending retry. It refuses a half-built row (no id, no source job, no request to re-submit, attempt < 1) and defaults the state to pending, so a row never reads back as "unset". CreatedAt is taken as given (the callers pass the clock, keeping this store testable/clock-free).
func (*Store) InsertSchedule ¶
func (s *Store) InsertSchedule(r ScheduleRecord) error
func (*Store) InsertSkill ¶
InsertSkill persists a NEW skill row. A duplicate name is an error, not an upsert: the skill store replaces an existing skill through UpdateSkill once its tree has been swapped in, so a silent insert-over would hide a caller bug.
func (*Store) InsertTodo ¶
InsertTodo persists a new todo. The caller must generate a non-empty todo id. A blank JobID is stored as NULL and scans back as "" via COALESCE.
func (*Store) InsertWakeup ¶
func (s *Store) InsertWakeup(r WakeupRecord) error
InsertWakeup records a new wakeup. It refuses a half-built row (no id / target job / kind) and defaults the mode to once so a row never reads back as "unset".
func (*Store) InsertWorkflow ¶
InsertWorkflow persists a new workflow header row. created_at/updated_at are taken from w as given (caller passes the current time so the store stays clock-free / testable). Writes go through s.writeMu like every other writer so SQLite never sees two concurrent writers.
func (*Store) InsertWorkflowEvent ¶
func (s *Store) InsertWorkflowEvent(e WorkflowEvent) (int64, error)
InsertWorkflowEvent appends one workflow lifecycle event row (append-only — INSERT only, never update/upsert: the stream is the immutable history). It returns the assigned seq (lastInsertId). Writes go through s.writeMu (like every other writer) so SQLite never sees two concurrent writers and cannot return SQLITE_BUSY.
func (*Store) InsertXfer ¶
func (s *Store) InsertXfer(r XferRecord) error
InsertXfer records a new transfer row. It fails when the id or an essential field is empty, so a half-built row can never be stored.
func (*Store) IsStewardJob ¶
IsStewardJob reports whether jobID was started as the steward.
func (*Store) JobMetricsEvidence ¶
func (s *Store) JobMetricsEvidence(jobID string) (MetricsEvidence, error)
JobMetricsEvidence reads the job's metric-relevant events and interactions and folds them (two indexed per-job queries).
func (*Store) JobOutcomesSince ¶
func (s *Store) JobOutcomesSince(since int64) (JobOutcomeCounts, error)
JobOutcomesSince counts the jobs that ended at or after since.
func (*Store) JobTitles ¶
JobTitles returns each job's display title: request title, else the first line of its prompt (the caller truncates). Unknown ids are absent.
func (*Store) LastStewardReview ¶
func (s *Store) LastStewardReview() (StewardReview, bool, error)
LastStewardReview returns the newest review that actually ran (not skipped).
func (*Store) LastWorkSummary ¶
func (s *Store) LastWorkSummary(sessionID string) (WorkSummaryRun, bool, error)
LastWorkSummary returns the most recent run for a session.
func (*Store) LatestAuditEvent ¶
func (s *Store) LatestAuditEvent(kind, targetID string) (AuditEventDetail, bool, error)
LatestAuditEvent returns the newest row of one kind for one target; ok is false when there is none.
func (*Store) LatestLeaderJob ¶
LatestLeaderJob returns the id of the leader job a plan's most recent fired round started ("" when there is none) — the link the plan view shows.
func (*Store) LatestWorkJournalAt ¶
LatestWorkJournalAt is the time of an item's newest journal line (0 = none).
func (*Store) LeaderRoundsSpent ¶
LeaderRoundsSpent reports how many leader rounds a plan has already used: the rows that started a leader job (fired) plus the one a sweep is submitting right now (firing). Cancelled and still-pending rows are NOT rounds — nothing ran for them.
func (*Store) LeaderWakeArmedForMember ¶
LeaderWakeArmedForMember reports whether a member job already has a live (not cancelled) round. The terminal path consults it so a job that reaches finish twice — a re-run, or the accept/reject path after a park — arms ONE round, not two.
func (*Store) ListActiveAuthGrants ¶ added in v0.161.0
ListActiveAuthGrants 返回某一个主体里未被撤销、也不是孤儿的授权 —— 计算有效权限时只该看这些行 (设计 §2:孤儿授权「标为孤儿并停用」)。到期与否由调用方按自己的时钟判定,会话主体的 owner 与 化身比对同样在调用方(设计 §4)。
func (*Store) ListActiveAuthGrantsAll ¶ added in v0.162.0
ListActiveAuthGrantsAll 返回全部**生效**的授权:未被撤销、不是孤儿,主体不限。这是入口层的授权缓存 每 5 秒重读的那条查询(设计「一致性」):一次读完 users 与每个 caller:<id> 的授权,再按主体分组, 而不是按主体逐个查询。到期与否仍由调用方按自己的时钟判定。
func (*Store) ListActiveNudges ¶
func (s *Store) ListActiveNudges() ([]SessionNudge, error)
ListActiveNudges is the sweeper's read: every active nudge of every session.
func (*Store) ListAgentSessions ¶
func (s *Store) ListAgentSessions(opts ListSessionsOpts) ([]AgentSession, error)
ListAgentSessions lists sessions, waiting_reply / needs_attention first, then most recently seen first.
func (*Store) ListAuditEvents ¶
func (s *Store) ListAuditEvents(kind, targetID string) ([]AuditEvent, error)
ListAuditEvents returns the audit rows of one kind (and, when targetID is set, one target), oldest first.
func (*Store) ListAuditEventsSince ¶
func (s *Store) ListAuditEventsSince(kind string, since int64, limit int) ([]AuditEventDetail, error)
ListAuditEventsSince returns the rows of one kind at or after since, newest first, capped at limit (<= 0 means 500).
func (*Store) ListAuthAudit ¶ added in v0.162.0
func (s *Store) ListAuthAudit(f AuthAuditFilter) ([]AuthAuditEntry, error)
ListAuthAudit 读审计记录,最新的在前(同一秒内按写入顺序倒序)。
func (*Store) ListAuthGrants ¶ added in v0.161.0
ListAuthGrants 返回全部授权行,撤销的与孤儿的都在内(审计视图要它们),按授权时间从早到晚。
func (*Store) ListComments ¶
ListComments returns one thread (scope + scope_id) in created_at order, id as the tiebreaker so two comments written in the same second keep a stable order.
func (*Store) ListDecisionAdvice ¶
func (s *Store) ListDecisionAdvice() ([]DecisionAdvice, error)
ListDecisionAdvice returns every advice row, oldest first.
func (*Store) ListDecisions ¶
func (s *Store) ListDecisions(state, planID string) ([]*PlanDecision, error)
ListDecisions returns decisions, optionally filtered by state ("" = all) and/or plan id ("" = all plans), oldest-asked first. Lazy expiry runs first (plan D2) so the bell never shows an "eternally OPEN" ghost card.
func (*Store) ListDeliveriesByJob ¶
ListDeliveriesByJob returns a job's webhook deliveries in id order (creation order) for the read-only deliveries view (P2-d). A job with no deliveries yields an empty slice and no error.
func (*Store) ListDueHolds ¶ added in v0.137.0
ListDueHolds returns the awaiting_approval jobs whose hold expired at or before now, oldest deadline first, at most limit rows (<= 0 means DefaultListLimit). It is the read behind the expiry sweep, served by the partial idx_jobs_hold_due index.
func (*Store) ListDueWorkItems ¶
ListDueWorkItems returns the items whose reminder or park deadline has passed at now and that have not been announced for that deadline yet.
func (*Store) ListFinalWorkItemIDs ¶
ListFinalWorkItemIDs returns the ids of every item in the given final status (done | dropped), merged sources included — the set a "delete all dropped" sweep removes.
func (*Store) ListInteractions ¶
func (s *Store) ListInteractions(jobID string) ([]InteractionRecord, error)
ListInteractions returns the interactions for a job in creation order (created_at asc, id asc as a stable tiebreaker). A job with no interactions yields an empty slice and no error.
func (*Store) ListJobEvents ¶
ListJobEvents returns a job's events in insertion order (seq ASC). When sinceSeq > 0 only events strictly after it are returned (the incremental cursor for SSE/poll). A job with no events yields an empty slice and no error.
func (*Store) ListJobEventsDesc ¶
ListJobEventsDesc returns a scope's events NEWEST first (seq DESC), capped at limit. When before > 0 only events strictly OLDER (a smaller seq) are returned — the cursor a paging UI walks backwards with. It is the plan event area's reader (LEAD-02): the job timeline pages FORWARD from a `since` cursor and must stay untouched, so the two directions get two queries rather than a flag that can be passed wrong.
func (*Store) ListJobs ¶
ListJobs returns job records matching q, newest first (started_at desc, id desc as a stable tiebreaker), with DB-side filtering, ordering and pagination.
func (*Store) ListJobsByTodo ¶
ListJobsByTodo returns the jobs attached to one plan todo (jobs.todo_id), newest first, capped at limit (<= 0 means DefaultListLimit). It is what `plan show` / GET /v1/plans/{id} list under a todo: a todo can be carried by several runs (retries, re-runs, continuations), and the most recent one is the interesting one.
func (*Store) ListJobsForMetrics ¶
func (s *Store) ListJobsForMetrics(since, afterEnded int64, afterID string, limit int, onlyStale bool) ([]JobRecord, error)
ListJobsForMetrics pages through ended jobs (ended_at >= since) in (ended_at, id) order after the cursor — the backfill's walk. onlyStale skips jobs whose metrics row already exists at the current JobMetricsVersion, which is what makes a re-run a no-op.
func (*Store) ListLeaderWakesForPlan ¶
func (s *Store) ListLeaderWakesForPlan(planID string) ([]LeaderWake, error)
ListLeaderWakesForPlan returns a plan's rounds oldest-first (the order they were armed in, which is how the plan reads them and how the tests count them).
func (*Store) ListMemoryCandidates ¶
func (s *Store) ListMemoryCandidates(f MemoryCandidateFilter) ([]MemoryCandidate, error)
ListMemoryCandidates lists candidates, oldest first.
func (*Store) ListMemorySuggestions ¶
func (s *Store) ListMemorySuggestions(state string) ([]MemorySuggestion, error)
ListMemorySuggestions lists the suggestions in one state ("" = every state), oldest first.
func (*Store) ListOpenSessionPermissions ¶
func (s *Store) ListOpenSessionPermissions(sessionID string, limit int) ([]*PlanDecision, error)
ListOpenSessionPermissions returns the session's OPEN permission decisions, newest first.
func (*Store) ListOpenSessionTurns ¶
func (s *Store) ListOpenSessionTurns(sessionID string, limit int) ([]*PlanDecision, error)
ListOpenSessionTurns returns the session's OPEN decisions that are relay turns (every kind except DecisionKindPermission), newest first. It is what "answer the session's open turn" must look at: a pending permission prompt is answered through its own endpoint, never by free text typed into the reply box.
func (*Store) ListOrphanSessionCandidates ¶
func (s *Store) ListOrphanSessionCandidates(workerRunners []string) ([]OrphanSessionCandidate, error)
ListOrphanSessionCandidates returns the jobs a reconcile is about to fail whose session_id is still empty — the rows worth re-scanning for a session id BEFORE they are marked failed (F11). A serve restart kills finish(), so the terminal capture never ran: an omp job whose id only ever lived in the in-process entry used to end `failed` with an empty session_id, and `job resume` refused it.
The predicate mirrors the FAILING half of ReconcileOrphanJobs exactly — the non-terminal rows minus the worker rows step 1 holds in `recovering` — so the two can never disagree about which rows are about to be failed. Worker jobs are excluded on purpose: their logs live on the worker and their rows go to the recovery window, not to `failed` (RECOV-01).
func (*Store) ListOverdueWorkRequests ¶
func (s *Store) ListOverdueWorkRequests(now int64) ([]WorkRequest, error)
ListOverdueWorkRequests returns the in-flight requests whose deadline has passed.
func (*Store) ListPausedForUpdate ¶ added in v0.156.0
ListPausedForUpdate returns up to limit rows parked by a one-click update waiting for idle (gofer-dzv3), oldest first. The release in job.Service re-submits each one under its own id.
func (*Store) ListPendingInteractions ¶
func (s *Store) ListPendingInteractions() ([]InteractionRecord, error)
ListPendingInteractions returns the pending interactions across ALL jobs that are still ACTIVE (the job's status is NOT terminal), creation order (E25 监督). The JOIN + terminal-job filter (复审 #4) excludes 僵尸 pending rows left on a job that finished while an interaction was unanswered — a supervisor must never be pointed at a dead job. (finish() reconciles those to cancelled, and ReconcileOrphanInteractions sweeps crash残留; this filter is the read-side guard.)
func (*Store) ListPendingWorkSuggestionsFor ¶
func (s *Store) ListPendingWorkSuggestionsFor(fields []string) ([]WorkSuggestion, error)
ListPendingWorkSuggestionsFor returns every pending suggestion for the given fields across all open (not closed, not merged-away) work items, oldest first.
func (*Store) ListPlanHandoffHistory ¶
func (s *Store) ListPlanHandoffHistory(planID string) ([]PlanHandoff, error)
ListPlanHandoffHistory returns all versions newest first.
func (*Store) ListPlans ¶
func (s *Store) ListPlans(f PlanFilter) ([]Plan, error)
ListPlans returns one page of plans matching f, newest first. The order is created_at DESC, rowid DESC — a total order, so consecutive pages neither repeat nor skip a row that shares a created_at with its neighbour.
func (*Store) ListPtySessionsByJob ¶
func (s *Store) ListPtySessionsByJob(jobID string) ([]PtySessionRecord, error)
ListPtySessionsByJob returns every pty session for a job, newest first. The returned slice is always non-nil so HTTP list responses serialize as [].
func (*Store) ListPushSubscriptions ¶
func (s *Store) ListPushSubscriptions(callerID string) ([]PushSubscription, error)
ListPushSubscriptions returns only caller's subscriptions. Encryption keys are included for the internal sender; HTTP projections deliberately omit them.
func (*Store) ListRecentPtySessions ¶
func (s *Store) ListRecentPtySessions(limit int) ([]PtySessionRecord, error)
ListRecentPtySessions returns recent pty sessions across jobs, newest first. limit <= 0 falls back to 50. The returned slice is always non-nil.
func (*Store) ListRecentWorkJournal ¶
func (s *Store) ListRecentWorkJournal(since int64, limit int) ([]WorkJournalEntry, error)
ListRecentWorkJournal returns journal entries written at or after `since` across every open work item, newest first (the steward prime's 24h digest reads it).
func (*Store) ListRecoveringJobs ¶
ListRecoveringJobs returns every job the store holds in `recovering` for workerID (all workers when workerID is empty). It is the RECOV-01 R4 adoption source: after a serve restart the new hub has no in-memory recovery set, so the rows are the only record of what a reconnecting worker process may still be running.
func (*Store) ListRetriesByJob ¶
func (s *Store) ListRetriesByJob(jobID string) ([]RetryRecord, error)
ListRetriesByJob returns a job's retry chain oldest attempt first (the order the job detail and `job retry ls` read it in). A job with no retries yields an empty slice, not an error — every job without a retry policy is that case.
func (*Store) ListRules ¶
ListRules returns every indexed rule, ordered by name so `rule ls` is stable.
func (*Store) ListSchedules ¶
func (s *Store) ListSchedules(projectFilter string, enabledOnly bool) ([]ScheduleRecord, error)
func (*Store) ListScopedMemories ¶
func (s *Store) ListScopedMemories(scope, scopeKey, keyword string, tags []string) ([]ScopedMemory, error)
func (*Store) ListSessionDecisions ¶
func (s *Store) ListSessionDecisions(sessionID, state string, limit int, before string) (SessionDecisionPage, error)
ListSessionDecisions returns the relay turns (and any other decisions) owned by an agent session, NEWEST first. before is an opaque cursor returned by a previous page; ordering is asked_at DESC, rowid DESC so same-second rows use SQLite insertion order. limit <= 0 uses the public default of 10.
func (*Store) ListSessionJobWatches ¶
func (s *Store) ListSessionJobWatches(sessionID string) ([]SessionJobWatch, error)
ListSessionJobWatches returns watches in registration order.
func (*Store) ListSessionNudges ¶
func (s *Store) ListSessionNudges(sid string, includeEnded bool) ([]SessionNudge, error)
ListSessionNudges lists a session's nudges oldest first; ended ones only with includeEnded. An empty sid lists every session's.
func (*Store) ListSkills ¶
ListSkills returns every skill, name-ordered: the library listing and the `--skill` completion both want a stable order, and name is the key.
func (*Store) ListStewardReviews ¶
func (s *Store) ListStewardReviews(limit int) ([]StewardReview, error)
ListStewardReviews lists review runs newest first.
func (*Store) ListTodaySnoozes ¶
func (s *Store) ListTodaySnoozes() ([]TodaySnooze, error)
ListTodaySnoozes returns every row (active and woken), oldest first.
func (*Store) ListTodosByPlan ¶
ListTodosByPlan returns a plan's todos in stable display order.
func (*Store) ListTrackerIssues ¶
func (s *Store) ListTrackerIssues(trackerID string, sinceRev int64) ([]TrackerRecord, error)
func (*Store) ListTrackerMemories ¶
func (s *Store) ListTrackerMemories(trackerID string, sinceRev int64) ([]TrackerRecord, error)
func (*Store) ListTrackerRepos ¶
func (s *Store) ListTrackerRepos() ([]TrackerRepo, error)
func (*Store) ListTrackerSyncClients ¶ added in v0.152.0
func (s *Store) ListTrackerSyncClients(trackerID string) ([]TrackerSyncClient, error)
ListTrackerSyncClients lists the machines that synced trackerID, most recent first.
func (*Store) ListTunnelPresets ¶
func (s *Store) ListTunnelPresets() ([]TunnelPresetRecord, error)
ListTunnelPresets returns every preset, name-ordered (the map-like local file had no order; a listing must be stable to be readable).
func (*Store) ListUpgradeRestartBlockers ¶ added in v0.156.0
func (s *Store) ListUpgradeRestartBlockers(excludedIDs, workerRunners []string, limit int) ([]UpgradeBlocker, error)
ListUpgradeRestartBlockers returns up to limit of the rows the restart census counts (oldest first), so an operator — or the update progress on the console — can see what the restart is waiting for. The job's TITLE is not a column: the caller that needs it reads the row through the job package (fromRecord).
func (*Store) ListWakeups ¶
func (s *Store) ListWakeups(jobID string) ([]WakeupRecord, error)
ListWakeups returns a job's wakeups oldest-first (the order they were registered in, which is how the job detail reads them).
func (*Store) ListWorkItemSessions ¶
func (s *Store) ListWorkItemSessions(id string) ([]WorkItemSession, error)
ListWorkItemSessions returns an item's sessions, current first.
func (*Store) ListWorkItems ¶
func (s *Store) ListWorkItems(o WorkListOpts) ([]WorkItem, error)
ListWorkItems lists work items, most recently active first. Closed (done/dropped) and merged-away items are excluded unless asked for, or unless Statuses names a closed status explicitly.
func (*Store) ListWorkJournal ¶
ListWorkJournal returns the newest `limit` entries (default 200), oldest first, so the timeline reads top to bottom. before > 0 pages backwards by entry id.
func (*Store) ListWorkJournalLevel ¶
func (s *Store) ListWorkJournalLevel(id string, limit int, before int64, level string) ([]WorkJournalEntry, error)
ListWorkJournalLevel is ListWorkJournal restricted to one level ("" = every line).
func (*Store) ListWorkLinks ¶
ListWorkLinks returns an item's links.
func (*Store) ListWorkMergeSuggestions ¶
func (s *Store) ListWorkMergeSuggestions(state string) ([]WorkMergeSuggestion, error)
ListWorkMergeSuggestions lists suggestions in the given state ("" = pending), newest first.
func (*Store) ListWorkRequests ¶
func (s *Store) ListWorkRequests(workItemID string, activeOnly bool, limit int) ([]WorkRequest, error)
ListWorkRequests lists an item's requests, newest first ("" = every item). Limit defaults to 50.
func (*Store) ListWorkSuggestions ¶
func (s *Store) ListWorkSuggestions(id string) ([]WorkSuggestion, error)
ListWorkSuggestions returns an item's pending suggestions.
func (*Store) ListWorkSummaries ¶
func (s *Store) ListWorkSummaries(itemID string, limit int) ([]WorkSummaryRun, error)
ListWorkSummaries returns an item's recent runs, newest first.
func (*Store) ListWorkbenchThreadPrefs ¶
func (s *Store) ListWorkbenchThreadPrefs(callerID string) ([]WorkbenchThreadPref, error)
ListWorkbenchThreadPrefs returns every preference row for caller. The table's compound primary key keeps this bounded to that caller without a second index.
func (*Store) ListWorkflowEvents ¶
func (s *Store) ListWorkflowEvents(wfID string, sinceSeq int64) ([]WorkflowEvent, error)
ListWorkflowEvents returns a workflow's events in insertion order (seq ASC). When sinceSeq > 0 only events strictly after it are returned (the incremental cursor for poll). A workflow with no events yields an empty slice and no error.
func (*Store) ListWorkflowJobs ¶
ListWorkflowJobs returns every step-job of a workflow, ordered by step_index ascending (step 1 first), for the engine (find the current step's job) and the detail API (the step list). A workflow with no jobs yields an empty slice.
func (*Store) ListWorkflows ¶
ListWorkflows returns workflows, optionally filtered by status (exact match when non-empty), newest first (created_at desc, id desc as a stable tiebreaker), capped at limit (<= 0 => DefaultListLimit). It feeds both the list API and the sweeper's running-workflow scan (ListWorkflows("running", N)).
func (*Store) ListWorktrees ¶
func (s *Store) ListWorktrees() ([]WorktreeRecord, error)
ListWorktrees returns every job row that records a managed worktree (WT-01), newest first. The retention sweep snapshots these BEFORE pruning so it can tell which worktrees lost their row (PruneJobs returns result dirs, not ids) and clean up the merged ones.
func (*Store) ListXfers ¶
func (s *Store) ListXfers(f XferFilter) ([]XferRecord, error)
ListXfers returns transfer rows newest-first, optionally filtered by state, runner and/or initiating caller.
func (*Store) LoadWorkbenchSnapshot ¶
func (s *Store) LoadWorkbenchSnapshot(callerID string, since int64, includeInternal bool) (WorkbenchSnapshot, error)
LoadWorkbenchSnapshot loads every W1 projection input with a fixed number of bulk queries. since is a unix-second activity watermark. A qualifying job with a session selects the entire session chain so its first title and turn count do not disappear when only the latest turn is recent.
func (*Store) MarkAuthGrantUsed ¶ added in v0.164.0
MarkAuthGrantUsed atomically updates the usage counters of a live grant.
func (*Store) MarkDelivered ¶
MarkDelivered moves a delivery to the terminal delivered state after a 2xx webhook response. now stamps updated_at and last_error is cleared.
func (*Store) MarkFailed ¶
MarkFailed moves a delivery to the terminal failed state (retry cap reached). attempts is recorded as given and lastErr captures the final failure.
func (*Store) MarkInteractionNeedsHuman ¶
MarkInteractionNeedsHuman sets needs_human=1 on one interaction row — the通用 sup 对 高危/拿不准的 interaction 拒答(留给人)的标记(事件驱动按需派发 y5wt)。TARGETED UPDATE (not a full upsert) so it touches only needs_human and never clobbers status/answer; an unknown (job_id, id) is a silent no-op (0 rows). Writes go through writeMu like every other writer. The interaction itself stays pending (a human answers it later).
func (*Store) MarkPushSubscriptionOK ¶
MarkPushSubscriptionOK records the most recent successful 2xx delivery.
func (*Store) MarkRetry ¶
func (s *Store) MarkRetry(id int64, attempts int, nextRetryAt int64, lastErr string, now int64) error
MarkRetry records a failed attempt that will be retried: it sets status back to pending, bumps attempts, sets next_retry_at to the backoff target and records lastErr. now stamps updated_at.
func (*Store) MarkRetryDone ¶
MarkRetryDone records that a claimed retry was submitted as newJobID: the row becomes done, releases its lease and keeps the id of the job it produced. Only a CLAIMED row can be completed (that is the state the sweeper just took it in), so a row cancelled or completed elsewhere is reported as an error instead of being silently overwritten.
func (*Store) MarkStaleSessionsOffline ¶
MarkStaleSessionsOffline moves sessions that have been silent since before cutoff (unix seconds) to `offline` and returns how many it changed. Excluded: ended and already-offline rows, handed_off (a live pty job drives it), and any session with an OPEN decision whose deadline is still later than cutoff — a Stop hook parked on a relay turn sends no heartbeat while it waits, so its silence is measured from the turn's deadline instead of its last beat.
func (*Store) MarkStewardEventsHandled ¶
MarkStewardEventsHandled stamps the given events as handled.
func (*Store) MarkStewardJob ¶
MarkStewardJob records that jobID is the steward's session job. It is stamped by the server before the job gets its credential, and read back when a resident session is recovered after a restart.
func (*Store) MarkWorkItemReminded ¶
MarkWorkItemReminded records that the deadline due at `due` was announced, so the next sweep stays quiet until a later remind_at / park_until is set.
func (*Store) MarkWorkRequest ¶
func (s *Store) MarkWorkRequest(id, state, channel, errText string, from ...string) (WorkRequest, bool, error)
MarkWorkRequest moves a request to a new state if its current state is one of from (empty = any) and reports whether it changed. sent / answered stamp their times; an error text is kept for failed.
func (*Store) MatchingEventWakeups ¶
func (s *Store) MatchingEventWakeups(sourceJobID, eventType string) ([]WakeupRecord, error)
MatchingEventWakeups returns the ENABLED event wakeups that subscribe to eventType raised by sourceJobID: kind=event, the source job matches the filter (an empty filter_job_id means "the job the wakeup is registered on" — CreateWakeup always fills it, so this only covers a hand-written row) and event_types_json contains the type. The status filter (job.terminal only) is applied by the caller, which is where that vocabulary lives.
func (*Store) MemorySuggestionDismissedSince ¶
func (s *Store) MemorySuggestionDismissedSince(trackerID, key, action string, since int64) (bool, error)
MemorySuggestionDismissedSince reports whether (tracker, key, action) was dismissed at or after since (the steward's re-propose cooldown).
func (*Store) MergeWorkItems ¶
MergeWorkItems folds the sources into target (design §4: 合并): sessions and links move over, the sources' journals are re-homed onto the target with their origin recorded, and each source ends as dropped + merged_into so it vanishes from the default list but stays resolvable. A source that is the target, already merged or unknown is an error before anything changes.
func (*Store) OpenWorkItemsFor ¶
OpenWorkItemsFor returns the open (not done / dropped / merged) work items a job, a plan or a session belongs to: an explicit job / plan link, a current session that IS the job (an ACP / pty session job) or the session itself, or a current session that watches the job (a job a terminal session submitted).
func (*Store) OrphanAuthGrants ¶ added in v0.162.0
OrphanAuthGrants 把列出的授权标为孤儿(设计 §2「孤儿授权」):发给一个配置里不存在的调用方的授权 停用。标过就不再改 —— 同一 id 以后重新出现也仍保持停用,只有 ActivateAuthGrant 才恢复。 已经孤儿或已撤销的行不动;返回真正改动的行数。
func (*Store) OverviewJobs ¶
func (s *Store) OverviewJobs(from int64) ([]OverviewJobRow, error)
OverviewJobs reads every job that ended at or after from (unix seconds).
func (*Store) OverviewPlans ¶
OverviewPlans counts plans whose status is done and whose last update falls at or after from (plans keep no completion stamp, so updated_at approximates it), and the todos marked done in the same window.
func (*Store) OverviewReviews ¶
func (s *Store) OverviewReviews(from int64) ([]OverviewReviewRow, error)
OverviewReviews reads the jobs reviewed at or after from.
func (*Store) OverviewSessionUsage ¶
func (s *Store) OverviewSessionUsage(fromDay string) ([]SessionModelUsage, int, error)
OverviewSessionUsage sums session_usage_daily from fromDay (UTC YYYY-MM-DD) on, per model, plus the number of distinct sessions that reported usage.
func (*Store) PatchTrackerIssue ¶
func (s *Store) PatchTrackerIssue(trackerID, id string, expected int64, patch map[string]json.RawMessage, now, by string) (TrackerRecord, error)
func (*Store) PatchTrackerMemory ¶
func (s *Store) PatchTrackerMemory(trackerID, id string, expected int64, patch map[string]json.RawMessage, now, by string) (TrackerRecord, error)
func (*Store) PauseSessionNudge ¶
PauseSessionNudge pauses an active nudge (reason is kept for display).
func (*Store) PendingStewardEvents ¶
func (s *Store) PendingStewardEvents(limit int) ([]StewardEvent, error)
PendingStewardEvents lists the events nobody handled yet, oldest first.
func (*Store) PlanJobStatusCounts ¶
PlanJobStatusCounts returns a raw status->count map for jobs bound to planID. It uses a full GROUP BY query so counts are not affected by any job list limit.
func (*Store) PlanSessionUsage ¶
func (s *Store) PlanSessionUsage(planID string) (PlanSessionUsage, error)
PlanSessionUsage reads the attributed session usage of one plan (zero when none).
func (*Store) PlanTodoCountsByPlan ¶
func (s *Store) PlanTodoCountsByPlan(planIDs []string) (map[string]PlanTodoCounts, error)
PlanTodoCountsByPlan rolls up todo statuses for many plans with one grouped query per chunk (the plan list must not issue a query per plan). Plans without todos are absent from the map, i.e. read as the zero PlanTodoCounts.
func (*Store) PlanUsage ¶
PlanUsage aggregates the usage its attached jobs reported, per agent and in total. A plan with no jobs (or none that reported usage) is the zero value — ByAgent is always non-nil so a caller can index it without a nil check.
func (*Store) PruneAuthAudit ¶ added in v0.164.0
PruneAuthAudit removes entries older than the design's 90-day retention window.
func (*Store) PruneJobTokens ¶
PruneJobTokens deletes credential rows whose job is long gone (revoked or expired before cutoff). The rows a pruned JOB leaves behind are deleted with the job itself (see PruneJobs); this sweeper covers the rest — a credential revoked by the terminal path but whose job row is retained for its result dir.
func (*Store) PruneJobs ¶
func (s *Store) PruneJobs(policy RetentionPolicy, now int64) (deleted int, prunedDirs []string, err error)
PruneJobs deletes the terminal jobs (status in done/failed/cancelled/timeout) that the retention policy evicts, along with their interaction, event (E13) and webhook-delivery (E14) rows. Live jobs (queued/running/pending_interaction) are NEVER deleted. It returns the number of jobs deleted and the result_dir of each, so the caller can best-effort remove the on-disk log directories (the DB does not own those files).
now is injected (unix seconds) so tests can pin the clock; production passes time.Now().Unix().
All work runs under writeMu (like every other writer) so SQLite never sees a concurrent writer; the deletes run inside a single transaction so a job row and its interactions are removed atomically.
func (*Store) PruneWorkflows ¶
func (s *Store) PruneWorkflows(policy WorkflowRetentionPolicy, now int64) (deleted int, prunedDirs []string, err error)
PruneWorkflows deletes terminal workflows (status in done/failed/cancelled) older than the policy's MaxAge, and连带删 each workflow's step-jobs (+ their job_events / interactions / event_deliveries) and its workflow_events — so a pruned workflow leaves NO悬挂 rows (D22). Running workflows are NEVER deleted. It returns the number of workflows deleted and the result_dir of every deleted step-job, so the caller can best-effort remove the on-disk log directories.
now is injected (unix seconds) so tests can pin the clock. All work runs under writeMu and inside a single transaction (a workflow header + its step-jobs + all event/delivery rows are removed atomically).
func (*Store) PutScopedMemory ¶
func (*Store) PutScopedMemoryPatch ¶
func (s *Store) PutScopedMemoryPatch(scope, scopeKey, key, content string, tags []string, meta ScopedMemoryMetaPatch, updatedBy string) (ScopedMemory, error)
PutScopedMemoryPatch upserts a scoped memory. Content and tags are replaced as before; the meta fields follow tracker.ApplyMemoryPatch (nil keeps).
func (*Store) PutWorkbenchLayout ¶
func (s *Store) PutWorkbenchLayout(callerID string, expectedVersion int64, bodyJSON string, updatedAt int64) (layout WorkbenchLayout, updated bool, err error)
PutWorkbenchLayout atomically replaces caller's layout only when expectedVersion matches the current version (missing rows have version 0). updated=false returns the current record without changing it.
func (*Store) ReadSessionMessageLog ¶
ReadSessionMessageLog returns the bounded plain Markdown history for a session.
func (*Store) ReadSessionOutbox ¶
func (s *Store) ReadSessionOutbox(sid string) ([]SessionMessage, error)
ReadSessionOutbox returns the latest state for each message in send order.
func (*Store) RecentWorkRequests ¶
func (s *Store) RecentWorkRequests(workItemID string, finishedSince int64) ([]WorkRequest, error)
RecentWorkRequests returns, for the card, an item's in-flight requests plus its most recent finished one (so "会话已回复 / 未回应,已改为整理" stays visible for a while).
func (*Store) ReconcileOrphanInteractions ¶
ReconcileOrphanInteractions flips to cancelled every pending interaction whose job is already terminal — the crash-recovery backstop (复审 #4) for the in-memory reconciliation finish() does (a process that died mid-job never ran finish, so its pending rows are stuck). ts stamps answered_at. Returns the rows fixed. Run once at serve startup. Writes go through writeMu like every other writer.
func (*Store) ReconcileOrphanJobs ¶
ReconcileOrphanJobs resolves every job left non-terminal by a previous serve instance — the crash-recovery backstop (mirrors ReconcileOrphanInteractions). Run ONCE at serve startup, before new work is accepted, so the in-memory job map is empty and no live job can be misclassified. Two outcomes (RECOV-01):
- worker job: held in `recovering` with recovering_since=ts and an explanatory error. A worker job is a row whose worker_id is non-empty OR whose runner is one of workerRunners (the worker-type runner names the caller resolved from config). The runner half is load-bearing: a runner=worker job whose worker_id was empty on the request (the D4 "runner's configured default worker" fallback, resolved at dispatch) used to be misclassified as a local job and failed at once. The worker process may still be RUNNING the job (its job.Service is process-scoped, so a worker-side job survives a serve restart), and serve arms the recovery window so the same process can reconnect and be ADOPTED (R4: the hub rebuilds a sink for a store-held recovering row whose worker_instance_id matches the re-registering process). Rows with no recorded instance are still held for the window and then failed (they can never be adopted).
- every other non-terminal job (local runner / peer-http): failed, as before — its in-process state really is gone.
ts stamps updated_at (+ ended_at on the failed rows); reason is recorded in the error column (the recovering rows prefix it and append the worker id). Returns the total rows touched (held + failed), so the caller's startup log reports both.
func (*Store) RecordNudgeAttempt ¶
func (s *Store) RecordNudgeAttempt(id string, now int64, ok bool, errText string, nextRun int64, maxFails int) (n SessionNudge, paused bool, err error)
RecordNudgeAttempt stores the outcome of one delivery attempt of an ACTIVE nudge. A success resets the consecutive-failure count; a failure increments it and, on reaching maxFails, pauses the nudge (paused=true). nextRun re-arms an "every" nudge (ignored for "stalled"). A nudge that is no longer active (paused / ended meanwhile) is left alone.
func (*Store) RecordTrackerSyncClient ¶ added in v0.152.0
func (s *Store) RecordTrackerSyncClient(c TrackerSyncClient) error
RecordTrackerSyncClient upserts the (tracker, host, caller) row with the latest sync time and summary. An empty host is stored as UnknownSyncClientHost.
func (*Store) RedactJob ¶
func (s *Store) RedactJob(jobID string, literals, patterns []string) (RedactReport, error)
RedactJob replaces literals and RE2 patterns in every text column belonging to one terminal job, then scans its result directory. DB changes and the audit event are committed together; files are rewritten with temp-file swaps.
func (*Store) RedactSecrets ¶
func (s *Store) RedactSecrets(literals, patterns []string, filter SecretScanFilter, vacuum bool) (SecretBatchRedactReport, error)
RedactSecrets scans once, reuses RedactJob's column/file implementation for every terminal hit, and checkpoints the WAL once after the batch.
func (*Store) ReleaseDecision ¶
ReleaseDecision closes an OPEN decision WITHOUT an answer: state EXPIRED plus the released_by tag (SR-A5, "user_returned"). ok is false when the row is unknown or no longer OPEN — an answer that beat the release wins.
🔒 Takes writeMu itself; callers must not hold it.
func (*Store) ReleaseRetry ¶
ReleaseRetry gives a claimed retry back for a LATER attempt: it returns to pending with a new next_run_at (a failed submit must not lose the row — the design's "最多 晚一轮") and drops the lease. Only a claimed row can be released.
func (*Store) ReleaseSessionHandedOff ¶
ReleaseSessionHandedOff undoes that: the takeover columns are cleared and the session returns to idle, so the terminal that registered it relays again — or to ended when it had ended before the takeover (a woken-up closed terminal: ended_at is still set, and a re-registration, which clears it, is what makes a session live again). ok is false when the session is unknown.
func (*Store) ReleaseWakeupClaim ¶
ReleaseWakeupClaim frees the continuation slot when it still holds the value the caller expects (the pending sentinel after a failed submit, or the id of a continuation that has since reached a terminal state). The CAS keeps a release from clearing a slot another fire just took.
func (*Store) RemoveSessionJobWatch ¶
RemoveSessionJobWatch removes one watch and reports whether it existed.
func (*Store) RemoveWorkLink ¶
RemoveWorkLink removes a link; ok=false when it was not there.
func (*Store) RenameTracker ¶
RenameTracker moves a mirrored repository from oldID to newID across tracker_repos, tracker_issues and tracker_memories in one transaction. It is idempotent: when oldID is absent it is a no-op (renamed=false). When both exist it returns ErrTrackerRenameConflict and changes nothing.
func (*Store) ResolveWorkMergeSuggestion ¶
ResolveWorkMergeSuggestion moves a pending suggestion to accepted / dismissed.
func (*Store) ResumeSessionNudge ¶
ResumeSessionNudge re-arms a paused nudge: the failure count and pause reason are cleared and the timers restart from now.
func (*Store) RevokeAuthGrant ¶ added in v0.162.0
RevokeAuthGrant 撤销一条授权:写 revoked_at / revoked_by(设计 §2「撤销」,那行永远留着)。已经撤销 过的行是幂等的空操作,返回它现在的样子;不存在时 ok 为 false。
func (*Store) RevokeJobToken ¶
RevokeJobToken marks a job's credential dead (revoked_at = now). It reports whether a row was actually flipped (false = the job holds no credential, or it was already revoked) so the terminal path can stay silent about a no-op.
func (*Store) ScanSecrets ¶
func (s *Store) ScanSecrets(literals, patterns []string, filter SecretScanFilter) (SecretScanReport, error)
ScanSecrets searches the same SQLite text-column and result-directory surfaces that RedactJob handles, plus comments/events discovered through the same job ownership rule. It never returns source text.
func (*Store) SessionGrantAnchor ¶ added in v0.162.0
func (s *Store) SessionGrantAnchor(sid string) (SessionGrantAnchor, bool, error)
SessionGrantAnchor reads the facts a session grant binds to and is judged by. A session that does not exist answers ok=false with no error.
func (*Store) SessionStats ¶
func (s *Store) SessionStats(now int64) (SessionStats, error)
SessionStats aggregates agent_sessions and their relay turns. now is the current unix seconds. Unlike the decision READ paths it performs NO lazy expiry (a dashboard poll must not write): a relay turn counts as waiting only while it is OPEN *and* still inside its own timeout window, which is the same set the expiry sweep would keep. ByState/ByRelayMode are zero-filled for every known state/mode so the JSON shape is stable; unknown values a newer hook wrote still appear.
func (*Store) SessionUsageStats ¶
SessionUsageStats sums session_usage_daily for each window ending at now.
func (*Store) SetChangeHook ¶
func (s *Store) SetChangeHook(h ChangeHook)
SetChangeHook installs (nil clears) the write observer. It is wired once at serve assembly; reads of the pointer on every write are lock-free.
func (*Store) SetClock ¶
SetClock overrides the clock unixNow reads (tests; nil restores the wall clock).
func (*Store) SetCommentTriggeredJob ¶
SetCommentTriggeredJob records the job a comment dispatched. It is a conditional UPDATE on the row id, so a comment already linked is simply overwritten (the last dispatch wins) and an unknown id reports ok=false rather than an error.
func (*Store) SetJobSessionID ¶
SetJobSessionID writes a session id onto a job row that does not have one yet — the narrow, first-wins update the LIVE capture paths use (F11: the ndjson projector the moment it sees the agent's session row, and the post-restart log re-scan). It touches ONE column, so it can neither resurrect a terminal row nor interfere with the batch UPDATE that is about to fail an orphan, and it never overwrites an id that was already captured (injected at submit, or read earlier). The bool reports whether this call was the one that wrote it.
func (*Store) SetLeaderWakeFired ¶
SetLeaderWakeFired records the job a claimed round started, and the round number that was decided when it fired (two members can arm inside one wake window, so the number is settled at fire time). It CASes on `firing`, so a round cancelled in between is not overwritten by a late submit.
func (*Store) SetPlanBlocked ¶
SetPlanBlocked parks a plan on the item a failed chain job belongs to (PLAN-03): blocked_todo records WHICH item, and the status becomes PlanBlocked so the plan list and the web banner show it. The two move in ONE statement — a plan whose status says blocked but names no item would be unactionable.
func (*Store) SetPlanHandoff ¶
func (s *Store) SetPlanHandoff(planID, body, by string, expectedVersion int) (PlanHandoff, error)
SetPlanHandoff appends a new version if expectedVersion matches the current version. expectedVersion=0 is the first write. The version read and insert are one transaction under the store writer lock, so concurrent writers cannot skip or reuse a version.
func (*Store) SetPlanLeader ¶
SetPlanLeader flips a plan's leader-round switch (LEAD-02). It touches nothing else: the switch is a human's decision about a plan, not a status change. The caller validates the value at its own boundary (jobstore stays value-permissive like the other plan setters).
func (*Store) SetPlanNotify ¶ added in v0.160.0
SetPlanNotify flips the plan's end-notification switch (gofer-3db4): with it on, every job the plan dispatches tells the plan's supervisor session that it ended.
func (*Store) SetPlanPaused ¶
SetPlanPaused holds or releases a plan's automatic chain advance (PLAN-03). progress is untouched.
func (*Store) SetPlanStatus ¶
SetPlanStatus moves a plan to status and optionally updates progress. progress < 0 keeps the current progress value.
func (*Store) SetPlanSupervisorSessionID ¶
SetPlanSupervisorSessionID explicitly binds or clears the plan's trusted supervising session. Omission is handled by callers as "preserve".
func (*Store) SetScheduleLastJob ¶
func (*Store) SetScheduleTriggerToken ¶
SetScheduleTriggerToken replaces a schedule's webhook token (AUTO-02b). An empty token DISABLES the endpoint for that schedule; the rotation and the enable/disable paths are the only writers.
func (*Store) SetSessionHandedOff ¶
func (s *Store) SetSessionHandedOff(sid, jobID string) (AgentSession, error)
SetSessionHandedOff records path B's takeover (design §9.1 B): the interactive pty job that now continues this session takes it over, so the state moves to handed_off with the job and the moment stored — that is what the web links to, what the original terminal is told, and what a release must undo.
func (*Store) SetSessionMessageLogRoot ¶
SetSessionMessageLogRoot selects storage.root independently of a custom db_path.
func (*Store) SetSessionRelayMode ¶
SetSessionRelayMode stores the relay switch (auto | on | off). ok is false when the session is unknown.
func (*Store) SetSessionState ¶
SetSessionState moves a session to state (no other field changes besides ended_at for `ended`). ok is false when the session is unknown.
func (*Store) SetSessionTopic ¶ added in v0.166.0
func (s *Store) SetSessionTopic(sid string, topic *string, scope *[]string, source string) (a AgentSession, ok, ended bool, err error)
SetSessionTopic stores the session's topic and scope (the PATCH /v1/sessions/{sid} write). topic / scope nil leave that part as it was; source is SessionTopicSelf or SessionTopicHuman. ok is false for an unknown session; ended is true (nothing written) when the session has ended — a finished session is no longer a delivery target, so its topic is not edited. The returned row is the stored one.
func (*Store) SetStewardReviewSummary ¶
func (s *Store) SetStewardReviewSummary(day, summary string) (StewardReview, error)
SetStewardReviewSummary stores the steward's point-of-view text on the newest running review (or, when none is running, on today's newest done one) and reports which review took it.
func (*Store) SetTodoDispatchError ¶
SetTodoDispatchError records why the last dispatch attempt produced no job, or clears the note with msg "" (PLAN-02 P2). It is the ONE writer of dispatch_error: a failed attempt stores the reason, a successful one clears it, and a skipped one (the preconditions were simply not met yet) touches nothing. Best-effort by contract — the caller dispatches jobs, it does not fail because a note could not be written.
func (*Store) SetTodoDone ¶
SetTodoDone sets a todo's done flag (legacy二态 surface). It maps onto the lifecycle: done=true → TodoDone, done=false → TodoPending, with the same automatic timestamps as UpdateTodoStatus.
func (*Store) SetTodoJob ¶
SetTodoJob binds a todo to the job that most recently carried it (SUP-01 C). The todo keeps a pointer to ONE job — the latest run — so the checklist can link to "what is doing this" without scanning the jobs table. ok is false when the todo is unknown.
func (*Store) SetTodoReadyIfPending ¶
SetTodoReadyIfPending promotes a PENDING todo to `ready` in one conditional statement and reports whether it was the one that did it (PLAN-03). The `WHERE status='pending'` is what makes the chain advance idempotent: two concurrent terminal outcomes of the same plan can both decide an item is due, but only one flips it, and only that one dispatches it (a second dispatch would be refused by the active-job gate anyway — this keeps the event log honest too).
The timestamp rule matches UpdateTodoStatus' `→ ready`: done_at/done are cleared so a re-queued item is not shown as finished, started_at is untouched.
func (*Store) SetWakeupContinuation ¶
SetWakeupContinuation replaces the in-flight claim with the real continuation job id. It CASes on the pending sentinel, so a fire that had already lost its slot can never overwrite the winner's continuation.
func (*Store) SetWakeupEnabled ¶
SetWakeupEnabled flips a wakeup's switch (the enable/disable surface and the once-consumption / TTL-expiry writes).
func (*Store) SetWorkItemAutoStatus ¶
SetWorkItemAutoStatus applies the session-derived status to an item whose status is still owned by `auto` and is not finished. changed=false when nothing was written.
func (*Store) SetWorkbenchSeenBaseline ¶
SetWorkbenchSeenBaseline advances the caller-wide seen watermark. It is monotonic so a skewed clock or racing request cannot make old attention reappear.
func (*Store) SetWorkflowStatus ¶
SetWorkflowStatus moves a workflow to a terminal/explicit status, recording an optional error message and stamping updated_at. Idempotent re-writes are harmless (same terminal status). Runs under writeMu.
func (*Store) SetXferContent ¶
SetXferContent records the byte size + sha256 of the transfer's staged payload (a get's result arrives only once the worker has uploaded it).
func (*Store) SplitWorkItem ¶
SplitWorkItem creates a new work item out of id (design §4: 拆分) and returns (source, new). The new item inherits project/workspace and starts active.
func (*Store) StatsGen ¶
StatsGen is the dashboard overview's invalidation counter: it moves whenever a job ends, is reviewed or deleted, terminal-session usage lands, or a job_metrics row is written. A cached overview built under an older value may be stale.
func (*Store) StewardReviewComment ¶
StewardReviewComment returns the point-of-view text of the newest done review of day ("" when none): what the daily digest appends as the steward's comment.
func (*Store) SyncTrackerIssue ¶
func (s *Store) SyncTrackerIssue(rec TrackerRecord, baseRev int64) (TrackerSyncResult, error)
SyncTrackerIssue / SyncTrackerMemory apply one pushed record under optimistic concurrency. baseRev is the server rev the client last saw (0 = never seen): baseRev < stored rev is a stale write and is NOT applied (the current record is returned as a conflict); otherwise the record is stored as stored rev + 1 (rev 1 for a new record). Lookup and write share one transaction.
func (*Store) SyncTrackerMemory ¶
func (s *Store) SyncTrackerMemory(rec TrackerRecord, baseRev int64) (TrackerSyncResult, error)
func (*Store) TombstoneTrackerMemoryAt ¶
func (s *Store) TombstoneTrackerMemoryAt(trackerID, key string, expected int64, body []byte, now, deletedBy string) (TrackerRecord, error)
TombstoneTrackerMemoryAt writes a tombstone over one mirrored memory only while it is still LIVE at rev expected — a compare-and-set inside the write lock, so a sync that landed in between is never overwritten. A missing key, a tombstone or another rev returns ErrTrackerConflict and changes nothing. The tombstone gets rev expected+1 and a fresh changed_seq (clones pick it up on their next pull). Unlike UpsertTrackerMemory (the sync path, "newer rev wins") it never applies blindly.
func (*Store) TouchAgentSession ¶
func (s *Store) TouchAgentSession(sid string, hb SessionHeartbeat) (AgentSession, bool, error)
TouchAgentSession applies a hook heartbeat: refreshes last_seen_at and last_event, optionally moves state, stores the latest assistant message and records the hook's input-idle reading (IdleSec nil = leave it). State `ended` also stamps ended_at. ok is false when the session is unknown.
func (*Store) TransferAgentSessionOwner ¶ added in v0.155.1
func (s *Store) TransferAgentSessionOwner(sessionID, callerID, by string) (a AgentSession, from string, ok bool, err error)
TransferAgentSessionOwner hands a session to another authenticated caller — the admin action behind `gofer session owner` / POST /v1/sessions/{sid}/owner (gofer-eh53). It is a single dedicated statement rather than a read-then-upsert: the row keeps its state, its turns and its watches, only the owner changes, and the refusal note goes away because it described the ownership that just ended. from is the owner it had (may be ""). ok is false when the session is unknown.
The hand-over also REVOKES the session's own grants, in the same transaction (设计 §4: 「归属转移时,撤销授权与改 owner 在同一事务里完成」). Ownership is one of the conditions a session grant is judged by, so a grant of the previous owner stops applying the moment the owner changes anyway; revoking it says so in the row and in the audit trail instead of leaving a grant that looks live but never is. `by` names the caller that performed the hand-over (the revoked_by of those rows).
func (*Store) UnackDecision ¶
UnackDecision clears the read marker on an OPEN decision. It is idempotent and never changes a settled decision.
func (*Store) UpdatePlanTags ¶
UpdatePlanTags replaces tags when tags is non-nil and then removes any tags named in untag. It is additive-schema safe and leaves all other plan fields intact.
func (*Store) UpdateSkill ¶
UpdateSkill replaces an existing skill row (name is the key and never changes: a rename upstream is a re-import, not an update). A name that is not in the table is an error rather than a no-op — the caller has just put the skill's files in place, so "0 rows updated" means the index and the library have drifted apart and the caller must hear about it.
func (*Store) UpdateTodoPatch ¶
UpdateTodoPatch applies the dispatch fields a caller set (PLAN-02 P2): only the non-nil entries of p are written, so two writers touching different fields do not overwrite each other's value. It returns false (nil error) for an unknown todo, and true without writing anything for an empty patch.
func (*Store) UpdateTodoStatus ¶
UpdateTodoStatus moves a todo along its lifecycle and/or updates its note (Part C §C2). status "" keeps the current status (note-only update); note nil keeps the current note (status-only update). Timestamps are stamped on the transition itself:
- → doing: started_at is set (only if still 0 — a redo keeps the original start), done_at is cleared (done → doing = redo);
- → done/skipped: done_at is set;
- → ready: the queue position only (PLAN-02 P2) — started_at is untouched (nothing has started), but a re-queued item drops done_at/done so a redone item is not shown as finished;
- → pending: both cleared (full reset).
The legacy done flag stays in lockstep (done ⟺ status=done).
func (*Store) UpdateWakeup ¶
func (s *Store) UpdateWakeup(r WakeupRecord) error
UpdateWakeup persists the AUTHORED fields of a wakeup (everything the operator may change: the timer spec, the event filter, the instruction, the mode, the expiry, the enabled flag and the re-armed next_run_at) and bumps Revision. The fire counters are NOT written here — they belong to ClaimWakeupFire / SetWakeupContinuation — so a re-arm cannot erase what a concurrent fire recorded.
func (*Store) UpdateWorkItem ¶
func (s *Store) UpdateWorkItem(id string, p WorkItemPatch, expectedRev int64, by string) (WorkItem, string, error)
UpdateWorkItem applies a patch under optimistic locking (expectedRev 0 = skip the check) and journals what changed. It returns the stored item and the one-line change summary ("" when nothing changed — then nothing is written and rev stays).
func (*Store) UpdateWorkflowSpec ¶
UpdateWorkflowSpec replaces the declarative spec while a workflow remains running. It is used for the explicit human pick decision; the change is conditional on the workflow id and does not alter its state machine pointer.
func (*Store) UpdateXferState ¶
UpdateXferState moves a transfer to a terminal (or dispatched) state. errMsg and finishedAt are optional: an empty errMsg / zero finishedAt leaves the stored values untouched, so a state move never has to invent a timestamp.
func (*Store) UpsertAgentSession ¶
func (s *Store) UpsertAgentSession(in AgentSession) (AgentSession, error)
UpsertAgentSession registers a session or refreshes an existing one. On insert the row starts `running` (unless in.State is given) with started_at = now and relay_mode `auto` (unless in.RelayMode is given). On update only NON-EMPTY descriptive fields overwrite the stored ones (agent/project/runner/cwd/title/transcript/tmux_pane), last_seen_at is refreshed, and an `ended` session comes back to `running` (a resumed CLI session re-registers under the same id). in.LastHumanAt > 0 stamps last_human_at (see RegisterInput.Event == SessionStart); relay_mode and turn_no are never touched here. It returns the stored row.
func (*Store) UpsertAgentSessionForOwner ¶
func (s *Store) UpsertAgentSessionForOwner(in AgentSession) (AgentSession, bool, error)
UpsertAgentSessionForOwner atomically rejects a re-registration when an existing non-empty caller_id belongs to another authenticated principal. Ordinary internal UpsertAgentSession retains its prior merge behavior.
func (*Store) UpsertDecisionAdvice ¶
func (s *Store) UpsertDecisionAdvice(a DecisionAdvice) (DecisionAdvice, error)
UpsertDecisionAdvice writes (replaces) the advice of one card; At defaults to now.
func (*Store) UpsertInteraction ¶
func (s *Store) UpsertInteraction(rec InteractionRecord) error
UpsertInteraction inserts an interaction row or updates the existing one with the same (job_id, id). The pending and answered writes for one interaction are two upserts on the same row (the answered snapshot overwrites the pending one), so the table keeps a single, latest row per interaction — the DB equivalent of folding interactions.jsonl. Writes go through s.writeMu (like UpsertJob) so SQLite never sees two concurrent writers and cannot return SQLITE_BUSY.
func (*Store) UpsertJob ¶
UpsertJob inserts a job row or updates the existing one with the same id. The create and finish writes for a job are two upserts on the same row (not two appended lines as in jobs.jsonl), so the index stays naturally deduplicated. UpdatedAt falls back to StartedAt when the caller leaves it zero, so ordering / retention always have a value.
func (*Store) UpsertJobMetrics ¶
func (s *Store) UpsertJobMetrics(m JobMetrics) error
UpsertJobMetrics writes (or replaces) a job's derived metrics row.
func (*Store) UpsertJobToken ¶
func (s *Store) UpsertJobToken(rec JobTokenRecord) error
UpsertJobToken stores (or replaces) the credential row of a job. Replacing is the right shape for a re-submitted/rebuild job that reuses an id — there is at most one live credential per job, and the new one supersedes the old.
func (*Store) UpsertPtySession ¶
func (s *Store) UpsertPtySession(rec PtySessionRecord) error
UpsertPtySession inserts a pty session row or updates the existing one with the same pty_session_id. The open and closed writes for one session are two upserts on the same PK (the closed snapshot overwrites the open one), so the table keeps a single latest row per session. Encrypted defaults to 2 (no) when left zero so the SR301 "avoid 0" invariant holds. Writes go through writeMu like every other writer so SQLite never sees two concurrent writers.
func (*Store) UpsertPushSubscription ¶
func (s *Store) UpsertPushSubscription(sub PushSubscription) error
UpsertPushSubscription registers endpoint for caller. Endpoint is globally unique: a browser endpoint re-registered by another authenticated caller moves to that caller and resets last_ok_at because the key material changed.
func (*Store) UpsertRule ¶
UpsertRule writes one index row, replacing an existing one of the same name (`rule set` on an existing name is a replace by design).
func (*Store) UpsertTodaySnooze ¶
func (s *Store) UpsertTodaySnooze(in TodaySnooze) (TodaySnooze, error)
UpsertTodaySnooze snoozes (or re-snoozes) one card; a re-snooze clears the wake marker. CreatedAt is stamped by the store.
func (*Store) UpsertTrackerIssue ¶
func (s *Store) UpsertTrackerIssue(rec TrackerRecord) error
func (*Store) UpsertTrackerMemory ¶
func (s *Store) UpsertTrackerMemory(rec TrackerRecord) error
func (*Store) UpsertTrackerRepo ¶
func (s *Store) UpsertTrackerRepo(repo TrackerRepo) error
func (*Store) UpsertTunnelPreset ¶
func (s *Store) UpsertTunnelPreset(rec TunnelPresetRecord) error
UpsertTunnelPreset writes a preset, replacing the row of the same name. It is an upsert rather than an insert because whether a name may be replaced is the CLI's `--force` question (asked over the whole store, with a 409 when the answer is no), not a storage detail.
func (*Store) UpsertWorkSuggestion ¶
func (s *Store) UpsertWorkSuggestion(sg WorkSuggestion) (stored bool, err error)
UpsertWorkSuggestion stores (or replaces) the pending suggestion for a field. A proposal identical to one the person already dismissed is not stored again (stored=false), so a dismissed idea does not keep coming back.
func (*Store) UpsertWorkbenchThreadPref ¶
func (s *Store) UpsertWorkbenchThreadPref(pref WorkbenchThreadPref) error
UpsertWorkbenchThreadPref replaces one caller/thread preference row.
func (*Store) UsageStats ¶
func (s *Store) UsageStats(now int64, windows []time.Duration, budget time.Duration) (UsageStats, error)
UsageStats aggregates what each agent reported in each window ending at now. budget caps the TOTAL pass (one query per window, each cheap, but the dashboard polls this every few seconds); when it is exhausted the remaining windows are left out of the map and Partial is set — a caller must read a MISSING window as "not computed", never as zero usage.
func (*Store) WakeTodaySnooze ¶
WakeTodaySnooze marks an active row as woken (reason: time / job / activity). It is a no-op on a row that already woke or is gone, so concurrent readers agree on one wake.
func (*Store) WorkCounts ¶
WorkCounts is the dashboard count per status for open items.
func (*Store) WorkFieldSources ¶
func (s *Store) WorkFieldSources(id string) (map[string]WorkFieldSource, error)
WorkFieldSources returns the per-field sources of one item (missing = never written since this tracking existed).
func (*Store) WorkItemLinkedJobs ¶
WorkItemLinkedJobs returns the jobs a work item is linked to — what its current sessions watch, its explicit job links, and the newest perPlan jobs of each linked plan — newest submitted first, at most limit rows, in ONE query (the Works list, the Today page and the lanes call this per item; a per-session / per-job lookup there was an N+1 re-run on every live push).
type TodaySnooze ¶
type TodaySnooze struct {
CardKey string `json:"card_key"`
UntilAt int64 `json:"until_at,omitempty"`
UntilJobID string `json:"until_job_id,omitempty"`
ActivityAt int64 `json:"activity_at"`
CreatedAt int64 `json:"created_at"`
WokeAt int64 `json:"woke_at,omitempty"`
WokeReason string `json:"woke_reason,omitempty"`
}
TodaySnooze is one today_snooze row (N3 T3 「稍后」, design §2.3). A row is ACTIVE while WokeAt is 0; once a wake rule fired (time / job / activity) it stays as a marker so the card returns flagged 「有新动静」 until it is handled or the marker ages out.
type TodoPatch ¶
type TodoPatch struct {
Assignee *string `json:"assignee,omitempty"`
ProjectKey *string `json:"project,omitempty"`
Template *string `json:"template,omitempty"`
Vars map[string]string `json:"vars,omitempty"`
Verify []string `json:"verify,omitempty"`
Review *bool `json:"review,omitempty"`
Runner *string `json:"runner,omitempty"`
Cwd *string `json:"cwd,omitempty"`
TimeoutSec *int `json:"timeout_sec,omitempty"`
// PLAN-03 chain fields: After sets the dependencies (a non-nil empty list clears
// them), Auto the auto-advance switch, Cmd the argv of an exec item.
After *[]string `json:"after,omitempty"`
Auto *bool `json:"auto,omitempty"`
Cmd *[]string `json:"cmd,omitempty"`
// Model is the model the item's job runs with (N1 §B); a non-nil empty string
// clears it.
Model *string `json:"model,omitempty"`
// Budget is the job's spend ceiling (N2 §B); a non-nil all-zero value clears it.
Budget *config.Budget `json:"budget,omitempty"`
// Acceptance is the item's acceptance criteria; a non-nil empty string clears it.
Acceptance *string `json:"acceptance,omitempty"`
// Scope is the item's declared change scope (path globs); a non-nil empty list
// clears it.
Scope *[]string `json:"scope,omitempty"`
// PrimeKeywords are the task keywords of the item's job (gofer-11tz); a non-nil empty
// list clears them.
PrimeKeywords *[]string `json:"prime_keywords,omitempty"`
}
TodoPatch is the set of dispatch fields an update may change (PLAN-02 P2). It is shared by every write path — the HTTP PATCH body decodes into it, the CLI and MCP fill it, and the store applies it — so the three surfaces cannot drift.
A nil pointer/slice/map means "keep the current value"; a non-nil EMPTY value clears it (that is how a runner is taken back or a verify step removed). Status, Note and AppendNote are NOT part of it: they move through UpdateTodoStatus/AppendTodoNote, which own the lifecycle timestamps.
type TrackerBatchResult ¶
type TrackerBatchResult struct {
ID string `json:"id"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
TrackerBatchResult is the per-issue outcome of BatchPatchTrackerIssues.
type TrackerBatchSet ¶
type TrackerBatchSet struct {
Status string `json:"status,omitempty"`
CloseReason string `json:"close_reason,omitempty"`
AddTags []string `json:"add_tags,omitempty"`
}
TrackerBatchSet is the change applied to every issue of a batch. Status and CloseReason follow the single-edit semantics: closing stamps closed_at (kept if already closed) and records the reason; any other status clears both.
func (TrackerBatchSet) Validate ¶
func (b TrackerBatchSet) Validate() error
Validate rejects a set that changes nothing or is inconsistent.
type TrackerDeleteResult ¶ added in v0.139.0
type TrackerDeleteResult struct {
Repo bool `json:"repo"`
Issues int64 `json:"issues"`
Memories int64 `json:"memories"`
Suggestions int64 `json:"suggestions"`
}
TrackerDeleteResult counts what DeleteTracker removed.
func (TrackerDeleteResult) Empty ¶ added in v0.139.0
func (r TrackerDeleteResult) Empty() bool
Empty reports that nothing with the tracker_id existed.
type TrackerRecord ¶
type TrackerRecord struct {
TrackerID string `json:"tracker_id"`
ID string `json:"id"`
Body json.RawMessage `json:"body"`
Rev int64 `json:"rev"`
UpdatedAt string `json:"updated_at"`
Deleted bool `json:"deleted"`
DeletedAt string `json:"deleted_at"`
DeletedBy string `json:"deleted_by"`
ChangedSeq int64 `json:"changed_seq"`
// ServerCreated marks an issue the server filed that no repository has pulled yet
// (the web shows it as 「待同步」); see tracker_server_issue.go.
ServerCreated bool `json:"server_created,omitempty"`
}
type TrackerRename ¶ added in v0.166.0
TrackerRename records one id change made while accepting a push.
type TrackerRepo ¶
type TrackerRepo struct {
TrackerID string `json:"tracker_id"`
ProjectKey string `json:"project_key"`
RelPath string `json:"rel_path"`
Prefix string `json:"prefix"`
LastSyncAt int64 `json:"last_sync_at"`
SyncSummary string `json:"sync_summary"`
// SourceRunner is the runner of the job that last pushed this repo (TRK-05): where
// a server-dispatched `repo sync` has to run. Empty = never seen from a job, so the
// dispatcher falls back to the project's default runner.
SourceRunner string `json:"source_runner,omitempty"`
}
type TrackerSyncClient ¶ added in v0.152.0
type TrackerSyncClient struct {
TrackerID string `json:"tracker_id"`
ClientHost string `json:"client_host"`
Caller string `json:"caller"`
LastSyncAt int64 `json:"last_sync_at"`
Summary string `json:"summary"`
}
TrackerSyncClient is one machine's last sync of a tracker: which host, under which authenticated caller, when, and the client's one-line summary.
type TrackerSyncResult ¶
type TrackerSyncResult struct {
// Rec is the stored record: the accepted write (new rev), or on Conflict the
// current server record the client has not seen yet.
Rec TrackerRecord
Conflict bool
// Ahead marks a write accepted although the client claimed a newer base rev
// than the server holds (the mirror was reset or restored).
Ahead bool
// Renamed is set when the push was a new issue whose id collided with a
// server-created, never-pulled record: that record was given a new id (Renamed.To,
// returned in Moved) in the same transaction and the push was accepted.
Renamed *TrackerRename
// Moved is the renamed server record (under its new id).
Moved *TrackerRecord
}
TrackerSyncResult is the outcome of one record pushed by `repo sync`.
type TunnelPresetRecord ¶
type TunnelPresetRecord struct {
Name string
// Worker is the worker a `tun forward -n` run reaches the target through.
Worker string
// SpecsJSON is `["1502:10.0.0.5:502", ...]`, already split (never one compound
// comma-joined entry).
SpecsJSON string
Note string
Autostart bool
// UpdatedAt / UpdatedBy are the write audit: unix SECONDS (like every other
// timestamp in this store) and the authenticated caller that saved it.
UpdatedAt int64
UpdatedBy string
}
TunnelPresetRecord is one server-side forward preset (TUN-03: the preset store the CLI and the console share, replacing the machine-local tunnels.yaml as the source of truth). SpecsJSON holds the rule list as a JSON array of strings — the CLI's own spelling, one rule per entry — and stays an opaque string here so this package needs no import of internal/tunnel, exactly like schedules.request_json.
type UpgradeBlocker ¶ added in v0.138.1
type UpgradeBlocker struct {
ID string
Status string
Runner string
// StartedAt is when the job was submitted (the row's started_at, 0 for a job a
// worker has not begun yet).
StartedAt int64
}
UpgradeBlocker is one job row that keeps a server restart waiting.
type UsageAgent ¶
type UsageAgent struct {
Jobs int
TotalTokens int64
InputTokens int64
OutputTokens int64
CostUSD float64
}
UsageAgent is one agent's tally inside a window. Jobs counts EVERY job the agent ran in the window — one that captured no usage still ran — while the token/cost sums only see the jobs that actually reported numbers.
type UsageStats ¶
type UsageStats struct {
Windows map[string]UsageWindow
Partial bool
}
UsageStats is the per-agent token/cost aggregate behind /v1/stats (SUP-01 E): one entry per computed window, keyed by the window's label ("24h", "7d"), plus the flag saying whether the budget ran out before every window was computed — the same degraded mode DBStats uses, because a dashboard poll must never stall on a big or cold db.
type UsageWindow ¶
type UsageWindow struct {
ByAgent map[string]UsageAgent
Total UsageAgent
}
UsageWindow is one reporting window of the aggregate: the per-agent tallies and their sum.
type WakeupRecord ¶
type WakeupRecord struct {
ID string
JobID string
Kind string
At int64
EverySec int64
CronExpr string
Timezone string
EventTypesJSON string
FilterJobID string
FilterStatusJSON string
Mode string
Instruction string
Enabled int
Revision int64
NextRunAt int64
LastFiredAt int64
FiredCount int64
CoalescedCount int64
// ContinuationJobID is the single outstanding continuation this wakeup started
// (or WakeupClaimPending while that submit is in flight). A trigger that finds
// it set and non-terminal only bumps CoalescedCount — one wakeup never stacks
// continuations (design §五 决策 6).
ContinuationJobID string
CreatedBy string
CreatedAt int64
ExpiresAt int64
}
WakeupRecord is the SQLite-persisted projection of one JOB-09 wakeup: an event subscription or timer registered on a job that starts a CONTINUATION of that job when it fires. The JSON columns are opaque strings to this package — jobstore must not import internal/job (G022) — and hold an array of event-type strings (EventTypesJSON) and of status strings (FilterStatusJSON).
Revision is bumped by every UpdateWakeup so a reader can tell an edited wakeup from the one it read; the fire counters (LastFiredAt / FiredCount / CoalescedCount / ContinuationJobID) are written by the fire path alone.
func (WakeupRecord) IsContinuationPending ¶
func (r WakeupRecord) IsContinuationPending() bool
IsContinuationPending reports whether the fire slot is held by an in-flight submit rather than by a job id.
type WorkFieldSource ¶
WorkFieldSource is who wrote one field and when (unix seconds).
type WorkItem ¶
type WorkItem struct {
ID string `json:"id"`
Title string `json:"title"`
Goal string `json:"goal"`
Status string `json:"status"`
StatusSource string `json:"status_source"`
BlockerKind string `json:"blocker_kind,omitempty"`
BlockerText string `json:"blocker_text,omitempty"`
NextStep string `json:"next_step,omitempty"`
Summary string `json:"summary,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
Workspace string `json:"workspace,omitempty"`
Priority int `json:"priority,omitempty"`
ParkUntil int64 `json:"park_until,omitempty"`
ParkNote string `json:"park_note,omitempty"`
RemindAt int64 `json:"remind_at,omitempty"`
RemindedAt int64 `json:"reminded_at,omitempty"`
Source string `json:"source"`
Unsorted bool `json:"unsorted"`
MergedInto string `json:"merged_into,omitempty"`
Rev int64 `json:"rev"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
ClosedAt int64 `json:"closed_at,omitempty"`
LastActivityAt int64 `json:"last_activity_at"`
StatusAt int64 `json:"status_at,omitempty"`
// Capture-box fields (empty for items that were not captured). The source session
// is a plain field, not a work_item_sessions row, so SyncAll and the summarizer
// never take the item over.
Kind string `json:"kind,omitempty"`
CaptureSourceSession string `json:"capture_source_session,omitempty"`
CaptureSourceJob string `json:"capture_source_job,omitempty"`
}
WorkItem is one thing the human is working on (design §4.1). Timestamps are unix seconds; Rev is the optimistic-lock counter (incremented on every field write).
type WorkItemInput ¶
type WorkItemInput struct {
Title string
Goal string
Status string
ProjectKey string
Workspace string
NextStep string
Priority int
Source string
Unsorted bool
// SessionIDs are attached as `current` sessions.
SessionIDs []string
By string
// Note is the creation journal text ("" = a default line).
Note string
}
WorkItemInput is the creation request.
type WorkItemPatch ¶
type WorkItemPatch struct {
Title *string
Goal *string
Status *string
BlockerKind *string
BlockerText *string
NextStep *string
Summary *string
ProjectKey *string
Workspace *string
Priority *int
ParkUntil *int64
ParkNote *string
RemindAt *int64
Unsorted *bool
// StatusSource overrides who owns the status (the work service sets it for session
// reports and the auto mapping); with a Status change and no override, a patch is a
// human edit.
StatusSource *string
// Quiet skips the automatic status journal line: the caller writes its own (a
// session report is journaled as a `report` entry instead of a `status` one).
Quiet bool
// FromCapture marks a call from a capture-box entry point: only then may the
// patch set Status to captured or move an item out of captured. Ordinary updates
// (reports, summarizer, steward, PATCH) leave it false and are refused.
FromCapture bool
}
WorkItemPatch is a partial update; nil fields are untouched.
type WorkItemSession ¶
type WorkItemSession struct {
WorkItemID string `json:"work_item_id"`
SessionID string `json:"session_id"`
Role string `json:"role"`
AttachedAt int64 `json:"attached_at"`
DetachedAt int64 `json:"detached_at,omitempty"`
}
WorkItemSession is one session <-> work item relation.
type WorkJournalEntry ¶
type WorkJournalEntry struct {
ID int64 `json:"id"`
WorkItemID string `json:"work_item_id"`
Kind string `json:"kind"`
Text string `json:"text"`
By string `json:"by"`
At int64 `json:"at"`
OriginItem string `json:"origin_item,omitempty"`
// Level is milestone | detail (WORK-06, see DefaultWorkJournalLevel).
Level string `json:"level"`
}
WorkJournalEntry is one append-only journal line.
type WorkLink ¶
type WorkLink struct {
WorkItemID string `json:"work_item_id,omitempty"`
Kind string `json:"kind"`
Ref string `json:"ref"`
CreatedAt int64 `json:"created_at,omitempty"`
// PendingSync is set on an issue link whose issue the server created and no
// repository has pulled yet (the web shows 「待同步」).
PendingSync bool `json:"pending_sync,omitempty"`
}
WorkLink points a work item at an issue / plan / todo / job.
type WorkListOpts ¶
type WorkListOpts struct {
Statuses []string
Project string
Workspace string
Unsorted *bool
SessionID string
Query string
IncludeClosed bool
IncludeMerged bool
// Due restricts to items whose reminder / park deadline has passed at Now.
Due bool
Now int64
Limit int
}
WorkListOpts filters ListWorkItems.
type WorkMergeSuggestion ¶
type WorkMergeSuggestion struct {
ID int64 `json:"id"`
TargetID string `json:"target_id"`
SourceID string `json:"source_id"`
Reason string `json:"reason,omitempty"`
By string `json:"by"`
At int64 `json:"at"`
State string `json:"state"`
}
WorkMergeSuggestion is a recorded "these two items look like one thing" for a person to confirm. Nothing merges until a person accepts it.
type WorkRefs ¶
WorkRefs names what a job / decision / interaction belongs to, to find the open work items it concerns.
type WorkRequest ¶
type WorkRequest struct {
ID string `json:"id"`
WorkItemID string `json:"work_item_id"`
SessionID string `json:"session_id,omitempty"`
Kind string `json:"kind"`
State string `json:"state"`
Channel string `json:"channel,omitempty"`
Text string `json:"text,omitempty"`
By string `json:"by"`
Error string `json:"error,omitempty"`
CreatedAt int64 `json:"created_at"`
SentAt int64 `json:"sent_at,omitempty"`
AnsweredAt int64 `json:"answered_at,omitempty"`
Deadline int64 `json:"deadline,omitempty"`
ParentID string `json:"parent_id,omitempty"`
}
WorkRequest is one row of the request ledger: an ask that was (or could not be) delivered, and what became of it. Timestamps are unix seconds.
type WorkRequestInput ¶
type WorkRequestInput struct {
WorkItemID string
SessionID string
Kind string
By string
Text string
// Deadline is the unix time after which an unanswered request expires (0 = never).
Deadline int64
ParentID string
}
WorkRequestInput creates a ledger row (state pending).
type WorkSuggestion ¶
type WorkSuggestion struct {
WorkItemID string `json:"work_item_id,omitempty"`
Field string `json:"field"`
Value string `json:"value"`
Confidence float64 `json:"confidence,omitempty"`
By string `json:"by"`
At int64 `json:"at"`
State string `json:"state"`
JobID string `json:"job_id,omitempty"`
}
WorkSuggestion is a proposal the summarizer made for a field it was not allowed to overwrite (a person or a session wrote it). The person adopts or dismisses it.
type WorkSummaryRun ¶
type WorkSummaryRun struct {
ID int64 `json:"id"`
WorkItemID string `json:"work_item_id"`
SessionID string `json:"session_id,omitempty"`
At int64 `json:"at"`
ActivityAt int64 `json:"activity_at,omitempty"`
State string `json:"state"`
JobID string `json:"job_id,omitempty"`
Cause string `json:"cause,omitempty"`
Error string `json:"error,omitempty"`
}
WorkSummaryRun is one tidy-up attempt: it is the cost-control ledger (per-session interval, daily cap, "was there new activity since") and an audit trail.
type WorkbenchLayout ¶
WorkbenchLayout is one caller's opaque, versioned workbench layout. The frontend owns the JSON schema; this package only provides atomic persistence.
type WorkbenchSnapshot ¶
type WorkbenchSnapshot struct {
Jobs []JobRecord
PendingInteractions []InteractionRecord
StalledJobIDs map[string]bool
Sessions []AgentSession
RelayDecisions []PlanDecision
BlockedPlans []Plan
OpenPlanDecisions []PlanDecision
DecisionPlans []Plan
Prefs []WorkbenchThreadPref
}
WorkbenchSnapshot is the fixed-query input to the workbench domain projector. Each slice is loaded in bulk; consumers must join it in memory rather than issue a query per thread/job.
type WorkbenchThreadPref ¶
type WorkbenchThreadPref struct {
CallerID string
ThreadID string
Title string
SeenAt int64
Pinned bool
}
WorkbenchThreadPref is the per-caller presentation state for one canonical workbench thread id. It deliberately contains no derived thread status.
type Workflow ¶
type Workflow struct {
ID string
Title string
Status string
CurrentStep int
TotalSteps int
SpecJSON string
CallerID string
Error string
CreatedAt int64
UpdatedAt int64
// StepAttempt is the 1-based attempt of the CURRENT step (P1, design §5.2).
// First run == 1; a retry advances (current_step,step_attempt) from (cur,att) to
// (cur,att+1). Together with CurrentStep it forms the二元组 AdvanceStep抢权 on
// (旧库/v1 行 COALESCE→1). 推进到下一步时 step_attempt 重置为 1.
StepAttempt int
// NextStepAt is the退避到点时间 (unix seconds) before the current step's next
// attempt may start (P1, design §5.2). 0 == immediate (no backoff pending). Set
// by a retry transition; the sweeper/advance skip a workflow whose NextStepAt is
// still in the future, then start the next attempt once it is due. 旧库行→0.
NextStepAt int64
// ParentWorkflowID is the父 workflow id when THIS workflow is a sub-workflow
// started by a parent step (P3, design §5.2, D19). "" for a top-level workflow.
// When non-empty, this workflow's terminal transition triggers the parent's
// advanceWorkflow (the parent step's terminal == this sub-workflow's terminal).
// 旧库/v1 行 COALESCE→"" (top-level), so向后兼容 (D23).
ParentWorkflowID string
// ParentStepIndex is the 1-based step index in the parent that started this
// sub-workflow (P3, design §5.2). 0 for a top-level workflow. Together with
// ParentWorkflowID it locates this sub-workflow as a parent step's child. 旧库行→0.
ParentStepIndex int
}
Workflow is the SQLite-persisted projection of one job-chain header (design §5.1). Like JobRecord it is a neutral struct (no internal/job import) so the job package can drive it without forming an import cycle.
CurrentStep is the 1-based active step (the step whose job is currently running or just finished). TotalSteps is len(spec.Steps). SpecJSON is the marshalled WorkflowSpec the engine rebuilds each step's JobRequest from. CallerID is inherited by every step-job (D8). Error holds the fail reason when Status=failed.
type WorkflowEvent ¶
type WorkflowEvent struct {
Seq int64 `json:"seq"`
WorkflowID string `json:"workflow_id"`
Type string `json:"type"`
Detail string `json:"detail,omitempty"`
At int64 `json:"at"`
}
WorkflowEvent is the SQLite-persisted projection of one append-only workflow lifecycle event (P1, design §5.4), the workflow analogue of JobEvent. Like every type here it is a neutral struct decoupled from internal/job so the workflow_events table can be populated without forming a job -> jobstore -> job import cycle.
Detail holds the marshalled detail_json original (already a JSON string); an empty string means "no detail" (the column stays NULL). Seq is the monotonic global insertion order assigned by SQLite (AUTOINCREMENT), used as the poll cursor; it is 0 on a value being inserted and set on read.
type WorkflowRetentionPolicy ¶
type WorkflowRetentionPolicy struct {
// MaxAge, when > 0, deletes terminal workflows whose updated_at is older than
// now-MaxAge, along with their step-jobs and workflow_events.
MaxAge time.Duration
}
WorkflowRetentionPolicy bounds how long terminal workflows are kept (P1, design §5.4 / D22). A zero MaxAge prunes nothing.
func (WorkflowRetentionPolicy) IsZero ¶
func (p WorkflowRetentionPolicy) IsZero() bool
IsZero reports whether the workflow policy would prune nothing.
type WorktreeRecord ¶
type WorktreeRecord struct {
JobID string
ProjectKey string
Path string
Branch string
BaseSHA string
}
WorktreeRecord is the WT-01 projection of one job's managed worktree: the row fields the retention sweep and `job worktree ls` need, without pulling a whole JobRecord. Empty Path means the job has no managed worktree.
type XferFilter ¶
type XferFilter struct {
State string
Runner string
// CallerID restricts the list to one caller's own transfers (gofer-hxld): the
// HTTP list pushes the caller id in for anyone but a root administrator, so a
// non-admin caller never reads a colleague's journal line — and the limit still
// means "my last N".
CallerID string
Limit int
}
XferFilter selects rows for ListXfers. Zero values mean "no filter"; Limit<=0 falls back to DefaultListLimit.
type XferRecord ¶
type XferRecord struct {
ID string
Op string // put | get
Runner string // worker id, or `local`/`server` for the server's own machine
ProjectKey string
Path string // project-relative path on the EXECUTING machine
Size int64
SHA256 string
State string // staged | dispatched | done | failed | expired
Error string
CallerID string
Force int // 1 = overwrite an existing destination
// JobID is RESERVED for X2 (`job run --upload/--collect`): the job a transfer
// belongs to. X1 always leaves it empty.
JobID string
CreatedAt int64
FinishedAt int64
ExpiresAt int64
}
XferRecord is the SQLite-persisted journal row of one file transfer (XFER-01 design §一.2). The payload bytes are NOT here: they live in the staging area (internal/xfer's Store). jobstore owns the row because the row is what the HTTP API lists/filters and what the prune loop expires; the transfer STATE vocabulary lives in internal/xfer (this package only stores the string).
Source Files
¶
- agent_sessions_count.go
- audit.go
- auth.go
- change.go
- comments.go
- dbstats.go
- decision_permission.go
- decisions.go
- delete.go
- deliveries.go
- events.go
- global_memories.go
- handoffs.go
- health.go
- holds.go
- interactions.go
- job_metrics.go
- jobs.go
- jobtokens.go
- leaderwakes.go
- memory_candidates.go
- memory_suggestions.go
- plans.go
- prune.go
- pty_sessions.go
- push.go
- redact.go
- retries.go
- rules.go
- schedules.go
- scoped_memories.go
- secret_scan.go
- session_nudges.go
- session_usage.go
- session_watches.go
- sessions.go
- skills.go
- stats_overview.go
- steward.go
- store.go
- today.go
- today_advice.go
- today_snooze.go
- todos.go
- tracker.go
- tracker_batch.go
- tracker_clients.go
- tracker_read.go
- tracker_server_issue.go
- tunnel_presets.go
- upgrade_drain.go
- usagestats.go
- wakeups.go
- work.go
- work_delete.go
- work_jobs.go
- work_level.go
- work_requests.go
- work_sources.go
- work_suggest.go
- workbench.go
- workflow_events.go
- workflows.go
- xfers.go