tasks

package
v0.48.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 27 Imported by: ? 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 tasks is the installation-wide task authority: one SQLite database shared by every session, the CLI and the serve process. The owner sees and edits everything; an agent only reaches its own checklist, its own open requests to the owner and its project's backlog, through Actor-scoped methods that enforce that inside the transaction.

Index

Constants

View Source
const (
	HandoffAwaiting = "awaiting_permission"
	HandoffSent     = "sent"
	HandoffDeclined = "declined"
)

Handoff states. awaiting_permission is a request in You (the user decides); sent is a task on the recipient's checklist; declined is closed unsent.

View Source
const (
	OutcomeDone   = "done"
	OutcomeCantDo = "cant_do"
)

Outcomes of a closed task between owners.

View Source
const (
	HandoffActionSend    = "send"
	HandoffActionDecline = "decline"
)

The user's answers to a request awaiting permission. Always allow is send plus a permission the caller stores in owner.json first.

View Source
const (
	AuthorHuman   = "human"
	AuthorSession = "session"
)

Comment authors.

View Source
const (
	StatusPending    = "pending"
	StatusInProgress = "in_progress"
	StatusDone       = "done"
)

Task statuses. The UI maps pending→open and in_progress→working.

View Source
const (
	NewsDone     = "done"
	NewsDeployed = "deployed"
	NewsProblem  = "problem"
	NewsInfo     = "info"
)

News kinds.

View Source
const (
	NoticePending   = "pending"
	NoticeHeld      = "held"
	NoticeSent      = "sent"
	NoticeDelivered = "delivered"
	NoticeFailed    = "failed"
)

Notice states. pending is waiting for the dispatcher (with a Reason when an attempt could not deliver it); held waits for its saved session to be opened; sent reserves a delivery attempt and waits to be seen in the persisted transcript; delivered is there; failed is terminal.

View Source
const (
	ReasonSessionDeleted  = "session_deleted"
	ReasonSessionLimit    = "session_limit"
	ReasonQuestionPending = "question_pending"
)

Reasons a notice is not delivered.

View Source
const (
	DeliverWake = "wake"
	DeliverHold = "hold"
)

Deliver modes for a recipient that is saved but not loaded: wake resumes it, hold waits until the owner opens it. Anything else means hold: a session is never woken without the owner choosing to.

View Source
const (
	MethodRun    = "run"
	MethodAppend = "append"
)

Delivery methods. run starts (or steers into) a turn; append only adds the notice to the transcript, used after the owner discarded its steer.

View Source
const (
	WorkDue     = "due"
	WorkDone    = "done"
	WorkStopped = "stopped"
)

Work says whether the answer's event still owes the model a continuation, apart from the transport state of its outbox row. due: the answer was accepted and the run that must read it has not finished; done: it has; stopped: Stop or a recall cancelled that run, the event is only appended.

View Source
const (
	OriginAskUser     = "ask_user"
	OriginRequestCall = "request_call"
)

Origin tools a question can come from.

View Source
const (
	WhenOnce   = "once"
	WhenRepeat = "repeat"
)

When kinds.

View Source
const (
	TargetSession = "session"
	TargetOwner   = "owner"
	TargetNew     = "new"
)

Target kinds: an exact session, an owner entity (resolved to its current conversation when a run is released), or a new session in a project.

View Source
const (
	BusySteer = "steer"
	BusyWait  = "wait"
	LateAsk   = "ask"
	LateRun   = "run"
	LateSkip  = "skip"
)

Delivery policies. Busy: steer into a working session or wait until it is idle. Saved: see DeliverWake/DeliverHold. Late: what a run found 10 minutes or more after its due time does.

View Source
const (
	OccLate     = "late"
	OccReady    = "ready"
	OccAssigned = "assigned"
	OccDone     = "done"
	OccFailed   = "failed"
	OccSkipped  = "skipped"
)

Occurrence states. late waits for the owner's decision; ready is authorized and waits for its child and assignment; assigned has both; failed could not be sent and needs the owner; done and skipped are final.

View Source
const (
	TriggerTimer    = "timer"
	TriggerRunNow   = "run_now"
	TriggerSkipNext = "skip_next"
	TriggerLegacy   = "legacy"
)

What consumed an occurrence's slot.

View Source
const (
	ReasonLateSkip             = "late_skip"
	ReasonOwnerSkip            = "owner_skip"
	ReasonRegated              = "regated"
	ReasonChildDone            = "child_done"
	ReasonChildRemoved         = "child_removed"
	ReasonScheduleDeleted      = "schedule_deleted"
	ReasonSuperseded           = "superseded"
	ReasonLegacyDelivered      = "legacy_delivered"
	ReasonTemplateInvalid      = "template_invalid"
	ReasonRerouted             = "rerouted"
	ReasonDeletedDuringDeliver = "session_deleted_during_delivery"
	ReasonDeletedAfterDeliver  = "session_deleted_after_delivery"
	// ReasonUncertain: the assignment was reserved for delivery but its
	// admission was never recorded, so it may or may not have reached its
	// session. It is never sent again without the owner.
	ReasonUncertain = "delivery_uncertain"
)

Occurrence reasons. Failure codes that the serve layer decides (owner missing, session limit, …) are free-form strings stored as given.

View Source
const (
	FreqDaily    = "daily"
	FreqWeekdays = "weekdays"
	FreqWeekly   = "weekly"
	FreqMonthly  = "monthly"
)

Recurrence frequencies.

View Source
const DatabaseName = "tasks.sqlite"

DatabaseName is the file inside the config directory.

View Source
const DeclinedNote = "Declined by the owner"

DeclinedNote is the completion note of a declined request.

View Source
const LateAfter = 10 * time.Minute

LateAfter is the first-observation delay from which a run is late: exactly ten minutes is late, a millisecond less is not.

View Source
const NewsKeep = 7 * 24 * time.Hour

NewsKeep is how long a read item stays listed (For you › Earlier).

View Source
const NoticeSourceName = "tasks"

NoticeSourceName is custom.source_name on a notice's transcript message.

View Source
const ReasonRewound = "rewound"

ReasonRewound closes a question whose origin the conversation left.

Variables

View Source
var (
	// ErrNotFound covers both "does not exist" and "not visible to you": an
	// agent must not be able to tell them apart.
	ErrNotFound = errors.New("not available")
	// ErrForbidden is a visible task the caller may not change.
	ErrForbidden = errors.New("not allowed to change this task")
	// ErrClaimed means another session claimed the task first.
	ErrClaimed = errors.New("task already claimed")
	// ErrInvalid wraps validation failures (message says which).
	ErrInvalid = errors.New("invalid task")
	// ErrSchemaTooNew means the database was written by a newer moa: reads work,
	// writes are refused and nothing is reset.
	ErrSchemaTooNew = errors.New("tasks database was written by a newer moa; update moa to change tasks")
	// ErrUnavailable means the database location cannot be resolved.
	ErrUnavailable = errors.New("tasks database unavailable")
)

Sentinel errors. Handlers map them to 404/403/409/400.

View Source
var (
	// ErrQuestionNotFound is an unknown question, or one of another session.
	ErrQuestionNotFound = fmt.Errorf("question %w", ErrNotFound)
	// ErrAnswerCount is an answer whose length is not the question's.
	ErrAnswerCount = errors.New("wrong number of answers")
)

Errors of the question store. They are typed so a caller can tell a stale request from a lost one without parsing messages.

View Source
var ErrNoticeNotFound = fmt.Errorf("notice %w", ErrNotFound)

ErrNoticeNotFound is an unknown notice ID.

View Source
var ErrOccurrenceNotFound = fmt.Errorf("run %w", ErrNotFound)

ErrOccurrenceNotFound is an unknown occurrence ID.

Functions

func ChildVariant added in v0.46.0

func ChildVariant(t core.Tool) (core.Tool, bool)

ChildVariant is the tasks tool as a subagent sees it: the owner's tool without send, whose schema and description are those of a plain session. A child inherits its parent's tools but does not speak for the owner. It reports false for any tool that is not an owner's tasks tool. The refusal itself lives in Execute (see actsForOwner), so selecting the tool by name cannot bypass this.

func LoadZone added in v0.45.0

func LoadZone(name string) (*time.Location, error)

LoadZone validates an IANA zone name. "Local" and empty names are refused: a schedule never silently follows the server's zone.

func NewQuestionID added in v0.47.0

func NewQuestionID() string

NewQuestionID mints a question ID. It is global: random, never a counter.

func NewTool

func NewTool(scope *Scope) core.Tool

NewTool returns the tasks tool for one session. Who is asking is the scope's identity, injected at bootstrap; the arguments cannot name another session or project. The one exception is send, offered only to an owner's conversation, which names another owner (never its session).

func NextSlot added in v0.45.0

func NextSlot(rule Rule, after time.Time, loc *time.Location) (time.Time, error)

NextSlot is the first instant of rule strictly after after, in loc. Days are walked in civil-date space, never by adding 24h to an instant, and each is resolved with ResolveWall, so the repeated hour of a DST overlap is never a second slot and a gap slot moves forward instead of disappearing.

func ResolveWall added in v0.45.0

func ResolveWall(y int, m time.Month, d, h, mi int, loc *time.Location) (time.Time, bool, error)

ResolveWall returns the instant of the civil date and wall time y-m-d h:mi in loc. The civil date must exist (31 February is an error, not 3 March). When the wall time happens twice (clocks going back) the earlier instant wins; when it does not happen at all (clocks going forward) it is moved forward by the length of the gap, keeping its minutes, and adjusted is true. time.Date is not used to pick: its choice in both cases is unspecified.

Types

type Actor added in v0.45.0

type Actor struct {
	SessionID  string
	ProjectKey string // core.CodebaseKey(cwd); "" when unknown
	ProjectCWD string
	// TZ is the IANA zone of the device that created the session, "" when
	// unknown. Scheduling by the agent uses it (UTC when unknown).
	TZ string
	// Owner says the actor is its project's owner conversation itself (not
	// a subagent): it also lists, and may withdraw, the requests to the user
	// that its project's sessions made.
	Owner bool
}

Actor is the identity an agent's tool call acts with. It is injected by bootstrap; the model never supplies it.

type AgentInput added in v0.45.0

type AgentInput struct {
	Title       string
	Description string
	DependsOn   []int64
	Subtasks    []SubtaskInput
}

AgentInput creates a checklist task or a request.

type AgentPatch added in v0.45.0

type AgentPatch struct {
	Title       *string
	Description *string
	Status      *string // pending or in_progress; completing goes through Done
	DependsOn   *[]int64
	Subtasks    *[]SubtaskInput
}

AgentPatch is a partial agent edit of a task it may edit.

type AgentTask added in v0.45.0

type AgentTask struct {
	ID             int64  `json:"id"`
	Title          string `json:"title"`
	Description    string `json:"description,omitempty"`
	Status         string `json:"status"`
	Place          Place  `json:"place"`
	CompletionNote string `json:"completion_note,omitempty"`
	CompletedAt    int64  `json:"completed_at,omitempty"`
	// Archived marks a task past the archive window; only list's archived and
	// search options (and get) reach it.
	Archived     bool      `json:"archived,omitempty"`
	CommentCount int       `json:"comment_count,omitempty"`
	Subtasks     []Subtask `json:"subtasks,omitempty"`
	// WaitsFor lists readable tasks this one waits for.
	WaitsFor []int64 `json:"waits_for,omitempty"`
	// PrivateBlockers counts open tasks this one waits for that the agent
	// cannot read: shown as "Blocked by a private task", with no title, note or
	// usable ID.
	PrivateBlockers int     `json:"private_blockers,omitempty"`
	Unblocks        []int64 `json:"unblocks,omitempty"`

	// A template the agent created for itself: when it runs.
	When          *When  `json:"when,omitempty"`
	TZ            string `json:"tz,omitempty"`
	Next          int64  `json:"next,omitempty"`
	ScheduleState string `json:"schedule_state,omitempty"`

	// A task between owners: who sent it (to its recipient) or to whom (to
	// its sender), where it stands, and (on get) its thread. Names only:
	// never a session or a project.
	From         string        `json:"from,omitempty"`
	To           string        `json:"to,omitempty"`
	HandoffState string        `json:"handoff_state,omitempty"`
	Outcome      string        `json:"outcome,omitempty"`
	Thread       []ThreadEntry `json:"thread,omitempty"`
}

AgentTask is what an agent may know about a task: never who else is involved, and never the identity of a task it cannot read. A dependency on such a task is only a count.

type AgentView added in v0.45.0

type AgentView struct {
	Checklist []AgentTask `json:"checklist"`
	Requests  []AgentTask `json:"requests"`
	Backlog   []AgentTask `json:"backlog"`
	// Scheduled are the templates this session created for itself. They are
	// not on its checklist: each run arrives as its own task.
	Scheduled []AgentTask `json:"scheduled,omitempty"`
	// Sent are the tasks this owner sent to other owners, whatever their state.
	Sent []AgentTask `json:"sent,omitempty"`
	// ProjectRequests are, for an owner, the requests to the user that the
	// other sessions of its project made, so it can find and withdraw them.
	ProjectRequests []AgentTask `json:"project_requests,omitempty"`
}

AgentView is the default listing of an agent.

type CallState added in v0.47.0

type CallState string

CallState is where a question's escalation is.

const (
	CallNone        CallState = ""
	CallPending     CallState = "pending"
	CallCalling     CallState = "calling"
	CallMissed      CallState = "missed"
	CallInterrupted CallState = "interrupted"
	CallCancelled   CallState = "cancelled"
	CallDone        CallState = "done"
)

type Comment added in v0.46.0

type Comment struct {
	ID              int64  `json:"id"`
	TaskID          int64  `json:"task_id"`
	AuthorKind      string `json:"author_kind"`
	AuthorSessionID string `json:"author_session_id,omitempty"`
	AuthorName      string `json:"author_name,omitempty"`
	Body            string `json:"body"`
	CreatedAt       int64  `json:"created_at"`
}

Comment is one entry of a task's thread.

type ConflictError added in v0.45.0

type ConflictError struct{ Current Record }

ConflictError is a stale revision. Current is the task as it is now, so the caller can show it instead of guessing.

func (*ConflictError) Error added in v0.45.0

func (e *ConflictError) Error() string

type Counts added in v0.45.0

type Counts struct {
	OpenRequests int `json:"open_requests"`
	// LateOccurrences are runs waiting for the owner's Run or Skip, counted
	// per run (a paused template's included); Attention adds them to the
	// open requests for the footer.
	LateOccurrences int `json:"late_occurrences"`
	Attention       int `json:"attention"`
	You             int `json:"you"`
	Backlog         int `json:"backlog"`
	Agents          int `json:"agents"`
}

Counts summarizes a listing. OpenRequests is the number the sidebar shows: only requests agents made that are still open.

type CreateInput added in v0.45.0

type CreateInput struct {
	Title       string
	Description string
	Place       Place
	Status      string // default pending

	// ProjectKey wins over ProjectCWD; with only a CWD the key is derived from
	// it (core.CodebaseKey), so worktrees of one repo share a project.
	ProjectKey string
	ProjectCWD string

	RequesterSessionID string // PlaceYou only: makes it a request from that session
	AssigneeSessionID  string // PlaceAgent only

	Subtasks []SubtaskInput
	WaitsFor []int64

	// Deliver is the owner's choice for a saved recipient: DeliverWake or
	// DeliverHold ("" means hold). A loaded recipient gets the notice at once.
	Deliver string

	// Schedule makes the task a scheduled template: a private task of yours
	// that the scheduler turns into runs. It has no requester or assignee.
	Schedule *ScheduleDef
}

CreateInput is a task written by the owner (UI, REST or CLI).

type Delivery added in v0.45.0

type Delivery struct {
	Busy  string `json:"busy"`
	Saved string `json:"saved"`
	Late  string `json:"late"`
}

Delivery is a template's delivery policy.

func DecodeDelivery added in v0.45.0

func DecodeDelivery(b []byte) (Delivery, error)

DecodeDelivery parses a delivery object strictly; missing fields take the schedule defaults (steer, wake, ask).

type Destination added in v0.45.0

type Destination struct {
	SessionID  string
	ProjectKey string
	ProjectCWD string
}

Destination is the session a run was resolved to, with its actual project.

type ErrQuestionConflict added in v0.47.0

type ErrQuestionConflict struct{ State QuestionState }

ErrQuestionConflict means the question is already closed in a way that does not match the request.

func (*ErrQuestionConflict) Error added in v0.47.0

func (e *ErrQuestionConflict) Error() string

type ErrQuestionOpen added in v0.47.0

type ErrQuestionOpen struct{ ID string }

ErrQuestionOpen means the session already has an open question (the bound of the first pilot is one per session). ID is that question.

func (*ErrQuestionOpen) Error added in v0.47.0

func (e *ErrQuestionOpen) Error() string

type Filter added in v0.45.0

type Filter struct {
	// ProjectKey limits backlog and agent tasks to one project. Tasks in You
	// are the owner's own and are always returned.
	ProjectKey      string
	IncludeAgents   bool
	IncludeArchived bool
}

Filter narrows an owner listing.

type Handoff added in v0.46.0

type Handoff struct {
	FromOwnerID   string `json:"from_owner_id"`
	FromOwnerName string `json:"from_owner_name"`
	ToOwnerID     string `json:"to_owner_id"`
	ToOwnerName   string `json:"to_owner_name"`
	State         string `json:"state"`
	Outcome       string `json:"outcome,omitempty"`
	// contains filtered or unexported fields
}

Handoff is what makes a task one owner's task for another. Names are copied when it is sent, so the task still says who asked after a rename or a deleted owner. Session IDs stay inside the package.

type LastRun added in v0.47.0

type LastRun struct {
	DueAt       int64  `json:"due_at"`
	State       string `json:"state"`
	CompletedAt int64  `json:"completed_at,omitempty"`
}

LastRun is a template's latest run, as a list row shows it.

type LegacySchedule added in v0.45.0

type LegacySchedule struct {
	ID        string
	SessionID string
	Text      string
	DueAt     int64 // Unix ms
	TZ        string
	CreatedAt int64 // Unix ms, 0 for now
	// Delivered: the old scheduler's prompt for it is already in the
	// session's transcript. It is imported as settled, never offered again.
	Delivered bool
}

LegacySchedule is one pending record of the old schedules.json.

type ListResult added in v0.45.0

type ListResult struct {
	Tasks    []Record `json:"tasks"`
	Counts   Counts   `json:"counts"`
	Revision int64    `json:"revision"`
}

ListResult is an owner listing with the global revision it was read at.

type News added in v0.47.0

type News struct {
	ID        string
	SessionID string
	Key       string
	Kind      string
	Title     string
	Body      string
	Revision  int64
	CreatedAt int64
	UpdatedAt int64
	ReadAt    int64
}

News is one item. Times are Unix milliseconds by the repository's clock; ReadAt is 0 while unread.

type NewsAck added in v0.47.0

type NewsAck struct {
	ID       string
	Revision int64
}

NewsAck acknowledges one revision of an item as read.

type NewsInput added in v0.47.0

type NewsInput struct {
	SessionID string
	Key       string
	Kind      string
	Title     string
	Body      string
	Origin    string
}

NewsInput is a publish. Origin identifies the invocation (message and tool call) that published it: the same invocation retried is the same item, not an update.

type NewsOutcome added in v0.47.0

type NewsOutcome string

NewsOutcome says what a publish did.

const (
	NewsCreated   NewsOutcome = "created"
	NewsUpdated   NewsOutcome = "updated"
	NewsDuplicate NewsOutcome = "duplicate" // a retry of the invocation that already published it
)

type NewsPublished added in v0.47.0

type NewsPublished struct {
	News
	Outcome NewsOutcome
}

NewsPublished is the item after a publish and what the publish did.

type Notice added in v0.45.0

type Notice struct {
	ID                 string     `json:"id"`
	TaskID             int64      `json:"task_id"`
	Kind               NoticeKind `json:"kind"`
	RecipientSessionID string     `json:"recipient_session_id"`
	State              string     `json:"state"`
	Reason             string     `json:"reason,omitempty"`
	CreatedAt          int64      `json:"created_at"`
	DeliveredAt        int64      `json:"delivered_at,omitempty"`

	Deliver   string `json:"-"`
	Method    string `json:"-"`
	Title     string `json:"-"`
	Text      string `json:"-"`
	SteerID   string `json:"-"`
	UpdatedAt int64  `json:"-"`
}

Notice is one event for a session, written in the same transaction as the gesture that caused it. Title and Text are rendered at commit, so the notice still says what happened after its task is gone.

type NoticeChange added in v0.45.0

type NoticeChange struct {
	From    []string
	State   string
	Reason  string
	Method  string // "" keeps the current one
	SteerID string
	// Admitted records that the session accepted the notice's input. For a
	// scheduled assignment it stamps the run's admitted_at; delivered implies it.
	Admitted bool
}

NoticeChange is a state transition. From lists the states it may leave, so a transition decided on a stale read (delivered meanwhile, say) changes nothing.

type NoticeKind added in v0.45.0

type NoticeKind string

NoticeKind says which owner gesture a notice reports.

const (
	NoticeHandoff         NoticeKind = "handoff"
	NoticeComment         NoticeKind = "comment"
	NoticeHandoffClosed   NoticeKind = "handoff_closed"
	NoticeHandoffDeclined NoticeKind = "handoff_declined"
)

Notice kinds of tasks between owners and of threads.

const (
	NoticeAssigned     NoticeKind = "assigned"
	NoticeUpdated      NoticeKind = "updated"
	NoticeRequestDone  NoticeKind = "request_done"
	NoticeAgentDone    NoticeKind = "agent_done"
	NoticeAgentDeleted NoticeKind = "agent_deleted"
)
const NoticeQuestionAnswer NoticeKind = "question_answer"

NoticeQuestionAnswer is the kind of the outbox row that carries an answer to the session that asked. Its task_id is 0.

type Occurrence added in v0.45.0

type Occurrence struct {
	ID             int64  `json:"id"`
	ScheduleTaskID int64  `json:"schedule_task_id"`
	Revision       int64  `json:"revision"`
	DueAt          int64  `json:"at"`
	State          string `json:"state"`
	Trigger        string `json:"trigger"`
	Reason         string `json:"reason,omitempty"`
	Note           string `json:"note,omitempty"`
	ChildTaskID    int64  `json:"child_task_id,omitempty"`
	SessionID      string `json:"session_id,omitempty"`
	NoticeID       string `json:"notice_id,omitempty"`
	ObservedAt     int64  `json:"observed_at"`
	ConfirmedAt    int64  `json:"confirmed_at,omitempty"`
	AdmittedAt     int64  `json:"admitted_at,omitempty"`
	CompletedAt    int64  `json:"completed_at,omitempty"`
	MissedCount    int    `json:"missed_count,omitempty"`

	DefinitionRevision int64          `json:"-"`
	Spec               OccurrenceSpec `json:"-"`
	// ReservedSessionID is the session a run for a new session creates, set
	// before it exists and kept for good. SessionID is where the run is
	// delivered now; a reroute changes it and the snapshot's target.
	ReservedSessionID string `json:"-"`
	CreatedAt         int64  `json:"-"`
	UpdatedAt         int64  `json:"-"`
}

Occurrence is one consumed slot of a template: its history row and, once authorized, the link to its child task and current assignment notice.

type OccurrenceConflictError added in v0.45.0

type OccurrenceConflictError struct {
	Current Occurrence
	Msg     string
}

OccurrenceConflictError is a stale occurrence revision or state. Msg, when set, says why in the owner's words.

func (*OccurrenceConflictError) Error added in v0.45.0

func (e *OccurrenceConflictError) Error() string

type OccurrenceSpec added in v0.45.0

type OccurrenceSpec struct {
	V                  int           `json:"v"`
	Title              string        `json:"title"`
	Description        string        `json:"description,omitempty"`
	Subtasks           []SpecSubtask `json:"subtasks,omitempty"`
	WaitsFor           []int64       `json:"waits_for,omitempty"`
	ProjectKey         string        `json:"project_key,omitempty"`
	ProjectCWD         string        `json:"project_cwd,omitempty"`
	When               When          `json:"when"`
	TZ                 string        `json:"tz"`
	Target             Target        `json:"target"`
	Delivery           Delivery      `json:"delivery"`
	CreatedBySessionID string        `json:"created_by_session_id,omitempty"`
}

OccurrenceSpec is the snapshot of a template taken when its slot is consumed. Later edits of the template never reach it; only the owner's reroute changes it, replacing its target with the chosen session.

type OwnerDirectory added in v0.46.0

type OwnerDirectory interface {
	// OwnerOf returns the owner whose conversation is sessionID.
	OwnerOf(sessionID string) (OwnerRef, bool, error)
	// Find resolves an owner by ID or by name.
	Find(nameOrID string) (OwnerRef, bool, error)
	// CanSend reports whether fromID may send tasks to toID without asking
	// the user. One-way.
	CanSend(fromID, toID string) (bool, error)
}

OwnerDirectory resolves owners for the tasks tool. It is implemented outside this package, over owner.json, and read on every call: a permission revoked in Edit owner applies to the very next send.

type OwnerRef added in v0.46.0

type OwnerRef struct {
	ID         string
	Name       string
	SessionID  string
	ProjectKey string
	ProjectCWD string
}

OwnerRef is a project owner as a task between owners records it: its identity, its conversation and the project a task sent to it belongs to.

type ParseError added in v0.45.0

type ParseError struct {
	Code string `json:"code"`
	Msg  string `json:"error"`
	At   int64  `json:"at,omitempty"`
}

ParseError is a "when" that could not be read. Code is one of unknown, repeat, invalid or past; At is the instant that was in the past.

func (*ParseError) Error added in v0.45.0

func (e *ParseError) Error() string

func (*ParseError) Unwrap added in v0.45.0

func (e *ParseError) Unwrap() error

type Parsed added in v0.45.0

type Parsed struct {
	When     When   `json:"when"`
	TZ       string `json:"tz"`
	Next     int64  `json:"next"`
	Alt      int64  `json:"alt,omitempty"`
	Adjusted bool   `json:"adjusted,omitempty"`
}

Parsed is a natural-language "when" resolved in a zone: the canonical definition, the first instant it fires and, for a once time whose hour was not qualified, the same time in the other half of the day.

func ParseWhen added in v0.45.0

func ParseWhen(text string, now time.Time, tz string) (*Parsed, error)

ParseWhen reads text in tz, relative to now. Empty text returns nil, nil: nothing has been chosen. Relative amounts are elapsed time; every calendar choice is resolved with the same civil resolver the planner uses.

type Patch added in v0.45.0

type Patch struct {
	Title       *string
	Description *string
	Status      *string
	Place       *Place // a move: an explicit gesture, see applyMove

	ProjectKey        *string
	ProjectCWD        *string
	AssigneeSessionID *string
	CompletionNote    *string
	// Outcome closes a task between owners as done or cant_do (which needs
	// a note). Only such a task accepts it.
	Outcome *string

	Subtasks *[]SubtaskInput
	WaitsFor *[]int64

	// Notify is "Save and notify": the saved task is sent to its assignee (or
	// to the requester of a request). Assigning or completing notifies anyway.
	Notify  bool
	Deliver string // see CreateInput.Deliver

	// Schedule replaces a template's definition, from its next unconsumed
	// slot on. Only a template accepts it.
	Schedule *ScheduleDef
}

Patch is a partial owner edit; nil fields are left alone.

type Place added in v0.45.0

type Place string

Place says who a task belongs to, and therefore who can see it.

const (
	// PlaceYou is the owner's. With a requester it is a request an agent asked
	// for; without one it is a private note no agent ever sees.
	PlaceYou Place = "you"
	// PlaceBacklog is a project's shared pool; agents of that project can claim.
	PlaceBacklog Place = "backlog"
	// PlaceAgent is one session's checklist (or a task assigned to it).
	PlaceAgent Place = "agent"
)

type Project added in v0.45.0

type Project struct {
	Key string `json:"key"`
	CWD string `json:"cwd,omitempty"`
}

Project is a project the owner can file tasks under.

type Question added in v0.47.0

type Question struct {
	ID        string
	SessionID string
	// OriginMsgID, OriginToolCallID and SessionID identify the invocation that
	// posted it: a retry of the same call finds the same question.
	OriginMsgID      string
	OriginToolCallID string
	OriginTool       string
	Questions        []askuser.Question
	RequiresTap      bool
	State            QuestionState
	Reason           string
	// Ack is exactly what the posting call returned, kept so a call whose
	// result never reached the transcript can be closed with the same result.
	Ack       QuestionAck
	Answers   []string
	Responder askuser.Responder
	EventID   string
	Work      string
	AskedAt   int64
	ClosedAt  int64
	UpdatedAt int64
	// CallDueAt (UTC milliseconds, 0 = none), CallState and CallAttempt are
	// the question's escalation to a call (question_calls.go).
	CallDueAt   int64
	CallState   CallState
	CallAttempt string
}

Question is one posted batch. Everything but State, Reason, Answers, Responder, EventID, Work and the times is immutable after the post.

type QuestionAck added in v0.47.0

type QuestionAck struct {
	Text   string         `json:"text"`
	Custom map[string]any `json:"custom,omitempty"`
}

QuestionAck is the tool result of a post: text for the model, metadata for the transcript.

type QuestionAnswerResult added in v0.47.0

type QuestionAnswerResult struct {
	Question Question
	// Duplicate: the same responder had already given the same answers; nothing
	// was written.
	Duplicate bool
}

QuestionAnswerResult is what an accepted answer produced.

type QuestionState added in v0.47.0

type QuestionState string

QuestionState is where a question is in its life. open is the only state that can change; the others are terminal.

const (
	QuestionOpen        QuestionState = "open"
	QuestionAnswered    QuestionState = "answered"
	QuestionWithdrawn   QuestionState = "withdrawn"
	QuestionDismissed   QuestionState = "dismissed"
	QuestionInvalidated QuestionState = "invalidated"
)

type Record added in v0.45.0

type Record struct {
	ID                 int64     `json:"id"`
	Title              string    `json:"title"`
	Description        string    `json:"description,omitempty"`
	Status             string    `json:"status"`
	Place              Place     `json:"place"`
	ProjectKey         string    `json:"project_key,omitempty"`
	ProjectCWD         string    `json:"project_cwd,omitempty"`
	RequesterSessionID string    `json:"requester_session_id,omitempty"`
	AssigneeSessionID  string    `json:"assignee_session_id,omitempty"`
	CompletionNote     string    `json:"completion_note,omitempty"`
	CreatedAt          int64     `json:"created_at"`
	UpdatedAt          int64     `json:"updated_at"`
	CompletedAt        int64     `json:"completed_at,omitempty"`
	ArchivedAt         int64     `json:"archived_at,omitempty"`
	Revision           int64     `json:"revision"`
	Subtasks           []Subtask `json:"subtasks,omitempty"`
	WaitsFor           []int64   `json:"waits_for,omitempty"`
	Unblocks           []int64   `json:"unblocks,omitempty"`
	// NoticeState is set in listings when the task's latest notice has not
	// reached its session (held, pending or failed).
	NoticeState string `json:"notice_state,omitempty"`

	// Scheduled template fields, set only on a template.
	When               *When       `json:"when,omitempty"`
	TZ                 string      `json:"tz,omitempty"`
	Target             *Target     `json:"target,omitempty"`
	Delivery           *Delivery   `json:"delivery,omitempty"`
	Next               int64       `json:"next,omitempty"`
	ScheduleState      string      `json:"schedule_state,omitempty"`
	CreatedBySessionID string      `json:"created_by_session_id,omitempty"`
	LateCount          int         `json:"late_count,omitempty"`
	Failure            *RunFailure `json:"failure,omitempty"`
	// RunStats summarizes a template's runs so a list can say how long it
	// has been running and when it last ran without opening its detail.
	RunStats *RunStats `json:"run_stats,omitempty"`
	// KeptAt is when the user said Keep to a recurring task that runs on
	// its own; 0 while nobody has reviewed it.
	KeptAt int64 `json:"kept_at,omitempty"`

	// A run's child task links back to its template and occurrence.
	ParentTaskID int64 `json:"parent_task_id,omitempty"`
	OccurrenceID int64 `json:"occurrence_id,omitempty"`

	// Handoff is set on a task one owner sent to another; CommentCount is
	// the length of its thread (tasks between owners and agents' requests).
	Handoff      *Handoff `json:"handoff,omitempty"`
	CommentCount int      `json:"comment_count,omitempty"`
	// contains filtered or unexported fields
}

Record is a task as the owner sees it, with its relations.

type RenderAnswer added in v0.47.0

type RenderAnswer func(q Question) (title, text string)

RenderAnswer turns an accepted answer into the title and the text the session will read. It runs inside the answer's transaction.

type Repo added in v0.45.0

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

Repo is the shared task database. It opens lazily: a process that never touches tasks never creates the file, and reads of a database that does not exist yet see no tasks instead of creating one.

func New added in v0.45.0

func New(path string) *Repo

New returns a repository on path. Nothing touches the disk until first use.

func Shared added in v0.45.0

func Shared() *Repo

Shared returns the process-wide repository for the current config directory. Runtime, CLI and serve all go through it, so there is one writer connection per process and never a per-session copy.

func (*Repo) AbandonQuestionAnswer added in v0.47.0

func (r *Repo) AbandonQuestionAnswer(ctx context.Context, eventID, reason string) (bool, error)

AbandonQuestionAnswer ends an answer whose conversation branch was left before it was admitted: the event fails (reason) and the run it would have caused is stopped, in one transaction. An answer already admitted is left alone; it reports false.

func (*Repo) AgentAsk added in v0.45.0

func (r *Repo) AgentAsk(ctx context.Context, a Actor, in AgentInput) (AgentTask, error)

AgentAsk files a request to the owner. It does not block the agent.

func (*Repo) AgentClaim added in v0.45.0

func (r *Repo) AgentClaim(ctx context.Context, a Actor, id int64) (AgentTask, error)

AgentClaim takes a pending backlog task of the agent's own project. It is the only write an agent has on the backlog. Of two sessions claiming at once, one wins and the others get "not available", the same answer as for a task assigned directly to someone else.

func (*Repo) AgentClose added in v0.46.0

func (r *Repo) AgentClose(ctx context.Context, a Actor, id int64, outcome, note string) (AgentTask, error)

AgentClose completes a task on the agent's checklist. A task another owner sent needs an outcome (done by default) and a note, which the sender reads; on anything else only the default outcome (done) is accepted, and ignored. The sender of a task can read it but never close it.

func (*Repo) AgentComment added in v0.46.0

func (r *Repo) AgentComment(ctx context.Context, a Actor, id int64, body string) (Comment, error)

AgentComment writes in the thread of a task the agent reads and takes part in. The other party hears it; the author never does.

func (*Repo) AgentCreate added in v0.45.0

func (r *Repo) AgentCreate(ctx context.Context, a Actor, in AgentInput) (AgentTask, error)

AgentCreate adds a task to the agent's own checklist.

func (*Repo) AgentDeleteSchedule added in v0.47.0

func (r *Repo) AgentDeleteSchedule(ctx context.Context, a Actor, id int64) error

AgentDeleteSchedule is the session's own Delete: only a task it scheduled. Its runs already on a checklist stay there, as with the owner's Delete.

func (*Repo) AgentGet added in v0.45.0

func (r *Repo) AgentGet(ctx context.Context, a Actor, id int64) (AgentTask, error)

AgentGet returns one task the agent can read.

func (*Repo) AgentList added in v0.45.0

func (r *Repo) AgentList(ctx context.Context, a Actor) (AgentView, error)

AgentList returns the agent's checklist (done ones included until they are archived), its own requests to the owner, the tasks it sent to other owners, and the pending backlog of its project. Nothing else.

func (*Repo) AgentPause added in v0.47.0

func (r *Repo) AgentPause(ctx context.Context, a Actor, taskID int64) (Record, error)

AgentPause and AgentResume are the session's own Pause and Resume: only on a recurring task it scheduled, at its current revision.

func (*Repo) AgentResume added in v0.47.0

func (r *Repo) AgentResume(ctx context.Context, a Actor, taskID int64) (Record, error)

func (*Repo) AgentSchedule added in v0.45.0

func (r *Repo) AgentSchedule(ctx context.Context, a Actor, in AgentInput, when When, tz string) (Record, error)

AgentSchedule schedules a task for the agent's own session: a template the owner owns and sees, which this session can read and which runs here. The target and the creator are the actor, never something the model says.

func (*Repo) AgentUpdate added in v0.45.0

func (r *Repo) AgentUpdate(ctx context.Context, a Actor, id int64, p AgentPatch) (AgentTask, error)

AgentUpdate edits a checklist task or a still-open request of the agent.

func (*Repo) AgentWithdraw added in v0.47.0

func (r *Repo) AgentWithdraw(ctx context.Context, a Actor, by string, id int64, note string) (AgentTask, error)

AgentWithdraw closes a request to the user that is no longer needed. It is not a delete: the request goes to Done with the reason, signed by who withdrew it (by), and is archived like any done task. by names the owner when the owner withdraws a session's request.

func (*Repo) AllOpenQuestions added in v0.47.0

func (r *Repo) AllOpenQuestions(ctx context.Context) ([]Question, error)

AllOpenQuestions returns every open question of every session, oldest first: what a cross-session view ("For you", the roster's marks) reads, so a question stays visible whether or not its session is loaded.

func (*Repo) AnswerQuestion added in v0.47.0

func (r *Repo) AnswerQuestion(ctx context.Context, sessionID, id string, answers []string, responder askuser.Responder, render RenderAnswer) (QuestionAnswerResult, error)

AnswerQuestion accepts the answer to an open question of sessionID in one transaction: the question closes as answered and its notice enters the outbox, or neither happens. A requires_tap question accepts only a human (ResponderUser) and is left untouched otherwise. The same responder repeating the same answers is a Duplicate and writes nothing.

func (*Repo) AssignOccurrence added in v0.45.0

func (r *Repo) AssignOccurrence(ctx context.Context, id int64, dest Destination) (Occurrence, error)

AssignOccurrence is the scheduler's T1: for a ready run, the child task on dest's checklist, its one assignment notice and the links commit together. An already assigned or finished run is returned as it is, so a retry after a lost response creates nothing. A snapshotted dependency that no longer exists fails the run (template_invalid) instead of being dropped.

func (*Repo) CancelPendingCall added in v0.47.0

func (r *Repo) CancelPendingCall(ctx context.Context, id string) (bool, error)

CancelPendingCall cancels the escalation of one question that has not been claimed (its owner can no longer call, or never could).

func (*Repo) CancelSessionCalls added in v0.47.0

func (r *Repo) CancelSessionCalls(ctx context.Context, sessionID string) ([]string, bool, error)

CancelSessionCalls is Stop: every live escalation of the session's open questions is cancelled, the questions stay open. It returns the attempts that were calling, for the caller to withdraw, and whether it cancelled any.

func (*Repo) Checklist added in v0.45.0

func (r *Repo) Checklist(ctx context.Context, sessionID string) ([]Task, error)

Checklist is the flat projection of the agent's checklist that the session WebSocket and /tasks carry.

func (*Repo) ClaimCallEscalation added in v0.47.0

func (r *Repo) ClaimCallEscalation(ctx context.Context, id, attempt string) (bool, error)

ClaimCallEscalation takes a due escalation for one attempt: it commits calling with attempt before anything rings. It reports false when the question was answered or closed, the escalation cancelled or claimed, or it is not due yet.

func (*Repo) ClearSessionDiscard added in v0.45.0

func (r *Repo) ClearSessionDiscard(ctx context.Context, sessionID string) error

ClearSessionDiscard withdraws the intent of a delete whose file was not unlinked: the session and its work stay as they were.

func (*Repo) Close added in v0.45.0

func (r *Repo) Close() error

Close releases the connections.

func (*Repo) CloseQuestion added in v0.47.0

func (r *Repo) CloseQuestion(ctx context.Context, sessionID, id string, to QuestionState, reason string) (Question, bool, error)

CloseQuestion ends an open question without an answer: to is withdrawn, dismissed or invalidated. Closing it again the same way is a no-op that reports changed=false; a question closed any other way, answered included, is a *ErrQuestionConflict and stays as it was.

func (*Repo) Comments added in v0.46.0

func (r *Repo) Comments(ctx context.Context, id int64) ([]Comment, error)

Comments is a task's thread, oldest first. The owner's view.

func (*Repo) CompleteForSession added in v0.45.0

func (r *Repo) CompleteForSession(ctx context.Context, sessionID string, id int64) error

CompleteForSession is the owner completing, from that session's /tasks, a task the session owns or asked for. It reaches nothing outside the session.

func (*Repo) ConfirmOccurrence added in v0.45.0

func (r *Repo) ConfirmOccurrence(ctx context.Context, id, revision int64, action string) (Occurrence, error)

ConfirmOccurrence answers a late run: "run" authorizes it (once), "skip" settles it. revision is the occurrence's; of two answers one wins.

func (*Repo) Create added in v0.45.0

func (r *Repo) Create(ctx context.Context, in CreateInput) (Record, error)

Create stores a task as the owner.

func (*Repo) DeferCallEscalation added in v0.47.0

func (r *Repo) DeferCallEscalation(ctx context.Context, id, attempt string, dueAt int64) (bool, error)

DeferCallEscalation puts a claimed attempt that did not ring back to pending, due at dueAt (outside the allowed hours, paused, the line busy).

func (*Repo) Delete added in v0.45.0

func (r *Repo) Delete(ctx context.Context, id, revision int64, deliver string) error

Delete removes a task with its subtasks and dependency edges. Deleting an open request tells nobody: the owner decided that. Deleting a session's open task tells that session; a finished one tells nobody. deliver is as in CreateInput.

func (*Repo) DueCallEscalations added in v0.47.0

func (r *Repo) DueCallEscalations(ctx context.Context, now int64) ([]Question, error)

DueCallEscalations returns the open questions whose call is due at now, oldest due first.

func (*Repo) DueQuestionWork added in v0.47.0

func (r *Repo) DueQuestionWork(ctx context.Context) ([]Question, error)

DueQuestionWork returns the answers whose continuation is still owed, oldest first: accepted, not stopped, and not yet seen to finish.

func (*Repo) FailOccurrence added in v0.45.0

func (r *Repo) FailOccurrence(ctx context.Context, id int64, reason, note string) (Occurrence, error)

FailOccurrence marks a ready run as not sent: its target could not be resolved or provisioned. The owner decides what happens next.

func (*Repo) FenceQuestionAnswers added in v0.47.0

func (r *Repo) FenceQuestionAnswers(ctx context.Context, sessionID string, stopRun bool, admitted []string) (int, error)

FenceQuestionAnswers commits, before a Stop or a recall is confirmed, what happens to answers already accepted: an answer not yet admitted stays in the outbox as an append (it joins the transcript, it starts nothing), and with stopRun the continuation an admitted one still owes is cancelled too. It is the durable order the dispatcher re-reads before admitting, so a Stop that lands between "accepted" and "admitted" cannot be raced by a reserved attempt. It returns how many rows it changed.

admitted lists the events whose message is already in the conversation (the caller knows; the outbox state only says what the transport did). Without stopRun they are left alone: a recall withdraws queued steers, not a run that is reading an answer.

func (*Repo) FinishCallEscalation added in v0.47.0

func (r *Repo) FinishCallEscalation(ctx context.Context, id, attempt string, to CallState) (bool, error)

FinishCallEscalation ends a claimed attempt as missed, done or cancelled.

func (*Repo) Get added in v0.45.0

func (r *Repo) Get(ctx context.Context, id int64) (Record, error)

Get returns one task with its relations, archived or not. The owner's view: agents go through Actor methods.

func (*Repo) GetQuestion added in v0.47.0

func (r *Repo) GetQuestion(ctx context.Context, id string) (Question, error)

GetQuestion returns a question by ID, whatever its session.

func (*Repo) HasQuestions added in v0.47.0

func (r *Repo) HasQuestions(ctx context.Context) bool

HasQuestions reports whether any question was ever stored. A database no asynchronous ask_user has touched has none, which lets the callers that only matter once there are questions skip their work entirely. It errs on the side of true when the table cannot be read.

func (*Repo) HumanComment added in v0.46.0

func (r *Repo) HumanComment(ctx context.Context, id int64, body string) (Comment, error)

HumanComment is the user writing in a thread: every party hears it.

func (*Repo) ImportLegacySchedules added in v0.45.0

func (r *Repo) ImportLegacySchedules(ctx context.Context, items []LegacySchedule) (bool, error)

ImportLegacySchedules turns every pending legacy record into a once template for its session, all in one transaction with the installation's import flag. A record already due becomes a late run straight away, however little it is overdue, so a prompt the old scheduler may have been sending when it stopped is never re-sent without the owner's OK; one whose prompt is known to be in its session (Delivered) is imported as a skipped run of a finished template. It returns false when the import had already happened.

func (*Repo) InsertQuestion added in v0.47.0

func (r *Repo) InsertQuestion(ctx context.Context, q Question) (Question, bool, error)

InsertQuestion commits a posted question. The invocation that already posted one gets it back (existed), so a retry is idempotent; a session at its bound gets *ErrQuestionOpen. q.ID, q.Ack and the origin are the caller's.

func (*Repo) InterruptCallEscalations added in v0.47.0

func (r *Repo) InterruptCallEscalations(ctx context.Context) ([]string, error)

InterruptCallEscalations marks interrupted every attempt still calling. Only the process that claimed an attempt can know how it ended, so this runs when a process starts, before it claims anything: those attempts belonged to one that died. It returns the questions it marked.

func (*Repo) Keep added in v0.47.0

func (r *Repo) Keep(ctx context.Context, taskID, revision int64) (Record, error)

Keep records that the user reviewed a recurring task and wants it to go on running: For you stops asking about it. The template's revision moves so every client sees the change.

func (*Repo) LateRuns added in v0.45.0

func (r *Repo) LateRuns(ctx context.Context, taskID int64) ([]Occurrence, error)

LateRuns returns every run of a template waiting for the owner's answer, oldest first, whatever page of Runs they fall on.

func (*Repo) LegacySchedulesImported added in v0.45.0

func (r *Repo) LegacySchedulesImported(ctx context.Context) (bool, error)

LegacySchedulesImported reports whether the one-time import has happened.

func (*Repo) List added in v0.45.0

func (r *Repo) List(ctx context.Context, f Filter) (ListResult, error)

List returns the owner's view. Archived tasks are left out unless asked for, and never counted.

func (*Repo) ListNews added in v0.47.0

func (r *Repo) ListNews(ctx context.Context) ([]News, error)

ListNews returns the unread items and those read less than NewsKeep ago, most recently updated first. A database that does not exist yet has none.

func (*Repo) MarkDeliveryUncertain added in v0.45.0

func (r *Repo) MarkDeliveryUncertain(ctx context.Context, noticeID string) (bool, error)

MarkDeliveryUncertain settles a scheduled assignment that was reserved for delivery (sent) but whose admission was never recorded, once no attempt is in flight: it may or may not have reached its session, so it is never sent again on its own, whatever its transcript says. Its run becomes the owner's decision (late, delivery_uncertain): Run sends it again, which may duplicate the work; Skip settles it. Like a re-gated run, it gives up its child and assignment, so Run goes through T1 again. A run whose template is gone cannot be answered and is skipped. It reports whether the notice was settled.

func (*Repo) MarkSessionDiscarding added in v0.45.0

func (r *Repo) MarkSessionDiscarding(ctx context.Context, sessionID string) error

MarkSessionDiscarding records, before a saved session's file is unlinked, that its delete is under way: the runs bound to it are neither given it again nor re-gated while the intent stands. Invisible to readers: it does not change the revision.

func (*Repo) MaterializeDue added in v0.45.0

func (r *Repo) MaterializeDue(ctx context.Context, limit int) ([]Occurrence, error)

MaterializeDue consumes every enabled template whose cursor is at or before now (at most limit of them), and returns the occurrences it created. It is the scheduler's T0: safe to repeat, and safe against another process doing the same, because each consumption checks the cursor it read.

func (*Repo) NextCallDueAt added in v0.47.0

func (r *Repo) NextCallDueAt(ctx context.Context) (int64, error)

NextCallDueAt is the earliest pending call of an open question, 0 if none.

func (*Repo) NextDueAt added in v0.45.0

func (r *Repo) NextDueAt(ctx context.Context) (int64, error)

NextDueAt is the earliest cursor of an enabled template, 0 when none.

func (*Repo) Notice added in v0.45.0

func (r *Repo) Notice(ctx context.Context, id string) (Notice, error)

Notice returns one notice.

func (*Repo) Occurrence added in v0.45.0

func (r *Repo) Occurrence(ctx context.Context, id int64) (Occurrence, error)

Occurrence returns one run.

func (*Repo) OccurrenceForNotice added in v0.45.0

func (r *Repo) OccurrenceForNotice(ctx context.Context, noticeID string) (Occurrence, bool, error)

OccurrenceForNotice returns the run whose current assignment is noticeID. The dispatcher uses it to apply the run's frozen delivery policy (busy wait). A superseded notice of a rerouted run maps to nothing.

func (*Repo) OpenNotices added in v0.45.0

func (r *Repo) OpenNotices(ctx context.Context) ([]Notice, error)

OpenNotices returns every notice the dispatcher still has work for, oldest first so a session receives them in the order they happened.

func (*Repo) OpenQuestions added in v0.47.0

func (r *Repo) OpenQuestions(ctx context.Context, sessionID string) ([]Question, error)

OpenQuestions returns the session's open questions, oldest first.

func (*Repo) Path added in v0.45.0

func (r *Repo) Path() string

Path is the database file, "" when it cannot be resolved.

func (*Repo) Pause added in v0.45.0

func (r *Repo) Pause(ctx context.Context, taskID, revision int64) (Record, error)

Pause stops a recurring template from consuming slots. Runs already authorized continue; late decisions stay answerable.

func (*Repo) PublishNews added in v0.47.0

func (r *Repo) PublishNews(ctx context.Context, in NewsInput) (NewsPublished, error)

PublishNews adds an item or, with a key the session already used, updates it. One transaction: two writers with the same key never make two items.

func (*Repo) QuestionByEvent added in v0.47.0

func (r *Repo) QuestionByEvent(ctx context.Context, eventID string) (Question, error)

QuestionByEvent returns the question whose answer notice is eventID.

func (*Repo) QuestionByInvocation added in v0.47.0

func (r *Repo) QuestionByInvocation(ctx context.Context, sessionID, msgID, toolCallID string) (Question, bool, error)

QuestionByInvocation returns the question a tool invocation posted.

func (*Repo) ReadNews added in v0.47.0

func (r *Repo) ReadNews(ctx context.Context, acks []NewsAck) (int, error)

ReadNews marks items read, each only at the revision acknowledged and only the first time: acknowledging again does not move read_at. Unknown items and stale revisions are skipped. It returns how many it marked. An empty list, or an empty ID, is an error: "mark all" is the client's snapshot of what it showed, never a blanket write.

func (*Repo) ReadyOccurrences added in v0.45.0

func (r *Repo) ReadyOccurrences(ctx context.Context) ([]Occurrence, error)

ReadyOccurrences lists the authorized runs still waiting for their child and assignment, oldest first.

func (*Repo) RegateOnRestart added in v0.45.0

func (r *Repo) RegateOnRestart(ctx context.Context) (int, error)

RegateOnRestart re-applies the late policy, at startup recovery, to runs that were authorized on time but never reached their session and whose due time is now ten minutes or more ago. ask returns them to late (their undelivered child and notice are withdrawn, so Run goes through T1 again), skip settles them, run lets them continue. Runs the owner confirmed or ran by hand, and runs already reserved or admitted, are never re-gated.

func (*Repo) Requests added in v0.45.0

func (r *Repo) Requests(ctx context.Context, sessionID string) ([]Task, error)

Requests is the flat projection of the session's open and answered requests to the owner.

func (*Repo) RerouteOccurrence added in v0.45.0

func (r *Repo) RerouteOccurrence(ctx context.Context, id, revision int64, dest Destination) (Occurrence, error)

RerouteOccurrence sends a failed, never admitted run to another existing session: the same child moves there and gets one new assignment notice. The old notice stays failed and is no longer the run's. Only the latest run of its template can be sent: a newer one already stands for the recurrence, which has one pending candidate.

func (*Repo) ReserveSession added in v0.45.0

func (r *Repo) ReserveSession(ctx context.Context, id int64, candidate string) (string, error)

ReserveSession records the ID a ready run for a new session creates its session with, before the session exists: candidate the first time, the recorded one ever after, whatever happens to the run. Invisible to readers: it does not change the revision.

func (*Repo) ResetChecklist added in v0.45.0

func (r *Repo) ResetChecklist(ctx context.Context, sessionID string) error

ResetChecklist deletes the session's checklist. Its requests, the backlog and the owner's notes are untouched.

func (*Repo) ResolveHandoff added in v0.46.0

func (r *Repo) ResolveHandoff(ctx context.Context, id, revision int64, action string) (Record, error)

ResolveHandoff is the user's answer to a request awaiting permission: send it to the recipient, or decline it (closed as Can't do; the sender hears).

func (*Repo) Resume added in v0.45.0

func (r *Repo) Resume(ctx context.Context, taskID, revision int64) (Record, error)

Resume re-enables a recurring template. The paused dates are not caught up: the next slot is strictly after now.

func (*Repo) Revision added in v0.45.0

func (r *Repo) Revision(ctx context.Context) (int64, error)

Revision is the global change counter: it grows with every committed change by any process. 0 when the database does not exist yet.

func (*Repo) RunNow added in v0.45.0

func (r *Repo) RunNow(ctx context.Context, taskID, revision, dueAt int64) (Occurrence, error)

RunNow consumes the template's next slot now, as an authorized run: it is that slot early, not an extra run. dueAt and revision are what the owner saw, so a retried request cannot consume the following slot.

func (*Repo) Runs added in v0.45.0

func (r *Repo) Runs(ctx context.Context, taskID, beforeID int64, limit int) ([]Occurrence, error)

Runs returns a template's runs newest first, before beforeID when it is not 0.

func (*Repo) ScheduledFor added in v0.45.0

func (r *Repo) ScheduledFor(ctx context.Context, sessionID string, ownerIDs []string) ([]Record, error)

ScheduledFor lists the templates that concern a session: the ones that target it, the ones it scheduled for itself, and the ones aimed at an owner whose conversation it is (ownerIDs). They are not on its checklist; each run arrives there as its own task.

func (*Repo) ScheduledInProject added in v0.47.0

func (r *Repo) ScheduledInProject(ctx context.Context, projectKey string) ([]Record, error)

ScheduledInProject lists every template filed under a project, whichever session scheduled it: what an owner's Tasks show besides its own.

func (*Repo) SendHandoff added in v0.46.0

func (r *Repo) SendHandoff(ctx context.Context, from, to OwnerRef, allowed bool, in AgentInput) (Record, error)

SendHandoff files a task from one owner to another. allowed is the sender's standing permission: with it the task lands on the recipient's checklist and the recipient is woken; without it, it is a request in You and nothing reaches the recipient until the user answers (ResolveHandoff).

func (*Repo) SessionDiscarding added in v0.45.0

func (r *Repo) SessionDiscarding(ctx context.Context, sessionID string) (bool, error)

SessionDiscarding reports whether a session's delete is under way: a run must not be given it meanwhile.

func (*Repo) SessionDiscards added in v0.45.0

func (r *Repo) SessionDiscards(ctx context.Context) ([]string, error)

SessionDiscards lists the sessions whose delete a start must finish or undo.

func (*Repo) SessionOwesWork added in v0.47.0

func (r *Repo) SessionOwesWork(ctx context.Context, sessionID string) (bool, error)

SessionOwesWork reports whether a session has an open question or an answer whose continuation is still due: it is waiting on something, so a goal must not read its silence as a result.

func (*Repo) SessionQuestions added in v0.47.0

func (r *Repo) SessionQuestions(ctx context.Context, sessionID string) ([]Question, error)

SessionQuestions returns every question of the session, oldest first.

func (*Repo) SetClock added in v0.45.0

func (r *Repo) SetClock(now func() time.Time)

SetClock replaces the clock; tests use it to age tasks past the archive window and to cross schedule boundaries without sleeping. It is safe to call while other goroutines use the repository.

func (*Repo) SetNoticeState added in v0.45.0

func (r *Repo) SetNoticeState(ctx context.Context, id string, c NoticeChange) (bool, error)

SetNoticeState applies c and reports whether it matched. A change bumps the global revision, so /api/tasks/ws tells open task details to refresh.

func (*Repo) SetQuestionWork added in v0.47.0

func (r *Repo) SetQuestionWork(ctx context.Context, eventID, from, to string) (bool, error)

SetQuestionWork moves an answer's owed work from one disposition to another.

func (*Repo) SettleDeletedSessionQuestions added in v0.47.0

func (r *Repo) SettleDeletedSessionQuestions(ctx context.Context, sessionID string) error

SettleDeletedSessionQuestions applies the question half of SettleSessionDeleted on its own: Delete runs it again once no post of the session can be in flight, for a question committed after the first pass.

func (*Repo) SettleSessionDeleted added in v0.45.0

func (r *Repo) SettleSessionDeleted(ctx context.Context, sessionID string) (int, error)

SettleSessionDeleted settles every unfinished run bound to a deleted session (see boundToSession), whatever gate it waits at, and clears the session's discard intent. Undelivered work fails (session_deleted) and can be sent elsewhere; work reserved or admitted is skipped with an unknown outcome. Finished history is unchanged.

func (*Repo) SkipNext added in v0.45.0

func (r *Repo) SkipNext(ctx context.Context, taskID, revision, dueAt int64) (Occurrence, error)

SkipNext records the next slot of an active recurring template as skipped and moves on to the following one.

func (*Repo) SlotDue added in v0.45.0

func (r *Repo) SlotDue(ctx context.Context, taskID int64) (bool, error)

SlotDue reports whether a recurring template has a slot due that the planner has not taken yet: a delivery of one of its older runs would be superseded by it, and waits for it instead.

func (*Repo) TaskNotices added in v0.45.0

func (r *Repo) TaskNotices(ctx context.Context, taskID int64, limit int) ([]Notice, error)

TaskNotices returns the latest notices of a task, newest first.

func (*Repo) TaskProjects added in v0.45.0

func (r *Repo) TaskProjects(ctx context.Context) ([]Project, error)

TaskProjects lists the projects tasks already refer to, most recent first wins for the display path.

func (*Repo) Update added in v0.45.0

func (r *Repo) Update(ctx context.Context, id, revision int64, p Patch) (Record, error)

Update applies an owner edit. revision must be the one the caller last saw: a stale form gets a *ConflictError carrying the current task instead of overwriting a change the CLI or an agent made in between.

func (*Repo) Watch added in v0.45.0

func (r *Repo) Watch(ctx context.Context, interval time.Duration, fn func(revision int64))

Watch reports changes made by any process, including this one, until ctx ends: fn gets the new global revision. It compares PRAGMA data_version on one persistent reader connection, which SQLite bumps whenever a different connection commits — so a CLI write is noticed without WAL or filesystem watchers, and a local write (a different connection from this reader) is noticed too. A local commit also wakes the loop early instead of waiting for the next tick. Before the database exists it only polls for the file.

type Rule added in v0.45.0

type Rule struct {
	Freq string `json:"freq"`
	DOW  *int   `json:"dow,omitempty"`
	DOM  *int   `json:"dom,omitempty"`
	H    int    `json:"h"`
	Mi   int    `json:"mi"`
}

Rule is a recurring wall-clock rule, interpreted in its schedule's IANA zone. DOW (0 = Sunday) is only for weekly, DOM (1–31) only for monthly.

type RunFailure added in v0.45.0

type RunFailure struct {
	OccurrenceID int64  `json:"occurrence_id"`
	Reason       string `json:"reason"`
	Note         string `json:"note,omitempty"`
}

RunFailure is the newest unresolved failed run of a template.

type RunStats added in v0.47.0

type RunStats struct {
	Ran     int      `json:"ran"`
	FirstAt int64    `json:"first_at,omitempty"`
	Last    *LastRun `json:"last,omitempty"`
	CostUSD *float64 `json:"cost_usd"`
}

RunStats counts a template's runs. Ran counts runs handed to a session (assigned or done); FirstAt is the first one's due time. Last is the most recent run in any state but late. CostUSD is what the runs cost: nil (unknown) until runs record their cost; it is never reported as zero.

type ScheduleDef added in v0.45.0

type ScheduleDef struct {
	When               When
	TZ                 string
	Target             Target
	Delivery           Delivery
	CreatedBySessionID string
}

ScheduleDef is the calendar definition of a template. CreatedBySessionID is provenance (an agent's own schedule), never a requester.

type Scope added in v0.45.0

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

Scope binds the shared repository to one session. The session's identity is fixed at construction by bootstrap; nothing the model says can change it.

func NewScope added in v0.45.0

func NewScope(repo *Repo, sessionID, cwd string) *Scope

NewScope binds repo to a session and its working directory.

func (*Scope) Actor added in v0.45.0

func (s *Scope) Actor() Actor

Actor is the identity used for authorization. The project key is resolved lazily: it runs git, and most sessions never touch tasks.

func (*Scope) ChangedChecklist added in v0.45.0

func (s *Scope) ChangedChecklist() ([]Task, bool)

ChangedChecklist returns the checklist and true when it differs from the last projection this scope handed out. Serve's change watcher uses it so a commit by the CLI (or by the tool itself, already announced) does not re-publish an identical list.

func (*Scope) Checklist added in v0.45.0

func (s *Scope) Checklist() []Task

Checklist is the session's flat checklist projection. It records what it handed out, so ChangedChecklist reports only real changes.

func (*Scope) MarkDone added in v0.45.0

func (s *Scope) MarkDone(id int) error

MarkDone completes a task of this session (checklist or its own request), for /tasks done. It reaches nothing outside the session.

func (*Scope) Repo added in v0.45.0

func (s *Scope) Repo() *Repo

Repo is the shared repository.

func (*Scope) Requests added in v0.45.0

func (s *Scope) Requests() []Task

Requests is the session's flat list of requests to the owner.

func (*Scope) ResetChecklist added in v0.45.0

func (s *Scope) ResetChecklist() error

ResetChecklist clears this session's checklist only.

func (*Scope) SessionID added in v0.45.0

func (s *Scope) SessionID() string

SessionID is the identity the scope acts as.

func (*Scope) WithOwners added in v0.46.0

func (s *Scope) WithOwners(dir OwnerDirectory, ownerSession bool) *Scope

WithOwners gives the scope the owner directory, and says whether the session was built as a project owner's conversation: only then is send offered, and it is still checked against the directory on every call.

func (*Scope) WithTZ added in v0.45.0

func (s *Scope) WithTZ(tz string) *Scope

WithTZ records the IANA zone of the device that created the session ("" when unknown). Set once at construction, before the scope is shared.

type SpecSubtask added in v0.45.0

type SpecSubtask struct {
	Title string `json:"title"`
}

SpecSubtask is a subtask line as frozen in an occurrence.

type Subtask added in v0.45.0

type Subtask struct {
	ID    int64  `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

Subtask is one checklist line of a task. There is no second level.

type SubtaskInput added in v0.45.0

type SubtaskInput struct {
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

SubtaskInput is a subtask as written by a caller; the whole list replaces the previous one.

type Target added in v0.45.0

type Target struct {
	Kind     string `json:"kind"`
	ID       string `json:"id,omitempty"`       // session or owner entity ID
	Project  string `json:"project,omitempty"`  // new: project key
	CWD      string `json:"cwd,omitempty"`      // new: canonical directory
	Model    string `json:"model,omitempty"`    // new: full model spec
	Thinking string `json:"thinking,omitempty"` // new: thinking level
}

Target is who receives a run.

func DecodeTarget added in v0.45.0

func DecodeTarget(b []byte) (Target, error)

DecodeTarget parses a canonical target object strictly.

type Task

type Task struct {
	ID          int    `json:"id"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	Status      string `json:"status"` // "pending", "in_progress", "done"
	DependsOn   []int  `json:"depends_on,omitempty"`
	CreatedAt   int64  `json:"created_at,omitempty"`   // unix millis
	CompletedAt int64  `json:"completed_at,omitempty"` // unix millis
	// The closing note: the summary of what was done (omitempty, like all
	// additions to this projection).
	CompletionNote string `json:"completion_note,omitempty"`

	// Set only on a task between owners (or one with a thread); names and
	// state only, never a session or project of the other owner.
	Handoff      *TaskHandoff `json:"handoff,omitempty"`
	CommentCount int          `json:"comment_count,omitempty"`
}

Task is the flat projection of a session checklist. Its JSON is what tasks_update and InitData.tasks have always carried, and installed clients (Pulse) parse exactly these fields: add to it only with omitempty.

type TaskHandoff added in v0.46.0

type TaskHandoff struct {
	State         string `json:"state"`
	Outcome       string `json:"outcome,omitempty"`
	FromOwnerName string `json:"from_owner_name"`
	ToOwnerName   string `json:"to_owner_name"`
}

TaskHandoff is what a session's projection says of a task between owners.

type ThreadEntry added in v0.46.0

type ThreadEntry struct {
	Author string `json:"author"`
	Body   string `json:"body"`
	At     int64  `json:"at"`
}

ThreadEntry is one comment as an agent reads it: the author is "you", "the user" or the other owner's name.

type When added in v0.45.0

type When struct {
	Kind string `json:"kind"`
	At   int64  `json:"at,omitempty"`
	Rule *Rule  `json:"rule,omitempty"`
}

When says when a template runs: a fixed instant once, or a wall-clock rule.

func DecodeWhen added in v0.45.0

func DecodeWhen(b []byte) (When, error)

DecodeWhen parses a canonical when object strictly: unknown fields, fractional or missing numbers and incompatible fields are errors, never defaults.

Jump to

Keyboard shortcuts

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