# AI Kanban — Browser Workspace for Human-AI Work

Build a polished, implementation-ready static JavaScript application for GitHub Pages, with no backend, under `outputs/implementations/ai-kanban-browser/`. AI Kanban is a local, folder-backed Kanban board in which every card is an active workspace for human–AI collaboration. The core board must work without an AI provider.

## Architecture and Board Workspace lifecycle

Use semantic HTML, modern CSS, and standards-based JavaScript ES modules. Deploy only static assets: no Node.js runtime, server routes, serverless functions, sockets, or local service. The deployable root contains `index.html`; all asset URLs are relative and work beneath a GitHub Pages repository subpath. Vendor pinned JavaScript and WebAssembly dependencies locally. Use Web Workers for SQLite, search, parsing, migrations, import/export, and other CPU-heavy work. UI code uses typed repository and service APIs only; it never receives a raw database connection or issues SQL.

A user-selected Board Workspace folder is the portable canonical workspace, agent working directory, and local trust boundary. Use a versioned `manifest.json` identifying the workspace id, format and protocol versions, primary state file, reserved directories, application-owned files, agent-bootstrap paths, and content fingerprints. Use validated relative paths including `board.sqlite`, `attachments/`, `artifacts/`, `exports/`, `.ai-kanban/coordination/`, and `.agents/skills/ai-kanban/`. Reject absolute paths, `..` traversal, symlink escapes, and paths outside the selected directory. Do not alter unrecognized files; require confirmation before destructive cleanup of recognized application-owned files.

First run presents exactly Open Board Workspace, Create Board Workspace, and Try demo. Open/Create invoke `showDirectoryPicker()` only from explicit user gestures in a secure context and request read/write permission. Never claim durability before a writable handle exists. Try demo is visibly memory-only. Bundle a Personal Research demo board with recurring cards for a macroeconomic pulse, things to do with a four-year-old in São Paulo, family trips, a collaborative vacation planner, and age-appropriate activities.

Persist only a recent `FileSystemDirectoryHandle` in IndexedDB for reconnection. On return, query permission and request it only through a user gesture. Show folder name, permission state, dirty/saving/saved status, and last successful durable write. Provide Save, Close workspace, and archive export. Before any action replaces dirty state, save successfully or ask for confirmation; cancellation changes nothing. Closing clears in-memory state. Feature-detect the File System Access API: on unsupported browsers, provide explicitly labeled archive import/download rather than connected autosave. Browser storage may cache preferences and handle metadata but never replaces `board.sqlite` as canonical data.

Use a calm, trustworthy visual language: restrained navy, mineral teal, warm paper, and coral attention accents. Use violet/teal for unreviewed AI changes and amber for Needs you, always with icon and text. Support visible focus, reduced motion, accessible native controls, keyboard-complete interactions, responsive layouts down to 320 CSS pixels, and the native `hidden` attribute as authoritative.

## SQLite schema and repository operations

Vendor a pinned SQLite WASM build that imports existing database bytes from `Uint8Array` and exports complete bytes. A dedicated Worker owns the only live database connection and exposes validated `create`, `open`, `health`, `snapshot`, `query`, `mutate`, `export`, and `close` messages. `board.sqlite` is canonical; in-memory SQLite, OPFS, IndexedDB, and caches are working state only. Document a practical workspace-size limit because saving rewrites complete database bytes.

Enable foreign keys, rollback-journal mode, full synchronous durability, bounded busy timeout, stable text ids, UTC ISO 8601 timestamps with timezone offsets, integer ordering keys, deterministic transactional migrations, and typed recovery errors. Preserve original bytes before migration; reject unsupported future schema versions. Validate messages, packets, paths, imports, and SQL parameters; never concatenate user input into SQL.

Implement and index normalized tables for: metadata including schema version, `workspace_id`, revision, control generation and owner; ordered columns; cards with title, Markdown description, `P0`–`P3`, assignee, kind (`task`, `question`, `result`), attention state, timestamps, archived state, current-turn and latest-output projections, provenance, and last-change actor; dependencies; explicit-state plan items; immutable execution turns; typed outputs, output versions, and surfaces; decision threads/options/feedback/gates; recurring research memory and coverage; append-only activity events; attachments, artifacts, and handoff packets; agent runs/questions/answers; and idempotency keys.

Create default ordered columns: Inbox, Planning, In Progress, Review, Blocked, and Done. Index column/order, title/description search, priority/attention, active turns, ready claims, output history, activity by target/time/type/actor, dependencies, and memory fingerprints/states. Keep append-only activity separate from current snapshots.

Make all multi-record updates transactional. Moving or reordering a card and creating its activity event are one transaction. Completing, failing, cancelling, or requeuing a turn updates the card projection and workflow position with the final event. A confirmed Done-to-Inbox move is Run again: it creates a fresh queued turn linked to the earlier successful turn and never changes historical turns. Allow at most one active turn per card by default; claim queued work atomically with expected revision and idempotency validation.

Use one serialized browser save queue, coalescing rapid writes without losing final committed state; explicit Save flushes it. Before replacement, compare on-disk revision and fingerprint with the loaded signature. Abort on external change and provide reload, compare, export-draft, or explicit conflict recovery; never silently overwrite. Keep prior bytes until replacement closes. Use Web Locks and `BroadcastChannel` where available so another tab is read-only unless it acquires the workspace lock.

## Human-agent coordination and skill protocol

Use versioned coordination records in `.ai-kanban/coordination/`: one human signal and one state record for each approved agent. Each actor writes only its own record. Records include `workspace_id`, protocol version, actor/holder id, monotonically increasing sequence or control generation, timestamp, requested state, and observed revision. Replace records safely and ignore incomplete, stale, mismatched, or lower-generation records. Store substantive questions, answers, progress, outputs, and audit history in SQLite, not mailbox files.

Create root `AGENTS.md`, root `CLAUDE.md`, and exactly one canonical `.agents/skills/ai-kanban/` bundle containing `SKILL.md`, dependency-free `ai_kanban.py`, `ai-kanban.sh`, and `ai-kanban.ps1`. Root files point to the skill rather than duplicating its contract. Track generated paths, version, and fingerprints in the manifest. On reopen, verify the bundle and offer Repair or Update when absent or stale. Never silently overwrite user-created or user-edited bootstrap files; show a comparison and require confirmation.

The skill tells compatible agents started in the workspace to read the manifest and skill, preflight, register identity and heartbeat, inspect/resume work, then watch: poll with bounded backoff, atomically claim one ready turn, execute validated commands, publish checkpoints, ask for input or complete/yield, and return to watching. Empty queues are quiet, not terminal. Stop on cancellation, control revocation, workspace closure, integrity failure, or host termination. State honestly that a skill cannot force a terminated runtime to act, remain alive, consume future output, or start future model turns; continuous autonomy requires a host-supported scheduler or runner.

Show Start your agent after create/reopen. Tell users to start Copilot CLI, Claude Code, or a compatible agent in the workspace; use folder-name/platform guidance, not fabricated absolute `cd` commands. Show Waiting for agent until a valid workspace-matched heartbeat arrives, then show identity, control state, current turn, and heartbeat. Offer copyable fallback instructions, diagnostics, Repair, and retry without promising all products discover instruction files automatically.

Enforce the cooperative single-writer baton states `human`, `granting_agent`, `agent`, `reclaim_requested`, and `recovering`, with owner, holder, generation, revision, and bounded lease. Every mutation verifies generation, holder, and expected revision immediately before write. A new owner may write only after the old owner commits or rolls back, closes its writer, publishes final revision, and acknowledges handoff. Human reclamation has priority. Lease expiry is recovery evidence, not overwrite permission.

For browser whole-file SQLite and native agent SQLite, control generation and revision must agree in SQLite and coordination records. The browser saves, grants control in SQLite, closes its writable stream, publishes the grant, and becomes read-only. Agents open fresh connections, use `BEGIN IMMEDIATE`, verify control/revision, mutate and audit, increment revision, commit and close, then publish a marker. Never hold a transaction during reasoning, tools, generation, waiting, or polling. The browser reloads only after marker, journal stabilization, integrity check, and revision confirmation. The Python CLI uses only `sqlite3`, `argparse`, JSON, and filesystem APIs; mutation commands require revision, generation, actor, run id, and idempotency key.

## Cards, decision loops, execution turns, memory, and output surfaces

Cards are mixed task, question, and result workspaces. Users can create, edit, archive, search, filter, reorder, and move cards through pointer and keyboard controls. Compact cards show title, priority, assignee, highest-value summary, turn status, latest-result preview, dependencies, attention cue, and relevant action. Detail exposes metadata, safe Markdown description, plans, decision thread, turns, memory, output history, activity, provenance, handoff, archive, and publish-result actions.

An execution turn is one bounded attempt with stable id, monotonic display number, status `queued`, `claimed`, `running`, `needs_input`, `review`, `complete`, `failed`, or `cancelled`, trigger/requester, actor, agent run id, idempotency key, instruction snapshot, lifecycle timestamps, checkpoints, result/error, outputs, and memory lineage. Completed history is immutable. Initial placement does not run work automatically; expose Ready for agent. Requeue/Run again creates a fresh linked turn with a new snapshot. A needs-input turn resumes after an answer. Cancellation keeps partial outputs and reasons.

Implement typed text, status, link, program, table, diff, image, and file surfaces. Every surface has stable id, owner, title, payload/reference, schema version, draft/streaming/complete/failed/stale/superseded/approved status, source, timestamps, lineage, and actions. Render content safely. Support program copy/open/download, validated sortable/filterable/exportable tables, diff comparison/approval, image preview/gallery/zoom/download/alt text, and safe file metadata. Feature the latest successful result and keep dated versions in ordered History with comparison where meaningful.

Implement durable decision threads with `briefing`, `exploring`, `needs_feedback`, `committed`, `deep_work`, `review`, and `accepted` phases. The editable briefing captures goals, suggestions, constraints, preferences, exclusions, budget/effort bounds, criteria, and unknowns; the user explicitly marks it Ready for agent. Exploration tests credible alternatives and displays bounded comparisons with evidence, fit, tradeoffs, uncertainty, and practical constraints. Ask focused questions when missing preferences materially change ranking; do not guess. Preserve append-only feedback, ranking, shortlist, rejection, restoration, notes, and added options.

Deep work requires an explicit gate selecting one option and current constraints. A confirmed Planning-to-In Progress move can complete exploration and queue deep work atomically. Snapshot selected option, evidence, feedback, constraints, and unresolved questions. Do not reconsider rejected options without material new evidence. Review shows proposal, assumptions, evidence dates, risks, and accept/revise actions; acceptance retains all history.

Support recurring topic monitor cards as dated cycles with cadence, lookback window, topic, source coverage, gaps, new findings, and retained context. Read prior reports and durable inspectable memory before a cycle. Classify findings as new, materially updated, unchanged context, duplicate coverage, corrected, or no longer current. Distinguish confirmed facts, claims, announcements, opinions, forecasts, and speculation. Memory retains normalized subject, fingerprint, summary, source, publisher, evidence date, first/last seen, content hash, relevance, state, coverage, gaps, and lineage. Users can inspect, correct, dismiss, pin, export, and explicitly forget memory without rewriting historical reports.

Provide provider-neutral handoff: export selected cards as compact versioned JSON and Markdown containing intent, context, plan, relevant activity, and requested response shape. Import response packets by paste or file, validate completely, preview proposed changes, require approval before commit, and retain packet/activity provenance. An optional `AIProviderAdapter` remains vendor-neutral. Credentials are session-memory only. Before direct send, show provider, endpoint, model, exact content, and purpose, then require confirmation.

## Interface states and interactions

Before activation show Open Board Workspace, Create Board Workspace, and Try demo; afterward show state-aware Save, New card, Agent control, AI handoff, Workspace menu, search, and attention filters. Foreground Needs you, AI working, and AI updated counts without a global chat pane or operations-console feel. Keep raw SQLite details in About workspace.

Implement accessible first-run, loading, empty, active, dirty, saving, saved, permission-limited, read-only, conflict, unsupported-browser, recovery, agent-waiting, connected, transfer, and error states, each with explanation and next safe action. Board filters cover title/description, priority, assignee, column, kind, turn status, attention, origin, blocked, and archived state. Pointer drag/drop includes preview, targets, cancellation, persistence-conflict rollback, and full keyboard alternatives. Show invalid-move reasons at the interaction point.

Implement the vacation loop: humans edit candidate destinations and constraints in Inbox; Planning performs broad comparison and feedback rounds; confirmed movement to In Progress queues deep research and dated itineraries; Review presents revision or acceptance. Maintain explicit turn, gate, output, and activity history. Add a quiet footer with relative links to the source promplet, compiled implementation specification, and public tutorial.

## Security, compatibility, and recovery

Treat workspace, agent, packet, attachment, artifact, and provider content as untrusted. Never render imported text as executable HTML or execute generated files. Validate manifests, versions, ids, packet schemas, relative paths, Worker messages, and coordination records. Do not upload workspace bytes for analytics, diagnostics, previews, or crash reporting. Do not claim secure secret storage, background execution, WebSockets, or protection from malicious software that ignores the cooperative protocol.

Handle revoked permission, missing files, invalid manifests, future versions, corrupt databases, migration errors, partial export, stale coordination, crashed agents, expired leases, commit-marker mismatch, journal delay, lock contention, conflicting tabs, and unsupported browsers with concrete recovery instructions. Never silently fall back from connected workspace data to unrelated browser storage. Preserve drafts on conflicts.

## File tree, implementation sequence, and test matrix

Deliver `index.html`, `README.md`, `package.json`, source modules for UI/domain/workspace/coordination/repository, vendored SQLite WASM and licenses, root instruction templates, a sample Board Workspace with the skill bundle, documentation, unit/integration/Playwright tests and fixtures, `scripts/serve-static.mjs`, and `scripts/verify-vendor-assets.mjs` beneath `outputs/implementations/ai-kanban-browser/`.

Implement in order: static entrypoint, relative assets, design tokens, and shell; vendored SQLite and Worker/schema/migrations/repository; workspace lifecycle/save/lock/conflict recovery; card/turn/activity/output/decision/research services; responsive board/detail and accessible drag/reorder; coordination protocol, bootstrap, Python skill, launchers, and agent UI; handoff boundary; demo/docs/GitHub Pages/footer; then verification.

Write deterministic unit tests for schema creation/reopen/migration/rollback, constraints, ordering, movement/activity atomicity, search/filter, turn lifecycle and claim idempotency, requeue, question/resume, cancellation, output history, decisions, memory classification, import/export equivalence, corruption/future schema, Worker propagation, path/manifest validation, and conflict recovery. Write integration tests for lifecycle, save coalescing, permission loss, archive fallback, locks, handoff/reclaim, stale generation, revision mismatch, agent crash points, journal stabilization, malformed records, unsupported hosts, and competing claims. Use Playwright for first run, create/open/reconnect, demo labeling, board operations, pointer/keyboard drag, 320-pixel layouts, reduced motion, focus, detail/output/decision flows, heartbeat/control, packet approval, repository-subpath/static/offline behavior, and clean console output. README documents development/test commands, canonical data boundary, browser support, workspace-size guidance, and known limitations.