Documentation
¶
Overview ¶
Package work is the work-item domain service (W1, design 2026-10-05): the layer above terminal sessions that records "what the human is doing", derives its status from the sessions, tracks reminders and produces the daily digest. It depends only on jobstore/config/notify; the entry layers (httpapi, mcpserver, commands) consume it and never the other way round (G022).
Index ¶
- Constants
- Variables
- func ActorKind(by string) string
- func ComputeHealth(in HealthInput, now int64, stallAfter time.Duration) (health, reason string)
- func HealthRank(h string) int
- func HumanBy(caller string) string
- func IssueTypeForKind(kind string) string
- func JobActivityAt(j jobstore.JobRecord) int64
- func OutcomeLine(o JobOutcome) (text, level string)
- func SessionBy(sid, agent string) string
- func SessionOf(by string) (sid, agent string, ok bool)
- func StatusLabel(st string) string
- func StewardBy(agent string) string
- func SummarizerBy(agent string) string
- func WorkListOptsOpen() jobstore.WorkListOpts
- type AlreadyTodoError
- type AskInput
- type AskResult
- type CaptureInput
- type CapturedItem
- type DeleteFailure
- type DeleteResult
- type DetailView
- type DialectSource
- type Digest
- type HealthInput
- type ItemView
- type JobOutcome
- type JobProbe
- type JobState
- type Messenger
- type Notifier
- type OneShot
- type OneShotRequest
- type OneShotResult
- type ProjectChooser
- type ReportInput
- type RequestOpts
- type RequestOutcome
- type Service
- func (s *Service) AcceptMergeSuggestion(id int64, by string) (jobstore.WorkItem, error)
- func (s *Service) AcceptSuggestion(id, field, by string) (jobstore.WorkItem, error)
- func (s *Service) AskSession(ctx context.Context, in AskInput) (AskResult, error)
- func (s *Service) BackgroundContext() context.Context
- func (s *Service) BuildDigest(now time.Time) (Digest, error)
- func (s *Service) Capture(in CaptureInput) (jobstore.WorkItem, error)
- func (s *Service) Captured(id string) (CapturedItem, error)
- func (s *Service) Close() error
- func (s *Service) Delete(ids []string, status, actor string) (DeleteResult, error)
- func (s *Service) Detail(id string, journalLimit int) (DetailView, error)
- func (s *Service) DismissMergeSuggestion(id int64) error
- func (s *Service) DismissSuggestion(id, field, by string) error
- func (s *Service) DispatchClose(id, to, by string) (jobstore.WorkItem, error)
- func (s *Service) DispatchToIssue(id, trackerID, titleOverride, by string) (jobstore.TrackerRecord, jobstore.WorkItem, error)
- func (s *Service) DispatchToTodo(id string, in ToTodoInput) (ToTodoResult, jobstore.WorkItem, error)
- func (s *Service) ExistingTodo(id string) (todoID, planID string, ok bool, err error)
- func (s *Service) FinishDispatch(id string, status, linkKind, linkRef, journal, by string) (jobstore.WorkItem, error)
- func (s *Service) IsJobSession(id string) bool
- func (s *Service) List(o jobstore.WorkListOpts) ([]ItemView, error)
- func (s *Service) ListRequests(itemID string, activeOnly bool, limit int) ([]jobstore.WorkRequest, error)
- func (s *Service) MarkDirty()
- func (s *Service) MarkSessionDirty(sid string)
- func (s *Service) MergeSuggestions() ([]jobstore.WorkMergeSuggestion, error)
- func (s *Service) NoteJobOutcome(o JobOutcome)
- func (s *Service) OnHumanPrompt(a jobstore.AgentSession, prompt string)
- func (s *Service) OnSessionBeat(a jobstore.AgentSession)
- func (s *Service) Park(id string, until int64, note, by string) (jobstore.WorkItem, error)
- func (s *Service) Report(id string, in ReportInput) (jobstore.WorkItem, error)
- func (s *Service) RequestSessions(ctx context.Context, itemID string, o RequestOpts) ([]RequestOutcome, error)
- func (s *Service) Run(stop <-chan struct{})
- func (s *Service) RunSummarize(ctx context.Context, itemID string, o SummarizeOpts) (SummarizeResult, error)
- func (s *Service) SendDigest(now time.Time) (Digest, int, error)
- func (s *Service) SessionBy(sid string) string
- func (s *Service) SessionTail(ctx context.Context, sid string, maxBytes int64) (SessionTailResult, error)
- func (s *Service) SetConfigFn(fn func() config.WorkConfig)
- func (s *Service) SetDueHook(fn func(w jobstore.WorkItem, reason string, at int64))
- func (s *Service) SetJobProbe(p JobProbe)
- func (s *Service) SetMessenger(m Messenger)
- func (s *Service) SetNotifier(n Notifier)
- func (s *Service) SetNow(fn func() time.Time)
- func (s *Service) SetOneShot(o OneShot)
- func (s *Service) SetSessionSayer(x SessionSayer)
- func (s *Service) SetTranscriptSource(t TranscriptSource)
- func (s *Service) StallAfter() time.Duration
- func (s *Service) StartSummarize(itemID string, o SummarizeOpts)
- func (s *Service) StewardUpdate(id string, p jobstore.WorkItemPatch, expectedRev int64, by string) (StewardUpdateResult, error)
- func (s *Service) Store() *jobstore.Store
- func (s *Service) SuggestMerge(targetID, sourceID, reason, by string) (jobstore.WorkMergeSuggestion, bool, error)
- func (s *Service) Summarize() (Summary, error)
- func (s *Service) SummarizerStatus() SummarizerStatus
- func (s *Service) SyncAll()
- func (s *Service) SyncItem(id string)
- func (s *Service) TargetQuery(id string) (TargetQuery, error)
- func (s *Service) Tick(now time.Time)
- func (s *Service) TidyNow(itemID, by string) (jobstore.WorkRequest, error)
- func (s *Service) ToTodo(id string, in ToTodoInput) (ToTodoResult, error)
- func (s *Service) Update(id string, p jobstore.WorkItemPatch, expectedRev int64, by string) (jobstore.WorkItem, error)
- func (s *Service) WaitIdle()
- type SessionBrief
- type SessionSayer
- type SessionTailResult
- type StewardUpdateResult
- type SummarizeOpts
- type SummarizeResult
- type SummarizerStatus
- type Summary
- type SummaryOut
- type TargetQuery
- type ToTodoInput
- type ToTodoResult
- type TranscriptSource
Constants ¶
const ( ActorHuman = "human" ActorSession = "session" ActorSteward = "steward" ActorSummarizer = "summarizer" ActorJob = "job" ActorSystem = "system" ActorOther = "other" )
Speaker labels (W2a, design §14.1.5). Every work-item field change and journal line carries who made it, in ONE canonical spelling, so the card can show "谁写的、何时" and a reader can tell a person's word from a session's report or a model's tidy-up:
human:<caller> a person (web / CLI with that caller id) session:<sid>(<agent>) a terminal session reporting about itself steward(<agent>) the steward (W2b) summarizer(<agent>) the passive tidy-up job job:<id> / system a job credential / gofer's own bookkeeping
const ( DispatchSession = "session" DispatchJob = "job" DispatchTodo = "todo" DispatchArchive = "archive" DispatchDrop = "drop" DispatchIssue = "issue" )
Dispatch targets accepted by the HTTP route.
const ( HealthOK = "ok" HealthAtRisk = "at_risk" HealthStalled = "stalled" HealthBlocked = "blocked" )
Lane health (N3 design 2026-10-09 §3.2): how a piece of parallel work is doing, computed from facts the store already has. Only the non-ok values are shown.
const ( DefaultSessionTailBytes = 64 * 1024 MaxSessionTailBytes = 256 * 1024 )
DefaultSessionTailBytes / MaxSessionTailBytes bound what the steward's read-only session tail returns (the same read the summarizer uses, so a worker's v17 transcript_tail frame enforces the size limit on its side too).
const ( CauseManual = "manual" // the 「整理」 button / `gofer work summarize` CauseRequest = "request" // a report / hand-over request that could not be answered CauseAuto = "auto" // the passive scan (idle / offline / ended with new activity) )
Why a tidy-up runs.
const ( ProjectSourceConfig = "config" // work.summarizer_project is set ProjectSourceItem = "item" // the work item's own project ProjectSourceDefault = "default" // the built-in / declared `default` project )
Summarizer project sources, as reported by SummarizerStatus.ProjectSource.
const DefaultCaptureKind = jobstore.WorkKindNote
DefaultCaptureKind is the kind of a capture that names none: a plain note is the least presumptuous label (an idea / issue / request is a claim about what the text is).
const KindJob = "job"
KindJob marks a SessionBrief whose id is a job id (ACP persistent / pty session).
const (
// ParkedStaleSec is the "搁置超过 7 天" digest threshold.
ParkedStaleSec = 7 * 24 * 3600
)
Variables ¶
var ( // ErrAskNotFound: the id is neither a registered terminal session nor a job. ErrAskNotFound = errors.New("session not found") // ErrAskOffline: the session exists but cannot receive a message right now. The text // is NOT queued — the caller is told and decides. ErrAskOffline = errors.New("session is not online") // ErrAskDenied: the caller may not speak to this session. ErrAskDenied = errors.New("not allowed to speak to this session") // ErrAskEmpty: nothing to say. ErrAskEmpty = errors.New("text is required") // ErrAskUnsupported: no delivery path is wired for this kind of session. ErrAskUnsupported = errors.New("no delivery path for this session") )
Errors of AskSession; the entry layers map them to 404 / 409 / 403 / 400.
var ErrEmptyReport = errEmptyReport
ErrEmptyReport is returned for a report that says nothing.
var ErrMergeSuggestionResolved = errors.New("merge suggestion was already decided")
ErrMergeSuggestionResolved is returned when a suggestion was already decided.
var ErrNoSession = errors.New("work item has no current session to ask")
ErrNoSession is returned when a request has no current session to ask.
var ErrNoTranscript = errors.New("transcript unavailable")
ErrNoTranscript is returned by a TranscriptSource that cannot supply a transcript (none registered, an old worker, the file is gone); the tidy-up then degrades to the session's last message, progress line and the item's journal.
var ErrNotCaptured = errors.New("work item is not in the capture box")
ErrNotCaptured is returned when the item is not in the capture box (any dispatch of an item that already left it is refused, so a double click cannot act twice).
var ErrPlanNotFound = errors.New("plan not found")
ErrPlanNotFound is returned by ToTodo when the chosen plan does not exist.
var ErrSessionNotFound = errors.New("session not found")
ErrSessionNotFound is returned by SessionTail for an unknown session id.
var ErrStewardFinalStatus = errors.New("the steward may not mark a work item done or dropped; that is a person's decision")
ErrStewardFinalStatus is returned when the steward asks to end a work item: done and dropped are a person's call.
var ErrSuggestionConflict = errors.New("suggestion cannot be applied")
ErrSuggestionConflict is returned when a suggestion cannot be applied any more.
ErrSummarizerUnavailable is returned when no usable summarizer agent is configured.
Functions ¶
func ComputeHealth ¶
func ComputeHealth(in HealthInput, now int64, stallAfter time.Duration) (health, reason string)
ComputeHealth applies §3.2: blocked (a blocked plan, or an unresolved blocker on an item that waits for a person) > stalled (in progress and quiet for stallAfter) > at_risk (the latest linked job failed or hit its budget) > ok. reason is a short human sentence ("" for ok).
func HealthRank ¶
HealthRank is the sort key of a health value (lower = needs attention sooner).
func IssueTypeForKind ¶ added in v0.166.0
IssueTypeForKind is the tracker issue type a captured kind becomes: a captured issue is a bug, everything else (idea / request / note) a task.
func JobActivityAt ¶
JobActivityAt is a job's newest timestamp (updated / ended / started).
func OutcomeLine ¶
func OutcomeLine(o JobOutcome) (text, level string)
OutcomeLine renders a job outcome as one journal line and its level (WORK-06 §3.3: a success with commits, a failure and a budget stop are milestones; the rest — a success without commits, a cancel — are details; a review verdict is a milestone).
func StatusLabel ¶
StatusLabel is the Chinese label of a work-item status (the steward prime and the digest use the same words the board shows).
func SummarizerBy ¶
SummarizerBy is the speaker label of the summarizer agent.
func WorkListOptsOpen ¶
func WorkListOptsOpen() jobstore.WorkListOpts
WorkListOptsOpen lists every open (not done/dropped/merged) item.
Types ¶
type AlreadyTodoError ¶
AlreadyTodoError is returned by ToTodo when the item already became a todo: the caller shows where it went instead of making a second one.
func (*AlreadyTodoError) Error ¶
func (e *AlreadyTodoError) Error() string
type AskInput ¶
type AskInput struct {
// SessionID is a terminal relay session id OR an ACP / pty session job id.
SessionID string
Text string
// By is the speaker label (steward(<agent>) / human:<caller>).
By string
// WorkID, when set, names the work item the message is logged on; otherwise every
// open item that has the session as a current one gets the log line.
WorkID string
// Prefix is put in front of the text delivered to the session (the steward tells the
// session who is talking); the journal records the bare text.
Prefix string
// Allow vets the target; nil allows all. job is true for a job session.
Allow func(sid string, job bool) bool
}
AskInput is one "带话": a short message ("the resource arrived, carry on") for a running session.
type AskResult ¶
type AskResult struct {
SessionID string `json:"session_id"`
// Kind is "session" (terminal relay session) or "job" (ACP / pty session job).
Kind string `json:"kind"`
// Channel is the path that carried it ("turn" / "messenger" / "job_say").
Channel string `json:"channel"`
// WorkItems are the items the delivery was logged on.
WorkItems []string `json:"work_items"`
}
AskResult says where the message went.
type CaptureInput ¶ added in v0.166.0
type CaptureInput struct {
Text string
Kind string // idea | issue | request | note; empty = DefaultCaptureKind
Project string
Workspace string
// SourceSession / SourceJob are recorded as fields only; By is the journal author.
SourceSession string
SourceJob string
By string
}
CaptureInput is one quick record.
type CapturedItem ¶ added in v0.166.0
CapturedItem is a captured item as the dispatch sees it: the text to hand over and the revision the follow-up write is checked against.
type DeleteFailure ¶
DeleteFailure is one item a delete sweep could not remove.
type DeleteResult ¶
type DeleteResult struct {
Deleted []string `json:"deleted"`
Failed []DeleteFailure `json:"failed"`
}
DeleteResult is the outcome of Delete: what went, and what stayed with why.
type DetailView ¶
type DetailView struct {
ItemView
Journal []jobstore.WorkJournalEntry `json:"journal"`
// Notes are the parts of an update that were deliberately not applied (a steward update
// that asked for a status a person's own status outranks); empty on every other read.
Notes []string `json:"notes,omitempty"`
}
DetailView adds the journal to the item view; Sessions then holds current AND past.
type DialectSource ¶
DialectSource is an optional capability of a TranscriptSource: the agent's configured transcript_dialect ("" = not configured). Parsing happens on the server for every source (a worker's transcript_tail frame only carries raw bytes), so the dialect never needs to cross the wire.
type Digest ¶
type Digest struct {
Title string `json:"title"`
Text string `json:"text"`
NeedsMe int `json:"needs_me"`
Waiting int `json:"waiting_resource"`
Onsite int `json:"needs_onsite"`
Review int `json:"review"`
ParkedOver int `json:"parked_over_7d"`
Yesterday int `json:"yesterday"`
// Commentary is the steward's point of view for today (W2b): the text its review wrote,
// already appended to Text. Empty without a steward or before its review finished.
Commentary string `json:"commentary,omitempty"`
}
Digest is the deterministic daily summary, computed from the database only.
type HealthInput ¶
type HealthInput struct {
// InProgress says the item / plan is meant to be moving right now (work status
// active, plan open): only then can it stall. Waiting / parked work never stalls.
InProgress bool
// Blocker is the unresolved blocker text ("" = none). It only counts while the
// item waits on a person (NeedsPerson): a blocker on waiting-for-resource or active
// work is context, not a red flag — otherwise most lanes read "blocked".
Blocker string
// NeedsPerson: the item's status asks for a person (needs_me / needs_onsite).
NeedsPerson bool
// BlockedPlan names a linked plan whose status is blocked ("" = none).
BlockedPlan string
// LastActivity is the newest journal line / linked-job activity (unix s); a
// session heartbeat does not count.
LastActivity int64
// AgentRunning: an agent is working on it right now (never stalled then).
AgentRunning bool
// LatestJob is the most recent linked job (nil = none).
LatestJob *jobstore.JobRecord
}
HealthInput is everything ComputeHealth looks at.
type ItemView ¶
type ItemView struct {
jobstore.WorkItem
// LastActivityAt shadows the stored value with max(stored, current sessions' last
// seen), so the card's "last activity" follows the terminals too.
LastActivityAt int64 `json:"last_activity_at"`
Due bool `json:"due"`
Sessions []SessionBrief `json:"sessions"`
SessionIDs []string `json:"session_ids"`
SessionOffline bool `json:"session_offline"`
// Usage is the token usage (main + sub-agents) summed over the item's CURRENT
// terminal sessions (N2 §A); nil when none of them reported any.
Usage *runner.Usage `json:"usage,omitempty"`
Links []jobstore.WorkLink `json:"links"`
// FieldSources says who last wrote goal / blocker / next / summary and when.
FieldSources map[string]jobstore.WorkFieldSource `json:"field_sources"`
// Requests are the in-flight report / hand-over / tidy-up requests plus the ones that
// finished within the last day (the card shows what became of them).
Requests []jobstore.WorkRequest `json:"requests"`
// Suggestions are the summarizer's pending proposals for fields it may not overwrite.
Suggestions []jobstore.WorkSuggestion `json:"suggestions"`
// Milestones are the newest journal milestones (WORK-06, up to 5, oldest first).
Milestones []jobstore.WorkJournalEntry `json:"milestones"`
// Health / HealthReason are the N3 lane health (ok | at_risk | stalled | blocked) and
// why; the reason is empty for ok.
Health string `json:"health"`
HealthReason string `json:"health_reason,omitempty"`
// LinkedJobs (newest first) and Plans are the linked jobs / plans the health was
// computed from; internal to the server (the Today lanes reuse them).
LinkedJobs []jobstore.JobRecord `json:"-"`
Plans []jobstore.Plan `json:"-"`
}
ItemView is a work item as the entry layers return it.
type JobOutcome ¶
type JobOutcome struct {
ID string
Agent string
Title string
Status string
PlanID string
FailureClass string
Error string
Commits int
// Reviewed says the status is a person's verdict on a needs_review job.
Reviewed bool
}
JobOutcome is what the work journal needs to know about a finished linked job (the entry layer adapts job.JobResult — work must not import job).
type JobState ¶
type JobState struct {
Status string
PendingInteraction bool
// PlanID is the plan the job belongs to ("" = none); an open decision of that plan
// makes the work item "needs me" too (X2).
PlanID string
}
JobState is what the status mapping needs to know about a linked job.
type Messenger ¶
type Messenger interface {
// SendRequest returns the channel that carried the text ("turn" / "messenger" / ...).
SendRequest(ctx context.Context, sid, text, operator string) (channel string, err error)
}
Messenger delivers a request text into a running terminal session (httpapi adapts sessionrelay.SendMessage: a session waiting for a reply gets it through the relay, anything else through the one-shot messenger). The service never knows how.
type Notifier ¶
type Notifier interface {
NotifyWork(eventType, projectKey, title, text, link, linkLabel string) int
WebURL(path string) string
}
Notifier is the outbound seam (job.Service implements it): the service knows WHEN a reminder is due, not about webhooks or config.
type OneShot ¶
type OneShot interface {
// Check reports why the agent cannot be used ("" nil = usable).
Check(agent string) error
Run(ctx context.Context, r OneShotRequest) (OneShotResult, error)
}
OneShot runs the summarizer job (the entry layer adapts job.Service).
type OneShotRequest ¶
type OneShotRequest struct {
Agent string
Args []string
ProjectKey string
Prompt string
Title string
TimeoutSec int
}
OneShotRequest is the summarizer job: a read-only, tool-less run of a cli-agent.
type OneShotResult ¶
OneShotResult is what the job produced.
type ProjectChooser ¶
type ProjectChooser interface {
// ProjectUsable reports whether the project exists and admits the agent on the
// built-in local runner (the summarizer job is always local, read-only).
ProjectUsable(key, agent string) bool
// ProjectDir is the directory a job of that project runs in ("" when unknown).
ProjectDir(key string) string
}
ProjectChooser is the optional second face of a OneShot: it lets the service pick the project the summarizer job runs in. A OneShot without it keeps the plain order (the first non-empty candidate, else `default`) without checking anything.
type ReportInput ¶
type ReportInput struct {
Goal string
Status string
Blocker string
Next string
Summary string
// By is the journal author ("session:<sid>(<agent>)", "job:<id>", "human:<caller>").
By string
// RequestID names the ledger request this report answers (`gofer work report
// --request <id>`); it must belong to the item.
RequestID string
}
ReportInput is a session's self-report (`gofer work report`, gofer_work_report).
type RequestOpts ¶
type RequestOpts struct {
// Kind is report (default) or handoff.
Kind string
// SessionID restricts the ask to one of the item's current sessions.
SessionID string
// By is the speaker label of whoever asked ("" = system).
By string
// Allow vets each target session (the owner check); nil allows all.
Allow func(sid string) bool
}
RequestOpts selects what to ask and whom.
type RequestOutcome ¶
type RequestOutcome struct {
SessionID string `json:"session_id"`
RequestID string `json:"request_id,omitempty"`
// Kind is the kind of request actually recorded: a session that is not running is
// turned into a "summarize" one.
Kind string `json:"kind,omitempty"`
State string `json:"state,omitempty"`
Sent bool `json:"sent"`
Channel string `json:"channel,omitempty"`
Reason string `json:"reason,omitempty"`
}
RequestOutcome is what happened to the ask for one session.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service owns the work-item rules on top of the store.
func (*Service) AcceptMergeSuggestion ¶
AcceptMergeSuggestion is the person's yes: it performs the merge and closes the suggestion.
func (*Service) AcceptSuggestion ¶
AcceptSuggestion applies a pending suggestion as the person's own write (by is the person): it then counts as human-written, so a later tidy-up proposes instead of overwriting. A status_hint becomes the item's status (a person's status).
func (*Service) AskSession ¶
AskSession delivers a message to a running session over the existing "传话" channels: a terminal session through the relay (answering an open turn, else the one-shot messenger), an ACP / pty session job through `job say`. A session that is not online is an explicit ErrAskOffline — nothing is queued or silently dropped. A delivered message is logged on the work item(s) of that session.
func (*Service) BackgroundContext ¶
BackgroundContext is the context background tasks run under; Close cancels it.
func (*Service) BuildDigest ¶
BuildDigest renders the digest for now (no side effects).
func (*Service) Capture ¶ added in v0.166.0
func (s *Service) Capture(in CaptureInput) (jobstore.WorkItem, error)
Capture records a captured item (status captured, status_source human). The kind is validated by the store (jobstore.ErrWorkInvalid).
func (*Service) Captured ¶ added in v0.166.0
func (s *Service) Captured(id string) (CapturedItem, error)
Captured loads item id and refuses (ErrNotCaptured) one that is not captured.
func (*Service) Close ¶
Close stops the Run loops and background tasks and waits for them, at most closeWait; it returns an error when something was still running then. Safe to call more than once, and before Run ever started. Call it before the store is closed.
func (*Service) Delete ¶
func (s *Service) Delete(ids []string, status, actor string) (DeleteResult, error)
Delete permanently removes finished work items. ids names items explicitly; status (done | dropped, or empty) adds every item in that final status. Each item is its own transaction, so one that is still open (or already gone) is reported in Failed and does not stop the rest. actor is only recorded in the audit row (see Store.DeleteWorkItem).
func (*Service) Detail ¶
func (s *Service) Detail(id string, journalLimit int) (DetailView, error)
Detail returns one item with its full journal and all sessions.
func (*Service) DismissMergeSuggestion ¶
DismissMergeSuggestion is the person's no.
func (*Service) DismissSuggestion ¶
DismissSuggestion drops a pending suggestion (the same proposal is not made again).
func (*Service) DispatchClose ¶ added in v0.166.0
DispatchClose archives (status done, journal 「归档」) or drops (status dropped) a captured item; to is DispatchArchive or DispatchDrop.
func (*Service) DispatchToIssue ¶ added in v0.166.0
func (s *Service) DispatchToIssue(id, trackerID, titleOverride, by string) (jobstore.TrackerRecord, jobstore.WorkItem, error)
DispatchToIssue files the captured item as a new issue in the server mirror of trackerID (title: titleOverride or the item's title; description: its goal, plus where it came from), links it (kind issue) and parks the item. The issue is flagged server-created until a repository sync pulls it (the web shows 「待同步」); the journal says so. The store's errors (ErrTrackerNoPrefix, ErrTrackerRepoUnknown, ErrReservedTracker) pass through unchanged. Returns the created record.
func (*Service) DispatchToTodo ¶ added in v0.166.0
func (s *Service) DispatchToTodo(id string, in ToTodoInput) (ToTodoResult, jobstore.WorkItem, error)
DispatchToTodo converts a captured item into a todo (the to-todo rules) and moves it to active.
func (*Service) ExistingTodo ¶
ExistingTodo returns the todo (and its plan) an item was already converted into.
func (*Service) FinishDispatch ¶ added in v0.166.0
func (s *Service) FinishDispatch(id string, status, linkKind, linkRef, journal, by string) (jobstore.WorkItem, error)
FinishDispatch records a successful hand-over: an optional link (job / todo / plan kinds), a journal line, and the move out of captured to the given status. The item is read again first: one that left the capture box meanwhile (a second click) is ErrNotCaptured instead of a second dispatch. (The link write bumps the revision, so the revision read by Captured cannot be the check here.)
func (*Service) IsJobSession ¶
IsJobSession reports whether id is a job id (see SessionBrief.Kind).
func (*Service) List ¶
func (s *Service) List(o jobstore.WorkListOpts) ([]ItemView, error)
List returns the item views for the filter, most recently active first.
func (*Service) ListRequests ¶
func (s *Service) ListRequests(itemID string, activeOnly bool, limit int) ([]jobstore.WorkRequest, error)
ListRequests returns an item's ledger rows, newest first ("" = all items).
func (*Service) MarkDirty ¶
func (s *Service) MarkDirty()
MarkDirty asks for a status re-sync of every open work item. It never blocks and coalesces bursts: serve calls it for every session / job / decision write.
func (*Service) MarkSessionDirty ¶
MarkSessionDirty schedules a re-sync of the work items that session belongs to.
func (*Service) MergeSuggestions ¶
func (s *Service) MergeSuggestions() ([]jobstore.WorkMergeSuggestion, error)
MergeSuggestions lists pending suggestions.
func (*Service) NoteJobOutcome ¶
func (s *Service) NoteJobOutcome(o JobOutcome)
NoteJobOutcome journals a finished job on every open work item it belongs to (a job / plan link, a session that watches it, or the job as an attached session). Best-effort: errors are logged, never returned (it runs from the job's terminal hook).
func (*Service) OnHumanPrompt ¶
func (s *Service) OnHumanPrompt(a jobstore.AgentSession, prompt string)
OnHumanPrompt is called when a HUMAN typed a prompt in a session (the hook's title is the prompt's first line): the first one creates the auto draft work item. Errors are logged, never returned — the session relay must not fail because of work items.
func (*Service) OnSessionBeat ¶
func (s *Service) OnSessionBeat(a jobstore.AgentSession)
OnSessionBeat is called after a hook heartbeat was applied: the store does not announce heartbeats (they are too chatty for the browser), but a Stop / prompt beat is exactly what moves a work item between "active" and "needs me", so the service re-syncs that session's items shortly (debounced, one session only).
func (*Service) Park ¶
Park parks an item: status parked (a person's status), an optional wake-up time and a free-text condition ("到货后继续").
func (*Service) Report ¶
Report applies a session's self-report: free-text fields are stored, the status is honoured under the human-priority rule (a person's status only yields to an explicit `active` — "the blocker is gone"), and one `report` journal line records it.
func (*Service) RequestSessions ¶
func (s *Service) RequestSessions(ctx context.Context, itemID string, o RequestOpts) ([]RequestOutcome, error)
RequestSessions asks the item's current sessions to report (or write a hand-over) through the request ledger. A session that is running gets the text with the request id (it answers with `gofer work report --request <id>`); one that is not running — or that the text cannot be delivered to — is turned into a tidy-up (kind summarize) instead, so the item still gets fresher content.
func (*Service) Run ¶
func (s *Service) Run(stop <-chan struct{})
Run drives the debounced sync and the periodic Tick until stop closes.
func (*Service) RunSummarize ¶
func (s *Service) RunSummarize(ctx context.Context, itemID string, o SummarizeOpts) (SummarizeResult, error)
RunSummarize runs one tidy-up of an item synchronously.
func (*Service) SendDigest ¶
SendDigest builds and sends the digest now (the manual trigger); it reports how many webhooks it was queued for.
func (*Service) SessionTail ¶
func (s *Service) SessionTail(ctx context.Context, sid string, maxBytes int64) (SessionTailResult, error)
SessionTail returns the tail of a session's transcript rendered as plain text, or — when the transcript is not readable (none registered, an old worker, the file is gone) — the session's last message and progress line. maxBytes <= 0 means the default; it is clamped to MaxSessionTailBytes. It never writes anything.
func (*Service) SetConfigFn ¶
func (s *Service) SetConfigFn(fn func() config.WorkConfig)
SetConfigFn supplies the live work: config block (read on every tick, so a hot reload applies to the next one). nil keeps the defaults.
func (*Service) SetDueHook ¶
SetDueHook installs the observer of announced reminders / park deadlines (nil = none).
func (*Service) SetJobProbe ¶
SetJobProbe injects the linked-job lookup (nil = jobs never influence the status).
func (*Service) SetMessenger ¶
SetMessenger injects the delivery seam (nil = requests cannot be delivered and are turned into a tidy-up straight away).
func (*Service) SetNotifier ¶
SetNotifier injects the notification seam (nil = no notifications).
func (*Service) SetOneShot ¶
SetOneShot injects the summarizer job runner (nil = tidy-up unavailable).
func (*Service) SetSessionSayer ¶
func (s *Service) SetSessionSayer(x SessionSayer)
SetSessionSayer injects the job-session delivery seam (nil = job sessions cannot be addressed).
func (*Service) SetTranscriptSource ¶
func (s *Service) SetTranscriptSource(t TranscriptSource)
SetTranscriptSource injects the transcript reader (nil = always degraded input).
func (*Service) StallAfter ¶
StallAfter is the effective work.stall_after.
func (*Service) StartSummarize ¶
func (s *Service) StartSummarize(itemID string, o SummarizeOpts)
StartSummarize runs a tidy-up in the background and settles its request when done.
func (*Service) StewardUpdate ¶
func (s *Service) StewardUpdate(id string, p jobstore.WorkItemPatch, expectedRev int64, by string) (StewardUpdateResult, error)
StewardUpdate applies the steward's patch: descriptive and scheduling fields freely, the status only to a non-final one and never over a status a person set (then it is reported back in Notes and the rest of the patch still applies). A status the steward does set is owned by `report`, not `human`, so the session-derived mapping and a person can still override it.
func (*Service) SuggestMerge ¶
func (s *Service) SuggestMerge(targetID, sourceID, reason, by string) (jobstore.WorkMergeSuggestion, bool, error)
SuggestMerge records the steward's "source belongs in target" for a person to confirm. It merges nothing.
func (*Service) SummarizerStatus ¶
func (s *Service) SummarizerStatus() SummarizerStatus
SummarizerStatus reports the effective summarizer configuration and availability.
func (*Service) SyncItem ¶
SyncItem re-derives one item's status from its sessions. Only an item whose status is still owned by `auto` moves (a human's or a report's status wins).
func (*Service) TargetQuery ¶ added in v0.166.0
func (s *Service) TargetQuery(id string) (TargetQuery, error)
TargetQuery returns the text and project of item id for the recommendation. An item that is not captured is allowed too: the same text / project rule applies. ErrWorkItemNotFound for an unknown id.
func (*Service) Tick ¶
Tick runs one scan: status sync, due reminders, and the daily digest when it is time.
func (*Service) TidyNow ¶
func (s *Service) TidyNow(itemID, by string) (jobstore.WorkRequest, error)
TidyNow is the manual trigger (the 「整理」 button, `gofer work summarize`): it records a summarize request, runs the tidy-up in the background and returns the request id.
func (*Service) ToTodo ¶
func (s *Service) ToTodo(id string, in ToTodoInput) (ToTodoResult, error)
ToTodo turns a work item into a plan todo: title and description come from the item, the item records a todo link (plus a plan link) so the two can be followed both ways. Converting twice is refused with *AlreadyTodoError.
type SessionBrief ¶
type SessionBrief struct {
SessionID string `json:"session_id"`
Role string `json:"role"`
Agent string `json:"agent,omitempty"`
Runner string `json:"runner,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
Cwd string `json:"cwd,omitempty"`
Title string `json:"title,omitempty"`
// PeerName is the agent's own session name (Claude Code `name`), copyable as the
// SendMessage address; empty until the hook reports one.
PeerName string `json:"peer_name,omitempty"`
State string `json:"state,omitempty"`
RelayMode string `json:"relay_mode,omitempty"`
LastMessage string `json:"last_message,omitempty"`
LastSeenAt int64 `json:"last_seen_at,omitempty"`
// Offline is true when the session's process is gone (offline / ended) or the row no
// longer exists (Missing).
Offline bool `json:"offline"`
Missing bool `json:"missing,omitempty"`
// Kind is "job" when the id is an ACP persistent / interactive pty session's JOB id
// (open it at /jobs/<id>); empty for a terminal relay session.
Kind string `json:"kind,omitempty"`
}
SessionBrief is the slice of a session a work card shows.
type SessionSayer ¶
SessionSayer delivers a message into a resident ACP / pty session JOB (job.Service implements it via an adapter: `job say`).
type SessionTailResult ¶
type SessionTailResult struct {
SessionID string `json:"session_id"`
Agent string `json:"agent"`
// Source is "transcript" (the registered transcript's tail) or "fallback" (the
// session's last message / progress line when the transcript cannot be read).
Source string `json:"source"`
Text string `json:"text"`
}
SessionTailResult is the read-only transcript tail of one session.
type StewardUpdateResult ¶
type StewardUpdateResult struct {
Item jobstore.WorkItem
// Notes are the parts of the request that were deliberately not applied (e.g. a status
// asked for while the person's own status stands).
Notes []string
}
StewardUpdateResult is what a steward update did.
type SummarizeOpts ¶
type SummarizeOpts struct {
Cause string
// RequestID is the ledger row to settle (answered / failed) when the run ends.
RequestID string
// SessionID picks the session to read ("" = the most recently seen current one).
SessionID string
By string
}
SummarizeOpts describes one tidy-up run.
type SummarizeResult ¶
type SummarizeResult struct {
RunID int64 `json:"run_id,omitempty"`
JobID string `json:"job_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Applied []string `json:"applied"`
Suggested []string `json:"suggested"`
StatusHint string `json:"status_hint,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
// Milestone is the summarizer's optional one-liner, journaled as a milestone.
Milestone string `json:"milestone,omitempty"`
// Degraded says the transcript could not be read and the input was the session's
// last message, progress line and the item's journal.
Degraded bool `json:"degraded,omitempty"`
}
SummarizeResult is what one tidy-up did.
type SummarizerStatus ¶
type SummarizerStatus struct {
// Enabled is the automatic (passive) tidy-up switch; the manual action works
// whenever Available.
Enabled bool `json:"enabled"`
Agent string `json:"agent"`
Args []string `json:"args"`
Project string `json:"project,omitempty"`
// EffectiveProject / EffectiveDir / ProjectSource say where a job runs when no
// work item decides: work.summarizer_project, else the `default` project.
EffectiveProject string `json:"effective_project,omitempty"`
EffectiveDir string `json:"effective_dir,omitempty"`
ProjectSource string `json:"project_source,omitempty"`
Available bool `json:"available"`
// Reason says why it is not available (or degraded) in plain words.
Reason string `json:"reason,omitempty"`
IdleMin int `json:"idle_min"`
IntervalMin int `json:"interval_min"`
DailyLimit int `json:"daily_limit"`
DailyUsed int `json:"daily_used"`
AutoHandoff bool `json:"auto_handoff"`
TimeoutMin int `json:"request_timeout_min"`
}
SummarizerStatus is what the settings page / `GET /v1/work-items/summarizer` shows.
type SummaryOut ¶
type SummaryOut struct {
Goal string
Progress string
BlockerK string
Blocker string
Next string
StatusHint string
// Milestone is optional (WORK-06): a <=40-rune line worth keeping on the timeline,
// "" when nothing new happened (or an older summarizer omitted the key).
Milestone string
Confidence float64
}
SummaryOut is the summarizer's fixed JSON.
func ParseSummary ¶
func ParseSummary(output string) (SummaryOut, error)
ParseSummary extracts the summary object from a job's output. It is forgiving about what surrounds the object (code fences, a stream-json result envelope, chatter) but not about its content: an output without any recognised key is an error.
type TargetQuery ¶ added in v0.166.0
TargetQuery is what the session recommendation matches an item by.
type ToTodoInput ¶
type ToTodoInput struct {
// PlanID is an existing plan; empty creates a new plan named NewPlanTitle (default:
// the work item's title).
PlanID string
NewPlanTitle string
// By is the actor label for the plan owner / journal.
By string
}
ToTodoInput picks the destination of the conversion.
type ToTodoResult ¶
type ToTodoResult struct {
TodoID string `json:"todo_id"`
PlanID string `json:"plan_id"`
PlanCreated bool `json:"plan_created"`
}
ToTodoResult says what was created.
type TranscriptSource ¶
type TranscriptSource interface {
ReadTail(ctx context.Context, a jobstore.AgentSession, maxBytes int64) ([]byte, error)
}
TranscriptSource reads the tail of a session's registered transcript (the entry layer adapts the local disk and the worker transcript_tail frame; the service never knows where the file lives).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package transcript turns an agent CLI's own session file into a short list of conversation turns for the work-item summarizer (W2a, design §14.2).
|
Package transcript turns an agent CLI's own session file into a short list of conversation turns for the work-item summarizer (W2a, design §14.2). |