Kata Durable Task Ledger

repository·main·Indexed 43 days ago

https://github.com/kenn-io/kata

A durable task ledger and local-first issue tracking system designed for coding agents and humans. It stores state in a local SQLite database and provides CLI, TUI, and Web interfaces. Features include agent-specific operating contracts, integration with Claude Code and Codex, and a Svelte-based UI package (@kenn-io/kata-ui) for embedding issue details.

Tokens
98K
Snippets
249
Records
397
Agent score
57%

What's inside Kata

  1. Use @kenn-io/kata-ui to embed Kata issue details

    main

    The @kenn-io/kata-ui package provides Svelte components for rendering read-only Kata issue details within trusted hosts.

    Key Architectural Principles:

    • No Networking/Routing: The package does not perform network requests, manage routing, or own persistence state. The host application is responsible for fetching data.
    • Data Flow: The host must fetch a canonical Kata issue-detail response, verify its compatibility using supportsKataAPISchema, transform it using projectIssueDetail, and then pass the resulting model to the IssueDetail component.
    • Security: The package only receives Kata wire data and host-supplied callbacks. Do not expose daemon bearer tokens or browser-session headers to the package. All data fetching should occur through an authenticated backend or credential broker.
    <script lang="ts">
      import {
        IssueDetail,
        projectIssueDetail,
        supportsKataAPISchema,
        type KataIssueDetailModel,
        type KataIssueDetailWire,
      } from '@kenn-io/kata-ui'
    
      let { 
        apiSchemaVersion, 
        wire 
      }: { 
        apiSchemaVersion?: string; 
        wire: KataIssueDetailWire 
      } = $props()
    
      const compatible = $derived(supportsKataAPISchema(apiSchemaVersion ?? ''))
      const detail: KataIssueDetailModel | undefined = $derived(
        compatible ? projectIssueDetail(wire) : undefined,
      )
    </script>
    
    {#if detail}
      <IssueDetail {detail} />
    {:else}
      <p>This Kata daemon is not compatible with the embedded issue detail.</p>
    {/if}
  2. Understand MCP Project Scopes

    main

    The MCP server's authority is determined by its startup scope. You can restrict or expand what the MCP client can see and modify using the following flags:

    FlagBehavior
    --workspace or --projectServes exactly one explicit project. Issue references are scoped to that project.
    --projects <list>Serves a specific list of projects. The list is resolved once using immutable project UIDs.
    --all-projectsServes every project accessible to the selected daemon. Required for project administration (create, rename, merge, etc.).

    Multi-project behavior:

    • Issue References: Use the format project#ref for reads/writes across multiple projects.
    • Search: Results from multiple projects are interleaved. If projects use different search modes, the result reports mode: "mixed".
    • Writes: Creating issues or other project-selected writes in multi-project mode requires an explicit project identifier.
    • Permissions: A scoped server (using --project or --projects) can read its projects but cannot perform administrative actions like purge or archive on the daemon's catalog; those require --all-projects scope.
  3. How actor attribution is determined

    main

    Every mutation in kata records an actor string. The precedence for determining the actor in Local mode is:

    1. --as flag
    2. $KATA_AUTHOR environment variable
    3. $USER environment variable
    4. git config user.name
    5. anonymous

    In Shared identity mode, the daemon derives the actor directly from the bearer token and ignores any actor supplied in the request body.

    Note: Actors are stored as free-form snapshots on each event to ensure historical auditability even if a user is renamed or a token is revoked.

  4. Understand the Agent Orchestration model in Kata

    main

    Kata is a tracker, not an orchestrator. It does not manage worktrees, launch agents, or supervise processes. Instead, it provides a durable board and a metadata convention (work.*) that external tools (Launchers, Agents, Coordinators, and Merge Automations) use to coordinate work around a shared issue.

    Core Roles

    • Launcher: Starts the agent session, creates the tracking issue, and manages work.branch.
    • Working Agent: The coding agent that signals its live state (e.g., stuck, needs-human) via work.attention.
    • Coordinator: A delegating agent or human dashboard that monitors issues using kata wait, kata list, or kata events.
    • Merge Automation: A pipeline that verifies work and closes the issue using kata close.
  5. How the event log works as the system spine

    main

    Kata is auditable by construction because state changes are recorded as events rather than just updating rows. The system follows three core rules:

    • events table: An append-only, authoritative record of every state change. Each event includes the actor, a stable event uid, the originating instance uid, and a payload containing the field-level diff.
    • comments table: Stores current comment bodies and teammate attribution. While bodies can be edited for redaction, the UID, author, and creation time remain immutable. There is no 'delete' operation for comments other than a full issue purge.
    • Mutable current-state: While issues are stored as mutable rows for performance, every mutation emits an event, allowing the current state to be fully reconstructed from the event history.
  6. Manage the kata.Service lifecycle

    main

    The kata.Service lifecycle is managed via Run, Close, and Handler:

    • Run(ctx): Starts background workers (federation, GitHub sync, timed-claim). It does not open a network listener. It blocks until the context is canceled or Close is called. If Run returns, treat it as service termination: stop accepting traffic and inspect the error.
    • Close(): Cancels active work/requests, waits for them to stop, and closes the storage handle. It is safe to call multiple times.
    • Handler(): Returns the HTTP handler for the service.
  7. Implement conditional field writes (Compare-and-Set)

    main

    If your connector supports the conditional_fields capability, it can perform atomic compare-and-set operations on fields.

    When a write_fields request includes an expected object, the connector must:

    1. Compare the current canonical values of the fields in expected with the values provided in the request.
    2. If every current value matches its corresponding expected value, perform the write and return the canonical readback.
    3. If any value does not match, change nothing and return a field_conflict error.

    If the expected object is absent, the write is treated as an unconditional write.

  8. Understand Federation consistency and limitations

    main

    Federation operates under an eventual consistency model with several expected behaviors and limitations:

    • State Lag: Spokes read local state and may be behind the hub. Hub outages degrade lease acquisition, pull, push, and status freshness.
    • Write Lifecycle: Local spoke writes occur before hub acceptance. Offline cached hard leases can be superseded later.
    • Lease Violations: Lease violation signals are best-effort at ingest time and do not provide proof of causal authorization at the time of the original edit. Unleased edits are expected and not treated as violations.
    • Schema Skew: Pushing with a future schema will pause the push until the hub is upgraded. Stale schema-skew quarantines from older spoke builds will auto-release after the spoke is upgraded and restarted.
    • Validation Failures:
      • Stale peer-validation: Auto-releases when a compatible spoke syncs against a compatible hub.
      • Unknown-primary/Malformed events/Actor violations/Hash conflicts: These are permanent validation failures that can quarantine pushes and require operator diagnosis.
    • Enrollment Security: Enrollment creation uses normal daemon auth. The generated enrollment token only authorizes the spoke transport grant; it is not a user daemon API token.
    • Actor Enforcement: Pushed event actors are bound to the enrollment actor. If a spoke attempts to push a different actor, the hub rejects the batch and the spoke records it in quarantine.
    • Cross-Project Links: Links may span projects. If a peer is missing, the event and cursor advance, but the edge remains absent. The edge only materializes when both endpoint projects are enabled through the same hub federation group.
    • Purge: Running a purge causes the spoke to re-bootstrap.
  9. How Hybrid Search fusion works

    main

    When using hybrid or auto (with embeddings) modes, kata performs Reciprocal Rank Fusion (RRF) to combine results from the lexical (FTS) and semantic (vector) legs.

    Fusion Algorithm:

    • Uses $k=60$ with equal weights for both legs.
    • Formula: score(d) = Σ_legs 1/(60 + rank_leg(d))
    • Ties are broken deterministically using updated_at (descending) and then id.

    Result Metadata:

    • The matched_in field preserves original FTS column values but adds "semantic" if the vector leg contributed the document to the result set.
  10. Understand the Semantic Search generation lifecycle

    main

    Kata manages embedding models through a 'generation' lifecycle to ensure search stability during model upgrades:

    1. Building: When a new configuration (new fingerprint) is detected, the reconciler creates a building generation. It populates this generation using kitvec.Fill while the current active generation continues to serve search queries unchanged.
    2. Cutover: Once the building generation is fully populated, CutOver is called. This makes the new generation active, marks all previous generations as retired, and reclaims their storage (dropping vec0 tables and related rows).
    3. Cold Start: On a fresh installation or after a configuration reset, the reconciler performs an immediate cutover before the fill. During this period, search will return partial results while the backlog is processed.

    Important: Index.Query only reads from the active generation. A model swap will never expose a partially-filled index to users; users will see results from the old model until the new one is fully ready.

  11. Understand Leases and Write Gates in Kata Federation

    main

    In Kata Federation, Leases are hub-authoritative mechanisms used for agent coordination. They allow an agent to signal active work on an issue and gain temporary exclusivity against other non-comment mutations.

    Key Behaviors:

    • Exclusivity: When a lease is live, non-comment mutations on that issue are denied to other holders. Comment creation and edits bypass leases.
    • Conflict Handling: If a spoke pushes work that conflicts with a live lease, the hub does not drop the work; instead, it records a claim.violated status.
    • Offline Behavior: Spokes use cached lease state as a continuity hint when offline, but this is not proof of exclusivity. Timed leases expire based on hub time.
    • Audit: Use kata show to see current leases and unresolved violations for a federated issue, or kata federation status for project-level summaries.
    # View lease and violation info for a specific issue
    kata show
    
    # View project-level lease counts and violation summaries
    kata federation status
  12. Understand Kata Shutdown Behavior

    main
    The Kata daemon handles SIGTERM gracefully. When a shutdown signal is received, HTTP handlers are given up to 10 seconds to drain. There is a total shared budget of 25 seconds for all handlers, background workers, and hooks to complete before the process terminates.