engine

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 modules, 0 packages

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

Documentation

Index

Constants

View Source
const (
	CodeNotFound           = "not_found"
	CodeInvalid            = "invalid_argument"
	CodeUnknownStatus      = "unknown_status"
	CodeUnknownKind        = "unknown_kind"
	CodeUnknownLabel       = "unknown_label"
	CodeUnknownField       = "unknown_field"
	CodeInvalidField       = "invalid_field"
	CodeUnknownProject     = "unknown_project"
	CodeClaimLost          = "claim_lost"
	CodeNotClaimed         = "not_claimed"
	CodeNotYourClaim       = "not_your_claim"
	CodeResolutionRequired = "resolution_required"
	CodeThrottled          = "progress_throttled"
	CodeMoved              = "ticket_moved"
	CodeIDTaken            = "id_taken"
	CodeReadOnly           = "read_only_store"
	CodeDanglingRef        = "dangling_ref"
	CodeCycle              = "cycle"
	CodeNoCandidates       = "no_candidates"
	CodeGitBusy            = "git_busy"
	CodeGit                = "git_error"
	CodeNoQuestion         = "no_open_question"
	CodeConflict           = "edit_conflict"
)

Error codes.

View Source
const (
	EvTicketCreated     = "ticket.created"
	EvTicketUpdated     = "ticket.updated"
	EvTicketMoved       = "ticket.moved" // status changed
	EvTicketRemoved     = "ticket.removed"
	EvCommentCreated    = "comment.created"
	EvClaimChanged      = "claim.changed"
	EvQuestionOpened    = "question.opened"
	EvQuestionAnswered  = "question.answered"
	EvSyncState         = "sync.state"
	EvConflictPreserved = "sync.conflict_preserved"
	EvStoreChanged      = "store.changed"
	EvPresenceChanged   = "presence.changed"
	EvReset             = "reset"
)

Event types.

View Source
const (
	DefaultFetchInterval = 15 * time.Second
	DefaultPushDelay     = 2 * time.Second
)

Defaults.

View Source
const EvCommit = "commit"

EvCommit is a history entry for a commit made outside ka.

View Source
const Gitattributes = "* text=auto eol=lf\nticket.md merge=ka\n"

Gitattributes is what ka init writes (and ka doctor expects).

View Source
const SystemActor = "agent/ka"

SystemActor authors comments written by ka itself.

Variables

EventTypes lists every event type.

View Source
var LockTimeout = 2 * time.Minute

lock takes the per-clone write lock (flock on Unix, LockFileEx on Windows). LockTimeout bounds how long a write waits for another process's write to the same clone (which may include push retries over a slow network).

View Source
var MergeDriverCommand string

MergeDriverCommand is the command registered as git's merge.ka.driver, e.g. `"/usr/local/bin/ka" merge-driver %O %A %B %P`. The CLI sets it from its own executable path; when empty, ka does not register a driver.

View Source
var QueryKeys = []string{"id", "project", "store", "status", "category", "priority", "kind", "label",
	"assignee", "owner", "claimed", "parent", "blocked_by", "blocks", "created_by", "is", "has", "sort"}

QueryKeys are the recognized filter keys.

Functions

func AgentsMD

func AgentsMD(project, prefix string) string

AgentsMD is the hand-writing protocol for AGENTS.md (PRD §7.12).

func BlobSHA

func BlobSHA(data []byte) string

BlobSHA is git's SHA-1 object ID for a file's bytes. It identifies a version of ticket.md for If-Match.

func ConfigDir

func ConfigDir() string

ConfigDir is where ka keeps user configuration.

func DataDir

func DataDir() string

DataDir is where ka keeps managed clones.

func InitStore

func InitStore(ctx context.Context, o InitOptions) ([]string, error)

InitStore creates a store (and git repo, if needed) in Dir. Existing files are left alone. It returns the files it created.

func IsCode

func IsCode(err error, code string) bool

IsCode reports whether err is an *Error with the given code.

func NormalizeAgent

func NormalizeAgent(name string) string

NormalizeAgent turns an MCP client name into an agent actor.

func ParsePushMode

func ParsePushMode(s string) (mode string, delay time.Duration, err error)

ParsePushMode parses immediate | manual | debounce | debounce:<duration>.

func RegisterMergeDriver

func RegisterMergeDriver(ctx context.Context, g *gitx.Repo) error

RegisterMergeDriver records the semantic merge driver in a repository's config.

func RunMergeDriver

func RunMergeDriver(ctx context.Context, base, ours, theirs, path string) int

RunMergeDriver implements `ka merge-driver %O %A %B %P`, registered with git config merge.ka.driver. It writes the result to %A and returns the exit code git expects (0 clean, 1 conflict).

func Template

func Template(prefix, status, now string) string

Template is a blank ticket for hand-writing (ka template).

Types

type ActivityIn

type ActivityIn struct {
	Limit  int    `json:"limit,omitempty"`  // default 100, at most 500
	Before string `json:"before,omitempty"` // RFC 3339: only older entries
	Ticket string `json:"ticket,omitempty"` // only this ticket's history
}

ActivityIn selects a page of history.

type ActivityOut

type ActivityOut struct {
	Events []Event `json:"events"`
	// More is true when older entries exist; pass the last event's at as before.
	More bool `json:"more"`
}

ActivityOut is a page of history, newest first.

type ActorOut

type ActorOut struct {
	Handle  string   `json:"handle"`
	Kind    string   `json:"kind"` // human or agent
	Name    string   `json:"name,omitempty"`
	Emails  []string `json:"emails,omitempty"`
	Aliases []string `json:"aliases,omitempty"`
	Roles   []string `json:"roles,omitempty"`
}

ActorOut is one actor from the merged actor registry.

type AnswerIn

type AnswerIn struct {
	ID       string `json:"id"`
	Question string `json:"question,omitempty"` // comment filename; default: the newest open question
	Choice   *int   `json:"choice,omitempty"`
	Text     string `json:"text,omitempty"`
	Approved *bool  `json:"approved,omitempty"` // set for ka approve / ka reject
}

AnswerIn answers (or approves/rejects) an open question.

type AskIn

type AskIn struct {
	ID       string        `json:"id"`
	Question string        `json:"question"`
	Options  []string      `json:"options,omitempty"`
	To       string        `json:"to,omitempty"`
	Kind     string        `json:"kind,omitempty"` // question (default) or approval
	Wait     time.Duration `json:"-"`
}

AskIn is ka_ask's input.

type AskOut

type AskOut struct {
	WriteOut
	Question string      `json:"question"`
	Answered bool        `json:"answered"`
	Answer   *CommentOut `json:"answer,omitempty"`
}

AskOut reports a question and, if waited for, its answer.

type BoardIn

type BoardIn struct {
	Store       string   `json:"store" doc:"The store to save the board in."`
	Key         string   `json:"key" doc:"The file name without .yml: lowercase letters, digits, - and _."`
	Title       string   `json:"title" doc:"The display name (the file's name: field)."`
	Description string   `json:"description,omitempty"`
	Filter      string   `json:"filter,omitempty" doc:"A ka query."`
	GroupBy     string   `json:"group_by,omitempty"`
	Sort        string   `json:"sort,omitempty"`
	Swimlanes   string   `json:"swimlanes,omitempty"`
	Columns     []string `json:"columns,omitempty" doc:"The columns (statuses, when grouped by status) to show, in order."`
	CardFields  []string `json:"card_fields,omitempty"`
}

BoardIn is a saved board to write (PRD §7.7). Boards are definitions only: a filter and how to lay it out, never ticket membership or order.

type BoardOut

type BoardOut struct {
	ID          string   `json:"id" doc:"store/key: unique across the workspace."`
	Name        string   `json:"name" doc:"The key (file name without .yml)."`
	Title       string   `json:"title" doc:"The display name."`
	Store       string   `json:"store"`
	Description string   `json:"description,omitempty"`
	Filter      string   `json:"filter,omitempty"`
	GroupBy     string   `json:"group_by,omitempty"`
	Sort        string   `json:"sort,omitempty"`
	Swimlanes   string   `json:"swimlanes,omitempty"`
	Columns     []string `json:"columns,omitempty"`
	CardFields  []string `json:"card_fields,omitempty"`
}

BoardOut is a saved board.

type Caller

type Caller struct {
	Actor      string // bsant or agent/claude-code
	OnBehalfOf string // the human an agent works for
	Session    string
}

Caller identifies who is acting (PRD §7.6, §11.1).

type CheckIn

type CheckIn struct {
	ID    string      `json:"id"`
	Items []CheckItem `json:"items"`
}

CheckIn is ka_check's input.

type CheckItem

type CheckItem struct {
	Index *int   `json:"index,omitempty"`
	Text  string `json:"text,omitempty"`
	Done  bool   `json:"done"`
}

CheckItem marks one acceptance item, by index or by text.

type Claim

type Claim struct {
	By    string `json:"by"`
	At    string `json:"at"`
	Stale bool   `json:"stale,omitempty"`
}

Claim is a claim as reported to callers.

type ClaimEvent

type ClaimEvent struct {
	Ticket Summary `json:"ticket"`
	From   *Claim  `json:"from,omitempty"`
	To     *Claim  `json:"to,omitempty"`
}

ClaimEvent is the payload of claim.changed.

type ClaimOut

type ClaimOut struct {
	WriteOut
	Confirmed bool `json:"confirmed"` // published (or the store has no remote)
}

ClaimOut reports a claim.

type CommentEvent

type CommentEvent struct {
	Ticket  Ref        `json:"ticket"`
	Comment CommentOut `json:"comment"`
}

CommentEvent is the payload of comment.created and question.*.

type CommentIn

type CommentIn struct {
	ID         string `json:"id"`
	Type       string `json:"type,omitempty"` // note (default), progress, decision
	Body       string `json:"body"`
	Supersedes string `json:"supersedes,omitempty"`
	Retracts   string `json:"retracts,omitempty"`
}

CommentIn is ka_comment's input.

type CommentOut

type CommentOut struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	Author     string   `json:"author"`
	Created    string   `json:"created"`
	To         string   `json:"to,omitempty"`
	Options    []string `json:"options,omitempty"`
	Answers    string   `json:"answers,omitempty"`
	Choice     *int64   `json:"choice,omitempty"`
	ChoiceText string   `json:"choice_text,omitempty"` // the chosen option, from the question
	Approved   *bool    `json:"approved,omitempty"`
	Resolution string   `json:"resolution,omitempty"`
	Body       string   `json:"body,omitempty"`
}

CommentOut is a comment as reported to callers.

type CommitOut

type CommitOut struct {
	SHA       string            `json:"sha"`
	Store     string            `json:"store"`
	Author    string            `json:"author"`
	Date      string            `json:"date"`
	Subject   string            `json:"subject"`
	Trailers  map[string]string `json:"trailers,omitempty"`
	Diff      string            `json:"diff"`
	Truncated bool              `json:"truncated,omitempty"`
}

CommitOut is one commit and its diff, limited to the store.

type ConfigEntry

type ConfigEntry struct {
	Key      string `json:"key"`
	Value    string `json:"value"`
	Class    string `json:"class" doc:"data (validation; resolved through extends) or runtime (this ka instance; the user wins)."`
	Source   string `json:"source" doc:"The layer that set the value: a file, built-in defaults, or the workspace."`
	Line     int    `json:"line,omitempty"`
	LockedBy string `json:"locked_by,omitempty" doc:"The layer whose lock fixes this value."`
	Note     string `json:"note,omitempty"`
}

ConfigEntry is one effective config value and where it came from (PRD §9.3, "Seeing where a value came from").

type ConfigExplainOut

type ConfigExplainOut struct {
	Project string        `json:"project"`
	Store   string        `json:"store"`
	Layers  []string      `json:"layers" doc:"The data config chain, lowest first."`
	Entries []ConfigEntry `json:"entries"`
	Locked  []string      `json:"locked,omitempty"`
}

ConfigExplainOut is a project's effective config.

type CreateIn

type CreateIn struct {
	Project    string         `json:"project,omitempty"`
	Title      string         `json:"title"`
	Kind       string         `json:"kind,omitempty"`
	Priority   string         `json:"priority,omitempty"`
	Status     string         `json:"status,omitempty"`
	Labels     []string       `json:"labels,omitempty"`
	Assignee   string         `json:"assignee,omitempty"`
	Owner      string         `json:"owner,omitempty"`
	Parent     string         `json:"parent,omitempty"`
	BlockedBy  []string       `json:"blocked_by,omitempty"`
	Related    []string       `json:"related,omitempty"`
	Links      []string       `json:"links,omitempty"`
	Acceptance []string       `json:"acceptance,omitempty"`
	Fields     map[string]any `json:"fields,omitempty"`
	Problem    string         `json:"problem,omitempty"`
	Approach   string         `json:"approach,omitempty"`
	Body       string         `json:"body,omitempty"`
}

CreateIn is one ticket for ka_create.

type CreateOut

type CreateOut struct {
	Created []Ref `json:"created"`
	Pushed  bool  `json:"pushed"`
	Local   bool  `json:"local_only,omitempty"`
	// PushPending: committed; a debounced push follows within seconds.
	PushPending bool   `json:"push_pending,omitempty"`
	Error       *Error `json:"error,omitempty"` // first failure; earlier tickets were still created
}

CreateOut lists created tickets.

type Detail

type Detail struct {
	Summary
	ParentRef     *Ref                    `json:"parent_ref,omitempty"`
	BlockedBy     []Ref                   `json:"blocked_by,omitempty"`
	Blocks        []Ref                   `json:"blocks,omitempty"`
	Children      []Ref                   `json:"children,omitempty"`
	Related       []string                `json:"related,omitempty"`
	Links         []string                `json:"links,omitempty"`
	AcceptanceAll []kaspec.AcceptanceItem `json:"acceptance_items,omitempty"`
	Body          string                  `json:"body,omitempty"`
	OpenQuestions []CommentOut            `json:"open_questions,omitempty"`
	Decisions     []CommentOut            `json:"decisions,omitempty"`
	Recent        []CommentOut            `json:"recent_comments,omitempty"`
	Comments      []CommentOut            `json:"comments,omitempty"`
	CommentCount  int                     `json:"comment_count,omitempty"`
	CreatedBy     string                  `json:"created_by,omitempty"`
	Store         string                  `json:"store"`
	Path          string                  `json:"path"`
}

Detail is a full ticket with its context digest.

type DocEntry

type DocEntry struct {
	Project string `json:"project"`
	Path    string `json:"path" doc:"Relative to the project's docs/ directory, slash-separated."`
	Title   string `json:"title" doc:"The first markdown heading, else the file name."`
	Size    int64  `json:"size"`
}

DocEntry is one file under a project's docs/ directory (PRD §7.2, §13.2).

type DocOut

type DocOut struct {
	DocEntry
	Store     string `json:"store"`
	StorePath string `json:"store_path" doc:"The path tickets use to link it: projects/<key>/docs/<path>."`
	Body      string `json:"body" doc:"The file's text (markdown for .md files)."`
	Text      bool   `json:"text" doc:"False for binary files, whose body is empty."`
	Truncated bool   `json:"truncated,omitempty"`
	Backlinks []Ref  `json:"backlinks" doc:"Tickets whose description, links or comments mention store_path."`
}

DocOut is one doc with the tickets that mention it.

type DocsOut

type DocsOut struct {
	Docs []DocEntry `json:"docs"`
}

DocsOut lists project docs.

type Error

type Error struct {
	Code    string         `json:"code"`
	Message string         `json:"message"`
	Fix     string         `json:"fix,omitempty"`
	Data    map[string]any `json:"data,omitempty"`
}

Error is a structured, actionable error. The same codes are used by the CLI, MCP and (from M2) REST, so an agent learns them once.

func AsError

func AsError(err error) *Error

AsError converts any error into an *Error.

func Errf

func Errf(code, fix, format string, args ...any) *Error

Errf builds an Error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) With

func (e *Error) With(k string, v any) *Error

With attaches data to an error.

type Event

type Event struct {
	Seq     uint64 `json:"id" doc:"Monotonic per daemon; also the SSE id."`
	Type    string `json:"type"`
	At      string `json:"at"`
	Store   string `json:"store,omitempty"`
	Project string `json:"project,omitempty"`
	Ticket  string `json:"ticket,omitempty"`
	Actor   string `json:"actor,omitempty" doc:"Who caused it, when known."`
	Data    any    `json:"data,omitempty"`
	// History entries (GET /activity) only: the commit, and its subject
	// without the ticket ID.
	Commit string `json:"commit,omitempty"`
	Text   string `json:"text,omitempty"`
}

Event is one domain event.

type EventFilter

type EventFilter struct {
	Types, Projects, Tickets []string
}

EventFilter selects events by type (prefix patterns such as ticket.*), project and ticket. Empty lists match everything; reset always matches.

func ParseEventFilter

func ParseEventFilter(types, projects, tickets string) EventFilter

ParseEventFilter reads comma-separated lists.

func (EventFilter) Match

func (f EventFilter) Match(e Event) bool

Match reports whether an event passes the filter.

type EventHub

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

EventHub numbers events and keeps the most recent ones in a ring buffer for replay (Last-Event-ID). Sequence numbers start at the daemon's start time in microseconds, so IDs from an earlier daemon are always older than the buffer and get a reset.

func NewEventHub

func NewEventHub(size int) *EventHub

NewEventHub keeps the last size events.

func (*EventHub) Publish

func (h *EventHub) Publish(evs ...Event)

Publish assigns sequence numbers and wakes waiting readers.

func (*EventHub) Seq

func (h *EventHub) Seq() uint64

Seq is the last assigned sequence number.

func (*EventHub) Since

func (h *EventHub) Since(seq uint64) (evs []Event, ok bool, more <-chan struct{})

Since returns the events after seq. ok is false when some of them are no longer buffered (or seq is not from this hub); the caller must reset. The channel is closed when more events arrive.

type EventSink

type EventSink interface {
	Publish(evs ...Event)
}

EventSink receives events.

type FieldChange

type FieldChange struct {
	From any `json:"from"`
	To   any `json:"to"`
}

FieldChange is one frontmatter field's old and new value.

type FixCategory

type FixCategory struct {
	Name   string   `json:"name"`
	Files  []string `json:"files"`
	Commit string   `json:"commit,omitempty"`
}

FixCategory is one kind of repair; each becomes one commit.

type FixOut

type FixOut struct {
	Categories []FixCategory `json:"categories"`
}

FixOut reports what ka fix changed, per category.

type GetIn

type GetIn struct {
	ID      string   `json:"id"`
	Include []string `json:"include,omitempty"` // comments, children, relations
}

GetIn is ka_get's input.

type InboxItem

type InboxItem struct {
	ID       string     `json:"id"`
	Title    string     `json:"title"`
	Comment  CommentOut `json:"comment"`
	Question string     `json:"question,omitempty"` // for answers: the question's filename
	// Restorable: a preserved operation that POST /tickets/{id}/restore can re-apply.
	Restorable bool `json:"restorable,omitempty"`
}

InboxItem is one entry in an inbox.

type InboxOut

type InboxOut struct {
	Answers   []InboxItem `json:"answers"`   // answers and approvals to the caller's questions
	Questions []InboxItem `json:"questions"` // open questions addressed to the caller
}

InboxOut is ka_inbox's output.

type Index

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

Index is the in-memory model of a workspace. It is disposable: it is rebuilt from the files at startup and updated from changed paths.

func (*Index) Workspace

func (ix *Index) Workspace() *kaspec.Workspace

Workspace returns the kaspec workspace for validation (ka check).

type InitOptions

type InitOptions struct {
	Dir     string
	Name    string // store name (default: directory name)
	Project string // optional first project key
	Prefix  string // its ID prefix (default derived from the key)
	Extends string // optional parent store URL
}

InitOptions configures ka init.

type LinkOut

type LinkOut struct {
	Link string `json:"link"`
	Path string `json:"path,omitempty"` // local file
	URL  string `json:"url,omitempty"`  // forge URL
	Line string `json:"line,omitempty"`
}

LinkOut is a resolved code link.

type MoveProjectOut

type MoveProjectOut struct {
	Project    string   `json:"project"`
	From       string   `json:"from"`
	To         string   `json:"to"`
	Files      int      `json:"files"`
	Tickets    int      `json:"tickets"`
	ToCommit   string   `json:"to_commit,omitempty"`
	FromCommit string   `json:"from_commit,omitempty"`
	Pushed     []string `json:"pushed,omitempty" doc:"Stores whose commit was pushed."`
	PushError  string   `json:"push_error,omitempty"`
	DryRun     bool     `json:"dry_run,omitempty"`
}

MoveProjectOut reports a project move.

type NextIn

type NextIn struct {
	Query   string `json:"query,omitempty"` // extra filters: project:jk kind:bug label:cache
	Project string `json:"project,omitempty"`
	Peek    bool   `json:"peek,omitempty"` // do not claim (claim: false)
}

NextIn is ka_next's input.

type NextOut

type NextOut struct {
	Ticket    *Detail `json:"ticket,omitempty"`
	Claimed   bool    `json:"claimed"`
	Confirmed bool    `json:"confirmed"`
	PushError string  `json:"push_error,omitempty"`
	Remaining int     `json:"remaining"` // other ready tickets matching the filters
}

NextOut is ka_next's output.

type Op

type Op struct {
	Op string `json:"op"` // create, update, claim, release, transition, comment, check
	ID string `json:"id"`
	At string `json:"at"`

	// Identity travels in commit trailers, not in Ka-Op.
	Actor      string `json:"-"`
	OnBehalfOf string `json:"-"`
	Session    string `json:"-"`

	New    *kaspec.Ticket                `json:"new,omitempty"`    // create
	Set    map[string]*string            `json:"set,omitempty"`    // update: scalar fields; nil clears
	Fields map[string]*kaspec.FieldValue `json:"fields,omitempty"` // update: custom fields; nil clears
	Add    map[string][]string           `json:"add,omitempty"`    // update: labels, blocked_by, related, links, acceptance
	Remove map[string][]string           `json:"remove,omitempty"` // update
	Body   *string                       `json:"body,omitempty"`   // update

	Steal  bool   `json:"steal,omitempty"`  // claim
	Status string `json:"status,omitempty"` // claim (start status), release, transition

	Comment     *kaspec.Comment `json:"comment,omitempty"` // comment, transition (resolution)
	CommentName string          `json:"comment_name,omitempty"`

	Check []CheckItem `json:"check,omitempty"`

	// IfMatch, when set, requires ticket.md to still have this blob SHA
	// (BlobSHA). It guards editor saves against lost updates; it is checked
	// only on first application and never travels in Ka-Op.
	IfMatch string `json:"-"`
}

Op is one replayable operation (PRD §7.9, §10.2). Everything needed to re-apply it against a different upstream state is inside the value, including timestamps and generated names, so a replay is deterministic.

func DecodeOp

func DecodeOp(s string) (*Op, error)

DecodeOp parses a Ka-Op trailer value.

func (*Op) Encode

func (o *Op) Encode() string

Encode renders the Ka-Op trailer value.

type OpCount

type OpCount struct {
	Op, Result string
	N          uint64
}

OpCount is one row of operation statistics.

type OpStats

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

OpStats counts operations by kind and outcome, for /metrics.

func (*OpStats) Snapshot

func (m *OpStats) Snapshot() ([]OpCount, map[string]float64)

Snapshot returns the counts, sorted, and the total seconds per op.

type OpenOptions

type OpenOptions struct {
	Dir       string            // where discovery starts (default: cwd)
	Workspace string            // explicit workspace file
	Map       map[string]string // remote URL -> local store directory
	Offline   bool              // never clone or fetch
}

OpenOptions controls workspace discovery.

type Pointer

type Pointer struct {
	Dir     string // the checkout containing .ka.yml
	Store   string // URL or path
	Branch  string
	Project string
}

Pointer is a code repo's .ka.yml (PRD §9.4).

func ParsePointer

func ParsePointer(dir string) (*Pointer, error)

ParsePointer reads a .ka.yml pointer.

type Preserved

type Preserved struct {
	Path   string `json:"path"`
	Field  string `json:"field"`
	Lost   string `json:"lost"`
	Kept   string `json:"kept"`
	Commit string `json:"commit,omitempty"`
}

Preserved is a value that lost a semantic merge, recorded by the merge driver (which cannot write commits itself) and turned into a system comment by the next ka write or sync.

func MergeTickets

func MergeTickets(ctx context.Context, base, up, local []byte) (merged []byte, preserved []Preserved, ok bool)

MergeTickets merges two versions of a ticket.md against their common ancestor, field by field (PRD §10.3). up is the already published side; when both sides changed a scalar differently, up wins and the other value is returned in preserved. ok is false when a version does not parse, in which case git's text merge should be used instead.

type ProjectInfo

type ProjectInfo struct {
	Key      string
	Prefix   string
	Name     string
	Store    *Store
	Dir      string
	File     *kaspec.ProjectFile
	Cfg      *kaspec.Config
	CfgDiags []kaspec.Diagnostic
}

ProjectInfo is one project in the workspace.

type ProjectSchema

type ProjectSchema struct {
	Key        string                     `json:"key"`
	Prefix     string                     `json:"prefix"`
	Name       string                     `json:"name,omitempty"`
	Store      string                     `json:"store"`
	Archived   bool                       `json:"archived,omitempty"`
	ReadOnly   bool                       `json:"read_only,omitempty"`
	Statuses   []kaspec.Status            `json:"statuses"`
	Initial    string                     `json:"initial"`
	Kinds      []string                   `json:"kinds"`
	Labels     []string                   `json:"labels,omitempty"`
	LabelsOpen bool                       `json:"labels_open"`
	Fields     map[string]kaspec.FieldDef `json:"fields,omitempty"`
	Tickets    int                        `json:"tickets"`
}

ProjectSchema describes one project's vocabulary.

type Query

type Query struct {
	Sort []string
	// contains filtered or unexported fields
}

Query is a parsed filter in the shared query language (PRD §7.7):

project:jk,gyggly category:started -label:infra assignee:agent/* flaky cache

Terms are ANDed; comma-separated values within a term are ORed; a leading "-" negates a term; "*" in a value is a wildcard; "none" matches an empty field; bare words search the title and description.

func ParseQuery

func ParseQuery(s string) (*Query, error)

ParseQuery parses a query string.

func (*Query) Has

func (q *Query) Has(key string) bool

Has reports whether the query constrains a key.

type Rec

type Rec struct {
	ID       string
	Store    *Store
	Project  *ProjectInfo
	Dir      string // relative to the store root
	T        *kaspec.Ticket
	Raw      []byte
	Comments []*kaspec.CommentEntry
	Invalid  bool // ticket.md has errors; T may be partial
	// contains filtered or unexported fields
}

Rec is one indexed ticket.

type Ref

type Ref struct {
	ID     string `json:"id"`
	Title  string `json:"title,omitempty"`
	Status string `json:"status,omitempty"`
}

Ref is a related ticket, briefly.

type Result

type Result struct {
	Commit    string   `json:"commit,omitempty"`
	Pushed    bool     `json:"pushed"`
	HasRemote bool     `json:"has_remote"`
	Replayed  int      `json:"replayed,omitempty"`
	Preserved []string `json:"preserved,omitempty"`
	PushError string   `json:"push_error,omitempty"`
	// PushPending: committed locally; a debounced push follows shortly.
	PushPending bool `json:"push_pending,omitempty"`
	// Renamed maps IDs that collided with upstream during replay to their new IDs.
	Renamed map[string]string `json:"renamed,omitempty"`
}

Result describes the outcome of a write.

type SchemaOut

type SchemaOut struct {
	Projects       []ProjectSchema `json:"projects"`
	DefaultProject string          `json:"default_project,omitempty"`
	Priorities     []string        `json:"priorities"`
	Resolutions    []string        `json:"resolutions"`
	Humans         []string        `json:"humans,omitempty"`
	Agents         []string        `json:"agents,omitempty"`
	Roles          []string        `json:"roles,omitempty"`
	You            string          `json:"you"`
}

SchemaOut is ka_schema's output.

type SearchIn

type SearchIn struct {
	Query string   `json:"query,omitempty"`
	Sort  []string `json:"sort,omitempty"`
	Limit int      `json:"limit,omitempty"` // 0: 20; negative: all
	All   bool     `json:"all,omitempty"`   // include closed tickets when the query does not say
	// Full adds owner, created and custom fields to each summary.
	Full bool `json:"-"`
}

SearchIn is ka_search's input.

type SearchOut

type SearchOut struct {
	Total   int       `json:"total"`
	Tickets []Summary `json:"tickets"`
}

SearchOut is ka_search's output.

type Service

type Service struct {
	WS *Workspace

	Now      func() time.Time
	NoPush   bool          // commit locally only (ka --no-push)
	PollStep time.Duration // ka_ask wait polling interval

	// Background marks a long-running process (the daemon, ka mcp): it may
	// debounce pushes and run the fetch loop. Call Flush before exiting.
	Background bool
	// contains filtered or unexported fields
}

Service is the operation and query layer shared by the CLI, MCP and REST.

func New

func New(ctx context.Context, ws *Workspace) (*Service, error)

New builds the service and its index.

func (*Service) Activity

func (s *Service) Activity(ctx context.Context, in ActivityIn) (*ActivityOut, error)

Activity reads recent history from git across the workspace's stores and expresses it as the same events the live stream sends (without sequence numbers), so a client renders both alike. ka's own commits are decoded from their Ka-Op trailers; other commits appear as "commit" entries.

func (*Service) ActorFor

func (s *Service) ActorFor(nameOrEmail string) string

ActorFor maps a name, alias or email to an actor handle through the actor registry; anything else is returned as given.

func (*Service) Actors

func (s *Service) Actors() []ActorOut

Actors lists humans and agents with the roles they hold.

func (*Service) Answer

func (s *Service) Answer(ctx context.Context, c Caller, in AnswerIn) (*WriteOut, error)

Answer records an answer or approval.

func (*Service) Ask

func (s *Service) Ask(ctx context.Context, c Caller, in AskIn) (*AskOut, error)

Ask records a question for a human; with Wait it blocks until answered.

func (*Service) BoardFilter

func (s *Service) BoardFilter(ref string) (string, bool)

BoardFilter returns a saved board's filter. ref is "store/key", or a key (the first store that has it).

func (*Service) Boards

func (s *Service) Boards() []BoardOut

Boards lists saved boards from every store, namespaced by store (PRD §9.3: boards are a union; the same key in two stores is two boards).

func (*Service) CallerAs

func (s *Service) CallerAs(principal, actor, session string) Caller

CallerAs builds a caller for an authenticated principal (remote mode, PRD §15): a person acts as themselves; an agent (actor agent/<name>) acts on the principal's behalf. principal may be a handle or an email.

func (*Service) CallerFor

func (s *Service) CallerFor(actor, session string) Caller

CallerFor builds a caller for an actor (empty means the local human).

func (*Service) CheckItems

func (s *Service) CheckItems(ctx context.Context, c Caller, in CheckIn) (*WriteOut, string, error)

CheckItems marks acceptance items done or not done.

func (*Service) Claim

func (s *Service) Claim(ctx context.Context, c Caller, id string, steal bool) (*ClaimOut, error)

Claim claims a ticket for the caller and pushes synchronously.

func (*Service) Comment

func (s *Service) Comment(ctx context.Context, c Caller, in CommentIn) (*WriteOut, error)

Comment adds a note, progress or decision comment.

func (*Service) Commit

func (s *Service) Commit(ctx context.Context, store, sha string) (*CommitOut, error)

Commit returns a commit's message and its diff within the store (the change behind an activity entry).

func (*Service) ConfigExplain

func (s *Service) ConfigExplain(project, key string) (*ConfigExplainOut, error)

ConfigExplain reports each effective config value of a project and the layer it came from, plus locks. key limits the output to that key and the keys under it.

func (*Service) Create

func (s *Service) Create(ctx context.Context, c Caller, ins []CreateIn) (*CreateOut, error)

Create files one or many tickets. Each ticket is its own commit; the batch is pushed once at the end.

func (*Service) DeleteBoard

func (s *Service) DeleteBoard(ctx context.Context, c Caller, ref string) error

DeleteBoard removes a saved board ("store/key", or a key) with a commit.

func (*Service) Doc

func (s *Service) Doc(project, rel string) (*DocOut, error)

Doc returns one project doc and its backlinks.

func (*Service) Docs

func (s *Service) Docs(project string) (*DocsOut, error)

Docs lists the files under projects/<key>/docs/ (every project when project is empty), sorted by project and path.

func (*Service) ETag

func (s *Service) ETag(id string) (string, error)

ETag returns the blob SHA of a ticket's ticket.md as the index has it.

func (*Service) FetchLoop

func (s *Service) FetchLoop(ctx context.Context)

FetchLoop syncs each store with a remote every FetchInterval, and whenever Kick is called, until ctx is done. Fetched changes reach the index (and so the event stream) like any other.

func (*Service) Fix

func (s *Service) Fix(ctx context.Context, c Caller, dryRun bool) (*FixOut, error)

Fix normalizes data in the writable stores (PRD §10.5): timestamps on hand-written tickets, actor aliases, and canonical formatting (encoding, key order, quoting). Each category is committed separately.

func (*Service) Flush

func (s *Service) Flush(ctx context.Context)

Flush pushes every store with debounced commits now. Long-running processes call it before they exit.

func (*Service) Get

func (s *Service) Get(in GetIn) (*Detail, error)

Get returns a ticket with a digest of its comments.

func (*Service) Human

func (s *Service) Human() string

Human returns the detected principal.

func (*Service) Inbox

func (s *Service) Inbox(c Caller, since string) *InboxOut

Inbox lists answers to the caller's questions since a time, and open questions addressed to the caller (or a role they hold).

func (*Service) Index

func (s *Service) Index() *Index

Index exposes the index (read-only use).

func (*Service) Kick

func (s *Service) Kick(store string)

Kick asks the fetch loop to sync a store now ("" means every store), as a forge webhook does. It never blocks.

func (*Service) MoveProject

func (s *Service) MoveProject(ctx context.Context, c Caller, key, to string, dryRun bool) (*MoveProjectOut, error)

MoveProject moves a project to another store in the workspace (PRD §9.2): it copies projects/<key>/ into the target with one commit, then replaces it in the source with a project.yml tombstone (moved_to_store) in a second commit. Ticket IDs and paths do not change, so references from other stores still resolve. The target is pushed first; the source is pushed only once the target has the project.

func (*Service) Next

func (s *Service) Next(ctx context.Context, c Caller, in NextIn) (*NextOut, error)

Next picks the best ready ticket and, unless peeking, claims it. A claim lost to a concurrent agent moves on to the next candidate.

func (*Service) Ops

func (s *Service) Ops() *OpStats

Ops returns the service's operation statistics.

func (*Service) Projects

func (s *Service) Projects() []string

Projects lists project keys.

func (*Service) Release

func (s *Service) Release(ctx context.Context, c Caller, id, status string, force bool) (*WriteOut, error)

Release gives up a claim, optionally moving the ticket.

func (*Service) Reload

func (s *Service) Reload()

Reload rebuilds the index from disk.

func (*Service) ReplaceTicket

func (s *Service) ReplaceTicket(ctx context.Context, c Caller, id string, data []byte, ifMatch string) (*WriteOut, error)

ReplaceTicket commits a hand-edited ticket.md (ka edit with $EDITOR). The edit is validated first and recorded as an update of the changed fields, so it replays like any other operation. A non-empty ifMatch requires the file on disk to still have that blob SHA.

func (s *Service) ResolveLink(link string) (*LinkOut, error)

ResolveLink turns repo://path[@ref][#Lline] into a local path or forge URL.

func (*Service) RestorePreserved

func (s *Service) RestorePreserved(ctx context.Context, c Caller, id, comment string) (*WriteOut, error)

RestorePreserved re-applies an operation that a sync could not replay (PRD §10.4: nothing is lost silently; §13.2: a "restore" action). The operation is read from the system comment that preserved it and applied again now, attributed to the caller. Its preconditions are checked against the current ticket, so a claim someone else holds still fails.

func (*Service) SaveBoard

func (s *Service) SaveBoard(ctx context.Context, c Caller, in BoardIn) (*BoardOut, error)

SaveBoard writes boards/<key>.yml in a store and commits it, like any other change (PRD §13.2, saved boards).

func (*Service) Schema

func (s *Service) Schema(c Caller, project string) (*SchemaOut, error)

Schema describes the workspace (optionally one project).

func (*Service) Search

func (s *Service) Search(in SearchIn) (*SearchOut, error)

Search runs a query.

func (*Service) SetEvents

func (s *Service) SetEvents(sink EventSink)

SetEvents makes the service publish domain events to sink.

func (*Service) Stores

func (s *Service) Stores(ctx context.Context) []StoreOut

Stores lists the workspace's stores with their sync state.

func (*Service) StoresForRepo

func (s *Service) StoresForRepo(urls ...string) []string

StoresForRepo names the stores whose remote is one of urls, compared as host/path whatever the scheme (git@host:org/repo.git and https://host/org/repo are the same repository). Forge webhooks use it.

func (*Service) Sync

func (s *Service) Sync(ctx context.Context, force bool) *SyncOut

Sync syncs every store (when force is set) and reports state.

func (*Service) TicketCounts

func (s *Service) TicketCounts() map[[2]string]int

TicketCounts counts tickets by project and status category.

func (*Service) TicketPath

func (s *Service) TicketPath(id string) (string, *Store, error)

TicketPath returns the absolute path of a ticket's ticket.md.

func (*Service) Transition

func (s *Service) Transition(ctx context.Context, c Caller, in TransitionIn) (*WriteOut, error)

Transition changes status. Closing requires a resolution and summary, recorded as a resolution comment in the same commit.

func (*Service) Update

func (s *Service) Update(ctx context.Context, c Caller, ins []UpdateIn) ([]*WriteOut, error)

Update patches one or many tickets (one commit each, one push per store).

func (*Service) Validate

func (s *Service) Validate(now time.Time) []kaspec.Diagnostic

Validate runs ka check over the workspace.

func (*Service) WatchLocal

func (s *Service) WatchLocal(ctx context.Context, every time.Duration)

WatchLocal notices commits made by other processes sharing the clones (the CLI, another ka mcp) every interval, so their events reach subscribers without waiting for the next request.

func (*Service) WorkspaceInfo

func (s *Service) WorkspaceInfo() *WorkspaceOut

WorkspaceInfo describes the workspace.

type Store

type Store struct {
	Name     string // workspace name (unique)
	Root     string // absolute store root
	URL      string // remote URL, when known
	Managed  bool   // ka owns the clone
	ReadOnly bool   // reached only through extends, or unsupported spec
	PushMode string // immediate (default), manual or debounce
	// PushDelay is the quiet period before a debounced push.
	PushDelay time.Duration
	// FetchInterval is how often a long-running process fetches (0: 15 s).
	FetchInterval time.Duration
	// contains filtered or unexported fields
}

Store is one store in the workspace: a directory inside a git working tree.

func OpenStore

func OpenStore(ctx context.Context, name, dir string) (*Store, error)

OpenStore opens a store rooted at dir (which must be inside a git working tree).

func (*Store) Activity

func (s *Store) Activity() (lastFetch, lastPush time.Time, lastErr string)

Activity reports when the store last fetched and pushed, and the last network error if it is newer than both.

func (*Store) Do

func (s *Store) Do(ctx context.Context, h hooks, o *Op, push bool) (*Result, error)

Do applies and commits one operation, then pushes it when the store has a remote and push is requested. If the remote moved, local commits are replayed on top of it, which re-checks this operation's preconditions; an operation that no longer applies (for example a claim someone else won) returns its error and leaves no commit behind.

func (*Store) FetchOnly

func (s *Store) FetchOnly(ctx context.Context, h hooks) (*Result, error)

FetchOnly brings in upstream changes (replaying local commits on top) but does not push: for manual and debounced stores in the fetch loop.

func (*Store) Git

func (s *Store) Git() *gitx.Repo

Git exposes the store's repository.

func (*Store) PushSetting

func (st *Store) PushSetting() string

PushSetting renders a store's push mode as configured.

func (*Store) State

func (s *Store) State(ctx context.Context) SyncState

State reports sync status without touching the network.

func (*Store) Sync

func (s *Store) Sync(ctx context.Context, h hooks) (*Result, error)

Sync fetches, integrates and pushes (ka sync).

type StoreOut

type StoreOut struct {
	SyncState
	Root          string `json:"root"`
	URL           string `json:"url,omitempty"`
	Managed       bool   `json:"managed"`
	ReadOnly      bool   `json:"read_only,omitempty"`
	PushMode      string `json:"push_mode" doc:"immediate, manual or debounce:<delay>"`
	FetchInterval string `json:"fetch_interval" doc:"How often the daemon fetches."`
	LastFetch     string `json:"last_fetch,omitempty" doc:"When this process last fetched successfully."`
	LastPush      string `json:"last_push,omitempty" doc:"When this process last pushed successfully."`
	LastError     string `json:"last_error,omitempty" doc:"The last fetch or push error, if newer than the last success."`
	PushPending   bool   `json:"push_pending,omitempty" doc:"A debounced push is scheduled."`
}

StoreOut is one store and its sync state.

type StoreSpec

type StoreSpec struct {
	Name   string
	URL    string // remote; ka keeps a managed clone
	Branch string
	Path   string // attached checkout (store root)
	Push   string // immediate | manual | debounce[:2s]
	// FetchInterval overrides how often the daemon fetches this store.
	FetchInterval string
}

StoreSpec is one stores: entry.

type Summary

type Summary struct {
	ID         string   `json:"id"`
	Title      string   `json:"title"`
	Status     string   `json:"status"`
	Priority   string   `json:"priority,omitempty"`
	Kind       string   `json:"kind,omitempty"`
	Labels     []string `json:"labels,omitempty"`
	Assignee   string   `json:"assignee,omitempty"`
	Claim      *Claim   `json:"claim,omitempty"`
	Parent     string   `json:"parent,omitempty"`
	Blocked    bool     `json:"blocked,omitempty"`
	Acceptance string   `json:"acceptance,omitempty"` // "2/5"
	Project    string   `json:"project"`
	Updated    string   `json:"updated,omitempty"`
	// Filled for ka_get, events, and searches with include=fields (the
	// table view's columns); empty in agent-facing lists to save tokens.
	Owner   string         `json:"owner,omitempty"`
	Created string         `json:"created,omitempty"`
	Fields  map[string]any `json:"fields,omitempty"`
}

Summary is the compact form of a ticket used in lists.

type SyncOut

type SyncOut struct {
	Stores    []SyncState       `json:"stores"`
	Preserved []string          `json:"preserved,omitempty"` // written during this sync
	Conflicts []InboxItem       `json:"conflicts,omitempty"` // recent preserved-conflict comments
	Errors    []*Error          `json:"errors,omitempty"`
	Renamed   map[string]string `json:"renamed,omitempty"`
}

SyncOut is ka_sync's output.

type SyncState

type SyncState struct {
	Store    string `json:"store"`
	Remote   string `json:"remote,omitempty"`
	Branch   string `json:"branch,omitempty"`
	Ahead    int    `json:"ahead"`
	Behind   int    `json:"behind"`
	State    string `json:"state"` // local (no remote), synced, ahead, behind, diverged, degraded, busy
	Detail   string `json:"detail,omitempty"`
	Head     string `json:"head,omitempty"`
	Attached bool   `json:"attached"`
}

SyncState summarizes a store's relation to its remote.

type TicketEvent

type TicketEvent struct {
	Ticket      Summary                `json:"ticket"`
	Changes     map[string]FieldChange `json:"changes,omitempty"`
	BodyChanged bool                   `json:"body_changed,omitempty"`
	From        string                 `json:"from,omitempty"` // ticket.moved: the old status
	To          string                 `json:"to,omitempty"`   // ticket.moved: the new status
	Category    string                 `json:"category,omitempty"`
}

TicketEvent is the payload of ticket.created, ticket.updated and ticket.moved.

type TransitionIn

type TransitionIn struct {
	ID         string `json:"id"`
	Status     string `json:"status"`
	Resolution string `json:"resolution,omitempty"`
	Summary    string `json:"summary,omitempty"`
}

TransitionIn is ka_transition's input.

type UpdateIn

type UpdateIn struct {
	ID     string              `json:"id"`
	Set    map[string]any      `json:"set,omitempty"`
	Add    map[string][]string `json:"add,omitempty"`
	Remove map[string][]string `json:"remove,omitempty"`
	Body   *string             `json:"body,omitempty"`
	// IfMatch makes the update conditional on ticket.md's blob SHA (REST If-Match).
	IfMatch string `json:"if_match,omitempty"`
}

UpdateIn patches one ticket.

type Workspace

type Workspace struct {
	File    *WorkspaceFile // nil for an implicit workspace
	Stores  []*Store
	Project string            // default project
	Repos   map[string]string // repo name -> local checkout
	Actor   string            // configured identity
	Source  string            // how the workspace was found
}

Workspace is a resolved set of stores.

func Open

func Open(ctx context.Context, o OpenOptions) (*Workspace, error)

Open discovers and opens the workspace.

func (*Workspace) StoreByName

func (ws *Workspace) StoreByName(name string) *Store

WriteStore picks the store new tickets for a project go to.

type WorkspaceFile

type WorkspaceFile struct {
	Path     string
	Name     string
	Stores   []StoreSpec
	Actor    string            // identity.actor
	Repos    map[string]string // repo name -> local checkout
	Project  string            // default project
	Offline  bool
	Explicit bool
}

WorkspaceFile is a workspace definition (PRD §9.1), read from --workspace, $KA_WORKSPACE, ./.ka-workspace.yml (searched upward) or <user config dir>/ka/workspace.yml.

func ParseWorkspaceFile

func ParseWorkspaceFile(p string) (*WorkspaceFile, error)

ParseWorkspaceFile reads a workspace definition.

type WorkspaceOut

type WorkspaceOut struct {
	Name           string   `json:"name,omitempty"`
	Source         string   `json:"source"` // the file or directory the workspace was found from
	DefaultProject string   `json:"default_project,omitempty"`
	Stores         []string `json:"stores"`
	Projects       []string `json:"projects"`
	You            string   `json:"you"`
}

WorkspaceOut describes the workspace a service runs on.

type WriteOut

type WriteOut struct {
	ID        string   `json:"id"`
	Status    string   `json:"status,omitempty"`
	Pushed    bool     `json:"pushed"`
	Local     bool     `json:"local_only,omitempty"` // the store has no remote
	PushError string   `json:"push_error,omitempty"`
	Comment   string   `json:"comment,omitempty"`
	Unblocked []string `json:"unblocked,omitempty"`
	Commit    string   `json:"commit,omitempty"`
	Preserved []string `json:"preserved,omitempty"`
	NoChange  bool     `json:"no_change,omitempty"`
	// PushPending: committed; a debounced push follows within seconds.
	PushPending bool `json:"push_pending,omitempty"`
}

WriteOut is the compact result of a write.

Jump to

Keyboard shortcuts

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