ticket

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package ticket stores tickets as first-class entities under a project (`projects/<id>/tickets/<ticketID>/ticket.json`), each holding zero or more sessions.

A ticket owns the work; a session is one conversation about it. That is why the two are separate: when an agent goes off the rails you start a fresh session on the SAME ticket, keeping its status, assignee, fields, and notes. An earlier design put the ticket on session.Meta, which made that impossible.

The ticket's Sessions slice is the list of record. session.Meta.TicketID is a denormalised back-pointer so the sidebar and the pool can answer "which ticket is this session in?" without scanning every ticket; when the two disagree, this package's copy wins.

Index

Constants

View Source
const (
	EventCreated         = "ticket.created"
	EventUpdated         = "ticket.updated"
	EventStatusChanged   = "ticket.status_changed"
	EventAssigned        = "ticket.assigned"
	EventDeleted         = "ticket.deleted"
	EventSessionAttached = "ticket.session_attached"
	EventSessionDetached = "ticket.session_detached"
	EventNoteAdded       = "ticket.note_added"
	EventFollowup        = "ticket.followup"
	EventAutoResolved    = "ticket.auto_resolved"
)

Event names. These strings are a public contract: they go out on the wire in X-Wick-Event, they are what a webhook filters on, and they are stored in project config. Renaming one silently breaks every receiver, so treat them as append-only.

View Source
const (
	ActorUser   = "user"
	ActorAgent  = "agent"
	ActorSystem = "system"
	ActorAPI    = "api"
)

Actor types. Who moved the ticket matters to a receiver: a human dragging a card and the stale-followup sweeper closing one are different signals, and a receiver that echoes changes back needs to recognise its own writes.

View Source
const (
	StatusOpen       = project.StatusOpen
	StatusInProgress = project.StatusInProgress
	StatusWaiting    = project.StatusWaiting
	StatusDone       = project.StatusDone
)

Status keys are per PROJECT — a team names its own stages. These constants are the built-in set every project starts with, re-exported from the project package so callers that only import this one can still name them.

View Source
const (
	HeaderEvent     = "X-Wick-Event"
	HeaderDelivery  = "X-Wick-Delivery"
	HeaderSignature = "X-Wick-Signature"
)

Delivery headers. A receiver identifies the event from the header without parsing the body, and dedupes on the delivery id.

Variables

This section is empty.

Functions

func AllEvents added in v1.2.9

func AllEvents() []string

AllEvents is the catalogue the settings UI offers and the docs list, in a sensible reading order rather than alphabetically.

func AttachSession

func AttachSession(layout config.Layout, projectID, ticketID, sessionID string) error

AttachSession adds a session to a ticket and brings its notes along. Idempotent: attaching one that is already there changes nothing, so a retry after a partial failure is safe. Does not touch UpdatedAt — adding a session is not an edit to the ticket's own state and should not reset its staleness.

When the session was on another ticket it is detached from that one first, so a session is never on two tickets at once — that is what makes dragging a session between cards a move rather than a copy.

func AutoCreateTitle

func AutoCreateTitle(r project.AutoCreateRule, in AutoCreateInput) string

AutoCreateTitle renders the title for an auto-created ticket. The rule's template wins when set; otherwise the first message is the title, because that is what a person scanning the board would have written anyway.

func DefaultStatuses added in v0.40.1

func DefaultStatuses() []string

DefaultStatuses is the built-in board order, for callers with no project config to hand (a test fixture, a fallback path). Anything acting on a real project reads cfg.StatusKeys() instead — a project may have renamed or replaced every one of these.

func Delete

func Delete(layout config.Layout, projectID, ticketID string) error

Delete removes a ticket and everything under it, notes included.

func DetachSession

func DetachSession(layout config.Layout, projectID, ticketID, sessionID string) error

DetachSession removes a session from a ticket and moves its notes back to the session itself. Removing one that is not there is a no-op, not an error: callers reconcile stale back-pointers through this path.

func EmitAutoResolved added in v1.2.9

func EmitAutoResolved(tk Ticket, from string)

EmitAutoResolved fires ticket.auto_resolved, naming the stage the sweeper moved the ticket out of.

func EmitFollowup added in v1.2.9

func EmitFollowup(tk Ticket)

EmitFollowup fires ticket.followup — the sweeper nudged a stale ticket.

func EmitNoteAdded added in v1.2.9

func EmitNoteAdded(layout config.Layout, projectID, ticketID, body string, actor Actor)

EmitNoteAdded fires ticket.note_added.

Exported because notes are stored by their own package: the note write does not pass through this one, so the HTTP layer reports it. A ticket that cannot be loaded is skipped rather than failing the note.

func EventsFor added in v1.2.9

func EventsFor(changes map[string]Change) []string

EventsFor decides which events a before→after transition should fire.

A status move emits BOTH ticket.status_changed and ticket.updated: a receiver that only cares about board movement subscribes to the specific one, while a receiver mirroring all edits subscribes to updated and does not have to enumerate every specific event to stay complete.

func Exists

func Exists(layout config.Layout, projectID, ticketID string) bool

Exists reports whether a ticket is on disk.

func FollowupMessage

func FollowupMessage(t Ticket, cfg project.TicketConfig) string

FollowupMessage renders the turn sent to a ticket's agent when the ticket goes stale: a snapshot plus the project's follow-up prompt. The agent decides the action — post to a channel, ping the assignee, close the ticket — because only it can see the conversation so far.

func NeedsAutoResolve

func NeedsAutoResolve(cfg project.TicketConfig, t Ticket, now time.Time) bool

NeedsAutoResolve reports whether a ticket has been idle long enough to close on its own.

func NeedsFollowup

func NeedsFollowup(cfg project.TicketConfig, t Ticket, now time.Time) bool

NeedsFollowup reports whether a ticket is stale enough to wake its agent: ticket mode on, follow-up timer on, not done, no ticket edit for a full window, and the previous follow-up (if any) at least a window ago — so a stuck ticket is nudged once per window, not once per tick.

func NormalizeID added in v1.2.9

func NormalizeID(id string) (string, error)

NormalizeID canonicalises a caller-supplied ticket id.

Any id in the safe charset is kept verbatim — "TIK-2026-001" stays what the caller typed, because an id adopted from another system is only useful if it survives the trip unchanged.

The one exception is a uuid, which is folded to dashless lowercase. Notion hands the same page id out in two shapes (dashless 32-hex in a page URL, dashed uuid from its API) and they must not become two tickets: collapsing both to one form is what makes "create from this page" idempotent no matter which shape the caller copied.

func OrphanedStatuses added in v0.40.1

func OrphanedStatuses(layout config.Layout, projectID string, next []project.TicketStatus) []string

OrphanedStatuses returns the status keys that would be left holding tickets if a project's statuses were replaced by next.

Renaming a stage is cheap; losing sight of the tickets in it is not. So a status still in use cannot simply be dropped: the caller is told which ones, and moves those tickets first. Silently rewriting them would change data nobody looked at, and there is no "unassigned status" to park them in — a ticket always sits in a column.

func Save

func Save(layout config.Layout, tk Ticket) error

Save rewrites a ticket and bumps UpdatedAt, which is what the stale and auto-resolve timers key on. Callers that must NOT move those timers (the sweeper stamping LastFollowupAt) use SaveKeepingTimestamp.

func SaveAs added in v1.2.9

func SaveAs(layout config.Layout, tk Ticket, actor Actor) error

SaveAs is Save with the actor named, so the outbound event can say who moved the ticket. Save stays as the unattributed form because most internal callers genuinely have nobody to name.

func SaveKeepingTimestamp

func SaveKeepingTimestamp(layout config.Layout, tk Ticket) error

SaveKeepingTimestamp persists a ticket exactly as given, leaving UpdatedAt alone.

func SetEmitter added in v1.2.9

func SetEmitter(e Emitter)

SetEmitter installs the process-wide event sink. Called once at boot.

func SetNotesMover

func SetNotesMover(fn NotesMover)

SetNotesMover installs the notes-follow-the-session hook. Call once at boot, before anything can attach or detach.

Why this exists: notes are scoped to the ticket when a session belongs to one, and to the session when it does not. Move the session without moving its notes and they silently stop being visible anywhere — the reader has no way to tell they were ever written. So every attach, move, and detach carries them along.

func ShouldAutoCreate

func ShouldAutoCreate(rules []project.AutoCreateRule, in AutoCreateInput) (bool, project.AutoCreateRule)

ShouldAutoCreate reports whether a session should be given a ticket, and which rule decided it. Rules are tried in order and the FIRST match wins, so a narrow exception placed above a broad rule carves a hole in it — that is how "everything from Slack except DMs" is expressed.

A rule whose Match cannot be judged yet (a text condition with no message to test) does not fire. Waiting is the safe direction: a ticket created from the wrong session is worse than one created a turn later.

func Sign added in v1.2.9

func Sign(secret string, body []byte) string

Sign returns the X-Wick-Signature value for a raw body.

The signature covers the bytes on the wire, not a re-serialised copy: JSON key order and whitespace are not stable across languages, so a receiver that re-encodes before verifying will fail. The docs say this too.

func Start

func Start(ctx context.Context, d Deps)

Start runs the sweeper until ctx is cancelled. A project with ticket mode off costs one already-loaded meta read per tick and nothing else.

func ValidEvent added in v1.2.9

func ValidEvent(name string) bool

ValidEvent reports whether name is a known event. Used when saving a webhook so a typo'd filter is refused instead of silently matching nothing forever.

func ValidStatus

func ValidStatus(cfg project.TicketConfig, s string) bool

ValidStatus reports whether s is one of the project's statuses.

func ValidateAutoCreate

func ValidateAutoCreate(rules []project.AutoCreateRule) error

ValidateAutoCreate checks a rule list before it is stored. A rule that cannot fire (an origin nobody sets, a regex that will not compile) is refused here rather than sitting in the config looking active.

func ValidateStatuses added in v0.40.1

func ValidateStatuses(list []project.TicketStatus) error

ValidateStatuses checks a status list before it is stored.

Two rules, both structural. A board needs at least one column, and exactly one status must be terminal: without it auto-resolve has nowhere to move a finished ticket and the followup timer would nag work that is already done.

func Verify added in v1.2.9

func Verify(secret string, body []byte, sig string) bool

Verify reports whether sig matches body under secret. Exported so the docs can point at a real implementation, and used by tests.

Types

type Actor added in v1.2.9

type Actor struct {
	Type string `json:"type"`
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
}

Actor identifies who caused an event.

type AutoCreateDeps

type AutoCreateDeps struct {
	Layout config.Layout
	// LoadRules returns a project's auto-create rules.
	LoadRules func(projectID string) ([]project.AutoCreateRule, error)
	// WriteBackPointer keeps session.Meta.TicketID in step. Optional.
	WriteBackPointer func(sessionID, ticketID string)
}

AutoCreateDeps are what EvaluateAutoCreate needs from outside: the project's rules and a way to record the new ticket on the session.

type AutoCreateInput

type AutoCreateInput struct {
	// Origin is the session's origin ("ui", "slack", "telegram", "rest", …).
	Origin string
	// ChannelKind is "dm", "channel", or "thread" for channel origins;
	// empty elsewhere.
	ChannelKind string
	// FirstMessage is the text the session opened with. Empty when it is
	// not known yet, in which case a rule carrying a text condition cannot
	// fire — it waits rather than guessing.
	FirstMessage string
	// IsSubAgent marks a delegated child's session. Those are working
	// contexts, not somebody's piece of work, so they never get a ticket.
	IsSubAgent bool
	// AlreadyTicketed short-circuits everything: a session on a ticket is
	// left alone.
	AlreadyTicketed bool
}

AutoCreateInput is what a rule is judged against: where the session came from and what it opened with.

type Change added in v1.2.9

type Change struct {
	From string `json:"from"`
	To   string `json:"to"`
}

Change is one field's before/after. Values are strings because every ticket field that can change is already a string on the wire; a typed union would buy nothing a receiver can use.

type ConfigLookup added in v1.2.9

type ConfigLookup func(projectID string) (project.TicketConfig, bool)

ConfigLookup returns the ticket config for a project. Injected so the dispatcher can read a project's webhook list without the ticket package importing the project registry.

type CreateOptions

type CreateOptions struct {
	ProjectID string
	// ID adopts an external identifier instead of generating one. It exists
	// so a ticket mirroring a Notion page can BE that page — no mapping to
	// store, and creating from the same page twice collides instead of
	// silently opening a second ticket. Empty means "generate one", which
	// is what every internal caller wants. See NormalizeID for the shape.
	ID       string
	Title    string
	Status   string // defaults to open
	Assignee string
	Fields   map[string]string
	// Sessions optionally seeds the session list (used when a ticket is
	// created from an existing conversation).
	Sessions []string
	// Actor is who is creating this, for the outbound webhook envelope.
	// Zero value reports as "system", which is right for internal writes
	// (auto-create, the sweeper) and wrong for nothing.
	Actor Actor
}

CreateOptions describes a new ticket.

type Delivery added in v1.2.9

type Delivery struct {
	WebhookID string    `json:"webhook_id"`
	Event     string    `json:"event"`
	At        time.Time `json:"at"`
	Status    int       `json:"status,omitempty"`
	Err       string    `json:"error,omitempty"`
	Attempts  int       `json:"attempts"`
	OK        bool      `json:"ok"`
}

Delivery is one recorded attempt, for the settings UI.

type Deps

type Deps struct {
	Layout       config.Layout
	ListProjects func() ([]project.Project, error)
	// SendFollowup delivers the follow-up turn to one of the ticket's
	// sessions, spawning the agent if it is idle (wired to pool.Send with
	// role "user", source "ticket").
	SendFollowup func(sessionID, text string) error
}

Deps are the sweeper's injected collaborators. Funcs, not interfaces: the server wires them at boot, tests pass fakes. SendFollowup is a func so this package never imports the pool.

type Dispatcher added in v1.2.9

type Dispatcher struct {
	Lookup ConfigLookup
	// Client is the HTTP client used for deliveries. Left nil, a client
	// with attemptTimeout is used.
	Client *http.Client
	// AllowPrivate lifts the private-address guard. Off by default: a
	// webhook URL is user-supplied and the server fetches it, so the
	// default must not let a tenant point wick at its own metadata
	// service. Operators running an all-private deployment set this.
	AllowPrivate bool
	// contains filtered or unexported fields
}

Dispatcher delivers ticket events to a project's configured webhooks.

It implements Emitter, so installing it is the single wiring point that turns ticket mutations into outbound HTTP.

func NewDispatcher added in v1.2.9

func NewDispatcher(lookup ConfigLookup) *Dispatcher

NewDispatcher builds a dispatcher over a config lookup.

func (*Dispatcher) Deliveries added in v1.2.9

func (d *Dispatcher) Deliveries(webhookID string) []Delivery

Deliveries returns the recorded attempts for a webhook, newest first.

func (*Dispatcher) Emit added in v1.2.9

func (d *Dispatcher) Emit(ev Event)

Emit fans the event out to every webhook that wants it.

Each delivery runs in its own goroutine: a ticket write must never wait on somebody's slow endpoint, and one dead receiver must not delay the others.

func (*Dispatcher) SendTest added in v1.2.9

func (d *Dispatcher) SendTest(w project.TicketWebhook, projectID string) Delivery

SendTest delivers a synthetic event to one webhook and reports the outcome, so the settings page can prove an endpoint works before a real ticket depends on it. Synchronous by design: the operator clicked a button and is waiting for the answer.

type Emitter added in v1.2.9

type Emitter interface {
	Emit(ev Event)
}

Emitter delivers a ticket event. Implemented by the webhook dispatcher and injected via SetEmitter.

This indirection keeps the ticket package free of HTTP, project-registry, and config-service imports: ticket is the storage layer that the whole app depends on, so making it reach outward for the project's webhook list would create an import cycle. Same shape as the SetManager/SetLayout wiring in tools/agents.

type Event added in v1.2.9

type Event struct {
	ID          string            `json:"id"`
	Event       string            `json:"event"`
	DeliveredAt time.Time         `json:"delivered_at"`
	ProjectID   string            `json:"project_id"`
	Actor       Actor             `json:"actor"`
	Ticket      Ticket            `json:"ticket"`
	Changes     map[string]Change `json:"changes,omitempty"`
	// Session carries the session id for the attach/detach events, where
	// the interesting subject is the link rather than the ticket.
	Session string `json:"session,omitempty"`
	// Note carries the note body for ticket.note_added.
	Note string `json:"note,omitempty"`
}

Event is the webhook envelope.

The full ticket rides along on every event, not just the diff: a receiver that missed an earlier delivery (or starts up mid-stream) can still act on the current state without calling back for it.

type NotesMover

type NotesMover func(layout config.Layout, sessionID, fromTicketID, toTicketID string) error

NotesMover moves a session's notes when the session changes ticket.

A func rather than a direct call because internal/agents/notes already imports this package (to resolve a session's scope), so calling it back from here would close an import cycle. The server wires the real implementation at boot; nil means "leave notes where they are", which is what tests that do not care about notes get.

type Ticket

type Ticket struct {
	// ID is a short, human-quotable code ("T-4F2A") rather than a UUID:
	// it appears on every board card and gets typed into chat.
	ID        string `json:"id"`
	ProjectID string `json:"project_id"`
	Title     string `json:"title"`
	Status    string `json:"status"`
	Assignee  string `json:"assignee,omitempty"` // wick user ID
	// Fields holds values keyed by project.TicketField.Key.
	Fields map[string]string `json:"fields,omitempty"`
	// Sessions is the list of record for which sessions belong here.
	Sessions  []string  `json:"sessions,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	// UpdatedAt tracks the last TICKET edit — not chat activity. The
	// stale-followup and auto-resolve timers run from it.
	UpdatedAt time.Time `json:"updated_at"`
	// LastFollowupAt guards the sweeper against re-sending a followup on
	// every tick; the next one waits another full window.
	LastFollowupAt time.Time `json:"last_followup_at,omitempty"`
}

Ticket is the persisted shape of one ticket.

func Create

func Create(layout config.Layout, opt CreateOptions) (Ticket, error)

Create materialises a new ticket on disk, retrying on the (plausible, with only four random characters) chance of an ID collision.

func EvaluateAutoCreate

func EvaluateAutoCreate(d AutoCreateDeps, projectID, sessionID string, in AutoCreateInput) (Ticket, bool)

EvaluateAutoCreate gives a session a ticket when the project's rules say so, and returns the ticket it created (or the zero value when nothing matched). Safe to call on every first message: it is a no-op for projects with no rules, and a session already on a ticket is left alone.

The session is attached to the new ticket, which also carries any notes it already accumulated onto it.

func FindBySession

func FindBySession(layout config.Layout, projectID, sessionID string) (Ticket, bool)

FindBySession returns the ticket a session belongs to by scanning the project's tickets. This is the authoritative answer; the back-pointer on session meta is only a shortcut, so anything that must be correct (an MCP op resolving "this session's ticket") comes through here.

func List

func List(layout config.Layout, projectID string) ([]Ticket, error)

List returns a project's tickets, newest first. A project with no tickets directory yet is empty, not an error.

func Load

func Load(layout config.Layout, projectID, ticketID string) (Ticket, error)

Load reads one ticket.

type WebhookTarget added in v1.2.9

type WebhookTarget struct {
	Webhook project.TicketWebhook
	Event   Event
}

WebhookTarget is one resolved delivery: the endpoint plus the event that matched it. The dispatcher takes these rather than a TicketConfig so the matching rules stay testable without a project on disk.

Jump to

Keyboard shortcuts

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