work

package
v0.202.1 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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
View Source
const (
	DispatchSession = "session"
	DispatchJob     = "job"
	DispatchTodo    = "todo"
	DispatchArchive = "archive"
	DispatchDrop    = "drop"
	DispatchIssue   = "issue"
)

Dispatch targets accepted by the HTTP route.

View Source
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.

View Source
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).

View Source
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.

View Source
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.

View Source
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).

View Source
const KindJob = "job"

KindJob marks a SessionBrief whose id is a job id (ACP persistent / pty session).

View Source
const (

	// ParkedStaleSec is the "搁置超过 7 天" digest threshold.
	ParkedStaleSec = 7 * 24 * 3600
)

Variables

View Source
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.

View Source
var ErrEmptyReport = errEmptyReport

ErrEmptyReport is returned for a report that says nothing.

View Source
var ErrMergeSuggestionResolved = errors.New("merge suggestion was already decided")

ErrMergeSuggestionResolved is returned when a suggestion was already decided.

View Source
var ErrNoSession = errors.New("work item has no current session to ask")

ErrNoSession is returned when a request has no current session to ask.

View Source
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.

View Source
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).

View Source
var ErrPlanNotFound = errors.New("plan not found")

ErrPlanNotFound is returned by ToTodo when the chosen plan does not exist.

View Source
var ErrSessionNotFound = errors.New("session not found")

ErrSessionNotFound is returned by SessionTail for an unknown session id.

View Source
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.

View Source
var ErrSuggestionConflict = errors.New("suggestion cannot be applied")

ErrSuggestionConflict is returned when a suggestion cannot be applied any more.

View Source
var ErrSummarizerUnavailable = errors.New("work summarizer unavailable")

ErrSummarizerUnavailable is returned when no usable summarizer agent is configured.

Functions

func ActorKind

func ActorKind(by string) string

ActorKind classifies a speaker label (the web colours the timeline by it).

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

func HealthRank(h string) int

HealthRank is the sort key of a health value (lower = needs attention sooner).

func HumanBy

func HumanBy(caller string) string

HumanBy is the speaker label of a person.

func IssueTypeForKind added in v0.166.0

func IssueTypeForKind(kind string) string

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

func JobActivityAt(j jobstore.JobRecord) int64

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 SessionBy

func SessionBy(sid, agent string) string

SessionBy is the speaker label of a terminal session; agent may be empty.

func SessionOf

func SessionOf(by string) (sid, agent string, ok bool)

SessionOf extracts the session id and agent from a session speaker label.

func StatusLabel

func StatusLabel(st string) string

StatusLabel is the Chinese label of a work-item status (the steward prime and the digest use the same words the board shows).

func StewardBy

func StewardBy(agent string) string

StewardBy is the speaker label of the steward agent.

func SummarizerBy

func SummarizerBy(agent string) string

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

type AlreadyTodoError struct {
	TodoID string
	PlanID string
}

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

type CapturedItem struct {
	Item jobstore.WorkItem
	Text string
}

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

type DeleteFailure struct {
	ID    string `json:"id"`
	Error string `json:"error"`
}

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

type DialectSource interface {
	ConfiguredDialect(agent string) string
}

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 JobProbe

type JobProbe interface {
	JobStates(ids []string) map[string]JobState
}

JobProbe looks up linked jobs' states in one call (job.Service via an adapter).

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
	// Origin is the ceiling owner the job is submitted under ("" = none).
	Origin string
}

OneShotRequest is the summarizer job: a read-only, tool-less run of a cli-agent.

type OneShotResult

type OneShotResult struct {
	JobID string
	// SessionID is the agent session the job ran in (injected or captured by the job
	// layer); recorded so the next tidy-up knows what it is continuing.
	SessionID string
	Output    string
}

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 ResumeRequest added in v0.184.0

type ResumeRequest struct {
	// JobID is the earlier summarizer job whose session is continued.
	JobID      string
	Prompt     string
	ProjectKey string
	Title      string
	TimeoutSec int
	Origin     string
}

ResumeRequest continues the agent session of the project's previous summarizer job instead of opening a new one (the same seam `job resume` uses).

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service owns the work-item rules on top of the store.

func New

func New(store *jobstore.Store) *Service

New builds the service over the shared job store.

func (*Service) AcceptMergeSuggestion

func (s *Service) AcceptMergeSuggestion(id int64, by string) (jobstore.WorkItem, error)

AcceptMergeSuggestion is the person's yes: it performs the merge and closes the suggestion.

func (*Service) AcceptSuggestion

func (s *Service) AcceptSuggestion(id, field, by string) (jobstore.WorkItem, error)

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

func (s *Service) AskSession(ctx context.Context, in AskInput) (AskResult, error)

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

func (s *Service) BackgroundContext() context.Context

BackgroundContext is the context background tasks run under; Close cancels it.

func (*Service) BuildDigest

func (s *Service) BuildDigest(now time.Time) (Digest, error)

BuildDigest renders the digest for now (no side effects).

func (*Service) BuildDigestScoped added in v0.178.0

func (s *Service) BuildDigestScoped(now time.Time, allow func(string) bool) (Digest, error)

BuildDigestScoped is BuildDigest restricted to the caller's项目范围 (gofer-7798 第二期): a non-nil allow keeps only the work items whose project it accepts, and every count is summed over the kept items. The steward's commentary is a server-global text, so it is left out of a scoped digest. nil = every item, the unchanged digest.

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

func (s *Service) Close() error

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

func (s *Service) DismissMergeSuggestion(id int64) error

DismissMergeSuggestion is the person's no.

func (*Service) DismissSuggestion

func (s *Service) DismissSuggestion(id, field, by string) error

DismissSuggestion drops a pending suggestion (the same proposal is not made again).

func (*Service) DispatchClose added in v0.166.0

func (s *Service) DispatchClose(id, to, by string) (jobstore.WorkItem, error)

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: the captured text plus where it came from, see issueDescription), links it (kind issue) and closes 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 closes the capture item after handing it over.

func (*Service) DropShortItems added in v0.179.0

func (s *Service) DropShortItems(items []ItemView, now time.Time) []ItemView

DropShortItems removes the items whose current sessions are ALL short-lived: the steward neither reviews nor primes those. An item with at least one session that is not short stays, and so does an item without a current session (nothing to judge — a hand-made item, a job-only item). A store error keeps every item: a read failure must never silence the steward.

func (*Service) ExistingTodo

func (s *Service) ExistingTodo(id string) (todoID, planID string, ok bool, err error)

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

func (s *Service) IsJobSession(id string) bool

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

func (s *Service) MarkSessionDirty(sid string)

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 prompt is counted, and the work.draft.min_prompts-th one creates the auto draft work item — unless the session has no project or the exclusion lists say no (design 2026-10-20 §总体方案 1: 第 2 次才建、无项目不建、命中排除不建). 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

func (s *Service) Park(id string, until int64, note, by string) (jobstore.WorkItem, error)

Park parks an item: status parked (a person's status), an optional wake-up time and a free-text condition ("到货后继续").

func (*Service) Report

func (s *Service) Report(id string, in ReportInput) (jobstore.WorkItem, error)

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

func (s *Service) SendDigest(now time.Time) (Digest, int, error)

SendDigest builds and sends the digest now (the manual trigger); it reports how many webhooks it was queued for.

func (*Service) SessionBy

func (s *Service) SessionBy(sid string) string

SessionBy returns the canonical speaker label of a registered session.

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

func (s *Service) SetDueHook(fn func(w jobstore.WorkItem, reason string, at int64))

SetDueHook installs the observer of announced reminders / park deadlines (nil = none).

func (*Service) SetJobProbe

func (s *Service) SetJobProbe(p JobProbe)

SetJobProbe injects the linked-job lookup (nil = jobs never influence the status).

func (*Service) SetLanguageFor added in v0.198.0

func (s *Service) SetLanguageFor(f func(project string) i18n.Lang)

SetLanguageFor injects the config's language resolution (config.LanguageFor): the language of every text this service sends into a session.

func (*Service) SetMessenger

func (s *Service) SetMessenger(m Messenger)

SetMessenger injects the delivery seam (nil = requests cannot be delivered and are turned into a tidy-up straight away).

func (*Service) SetNotifier

func (s *Service) SetNotifier(n Notifier)

SetNotifier injects the notification seam (nil = no notifications).

func (*Service) SetNow

func (s *Service) SetNow(fn func() time.Time)

SetNow overrides the clock (tests).

func (*Service) SetOneShot

func (s *Service) SetOneShot(o OneShot)

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) SetSettings added in v0.179.0

func (s *Service) SetSettings(st Settings)

SetSettings injects the extension settings. nil (or a nil service) means "registry defaults", so a service built without one behaves like a fresh install.

func (*Service) SetTranscriptSource

func (s *Service) SetTranscriptSource(t TranscriptSource)

SetTranscriptSource injects the transcript reader (nil = always degraded input).

func (*Service) ShortSession added in v0.179.0

func (s *Service) ShortSession(a jobstore.AgentSession, now time.Time) (string, bool)

ShortSession reports whether the session is a short-lived one the summarizer and the steward skip, with the reason (design §关键流程). The thresholds are the extension settings; a settings read failure falls back to the registry defaults.

func (*Service) StallAfter

func (s *Service) StallAfter() time.Duration

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) Store

func (s *Service) Store() *jobstore.Store

Store exposes the underlying store for the entry layers' simple reads.

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) Summarize

func (s *Service) Summarize() (Summary, error)

Summarize returns the header counts.

func (*Service) SummarizerStatus

func (s *Service) SummarizerStatus() SummarizerStatus

SummarizerStatus reports the effective summarizer configuration and availability.

func (*Service) SyncAll

func (s *Service) SyncAll()

SyncAll re-syncs every open auto-status item.

func (*Service) SyncItem

func (s *Service) SyncItem(id string)

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

func (s *Service) Tick(now time.Time)

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) TidyNowFor added in v0.172.0

func (s *Service) TidyNowFor(itemID, by, origin string) (jobstore.WorkRequest, error)

TidyNowFor is TidyNow for a request made by a caller with a ceiling owner: the tidy-up job is submitted under `origin` (see SummarizeOpts.Origin).

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.

func (*Service) Update

func (s *Service) Update(id string, p jobstore.WorkItemPatch, expectedRev int64, by string) (jobstore.WorkItem, error)

Update applies a patch with the cross-field rules the store does not know: filling in the goal of a draft marks it sorted.

func (*Service) WaitIdle

func (s *Service) WaitIdle()

WaitIdle blocks until every background task started so far has finished (tests).

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 SessionKeeper added in v0.184.0

type SessionKeeper interface {
	CanContinueSession(agent string) bool
}

SessionKeeper is the optional second face of a OneShot: whether a finished summarizer job's agent session can be continued (the agent has a session_resume template). Only then does the project keep ONE session instead of opening one per tidy-up; every other agent keeps the old behaviour.

type SessionResumer added in v0.184.0

type SessionResumer interface {
	Resume(ctx context.Context, r ResumeRequest) (OneShotResult, error)
}

SessionResumer is the optional third face of a OneShot: continue the agent session of a previous summarizer job (the entry layer adapts job.Service.ResumeJob).

type SessionSayer

type SessionSayer interface {
	SaySession(jobID, text string) error
}

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 Settings added in v0.179.0

type Settings interface {
	GetInt(key string) (int, error)
	GetString(key string) (string, error)
	GetStrings(key string) ([]string, error)
	Patterns(key string) ([]*regexp.Regexp, error)
}

Settings is the slice of the extension-settings service (internal/settings) the noise rules read. An interface keeps this package off the entry layers and lets a test supply its own values (G022).

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
	// Origin is the ceiling owner of the tidy-up job: the caller that asked for it. Empty
	// for a run nobody asked for (the timer, a session event).
	Origin 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 Summary

type Summary struct {
	NeedsMe int `json:"needs_me"`
	Due     int `json:"due"`
	Open    int `json:"open"`
}

Summary counts for the page header and the badge.

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

type TargetQuery struct {
	Text    string
	Project string
}

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).

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).

Jump to

Keyboard shortcuts

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