Local AI Agent Workflows, Git Worktrees & Queue Merge
Canban workflows are declarative YAML 1.2 graphs (schema: 13, CURRENT in crates/workflow-engine) stored in SQLite (workflow_sources and immutable workflow_revisions). Visual Studio, manual YAML edits, and Edit with agent all compile and validate through the exact same Rust engine.
Visual Studio, SQLite source of truth & Stage projection
Open Workflows in any Project header to switch between Visual Studio, YAML Source, History, and Edit with agent:
SQLite Single Source of Truth: Workflows live inside canban.sqlite (workflow_sources + immutable workflow_revisions) rather than hidden YAML files in ~/.canban. Each WorkflowRun freezes its definition and definition_revision at creation so publishing new YAML never mutates in-flight runs.
Linear Schema Migrations (1..=13): crates/workflow-engine/src/migrations.rs sets BASELINE = 1 and CURRENT = 13, sequentially upgrading older YAML documents on parse (schema 11 added cardless event rules + exclude_self, schema 12 added secret/var env expressions, and schema 13 replaced with.profile on uses: agent steps with mutually exclusive default_agent / override to work with per-Card assignee).
How Visual Studio Maps Stages (stages.rs): YAML files do not have a top-level stages: block; instead, canban_workflow_engine::stages derives one Stage swimlane (StageView) per Board column (column, name, ordered steps, entry_rule, and exit via card.move using column: $next / next: $entry or Stay). Each Step can set stage: <column_id> explicitly (or let Studio infer it from on column entry rules and card.move transitions) and enabled: false to skip a step at compile time without breaking links.
Visual Studio for development.yaml: Backlog, Develop (@developer), and Review stages with the /card/source_trust == external_pr branch, Human approval gate, and Rebase · Sync Queue merge.
Verified YAML structure (schema: 13)
Parsing uses serde_yaml_ng with #[serde(deny_unknown_fields)] on Document, Step, WorkflowColumn, WorkflowRule, EventSelector, and ScheduleCardConfig. Unknown fields are rejected before publication.
Event triggers: event (card.column_entered, card.column_left, card.created, card.updated, manual, or repository events such as github.issue.opened, github.issue.comment_created, github.pr.comment_created, github.pr.review_submitted, github.pr.head_changed, github.pr.ci_failed, github.pr.ci_succeeded), start_at (target step ID), cardless (bool, default false), match (EventSelector: column, actor, origin, source_kind, reason, changed_fields, repository, subject, reply_to, include_related, include_initial, exclude_self), and enabled (bool, default true).
Repository polling & self-loop prevention: Active GitHub event rules poll repository endpoints even when Card intake is off, using durable baseline watermarks (opened vs. discovered). Set match.exclude_self: true (and optional match.repository: org/repo) to suppress triggers caused by Canban's own comments or reviews.
Cardless event rules (cardless: true, schema 11): Execute script, condition, agent, notify, and complete steps through the unified WorkflowRun engine without creating a Card (passing outputs between steps via $CANBAN_OUTPUT).
Schedule triggers: Set cron (5-field POSIX cron or @hourly / @daily / @weekly / @monthly) to mark a rule as event: schedule. Optional timezone (Local default, UTC, fixed offset like +08:00, or IANA name), overlap (skip default, queue, allow), and card: { column, title, body } (with {{date}}, {{datetime}}, {{run_number}}, {{workflow}}, {{rule}} placeholders; omit card for Cardless runs).
steps[] fields
Common keys: id (unique non-empty string), name, uses (optional when top-level run: is present), with, next (defaults to next list item except for condition and complete; card.move may use $entry), stage (optional column ID), enabled (bool, default true), on_changes_requested (top-level rework target on approval / deliver), on_failure (top-level single-use automatic fallback step ID on script steps).
script-only keys accepted at step top-level or inside with: (without conflicting values): run, shell (default bash -eo pipefail, fallback sh -e), working_directory (relative to Card workspace, no ..), timeout_minutes (1..=1440), timeout_seconds (1..=86400), continue_on_error (bool, default false).
env: { KEY: VALUE } map, valid only on agent and script steps, supporting ${{ secrets.KEY }} and ${{ vars.KEY }} (schema 12). Full precedence order: Host Login Shell < Global < CLI Agent < @Identity < Project < protected CANBAN_* context < workflow env < $CANBAN_ENV exports < step env.
Enters serialized FIFO Queue Merge (waiting_delivery). Pauses in waiting_approval immediately if card.hold_auto_merge is set.
notify
with.message, next
Emits workflow.notified timeline event and attention notification, then continues to next.
complete
*(none)*
Terminal step marking the WorkflowRuncompleted.
Conditions, source_trust & admit gates
Condition evaluation (condition)
During execution (crates/workflow-engine/src/runtime.rs), condition builds { "inputs": run.inputs, "outputs": run.outputs, "card": card } (with card.source_trust populated from Card::trust_level() — "local", "collaborator" for GitHub Issues, or "external_pr" for external GitHub PRs) and resolves with.pointer (must be empty or start with /):
Equality rules: Matches exact JSON equality, string "true" / "false" against booleans, numeric strings against numbers, and an absent pointer against null.
External PR gate: pointer: /card/source_trust with equals: external_pr routes untrusted PRs to approval:review while sending trusted branches to deliver:review.
Script output branching: Any KEY=VALUE written to $CANBAN_OUTPUT in a prior script step is stored at /outputs/<step_id>/<KEY>, e.g., pointer: /outputs/script:check/gate with equals: ok.
Capacity & ready-queue gates (admit)
admit validates that at least one of agent_slot: true or max_ready: 1..=100 is enabled (definition.rs). Waiting runs enter waiting_capacity and are released by AppServer's admission pump (canban_scheduler::admissions) strictly in Board order within their column:
agent_slot: true (default): Holds the Card until a global automatic Agent slot (scheduler.max_agents, default 8) is free.
max_ready: K: Caps how many Cards that already passed this gate may remain in that column (for example, gating Backlog planning at max_ready: 2).
canban card adopt: Claiming a live interactive session via start_adopted bypasses admit gates so an active user terminal is never queued behind pending capacity.
Canban resolves environment variables and encrypted secrets across a 1 Global + 3 Local Layers model without writing plaintext secrets into config/agents.json or snapshots:
Host Login Shell (Base): Controlled per host via Host Settings (Inherit vs. Minimal (PATH only)).
Global (Settings → App → Environment & Secrets): Shared across Projects, Agents, Scripts, and Terminals on the host, with desensitized preview (env.preview) and Unset support.
CLI Agent & @Identity (Settings → Host Settings → Agents & Identities): Stored per host in SQLite (CLI Agent < @Identity) without touching config/agents.json.
Workflow, $CANBAN_ENV & Step env:: Workflow root env < $CANBAN_ENV < step env, expanding ${{ secrets.KEY }} and ${{ vars.KEY }} (lookup precedence: Project → Agent → Global), while core CANBAN_* context keys are protected from override.
Per-host encrypted Vault (XChaCha20-Poly1305): Each host maintains an independent 256-bit <CANBAN_HOME>/vault.key (0600) and encrypts secret values in SQLite vault_entries with AAD binding. Snapshots and env.preview expose only masked hints (configured + short suffix), never plaintext.
Untrusted external_pr isolation & log masking: Unattended runs on external_pr or untrusted external cardless events automatically force Minimal (PATH only) host env, skip all secrets (expanding ${{ secrets.KEY }} to an empty string with a log notice), and mask secret values (len >= 6) as *** across script logs, failure tails, and $CANBAN_OUTPUT.
Tip: For PR reviews, keep @reviewer saving a local unpublished review_draft.json via canban review draft, or add an optional toggleable script step that calls "$CANBAN_CLI" review publish after human approval.
Validation, rework loops & failure handling
Static validation rules (definition.rs)
Before saving or publishing, validate_definition verifies all column IDs, profile IDs, step targets, sync_base prerequisites (create_worktree: true), relative working_directory bounds, and cycle freedom: automatic cycles through next, condition.then, and condition.otherwise are rejected.
Rework & failure edges
Loops are only permitted across explicit decision or failure boundaries:
Human rework (on_changes_requested): Available on approval and deliver steps (compiles to rework). Requesting changes (workflow.decide with decision: "rework") clears human_gate, saves optional reviewer notes into inputs.rework_feedback, and routes back to the target step (e.g., agent:develop).
Script fallback (on_failure): When a script step fails (continue_on_error: false), fail_script records exit code and log tail feedback (rework_origin: "script_failure") and jumps to on_failureat most once per run (script_failures[step_id] == 0). A second consecutive failure (or unconfigured on_failure) pauses in waiting_approval for human Retry, Rework, or Stop.
Agent reporting & stale detection: Terminal exit or idle never advances agent steps. canban report --state completed advances to next; blocked / failed moves the run to blocked; backlog cancels the run. Modifying Card title/body/content mid-run changes input_digest and marks completion stale until human rework or stop.
Serialized FIFO Queue Merge (deliver)
Entering deliver serializes delivery across parallel Card worktrees so branches never race against the target branch:
Strict FIFO Queue Order: Drains waiting_delivery runs in (inputs.queued_at, storage_index) order, grouping up to batch_size (1..=50, default 5) compatible queue-head Cards (target_branch, strategy, sync_upstream, test_command, and conflict profile) into <home>/worktrees/<project-ns>/_merge_queue.
Agent Turn-Settle Guard: If an Agent invoked canban report --state completed mid-turn while Herdr still reports active work, Canban waits for the turn to settle (bounded by a 3-minute grace window) before integrating.
Integrate & Verify: Applies strategy (rebase default, squash, or --first-parentmerge), then runs test_command once on the integrated batch if configured (skipped when unset).
Fast-Forward, Push & Archive: Clean batches fast-forward the target branch once, push once when sync_upstream: true, and auto-archive merged Cards after saving refs/canban/cards/<card-id>.
Conflict Resolution (@merger): On batch conflict or test failure, Canban persists MergeBatch and refs/canban/batch/<short_id>/{target,card-<N>}, marks participating runs waiting_batch, and dispatches one Project-scoped @merger session in _merge_queue (which can fix in place or evict a failing Card via canban batch report --state completed --evict <CARD_NUMBER>). Single-Card deliveries without test_command resolve directly in the Card worktree up to max_conflict_attempts (default 3, 0 disables).
Managing workflows via CLI
Inspect, validate, export, and publish workflows from the terminal (or query the live schema contract via workflow.schema):
How does Canban isolate parallel coding agents on the same Git repository?
When a Card enters a workflow with workspace.create_worktree enabled, AppServer allocates a dedicated Git worktree at <dir>-<proj4>/<card-number> so multiple agents never edit or overwrite the same working directory simultaneously.
Why does Canban require explicit canban report instead of detecting shell exit?
Interactive coding CLIs frequently run inside long-lived PTYs or wait between sub-tasks, so shell exit or prompt idle is ambiguous. Explicit canban report --state completed guarantees a stage only advances when the agent confirms its deliverables and tests.
How does FIFO Queue Merge prevent broken main branches when multiple cards finish together?
The deliver step queues parallel Card branches in strict FIFO order into a single _merge_queue worktree, integrates batches via rebase, squash, or merge, runs test_command once on the combined result, and invokes a project-scoped @merger agent only if a conflict or test failure occurs.
Can I schedule recurring coding agent tasks without creating Kanban clutter?
Yes. Any workflow rule with a cron expression runs on schedule; include card: { column, title, body } to generate a Card per run or omit card for Cardless background execution, with overlap controls (skip, queue, or allow).
How are workflow secrets protected from untrusted external PRs and logs?
Secrets live in a per-host XChaCha20-Poly1305 encrypted Vault keyed by <CANBAN_HOME>/vault.key (mode 0600) and are never stored in snapshots. Unattended runs for external_pr or untrusted cardless events force Minimal (PATH only) host env and skip all secrets, while script logs and outputs mask secret values with ***.