kaspec

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 19 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 kaspec implements the KanArtist Store Spec v1: parsing, canonical formatting, config layering and validation of store contents.

The spec itself lives in spec/v1/README.md. This package is one implementation of it; the conformance corpus in spec/v1/conformance is the arbiter when the two disagree.

Index

Constants

View Source
const Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

Alphabet is Crockford base32: digits and upper-case letters without I, L, O, U.

View Source
const DefaultSuffixLength = 5

DefaultSuffixLength is the default length of the random part of a ticket ID.

View Source
const SpecVersion = 1

SpecVersion is the major Store Spec version this package reads and writes.

Variables

View Source
var (
	// IDRe matches a ticket ID: PREFIX-SUFFIX.
	IDRe = regexp.MustCompile(`^([A-Z][A-Z0-9]{0,9})-([0-9A-HJKMNP-TV-Z]{5,8})$`)
	// PrefixRe matches a project ID prefix.
	PrefixRe = regexp.MustCompile(`^[A-Z][A-Z0-9]{0,9}$`)
	// ProjectKeyRe matches a project key (also its directory name).
	ProjectKeyRe = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
	// ActorRe matches an actor handle: a human, agent/<name> or role/<name>.
	ActorRe = regexp.MustCompile(`^((agent|role)/)?[a-z0-9][a-z0-9._-]{0,63}$`)
	// HumanRe matches a human actor handle.
	HumanRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
	// AgentRe matches an agent actor handle.
	AgentRe = regexp.MustCompile(`^agent/[a-z0-9][a-z0-9._-]{0,63}$`)
	// TimestampRe matches the canonical timestamp form: RFC 3339, UTC, whole seconds.
	TimestampRe = regexp.MustCompile(`^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\dZ$`)
	// DateRe matches a calendar date.
	DateRe = regexp.MustCompile(`^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$`)
	// CommentFileRe matches a comment filename: <yyyymmddThhmmssZ>-<4 base32>.md
	CommentFileRe = regexp.MustCompile(`^(\d{8}T\d{6}Z)-([0-9A-HJKMNP-TV-Z]{4})\.md$`)
	// LinkRe matches a symbolic code link: repo://path[@ref][#Lstart[-end]].
	LinkRe = regexp.MustCompile(`^([a-z][a-z0-9-]{0,31})://([^@#\s]+)(@[^#\s]+)?(#L[0-9]+(-L?[0-9]+)?)?$`)
)
View Source
var Categories = []string{"triage", "backlog", "unstarted", "started", "completed", "canceled"}

Categories is the fixed set of workflow categories.

View Source
var Codes = map[string]Severity{

	"crlf":                SevError,
	"bom":                 SevError,
	"frontmatter_missing": SevError,
	"yaml_syntax":         SevError,
	"yaml_feature":        SevError,
	"duplicate_key":       SevError,
	"non_canonical":       SevWarning,

	"unknown_key":         SevError,
	"missing_field":       SevError,
	"invalid_value":       SevError,
	"unknown_status":      SevError,
	"unknown_kind":        SevError,
	"unknown_label":       SevError,
	"unknown_field":       SevError,
	"invalid_field_value": SevError,
	"placeholder_text":    SevWarning,
	"low_entropy_id":      SevWarning,
	"unknown_repo":        SevWarning,

	"invalid_store":             SevError,
	"spec_unsupported":          SevError,
	"project_key_mismatch":      SevError,
	"project_missing_file":      SevError,
	"ticket_missing_file":       SevError,
	"id_dir_mismatch":           SevError,
	"id_prefix_mismatch":        SevError,
	"duplicate_project":         SevError,
	"moved_project_has_tickets": SevWarning,
	"duplicate_prefix":          SevError,
	"duplicate_id":              SevError,
	"stray_file":                SevWarning,
	"comment_filename":          SevError,
	"comment_time_mismatch":     SevWarning,

	"dangling_ref":    SevError,
	"external_ref":    SevInfo,
	"self_ref":        SevError,
	"cycle":           SevError,
	"answer_dangling": SevError,

	"stale_claim":       SevInfo,
	"archived_project":  SevInfo,
	"secret_suspect":    SevWarning,
	"comment_too_large": SevWarning,
	"file_too_large":    SevWarning,

	"config_invalid":            SevError,
	"config_locked":             SevError,
	"config_cycle":              SevError,
	"config_parent_unavailable": SevError,
}

Codes is the registry of diagnostic codes and their severities. It is the single source of truth; spec/v1/README.md restates it and a test fails if the two disagree.

View Source
var CommentKeys = []string{
	"type", "author", "on_behalf_of", "session", "created", "to",
	"answers", "choice", "approved", "resolution", "supersedes", "retracts", "options",
}

CommentKeys is the canonical frontmatter key order of a comment.

View Source
var CommentTypes = []string{"note", "progress", "question", "answer", "decision", "resolution", "approval", "system"}

CommentTypes is the fixed comment type vocabulary.

View Source
var ConfigKeys = []string{"id_suffix_length", "workflow", "kinds", "labels", "fields", "claims", "comments", "attachments", "template", "locked", "runtime"}

ConfigKeys is the set of top-level keys allowed in .ka/config.yml and a project's config block.

View Source
var FieldTypes = []string{"string", "text", "number", "integer", "boolean", "enum", "date", "timestamp", "actor", "url", "id", "list"}

FieldTypes is the set of custom field types.

View Source
var Priorities = []string{"P0", "P1", "P2", "P3"}

Priorities is the fixed priority vocabulary, highest first.

View Source
var Resolutions = []string{"done", "canceled", "duplicate", "wontfix"}

Resolutions is the fixed resolution vocabulary.

View Source
var TicketKeys = []string{
	"id", "title", "status", "priority", "kind", "labels",
	"assignee", "owner", "claim",
	"parent", "blocked_by", "related", "duplicate_of",
	"links", "acceptance", "milestone", "due", "fields", "moved_to",
	"created", "created_by", "updated",
}

TicketKeys is the canonical frontmatter key order of ticket.md.

Functions

func CommentFilename

func CommentFilename(created, suffix string) string

CommentFilename builds a comment filename from a canonical timestamp and a 4-character suffix.

func DefaultPrefix

func DefaultPrefix(key string) string

DefaultPrefix derives a project's ID prefix from its key when project.yml omits one.

func DefaultsYAML

func DefaultsYAML() []byte

DefaultsYAML returns the built-in data-config defaults (spec §6.2).

func EmitYAML

func EmitYAML(m []KV) string

EmitYAML renders an ordered mapping as canonical YAML.

func FormatComment

func FormatComment(c *Comment) []byte

FormatComment renders a comment in canonical form.

func FormatTicket

func FormatTicket(t *Ticket) []byte

FormatTicket renders a ticket in canonical form. Set-valued lists (labels, blocked_by, related) are sorted and de-duplicated.

func HasErrors

func HasErrors(ds []Diagnostic, strict bool) bool

HasErrors reports whether any diagnostic is an error (or, when strict, a warning).

func HashBase32

func HashBase32(seed string, n int) string

HashBase32 derives n base32 characters deterministically from a seed. Used by importers that must assign the same ID on every run.

func Join

func Join(elem ...string) string

Join is path.Join for store-relative paths.

func LowEntropy

func LowEntropy(suffix string) bool

LowEntropy flags suffixes that look hand-made rather than random: fewer than three distinct characters, or a straight run through the alphabet.

func NewID

func NewID(prefix string, n int) string

NewID returns a fresh random ID with the given prefix and suffix length.

func NormalizeEncoding

func NormalizeEncoding(data []byte) []byte

NormalizeEncoding strips a BOM and converts CRLF/CR to LF.

func ParseActors

func ParseActors(p string, data []byte) (*Actors, []Diagnostic)

ParseActors parses .ka/actors.yml.

func ParseBoard

func ParseBoard(p string, data []byte) (*Board, []Diagnostic)

ParseBoard parses boards/<name>.yml.

func ParseComment

func ParseComment(path string, data []byte) (*Comment, []Diagnostic)

ParseComment parses a comment file.

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration accepts Go durations plus a whole-day form such as "7d".

func ParseID

func ParseID(id string) (prefix, suffix string, ok bool)

ParseID splits a ticket ID into prefix and suffix.

func ParseProjectFile

func ParseProjectFile(p string, data []byte) (*ProjectFile, []Diagnostic)

ParseProjectFile parses projects/<key>/project.yml.

func ParseStoreFile

func ParseStoreFile(p string, data []byte) (*StoreFile, []Diagnostic)

ParseStoreFile parses .ka/store.yml.

func ParseTicket

func ParseTicket(path string, data []byte) (*Ticket, []Diagnostic)

ParseTicket parses ticket.md. Diagnostics cover encoding, syntax and the config-independent rules; config-dependent rules run in Check.

func ProjectConfig

func ProjectConfig(w *Workspace, s *Store, pr *Project) (*Config, []Diagnostic)

ProjectConfig exposes effective config resolution for callers (e.g. `ka config explain`).

func RandomBase32

func RandomBase32(n int) string

RandomBase32 returns n cryptographically random Crockford base32 characters.

func ResolveConfig

func ResolveConfig(layers []ConfigLayer) (*Config, []Diagnostic)

ResolveConfig merges layers bottom-up (built-in defaults first, then each layer in order; later layers win) and decodes the result. Locks set by a layer stop every later layer from changing the locked path.

func SortDiagnostics

func SortDiagnostics(ds []Diagnostic)

SortDiagnostics orders diagnostics deterministically (path, line, code, message).

func ValidateFieldValue

func ValidateFieldValue(def FieldDef, v FieldValue) error

ValidateFieldValue checks a custom field value against its declaration.

Types

type AcceptanceItem

type AcceptanceItem struct {
	Text string `json:"text"`
	Done bool   `json:"done"`
}

AcceptanceItem is one acceptance criterion.

type Actors

type Actors struct {
	Humans map[string]Human
	Agents map[string]string // handle -> display name
	Roles  map[string][]string
}

Actors is .ka/actors.yml.

type Board

type Board struct {
	Name, Description, Filter, GroupBy, Sort, Swimlanes string
	Columns, CardFields                                 []string
}

Board is boards/<name>.yml.

type CheckOptions

type CheckOptions struct {
	Now time.Time // for stale-claim detection; zero disables it
}

CheckOptions tunes Check.

type Claim

type Claim struct {
	By      string `json:"by"`
	Session string `json:"session,omitempty"`
	At      string `json:"at"`
}

Claim records who holds a ticket.

type Comment

type Comment struct {
	Type       string         `json:"type"`
	Author     string         `json:"author,omitempty"`
	OnBehalfOf string         `json:"on_behalf_of,omitempty"`
	Session    string         `json:"session,omitempty"`
	Created    string         `json:"created,omitempty"`
	To         string         `json:"to,omitempty"`
	Answers    string         `json:"answers,omitempty"`
	Choice     *int64         `json:"choice,omitempty"`
	Approved   *bool          `json:"approved,omitempty"`
	Resolution string         `json:"resolution,omitempty"`
	Supersedes string         `json:"supersedes,omitempty"`
	Retracts   string         `json:"retracts,omitempty"`
	Options    []string       `json:"options,omitempty"`
	Body       string         `json:"body,omitempty"`
	Lines      map[string]int `json:"-"`
}

Comment is one append-only comment file.

type CommentEntry

type CommentEntry struct {
	Name    string
	Path    string
	Comment *Comment
	Raw     []byte
}

CommentEntry is a loaded comment file.

type Config

type Config struct {
	IDSuffixLength      int
	Statuses            []Status
	Initial             string
	AgentCreatedInitial string
	Kinds               []string
	LabelsClosed        bool
	LabelsKnown         []string
	FieldOrder          []string
	Fields              map[string]FieldDef
	ClaimsStaleAfter    time.Duration
	CommentsMaxBytes    int64
	ProgressMinInterval time.Duration
	AttachmentsMaxBytes int64
	TemplateSections    []string
	Locked              []string
	Runtime             *Node // class 3; not validated here

	// Sources maps a dotted key path to the layer that last set it, and
	// SourceLines to the line in that layer (0 for built-in defaults).
	Sources     map[string]string
	SourceLines map[string]int
	SourceNotes map[string]string // e.g. "patched with $append/$remove"
	// Layers names the layers merged, lowest first (built-in defaults first).
	Layers []string
	// Effective is the merged config tree (for `ka config explain`).
	Effective *Node
	// LockedBy maps a locked path to the layer that locked it.
	LockedBy map[string]string
}

Config is the effective data config of a project.

func (*Config) StatusByName

func (c *Config) StatusByName(name string) (Status, bool)

StatusByName returns the status with the given name.

func (*Config) StatusNames

func (c *Config) StatusNames() []string

StatusNames lists the workflow's status names.

type ConfigLayer

type ConfigLayer struct {
	Name string // shown in diagnostics and `ka config explain`, e.g. "org/.ka/config.yml"
	Path string // diagnostic path
	Node *Node  // a mapping; nil for an absent file
}

ConfigLayer is one layer of a config chain.

type Diagnostic

type Diagnostic struct {
	Code     string   `json:"code"`
	Severity Severity `json:"severity"`
	Path     string   `json:"path"`           // slash-separated, relative to the store root (or workspace label)
	Line     int      `json:"line,omitempty"` // 1-based; 0 when not applicable
	Message  string   `json:"message"`
	Fix      string   `json:"fix,omitempty"` // a one-line hint on how to fix it
}

Diagnostic is one finding from parsing or checking a store.

func Check

func Check(w *Workspace, opt CheckOptions) []Diagnostic

Check validates every store in the workspace, including cross-store rules.

func (Diagnostic) String

func (d Diagnostic) String() string

type FieldDef

type FieldDef struct {
	Type        string   `json:"type"`
	Values      []string `json:"values,omitempty"` // enum values
	Description string   `json:"description,omitempty"`
}

FieldDef declares a custom field.

type FieldValue

type FieldValue struct {
	Scalar string   `json:"v,omitempty"`
	Typed  bool     `json:"typed,omitempty"` // unquoted integer, boolean or date literal; emitted verbatim
	List   []string `json:"list,omitempty"`
	IsList bool     `json:"is_list,omitempty"`
	Line   int      `json:"-"`
}

FieldValue is the value of a custom field: a scalar or a list of strings.

type FileEntry

type FileEntry struct {
	Path string
	Size int64
}

FileEntry is an attachment.

type Human

type Human struct {
	Name    string
	Emails  []string
	Aliases []string
}

Human is a human actor.

type KV

type KV struct {
	K string
	V any
}

KV is one key/value pair of an ordered mapping.

type Node

type Node struct {
	Kind   NodeKind
	Value  string // scalar text
	Quoted bool   // scalar was quoted or block-style (always a string)
	Line   int

	Keys     []string // mapping keys in source order
	Map      map[string]*Node
	KeyLines map[string]int

	Items []*Node
}

Node is a YAML value parsed under the KanArtist YAML profile: no anchors, aliases, tags, merge keys or duplicate keys, and NO implicit typing. A scalar is kept as its source text; the reader of a field decides whether it is a string, a boolean, an integer or a date. That is what keeps `title: no` a string and `version: 1.10` from becoming 1.1.

func ParseYAML

func ParseYAML(src []byte) (*Node, error)

ParseYAML parses one YAML document under the KanArtist profile. An empty document yields an empty mapping.

func (*Node) ToAny

func (n *Node) ToAny() any

ToAny converts a Node into plain Go values for JSON-schema validation: unquoted true/false become booleans, unquoted integers become int64, everything else is a string.

type NodeKind

type NodeKind int

NodeKind classifies a parsed YAML value.

const (
	NullNode NodeKind = iota
	ScalarNode
	MapNode
	SeqNode
)

type Parent

type Parent struct {
	URL string
	Ref string
}

Parent is one entry of store.yml `extends`.

type ParentResolver

type ParentResolver func(from *Store, p Parent) (fsys fs.FS, key, label string, err error)

ParentResolver locates a parent store named in `extends`. It returns the parent's filesystem, a stable identity key (two references to the same store must return the same key) and a display label.

type Project

type Project struct {
	Key     string
	Dir     string
	File    *ProjectFile
	Tickets map[string]*TicketEntry
	IDs     []string // sorted
	Config  *Config  // effective config (set by Check)
}

Project is a loaded project.

type ProjectFile

type ProjectFile struct {
	Key          string
	Prefix       string
	Name         string
	Description  string
	Archived     bool
	Repos        map[string]Repo
	Config       *Node
	MovedToStore string
}

ProjectFile is projects/<key>/project.yml.

type Raw

type Raw string

Raw is a scalar emitted verbatim (the caller guarantees it is a valid typed literal).

type Repo

type Repo struct {
	Forge         string
	DefaultBranch string
}

Repo is a code repository a project's links can point into.

type Severity

type Severity string

Severity of a diagnostic.

const (
	SevError   Severity = "error"
	SevWarning Severity = "warning"
	SevInfo    Severity = "info"
)

type Status

type Status struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	Blocked  bool   `json:"blocked,omitempty"`
}

Status is one workflow status.

type Store

type Store struct {
	Label    string // display name used as the diagnostic path prefix
	FS       fs.FS
	File     *StoreFile
	Config   *Node // .ka/config.yml (nil when absent)
	Actors   *Actors
	Boards   map[string]*Board
	Projects map[string]*Project
	Keys     []string // project keys, sorted
	// Moved maps the key of a tombstoned project (moved_to_store) to the
	// store it moved to. Tombstones are not in Projects or Keys.
	Moved     map[string]string
	Diags     []Diagnostic
	ParentFor func(Parent) (*Store, error) // set by the workspace
}

Store is a loaded store.

func LoadStore

func LoadStore(fsys fs.FS, label string) *Store

LoadStore reads a store rooted at fsys. Label prefixes diagnostic paths (use "" for a single store). Parsing diagnostics are collected in Store.Diags; cross-file rules run in Check.

func (*Store) LoadTicket

func (s *Store) LoadTicket(tdir string) (*TicketEntry, []Diagnostic)

LoadTicket reads one ticket directory (relative to the store root).

type StoreFile

type StoreFile struct {
	Spec        int
	Name        string
	Description string
	Extends     []Parent
}

StoreFile is .ka/store.yml.

type Ticket

type Ticket struct {
	ID          string                `json:"id,omitempty"`
	Title       string                `json:"title,omitempty"`
	Status      string                `json:"status,omitempty"`
	Priority    string                `json:"priority,omitempty"`
	Kind        string                `json:"kind,omitempty"`
	Labels      []string              `json:"labels,omitempty"`
	Assignee    string                `json:"assignee,omitempty"`
	Owner       string                `json:"owner,omitempty"`
	Claim       *Claim                `json:"claim,omitempty"`
	Parent      string                `json:"parent,omitempty"`
	BlockedBy   []string              `json:"blocked_by,omitempty"`
	Related     []string              `json:"related,omitempty"`
	DuplicateOf string                `json:"duplicate_of,omitempty"`
	Links       []string              `json:"links,omitempty"`
	Acceptance  []AcceptanceItem      `json:"acceptance,omitempty"`
	Milestone   string                `json:"milestone,omitempty"`
	Due         string                `json:"due,omitempty"`
	Fields      map[string]FieldValue `json:"fields,omitempty"`
	MovedTo     string                `json:"moved_to,omitempty"`
	Created     string                `json:"created,omitempty"`
	CreatedBy   string                `json:"created_by,omitempty"`
	Updated     string                `json:"updated,omitempty"`
	Body        string                `json:"body,omitempty"`

	// Lines maps frontmatter keys to their line numbers (for diagnostics).
	Lines map[string]int `json:"-"`
}

Ticket is the parsed content of ticket.md.

type TicketEntry

type TicketEntry struct {
	Dir      string // relative to the store root
	Ticket   *Ticket
	Raw      []byte
	Comments []*CommentEntry
	Files    []FileEntry
}

TicketEntry is a loaded ticket directory.

type Workspace

type Workspace struct {
	Stores  []*Store
	Resolve ParentResolver
	// contains filtered or unexported fields
}

Workspace is a set of stores checked together.

func NewWorkspace

func NewWorkspace(resolve ParentResolver) *Workspace

NewWorkspace returns an empty workspace.

func (*Workspace) Add

func (w *Workspace) Add(fsys fs.FS, key, label string) *Store

Add loads a store into the workspace. key identifies the store's location (e.g. its absolute path); label prefixes its diagnostic paths.

func (*Workspace) AddLoaded

func (w *Workspace) AddLoaded(s *Store, key string)

AddLoaded adds an already loaded store (see Add).

func (*Workspace) KeyOf

func (w *Workspace) KeyOf(s *Store) string

KeyOf returns the identity key of any store the workspace has loaded, including parents pulled in through extends.

type YAMLError

type YAMLError struct {
	Code string // yaml_syntax | yaml_feature | duplicate_key
	Line int
	Msg  string
}

YAMLError is a syntax or profile violation.

func (*YAMLError) Error

func (e *YAMLError) Error() string

Jump to

Keyboard shortcuts

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