kanban

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 65 Imported by: 1 module, 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 (
	DefaultClaimTTLSeconds               = 15 * 60
	DefaultClaimHeartbeatMaxStaleSeconds = 60 * 60
	ReclaimDeferGraceSeconds             = 120
	DefaultCrashGraceSeconds             = 30
	KanbanRateLimitExitCode              = tools.KanbanRateLimitExitCode
	KanbanTerminalProviderExitCode       = tools.KanbanTerminalProviderExitCode
)
View Source
const (
	MemoryGuardMBPerWorker      = 512
	DerivedMaxInProgressFloor   = 2
	DerivedMaxInProgressCeiling = 8
)
View Source
const (
	DefaultFailureLimit             = 2
	DefaultRateLimitCooldownSeconds = 300
	UnverifiedWorkerFingerprint     = "unverified"
)
View Source
const (
	KanbanListDefaultLimit = 50
	KanbanListMaxLimit     = 200
)
View Source
const (
	ArchiveFormat        = "icebath-kanban-board"
	ArchiveFormatVersion = 1
)
View Source
const (
	DefaultLogRotateBytes = 2 * 1024 * 1024
	DefaultLogBackupCount = 1
)
View Source
const AdmissionAnswerMarginSeconds = 60.0

AdmissionAnswerMarginSeconds covers the owner's session setup and receipt around its admission write

View Source
const Archived = "archived"

Status outside every workflow, a filter toggle and never a board column

View Source
const BlackboardPrefix = "[swarm:blackboard] "

BlackboardPrefix opens every structured blackboard comment on a swarm root

View Source
const BlockRecurrenceLimit = 2

Unblock loop count after which a recurring block escalates

View Source
const DefaultBoard = "default"

Board whose database stays at the legacy root kanban.db

View Source
const DefaultBusyTimeoutMS = 120_000

Busy timeout kanban connections use unless ICEBATH_KANBAN_BUSY_TIMEOUT_MS overrides it

View Source
const DefaultMaxRecoveryAttempts = 3

Recovery attempts made when ICEBATH_KANBAN_TURN_RECOVERY is unset

View Source
const KanbanAttachmentMaxBytes = 25 * 1024 * 1024

Attachment size cap shared by the tools and CLI

View Source
const KanbanTerminalTimeoutGraceSeconds = 30
View Source
const KanbanWorkerClientEntry = "__icebath_kanban_worker_client__"

KanbanWorkerClientEntry is the argv word that runs this binary as the kanban worker client

View Source
const SchemaSQL = `
CREATE TABLE IF NOT EXISTS tasks (
    id                   TEXT PRIMARY KEY,
    title                TEXT NOT NULL,
    body                 TEXT,
    assignee             TEXT,
    status               TEXT NOT NULL,
    priority             INTEGER DEFAULT 0,
    created_by           TEXT,
    created_at           INTEGER NOT NULL,
    started_at           INTEGER,
    completed_at         INTEGER,
    workspace_kind       TEXT NOT NULL DEFAULT 'scratch',
    workspace_path       TEXT,
    branch_name          TEXT,
    -- Optional link to a first-class Project (projects.db of the profile). When set,
    -- the task's worktree is anchored under the project's primary repo with a
    -- deterministic branch name instead of a random wt/<task-id> fallback.
    project_id           TEXT,
    claim_lock           TEXT,
    claim_expires        INTEGER,
    tenant               TEXT,
    result               TEXT,
    idempotency_key      TEXT,
    -- Unified consecutive-failure counter. Incremented on spawn
    -- failure, timeout, or crash; reset only on successful completion.
    -- The circuit breaker in _record_task_failure trips when this
    -- exceeds DEFAULT_FAILURE_LIMIT consecutive non-successes.
    consecutive_failures INTEGER NOT NULL DEFAULT 0,
    worker_pid           INTEGER,
    -- Restart-stable fingerprint of worker_pid ("<boot/instantiation epoch>|<start time>",
    -- kanban_db_dispatch._process_fingerprint) recorded at spawn: liveness and kills require pid
    -- AND fingerprint to agree, so a PID recycled after a reboot is never read as our worker or
    -- signalled. NULL = legacy row (pre-fingerprint spawn); 'unverified' = capture failed at
    -- spawn (held while live, never signalled). Column keeps its INTEGER affinity for the
    -- start-time-only integer values older rows carry.
    worker_started_at    INTEGER,
    -- Short excerpt of the most recent failure's error text.
    last_failure_error   TEXT,
    max_runtime_seconds  INTEGER,
    last_heartbeat_at    INTEGER,
    -- Pointer into task_runs for the currently-active run (NULL if no
    -- run is in-flight). Denormalised for cheap reads.
    current_run_id       INTEGER,
    -- Forward-compat for v2 workflow routing. In v1 the kernel writes
    -- these when the task is opted into a template but otherwise ignores
    -- them; the dispatcher doesn't consult them for routing yet.
    workflow_template_id TEXT,
    current_step_key     TEXT,
    -- Force-loaded skills for the worker on this task, stored as JSON.
    -- Passed to the worker via ` + "`" + `--skills` + "`" + `. NULL or empty array = no extras.
    skills               TEXT,
    -- Per-task model override. When set, the dispatcher passes -m <model>
    -- to the worker, overriding the profile's default model. NULL = use
    -- the profile default.
    model_override       TEXT,
    -- Provider the model override belongs to. When set (alongside
    -- model_override), the dispatcher passes --provider <name> so the
    -- worker resolves the model against the right backend instead of the
    -- profile's configured provider. NULL = profile provider.
    provider_override    TEXT,
    -- Per-task reasoning effort for the worker (minimal|low|medium|high|
    -- xhigh|max|ultra, or 'none' for thinking off). When set, the dispatcher
    -- passes --reasoning <level> so the worker runs at that depth regardless
    -- of the profile's agent.reasoning_effort. NULL = profile setting.
    reasoning_effort     TEXT,
    -- Per-task override for the consecutive-failure circuit breaker.
    -- The value is the failure count at which the breaker trips — e.g.
    -- ` + "`" + `` + "`" + `max_retries=1` + "`" + `` + "`" + ` blocks on the first failure. NULL (the common
    -- case) falls through to the dispatcher-level ` + "`" + `` + "`" + `kanban.failure_limit` + "`" + `` + "`" + `
    -- config and then ` + "`" + `` + "`" + `DEFAULT_FAILURE_LIMIT` + "`" + `` + "`" + `.
    max_retries          INTEGER,
    -- When 1, the dispatched worker runs in a Ralph-style goal loop: an
    -- auxiliary judge re-evaluates the worker's response against the
    -- card title/body after each turn and feeds a continuation prompt
    -- back into the SAME session until the judge agrees the work is done
    -- or ` + "`" + `` + "`" + `goal_max_turns` + "`" + `` + "`" + ` is exhausted. NULL/0 = classic single-shot
    -- worker (the default).
    goal_mode            INTEGER NOT NULL DEFAULT 0,
    -- Goal-loop turn budget for ` + "`" + `` + "`" + `goal_mode` + "`" + `` + "`" + ` workers. NULL = use the
    -- goals-engine default.
    goal_max_turns       INTEGER,
    -- Originating chat/agent session id when the task was created from
    -- inside an agent loop that propagated ` + "`" + `` + "`" + `ICEBATH_SESSION_ID` + "`" + `` + "`" + `. NULL
    -- for tasks created from the CLI or any path that doesn't
    -- set the env var, and for an id with no ` + "`" + `` + "`" + `sessions` + "`" + `` + "`" + ` row in this
    -- profile's state.db (kanban_create verifies before stamping). Indexed
    -- so per-session list queries stay cheap on larger boards.
    session_id           TEXT,
    -- Typed block reason set by ` + "`" + `` + "`" + `block_task` + "`" + `` + "`" + ` (one of VALID_BLOCK_KINDS, or
    -- NULL for legacy/un-typed blocks). Drives routing: ` + "`" + `` + "`" + `dependency` + "`" + `` + "`" + ` never
    -- sits in ` + "`" + `` + "`" + `blocked` + "`" + `` + "`" + ` (goes to ` + "`" + `` + "`" + `todo` + "`" + `` + "`" + ` for parent-gating); the others go
    -- to ` + "`" + `` + "`" + `blocked` + "`" + `` + "`" + ` for a human. Preserved across unblock so a re-block for
    -- the SAME kind can be recognised as a loop.
    block_kind           TEXT,
    -- Unblock-loop counter. Incremented each time a task is re-blocked for the
    -- same truly-blocked reason after having been unblocked. When it reaches
    -- BLOCK_RECURRENCE_LIMIT the task is routed to ` + "`" + `` + "`" + `triage` + "`" + `` + "`" + ` instead of
    -- ` + "`" + `` + "`" + `blocked` + "`" + `` + "`" + ` so a cron can't spin it forever. Reset to 0 only on a
    -- successful completion — NOT on unblock (resetting on unblock is exactly
    -- the amnesia that let the loop run unbounded).
    block_recurrences    INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE IF NOT EXISTS task_links (
    parent_id  TEXT NOT NULL,
    child_id   TEXT NOT NULL,
    PRIMARY KEY (parent_id, child_id)
);

CREATE TABLE IF NOT EXISTS task_comments (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id    TEXT NOT NULL,
    author     TEXT NOT NULL,
    body       TEXT NOT NULL,
    created_at INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS task_events (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id    TEXT NOT NULL,
    run_id     INTEGER,
    kind       TEXT NOT NULL,
    payload    TEXT,
    created_at INTEGER NOT NULL
);

-- Historical attempt record. Each time the dispatcher claims a task, a
-- new row is created here; claim state, PID, heartbeat, runtime cap,
-- and structured summary all live on the run, not the task. Multiple
-- rows per task id when the task was retried after crash/timeout/block.
-- v2 of the kanban schema will use ` + "`" + `` + "`" + `step_key` + "`" + `` + "`" + ` to drive per-stage
-- workflow routing; in v1 the column is nullable and unused (kernel
-- ignores it).
CREATE TABLE IF NOT EXISTS task_runs (
    id                  INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id             TEXT NOT NULL,
    profile             TEXT,
    step_key            TEXT,
    status              TEXT NOT NULL,
    -- status: running | done | blocked | crashed | timed_out | failed | released
    claim_lock          TEXT,
    claim_expires       INTEGER,
    worker_pid          INTEGER,
    -- Spawn-time start fingerprint of worker_pid (see tasks.worker_started_at). Retained with
    -- worker_pid after the run ends so a worker that outlives its terminal transition can
    -- still be found and reaped; NULL = legacy row, never signalled.
    worker_started_at   INTEGER,
    max_runtime_seconds INTEGER,
    last_heartbeat_at   INTEGER,
    started_at          INTEGER NOT NULL,
    ended_at            INTEGER,
    outcome             TEXT,
    -- outcome: completed | blocked | crashed | timed_out | spawn_failed |
    --          gave_up | reclaimed | (null while still running)
    summary             TEXT,
    metadata            TEXT,
    error               TEXT
);

-- Files attached to a task (PDFs, images, source documents). The blob
-- lives on disk under ` + "`" + `` + "`" + `attachments_root(board)/<task_id>/<stored_name>` + "`" + `` + "`" + `;
-- this row carries metadata + the absolute ` + "`" + `` + "`" + `stored_path` + "`" + `` + "`" + ` so
-- ` + "`" + `` + "`" + `build_worker_context` + "`" + `` + "`" + ` can surface
-- the absolute path to the worker (which has full file-tool access). See
-- #35338.
CREATE TABLE IF NOT EXISTS task_attachments (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    task_id      TEXT NOT NULL,
    filename     TEXT NOT NULL,
    stored_path  TEXT NOT NULL,
    content_type TEXT,
    size         INTEGER NOT NULL DEFAULT 0,
    uploaded_by  TEXT,
    created_at   INTEGER NOT NULL
);

-- Subscription from a gateway source (platform + chat + thread) to a
-- task. The gateway's kanban-notifier watcher tails task_events and
-- pushes ` + "`" + `` + "`" + `completed` + "`" + `` + "`" + ` / ` + "`" + `` + "`" + `blocked` + "`" + `` + "`" + ` / ` + "`" + `` + "`" + `spawn_auto_blocked` + "`" + `` + "`" + ` events to
-- the original requester so human-in-the-loop workflows close the loop.
CREATE TABLE IF NOT EXISTS kanban_notify_subs (
    task_id       TEXT NOT NULL,
    platform      TEXT NOT NULL,
    chat_id       TEXT NOT NULL,
    thread_id     TEXT NOT NULL DEFAULT '',
    user_id       TEXT,
    user_id_alt   TEXT,
    chat_type     TEXT,
    notifier_profile TEXT,
    delivery_mode TEXT NOT NULL DEFAULT 'notify',
    delivery_metadata TEXT,
    created_at    INTEGER NOT NULL,
    last_event_id INTEGER NOT NULL DEFAULT 0,
    last_ping_event_id INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (task_id, platform, chat_id, thread_id)
);

CREATE INDEX IF NOT EXISTS idx_tasks_status          ON tasks(status);
CREATE INDEX IF NOT EXISTS idx_links_child           ON task_links(child_id);
CREATE INDEX IF NOT EXISTS idx_links_parent          ON task_links(parent_id);
CREATE INDEX IF NOT EXISTS idx_comments_task         ON task_comments(task_id, created_at);
CREATE INDEX IF NOT EXISTS idx_events_task           ON task_events(task_id, created_at);
CREATE INDEX IF NOT EXISTS idx_runs_task             ON task_runs(task_id, started_at);
CREATE INDEX IF NOT EXISTS idx_runs_status           ON task_runs(status);
CREATE INDEX IF NOT EXISTS idx_attachments_task      ON task_attachments(task_id, created_at);
CREATE INDEX IF NOT EXISTS idx_notify_task           ON kanban_notify_subs(task_id);
`

Kanban schema every connection applies on first use, idempotent through IF NOT EXISTS

View Source
const SlashKanbanHelp = "**/kanban** — manage the shared task board.\n" +
	"\n" +
	"Common subcommands:\n" +
	"  `list` (alias `ls`)   List tasks on the current board\n" +
	"  `show <id>`           Task details + comments + events\n" +
	"  `stats`               Per-status / per-assignee counts\n" +
	"  `create <title>…`     Create a task (auto-subscribes you to events)\n" +
	"  `comment <id> <msg>`  Append a comment\n" +
	"  `attach <id> <path>`  Attach a local file; `attachments <id>` to list\n" +
	"  `complete <id>…`      Mark task(s) done\n" +
	"  `request-review <id>` Enter first-class review; `request-changes <id> <reason>` returns an active review to its implementer\n" +
	"  `block <id> [reason]` Mark blocked; `schedule <id> [reason]` parks time-delay work; `unblock <id>` to revive\n" +
	"  `assign <id> <profile>`  Reassign\n" +
	"  `boards list`         Show all boards\n" +
	"  `assignees`           Known profiles + counts\n" +
	"  `context <id>`        Full worker-context dump\n" +
	"  `runs <id>`           Attempt history\n" +
	"  `log <id>`            Worker log\n" +
	"\n" +
	"Run `/kanban <subcommand> -h` for arguments. " +
	"Read-only commands are safe while an agent is running."

Curated short help a bare or help slash invocation shows instead of the full parser usage

View Source
const (
	TerminalWorkerReapGraceSeconds = 120
)
View Source
const WorkerExitTrailer = "[kanban-worker-exit] rc="

WorkerExitTrailer prefixes the exit code line a worker CLI appends to its own log

View Source
const (
	WorkerOutputSep = " Worker's last output: "
)

Variables

View Source
var DefaultStatuses = func() map[string]bool {
	if err := DefaultWorkflow.Validate(); err != nil {
		panic(err)
	}
	out := map[string]bool{Archived: true}
	for _, k := range DefaultWorkflow.Keys() {
		out[k] = true
	}
	return out
}()

Every value tasks.status can hold under the default workflow

View Source
var DefaultWorkflow = Workflow{
	Columns: []Column{
		{"triage", "Triage", "◇", true},
		{"todo", "Todo", "◻", true},
		{"scheduled", "Scheduled", "⏱", false},
		{"ready", "Ready", "▶", true},
		{"running", "Running", "●", false},
		{"blocked", "Blocked", "⊘", true},
		{"review", "Review", "◎", false},
		{"done", "Done", "✓", true},
	},
	Manual: FrozenManual(
		ManualRow{"triage", []string{"todo", "ready"}},
		ManualRow{"todo", []string{"triage", "scheduled", "ready"}},
		ManualRow{"scheduled", []string{"triage", "todo", "ready"}},
		ManualRow{"ready", []string{"triage", "todo", "scheduled", "blocked", "review", "done"}},
		ManualRow{"running", []string{"triage", "todo", "scheduled", "ready", "blocked", "review", "done"}},
		ManualRow{"blocked", []string{"triage", "todo", "scheduled", "ready", "done"}},
		ManualRow{"review", []string{"triage", "todo", "ready", "done"}},
		ManualRow{"done", []string{"triage", "todo", "ready"}},
		ManualRow{Archived, []string{"triage", "todo", "ready"}},
	),
}

Today's board in column order with its locked columns and its manual move matrix

View Source
var KanbanSpecifyMaxTokens = max(1500, utilsEnvInt("ICEBATH_KANBAN_SPECIFY_MAX_TOKENS", 6000))

KanbanSpecifyMaxTokens is the specifier reply budget, at least 1500

View Source
var ParseSlash func(tokens []string) SlashParse

Parses slash tokens with the kanban CLI parser shown as /kanban, assigned in cmd/icebath wiring

View Source
var RecoveryDelaysSeconds = []float64{15.0, 45.0, 90.0}

Backoff seconds before each recovery attempt, the last entry repeating

View Source
var SeverityOrder = []string{"warning", "error", "critical"}

SeverityOrder lists diagnostic severities from least to most urgent

View Source
var ValidBlockKinds = map[string]bool{"dependency": true, "needs_input": true, "capability": true, "transient": true}

Reasons a task can be blocked

View Source
var ValidInitialStatuses = map[string]bool{"running": true, "blocked": true}

Statuses a task may be created in besides the computed default

View Source
var ValidSortOrders = map[string]string{
	"created":        "created_at ASC, id ASC",
	"created-desc":   "created_at DESC, id DESC",
	"priority":       "priority DESC, created_at ASC",
	"priority-desc":  "priority ASC, created_at ASC",
	"status":         "status ASC, created_at ASC",
	"assignee":       "assignee ASC, created_at ASC",
	"title":          "title ASC, id ASC",
	"updated":        "started_at DESC NULLS LAST, created_at DESC",
	"completed-desc": "completed_at DESC NULLS LAST, id DESC",
}

Sort keys accepted by list_tasks mapped to their ORDER BY clauses

View Source
var ValidStatuses = DefaultStatuses

Every value tasks.status can hold

View Source
var ValidWorkspaceKinds = map[string]bool{"scratch": true, "worktree": true, "dir": true}

Workspace kinds a task may carry

Functions

func AddComment

func AddComment(ctx context.Context, conn state.SQLiteConn, taskID, author, body string) (int64, error)

Adds a stripped comment with a commented event and returns its id

func AddNotifySub

func AddNotifySub(ctx context.Context, conn state.SQLiteConn, o NotifySubOptions) error

Registers a gateway source wanting terminal state notifications, idempotent on task, platform, chat and thread

func AdmissionAnswerBudget

func AdmissionAnswerBudget() float64

Seconds a worker client waits for the owner's kanban.run answer, the longest board lock wait plus the margin

func AdoptWorkerPid

func AdoptWorkerPid(ctx context.Context, conn state.SQLiteConn, taskID string, runID int64, pid int) (bool, error)

Worker side pid registration before the first model call, false when the run is no longer live

func AdvanceNotifyCursor

func AdvanceNotifyCursor(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string, newCursor int64) error

Sets the subscription cursor after delivery

func AppendEvent

func AppendEvent(ctx context.Context, conn state.SQLiteConn, taskID, kind string, body any, runID *int64) error

Appends one task event with its JSON payload, bound to the run when given

func AppendTaskEvent

func AppendTaskEvent(ctx context.Context, conn state.SQLiteConn, taskID, kind string, body any, runID *int64) error

Inserts an event row inside the caller transaction, a nil run id marking it task scoped

func ArchiveTask

func ArchiveTask(ctx context.Context, conn state.SQLiteConn, taskID string, signalFn SignalFunc) (bool, error)

Archives a task, a running task having its host local worker terminated after the commit

func AssertNotDelegatedChildMutation

func AssertNotDelegatedChildMutation(ctx context.Context, path string) error

PermissionError when a delegate_task child context would mutate the kanban database at path

func AssignTask

func AssignTask(ctx context.Context, conn state.SQLiteConn, taskID string, profile *string) (bool, error)

Assigns or reassigns a task, refusing one running under a claim, and fires the updated observer after commit

func AttachmentsRoot

func AttachmentsRoot(ctx context.Context, board *string) (string, error)

Per board attachments root, ICEBATH_KANBAN_ATTACHMENTS_ROOT winning

func BlockTask

func BlockTask(ctx context.Context, conn state.SQLiteConn, taskID, reason string, expectedRunID *int64) error

Blocks a running or ready task with the worker reason under the run it owns

func BlockTaskWithKind

func BlockTaskWithKind(ctx context.Context, conn state.SQLiteConn, taskID string, reason, kind *string, expectedRunID *int64) (bool, error)

Moves running or ready to blocked, todo or triage by kind, classifying an untyped breaker block in place

func BoardArg

func BoardArg(slug string) *string

Optional board argument naming a slug, nil meaning the caller expressed no board

func BoardDir

func BoardDir(board *string) (string, error)

Board directory under boards root, metadata only for default whose database stays at the root

func BoardExists

func BoardExists(board *string) bool

Reports whether the board has a board.json on disk, default always existing

func BoardMetadataPath

func BoardMetadataPath(board *string) (string, error)

board.json path holding display metadata, the directory slug being the identity

func BoardStats

func BoardStats(ctx context.Context, conn state.SQLiteConn) (*pyjson.Object, error)

Per status and per assignee counts with the oldest ready age

func BoardsRoot

func BoardsRoot() string

Parent of the additional named boards under the kanban root

func BuildRecoveryNudge

func BuildRecoveryNudge(result any, attempt, maxAttempts int, taskID *string) string

Synthetic user turn telling the worker to continue the same session and end with a terminal kanban call

func BuildWorkerContext

func BuildWorkerContext(ctx context.Context, conn state.SQLiteConn, taskID string) (string, error)

Everything a worker reads about its task as capped markdown sections

func CheckDispatcherPresence

func CheckDispatcherPresence(ctx context.Context, icebathHome string) (running bool, message string)

Whether a gateway will dispatch ready work for the home, with guidance when none will, failing open

func CheckRespawnGuard

func CheckRespawnGuard(ctx context.Context, conn state.SQLiteConn, taskID, lane string) (*string, error)

Reason a ready or review task must not be respawned now, nil when it may be

func ChildIDs

func ChildIDs(ctx context.Context, conn state.SQLiteConn, taskID string) ([]string, error)

Direct children of a task in id order

func ClearCurrentBoard

func ClearCurrentBoard(ctx context.Context) error

Removes the current file so the active board reverts to default

func CompleteTask

func CompleteTask(ctx context.Context, conn state.SQLiteConn, taskID string, o CompleteTaskOptions) (bool, error)

Moves a task to done with its result, refusing a live claim without proof of ownership and gating evidence first

func ConfigFromKanbanConfig

func ConfigFromKanbanConfig(kanbanCfg map[string]any) (map[string]any, error)

Diagnostics config from the kanban section, the threshold following kanban.failure_limit unless overridden

func ConfigFromRuntimeConfig

func ConfigFromRuntimeConfig(rawConfig any) (map[string]any, error)

Diagnostics config from the full runtime config, carrying kanban, auxiliary and model for the triage rules

func ConfiguredMaxInProgress

func ConfiguredMaxInProgress(ctx context.Context) *int

Positive kanban.max_in_progress from config, nil when unset or invalid

func Connect

func Connect(ctx context.Context, dbPath string, board *string) (state.SQLiteConn, error)

Opens and on first use per path initializes the kanban database, read only for a fenced descendant

func ConnectClosing

func ConnectClosing(ctx context.Context, dbPath string, board *string, fn func(conn state.SQLiteConn) error) error

Runs fn on a fresh connection that is always closed afterwards

func CountNotifySubs

func CountNotifySubs(ctx context.Context, dbPath string, board *string, scope NotifyOwnerScope, platform, chatID, threadID *string) (int64, error)

Counts subscription rows over a read only connection, a missing file or table counting as zero

func CountRunningTasks

func CountRunningTasks(ctx context.Context, conn state.SQLiteConn) int

Number of running tasks, zero on any error

func CountRunningTasksOtherBoards

func CountRunningTasksOtherBoards(ctx context.Context, board *string) int

Running tasks across every board except the given one, matched by resolved database path

func CreateBoard

func CreateBoard(ctx context.Context, slug string, o BoardCreateOptions) (*pyjson.Object, error)

Creates board dir, database and metadata, an existing board returning its metadata and losing any archive tombstone

func CreateTask

func CreateTask(ctx context.Context, conn state.SQLiteConn, o CreateTaskOptions) (string, error)

Creates a task under its parents inside one write transaction and returns its id, or the live task holding the idempotency key

func CredentialFailureFlags

func CredentialFailureFlags(err error) (rateLimited, terminal, found bool)

CredentialFailureFlags reads the exit code credential flags from an error raised before any turn ran

func CurrentBoardPath

func CurrentBoardPath() string

File holding the slug boards switch writes

func DecomposeListTriageIDs

func DecomposeListTriageIDs(ctx context.Context, tenant *string) ([]string, error)

Task ids in the triage column, narrowed by tenant, at most a thousand

func DecomposeTriageTask

func DecomposeTriageTask(ctx context.Context, conn state.SQLiteConn, taskID string, rootAssignee *string, children []any, author *string, autoPromote bool) ([]string, error)

Fans a triage task out into children and parks the root in todo until every child is done, nil when it cannot decompose

func DeleteArchivedTask

func DeleteArchivedTask(ctx context.Context, conn state.SQLiteConn, taskID string) (bool, error)

Hard deletes an archived task with its related rows, anything else refused

func DeriveDefaultMaxInProgress

func DeriveDefaultMaxInProgress(sample *pyjson.Object) *int

Memory derived default for kanban.max_in_progress, nil when total memory is unknown

func DescribeSuppression

func DescribeSuppression(results []*DispatchResult) string

One line naming why the ticks held ready work back, empty when nothing was held

func DetectStaleRunning

func DetectStaleRunning(ctx context.Context, conn state.SQLiteConn, staleTimeoutSeconds int64, signalFn SignalFunc) ([]string, error)

Reclaims running tasks with no heartbeat progress past the timeout, zero disabling the check

func DiagnosticsDefaultConfig

func DiagnosticsDefaultConfig() map[string]any

DiagnosticsDefaultConfig is the rule configuration every computation starts from

func DispatchProfileAllowlistSummary

func DispatchProfileAllowlistSummary(ctx context.Context) string

Human readable kanban.dispatch_profiles resolution of this home for diagnostics

func EditTask

func EditTask(ctx context.Context, conn state.SQLiteConn, taskID string, o EditTaskOptions) (bool, error)

Edits task fields, a result backfill allowed only on a done task, and notifies the changed fields

func EnforceMaxRuntime

func EnforceMaxRuntime(ctx context.Context, conn state.SQLiteConn, signalFn SignalFunc) ([]string, error)

Terminates host local workers past their per task max runtime and books each as timed_out

func ExportBoard

func ExportBoard(ctx context.Context, board *string, outputPath string, includeAttachments, includeLogs bool) (*pyjson.Object, error)

Exports a board to a tar.gz with a scrubbed database snapshot, optional attachments and logs, returning a summary

func GCEvents

func GCEvents(ctx context.Context, conn state.SQLiteConn, olderThanSeconds int64) (int64, error)

Prunes old events of done and archived tasks, decomposition identity kept, returning the count deleted

func GCWorkerLogs

func GCWorkerLogs(ctx context.Context, olderThanSeconds int64, board *string) (int, error)

Deletes worker log files older than the window on one board, returning the count

func GetCurrentBoard

func GetCurrentBoard(ctx context.Context) string

Active slug from the context override, ICEBATH_KANBAN_BOARD, the current file while that board exists, else default

func GoalRunStatus

func GoalRunStatus(ctx context.Context, conn state.SQLiteConn, taskID string, expectedRunID *int64) (*string, error)

Lifecycle status as one run sees it, superseded once another run owns the task

func HasSpawnableReady

func HasSpawnableReady(ctx context.Context, conn state.SQLiteConn) (bool, error)

True when a ready assigned unclaimed task maps to a real profile

func HasSpawnableReview

func HasSpawnableReview(ctx context.Context, conn state.SQLiteConn) (bool, error)

True when a review assigned unclaimed task maps to a real profile

func HeartbeatClaim

func HeartbeatClaim(ctx context.Context, conn state.SQLiteConn, taskID string, ttlSeconds *int64, claimer *string) (bool, error)

Extends a running claim the caller still owns, mirroring the expiry onto its run

func HeartbeatCurrentWorkerFromEnv

func HeartbeatCurrentWorkerFromEnv(ctx context.Context) (beat bool)

Extends the claim and heartbeat of the current worker at most once a minute, true when both writes land

func HeartbeatWorker

func HeartbeatWorker(ctx context.Context, conn state.SQLiteConn, taskID string, note *string, expectedRunID *int64) (bool, error)

Records a heartbeat event and touches last_heartbeat_at, false when the task is not running under that run

func HeartbeatWorkerNote

func HeartbeatWorkerNote(ctx context.Context, conn state.SQLiteConn, taskID string, note any, expectedRunID *int64) (bool, error)

Heartbeat whose note is any JSON value, stored on the event only when truthy

func ImportBoard

func ImportBoard(ctx context.Context, archivePath string, slug *string, activate bool) (*pyjson.Object, error)

Imports an archive as a new board, the slug suffixed when taken, returning a summary

func InitDB

func InitDB(ctx context.Context, dbPath string, board *string) (string, error)

Creates the schema if missing and always reruns the migration pass, returning the path used

func InjectNewCommentsFromEnv

func InjectNewCommentsFromEnv(ctx context.Context, agent any) (injected bool)

Steers operator comments added since the last poll into the running agent, true when a note was injected

func KanbanCommand

func KanbanCommand(ctx context.Context, ns map[string]any, w, errw io.Writer) (int, error)

Entry point of icebath kanban, returning a shell style exit code

func KanbanDBPath

func KanbanDBPath(ctx context.Context, board *string) (string, error)

kanban.db path pinned by ICEBATH_KANBAN_DB, the root kanban.db for default, else the board dir

func KanbanHome

func KanbanHome() string

ICEBATH_KANBAN_HOME else the default root, shared across profiles so dispatcher and workers meet

func KanbanTaskID

func KanbanTaskID() string

Dispatcher set worker task id stripped once, empty when this process is not a worker run

func KanbanTurnRecoveryEnabled

func KanbanTurnRecoveryEnabled(taskID *string) bool

True when a worker task id is carried and the attempt budget is above zero

func KnownAssignees

func KnownAssignees(ctx context.Context, conn state.SQLiteConn) ([]*pyjson.Object, error)

Every on disk profile or task assignee with its presence and status counts

func LatestBlackboard

func LatestBlackboard(ctx context.Context, conn state.SQLiteConn, rootID string) (*pyjson.Object, error)

Merged structured blackboard comments of a root, later keys winning and _authors naming each winner

func LatestSummary

func LatestSummary(ctx context.Context, conn state.SQLiteConn, taskID string) (*string, error)

Newest non empty run summary of a task, nil when none

func LinkTasks

func LinkTasks(ctx context.Context, conn state.SQLiteConn, parentID, childID string, expectedChildRunID *int64) (bool, error)

Links parent to child, reporting whether the edge gated a ready child back to todo

func ListBoards

func ListBoards(includeArchived bool) ([]*pyjson.Object, error)

Metadata for every board, default first then board dirs holding board.json sorted case insensitively

func ListNotifySubs

func ListNotifySubs(ctx context.Context, conn state.SQLiteConn, taskID *string, scope NotifyOwnerScope) ([]*pyjson.Object, error)

Subscriptions as ordered row objects, optionally of one task and restricted to owner profiles

func ListProfilesOnDisk

func ListProfilesOnDisk() []string

Profiles with a config.yaml plus the implicit default, sorted

func LossyText

func LossyText(value any) any

Bytes decoded as UTF-8 with U+FFFD for undecodable sequences, anything else passed through

func MaxRecoveryAttempts

func MaxRecoveryAttempts() int

Attempt budget from ICEBATH_KANBAN_TURN_RECOVERY clamped to zero through ten, the default when unset or unparseable

func NormalizeBoardSlug

func NormalizeBoardSlug(slug *string) (string, error)

NormalizeBoardSlug exports normalizeBoardSlug

func NormalizeReasoningEffort

func NormalizeReasoningEffort(effort *string) (*string, error)

Valid reasoning effort or none case insensitively, nil for empty, a ValueError for anything else

func NotifyTaskUpdated

func NotifyTaskUpdated(ctx context.Context, conn state.SQLiteConn, taskID string, changedFields []string, board string)

Fires on_kanban_task_updated after a non lifecycle mutation commits, naming the changed fields only

func ParentIDs

func ParentIDs(ctx context.Context, conn state.SQLiteConn, taskID string) ([]string, error)

Direct parents of a task in id order

func PinFirstBoardResolution

func PinFirstBoardResolution(ctx context.Context) context.Context

Context resolving board paths env pin first, for machine flows that enumerate every board

func PostBlackboardUpdate

func PostBlackboardUpdate(ctx context.Context, conn state.SQLiteConn, rootID, author, key string, value any) (int64, error)

Appends one structured key and value update to a swarm root blackboard

func ProcessFingerprint

func ProcessFingerprint(pid int) *string

Start fingerprint of a live pid, nil when it cannot be read

func PromoteTask

func PromoteTask(ctx context.Context, conn state.SQLiteConn, taskID, actor string, reason *string, dryRun bool) (bool, string, error)

Operator promotion of todo or blocked to ready with an audit event, refused while a parent is unfinished

func PurgeStaleDoneNotifySubs

func PurgeStaleDoneNotifySubs(ctx context.Context, conn state.SQLiteConn, maxAgeDays int64) (int64, error)

Deletes subscriptions of tasks settled in done or blocked for longer than the window, zero or less disabling the sweep

func ReadBoardMetadata

func ReadBoardMetadata(board *string) (*pyjson.Object, error)

board.json merged over defaults plus slug and db_path, a missing or malformed file yielding the synthesized entry

func ReadWorkerLog

func ReadWorkerLog(ctx context.Context, taskID string, tailBytes *int64, board *string) (*string, error)

Worker log text or its last tailBytes, nil when the file is missing or unreadable

func ReapTerminalWorkers

func ReapTerminalWorkers(ctx context.Context, conn state.SQLiteConn, signalFn SignalFunc) ([]string, error)

Ends host local workers that outlived their closed run, returning the task ids whose worker was terminated

func ReapWorkerZombies

func ReapWorkerZombies() []int

Records every spawned worker that has exited since the last call and returns their pids

func ReassignTask

func ReassignTask(ctx context.Context, conn state.SQLiteConn, taskID string, profile *string, reclaimFirst bool, reason *string) (bool, error)

Reassigns a task, releasing a running claim first when asked, false when the task stays claimed

func ReclaimTask

func ReclaimTask(ctx context.Context, conn state.SQLiteConn, taskID string, reason *string, signalFn SignalFunc) (bool, error)

Operator reclaim regardless of TTL restoring the source phase and resetting the failure counter, false when not running

func RecomputeReady

func RecomputeReady(ctx context.Context, conn state.SQLiteConn, failureLimit *int64) (int, error)

Promotes todo and non sticky blocked tasks whose parents are all done or archived and returns the count

func ReconcileOrphanedRunning

func ReconcileOrphanedRunning(ctx context.Context, conn state.SQLiteConn) ([]string, error)

Requeues running cards with broken claim bookkeeping and no live local worker, returning their ids

func RecordBudgetExhausted

func RecordBudgetExhausted(ctx context.Context, kanbanTask string, apiCallCount, maxIterations int) error

Records the timed out outcome of a kanban worker whose iteration budget ran out

func RecordNotifyPing

func RecordNotifyPing(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string, eventID int64) error

Checkpoints a sent ping independently of the retryable wake cursor

func RecoverFailedKanbanTurns

func RecoverFailedKanbanTurns(ctx context.Context, runTurn func(nudge string), lastResult func() map[string]any, emit func(string)) (int, error)

Retries a failed worker turn in place under the environment pinned carrier, returning attempts made

func RecoverFailedKanbanTurnsWith

func RecoverFailedKanbanTurnsWith(ctx context.Context, turnFn func(nudge string), getResult func() any, o RecoveryOptions) (int, error)

Retries an authorised worker turn in place with proof before and after each backoff, returning attempts made

func RecoveryDelaySeconds

func RecoveryDelaySeconds(attempt int) float64

Backoff seconds before the one based recovery attempt

func RegisterCurrentWorkerFromEnv

func RegisterCurrentWorkerFromEnv(ctx context.Context) (registered bool)

Records this worker's pid on its run, false only when the board says the run was already reclaimed

func ReleaseStaleClaims

func ReleaseStaleClaims(ctx context.Context, conn state.SQLiteConn, signalFn SignalFunc, failureLimit *int64) (int, error)

Reclaims running tasks whose claim expired, extending live host local workers and booking every release as a failure

func RemoveBoard

func RemoveBoard(ctx context.Context, slug string, archive bool) (*pyjson.Object, error)

Archives a board under boards/_archived with a tombstone at its slug, or deletes it, default never removable

func RemoveNotifySub

func RemoveNotifySub(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string) (bool, error)

Deletes one subscription row, true when a row existed

func ReopenReviewTask

func ReopenReviewTask(ctx context.Context, conn state.SQLiteConn, taskID string) (bool, error)

Moves review back to ready or todo restoring the implementer from the review request

func ReopenTask

func ReopenTask(ctx context.Context, conn state.SQLiteConn, taskID, author string) (bool, error)

Takes a done or archived task back to ready, or todo while a parent is still open, with its status event; every descendant that went on from the finished work returns to todo and the workers running them are stopped once the change is committed

func RequestChanges

func RequestChanges(ctx context.Context, conn state.SQLiteConn, taskID, reason string, expectedRunID *int64) (bool, string, error)

Closes an active reviewer run and hands the task back to the implementer of the latest review request

func RequestReview

func RequestReview(ctx context.Context, conn state.SQLiteConn, taskID string, o RequestReviewOptions) (bool, string, error)

Moves running or ready to review with implementer and reviewer provenance, staged artifacts rolled back on failure

func RequireSlug

func RequireSlug(slug string) (string, error)

Normalized board slug, a ValueError for an empty or invalid one

func ResolveMaxInProgress

func ResolveMaxInProgress(configured *int) *int

Effective global concurrency cap, the configured value else the memory derived default

func ResolveWorkspace

func ResolveWorkspace(ctx context.Context, task *Task, board *string) (string, error)

Resolves and creates the workspace directory of a task by its kind

func RetryStatusForRun

func RetryStatusForRun(ctx context.Context, conn state.SQLiteConn, taskID string, runID *int64) (string, error)

Retry status the dispatcher reads for a run, review for a reviewer attempt

func ReviewDispatchEnabled

func ReviewDispatchEnabled(ctx context.Context) bool

Whether review tasks dispatch automatically, true unless kanban.review_dispatch is falsy

func RewindNotifyCursor

func RewindNotifyCursor(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string, claimedCursor, oldCursor int64) (bool, error)

Undoes a claim after a delivery failure unless a later notifier already advanced the row

func RotateWorkerLog

func RotateWorkerLog(logPath string, maxBytes, backupCount int64)

Rotates a worker log past max bytes into numbered generations up to the backup count, ignoring OS errors

func RunDaemon

func RunDaemon(ctx context.Context, o DaemonOptions)

Dispatcher loop ticking every interval until the stop channel closes or SIGINT or SIGTERM arrives

func RunSlash

func RunSlash(ctx context.Context, rest string) (string, error)

Runs the text after /kanban through the kanban CLI and returns its captured output, shared by the CLI and the gateway

func ScheduleTask

func ScheduleTask(ctx context.Context, conn state.SQLiteConn, taskID string, reason *string, expectedRunID *int64) (bool, error)

Parks a task in scheduled until an unblock re gates it

func ScopedCurrentBoard

func ScopedCurrentBoard(ctx context.Context, slug string) context.Context

Context pinning the active board for calls made with it only

func SetBranchName

func SetBranchName(ctx context.Context, conn state.SQLiteConn, taskID, branchName string) error

Persists the worktree branch name of a task

func SetCurrentBoard

func SetCurrentBoard(ctx context.Context, slug string) (string, error)

Persists slug as the active board and returns the file written, leaving existence checks to callers

func SetModelOverride

func SetModelOverride(ctx context.Context, conn state.SQLiteConn, taskID string, model, provider *string) (bool, error)

Sets the per task model and provider override, an empty model clearing both

func SetWorkspacePath

func SetWorkspacePath(ctx context.Context, conn state.SQLiteConn, taskID, path string) error

Persists the resolved workspace path of a task

func ShouldRecoverTurn

func ShouldRecoverTurn(result any, attempt int, taskID *string) bool

True when a settled worker turn is a retryable failure inside the budget with no wall, cancel or settlement

func SpecifyListTriageIDs

func SpecifyListTriageIDs(ctx context.Context, tenant *string) ([]string, error)

Task ids in the triage column, narrowed by tenant

func SpecifyTriageTask

func SpecifyTriageTask(ctx context.Context, conn state.SQLiteConn, taskID string, title, body, assignee, author *string) (bool, error)

Updates title, body and assignee when given and moves triage to todo in one transaction

func StoreAttachmentBytes

func StoreAttachmentBytes(ctx context.Context, conn state.SQLiteConn, taskID, filename string, data []byte, o StoreAttachmentOptions) (int64, error)

Writes an attachment blob under the task attachments directory and records its row, removing the blob when the row fails

func TaskAttachmentsDir

func TaskAttachmentsDir(ctx context.Context, taskID string, board *string) (string, error)

Per task attachment directory under the attachments root

func TaskGoalMaxTurns

func TaskGoalMaxTurns(task *Task) *int64

Goal turn budget stored on the task, nil when unset

func TaskGraphContext

func TaskGraphContext(ctx context.Context, conn state.SQLiteConn, taskID string) (*pyjson.Object, error)

Direct parents and children with title and status for one task

func TaskGraphContexts

func TaskGraphContexts(ctx context.Context, conn state.SQLiteConn, taskIDs []string) (*pyjson.Object, error)

Direct parents and children with title and status for each requested task in request order

func TriageAuxStatus

func TriageAuxStatus(config any) any

Whether the triage aux paths look configured, nil when no config context is present

func UnblockTask

func UnblockTask(ctx context.Context, conn state.SQLiteConn, taskID string) (bool, error)

Moves blocked or scheduled back to its resumable phase after re gating on parents, closing any leaked run first

func UnlinkTasks

func UnlinkTasks(ctx context.Context, conn state.SQLiteConn, parentID, childID string) (bool, error)

Removes a parent to child edge and promotes children it no longer gates

func WorkerAlive

func WorkerAlive(pid, startedAt any) bool

True when the pid is live and still the worker fingerprinted at spawn

func WorkerClaimIsLive

func WorkerClaimIsLive(ctx context.Context, proof ClaimProof) (bool, error)

True when this process still owns the pinned live run with an unexpired task and run lease

func WorkerLogPath

func WorkerLogPath(ctx context.Context, taskID string, board *string) (string, error)

Worker log path of a task on a board, which may not exist yet

func WorkerLogRotationConfig

func WorkerLogRotationConfig(ctx context.Context, kanbanCfg any) (int64, int64, error)

Rotation size and backup count for worker logs from the kanban config, defaults when unset

func WorkerLogsDir

func WorkerLogsDir(ctx context.Context, board *string) (string, error)

Per board worker log directory

func WorkerTerminalTimeoutEnv

func WorkerTerminalTimeoutEnv(maxRuntimeSeconds *int64, currentTimeout *string) *string

Terminal timeout a bound worker exports for its run budget, nil when the current one stands

func WorkspacesRoot

func WorkspacesRoot(ctx context.Context, board *string) (string, error)

Per board scratch workspace root, ICEBATH_KANBAN_WORKSPACES_ROOT winning

func WriteBoardMetadata

func WriteBoardMetadata(ctx context.Context, board *string, u BoardMetadataUpdate) (*pyjson.Object, error)

Creates or updates board.json preserving unmentioned fields, created_at set on first write

func WriteTxn

func WriteTxn(ctx context.Context, conn state.SQLiteConn, allowNested bool, body func() error) (err error)

Runs body in an IMMEDIATE write transaction, a savepoint when nesting is opted into, checking the file length after commit

Types

type ArtifactPreservationError

type ArtifactPreservationError struct{ Msg string }

Declared scratch deliverable that could not be preserved, unwrapping to RuntimeError

func (*ArtifactPreservationError) Error

func (e *ArtifactPreservationError) Error() string

func (*ArtifactPreservationError) Unwrap

func (e *ArtifactPreservationError) Unwrap() error

type Attachment

type Attachment struct {
	ID          int64
	TaskID      string
	Filename    string
	StoredPath  string
	ContentType *string
	Size        int64
	UploadedBy  *string
	CreatedAt   int64
}

One stored task attachment

func AttachmentFromRow

func AttachmentFromRow(r *Row) *Attachment

Attachment from a task_attachments row

func DeleteAttachment

func DeleteAttachment(ctx context.Context, conn state.SQLiteConn, attachmentID int64) (*Attachment, error)

Deletes the attachment row and its blob once no other row references it, nil when no row matched

func GetAttachment

func GetAttachment(ctx context.Context, conn state.SQLiteConn, attachmentID int64) (*Attachment, error)

Attachment by id, nil when no row matches

func ListAttachments

func ListAttachments(ctx context.Context, conn state.SQLiteConn, taskID string) ([]*Attachment, error)

Attachments of a task oldest first

type AttachmentTooLarge

type AttachmentTooLarge struct{ Msg string }

Attachment over the size cap, unwrapping to ValueError so generic handlers still catch it

func (*AttachmentTooLarge) Error

func (e *AttachmentTooLarge) Error() string

func (*AttachmentTooLarge) Unwrap

func (e *AttachmentTooLarge) Unwrap() error

type BoardCreateOptions

type BoardCreateOptions struct {
	Name           *string
	Description    *string
	Icon           *string
	Color          *string
	DefaultWorkdir *string
	ProjectID      *string
}

Board fields a new board starts with

type BoardMetadataUpdate

type BoardMetadataUpdate struct {
	Name           *string
	Description    *string
	Icon           *string
	Color          *string
	Archived       *bool
	DefaultWorkdir *string
	ProjectID      *string
}

Optional board.json fields a write updates, nil leaving a field unchanged

type CappedTask

type CappedTask struct {
	TaskID, Assignee string
	Running          int
}

CappedTask is one task deferred because its assignee was at the per profile running cap

type ClaimProof

type ClaimProof struct {
	TaskID    *string
	DBPath    *string
	RunID     *string
	ClaimLock *string
	SkipPid   bool
}

Explicit carrier a managed worker passes in place of the environment pins

type Column

type Column struct {
	Key        string
	Label      string
	Icon       string
	DragTarget bool
}

One board column, the stable key stored in tasks.status with its display label, CLI glyph and drag flag

type Comment

type Comment struct {
	ID        int64
	TaskID    string
	Author    string
	Body      string
	CreatedAt int64
}

One task comment

func CommentFromRow

func CommentFromRow(r *Row) *Comment

Comment from a task_comments row

func ListComments

func ListComments(ctx context.Context, conn state.SQLiteConn, taskID string) ([]*Comment, error)

Comments of a task oldest first

func ListCommentsAfter

func ListCommentsAfter(ctx context.Context, conn state.SQLiteConn, taskID string, afterID int64) ([]*Comment, error)

Comments with a rowid above the cursor in rowid order so a same second burst is never skipped

type CompleteTaskOptions

type CompleteTaskOptions struct {
	Result            *string
	Summary           *string
	Metadata          *pyjson.Object
	CreatedCards      []string
	ExpectedRunID     *int64
	SkipLifecycleHook bool
	Force             bool
	// contains filtered or unexported fields
}

CompleteTaskOptions holds the keyword arguments of a completion

type CrashSweepOutcome

type CrashSweepOutcome struct {
	Crashed     []string
	AutoBlocked []string
	RateLimited []string
}

CrashSweepOutcome is what one crash sweep reclaimed, auto blocked and requeued after a quota wall

type CreateTaskOptions

type CreateTaskOptions struct {
	Title               string
	Body                *string
	Assignee            *string
	CreatedBy           *string
	WorkspaceKind       *string
	WorkspacePath       *string
	BranchName          *string
	Tenant              *string
	Priority            int64
	Parents             []string
	Triage              bool
	IdempotencyKey      *string
	MaxRuntimeSeconds   *int64
	Skills              []string
	MaxRetries          *int64
	ModelOverride       *string
	ProviderOverride    *string
	ReasoningEffort     *string
	GoalMode            bool
	GoalMaxTurns        *int64
	InitialStatus       string
	SessionID           *string
	Board               *string
	ProjectID           *string
	ProjectSourceTaskID *string
	CreatorTaskID       *string
	CompletionContract  *string
	// contains filtered or unexported fields
}

Keyword arguments of task creation, nil pointers and nil slices standing for None

type DaemonOptions

type DaemonOptions struct {
	Interval     float64
	MaxSpawn     *int
	FailureLimit int64
	Stop         <-chan struct{}
	OnTick       func(*DispatchResult)
	Stderr       io.Writer
}

DaemonOptions are the keyword arguments of the long lived dispatcher loop

type DecomposeOutcome

type DecomposeOutcome struct {
	TaskID   string
	OK       bool
	Reason   string
	Fanout   bool
	ChildIDs []string
	NewTitle *string
}

DecomposeOutcome is the result of decomposing one triage task

func DecomposeTask

func DecomposeTask(ctx context.Context, taskID string, author *string, timeout *int64) (*DecomposeOutcome, error)

Decomposes a triage task into a routed child graph, expected failures as not ok

type Diagnostic

type Diagnostic struct {
	Kind        string
	Severity    string
	Title       string
	Detail      string
	Actions     []*DiagnosticAction
	FirstSeenAt int64
	LastSeenAt  int64
	Count       int64
	RunID       *int64
	Data        *pyjson.Object
}

Diagnostic is one active distress signal on a task

func ComputeTaskDiagnostics

func ComputeTaskDiagnostics(task any, events, runs []any, now *int64, config map[string]any, graph any) []*Diagnostic

Every rule for one task ordered critical first, ties broken by the most recent last seen

func (*Diagnostic) ToDict

func (d *Diagnostic) ToDict() *pyjson.Object

Ordered mapping of the diagnostic fields with every action expanded

type DiagnosticAction

type DiagnosticAction struct {
	Kind      string
	Label     string
	Payload   *pyjson.Object
	Suggested bool
}

DiagnosticAction is one recovery action the CLI renders as a hint

func (*DiagnosticAction) ToDict

func (a *DiagnosticAction) ToDict() *pyjson.Object

Ordered mapping of the action fields

type DispatchOptions

type DispatchOptions struct {
	SpawnFn                 SpawnFunc
	TTLSeconds              *int64
	DryRun                  bool
	MaxSpawn                *int
	MaxInProgress           *int
	FailureLimit            int64
	StaleTimeoutSeconds     int64
	Board                   *string
	DefaultAssignee         *string
	MaxInProgressPerProfile *int
	ReconcileOrphans        bool
}

DispatchOptions are the keyword arguments of one dispatcher tick

func DefaultDispatchOptions

func DefaultDispatchOptions() DispatchOptions

Dispatch options at the dispatch_once defaults

type DispatchResult

type DispatchResult struct {
	Reclaimed               int
	Promoted                int
	ReconciledOrphans       []string
	ReapedTerminalWorkers   []string
	Spawned                 []SpawnedTask
	SkippedUnassigned       []string
	AutoAssignedDefault     []string
	SkippedNonspawnable     []string
	SkippedPerProfileCapped []CappedTask
	Crashed                 []string
	AutoBlocked             []string
	TimedOut                []string
	Stale                   []string
	RespawnGuarded          []GuardedTask
	RateLimited             []string
	SkippedLocked           bool
	MemoryPressure          *string
}

DispatchResult is the outcome of a single dispatch pass

func DispatchOnce

func DispatchOnce(ctx context.Context, conn state.SQLiteConn, o DispatchOptions) (*DispatchResult, error)

One dispatcher tick under the board single writer lock, the loser returning a skipped locked result

func (*DispatchResult) Activity

func (r *DispatchResult) Activity(field string) bool

Python truthiness of the result field with that dataclass name, false for an unknown name

type EditTaskOptions

type EditTaskOptions struct {
	Title    *string
	Body     *string
	Priority *int64
	Result   *string
	Summary  *string
	Metadata *pyjson.Object
	Board    *string
}

EditTaskOptions holds the keyword arguments of a task edit

type EmptyCompletionError

type EmptyCompletionError struct{ TaskID string }

Completion refused for a task with no result or summary evidence, unwrapping to ValueError

func (*EmptyCompletionError) Error

func (e *EmptyCompletionError) Error() string

func (*EmptyCompletionError) Unwrap

func (e *EmptyCompletionError) Unwrap() error

type Event

type Event struct {
	ID        int64
	TaskID    string
	Kind      string
	Payload   any
	CreatedAt int64
	RunID     *int64
}

One task event

func ClaimUnseenEventsForSub

func ClaimUnseenEventsForSub(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string, kinds []string) (int64, int64, []*Event, error)

Atomically claims unseen events for one subscription, advancing its cursor under the writer lock

func EventFromRow

func EventFromRow(row *Row) (*Event, error)

Event from a task_events row, run_id tolerated absent

func ListEvents

func ListEvents(ctx context.Context, conn state.SQLiteConn, taskID string) ([]*Event, error)

Events of a task oldest first

func UnseenEventsForSub

func UnseenEventsForSub(ctx context.Context, conn state.SQLiteConn, taskID, platform, chatID string, threadID *string, kinds []string) (int64, []*Event, error)

New cursor and events past the subscription cursor, the cursor itself left in place

type FileNotFoundError

type FileNotFoundError struct{ Msg string }

FileNotFoundError is the Python FileNotFoundError a missing board database or archive raises

func (*FileNotFoundError) Error

func (e *FileNotFoundError) Error() string

type GatewayDispatchProbeSet

type GatewayDispatchProbeSet struct {
	SampleMemory     func() *pyjson.Object
	ClassifyPressure func(availableKiB, totalKiB any) string
	Liveness         func(ctx context.Context, profileDir string) (pid any, probeError bool)
}

GatewayDispatchProbeSet is the gateway memory sampling and pressure classification the dispatcher reads

var GatewayDispatchProbes GatewayDispatchProbeSet

Gateway memory and liveness probes, installed by pkg/gateway at init

type GatewayStatusProbeSet

type GatewayStatusProbeSet struct {
	PidExists          func(pid int) bool
	ProcessStartTime   func(pid int) any
	StartTimesAgree    func(current any, recorded ...any) (bool, error)
	InstantiationEpoch func() string
}

GatewayStatusProbeSet holds the gateway status process facts worker identity checks consult

var GatewayStatusProbes GatewayStatusProbeSet

Gateway status process facts, installed by pkg/gateway at init

type GuardedTask

type GuardedTask struct{ TaskID, Reason string }

GuardedTask is one task id the respawn guard skipped with its reason

type HallucinatedCardsError

type HallucinatedCardsError struct {
	Phantom          []string
	CompletingTaskID string
}

Completion refused for created cards that do not exist or this worker did not create, unwrapping to ValueError

func (*HallucinatedCardsError) Error

func (e *HallucinatedCardsError) Error() string

func (*HallucinatedCardsError) Unwrap

func (e *HallucinatedCardsError) Unwrap() error

type InvalidationResult

type InvalidationResult struct {
	Invalidated  []*pyjson.Object
	Terminations []WorkerTermination
}

InvalidationResult lists every demoted descendant and the workers to terminate post commit

func InvalidateDescendantsForParentReopen

func InvalidateDescendantsForParentReopen(ctx context.Context, conn state.SQLiteConn, taskID, author string) (*InvalidationResult, error)

Demotes every ready, review, running or done descendant of a reopened ancestor to todo with its audit trail

type KanbanDBCorruptError

type KanbanDBCorruptError struct {
	DBPath     string
	BackupPath string
	Reason     string
}

Existing kanban database that failed integrity checks, carrying the path and the backup made first

func (*KanbanDBCorruptError) Error

func (e *KanbanDBCorruptError) Error() string

type ListTasksOptions

type ListTasksOptions struct {
	Assignee           *string
	Status             *string
	Tenant             *string
	SessionID          *string
	IncludeArchived    bool
	Limit              int64
	OrderBy            *string
	WorkflowTemplateID *string
	CurrentStepKey     *string
}

Filters of a task listing, nil meaning unfiltered and a zero limit meaning unbounded

type LiveClaimError

type LiveClaimError struct{ TaskID string }

Completion refused while a live worker claim protects the run, unwrapping to ValueError

func (*LiveClaimError) Error

func (e *LiveClaimError) Error() string

func (*LiveClaimError) Unwrap

func (e *LiveClaimError) Unwrap() error

type ManualMoves

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

Manual move allow list keyed by source column in insertion order

func FrozenManual

func FrozenManual(rows ...ManualRow) ManualMoves

Frozen move table where a repeated source keeps its first position and its last destinations

type ManualRow

type ManualRow struct {
	Src  string
	Dsts []string
}

One source column and the destinations a human may request from it

type NotifyOwnerScope

type NotifyOwnerScope struct {
	Profiles       []string
	Scoped         bool
	IncludeUnowned bool
}

NotifyOwnerScope restricts subscriptions to notifier profile owners when scoped

type NotifySubOptions

type NotifySubOptions struct {
	TaskID           string
	Platform         string
	ChatID           string
	ThreadID         *string
	UserID           *string
	UserIDAlt        *string
	ChatType         *string
	NotifierProfile  *string
	DeliveryMode     *string
	DeliveryMetadata any
}

NotifySubOptions holds the keyword arguments of a notification subscription

type ParentStatus

type ParentStatus struct {
	ID     string
	Status string
}

Open parent of a task with its status

func UnsatisfiedParents

func UnsatisfiedParents(ctx context.Context, conn state.SQLiteConn, taskID string) ([]ParentStatus, error)

Every direct parent still gating the task with its status in id order

type PermissionError

type PermissionError struct{ Msg string }

Python PermissionError raised when a fenced context touches durable kanban state

func (*PermissionError) Error

func (e *PermissionError) Error() string

type PreparedAcceptance

type PreparedAcceptance struct {
	Snapshot *acceptanceSnapshot
	Receipt  *pyjson.Object
}

Snapshot paired with the receipt collected for it

type RecordFailureOptions

type RecordFailureOptions struct {
	Outcome           string
	FailureLimit      *int64
	ForceTrip         bool
	ReleaseClaim      bool
	EndRun            bool
	EventPayloadExtra *pyjson.Object
	Infrastructure    bool
}

RecordFailureOptions holds the keyword arguments of one non success outcome record

type RecoveryOptions

type RecoveryOptions struct {
	Sleep      func(seconds float64)
	Emit       func(string)
	ClaimCheck func() (bool, error)
	TaskID     *string
}

Seams and explicit carrier of the recovery loop, zero value sleeping on the wall clock with the default proof

type RepairResult

type RepairResult struct {
	Status             string
	DBPath             string
	Messages           []string
	PostRepairMessages []string
	BackupPath         string
	Reindexed          []string
}

Outcome of RepairDB with status ok, repaired, corrupt or missing

func RepairDB

func RepairDB(ctx context.Context, dbPath string, board *string) (result *RepairResult, err error)

Probes a kanban database and applies the narrow REINDEX repair, reporting instead of raising

type RequestReviewOptions

type RequestReviewOptions struct {
	Summary       *string
	Metadata      *pyjson.Object
	Reviewer      *string
	ExpectedRunID *int64
	Force         bool
}

RequestReviewOptions holds the keyword arguments of a review handoff

type Row

type Row struct {
	Cols []string
	Vals []any
}

One result row with its column names, the sqlite3.Row a board connection yields

func QueryOne

func QueryOne(ctx context.Context, conn state.SQLiteConn, query string, args ...any) (*Row, error)

First row of a query, nil when it returns none

func QueryRows

func QueryRows(ctx context.Context, conn state.SQLiteConn, query string, args ...any) ([]*Row, error)

Rows of a query with TEXT cells decoded the way the lossy text factory does

func (*Row) Get

func (r *Row) Get(col string) any

Value of a column, nil when absent

func (*Row) Lookup

func (r *Row) Lookup(col string) (any, bool)

Value of a column and whether the row carries it

type Run

type Run struct {
	ID                int64
	TaskID            string
	Profile           *string
	StepKey           *string
	Status            string
	ClaimLock         *string
	ClaimExpires      *int64
	WorkerPID         *int64
	MaxRuntimeSeconds *int64
	LastHeartbeatAt   *int64
	StartedAt         int64
	EndedAt           *int64
	Outcome           *string
	Summary           *string
	Metadata          any
	Error             *string
}

One attempt at a task, opened on claim and closed on complete, block, crash, timeout or reclaim

func LatestRun

func LatestRun(ctx context.Context, conn state.SQLiteConn, taskID string) (*Run, error)

Most recent run of a task regardless of outcome, nil when none

func ListRuns

func ListRuns(ctx context.Context, conn state.SQLiteConn, taskID string, includeActive bool, stateType, stateName *string) ([]*Run, error)

Runs of a task in start order, closed only without active, filtered by one status or outcome state

func RunFromRow

func RunFromRow(row *Row) (*Run, error)

Run from a task_runs row

type RuntimeError

type RuntimeError struct{ Msg string }

Python RuntimeError raised by misuse of the write transaction helper

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

type SignalFunc

type SignalFunc func(pid int, sig syscall.Signal) error

SignalFunc delivers sig to pid the way os.kill does, an error standing for the OSError reclaim absorbs

type SlashParse

type SlashParse struct {
	Namespace map[string]any
	Parsed    bool
	Out, Err  string
	ArgError  string
	Usage     string
	Failure   error
}

What the CLI parser made of slash tokens, parser text renamed to /kanban whenever no action parsed

type SpawnFunc

type SpawnFunc func(ctx context.Context, task *Task, workspace string, board *string) (*int64, error)

SpawnFunc starts a worker for a claimed task in its workspace and returns its pid, nil when none is known

type SpawnedTask

type SpawnedTask struct{ TaskID, Assignee, WorkspacePath string }

SpawnedTask is one task id, assignee and workspace path a dispatch tick spawned

type SpecifyOutcome

type SpecifyOutcome struct {
	TaskID   string
	OK       bool
	Reason   string
	NewTitle *string
}

SpecifyOutcome is the result of specifying one triage task

func SpecifyTask

func SpecifyTask(ctx context.Context, taskID string, author *string, timeout *int64) (*SpecifyOutcome, error)

Specifies one triage task through the aux model and promotes it to the backlog, expected failures as not ok

type StoreAttachmentOptions

type StoreAttachmentOptions struct {
	ContentType *string
	UploadedBy  *string
	Board       *string
	MaxBytes    *int64
	// contains filtered or unexported fields
}

Options of an attachment write, a nil cap meaning the package default

type SwarmCreated

type SwarmCreated struct {
	RootID        string
	WorkerIDs     []string
	VerifierID    string
	SynthesizerID string
}

SwarmCreated holds the ids a swarm creation produced

func CreateSwarm

func CreateSwarm(ctx context.Context, conn state.SQLiteConn, o SwarmOptions) (*SwarmCreated, error)

Atomically creates a dispatchable swarm graph, completing its planning root after commit

func (*SwarmCreated) AsDict

func (s *SwarmCreated) AsDict() *pyjson.Object

Ordered mapping of the created ids

type SwarmOptions

type SwarmOptions struct {
	Goal                string
	Workers             []SwarmWorkerSpec
	VerifierAssignee    string
	SynthesizerAssignee string
	RootTitle           *string
	VerifierTitle       string
	SynthesizerTitle    string
	Tenant              *string
	CreatedBy           string
	WorkspaceKind       *string
	WorkspacePath       *string
	Priority            int64
	IdempotencyKey      *string
}

SwarmOptions are the keyword arguments of a swarm creation

func DefaultSwarmOptions

func DefaultSwarmOptions() SwarmOptions

Swarm options at the create_swarm defaults

type SwarmWorkerSpec

type SwarmWorkerSpec struct {
	Profile           string
	Title             string
	Body              string
	Skills            []string
	Priority          int64
	MaxRuntimeSeconds *int64
}

SwarmWorkerSpec is one parallel worker card of a swarm

func ParseWorkerArg

func ParseWorkerArg(raw string) (SwarmWorkerSpec, error)

Worker spec of a CLI --worker value naming profile, title and optional skills

type Task

type Task struct {
	ID                  string
	Title               string
	Body                *string
	Assignee            *string
	Status              string
	Priority            int64
	CreatedBy           *string
	CreatedAt           *int64
	StartedAt           *int64
	CompletedAt         *int64
	WorkspaceKind       string
	WorkspacePath       *string
	ClaimLock           *string
	ClaimExpires        *int64
	Tenant              *string
	BranchName          *string
	ProjectID           *string
	Result              *string
	IdempotencyKey      *string
	ConsecutiveFailures int64
	WorkerPID           *int64
	LastFailureError    *string
	MaxRuntimeSeconds   *int64
	LastHeartbeatAt     *int64
	CurrentRunID        *int64
	WorkflowTemplateID  *string
	CurrentStepKey      *string
	Skills              []string
	SkillsSet           bool
	ModelOverride       *string
	ProviderOverride    *string
	ReasoningEffort     *string
	MaxRetries          *int64
	GoalMode            bool
	GoalMaxTurns        *int64
	SessionID           *string
	BlockKind           *string
	BlockRecurrences    int64
	CompletionContract  *string
}

One board task row

func ClaimReviewTask

func ClaimReviewTask(ctx context.Context, conn state.SQLiteConn, taskID string, ttlSeconds *int64, claimer *string) (*Task, error)

Atomically moves a review task to running under a new reviewer run, demoting it when a parent reopened

func ClaimTask

func ClaimTask(ctx context.Context, conn state.SQLiteConn, taskID string, ttlSeconds *int64, claimer *string) (*Task, error)

Atomically moves a ready task to running, demoting it to todo when a parent reopened, nil when the claim lost

func GetTask

func GetTask(ctx context.Context, conn state.SQLiteConn, taskID string) (*Task, error)

Task by id, nil when no row matches

func ListTasks

func ListTasks(ctx context.Context, conn state.SQLiteConn, o ListTasksOptions) ([]*Task, error)

Tasks matching the filters, archived ones only when asked, highest priority first by default

func TaskFromRow

func TaskFromRow(row *Row) (*Task, error)

Task from a row, epochs parsed from text stamps, skills decoded from JSON and absent columns defaulted

type TypeError

type TypeError struct{ Msg string }

TypeError is the Python TypeError a malformed value raises

func (*TypeError) Error

func (e *TypeError) Error() string

type ValueError

type ValueError struct{ Msg string }

Python ValueError raised by board and task validation

func (*ValueError) Error

func (e *ValueError) Error() string

type WorkerTermination

type WorkerTermination struct {
	Pid       any
	ClaimLock *string
	StartedAt any
}

WorkerTermination is the pid, claim lock and start time of a worker to signal after commit

type Workflow

type Workflow struct {
	Columns []Column
	Manual  ManualMoves
}

Board columns in board order and the manual move allow list

func (Workflow) All

func (w Workflow) All() iter.Seq[Column]

Columns in board order as an iterator

func (Workflow) Keys

func (w Workflow) Keys() []string

Column keys in board order, never including archived

func (Workflow) Validate

func (w Workflow) Validate() error

ValueError for duplicate keys, a reserved archived column or moves naming unknown columns

Jump to

Keyboard shortcuts

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