From 507081123516d05dd3b6fe6c3669fbca699bd8a7 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 15 Oct 2026 19:19:16 -0700 Subject: [PATCH 1/4] docs: consolidate product specs and preserve archive planning --- CONTEXT.md | 2 +- PRD.md | 174 --------- README.md | 4 +- docs/adr/0003-rust-owned-render-scene.md | 13 +- docs/adr/0004-local-claude-session-archive.md | 189 +++++++++ docs/architecture.md | 26 +- .../claude-codex-session-terminology.md | 2 + .../manual-github-release-retention.md | 2 + docs/research/serena-multi-agent.md | 2 + issues/031-notification-source-settings.md | 4 +- issues/051-ranch-animal-vocabulary-seam.md | 90 +---- issues/056-task-timer-binding.md | 4 +- issues/059-self-describing-hook-frame.md | 5 +- issues/060-session-staleness-sweep.md | 5 +- issues/061-hook-change-events.md | 4 +- issues/062-stable-hook-client-path.md | 5 +- issues/README.md | 7 +- .../024-display-subsystem-agent-prompt.md | 132 ------- .../046-timer-expiry-service-extraction.md | 2 +- .../{ => done}/057-animal-render-contract.md | 2 + .../058-selection-belongs-to-focus.md | 2 + issues/done/README.md | 3 + issues/icebox/021-all-monitors-default.md | 4 +- issues/icebox/022-wrangle.md | 4 +- specs/001-render-domain-seam/spec.md | 2 +- .../checklists/requirements.md | 36 ++ .../contracts/current-product-spec.md | 45 +++ .../contracts/pass-record.md | 70 ++++ .../contracts/source-marks.md | 87 +++++ specs/002-speckit-docs-pass/data-model.md | 114 ++++++ specs/002-speckit-docs-pass/pass-record.md | 105 +++++ specs/002-speckit-docs-pass/plan.md | 176 +++++++++ specs/002-speckit-docs-pass/quickstart.md | 70 ++++ specs/002-speckit-docs-pass/research.md | 141 +++++++ specs/002-speckit-docs-pass/spec.md | 118 ++++++ specs/002-speckit-docs-pass/tasks.md | 200 ++++++++++ specs/003-ranch-today/spec.md | 185 +++++++++ specs/004-task-timer-hand-edits/spec.md | 52 +++ specs/005-late-hook-frame/spec.md | 61 +++ specs/006-unheard-turn-ends/spec.md | 49 +++ specs/007-one-hook-delivery/spec.md | 48 +++ .../contracts/archive-health.md | 77 ++++ .../contracts/claude-ingestion.md | 135 +++++++ .../contracts/data-root-migration.md | 40 ++ .../contracts/ranch-db-v1.sql | 121 ++++++ .../008-claude-session-storage/data-model.md | 319 ++++++++++++++++ specs/008-claude-session-storage/plan.md | 340 +++++++++++++++++ .../008-claude-session-storage/quickstart.md | 186 +++++++++ specs/008-claude-session-storage/research.md | 349 +++++++++++++++++ specs/008-claude-session-storage/spec.md | 361 ++++++++++++++++++ specs/README.md | 24 ++ 51 files changed, 3776 insertions(+), 422 deletions(-) delete mode 100644 PRD.md create mode 100644 docs/adr/0004-local-claude-session-archive.md delete mode 100644 issues/done/024-display-subsystem-agent-prompt.md rename issues/{ => done}/057-animal-render-contract.md (94%) rename issues/{ => done}/058-selection-belongs-to-focus.md (90%) create mode 100644 issues/done/README.md create mode 100644 specs/002-speckit-docs-pass/checklists/requirements.md create mode 100644 specs/002-speckit-docs-pass/contracts/current-product-spec.md create mode 100644 specs/002-speckit-docs-pass/contracts/pass-record.md create mode 100644 specs/002-speckit-docs-pass/contracts/source-marks.md create mode 100644 specs/002-speckit-docs-pass/data-model.md create mode 100644 specs/002-speckit-docs-pass/pass-record.md create mode 100644 specs/002-speckit-docs-pass/plan.md create mode 100644 specs/002-speckit-docs-pass/quickstart.md create mode 100644 specs/002-speckit-docs-pass/research.md create mode 100644 specs/002-speckit-docs-pass/spec.md create mode 100644 specs/002-speckit-docs-pass/tasks.md create mode 100644 specs/003-ranch-today/spec.md create mode 100644 specs/004-task-timer-hand-edits/spec.md create mode 100644 specs/005-late-hook-frame/spec.md create mode 100644 specs/006-unheard-turn-ends/spec.md create mode 100644 specs/007-one-hook-delivery/spec.md create mode 100644 specs/008-claude-session-storage/contracts/archive-health.md create mode 100644 specs/008-claude-session-storage/contracts/claude-ingestion.md create mode 100644 specs/008-claude-session-storage/contracts/data-root-migration.md create mode 100644 specs/008-claude-session-storage/contracts/ranch-db-v1.sql create mode 100644 specs/008-claude-session-storage/data-model.md create mode 100644 specs/008-claude-session-storage/plan.md create mode 100644 specs/008-claude-session-storage/quickstart.md create mode 100644 specs/008-claude-session-storage/research.md create mode 100644 specs/008-claude-session-storage/spec.md create mode 100644 specs/README.md diff --git a/CONTEXT.md b/CONTEXT.md index 458339f..e53d25c 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -8,7 +8,7 @@ A desktop ranch you can see from the corner of your eye: each Focus the user hol ## Language -> Terms below are under review in an active domain-modeling session. Definitions will be rewritten as each term is settled. +> Settled names for the ranch. Specifications, issues, and UI copy use these words. The current product specification does not redefine them. ### Grouping diff --git a/PRD.md b/PRD.md deleted file mode 100644 index 9ff499b..0000000 --- a/PRD.md +++ /dev/null @@ -1,174 +0,0 @@ -# PRD — adhd-ranch - -**Status:** Living document — describes the app on `main` (latest release v0.1.4) -**Owner:** ryan -**Last updated:** 2026-09-20 - ---- - -## Problem - -A developer working across many microservices, agents, repos, and tickets loses the thread. Tools that try to help (Jira, GitHub, Linear) demand structure and time the user can't spend mid-flight. Notes, todos, and ticket trees become more cognitive load, not less. Agentic tools accelerate this — Claude Code spawns a tree of in-flight work with no central place to track "what am I actually focused on right now?" - -The problem isn't capacity. It's *signal compression*. The user needs a few buckets they can glance at and a way for those buckets to stay current without manual upkeep. - -## Why now - -Agentic coding is the multiplier. A user with 3+ Claude Code sessions running at once has exactly the context-fragmentation this addresses. The ambient pig overlay makes Focuses physically visible without demanding attention — the reminder is peripheral, not modal. - -## Target user - -Solo developer (initially: the author) who: -- Uses Claude Code daily across multiple repos. -- Has ADHD-flavored attention, or just runs more parallel work than working memory accommodates. -- Owns a Mac. -- Will hand-edit markdown if it's faster than clicking. - -## Guiding metaphor - -**A ranch you can see from the corner of your eye.** Pixel pig sprites roam the screen — one pig per Focus. They walk slowly. You don't have to look at them. But when you glance, you know what's on your ranch. Click a pig to see its tasks. Clear a task from that card. The pigs never interrupt; they just exist. - -## Goals - -1. Pixel pig sprites roam a transparent overlay spanning the enabled displays — one pig per Focus. -2. Clicking a pig shows its name and Task list in the `AnimalDetail` card. Tasks can be added, edited, checked off, and cleared from that card, and Focus/Task timers can be edited from clock/time controls. -3. Manual Focus creation from the tray menu. -4. Markdown is the source of truth — user can hand-edit any Focus file; pig count updates live via file watcher. -5. Hard caps (5 Focuses, 7 Tasks per Focus) with overload alerts. - -## Non-goals - -- Slash commands, a network API, or any external writer of Focus data. The Claude Code integration is inbound and read-only over a local Unix socket; the user is still the only author of Focuses and Tasks. -- Notification hook forwarding. -- Auto-completion of Tasks or auto-merge of Focuses. -- Platform parity. macOS is the primary target; Windows and Linux packages are built but are not a design driver. -- Multi-user / sync / cloud. -- Fancy menu bar UI — native tray menu is sufficient. - -## User stories - -- **US1.** I glance at my screen and see three pixel pigs wandering in the corners. I know immediately: three things are on my plate. I don't have to open anything. -- **US2.** I click a pig. A small dark card appears near the pig: its name and a short task list. I tap `✗` next to a task. It disappears. I click a clock/time control to start or clear a timer. Card closes when I click elsewhere. -- **US3.** I finish a Focus. I open the menu bar item, find it in the list, and delete it. Pig disappears from the screen. -- **US4.** I add a Focus: click the menu bar item → "+ New Focus" → enter name + description. A new pig spawns and starts wandering. -- **US5.** I hand-edit `~/.adhd-ranch/focuses/customer-x-bug/focus.md` in vim, append `- [ ] release staging`. Save. Pig's task list reflects it within seconds. -- **US6.** I have 6 Focuses. The tray icon turns red. I delete a stale Focus. - -## Functional requirements - -### FR1 — Focus storage - -Each Focus is a directory under `~/.adhd-ranch/focuses//` containing `focus.md` with YAML frontmatter (`id`, `title`, `description`, `created_at`) and a body of `- [ ]` / `- [x]` bullets. Plain text only. Optional `timer.json` and `task-timers.json` sidecars hold Focus and Task timers. On Windows the data root is `%APPDATA%\adhd-ranch\`. - -### FR2 — Transparent overlay window - -- Transparent Tauri overlay window: no decorations, always-on-top, covering the enabled display span. -- Click-through when not hovering a pig: Rust polling thread reads Tauri `cursor_position()` every 16ms, compares against pig bounding boxes (sent from frontend), calls `window.set_ignore_cursor_events(!is_over_pig)`. -- Pigs receive click events normally; transparent background passes clicks to whatever is beneath. -- File watcher (`notify`) on `~/.adhd-ranch/focuses/`; pig count re-renders on disk changes. - -### FR3 — Pig UI - -- One `PigSprite` per Focus, positioned at the sprite's current (x, y) on the overlay. -- Pigs wander the enabled display regions: ~60 px/s with a minimum speed floor, random direction changes every 3–8 s, soft steering near region edges. -- Animation: real pixel-art sprite sheet (4 directions × 4 frames in one PNG), ticked at ~150ms. -- Drag and toss: click-and-hold then move ≥ 4px drags the pig; release tosses it with friction. -- Clicking a pig opens the `AnimalDetail` panel near the pig (edge-clamped): editable Focus title, duplicate and delete actions, task list with check-off, edit, and `✗` per task, and an "Add task…" input. -- Focus and Task timer editing is accessed by clicking the clock icon or current remaining time. No timer renders as a small clock; a running/expired timer renders as its current time/expired status. -- `AnimalDetail` closes on click-outside or Escape. -- **Focus timer growth (028 + 030):** If a Focus has a `FocusTimer`, its current animal projection grows from 1× to 3× sprite size linearly over the timer window. Focuses without a timer stay at 1×. Expired animals become ghostly, stop moving, face away, and appear in the tray's Expired section. Adding a new task to an expired Focus clears the expired timer and revives the animal. -- **Task timers (052 + 053):** Task timers are independent per Task. When a Task timer expires, `status: Expired` is persisted, `AnimalDetail` renders the Task timer as Expired, and the `task_timer_expired` notification source can emit through the platform notification sink. Task timer expiry does not affect animal rendering, tray expired state, or Focus timer status. -- **Implementation status:** The only concrete animal today is still the pig sprite; the detail surface is animal-neutral as `AnimalDetail`. - -### FR4 — Tray menu - -- Tray icon in the menu bar. -- Native menu with: - - "Gather Pigs" — pulls every pig back onto the primary display. - - "Agents as Animals" — check item toggling `agents.enabled` (off by default). - - "+ New Focus" → opens a small webview window for title, description, and optional timer. - - One submenu per Focus with "Delete…" (confirms when `widget.confirm_delete` is on). - - Expired submenu listing expired Focuses; clicking one opens its detail card. - - "Settings…" → opens the Preferences window. - - "Open Overlay DevTools" (debug builds only). - - "Quit". -- Tray icon turns red when over-cap. - -### FR5 — Caps - -- `MAX_FOCUSES = 5`, `MAX_TASKS_PER_FOCUS = 7` (configurable in `settings.yaml`). -- Writes exceeding caps succeed but flip over-cap flag. -- Tray icon turns red while over. -- System notification fires once per `under → over` transition. - -### FR6 — Configuration - -`~/.adhd-ranch/settings.yaml`: -```yaml -caps: - max_focuses: 5 - max_tasks_per_focus: 7 -notifications: - timer_expired: true - task_timer_expired: true - focuses_over_cap: true - tasks_over_cap: true -widget: - always_on_top: false - confirm_delete: true -displays: - enabled: 0 -agents: - enabled: false -pens: - max_size: 320 -``` - -Edited from the Preferences window (General, Widget, Displays, Notifications). Changes made there are persisted and applied without a restart (050). Manual file edits are picked up on app restart. - -Timer presets available at Focus creation and in `AnimalDetail` clock dropdowns: No timer / 2m / 4m / 8m / 16m / 32m / Custom (free integer minutes). `AnimalDetail` allows start/restart/clear for the Focus timer and each Task timer. - -## Non-functional requirements - -- **Latency:** pig count reflects file changes within 1s of save. -- **Click-through:** hit-test polling at ~60fps (16ms); transition latency < 32ms. -- **Reliability:** atomic writes (tmpfile + rename) behind an exclusive lock file. No partial-write corruption. -- **Footprint:** Tauri release build < 20 MB on disk; idle RAM < 50 MB. -- **Privacy:** zero outbound network. No telemetry. - -## Success metrics - -- Author can name their active Focuses by glancing at the screen without opening any tool. -- Pigs are visible and not disruptive — clicks pass through to other apps with < 32ms latency. -- Click-a-pig → task card round trip feels instant (< 100ms perceived). - -## Out of scope - -- Harnesses other than Claude Code, the only one whose Agent Sessions the ranch reads. -- Menu bar Focus detail for non-expired Focuses (clicking a Focus in the menu → highlight pig, open detail). -- Notification-hook forwarding. -- External aggregators: Jira, GitHub, Linear. -- Multi-machine sync. - -## Open questions / risks - -- **R1.** Click-through latency: 16ms Rust poll + IPC round-trip should feel transparent, but needs real-device testing. -- **R2.** ~~Cursor coordinate space~~ — resolved for single-monitor. `drag_active: AtomicBool` in hit-test thread prevents click-through race during drag. Real-device mixed-monitor drag still needs periodic validation. -- **R3.** ~~Multiple monitors: pigs spawn on primary monitor only.~~ 024 `display/` refactor fixed logical coordinate math and window sizing. 049 added DisplaySpace: Rust owns monitor geometry, React movement consumes normalized visible monitor regions, and Animals cannot wander into invisible gaps inside the overlay span. Only the primary display is enabled by default (icebox 021). -- **R4.** Pig positions on resize: if screen resolution changes (external monitor connect/disconnect), pigs reset to safe positions. -- **R5.** Always-on-top + fullscreen apps: at kCGFloatingWindowLevel (3), pigs disappear behind fullscreen apps. Acceptable for now. - -## Implementation phases - -1. **Phase 0 (done):** Tauri skeleton, storage, HTTP API, markdown read/write, caps, file watcher, proposals queue. -2. **Phase 1 (done):** Custom titlebar, app menu, always-on-top, regular Mac app. -3. **Phase 2 (done):** Transparent fullscreen window, click-through Rust polling thread, `PigSprite` placeholder, `usePigMovement`, animal detail card, tray icon + live focus list, typed errors, structured logging. -4. **Phase 3 (done):** New-focus creation from tray (014), delete from tray (015), configurable display spanning (017), real sprite sheet (016). -5. **Phase 3 polish (done):** Larger pig hitbox (018), AnimalDetail redesign (019), drag-and-toss physics (020), display subsystem refactor (024), pig freeze fix + keep-still (025), settings/preferences (026, 027, 032), DisplaySpace seam (049). -6. **Phase 4 — Timers (done):** Focus timers (028), timer expiry + notification sources (029), growth + expired tray list (030), Task timers + clock dropdowns (052), Task timer expiry workflow (053). -7. **Phase 5 — Architecture deepening (done):** IPC layer (033), domain invariants (034), store tests (035), ts-rs types (036), reader/writer collapse (037–041), domain timer ticker (044), focus document module (048), settings update workflow (050). -8. **Phase 6 — Distribution (done):** Focus duplication, first-launch example Focus, Windows data paths (#66); manual cross-platform release workflow (#72). -9. **Baseline cleanup (done):** removed the unused Proposal queue, decision log, localhost HTTP API, and orphaned frontend components. -10. **Phase 7 — Agents as Animals (done):** Claude Code sessions drawn as Animals, fed by hooks over a local Unix socket, off by default (#75), Agent Hooks window and bounded hook journal (#76), Unix/inert hook server split and `task check:windows` (#77), pen size cap and fence rendering (#78), release-mode Rust lint (#79), one Animal list over Focuses and Agent Sessions (055). -11. **Open:** notification source registry (031), Animal vocabulary for the movement layer (051). -12. **Icebox:** all-monitors default on first launch (021), wrangle pig / wrangle all (022). diff --git a/README.md b/README.md index 0d3643e..5b418e9 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ Issue tracking for a five-year-old. Menubar/tray desktop app — Tauri v2 + React. macOS is the primary target. -A small number of buckets ("Focuses") with a few bullets each ("Tasks"). Pixel pigs roam the screen as a peripheral reminder — one pig per Focus. Click a pig to inspect or edit its Tasks. Markdown on disk is the source of truth. +A small number of buckets ("Focuses") with a few bullets each ("Tasks"). Pixel Pig sprites roam the screen as a peripheral reminder — one Animal per Focus, and, when you turn it on, one Animal per Agent Session. Click a Focus Animal to inspect or edit its Tasks. Markdown on disk is the source of truth. -See `PRD.md`, `CONTEXT.md`, and `CLAUDE.md` for the full design and the programming rules every slice must follow. +See `specs/003-ranch-today/spec.md` for what the ranch does today, `CONTEXT.md` for names, and `CLAUDE.md` for the programming rules every slice must follow. ## Quick install (end-user) diff --git a/docs/adr/0003-rust-owned-render-scene.md b/docs/adr/0003-rust-owned-render-scene.md index 8973d8a..7319d0f 100644 --- a/docs/adr/0003-rust-owned-render-scene.md +++ b/docs/adr/0003-rust-owned-render-scene.md @@ -149,10 +149,13 @@ the second Species and second Harness make that authority harder to relocate. ## Action Items -1. [ ] Define and generate the Rust-owned render-scene contract. -2. [ ] Add independent Rust Focus and Agent Session projectors with focused tests. -3. [ ] Add the read-only scene command and refresh it on source, settings, and DisplaySpace changes. -4. [ ] Cut the webview over to generated scene values and delete TypeScript source projections. -5. [ ] Move region layout and physical Pig policy to Rust; retain only frame mechanics and assets +Implemented in [PR #88](https://github.com/killallgit/adhd-ranch/pull/88); validation is recorded in +[the feature tasks](../../specs/001-render-domain-seam/tasks.md#phase-7-convergence). + +1. [x] Define and generate the Rust-owned render-scene contract. +2. [x] Add independent Rust Focus and Agent Session projectors with focused tests. +3. [x] Add the read-only scene command and refresh it on source, settings, and DisplaySpace changes. +4. [x] Cut the webview over to generated scene values and delete TypeScript source projections. +5. [x] Move region layout and physical Pig policy to Rust; retain only frame mechanics and assets in TypeScript. 6. [ ] Revisit backend-owned movement only through a separately measured Animal Runtime design. diff --git a/docs/adr/0004-local-claude-session-archive.md b/docs/adr/0004-local-claude-session-archive.md new file mode 100644 index 0000000..0af4137 --- /dev/null +++ b/docs/adr/0004-local-claude-session-archive.md @@ -0,0 +1,189 @@ +# ADR-0004: Archive Claude session records locally without making history live state + +**Status:** Accepted +**Date:** 2026-09-28 +**Accepted:** 2026-09-28 +**Deciders:** Ryan (project owner) + +## Context + +Ranch currently consumes five Claude Code lifecycle hooks, reduces each payload to the fields +needed for an in-memory `AgentSession`, and intentionally forgets both the payload and session when +the process ends. ADR-0002 accepted a stronger hook-state transport and rejected its Option C, +"Hooks become a doorbell; the transcript is the truth," because the renderer needed only live +Activity and reading a private transcript would expose prompts and tool output for no corresponding +product value. + +The product direction has changed. Ranch now needs a durable, Claude-specific data foundation that +preserves the structures Claude writes for a session. The database is intended to support later +session features; it is not a reason to make historical rows decide whether an Animal is alive. +Claude's current hook contract already supplies `session_id`, `prompt_id`, `transcript_path`, `cwd`, +and `hook_event_name`; `SubagentStop` additionally supplies `agent_id` and +`agent_transcript_path`. It warns that transcript writes are asynchronous and may lag the hook. +Claude's transcript schema is private and changes between releases. + +The same feature introduces the first Ranch database and renames the default application-data root +from `.adhd-ranch` to `.adhd`. Focus Markdown and timer sidecars remain canonical user-owned state; +only Claude archive data moves into the database in this decision. + +This ADR supersedes ADR-0002 only where that ADR rejects transcript ingestion. ADR-0002's accepted +push transport, bounded silent hook client, and in-memory live-state reducer remain authoritative. + +## Decision + +Use one embedded, local Turso database at `/ranch.db` and make raw Claude records the +archive's data-fidelity boundary. This describes schema-drift preservation, not a promise of +backward-compatible prototype wire or database schemas. + +1. Ranch's default data root becomes `~/.adhd` on Unix and `adhd` under the Windows application-data + directory. An explicit `ADHD_RANCH_HOME` remains unchanged. Startup atomically renames the legacy + default root only when the new root does not exist; it never auto-merges two roots. +2. `ranch.db` uses `turso` 0.8.0-pre.14 in local-only mode with default and sync features disabled. + The workspace Rust baseline rises to 1.90 to match the resolved dependency floor. Ordered + migrations have explicit transaction bounds and every writer connection verifies foreign keys. + A clean-shutdown/checkpoint plus SQLite reopen, integrity, and read test proves the engine escape + path instead of assuming file compatibility alone makes rollback safe. +3. Every Claude Hook Firing successfully admitted to the bounded archive queue is stored as an + immutable raw receipt with extracted common lookup fields and a digest. Duplicate deliveries + remain separate receipts; rejected admissions increment a content-free dropped-job counter. +4. A Hook Firing is also a synchronization hint. Ranch incrementally reads newly completed records + from validated `transcript_path` and `agent_transcript_path` values, stores each source line + byte-for-byte, and extracts only a small stable index. `SubagentStop` uses an archive-only verb + and never changes parent Activity. Unknown or malformed complete records are retained rather + than discarded. +5. The archive records a cursor and file-generation fingerprint. Repeated reads are idempotent; + truncation or replacement starts a new generation instead of mutating old records. +6. Archive I/O is a storage adapter behind the hook boundary. The dependency-light hook client does + not open the database or transcript. A Ranch-owned Tokio single-consumer task serializes database + writes and transcript reads so the socket listener and Claude process keep their existing bounded + behavior. Every hint receives bounded delayed retries, with terminal hooks settling on two + unchanged observations so asynchronous final rows do not require another hook. +7. The in-memory `LiveSessions` reducer remains the sole authority for present Agent Sessions and + Activity. Startup does not reconstruct live Animals from `ranch.db`. +8. Archival is local-only, defaults off for users who have not explicitly opted in, and is disclosed + as a plaintext copy of data that can include prompts, code, tool output, and secrets. Turning it + off stops new writes without deleting existing rows. +9. Claude's trusted config root resolves from explicit Ranch settings, then the app-inherited + `CLAUDE_CONFIG_DIR`, then the platform default. Hook paths cannot widen that root. +10. The first slice ingests only hook-observed sessions while Ranch is running. It does not crawl + historical Claude projects, add browsing/search UI, sync to a cloud service, ingest Codex, or + move Focus persistence into SQL. + +## Options Considered + +### Option A: Keep Claude state in memory only + +| Dimension | Assessment | +|-----------|------------| +| Complexity | Low | +| Schema-drift risk | None | +| Supports durable Claude features | No | +| Privacy change | None | +| Reversibility | N/A | + +**Pros:** preserves all current boundaries and stores no additional sensitive content. +**Cons:** cannot satisfy the requested durable Claude-data foundation and loses all evidence at app +exit. + +### Option B: Make a typed transcript crate the canonical model + +| Dimension | Assessment | +|-----------|------------| +| Complexity | Medium initially, high during drift | +| Schema-drift risk | High | +| Query ergonomics | High for known variants | +| Fidelity | Incomplete for unknown variants | +| Reversibility | Medium | + +**Pros:** provides rich Rust types immediately. The `claude-code-transcripts` crate is broad and +includes a round-trip checker; `claude-session-parser` provides higher-level chat and usage views. +**Cons:** Claude's schema is not stable. The current `claude-code-transcripts` release maps unknown +entry variants to a payload-free `Unknown`, its known structs do not retain unknown fields, and a +current local transcript already contains a `cost-state` type absent from that release. A typed enum +therefore cannot be the only stored copy. + +### Option C: Preserve raw records in Turso and derive narrow indexes (chosen) + +| Dimension | Assessment | +|-----------|------------| +| Complexity | Medium | +| Schema-drift risk | Low at the storage boundary | +| Query ergonomics | Medium; indexed envelope fields now, projections later | +| Fidelity | Byte-preserving | +| Reversibility | High after the cross-engine reopen/integrity test passes | + +**Pros:** unknown Claude data survives; known fields remain queryable; typed libraries may be added +or replaced without migrating the authoritative payload; live Agent behavior stays independent. +**Cons:** duplicates sensitive plaintext already held by Claude, needs cursor/generation logic, and +defers fully normalized queries until a consumer justifies them. + +### Option D: Copy transcript files wholesale and scan or backfill `~/.claude/projects` + +| Dimension | Assessment | +|-----------|------------| +| Complexity | Medium | +| Coverage | High, including sessions Ranch never observed | +| Coupling to Claude layout | High | +| Incremental query support | Low | +| Privacy blast radius | Highest | + +**Pros:** simplest path to a complete historical corpus. +**Cons:** reads sessions without a Hook Firing or explicit per-feature need, couples Ranch to +Claude's project-directory naming, duplicates whole files before any consumer exists, and exceeds +the requested first slice. + +## Trade-off Analysis + +The durable boundary is the decisive choice. Claude's JSONL records are rich enough that a full +normalized schema would become a second implementation of Claude Code. Raw bytes plus stable +indexes preserve what arrived and delay semantic commitments until Ranch has a feature that needs +them. This is a deeper storage module than a thin repository: it owns migration, incremental file +tailing, generation detection, idempotency, path validation, and privacy-safe diagnostics. + +Using the pre-1.0 `turso` Rust crate introduces dependency and platform risk. Local-only mode avoids +credentials and an HTTP/TLS runtime client, while a tested SQLite escape and an adapter-owned API +contain that risk. Current dependency resolution requires Rust 1.90, so the first slice updates the +workspace's stale 1.77 declaration and must pass all packaged-platform compile gates; otherwise the +decision returns for review rather than pinning transitive dependencies or silently switching +engines. + +The privacy cost is real: Ranch creates another plaintext copy of conversations that may contain +secrets. Explicit opt-in, user-only file permissions, no network features, clear disclosure, and a +separate archive preference are requirements, not follow-up polish. + +## Consequences + +**Easier** + +- Later Claude session features can query one stable local source rather than repeatedly parsing a + private directory layout. +- New Claude record variants survive upgrades even before Ranch understands them. +- Transcript ingestion can be replayed and tested independently from the renderer. +- A future typed projection or full-text index can be rebuilt from raw authoritative records. + +**Harder** + +- Startup now owns a user-data directory migration and a database migration lifecycle. +- Hook processing gains a background worker, failure diagnostics, and transcript generation logic. +- Ranch duplicates sensitive plaintext and must treat archive permissions, disclosure, and future + deletion/retention as product responsibilities. +- The Turso dependency is pre-1.0 and must be isolated behind the storage boundary. + +**To revisit** + +- User-controlled retention, deletion, and export. +- Historical backfill and recovery for Hook Firings missed while Ranch was stopped. +- Which typed Claude projections earn normalized tables or full-text indexes. +- Whether the same raw-record archive boundary generalizes to Codex without leaking Claude + vocabulary into the harness-neutral Agent Session domain. + +## Action Items + +1. [x] Accept this ADR before implementation begins. +2. [ ] Raise the workspace Rust baseline to 1.90 and prove pinned local-only `turso` on all + packaged targets. +3. [ ] Deliver the `.adhd` migration and empty `ranch.db` initialization as one rollback-safe slice. +4. [ ] Deliver raw Hook Receipt persistence and transcript cursoring with fixture proof. +5. [ ] Add explicit archive opt-in and plaintext-data disclosure without changing Agent display + semantics. +6. [ ] Update README and current architecture/storage documentation in the data-root slice. diff --git a/docs/architecture.md b/docs/architecture.md index 4c9157d..761e390 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,28 +103,28 @@ layout, and physical policy; TypeScript owns synchronous frame mechanics and pre ## Core interaction loop 1. **Animals roam the screen.** One generated Animal per visible Focus or enabled Agent Session. The Rust Pig profile supplies the current 60px/s speed, 3–8 s turns, friction, minimum-speed floor, footprint, toss cap, and frame cadence. `PigSprite` retains the 4-direction pixel-art presentation (016). Hit-box is 16px larger than the sampled sprite size (018). -2. **Click a pig.** Pig freezes. `AnimalDetail` card opens near the pig: editable Focus title, duplicate and delete buttons, scrollable Task list (check off, edit text, `✗` to clear), and an "Add task…" input at the bottom. Clock/time controls on the Focus title and each Task open compact timer dropdowns. Click-outside or Escape closes; pig resumes (019, 052). -3. **Drag a pig.** Click-and-hold then move > 4px enters drag mode — pig follows cursor. Release sends pig flying in that direction; friction decelerates it; bounces at region edges. Pure click (< 4px movement) still opens AnimalDetail (020). -4. **Clear a task.** Tap `✗` → `delete_task` Tauri command → markdown updated → pig's task list reflects change. +2. **Click a Focus Animal.** It freezes. `AnimalDetail` opens near it: editable Focus title, duplicate and delete buttons, scrollable Task list (Complete, edit text, Delete), and an "Add task…" input at the bottom. Clock/time controls on the Focus title and each Task open compact timer dropdowns. Click-outside or Escape closes; the Animal resumes (019, 052). An Agent Session Animal is not selectable. +3. **Drag an Animal.** Click-and-hold then move > 4px enters drag mode — the Animal follows the cursor. Release sends it flying in that direction; friction decelerates it; bounces at region edges. Pure click (< 4px movement) on a Focus Animal still opens AnimalDetail (020). +4. **Delete a Task.** Tap `✗` → `delete_task` Tauri command → markdown updated → the Animal's Task list reflects the change. 5. **Add a task.** Type in "Add task…" input in AnimalDetail → Enter → `append_task` Tauri command → markdown updated. -6. **Create a Focus.** *(014)* Tray → "+ New Focus" → small webview form → `create_focus` → new pig spawns. Timer dropdown (No timer / 2m / 4m / 8m / 16m / 32m / Custom) optionally attaches a `FocusTimer` (028). Focus and Task timers can later be started or cleared from `AnimalDetail` (052). -7. **Delete a Focus.** *(015, 027)* Tray → Focus submenu → "Delete…", or the delete button in `AnimalDetail` → `delete_focus` → pig disappears. Asks for confirmation when `widget.confirm_delete` is on. +6. **Create a Focus.** *(014, #89)* Tray → "+ New Focus" → small webview form → `create_focus` → a new Animal appears. The form offers None, built-in 10/30/60 minute chips, and saved custom durations. Focus and Task Timers can later be started, restarted, or cleared from `AnimalDetail`. Custom chips persist in `settings.yaml` under `timers.saved_minutes`; `edit_saved_timer_minutes` applies add/remove/clear operations to current settings in one synchronous command. Ordinary preference updates preserve those saved durations. Removing a chip does not clear a running Timer. +7. **Delete a Focus.** *(015, 027)* Tray → Focus submenu → "Delete…", or the delete button in `AnimalDetail` → `delete_focus` → the Animal disappears. Asks for confirmation when `widget.confirm_delete` is on. 8. **Configure displays.** *(017, 049)* Preferences → Displays — check/uncheck monitors. Enabled monitors share one spanning overlay window; Animals spawn in the primary display region and move only inside normalized visible monitor regions. Persists in `settings.yaml`. The display module owns monitor geometry, and React owns movement over the emitted DisplaySpace model. -9. **Change settings.** *(026, 032, 050)* Tray → "Settings…" or app menu → "Preferences…" opens the Preferences window. `update_settings` runs the settings workflow: persist `settings.yaml`, commit the in-memory settings, apply widget changes, reapply overlays when displays changed, refresh long-lived settings consumers, and rebuild the tray. Caps and notification toggles take effect without a restart. +9. **Change settings.** *(026, 032, 050)* Tray → "Settings…" or app menu → "Preferences…" opens the Preferences window. Preferences is the macOS menu label for the window that edits Settings. `update_settings` runs the settings workflow: persist `settings.yaml`, commit the in-memory settings, apply widget changes, reapply overlays when displays changed, refresh long-lived settings consumers, and rebuild the tray. Limits and notification toggles take effect without a restart. ## Application Single Tauri v2 desktop app written in Rust (core + frontend webview). macOS is the primary target; the release workflow also builds unsigned Windows and Linux packages. Surfaces: 1. **Transparent overlay window** — spans the enabled displays, always-on-top, no decorations. Renders pixel pig sprites via React. Click-through for non-pig areas via a Rust polling thread (Tauri `cursor_position()` every 16ms) that toggles `window.set_ignore_cursor_events`. -2. **Tray menu** — Gather Pigs, "Agents as Animals", "Install Hooks…", "+ New Focus", one submenu per Focus (with Delete), an Expired submenu, Settings…, and Quit (plus Open Overlay DevTools in debug builds). The tray icon turns red when over-cap. +2. **Tray menu** — Gather, "Agents as Animals", "Install Hooks…", "+ New Focus", one submenu per Focus (with Delete), an Expired submenu, Settings…, and Quit (plus Open Overlay DevTools in debug builds). The tray icon turns red when the ranch is Over Limit. The menu label is still "Gather Pigs" because Pig is the only Species. 3. **New Focus, Preferences, and Install Hooks windows** — small webviews opened from the tray or app menu. Install Hooks has an explicit user-scoped install button and copyable shell commands as a fallback. 4. **Agent Hooks window** — an always-on-top webview opened from Window → "Agent Hooks…"; shows the agent hook wiring, the live Agent Sessions, and recent hook firings. Responsibilities owned by the app: - Read/write per-Focus markdown files (frontmatter + body). -- Watch `~/.adhd-ranch/focuses/` via `notify` crate; reflect external edits live (pig count updates within 1s). +- Watch `~/.adhd-ranch/focuses/` via `notify` crate; reflect external edits live (the Animal count updates within 1s). - Run a 1s timer-expiry loop (`Timers::expire_due`) that persists expired timers and sends notifications. The UI picks up the change through the focuses watcher. - Enforce caps + emit overload alerts (`tauri-plugin-notification`). - Poll mouse position in a background thread; maintain shared pig bounding boxes; toggle click-through. @@ -136,18 +136,18 @@ No network API or Ranch CLI. The UI reaches Rust only through Tauri IPC. Rust in 1. **User** — pig detail UI, Preferences UI, tray/new-focus UI, or hand-edit markdown. 2. **Timer expiry loop** — marks timers `Expired`. -## Caps & overload alerting +## Limits -Hard limits: +Soft thresholds. The settings file still uses the key `caps`. - `MAX_FOCUSES` (default: 5) - `MAX_TASKS_PER_FOCUS` (default: 7) -App enforces caps at write time. When a write would exceed a cap, it succeeds but flips an over-cap flag; the tray icon turns red; system notification fires once per `under → over` transition. Goes away on transition back to under. +The app enforces Limits at write time. When a write would pass a Limit, it succeeds and the ranch is Over Limit; the tray icon turns red; a system notification fires once per `under → over` transition. The warning goes away on the transition back under. Agent Sessions do not count. ## Agents as Animals -An opt-in overlay mode that draws one Animal per running Claude Code session alongside the Focus pigs. It is off by default and controlled by `agents.enabled` in `settings.yaml`. +An opt-in overlay mode that draws one Animal per running Claude Code session alongside the Focus Animals. It is off by default and controlled by `agents.enabled` in `settings.yaml`. Pig is still the Species for both. - **Toggle.** The tray's "Agents as Animals" check item flips `agents.enabled` through the settings workflow (persist, commit, effects, tray rebuild). Turning it off clears live sessions and ignores subsequent Hook Firings; the Claude plugin remains installed. Turning it on opens the Install Hooks dialog when Claude does not list a complete, enabled user-scoped Ranch plugin. A failed status read is logged rather than treated as proof of absence; the toggle never repairs the plugin. - **Hook install.** Claude Code owns the user-scoped `adhd-ranch-hooks@adhd-ranch` plugin. Ranch never registers or removes direct Claude settings hooks on startup or toggle. The marketplace lives in this repository at `.claude-plugin/marketplace.json`; the plugin lives under `plugins/adhd-ranch-hooks/`. The tray's "Install Hooks…" dialog explicitly invokes Claude's CLI: add the marketplace if missing, install or enable the plugin at user scope, then validate the installed manifest, exact five event-to-action mappings, wrapper path/content/executable bit, and Claude's strict plugin schema. A complete existing install is untouched. An incomplete install is repaired only after this explicit click: refresh the marketplace and update the plugin, with a user-scoped reinstall if updating cannot repair the cache. The separate `claude_plugin` module owns this lifecycle; the dialog also shows fresh-shell commands for a first-time install. The plugin has an explicit version, which must be bumped for a new marketplace release; Claude's strict validator warns on an unversioned manifest. Existing Claude sessions need `/reload-plugins` or a restart. Plugin `hooks/hooks.json` runs a wrapper under `${CLAUDE_PLUGIN_ROOT}`; the wrapper finds Ranch's data root and invokes the stable local client there. @@ -191,5 +191,5 @@ Settings changed through the app are persisted and applied immediately. Manual f ## Scope -- **Current**: User creates Focuses from the app or by hand-editing. Pigs roam the overlay, show Tasks, and reflect markdown changes. Focus and Task timers, caps, and multi-display overlay work. Optional agent pigs for running Claude Code sessions. +- **Current**: The person creates Focuses from the app or by hand-editing. Animals roam the overlay. A Focus Animal shows Tasks and reflects markdown changes. Focus and Task Timers, Limits, and the multi-display overlay work. Optional Agent Session Animals for running Claude Code sessions. Pig is the only Species. - **Not built**: external aggregators (Jira, GitHub), sync, schema migrations. diff --git a/docs/research/claude-codex-session-terminology.md b/docs/research/claude-codex-session-terminology.md index 5fe1bfe..e8ff412 100644 --- a/docs/research/claude-codex-session-terminology.md +++ b/docs/research/claude-codex-session-terminology.md @@ -1,5 +1,7 @@ # Claude Code and Codex session terminology +> **Historical.** This note is evidence. It is not a current requirement and not an accepted decision. The constitution, accepted ADRs, and the current product specification govern where they disagree with it. See [specs/002-speckit-docs-pass/pass-record.md](../../specs/002-speckit-docs-pass/pass-record.md). + This is a glossary of how Claude Code and OpenAI Codex name their own session concepts. Its purpose is to let adhd-ranch reuse each tool's terms when it starts tracking sessions from them. It records findings only and makes no recommendation. Sources and versions, checked 2026-09-14: diff --git a/docs/research/manual-github-release-retention.md b/docs/research/manual-github-release-retention.md index af6231d..c557209 100644 --- a/docs/research/manual-github-release-retention.md +++ b/docs/research/manual-github-release-retention.md @@ -1,5 +1,7 @@ # Manual GitHub release and artifact retention +> **Historical.** This note is evidence. It is not a current requirement and not an accepted decision. The constitution, accepted ADRs, and the current product specification govern where they disagree with it. See [specs/002-speckit-docs-pass/pass-record.md](../../specs/002-speckit-docs-pass/pass-record.md). + ## Recommendation Use one manually dispatched workflow for the complete release transaction: diff --git a/docs/research/serena-multi-agent.md b/docs/research/serena-multi-agent.md index 8731005..0449258 100644 --- a/docs/research/serena-multi-agent.md +++ b/docs/research/serena-multi-agent.md @@ -1,5 +1,7 @@ # Serena across multiple agents and worktrees +> **Historical.** This note is evidence. It is not a current requirement and not an accepted decision. The constitution, accepted ADRs, and the current product specification govern where they disagree with it. See [specs/002-speckit-docs-pass/pass-record.md](../../specs/002-speckit-docs-pass/pass-record.md). + How to configure the Serena MCP server for this repo, and what breaks when agents run in git worktrees. Written after testing the failure directly; the negative results are recorded so nobody repeats them. Sources and versions, checked 2026-09-21: diff --git a/issues/031-notification-source-settings.md b/issues/031-notification-source-settings.md index 38ba86e..08b6fb5 100644 --- a/issues/031-notification-source-settings.md +++ b/issues/031-notification-source-settings.md @@ -1,8 +1,8 @@ # 031 — Notification source settings registry -## Parent PRD +## Owning specification -PRD.md §FR6 (configuration) +`specs/003-ranch-today/spec.md` — FR-008 ## What to build diff --git a/issues/051-ranch-animal-vocabulary-seam.md b/issues/051-ranch-animal-vocabulary-seam.md index 67eff77..7327b38 100644 --- a/issues/051-ranch-animal-vocabulary-seam.md +++ b/issues/051-ranch-animal-vocabulary-seam.md @@ -1,87 +1,39 @@ -# 051 — Animal vocabulary for the movement layer +# 051 — Animal vocabulary for the remaining hit-test adapter -## Parent PRD +## Owning specification -PRD.md §FR3 (Pig UI), the post-030 decision that timer-growth behavior is animal-neutral, and -ADR-0001, which settles **Animal** as a render-layer word. +`specs/003-ranch-today/spec.md` — FR-004; `specs/001-render-domain-seam/spec.md` — FR-013 ## What to build -Give the movement layer one vocabulary — Animal — without changing user-visible behavior. +The Rust-owned render scene and generic Animal movement shipped in PR #88. This issue now covers +only the remaining TypeScript hit-test adapter names: `PigHitRect` in `src/types/pig.ts`, the +shared wrappers in `src/api/pig.ts`, and their callers in `src/hooks/useAnimalMovement.ts`. +These values describe any Animal, not Pig-specific assets or physical policy. -### Why this issue changed - -The original 051 proposed these renames while CONTEXT.md still defined **Animal** as *"either a -Focus or an Agent Session."* Under that definition the renames would have stamped a domain union -across the one layer that is genuinely shared, teaching every future reader that the movement -layer traffics in domain objects. - -ADR-0001 fixes the definition rather than the rename. **Animal** now means the sprite the ranch -draws and moves; Focus and Agent Session each project their own. Under that definition these -renames are not merely safe, they are the point: `useAnimalMovement` moving Animals is exactly -what that layer does. - -Two things follow. The `Pig*` renames are unchanged from the original issue. But the scope was -too small — the movement layer carries **three** vocabularies today, not two. - -### The third vocabulary - -`lib/ranchAnimalMovement.ts` already speaks `RanchAnimalState`, `RanchAnimalDirection`, -`RanchAnimalInput`, `advanceRanchAnimal` and `restRanchAnimal`, while `hooks/usePigMovement.ts` -speaks `PigState`, `PigDirection` and `PigHitRect`, and both handle projected `Animal`s. CONTEXT.md -has listed `RanchAnimal` as a term to avoid the whole time. The original issue did not mention it. - -### Target shape - -- Rename the `Pig*` surface: `PIG_SIZE`, `PIG_SPEED`, `PigState`, `PigDirection`, `PigHitRect`, - `usePigMovement`, `types/pig.ts` and the `api/pig.ts` client. -- Rename the `RanchAnimal*` surface: `RanchAnimalState`, `RanchAnimalDirection`, - `RanchAnimalInput`, `advanceRanchAnimal`, `restRanchAnimal`, `lib/ranchAnimalMovement.ts`. -- Keep `PigSprite` and the pig sprite sheet. Those are the concrete Species asset and stay - pig-specific until a second Species exists. -- The movement layer must name no domain type. After 057 it takes Animals and regions; this - slice keeps it that way. -- Existing Tauri command names are either intentionally retained for compatibility or migrated - with wrappers. -- Do not change storage format, Focus ids, tray labels, or user-visible copy. - -### Out of scope - -- Adding a second Species. -- The render contract and the deletion of the `Animal` union (057). -- Moving selection into the Focus half (058). -- Replacing the current pig sprite sheet. -- Rewriting historical issue files that correctly described pig-only behavior at the time. +Rename those shared TypeScript types, modules, and wrappers to Animal vocabulary. Keep the +`update_pig_rects`, `set_pig_drag_active`, and `gather-pigs` IPC names as compatibility contracts, +as spec 001 permits. Keep `PigSprite`, its assets, and the Rust Pig profile species-specific. +Do not repeat the scene, projection, region, or selection cutover from PR #88. ## Completion promise -The movement layer speaks one vocabulary and names no domain type, while the concrete pig asset -stays pig-specific until a second Species exists. +The shared TypeScript hit-test adapter uses Animal vocabulary while existing IPC contracts and +visible behavior remain unchanged. ## Acceptance criteria -- [ ] Movement state, direction, hit-rect and input types carry Animal names; no `Pig*` and no - `RanchAnimal*` names remain in animal-neutral code -- [ ] No file in the movement layer imports or names `Focus`, `AgentSession`, `Timer` or `Pen` -- [ ] `PigSprite` and the sprite sheet keep their pig-specific names -- [ ] Current pig rendering, detail behavior, drag/toss, timer growth and tray behavior are - unchanged -- [ ] Existing public Tauri command names are either intentionally retained for compatibility or - migrated with compatibility wrappers -- [ ] Tests cover the renamed helpers or aliases -- [ ] `task check` green +- [ ] Shared hit-rectangle types and adapter wrappers use Animal names; the generic movement hook + no longer imports `PigHitRect` or Pig-named TypeScript wrappers +- [ ] Existing IPC command/event names remain unchanged +- [ ] Pig assets and the Rust Pig profile retain their species-specific names +- [ ] Hit-testing, selection, Gather, dragging, and tossing retain their current behavior +- [ ] Existing regression tests and `task check` pass ## Blocked by -057 — the render contract from ADR-0001 action item 3, not yet filed. - -Renaming first would churn the same files twice: 057 changes what the movement layer *takes*, -this changes what it is *called*. The original "blocked by 055" is resolved — 055 shipped and -`PigSubject` is gone. +None. The renderer contract and Focus-only selection shipped in PR #88. ## User stories addressed -- "When we add a second Species, the movement layer already speaks in Animal terms instead of - assuming every Animal is forever a pig." -- "When I read the movement layer, nothing in it tells me whether a Focus or an agent put that - Animal there." +- "When I read the movement adapter, its type names describe any Animal rather than a Pig." diff --git a/issues/056-task-timer-binding.md b/issues/056-task-timer-binding.md index 2b24fcf..b0d1a0b 100644 --- a/issues/056-task-timer-binding.md +++ b/issues/056-task-timer-binding.md @@ -1,8 +1,8 @@ # 056 — Task Timers drift when Tasks are hand-edited -## Parent PRD +## Owning specification -PRD.md §FR3 (Task timers), issues 052 and 053. Raised while designing 054. +`specs/004-task-timer-hand-edits/spec.md` ## What to build diff --git a/issues/059-self-describing-hook-frame.md b/issues/059-self-describing-hook-frame.md index a7edb4d..784f840 100644 --- a/issues/059-self-describing-hook-frame.md +++ b/issues/059-self-describing-hook-frame.md @@ -1,9 +1,8 @@ # 059 — A hook frame that describes a state at a time -## Parent PRD +## Owning specification -PRD.md §FR3 (Pig UI) and §Phase 7, and ADR-0002, which decides that a frame carries a claim about -a state rather than announcing an edge. +`specs/005-late-hook-frame/spec.md` ## What to build diff --git a/issues/060-session-staleness-sweep.md b/issues/060-session-staleness-sweep.md index 3e673b9..ed54738 100644 --- a/issues/060-session-staleness-sweep.md +++ b/issues/060-session-staleness-sweep.md @@ -1,9 +1,8 @@ # 060 — A session that stops speaking stops working -## Parent PRD +## Owning specification -PRD.md §FR3 (Pig UI) and §Phase 7, and ADR-0002's second slice: the store gets a way to notice -what it has lost. +`specs/006-unheard-turn-ends/spec.md` ## What to build diff --git a/issues/061-hook-change-events.md b/issues/061-hook-change-events.md index 2e22e7a..4962084 100644 --- a/issues/061-hook-change-events.md +++ b/issues/061-hook-change-events.md @@ -1,8 +1,8 @@ # 061 — The change event carries the change -## Parent PRD +## Owning specification -PRD.md §FR3 (Pig UI) and §Phase 7, and ADR-0002's third slice. +`specs/003-ranch-today/spec.md` — FR-014, under ADR-0002 ## What to build diff --git a/issues/062-stable-hook-client-path.md b/issues/062-stable-hook-client-path.md index 621ace3..bdb112f 100644 --- a/issues/062-stable-hook-client-path.md +++ b/issues/062-stable-hook-client-path.md @@ -1,9 +1,8 @@ # 062 — One hook client path, and reclaim the orphans -## Parent PRD +## Owning specification -PRD.md §FR6 (Configuration) and §Phase 7, and ADR-0002's fourth action item — the only one with a -live bug attached rather than a design change. +`specs/007-one-hook-delivery/spec.md` ## What to build diff --git a/issues/README.md b/issues/README.md index 447d46e..0728c61 100644 --- a/issues/README.md +++ b/issues/README.md @@ -11,9 +11,7 @@ Each issue is a self-contained vertical slice that one person or coding agent ca These are not required before 031. Pick one when we choose to spend a slice on internal seams or future-proofing. - [056](056-task-timer-binding.md) — Task Timers drift when Tasks are hand-edited -- [051](051-ranch-animal-vocabulary-seam.md) — Animal vocabulary for the movement layer (blocked by 057, per ADR-0001) -- [057](057-animal-render-contract.md) — Animal as a render contract (ADR-0001; unblocks 051 and 058) -- [058](058-selection-belongs-to-focus.md) — Selection belongs to the Focus half (blocked by 057) +- [051](051-ranch-animal-vocabulary-seam.md) — Animal vocabulary for the movement layer (render contract shipped; `Pig*` names remain) - [059](059-self-describing-hook-frame.md) — A hook frame that describes a state at a time (ADR-0002; unblocks 060 and 061) - [060](060-session-staleness-sweep.md) — A session that stops speaking stops working (blocked by 059) - [061](061-hook-change-events.md) — The change event carries the change (blocked by 059) @@ -27,7 +25,6 @@ Closed without implementation: - 042 — Unify cap-state behind a single `CapStatus` projection. Premise was wrong: both consumers already read the same `cap_state` projection. - 045 — Symmetric `fixtureReader` + caps fixture parity. Helper too thin to warrant abstraction; test-wrapper deletion folded into 039. -- 046 — Timer expiry workflow module. Superseded by 053, which moved the workflow into `crates/commands`. - 047 — Storage transaction seam for Proposal lifecycle. The Proposal queue and HTTP API were removed. ### Icebox (deferred) @@ -84,7 +81,7 @@ If any box can't be ticked, the issue is **not** done. Flag the human; don't sil ## Issue file shape ``` -## Parent PRD +## Owning specification ## What to build ## Completion promise ← single sentence, observable, non-negotiable ## Acceptance criteria ← checkboxes that prove the promise diff --git a/issues/done/024-display-subsystem-agent-prompt.md b/issues/done/024-display-subsystem-agent-prompt.md deleted file mode 100644 index 275d531..0000000 --- a/issues/done/024-display-subsystem-agent-prompt.md +++ /dev/null @@ -1,132 +0,0 @@ -# Agent prompt — pick up issue 024 - -You are implementing issue **024 — Display subsystem: coordinate bugs + module refactor** in the `adhd-ranch` Tauri desktop app at the repository root. - ---- - -## Your job - -Replace the broken `app/overlay_manager.rs` + `app/pig_hittest.rs` with a clean `display/` module tree that fixes multi-monitor coordinate bugs. The spec is in `issues/024-display-subsystem.md` — read it first. The workflow rules are in `issues/README.md`. Programming rules are in `CLAUDE.md`. All must be followed. - ---- - -## Context you need - -### Why this exists - -Multi-monitor spanning has never worked. Root cause: `overlay_manager::apply` mixes **logical positions** (macOS reports `Monitor::position()` in points) with **physical sizes** (`Monitor::size()` in raw pixels). At 2× DPR, `position.x = 1920` (logical) + `size.width = 3840` (physical) = `5760` — a nonsense value. The window is smaller than the actual display span and positioned inside it, so pigs hit a false barrier in the middle and walk off the true outer edges. The hit-test polling thread has the same mismatch. A 270°-rotated portrait monitor is also not handled. - -### Current code map - -Read these files before touching anything: - -| File | What it does | -|---|---| -| `src-tauri/src/app/overlay_manager.rs` | Window creation, bounding-box calc, hit-test thread — all in one file. **Delete this.** | -| `src-tauri/src/app/pig_hittest.rs` | `PigHitTester` struct + `is_hit`. **Move to `display/hit_test.rs`.** | -| `src-tauri/src/app/mod.rs` | Composition root. Enumerates monitors, wires state. Update imports only. | -| `src-tauri/src/app/tray.rs` | Builds display submenu. Uses `MonitorInfo` name field. Update to use `LogicalMonitor.label`. | -| `src-tauri/src/ui_bridge/mod.rs` | `PigHitState` + `update_pig_rects` command. **Do not touch.** | -| `crates/domain/src/` | `DisplayConfig`, `PigRect`, `RectUpdater` trait. **Do not touch.** | - -### New module tree to create - -```text -src-tauri/src/display/ - mod.rs — DisplayManager (public surface; replaces OverlayManager; impl RectUpdater) - monitor.rs — pure types + math: LogicalMonitor, compute_span, disambiguate_names - overlay.rs — window lifecycle: create, resize, show, destroy - hit_test.rs — PigHitTester + polling thread (move from app/pig_hittest.rs) -``` - -Add `mod display;` in `src-tauri/src/lib.rs` or `main.rs`. - -### The coordinate fix (critical) - -`LogicalMonitor::from_tauri` must divide physical values by `scale_factor`: - -```rust -pub fn from_tauri(index: usize, m: &tauri::Monitor) -> Self { - let sf = m.scale_factor(); - Self { - index, - label: m.name().unwrap_or_default().to_string(), - scale_factor: sf, - position: (m.position().x as f64 / sf, m.position().y as f64 / sf), - size: (m.size().width as f64 / sf, m.size().height as f64 / sf), - } -} -``` - -`compute_span` works entirely in logical space and returns `SpanBounds { x, y, width, height }` (all `f64` logical). - -Window calls use `LogicalSize` / `LogicalPosition` so Tauri handles physical conversion internally: - -```rust -window.set_size(tauri::LogicalSize::new(bounds.width, bounds.height))?; -window.set_position(tauri::LogicalPosition::new(bounds.x, bounds.y))?; -``` - -Hit-test thread: `outer_position()` returns physical — divide by `window.scale_factor()` to get logical before subtracting from cursor. OR use `outer_position().to_logical(sf)`. - -### What the DisplayManager must do - -- Same public interface as current `OverlayManager`: - - `apply(app, monitors: &[LogicalMonitor], config: &DisplayConfig)` — creates/resizes spanning window - - `impl RectUpdater` — `update_rects(label, rects)` delegates to `PigHitTester` -- Same Tauri state wrapper: `pub struct DisplayManagerState(pub DisplayManager)` -- In `app/mod.rs`: replace `OverlayManagerState` with `DisplayManagerState`; `MonitorsState` now wraps `Vec` - ---- - -## TDD — write tests first for pure logic - -Tests go in `src-tauri/src/display/monitor.rs` (inline `#[cfg(test)]` module). Write RED test, then implement GREEN, repeat. - -Required test cases for `compute_span`: - -1. Single landscape monitor at origin → bounds equal monitor bounds -2. Two landscape monitors side-by-side → width = sum, x = leftmost x -3. Monitor at negative x (secondary left of primary) → min_x is negative, total width correct -4. Portrait monitor (height > width, as from a 270° rotation) left of landscape → correct origin and total width - -Required test cases for `disambiguate_names`: - -1. Two monitors with identical names → each gets `" (x, y)"` suffix -2. Monitors with unique names → labels unchanged - ---- - -## Critical constraint - -**Do not mark this done without confirming the app launches at runtime without crashing.** `task check` passing is necessary but not sufficient — Tauri apps can typecheck and still panic on startup. Run `cargo tauri dev` or the equivalent and verify the overlay appears. - ---- - -## Workflow - -```bash -git checkout main && git pull -git checkout -b feat/024-display-subsystem -# implement + tests -task check # must be green -# confirm app launches at runtime -git add && git commit -m "feat: 024 — display/ module tree, logical coordinate fix" -git push -u origin feat/024-display-subsystem -gh pr create --title "feat: 024 — display subsystem refactor + coordinate fix" --body "..." -``` - -PR body must quote the completion promise from the issue file verbatim and link `issues/024-display-subsystem.md`. - ---- - -## Definition of done - -- [ ] `display/` module tree exists; `app/overlay_manager.rs` + `app/pig_hittest.rs` deleted -- [ ] `compute_span` and `disambiguate_names` covered by 6 unit tests (all passing) -- [ ] Both monitors enabled: pigs roam full span, no barrier in the middle, no open edges -- [ ] Portrait/rotated monitor included correctly in the span -- [ ] Monitor names disambiguated in tray -- [ ] Click-through hit-testing works across the full spanning window -- [ ] App launches at runtime without crash -- [ ] `task check` green diff --git a/issues/done/046-timer-expiry-service-extraction.md b/issues/done/046-timer-expiry-service-extraction.md index 6e0f347..25c4a15 100644 --- a/issues/done/046-timer-expiry-service-extraction.md +++ b/issues/done/046-timer-expiry-service-extraction.md @@ -1,6 +1,6 @@ # 046 — Extract timer-expiry workflow out of `app/` -> **Closed — superseded by 053.** `TimerExpiryWorkflow` in `crates/commands/src/timer_expiry.rs` owns tick → persist → notification requests behind an injected `NotificationSink`, with unit tests. `src-tauri/src/app/timer_expiry.rs` runs the 1s loop and adapts the returned events to Tauri emits and platform notifications. The type names differ from the target shape below. +> **Shipped.** The completion promise is true on `main`. The landed approach is `Timers::expire_due` in `crates/commands/src/timers.rs`, with tests, and `src-tauri/src/app/timer_expiry.rs` only starts the one-second loop and adapts notifications. The write-up's `TimerExpiryService` names were not what landed. ## Parent PRD diff --git a/issues/057-animal-render-contract.md b/issues/done/057-animal-render-contract.md similarity index 94% rename from issues/057-animal-render-contract.md rename to issues/done/057-animal-render-contract.md index 88b066f..8be01a5 100644 --- a/issues/057-animal-render-contract.md +++ b/issues/done/057-animal-render-contract.md @@ -1,5 +1,7 @@ # 057 — Animal as a render contract +**Status:** Shipped. The completion promise holds on `main` via the Rust-owned render scene (ADR-0003). The plan below is the frontend-only approach this file originally specified; that approach was not the one that landed. + ## Parent PRD PRD.md §FR3 (Pig UI) and ADR-0001, which moves the seam between the ranch's two halves from the diff --git a/issues/058-selection-belongs-to-focus.md b/issues/done/058-selection-belongs-to-focus.md similarity index 90% rename from issues/058-selection-belongs-to-focus.md rename to issues/done/058-selection-belongs-to-focus.md index c29d02c..9f38717 100644 --- a/issues/058-selection-belongs-to-focus.md +++ b/issues/done/058-selection-belongs-to-focus.md @@ -1,5 +1,7 @@ # 058 — Selection belongs to the Focus half +**Status:** Shipped. The renderer reports clicks and freezes by id through `useAnimalMovement`, and `useFocusSelection` is what decides a click means a Focus. The plan below names `usePigMovement`, which the render-scene slice replaced. + ## Parent PRD PRD.md §FR3 (Pig UI) and ADR-0001. diff --git a/issues/done/README.md b/issues/done/README.md new file mode 100644 index 0000000..3ec8574 --- /dev/null +++ b/issues/done/README.md @@ -0,0 +1,3 @@ +# Finished issues + +> **Historical.** These write-ups record what was asked at the time. They are not current requirements. A file marked **Shipped** had its outcome become true, including when the landed approach differs from the write-up. A file marked **Closed without building** was not built. The active queue is [../README.md](../README.md). diff --git a/issues/icebox/021-all-monitors-default.md b/issues/icebox/021-all-monitors-default.md index 198d559..f5771d2 100644 --- a/issues/icebox/021-all-monitors-default.md +++ b/issues/icebox/021-all-monitors-default.md @@ -1,8 +1,8 @@ # 021 — All monitors enabled by default on first launch -## Parent PRD +## Owning specification -PRD.md §FR2 (overlay window) + Phase 3 polish +None. Deferred. Not a requirement of `specs/003-ranch-today/spec.md`. ## Problem diff --git a/issues/icebox/022-wrangle.md b/issues/icebox/022-wrangle.md index 20a262a..b945073 100644 --- a/issues/icebox/022-wrangle.md +++ b/issues/icebox/022-wrangle.md @@ -1,8 +1,8 @@ # 022 — Wrangle pig + wrangle all -## Parent PRD +## Owning specification -PRD.md §FR3 (pig UI) +None. Deferred. Not a requirement of `specs/003-ranch-today/spec.md`. ## Problem diff --git a/specs/001-render-domain-seam/spec.md b/specs/001-render-domain-seam/spec.md index b47af9f..366aeaa 100644 --- a/specs/001-render-domain-seam/spec.md +++ b/specs/001-render-domain-seam/spec.md @@ -4,7 +4,7 @@ **Created**: 2026-09-26 -**Status**: Approved for planning +**Status**: Implemented — merged in [PR #88](https://github.com/killallgit/adhd-ranch/pull/88) on 2026-09-28 **Input**: User description: "Plan implementation of accepted ADR-0001 so Focuses and Agent Sessions are independent applications that share only the renderer. Preserve an explicit seam for diff --git a/specs/002-speckit-docs-pass/checklists/requirements.md b/specs/002-speckit-docs-pass/checklists/requirements.md new file mode 100644 index 0000000..067732a --- /dev/null +++ b/specs/002-speckit-docs-pass/checklists/requirements.md @@ -0,0 +1,36 @@ +# Specification Quality Checklist: Spec Kit Docs Pass + +**Purpose**: Validate specification completeness and quality before proceeding to planning +**Created**: 2026-10-15 +**Feature**: [spec.md](../spec.md) + +## Content Quality + +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +## Requirement Completeness + +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Success criteria are technology-agnostic (no implementation details) +- [x] All acceptance scenarios are defined +- [x] Edge cases are identified +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +## Feature Readiness + +- [x] All functional requirements have clear acceptance criteria +- [x] User scenarios cover primary flows +- [x] Feature meets measurable outcomes defined in Success Criteria +- [x] No implementation details leak into specification + +## Notes + +- Validation passed on the first pass (2026-10-15). +- Scope defaults are recorded in Assumptions: one current product specification, issues stay the shipping slices, glossary and accepted decisions stay in place, and the old PRD, finished issues, and research notes stay findable but historical. +- No branch was created. Spec Kit branch hooks are not registered in this project. diff --git a/specs/002-speckit-docs-pass/contracts/current-product-spec.md b/specs/002-speckit-docs-pass/contracts/current-product-spec.md new file mode 100644 index 0000000..ce7650e --- /dev/null +++ b/specs/002-speckit-docs-pass/contracts/current-product-spec.md @@ -0,0 +1,45 @@ +# Contract: Current Product Specification + +**Path**: `specs/003-ranch-today/spec.md` + +**Status field**: `Draft` + +This file is the description of what the ranch does today. It uses the Spec Kit specification shape. It is not a phase history and not an implementation plan. + +## Required sections + +1. Title, feature branch `003-ranch-today`, created date, status `Draft`, and a short input line that says this specification converts the product requirements document into the current description. +2. User scenarios for a person using the ranch today. Each scenario is independently readable. Scenarios describe current behavior, not a delivery sequence. +3. Edge cases that are true of the product today. +4. Functional requirements for current capabilities. Each carried-forward requirement ends with a source citation and a check note. +5. Limits and non-goals, as requirements a reader can find without opening `PRD.md`. +6. A sources appendix. The appendix is where citations live so the narrative stays readable. Every carried-forward statement in the body has a matching appendix entry. + +## Citation + +A carried-forward statement uses this form in the appendix: + +```text +- : source `` — checked against `main` on . . +``` + +A statement that is only true as an accepted decision cites the ADR. A statement that is only a constitution rule cites `.specify/memory/constitution.md`. A statement that is no longer true is omitted, not cited as a requirement. + +## Vocabulary + +Use the settled word from `CONTEXT.md`. In particular, the specification says Animal, Species, Motion, Focus, Task, Timer, Limit, Over Limit, Harness, Agent Session, Session Activity, Hook Firing, Pen, Agents as Animals, DisplaySpace, Gather, and Settings. + +Pig is the Species, and the sprite asset stays pig-named. The specification does not call every Animal a pig. Limit is the soft threshold. Gather is the tray action that brings Animals back onto the primary display. Settings is the stored configuration. Preferences appears only as the macOS menu label for the window that edits Settings. + +## Boundaries + +- No "Implementation phases" section. Finished phases are not requirements. +- No capability the product no longer has, including a localhost HTTP API and a proposal queue, as a requirement. +- No deferred work as a requirement. Multi-monitor default-on and wrangle stay out of this file. +- The render-domain outcome is one short capability: Focus and Agent Session each project Animals, the shared renderer does not import either domain, and Pig is the only Species. The record of that work is named as `specs/001-render-domain-seam/spec.md`. That spec's requirements are not copied. +- The glossary is not copied. Accepted ADR text is not copied. The specification may cite both. +- No task list, file-edit plan, or Rust or TypeScript design. + +## Reader test + +A person who opens only this file can list what the ranch does today, what it will not do, and the limits that hold, without `PRD.md`. diff --git a/specs/002-speckit-docs-pass/contracts/pass-record.md b/specs/002-speckit-docs-pass/contracts/pass-record.md new file mode 100644 index 0000000..0cecda5 --- /dev/null +++ b/specs/002-speckit-docs-pass/contracts/pass-record.md @@ -0,0 +1,70 @@ +# Contract: Pass Record + +**Path**: `specs/002-speckit-docs-pass/pass-record.md` + +The pass record is the inventory, the classification, and the unresolved list. It is not a product specification and not an ADR. + +## Required sections + +1. **How to read this.** Four short rules: `PRD.md` was removed after this pass; historical sources that remain are not requirements; the current description is `specs/003-ranch-today/spec.md` and it is Draft; accepted decisions remain in `docs/adr/` and names remain in `CONTEXT.md`. +2. **Inventory.** One row per source required by FR-001. +3. **Issue classification.** One row per issue that was active at the start of the pass, plus one row per icebox issue, plus one row per closed-without-building note. +4. **Unresolved.** Every disagreement that was not corrected. The section exists even when it says there are none. + +## Inventory row + +| Column | Content | +|---|---| +| Source | Path | +| Class | Accepted decision, verified observation, present direction, unresolved assumption, or historical context. A mixed document lists each class it contains | +| Checked | What was compared on `main`, or "not a behavior claim" for a pure historical note | +| Disposition | Kept as authority, carried into `specs/003-ranch-today/spec.md`, marked historical, deleted after carry-forward, left deferred, or listed as unresolved | + +Minimum sources: + +- `PRD.md` +- `issues/README.md` and every issue file under `issues/`, `issues/done/`, and `issues/icebox/` +- `CONTEXT.md` +- `docs/architecture.md` +- `docs/adr/0001-two-apps-over-one-renderer.md` +- `docs/adr/0002-agent-hook-transport.md` +- `docs/adr/0003-rust-owned-render-scene.md` +- `docs/research/serena-multi-agent.md` +- `docs/research/manual-github-release-retention.md` +- `docs/research/claude-codex-session-terminology.md` +- `specs/001-render-domain-seam/spec.md` + +Finished issue files may share one inventory row for the archive, with the count of files, plus individual rows for any file whose classification changed during the pass. + +`README.md`, `CHANGELOG.md`, and `CLAUDE.md` are not part of the FR-001 inventory. A contradicting sentence found in them is an unresolved entry or a correction noted under Unresolved as "corrected", with the path. + +## Issue classification row + +| Column | Content | +|---|---| +| Issue | Id and path | +| Class | still to do, already satisfied, superseded, or deferred | +| Evidence | The promise, and whether it is true on `main` | +| Owning specification | One path, or "none — not active" | + +## Unresolved entry + +```text +### U- + +- Higher: `` — +- Lower: `` — +- Check: +``` + +A corrected disagreement is not an unresolved entry. Record corrections in a short **Corrected** list: path, one sentence, higher authority cited. + +## Empty unresolved list + +When every disagreement was corrected, the section is: + +```text +## Unresolved + +None. +``` diff --git a/specs/002-speckit-docs-pass/contracts/source-marks.md b/specs/002-speckit-docs-pass/contracts/source-marks.md new file mode 100644 index 0000000..cea8be8 --- /dev/null +++ b/specs/002-speckit-docs-pass/contracts/source-marks.md @@ -0,0 +1,87 @@ +# Contract: Source Marks + +Banners are inserted at the top of the file, under the title when the file has one. Wording is fixed so every marked source reads the same way. + +## Product requirements document + +Delete `PRD.md` after `specs/003-ranch-today/spec.md` and `specs/002-speckit-docs-pass/pass-record.md` both exist. Do not leave a bannered copy. Do not replace it with a stub. + +`README.md` must not tell a reader to open `PRD.md`. Point the design sentence at `specs/003-ranch-today/spec.md`. + +Do not edit finished issues only to remove the words `PRD.md`. Replace `## Parent PRD` on active and deferred issues using the owning-spec section below, or, for a deferred issue, with: + +```markdown +## Owning specification + +None. Deferred. Not a requirement of `specs/003-ranch-today/spec.md`. +``` + +## Research notes + +Insert immediately under the title of each file in `docs/research/`: + +```markdown +> **Historical.** This note is evidence. It is not a current requirement and not an accepted decision. The constitution, accepted ADRs, and the current product specification govern where they disagree with it. See [specs/002-speckit-docs-pass/pass-record.md](../../specs/002-speckit-docs-pass/pass-record.md). +``` + +## Finished issue archive + +Create `issues/done/README.md`: + +```markdown +# Finished issues + +> **Historical.** These write-ups record what was asked at the time. They are not current requirements. A file marked **Shipped** had its outcome become true, including when the landed approach differs from the write-up. A file marked **Closed without building** was not built. The active queue is [../README.md](../README.md). +``` + +Do not add this banner to each existing finished file. + +## Shipped note + +Add at the top of an issue file moved to `issues/done/` because the promise is already true: + +```markdown +> **Shipped.** The completion promise is true on `main`. +``` + +## Closed-without-building note + +Add at the top of an issue file moved to `issues/done/` because it was superseded and the outcome was not shipped as that issue's promise: + +```markdown +> **Closed without building.** This file is not a current requirement. +``` + +## Glossary banner + +`CONTEXT.md` today says the terms are under review. After each entry is read: + +- If every entry is settled, replace that blockquote with: + +```markdown +> Settled names for the ranch. Specifications, issues, and UI copy use these words. The current product specification does not redefine them. +``` + +- If any entry is not settled, mark that entry with `**Unsettled**` on its own line under the term, leave its definition as written, and replace the banner with: + +```markdown +> Settled entries govern. Entries marked **Unsettled** do not. The current product specification uses only settled names. +``` + +Do not rewrite settled definitions. + +## Owning specification + +On each issue that remains to do, replace the whole `## Parent PRD` section with: + +```markdown +## Owning specification + +`` — +``` + +`` is `specs/003-ranch-today/spec.md` or the single follow-on spec created for that promise. The completion promise stays one sentence. Do not leave `## Parent PRD` in place beside the new section. + +## Render-domain record + +Do not add a banner to `specs/001-render-domain-seam/**`. Do not edit those files. diff --git a/specs/002-speckit-docs-pass/data-model.md b/specs/002-speckit-docs-pass/data-model.md new file mode 100644 index 0000000..e186813 --- /dev/null +++ b/specs/002-speckit-docs-pass/data-model.md @@ -0,0 +1,114 @@ +# Data Model: Spec Kit Docs Pass + +These are document entities. Nothing here is persisted in the Ranch data directory or sent over IPC. + +Authority, highest first: the constitution (`.specify/memory/constitution.md`), an Accepted ADR (`docs/adr/`), the current product specification, that specification's plan and tasks, then an issue. Historical sources are outside the order. A Draft specification is not approved authority under the constitution; this pass still writes it as the current description and records that status. + +## Entity: Current product specification + +| Field | Required | Rule | +|---|---|---| +| Path | yes | `specs/003-ranch-today/spec.md` | +| Status | yes | `Draft` until the owner changes it | +| Body | yes | Spec Kit spec shape in [contracts/current-product-spec.md](contracts/current-product-spec.md) | +| Vocabulary | yes | Settled entries from `CONTEXT.md` only | +| Carry-forward | yes | Each inherited statement cites a source and records the check against `main` | + +Relationships: cites the glossary and accepted ADRs. Points at `specs/001-render-domain-seam/spec.md` for the shipped render-domain record. Does not embed that spec, the glossary, or an ADR. Does not list deferred work or removed capabilities as requirements. + +## Entity: Follow-on specification + +| Field | Required | Rule | +|---|---|---| +| Path | yes | `specs/-/spec.md` | +| Status | yes | `Draft` | +| Body | yes | Spec Kit spec shape: user scenarios, requirements, success criteria | +| Plan and tasks | no | Must not exist as part of this pass | + +Exists only when the gap test in [research.md](research.md) passes for one still-to-do issue. One follow-on may own more than one issue only when those issues are the same user-visible outcome. It does not replace the issue. + +## Entity: Issue + +| Field | Required | Rule | +|---|---|---| +| Id | yes | Existing numeric id. Do not renumber | +| File | yes | Stays Markdown | +| Completion promise | yes | Exactly one, when the issue remains to do | +| Owning specification | yes | Exactly one path, when the issue remains to do | +| Class | yes | One of the classifications below | + +### Classification + +| Class | Queue after the pass | File | +|---|---|---| +| still to do | Active index: priority queue or architecture queue | Stays in `issues/` | +| already satisfied | Not active. Reader can see that it shipped | `issues/done/`, with the shipped note | +| superseded | Closed-without-building list, unless the outcome is true, in which case the class is already satisfied | `issues/done/`, with the closed-without-building note | +| deferred | Icebox section | Stays in `issues/icebox/` | + +An issue that was already closed without being built stays on that list and is not copied into the product specification. + +State transitions during the pass are one-way: active → still to do, already satisfied, or superseded. Deferred does not become active. Closed-without-building does not become a requirement. + +## Entity: Domain glossary + +| Field | Required | Rule | +|---|---|---| +| Path | yes | `CONTEXT.md` | +| Role | yes | Unchanged. Names live here | +| Banner | yes | Settled banner, or unsettled entries marked and the governing banner used | + +The product specification must not become a second glossary. + +## Entity: Decision record + +| Field | Required | Rule | +|---|---|---| +| Path | yes | `docs/adr/0001-two-apps-over-one-renderer.md`, `docs/adr/0002-agent-hook-transport.md`, `docs/adr/0003-rust-owned-render-scene.md` | +| Status | yes | Accepted. Only Accepted records govern | +| Body | yes | Unchanged by this pass unless a non-decision status correction is required | + +Draft, rejected, and superseded records would be context. None of those statuses are in `docs/adr/` at planning time. + +## Entity: Historical source + +| Field | Required | Rule | +|---|---|---| +| Kind | yes | Finished issue write-up, or research note | +| Path | yes | Original path, still findable | +| Mark | yes | Banner in [contracts/source-marks.md](contracts/source-marks.md) | + +`PRD.md` is inventoried, then deleted. It is not a historical source that remains. Finished write-ups are the files under `issues/done/` plus any file moved there because it shipped. Research notes are the three files in `docs/research/`. + +## Entity: Pass record + +| Field | Required | Rule | +|---|---|---| +| Path | yes | `specs/002-speckit-docs-pass/pass-record.md` | +| Inventory row | yes | One row per FR-001 source | +| Class | yes | Accepted decision, verified observation, present direction, unresolved assumption, or historical context | +| Unresolved entry | when needed | Both statements, both paths, and why the check could not pick one | + +The record is evidence of the pass. It is not an accepted ADR and not a second product specification. + +### Source class + +| Class | Meaning | +|---|---| +| Accepted decision | An Accepted ADR, or a constitution rule | +| Verified observation | Behavior checked on `main` | +| Present direction | What the owner still wants done, including a still-to-do issue | +| Unresolved assumption | A statement that could not be checked | +| Historical context | A finished phase, a finished issue, a research note, or the PRD after it is marked | + +A row may name a document that contains more than one class. The row says so, and the product specification receives only the verified and accepted parts. + +## Entity: Unresolved disagreement + +| Field | Required | Rule | +|---|---|---| +| Higher statement | yes | Quote or close paraphrase, with path | +| Lower statement | yes | Quote or close paraphrase, with path | +| Why unresolved | yes | What was checked on `main` and why it did not decide | + +Absent from the current specification, the glossary, accepted ADRs, and `docs/architecture.md` means the pass failed SC-004. A corrected lower document does not also need an unresolved entry. diff --git a/specs/002-speckit-docs-pass/pass-record.md b/specs/002-speckit-docs-pass/pass-record.md new file mode 100644 index 0000000..e2154a9 --- /dev/null +++ b/specs/002-speckit-docs-pass/pass-record.md @@ -0,0 +1,105 @@ +# Pass record + +## How to read this + +- `PRD.md` was removed after `specs/003-ranch-today/spec.md` existed. Git history still has it. It is not a current requirement. +- Finished issue write-ups and research notes that remain are not requirements. +- The current description is `specs/003-ranch-today/spec.md` and its status is Draft until the owner approves it. +- Accepted decisions remain in `docs/adr/`. Names remain in `CONTEXT.md`. + +## Inventory + +| Source | Class | Checked | Disposition | +|---|---|---|---| +| `PRD.md` | Historical context, plus verified observations that were revalidated | Compared with `docs/architecture.md`, accepted ADRs, and `main` on 2026-10-15. Finished phases, the localhost HTTP API, and the proposal queue are not current requirements | Deleted after carry-forward | +| `CONTEXT.md` | Accepted decision for names. The review banner was present direction that had gone stale | Each entry has a definition. Animal cites ADR-0001. No entry is marked unsettled | Kept as authority. Banner corrected | +| `docs/architecture.md` | Verified observation of the implementation. A few sentences used retired words or called every Animal a pig | Compared with the constitution, ADR-0001, ADR-0003, and `specs/003-ranch-today/spec.md` on 2026-10-15 | Kept as the implementation description. Contradicting sentences corrected | +| `docs/adr/0001-two-apps-over-one-renderer.md` | Accepted decision | Status line is Accepted | Kept as authority | +| `docs/adr/0002-agent-hook-transport.md` | Accepted decision | Status line is Accepted. Its unfinished user-visible consequences are issues 059, 060, and 062 | Kept as authority | +| `docs/adr/0003-rust-owned-render-scene.md` | Accepted decision | Status line is Accepted. `specs/001-render-domain-seam/` is the record of the shipped work | Kept as authority | +| `docs/research/serena-multi-agent.md` | Historical context | Not a behavior claim about the ranch product | Marked historical | +| `docs/research/manual-github-release-retention.md` | Historical context | Not a behavior claim about the ranch product | Marked historical | +| `docs/research/claude-codex-session-terminology.md` | Historical context | Glossary of vendor terms. `CONTEXT.md` remains the ranch's names | Marked historical | +| `specs/001-render-domain-seam/spec.md` | Accepted decision for that shipped feature | Implemented in PR #88. Consolidation updates only its lifecycle status, not requirements | Kept as authority | +| `issues/README.md` | Present direction for the queue | Compared with the issue files on 2026-10-15 | Updated so the queues match the classification | +| `issues/031-notification-source-settings.md` | Present direction | `src/components/SettingsWindow.tsx` still contains `NOTIFICATION_SOURCES` | Still to do. See classification | +| `issues/051-ranch-animal-vocabulary-seam.md` | Present direction | The scene and movement cutover shipped; `src/hooks/useAnimalMovement.ts` still imports the generic `PigHitRect` and Pig-named TypeScript wrappers | Still to do. See classification | +| `issues/056-task-timer-binding.md` | Present direction | `crates/storage/src/focus_store.rs` still stores Task Timers by index. No reorder repair | Still to do. See classification | +| `issues/059-self-describing-hook-frame.md` | Present direction | No late-frame stamp and no distinct failed-end Firing in the hook path | Still to do. See classification | +| `issues/060-session-staleness-sweep.md` | Present direction | `docs/architecture.md` still calls stale-session recovery future work. No such sweep is in the code | Still to do. See classification | +| `issues/061-hook-change-events.md` | Present direction | No `SessionChange` type. Delivery still emits a session-list refresh | Still to do. See classification | +| `issues/062-stable-hook-client-path.md` | Present direction | `src-tauri/src/app/claude_hook.rs` copies a stable client and does not write Claude settings. It also does not remove older direct entries | Still to do. See classification | +| `issues/icebox/021-all-monitors-default.md` | Present direction, deferred | Primary display remains the default | Left deferred | +| `issues/icebox/022-wrangle.md` | Present direction, deferred | Gather exists. Wrangle does not | Left deferred | +| `issues/done/` (49 files) | Historical context | The archive is the finished write-ups. This pass added a directory mark and did not rewrite the old bodies, except the shipped note on 046 | Marked historical | +| Closed-without-building notes 042, 045, 047 | Historical context | No files exist for these ids. The index still states why each was closed | Left closed | + +## Issue classification + +| Issue | Class | Evidence | Owning specification | +|---|---|---|---| +| 031 `issues/031-notification-source-settings.md` | still to do | The promise is that Settings toggles come from the Rust source registry. `SettingsWindow.tsx` still has a hardcoded `NOTIFICATION_SOURCES` list. The visible toggles already exist, so this is an internal seam, not a follow-on spec | `specs/003-ranch-today/spec.md` — FR-008 | +| 051 `issues/051-ranch-animal-vocabulary-seam.md` | still to do | The broad movement/scene cutover shipped in PR #88. `PigHitRect` and Pig-named TypeScript IPC wrappers remain generic. Keep only that adapter rename open; retain wire names as compatibility contracts | `specs/003-ranch-today/spec.md` — FR-004 | +| 056 `issues/056-task-timer-binding.md` | still to do | The promise is that a Task Timer stays on its Task across a hand-edit, or that the drift is a decided and tested behavior. Storage is still by position, and no reorder test decides it. The person can see the Timer move | `specs/004-task-timer-hand-edits/spec.md` | +| 059 `issues/059-self-describing-hook-frame.md` | still to do | The promise is that a late frame is ignored and Agent Hooks can tell an ended turn from a died turn. Neither is true on `main`. Both are visible in the session Animal or the Agent Hooks window | `specs/005-late-hook-frame/spec.md` | +| 060 `issues/060-session-staleness-sweep.md` | still to do | The promise is that a session whose turn ended unheard stops being drawn as working, without a restart. Architecture still lists that recovery as future work | `specs/006-unheard-turn-ends/spec.md` | +| 061 `issues/061-hook-change-events.md` | still to do | The promise is that a consumer can see a session change without comparing two lists. No `SessionChange` is exported. The person does not gain a new visible behavior. The overlay already refetches the list | `specs/003-ranch-today/spec.md` — FR-014, under ADR-0002 | +| 062 `issues/062-stable-hook-client-path.md` | still to do | The promise is that an entry the ranch wrote can be removed by the ranch, and one firing arrives once. The stable client exists. Older direct settings entries are not removed | `specs/007-one-hook-delivery/spec.md` | +| 021 `issues/icebox/021-all-monitors-default.md` | deferred | The owner deferred multi-monitor default-on. The file stayed in `issues/icebox/` | None. Deferred | +| 022 `issues/icebox/022-wrangle.md` | deferred | The owner deferred Wrangle. Gather remains the shipped action | None. Deferred | +| 042 | superseded | The index says the premise was wrong: both consumers already read the same cap-state projection. No file. Not copied into the current spec | None. Not active | +| 045 | superseded | The index says the helper was too thin and the work folded into 039. No file | None. Not active | +| 046 `issues/done/046-timer-expiry-service-extraction.md` | already satisfied | The promise is one tested workflow module, with `app/timer_expiry.rs` only wiring the loop. `crates/commands/src/timers.rs` owns `expire_due` and its tests. `src-tauri/src/app/timer_expiry.rs` spawns the one-second loop and adapts notifications. The type names differ from the write-up. The index had listed 046 under closed-without-building; that line was the lower-authority statement and was removed | None. Not active | +| 047 | superseded | The index says the proposal queue and HTTP API were removed, so the storage transaction for that queue was not built. No file | None. Not active | + +## Corrected + +- `issues/README.md`: removed 046 from the closed-without-building list. The outcome shipped. Higher authority: the promise checked against `crates/commands/src/timers.rs` and `src-tauri/src/app/timer_expiry.rs`. +- `docs/architecture.md`: the scope line and the interaction loop called every sprite a pig and called Limits caps. Higher authority: `CONTEXT.md` and `specs/003-ranch-today/spec.md`. +- `README.md`: the design pointer named `PRD.md`, and the opening said one pig per Focus. Higher authority: `specs/003-ranch-today/spec.md`. +- `CONTEXT.md`: the banner said the language was under review. The entries are settled. Higher authority: the glossary entries and ADR-0001. +- `CHANGELOG.md` `[0.1.4]`: the entry says hook install writes Claude's `settings.json` and that a dead session has nothing to go stale. Left in place. It is the note for that release, not a current requirement. Current behavior is FR-014 and FR-015 in `specs/003-ranch-today/spec.md`. +- `CLAUDE.md`: no sentence contradicted the current specification. No edit. + +## Unresolved + +None. + +## Consolidation with the saved foundation + +The owner requested consolidation on 2026-10-15 after PR #89 merged. The original documentation +pass remains above; the combined cleanup also preserves the earlier setup and the mechanical +HTML entrypoint move as separate changes. + +- `main` at `8fa695d` includes PR #89. The product draft and architecture now describe built-in + 10/30/60 minute chips and persisted custom chips, replacing the stale 2/4/8/16/32 description. +- Spec 001's status and ADR-0003's completed action items now reflect PR #88. Its requirements and + recorded validation are unchanged. The separate backend-movement decision remains open. +- Issue 051 stays active only for the remaining generic TypeScript hit-test adapter names. The + earlier foundation branch closed it too broadly; compatibility wire names remain exempt. +- Issues 057 and 058 remain in `issues/done/`; their original proposals are historical. +- The obsolete `issues/done/024-display-subsystem-agent-prompt.md` is removed; the actual shipped + issue remains at `issues/done/024-display-subsystem.md` and the prompt remains in Git history. +- The orchestrator and lane agents from `chore/project-foundation` are retained for Claude, + Codex, and Cursor. Both installed Spec Kit integrations are retained, with Codex as default. +- The archive design and accepted ADR-0004 are preserved as `specs/008-claude-session-storage/`. + Its former 002 prefix collided with the documentation pass. Renumbering does not approve new + implementation or change the archive decisions. +- HTML sources move under `src/`, while Vite still serves the same five page URLs and builds them + into root `dist/` for Tauri. This is checked separately from the document reader checks. +- Ranch Today and specs 004–007 remain Draft. Review with the owner is still required before + treating their proposed requirements as authority. + +### Consolidation validation + +- `task check` passed: Rust/frontend lint, unused-code checks, TypeScript, all unit tests, and + generated-type drift. Application TypeScript, Rust, generated types, and dependencies are unchanged. +- All five relocated HTML documents match their originals except equivalent module paths. Each + existing page URL and module entry returned HTTP 200 from Vite; production HTML and assets remain + under root `dist/`, matching Tauri's existing URLs. +- JSON/TOML parsing, Spec Kit manifest hashes, shell syntax and command-format checks, local + Markdown links, and `git diff --check` passed. +- The spec 008 files match the saved archive planning apart from the 002-to-008 path renumbering. + Product and follow-on spec lifecycle states are unchanged. +- Native desktop interaction was not rerun; the entrypoint change is covered by content, HTTP, + production-output, and regression-gate checks. diff --git a/specs/002-speckit-docs-pass/plan.md b/specs/002-speckit-docs-pass/plan.md new file mode 100644 index 0000000..22bfece --- /dev/null +++ b/specs/002-speckit-docs-pass/plan.md @@ -0,0 +1,176 @@ +# Implementation Plan: Spec Kit Docs Pass + +**Branch**: `002-speckit-docs-pass` | **Date**: 2026-10-15 | **Spec**: [spec.md](spec.md) + +**Input**: Feature specification from `specs/002-speckit-docs-pass/spec.md` + +## Summary + +Turn the living product requirements document into one Draft current product specification, and make the issue queue, glossary banner, architecture description, and historical sources agree with it. The pass writes and edits Markdown only. It does not change what the ranch does. + +The current specification is a new Spec Kit spec at `specs/003-ranch-today/spec.md`. It describes today's capabilities, limits, and non-goals in the glossary's settled words, with each carried-forward statement citing its source and recording that it was checked against `main`. After that spec exists, `PRD.md` is deleted. Spec Kit is the only planning document that remains. `specs/001-render-domain-seam/` stays the record of that shipped work and is not rewritten. `CONTEXT.md`, accepted ADRs, `docs/architecture.md`, and the issue queue keep their roles. + +A pass record in this feature directory inventories every required source, classifies it, and lists every disagreement that was corrected or left unresolved. Active issues are classified against the completion promise and the product on `main`. Issues that remain to do keep one promise and name the spec that owns it. A follow-on spec is created only when that promise is undone, user-visible, and absent from the current specification. + +## Technical Context + +**Language/Version**: Markdown documents. No Rust, TypeScript, Tauri, or frontend change. + +**Primary Dependencies**: The Spec Kit spec shape already used by `specs/001-render-domain-seam/spec.md` and `.specify/templates/spec-template.md`. The issue file shape in `issues/README.md`. No new tool or package. + +**Storage**: Git files only. No Ranch data directory, settings schema, or persisted user state changes. + +**Testing**: Reader checks in [quickstart.md](quickstart.md). `task check` once at the end proves the product gate still passes. No new product tests. + +**Target Platform**: The repository's documents, read on any platform. The ranch's packaged platforms are unchanged. + +**Project Type**: Documentation pass over the existing local-first Tauri desktop application. This feature does not modify the application. + +**Performance Goals**: N/A. No runtime path changes. + +**Constraints**: Documents only (FR-012, SC-006). Authority order is the constitution, then accepted ADRs, then the current specification, then an issue. Historical sources sit outside that order. Settled glossary words only. `specs/001-render-domain-seam/` is not rewritten. `PRD.md` is deleted only after `specs/003-ranch-today/spec.md` exists and its carry-forward citations are written. Deferred issues stay deferred. Issues closed without being built stay closed. `.specify/feature.json` stays pointed at `specs/002-speckit-docs-pass`. The new product spec stays Draft until the owner approves it. No second planning document. + +**Scale/Scope**: One PRD, one glossary, one architecture description, three accepted ADRs, three research notes, one accepted render-domain spec, the issue index, 7 active issue files, 49 finished issue files under `issues/done/`, 2 icebox files, and the closed-without-building notes in the index. Install guide (`README.md`), release history (`CHANGELOG.md`), and working agreements (`CLAUDE.md`) are scanned for contradicting sentences only. + +## Constitution Check + +*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design.* + +### Pre-design gate + +| Principle or constraint | Result | Evidence | +|---|---|---| +| I. User-Owned Local State | PASS | No persistence, network, telemetry, credentials, or integration install path is in scope. | +| II. Independent Domains, Shared Renderer | PASS | No domain or renderer code is edited. The documents must keep Focus and Agent Session independent and must not reintroduce a shared domain type. | +| III. Functional Core, I/O at the Edges | PASS | No modules, traits, or React components are added. | +| IV. Explicit, User-Controlled Integrations | PASS | Harness install, validation, and transport are untouched. | +| V. Observable Completion in Small Slices | PASS | The pass is four document slices, each with one reader-visible promise. `task check` is the regression gate. Review size stays about fifteen minutes per slice. | +| VI. Evidence Is Not Authority | PASS | The pass inventories the PRD before writing the product spec, carries forward only revalidated statements, then deletes the PRD. On 2026-10-15 the owner directed that the old planning document not stay in the tree. Research notes and finished issues stay marked historical. `spec.md` for this feature still says Draft; this command does not edit that status. The owner requested planning by running `/speckit-plan`. | +| Product constraints | PASS | No IPC, localhost API, or network surface. Vocabulary comes from `CONTEXT.md`. Accepted ADRs stay the architecture authority. The simplest design is new Markdown plus banners, not a new documentation system. | +| Work-management order | PASS | The pass uses a feature spec, this plan, later tasks, and the existing issue queue together. It does not replace issues with a task list. | + +**Gate result**: PASS. No exception is required. + +`specs/002-speckit-docs-pass/spec.md` remains Draft in the file. Planning does not promote it. The product specification this pass writes also stays Draft until the owner approves that file. Until that approval, Principle VI says the Draft product spec is not yet the governing requirements authority. The pass still writes it, marks the PRD historical, and points readers at it as the current description, which is what FR-002 and US1 require on paper. + +## Project Structure + +### Documentation (this feature) + +```text +specs/002-speckit-docs-pass/ +├── spec.md # this feature's intent; not edited by the plan +├── plan.md # this file +├── research.md # Phase 0 +├── data-model.md # Phase 1 +├── quickstart.md # Phase 1 +├── contracts/ +│ ├── current-product-spec.md # shape of specs/003-ranch-today/spec.md +│ ├── pass-record.md # inventory, classification, unresolved list +│ └── source-marks.md # historical banners and issue citations +├── checklists/ +│ └── requirements.md # already present +└── pass-record.md # written during implementation, not by this command + +specs/003-ranch-today/ +└── spec.md # Draft current product specification; implementation + +specs/001-render-domain-seam/ # shipped record; do not rewrite +``` + +`tasks.md` is deferred to `/speckit-tasks`. + +### Documents the pass may edit + +```text +PRD.md # deleted after specs/003-ranch-today/spec.md exists +CONTEXT.md # review banner only; definitions stay +docs/architecture.md # contradicting sentences only +docs/research/*.md # historical banner on each note +issues/README.md # index matches classification +issues/done/README.md # new archive mark +issues/031-*.md # classify; cite an owning spec if still to do +issues/051-*.md +issues/056-*.md +issues/059-*.md +issues/060-*.md +issues/061-*.md +issues/062-*.md +issues/done/.md # only files moved here, plus a shipped or closed note +issues/icebox/*.md # stay deferred; no promotion +README.md # a contradicting pointer only +CHANGELOG.md # a contradicting sentence only, if one exists +CLAUDE.md # a contradicting sentence only, if one exists +``` + +A follow-on spec, if the gap test in [research.md](research.md) passes for a remaining issue, is a new `specs/-/spec.md` and nothing else in that directory. + +### Untouched + +Application and host code (`src/`, `src-tauri/`, `crates/`), package and Cargo manifests, `Taskfile*`, generated types, `specs/001-render-domain-seam/**`, accepted ADR bodies, `.specify/feature.json`, and `.specify/memory/constitution.md`. + +**Structure Decision**: Keep the conversion inside the existing Spec Kit and issue layout. The product specification gets the next free number, `003`, so a later `/speckit-specify` allocates `004` or higher. This feature's directory holds the pass record and stays the directory named by `.specify/feature.json`. Finished issues stay in `issues/done/`. Deferred issues stay in `issues/icebox/`. No new documentation tree, site, or issue tracker is introduced. + +## Design and Delivery Strategy + +Implementation order is fixed because later slices read earlier documents. + +### 1. Pass record + +Write `specs/002-speckit-docs-pass/pass-record.md` in the shape of [contracts/pass-record.md](contracts/pass-record.md). Inventory every source named in FR-001. Classify each one before any other document changes. Do not copy historical material into the record as a requirement. + +**Completion promise**: A reader can take any inventoried source and say which class it has. + +### 2. Current product specification + +Write `specs/003-ranch-today/spec.md` in the shape of [contracts/current-product-spec.md](contracts/current-product-spec.md). Start from current behavior on `main`, accepted ADRs, and settled glossary entries. Carry a PRD statement forward only when it is still true, and record the check. Leave finished phases, removed capabilities, and deferred work out of the requirements. + +State the shipped render outcome in glossary words and point at `specs/001-render-domain-seam/spec.md` as the record of that work. Do not restate that spec. + +**Completion promise**: A reader who has not seen the repository can list current capabilities, limits, and non-goals from this file alone. + +### 3. Issue queue + +Classify every issue that was active at the start of the pass, using the rules in [data-model.md](data-model.md). Move already-satisfied files to `issues/done/` with a shipped note. Move superseded issues that did not ship out of the active directory, record them on the index's closed-without-building list, and keep the file findable under `issues/done/` with a closed-without-building note. Leave icebox files in `issues/icebox/`. Leave issues that are already closed without being built on that list. + +For each issue that remains to do, replace `## Parent PRD` with one owning-spec citation, as in [contracts/source-marks.md](contracts/source-marks.md). Keep a single completion promise. Create a follow-on spec only when the gap test passes. Update `issues/README.md` so its queues match the files, and so the issue-file shape shows `## Owning specification` instead of `## Parent PRD`. + +**Completion promise**: The active queue contains only undone issues, and each one cites exactly one owning specification and one observable promise. + +### 4. Marks and settlements + +Delete `PRD.md` only after `specs/003-ranch-today/spec.md` and the pass record exist. Point `README.md` at the current specification, not at the deleted file. Add the historical banners from [contracts/source-marks.md](contracts/source-marks.md) to each research note and to `issues/done/README.md`. Correct the glossary banner, or mark unsettled entries, per the edge case in the feature spec. Where an inventoried document disagrees with a higher authority about current behavior, correct the lower document or add both statements to the pass record's unresolved list. Scan `CHANGELOG.md` and `CLAUDE.md` for contradicting sentences only. + +**Completion promise**: The working tree has no `PRD.md`. Finished write-ups and research notes are findable and marked historical. Every disagreement found is either corrected or on the unresolved list. + +Do not edit `specs/001-render-domain-seam/**`. Do not edit application code. + + +## Protected Seams + +- The ranch's behavior, persistence, IPC, and integrations stay as they are. +- `CONTEXT.md` remains the glossary. The product spec uses it and does not absorb it. +- Accepted ADRs remain the decision records. The pass does not rewrite an accepted decision. A status correction that does not change the decision may be made in place only when the record's status is wrong; none is expected. +- `specs/001-render-domain-seam/spec.md` remains the render-domain record. +- The issue queue remains the shipping unit. This pass does not emit `tasks.md` entries as a replacement queue. + +## Complexity Tracking + +No constitution violations require justification. + +### Post-design gate + +Re-checked after [research.md](research.md), [data-model.md](data-model.md), [quickstart.md](quickstart.md), and `contracts/`. + +| Principle or constraint | Result | Evidence | +|---|---|---| +| I. User-Owned Local State | PASS | Design artifacts name Markdown paths only. | +| II. Independent Domains, Shared Renderer | PASS | The product-spec contract forbids a second render-domain specification and forbids retired shared-domain wording. | +| III. Functional Core, I/O at the Edges | PASS | No code design is introduced. | +| IV. Explicit, User-Controlled Integrations | PASS | No integration contract is added. | +| V. Observable Completion in Small Slices | PASS | Four slices, each with one promise. Quickstart maps those promises to reader checks and a final `task check`. | +| VI. Evidence Is Not Authority | PASS | Research orders authorities and defines the carry-forward rule. The PRD is deleted only after that carry-forward. The pass record separates observation, accepted decision, present direction, unresolved assumption, and historical context. The product spec stays Draft. | +| Product constraints | PASS | Glossary contract binds the spec to settled names. Number `003` reuses the existing spec directory convention. | +| Work-management order | PASS | Follow-on specs are conditional and do not include plans or task lists. `.specify/feature.json` is left on this feature. | + +**Gate result**: PASS. diff --git a/specs/002-speckit-docs-pass/quickstart.md b/specs/002-speckit-docs-pass/quickstart.md new file mode 100644 index 0000000..15ac16b --- /dev/null +++ b/specs/002-speckit-docs-pass/quickstart.md @@ -0,0 +1,70 @@ +# Quickstart: Spec Kit Docs Pass + +Validation is a read of the documents. No app launch is required. Run the checks from the repository root after implementation, on a tree synced with current `main`. + +## Prerequisites + +- `specs/003-ranch-today/spec.md` exists, written from `PRD.md` before that file was deleted. +- `specs/002-speckit-docs-pass/pass-record.md` exists. +- `PRD.md` does not exist. +- `CONTEXT.md`, `docs/architecture.md`, `docs/adr/`, `docs/research/`, `issues/`, and `specs/001-render-domain-seam/` are the sources still under test. + +## 1. Cold read of the current specification + +Open only `specs/003-ranch-today/spec.md`. + +Expected: + +- The status is Draft. +- You can name current capabilities, limits, and non-goals from this file alone. `PRD.md` is not in the working tree. +- You do not find a finished implementation-phase list, a localhost HTTP API requirement, or a proposal-queue requirement. +- Deferred multi-monitor default-on and wrangle are absent from the requirements. +- Animals, Limits, Gather, and Settings are named with the glossary's words. Pig is the Species, not the word for every Animal. +- The render-domain outcome points at `specs/001-render-domain-seam/spec.md` and does not copy that spec. +- Every carried-forward requirement has a source citation and a note that it was checked against `main`. + +## 2. Active queue + +Compare `issues/README.md` with the issue files and with `specs/002-speckit-docs-pass/pass-record.md`. + +Expected: + +- Every issue that was active at the start (`031`, `051`, `056`, `059`, `060`, `061`, `062`) has one classification row. +- Every file still in `issues/` outside `done/` and `icebox/` is classified still to do. +- Each of those files has one `## Completion promise` and one `## Owning specification`, and no `## Parent PRD`. +- The owning path is `specs/003-ranch-today/spec.md` or one follow-on `specs/-/spec.md`. +- A follow-on directory contains `spec.md` only. +- `issues/icebox/021-all-monitors-default.md` and `issues/icebox/022-wrangle.md` are still the icebox, and they are not requirements in the product spec. +- The closed-without-building notes still include the issues that were closed that way, unless a correction in the pass record shows the outcome shipped. +- An issue moved to `issues/done/` during the pass starts with **Shipped** or **Closed without building**. + +## 3. History and disagreements + +Expected: + +- `PRD.md` does not exist. `README.md` does not send a reader to it. +- Each file in `docs/research/` has the historical banner. +- `issues/done/README.md` marks the archive historical. +- `CONTEXT.md` still defines the terms. The review banner is gone, or unsettled entries are marked and the governing banner is present. +- `docs/adr/0001-two-apps-over-one-renderer.md`, `docs/adr/0002-agent-hook-transport.md`, and `docs/adr/0003-rust-owned-render-scene.md` are still Accepted and were not rewritten into the product spec. +- Spec 001 has only its lifecycle-status correction from the saved foundation; requirements and validation records are unchanged. +- The pass record has an Unresolved section. Each entry shows both statements and both paths. A disagreement you can still find between the product spec, the glossary, an accepted ADR, and `docs/architecture.md` appears there. + +## 4. Behavior did not change + +```sh +git diff --stat -- src src-tauri crates package.json package-lock.json Cargo.toml Cargo.lock Taskfile.yaml src/types/generated +``` + +Expected for the original documentation pass: empty. In the consolidated cleanup, only the five +HTML entrypoint moves are allowed under `src/`; application TypeScript, Rust, generated types, +and dependency manifests remain unchanged. Vite and the unused-source scanner are updated to +follow the new source root. + +```sh +task check +``` + +Expected: the gate passes. + +`.specify/feature.json` still names `specs/002-speckit-docs-pass`. diff --git a/specs/002-speckit-docs-pass/research.md b/specs/002-speckit-docs-pass/research.md new file mode 100644 index 0000000..a6fdc9a --- /dev/null +++ b/specs/002-speckit-docs-pass/research.md @@ -0,0 +1,141 @@ +# Research: Spec Kit Docs Pass + +All technical unknowns for this documentation pass are resolved. No product capability was chosen here; the decisions are about where documents live and how a disagreement is recorded. + +## Decision: The current product specification is `specs/003-ranch-today/spec.md` + +**Rationale**: The feature asks for one current specification in the format the project already uses, which is a Spec Kit `spec.md`. Number `003` is the next free prefix after `specs/001-render-domain-seam/` and `specs/002-speckit-docs-pass/`. `create-new-feature.sh` allocates the next number from existing directory prefixes, so a later specify command will use `004` or higher. The file is written by this pass. It is not created by `/speckit-specify`, because that command would retarget `.specify/feature.json` and draft from a new prompt. + +The spec stays **Draft**. The constitution says a feature specification remains Draft until the owner approves it. This pass must not flip that status. + +**Alternatives considered**: + +- Rewriting `PRD.md` in place. Rejected. The owner wants Spec Kit as the only planning document. A rewritten PRD would still be a second plan. +- Keeping `PRD.md` with a historical banner. Rejected on 2026-10-15. The owner directed that the old planning document be removed. +- Putting the product spec inside `specs/002-speckit-docs-pass/`. Rejected. That directory is the conversion feature, not the product description a later slice should cite. + +## Decision: This feature's directory keeps the pass record + +**Rationale**: FR-001 and the pass-record entity need an inventory, a classification, and a visible unresolved list. `specs/002-speckit-docs-pass/pass-record.md` is that list. `.specify/feature.json` already points at this directory and must keep doing so, or later Spec Kit commands for this feature will look at the product spec instead. + +The unresolved list is visible because the historical banners and the corrected `README.md` pointer name the pass record. A disagreement is not settled by omitting it. The pass record also notes that `PRD.md` was removed after the current specification was written. + +**Alternatives considered**: + +- A new `docs/decisions/` index. Rejected. Accepted decisions already live in `docs/adr/`. A second index would look like a new authority. +- Leaving the inventory inside `PRD.md`. Rejected. That file is deleted. + +## Decision: Delete `PRD.md` after the current specification exists + +**Rationale**: The owner directed, on 2026-10-15, that the old planning document come out and that Spec Kit be the planning format that remains. FR-009 requires the deletion. The file is read during the inventory and the carry-forward. It is deleted only after `specs/003-ranch-today/spec.md` and the pass record exist, so the citations have somewhere to point in the working tree until that moment. Git history keeps the old text. The working tree does not. + +`README.md` currently says to see `PRD.md` for the design. That sentence points at `specs/003-ranch-today/spec.md` instead. It does not name a file that was just deleted as a place to keep reading. + +Active and deferred issues stop citing `PRD.md`. Finished issues are not rewritten to chase the deleted path. A `## Parent PRD` line in `issues/done/` is historical prose. + +The glossary, accepted ADRs, `docs/architecture.md`, research notes, and the issue queue stay. They are not the old plan. The constitution still requires the glossary, accepted decisions, and the issue queue beside Spec Kit. + +**Alternatives considered**: + +- Deleting `PRD.md` before the current specification is written. Rejected. The conversion would lose its source. +- Also deleting `CONTEXT.md`, `docs/adr/`, `docs/architecture.md`, `docs/research/`, or `issues/`. Rejected. Those are names, decisions, the implementation description, evidence, and the shipping queue. The owner asked to remove the old planning document, not those authorities. + +## Decision: Mark the remaining historical sources with a banner, not a move + +**Rationale**: Finished issue write-ups and research notes stay findable and must be identifiable as historical. Moving them would break links. Editing all 49 finished issue bodies would rewrite history the feature says to keep. + +The mark is one banner: + +- On each of the three files in `docs/research/`. +- Once for the finished archive, in a new `issues/done/README.md`, so the archive is marked as a class. + +Files moved into `issues/done/` during this pass also get a one-line shipped note or closed-without-building note, so a reader can tell those apart from work that shipped as written. + +`specs/001-render-domain-seam/` is the accepted record of shipped render-domain work (FR-011). It gets no banner and no edit. + +**Alternatives considered**: + +- A banner on every file in `issues/done/`. Rejected. The archive is one class, and a directory mark keeps the old write-ups intact. +- Marking `specs/001-render-domain-seam/spec.md` historical. Rejected. That would rewrite the record FR-011 says to leave in place. + +## Decision: Classify issues by the observable promise, not the original checklist + +**Rationale**: US2 and the edge case about a shipped issue whose checklist names files that never landed. An active issue is judged by whether its completion promise is true on `main`, compared with the code, the accepted ADRs, and `docs/architecture.md`. Ticking the original checklist is not the test. + +Classes: + +- **still to do** — the promise is not true, the owner has not deferred it, and later work has not replaced it. The file stays in `issues/` and cites one owning spec. +- **already satisfied** — the promise is true on `main`, including when a different approach landed. Move the file to `issues/done/` and add the shipped note. +- **superseded** — later work replaced the issue or its premise was wrong, and the original promise is not the work to do. If the outcome is nevertheless true, classify it as already satisfied instead. Otherwise add it to the index's closed-without-building list and move the file to `issues/done/` with the closed-without-building note. +- **deferred** — the owner has deferred it. The two icebox files stay in `issues/icebox/` and stay off the current specification's requirements. + +The index's priority queue and architecture queue are both active. Both may contain only still-to-do issues after the pass. Do not collapse those two subsections. + +Known input the implementation must classify, not a result decided here: `issues/README.md` lists 046 as closed without implementation, and `issues/done/046-timer-expiry-service-extraction.md` also exists. The pass record must show which statement was checked against `main`, and the lower-authority line must be corrected or both statements must appear on the unresolved list. + +Active files at planning time: `031`, `051`, `056`, `059`, `060`, `061`, `062`. Icebox: `021`, `022`. Closed-without-building notes already in the index: `042`, `045`, `046`, `047`. Those notes stay closed unless a check shows the outcome actually shipped, in which case the note is corrected so a reader can see that it shipped. + +**Alternatives considered**: + +- Re-checking every acceptance checkbox against the original file list. Rejected. That recreates the stale-plan failure the feature describes. +- A new `issues/closed/` directory. Rejected. The index already has a closed-without-building list, and a new directory would be a second queue. + +## Decision: One owning spec, and a follow-on only when the gap is real + +**Rationale**: FR-006 and FR-007. A remaining issue stops citing `## Parent PRD` and cites either `specs/003-ranch-today/spec.md` or one follow-on spec. It keeps a single completion promise. + +Gap test, applied only after the current specification exists, and only to an issue classified still to do: + +1. The promise describes behavior a person using the ranch can observe. +2. The current specification does not already state that outcome, as a capability or as a limit. +3. The promise is not only an internal seam, a rename, or a regression fix of a behavior the current specification already states. + +Create a follow-on `spec.md` only when all three are true. The directory number is the next free prefix at the time of creation, never a number reserved in advance other than `003` for the product spec. The follow-on file is Draft, uses the Spec Kit spec shape, and has no `plan.md` or `tasks.md`. Internal slices cite the current specification section they serve, plus an accepted ADR when the issue already cites one. + +The pass does not replace the issue queue with `tasks.md`. + +**Alternatives considered**: + +- One follow-on spec per remaining issue. Rejected by the feature assumptions. +- Leaving `## Parent PRD` in place and adding a second parent. Rejected. The issue would still point at a historical document as its authority. + +## Decision: Settled glossary words, banner corrected in place + +**Rationale**: FR-003 and FR-008. `CONTEXT.md` stays the glossary. The product specification uses settled entries and does not redefine them. The banner that says the language is still under review is the edge case in the feature spec. Implementation reads each entry. If every entry is settled, replace the banner with the settled banner in [contracts/source-marks.md](contracts/source-marks.md). If an entry is not settled, mark that entry **Unsettled** and use the banner that says settled entries govern. + +Retired words are the entry's `_Avoid_` line. The product specification uses the settled word for that idea. **Pig** remains the Species name and the concrete sprite name. It is not the word for the general Animal. **Limit** is the word for the soft threshold the PRD calls a cap. **Gather** is the word for bringing Animals back. **Settings** is the word for stored configuration. **Preferences** remains only the macOS menu label. + +**Alternatives considered**: + +- Copying the glossary into the product spec and deleting `CONTEXT.md`. Rejected by FR-008. +- Leaving the review banner untouched. Rejected. The feature's edge case says the banner is corrected or the unsettled entries are called out. + +## Decision: Correct the lower authority, or write both statements down + +**Rationale**: FR-010 and the constitution's authority order. When two inventoried documents disagree about current behavior: + +1. Constitution. +2. Accepted ADR (`docs/adr/0001`, `0002`, `0003` are all Accepted). +3. The current product specification, once it states the revalidated behavior. While it is Draft, do not use it to overrule the constitution or an accepted ADR. Do use it as the requirements document the architecture description, README, and issues must stop contradicting. +4. An issue. +5. Historical sources never win: `issues/done/**` and `docs/research/**`. `PRD.md` is read, then deleted, so it cannot remain a competing statement. + +The lower document is edited. If the pass cannot tell which statement is true on `main`, both statements go on the unresolved list and neither is silently dropped. + +`docs/architecture.md` is the implementation description. It is corrected where it claims a current behavior the constitution, an accepted ADR, or the revalidated product spec does not hold. It is not converted into a specification. + +`README.md`, `CHANGELOG.md`, and `CLAUDE.md` are not converted. A sentence that contradicts the current specification is corrected or listed. The expected README settlement is the sentence that sends the reader to `PRD.md` for the design: point that sentence at `specs/003-ranch-today/spec.md`. Confirm the sentence still says that before editing. + +**Alternatives considered**: + +- Rewriting `docs/architecture.md` to mirror the product spec. Rejected. It describes implementation, and wholesale conversion is out of scope. +- Keeping the PRD until the owner approves the Draft spec. Rejected. The owner asked for it to be removed. The Draft status stays on the product spec and in the pass record so Principle VI stays visible. + +## Decision: Proof is a reader check plus an empty product diff + +**Rationale**: SC-001 through SC-006 are document outcomes. [quickstart.md](quickstart.md) is the validation guide. `task check` runs once after the document edits. A diff that touches `src/`, `src-tauri/`, `crates/`, manifests, or generated types fails the pass even if the gate is green, because FR-012 forbids a behavior change. + +**Alternatives considered**: + +- New Vitest or Rust tests for prose. Rejected. There is no code contract to execute. +- Skipping `task check`. Rejected. The constitution requires the gate after synchronization with `main`, and a green gate is the evidence the document pass did not break the build. diff --git a/specs/002-speckit-docs-pass/spec.md b/specs/002-speckit-docs-pass/spec.md new file mode 100644 index 0000000..f9a3214 --- /dev/null +++ b/specs/002-speckit-docs-pass/spec.md @@ -0,0 +1,118 @@ +# Feature Specification: Spec Kit Docs Pass + +**Feature Branch**: `002-speckit-docs-pass` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: User description: "converting our PRD, issues and docs into the speckit format and doing a pass over it" + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Read the product as it is now (Priority: P1) + +The owner, or anyone they hand the project to, can read one current specification and learn what the ranch does today, what it will not do, and which words to use. They do not have to rebuild that picture from the product requirements document's phase history, from finished issue write-ups, or from research notes. + +**Why this priority**: Every later slice is wrong if the current product is still described in several places that disagree. One current specification is the point of the conversion. + +**Independent Test**: Hand a reader who has not seen the repository only the current specification. They can name the product's current capabilities, its limits, and its explicit non-goals, and they never need the old product requirements document to do it. + +**Acceptance Scenarios**: + +1. **Given** the product requirements document, the domain glossary, accepted decision records, and the behavior already shipped, **When** the pass finishes, **Then** one current specification states today's capabilities, limits, and non-goals in the glossary's settled words. +2. **Given** the old product requirements document describes finished phases or capabilities the product no longer has, **When** a reader opens the current specification, **Then** those phases and retired capabilities are absent from its requirements. +3. **Given** the render-domain work already has an accepted specification and has shipped, **When** the pass finishes, **Then** that specification remains the record of that work and is not rewritten as a second specification of the same outcome. + +--- + +### User Story 2 - Trust the work still to do (Priority: P2) + +Someone choosing the next slice sees only work that is still undone. Each remaining slice points at the current specification, or at a follow-on specification when the current one does not already cover that outcome. Shipped, superseded, and deferred items are not sitting in the active queue. + +**Why this priority**: A converted specification that leaves a stale queue still sends the next person after work that already shipped or was rejected. + +**Independent Test**: Compare the active queue with the product as it exists after the pass. Every active item is still undone, names one observable outcome, and cites the specification that owns that outcome. Deferred items are visibly deferred. Items closed without being built stay closed. + +**Acceptance Scenarios**: + +1. **Given** an issue whose observable outcome is already true in the product, **When** the pass classifies it, **Then** it leaves the active queue and a reader can see that it shipped, including when the original write-up described a different approach than the one that landed. +2. **Given** an issue the owner has deferred, **When** the pass finishes, **Then** it remains deferred and is not promoted into the active queue or into the current specification's requirements. +3. **Given** an issue that was closed because its premise was wrong or later work replaced it, **When** the pass finishes, **Then** it stays closed and is not copied in as a requirement. +4. **Given** an issue that is still undone, **When** the pass finishes, **Then** it keeps a single observable completion promise and names the specification that owns that promise. + +--- + +### User Story 3 - Tell history from authority (Priority: P3) + +A reader who opens an old issue, a research note, or the architecture description can tell whether they are looking at a current decision or at history. The old product requirements document is gone, so it cannot be mistaken for the current specification. Disagreements found during the pass are settled in the lower-authority document, or written down as unresolved. Nothing is silently left in conflict. + +**Why this priority**: The conversion fails if a second planning document stays beside the specification, or if the remaining old documents stay unmarked and keep contradicting it. + +**Independent Test**: Take each source the pass inventoried. A reader can say which role it has, and can find a written settlement for every place it disagreed with a higher authority. + +**Acceptance Scenarios**: + +1. **Given** the product requirements document, finished issue write-ups, and research notes, **When** the pass finishes, **Then** the product requirements document is gone from the working tree, and the finished write-ups and research notes remain findable and are marked so they cannot be mistaken for current requirements. +2. **Given** the domain glossary and an accepted decision record, **When** the pass finishes, **Then** both remain the authorities they already are, and the current specification uses them instead of replacing them. +3. **Given** two documents disagree about current behavior, **When** the pass settles the disagreement, **Then** the lower-authority document is corrected, or the disagreement is listed as unresolved with the two statements side by side. +4. **Given** the architecture description claims a behavior the current specification or an accepted decision no longer holds, **When** the pass finishes, **Then** the description matches the higher authority or the mismatch is on the unresolved list. + +### Edge Cases + +- The product requirements document narrates finished work, including capabilities that were later removed, in the same document as current requirements. The pass carries forward only what is still true, then deletes the document. +- An active issue describes a plan that already shipped by a different approach, so ticking its original checklist would describe files and steps that never landed. +- A glossary banner says the language is still under review while individual entries are already settled. Settled entries govern; the banner is corrected or the unsettled entries are called out. +- A research note is the only write-up of an idea that later became an accepted decision. The note stays historical; the accepted decision stays the authority. +- Deferred multi-monitor work is mentioned beside current requirements. It stays deferred. +- The install guide, release history, or working agreements contradict the current specification. Those documents are not converted wholesale; the contradicting sentence is corrected or listed. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: The pass MUST inventory the product requirements document, the issue queue (active, deferred, finished, and closed without being built), the domain glossary, the architecture description, accepted decision records, research notes, and the already accepted render-domain specification, and MUST classify each source as an accepted decision, a verified observation of the product today, present direction, an unresolved assumption, or historical context. +- **FR-002**: The pass MUST produce one current product specification of what the ranch does today. Carried-forward statements MUST cite their source and record that they were checked against the product as it exists now. +- **FR-003**: The current specification MUST use the glossary's settled words. Where an older document uses a retired word for the same idea, the specification uses the settled word. +- **FR-004**: The current specification MUST state current capabilities, limits, and non-goals. It MUST NOT treat a history of finished phases as requirements. +- **FR-005**: The pass MUST classify every active issue as still to do, already satisfied, superseded, or deferred. Already satisfied and superseded issues MUST leave the active queue. Deferred issues MUST stay visibly deferred. Issues closed without being built MUST stay closed. +- **FR-006**: Each issue that remains to do MUST keep a single observable completion promise and MUST name the current specification, or a follow-on specification, that owns that promise. +- **FR-007**: A follow-on specification MUST be created only for undone, user-visible behavior that the current specification does not already cover. The pass MUST NOT replace the issue queue with a task list. +- **FR-008**: The domain glossary and accepted decision records MUST keep their current roles. The pass MUST NOT absorb them into the specification and remove them. +- **FR-009**: After the current specification exists, the pass MUST delete the product requirements document from the working tree. Finished issue write-ups and research notes MUST remain findable and MUST be marked as historical, so they are not current requirements. +- **FR-010**: Where two inventoried documents disagree about current behavior, the pass MUST correct the lower-authority document, or MUST list the disagreement as unresolved with both statements visible. The pass MUST NOT leave a silent conflict. +- **FR-011**: The already accepted render-domain specification MUST remain the record of that shipped work. +- **FR-012**: The pass MUST NOT change what a person can do with the ranch. No capability is added or removed except on paper. +- **FR-013**: The issue index MUST match the classification: active work, deferred work, and the notes for work closed without being built. + +### Key Entities + +- **Current product specification**: The single description of what the ranch does today, what it will not do, and the limits a reader can check. It replaces the product requirements document as the requirements authority. +- **Follow-on specification**: A separate description of undone, user-visible behavior that the current specification does not already cover. It exists only when that gap is real. +- **Issue**: One slice of work with one observable promise. Active issues are still to do. Deferred, finished, and closed-without-building issues are not active requirements. +- **Domain glossary**: The settled names for the ranch's ideas. The specification uses these names and does not redefine them. +- **Decision record**: An accepted choice about how the product is shaped. Only accepted records govern. Draft, rejected, and superseded records are context. +- **Historical source**: A finished issue write-up or a research note. Findable, and marked so it is not a current requirement. The old product requirements document is not kept. +- **Pass record**: The inventory, the classification of each source, and the list of disagreements that were corrected or left unresolved. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: A reader who has not seen the repository can list the product's current capabilities, limits, and non-goals from the current specification alone, without opening the old product requirements document. +- **SC-002**: 100% of issues that were active at the start of the pass are classified, and the active queue contains only issues that are still undone. +- **SC-003**: Every remaining active issue cites exactly one owning specification and states exactly one observable promise. +- **SC-004**: Zero silent conflicts remain between the current specification, the glossary, accepted decision records, and the architecture description. Every disagreement found is either corrected in the lower-authority document or present on a visible unresolved list. +- **SC-005**: The product requirements document is absent from the working tree. 100% of finished issue write-ups and research notes remain findable and are identifiable as historical. +- **SC-006**: After the pass, a person using the ranch can do the same things they could do before it. The pass changes documents only. + +## Assumptions + +- The project's adopted specification format is the one already in use: a current specification for user-visible intent, accepted decision records for durable choices, the glossary for names, and issues as the slices that get built. This pass uses that format. It does not invent a second one. +- One current product specification is the conversion of the product requirements document. Remaining issues stay issues. A follow-on specification is added only for a real gap, not one per issue. +- The product requirements document is the input to the current specification, then it is deleted. Spec Kit is the only planning format that remains. Finished issue write-ups stay in their archive. Research notes stay. The glossary, accepted decision records, the architecture description, and the issue queue stay, because they are not the old plan. +- The render-domain specification already accepted for that shipped work is left as that record. +- Install instructions, release history, and day-to-day working agreements are not converted into specifications. A sentence in them that contradicts the current specification is corrected or added to the unresolved list. +- Deferred work stays deferred, and work already closed without being built stays closed, unless the owner gives a new direction during the pass. +- Authority, when documents disagree, follows the order the project already uses: project rules, then accepted decisions, then the current specification, then an issue. Historical sources are outside that order. +- "Checked against the product as it exists now" means checked against the behavior and the accepted records on the current main line, not against an old plan that was never what landed. diff --git a/specs/002-speckit-docs-pass/tasks.md b/specs/002-speckit-docs-pass/tasks.md new file mode 100644 index 0000000..cbfc2b2 --- /dev/null +++ b/specs/002-speckit-docs-pass/tasks.md @@ -0,0 +1,200 @@ +# Tasks: Spec Kit Docs Pass + +**Input**: Design documents from `specs/002-speckit-docs-pass/` + +**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/, quickstart.md + +**Tests**: No product tests. This pass edits Markdown only. Proof is the reader checks in `specs/002-speckit-docs-pass/quickstart.md` and a final `task check`. + +**Consolidation scope (2026-10-15)**: The owner subsequently requested combining this pass with +the saved foundation and the existing HTML entrypoint move. Those additional changes are recorded +in `pass-record.md`; the document-only boundaries below describe the original pass. No application +TypeScript or Rust behavior is changed, and new product/follow-on specs remain Draft. + +**Organization**: Tasks are grouped by user story. The pass record is foundational. User Story 2 waits for the current specification. User Story 3 waits for the queue, because `PRD.md` is deleted only after the spec exists and active issues no longer cite it. + +## Format: `[ID] [P?] [Story] Description` + +- **[P]**: Can run in parallel (different files, no dependencies) +- **[Story]**: Which user story this task belongs to (US1, US2, US3) +- Every task includes an exact file path + +## Path Conventions + +Documents only, at the repository root: + +- `specs/003-ranch-today/spec.md` — Draft current product specification +- `specs/002-speckit-docs-pass/pass-record.md` — inventory, classification, unresolved list +- `PRD.md` — read during the pass, then deleted +- `CONTEXT.md`, `docs/adr/`, `docs/architecture.md`, `docs/research/`, `issues/`, `README.md` +- Do not edit `src/`, `src-tauri/`, `crates/`, manifests, `Taskfile.yaml`, `src/types/generated/`, `specs/001-render-domain-seam/**`, or `.specify/memory/constitution.md` + +## Phase 1: Setup (Shared Infrastructure) + +**Purpose**: Reserve the product-spec directory and keep Spec Kit pointed at this feature + +- [x] T001 Confirm `.specify/feature.json` contains `"feature_directory": "specs/002-speckit-docs-pass"` and do not edit that file +- [x] T002 Create the directory `specs/003-ranch-today/` and do not write `specs/003-ranch-today/spec.md` in this task + +--- + +## Phase 2: Foundational (Blocking Prerequisites) + +**Purpose**: Inventory every required source before any requirements text is written or any issue file is moved + +**⚠️ CRITICAL**: No user story work can begin until this phase is complete + +- [x] T003 Create `specs/002-speckit-docs-pass/pass-record.md` with the sections How to read this, Inventory, Issue classification, Corrected, and Unresolved, per `specs/002-speckit-docs-pass/contracts/pass-record.md`. How to read this states four rules: `PRD.md` is deleted only after `specs/003-ranch-today/spec.md` exists; remaining historical sources are not requirements; the current description is `specs/003-ranch-today/spec.md` and its status is Draft; accepted decisions remain in `docs/adr/` and names remain in `CONTEXT.md`. Unresolved is `None.` until a later task cannot decide a disagreement +- [x] T004 Add one inventory row in `specs/002-speckit-docs-pass/pass-record.md` for each of `PRD.md`, `CONTEXT.md`, `docs/architecture.md`, `docs/adr/0001-two-apps-over-one-renderer.md`, `docs/adr/0002-agent-hook-transport.md`, `docs/adr/0003-rust-owned-render-scene.md`, `docs/research/serena-multi-agent.md`, `docs/research/manual-github-release-retention.md`, `docs/research/claude-codex-session-terminology.md`, and `specs/001-render-domain-seam/spec.md`. Columns are Source, Class, Checked, and Disposition. Class is one or more of: Accepted decision, verified observation, present direction, unresolved assumption, historical context. Disposition is one of: Kept as authority, carried into `specs/003-ranch-today/spec.md`, marked historical, deleted after carry-forward, left deferred, listed as unresolved. Set `PRD.md` to deleted after carry-forward. Set each ADR, all of which are Accepted, to Kept as authority. Set `specs/001-render-domain-seam/spec.md` to Kept as authority and do not edit that file +- [x] T005 Add inventory rows in `specs/002-speckit-docs-pass/pass-record.md` for `issues/README.md`, `issues/031-notification-source-settings.md`, `issues/051-ranch-animal-vocabulary-seam.md`, `issues/056-task-timer-binding.md`, `issues/059-self-describing-hook-frame.md`, `issues/060-session-staleness-sweep.md`, `issues/061-hook-change-events.md`, `issues/062-stable-hook-client-path.md`, `issues/icebox/021-all-monitors-default.md`, `issues/icebox/022-wrangle.md`, one shared row for the 49 files under `issues/done/`, and the closed-without-building notes for 042, 045, 046, and 047. Record that `issues/README.md` lists 046 as closed without implementation while `issues/done/046-timer-expiry-service-extraction.md` exists, and do not choose which statement wins in this task + +**Checkpoint**: A reader can take any inventoried source and see its class. No issue file has been moved and `PRD.md` still exists. + +--- + +## Phase 3: User Story 1 - Read the product as it is now (Priority: P1) 🎯 MVP + +**Goal**: One Draft specification states today's capabilities, limits, and non-goals in the glossary's settled words + +**Independent Test**: Hand a reader who has not seen the repository only `specs/003-ranch-today/spec.md`. They can name current capabilities, limits, and non-goals, and they do not need `PRD.md` to do it. + +### Implementation for User Story 1 + +- [x] T006 [US1] Write `specs/003-ranch-today/spec.md` per `specs/002-speckit-docs-pass/contracts/current-product-spec.md` with status `Draft`, feature branch `003-ranch-today`, and an input line that this specification converts the product requirements document into the current description. Include user scenarios of a person using the ranch today, edge cases that are true today, functional requirements, limits and non-goals, and a sources appendix. Carry a statement forward only when it is still true on `main` +- [x] T007 [US1] Revise `specs/003-ranch-today/spec.md` so it uses only settled names from `CONTEXT.md`: Animal, Species, Motion, Focus, Task, Timer, Limit, Over Limit, Harness, Agent Session, Session Activity, Hook Firing, Pen, Agents as Animals, DisplaySpace, Gather, and Settings. Pig is the Species and the sprite asset name, not the word for every Animal. Limit is the soft threshold. Gather brings Animals back onto the primary display. Settings is the stored configuration. Preferences appears only as the macOS menu label for the window that edits Settings +- [x] T008 [US1] Revise `specs/003-ranch-today/spec.md` so requirements omit implementation phases, a localhost HTTP API, a proposal queue, deferred multi-monitor default-on, and wrangle. State the render outcome in one short capability: Focus and Agent Session each project Animals, the shared renderer does not import either domain, and Pig is the only Species. Name `specs/001-render-domain-seam/spec.md` as the record of that work and do not copy its requirements, `CONTEXT.md`, or any accepted ADR +- [x] T009 [US1] Add a sources appendix entry in `specs/003-ranch-today/spec.md` for every carried-forward requirement, in the form `- : source \`\` — checked against \`main\` on . .` Cite `docs/adr/` or `.specify/memory/constitution.md` when that is the source. Omit statements that are no longer true. In `specs/002-speckit-docs-pass/pass-record.md`, set Disposition to `carried into specs/003-ranch-today/spec.md` only for rows whose statements were actually carried + +**Checkpoint**: User Story 1 is testable from `specs/003-ranch-today/spec.md` alone. `PRD.md` is still present until User Story 3. + +--- + +## Phase 4: User Story 2 - Trust the work still to do (Priority: P2) + +**Goal**: The active queue contains only undone issues, each with one promise and one owning specification + +**Independent Test**: Compare `issues/README.md` and the files still in `issues/` with the product on `main`. Every active item is still undone, names one observable outcome, and cites one owning specification. Deferred items stay in `issues/icebox/`. Issues closed without being built stay closed. + +### Implementation for User Story 2 + +- [x] T010 [US2] Add one classification row in `specs/002-speckit-docs-pass/pass-record.md` for issues 031, 051, 056, 059, 060, 061, 062, 021, 022, 042, 045, 046, and 047. Columns are Issue, Class, Evidence, and Owning specification. Class is exactly one of: still to do, already satisfied, superseded, deferred. Judge the completion promise against `main`, not the original checklist. still to do means the promise is not true, the owner has not deferred it, and later work has not replaced it. already satisfied means the promise is true on `main`, including when a different approach landed. superseded means later work replaced the issue or its premise was wrong; if the outcome is nevertheless true, classify it already satisfied instead. deferred means the owner has deferred it. If the 046 note in `issues/README.md` and `issues/done/046-timer-expiry-service-extraction.md` still disagree after that check, correct the lower-authority line or add an unresolved entry with both statements +- [x] T011 [US2] Move each issue classified already satisfied from `issues/` to `issues/done/` and add this note at the top of that file: `> **Shipped.** The completion promise is true on \`main\`. ` If none are already satisfied, write that in `specs/002-speckit-docs-pass/pass-record.md` and move nothing +- [x] T012 [US2] Move each issue classified superseded, whose outcome did not ship, from `issues/` to `issues/done/`, add it to the closed-without-building list in `issues/README.md`, and add this note at the top of that file: `> **Closed without building.** This file is not a current requirement.` Leave 042, 045, 046, and 047 closed. If none of the active files are superseded, write that in `specs/002-speckit-docs-pass/pass-record.md` and move nothing +- [x] T013 [P] [US2] In `issues/icebox/021-all-monitors-default.md` and `issues/icebox/022-wrangle.md`, replace the whole `## Parent PRD` section with `## Owning specification` followed by `None. Deferred. Not a requirement of \`specs/003-ranch-today/spec.md\`.` Leave both files in `issues/icebox/`. Do not add either outcome to `specs/003-ranch-today/spec.md` +- [x] T014 [US2] For each issue that remains in `issues/` outside `issues/done/` and `issues/icebox/`, replace the whole `## Parent PRD` section in that issue file with `## Owning specification` and exactly one path, and keep exactly one `## Completion promise`. Use `specs/003-ranch-today/spec.md` plus a requirement id or section name, unless all three gap-test conditions are true: the promise describes behavior a person using the ranch can observe; `specs/003-ranch-today/spec.md` does not already state that outcome as a capability or a limit; the promise is not only an internal seam, a rename, or a regression fix of behavior that specification already states. When all three are true, create only `specs/-/spec.md` with status Draft, user scenarios, requirements, and success criteria, and no `plan.md` or `tasks.md`, and cite that path +- [x] T015 [US2] Update `issues/README.md` so the priority queue and the architecture queue contain only issues classified still to do, the icebox section still lists `issues/icebox/021-all-monitors-default.md` and `issues/icebox/022-wrangle.md`, the closed-without-building notes match the classification, and the documented issue file shape shows `## Owning specification` instead of `## Parent PRD` + +**Checkpoint**: The active queue is only undone work. User Story 1's specification is unchanged except that no deferred outcome was added to it. + +--- + +## Phase 5: User Story 3 - Tell history from authority (Priority: P3) + +**Goal**: `PRD.md` is gone, remaining historical sources are marked, and every disagreement is corrected or listed + +**Independent Test**: Take each source in `specs/002-speckit-docs-pass/pass-record.md`. A reader can say which role it has. `PRD.md` is absent. Every disagreement with a higher authority is either corrected in the lower document or present as an unresolved entry with both statements. + +### Implementation for User Story 3 + +- [x] T016 [US3] Delete `PRD.md` after `specs/003-ranch-today/spec.md` and `specs/002-speckit-docs-pass/pass-record.md` both exist. Do not leave a banner or a stub. In `specs/002-speckit-docs-pass/pass-record.md`, state that `PRD.md` was removed and keep its disposition as deleted after carry-forward +- [x] T017 [P] [US3] In `README.md`, replace the sentence that says to see `PRD.md` for the design so it points at `specs/003-ranch-today/spec.md`. Do not tell a reader to open `PRD.md` +- [x] T018 [P] [US3] Insert this banner immediately under the title of `docs/research/serena-multi-agent.md`: `> **Historical.** This note is evidence. It is not a current requirement and not an accepted decision. The constitution, accepted ADRs, and the current product specification govern where they disagree with it. See [specs/002-speckit-docs-pass/pass-record.md](../../specs/002-speckit-docs-pass/pass-record.md).` +- [x] T019 [P] [US3] Insert the same historical banner immediately under the title of `docs/research/manual-github-release-retention.md` +- [x] T020 [P] [US3] Insert the same historical banner immediately under the title of `docs/research/claude-codex-session-terminology.md` +- [x] T021 [P] [US3] Create `issues/done/README.md` with the heading `# Finished issues` and the banner `> **Historical.** These write-ups record what was asked at the time. They are not current requirements. A file marked **Shipped** had its outcome become true, including when the landed approach differs from the write-up. A file marked **Closed without building** was not built. The active queue is [../README.md](../README.md).` Do not add that banner to each existing file under `issues/done/` +- [x] T022 [P] [US3] In `CONTEXT.md`, read every entry and do not rewrite a settled definition. If every entry is settled, replace the under-review blockquote with `> Settled names for the ranch. Specifications, issues, and UI copy use these words. The current product specification does not redefine them.` If any entry is not settled, mark that entry with `**Unsettled**` on its own line under the term and replace the banner with `> Settled entries govern. Entries marked **Unsettled** do not. The current product specification uses only settled names.` +- [x] T023 [US3] Compare `docs/architecture.md` with `.specify/memory/constitution.md`, `docs/adr/0001-two-apps-over-one-renderer.md`, `docs/adr/0002-agent-hook-transport.md`, `docs/adr/0003-rust-owned-render-scene.md`, and `specs/003-ranch-today/spec.md`. Correct the lower-authority sentence in `docs/architecture.md`, or add an unresolved entry to `specs/002-speckit-docs-pass/pass-record.md` as `### U- ` with bullets `Higher: \`\` — `, `Lower: \`\` — `, and `Check: `. Do not convert `docs/architecture.md` into a specification. Do not rewrite the three ADR bodies +- [x] T024 [US3] Read `CHANGELOG.md` and `CLAUDE.md` for a sentence that contradicts `specs/003-ranch-today/spec.md`. Correct that sentence in the file that contains it, or record it on the Corrected or Unresolved list in `specs/002-speckit-docs-pass/pass-record.md`. Do not rewrite either file wholesale. A corrected disagreement is a Corrected list item: path, one sentence, higher authority cited + +**Checkpoint**: `PRD.md` is absent. Finished write-ups and research notes are findable and marked historical. The glossary and accepted ADRs still hold their roles. + +--- + +## Phase 6: Polish & Cross-Cutting Concerns + +**Purpose**: Prove the pass changed documents only and that the three reader checks hold together + +- [x] T025 Walk sections 1 through 3 of `specs/002-speckit-docs-pass/quickstart.md` and fix any miss in the file that check names +- [x] T026 Confirm application TypeScript, Rust, generated types, dependency manifests, and `Taskfile.yaml` are unchanged against `main`. The separately authorized five HTML entrypoint moves are checked through content comparison, the same dev page URLs, and production output paths per `quickstart.md` +- [x] T027 From the repository root, run `task check` as defined in `Taskfile.yaml` and confirm the gate passes +- [x] T028 Confirm `.specify/feature.json` still contains `"feature_directory": "specs/002-speckit-docs-pass"` + +--- + +## Dependencies & Execution Order + +### Phase Dependencies + +- **Setup (Phase 1)**: No dependencies +- **Foundational (Phase 2)**: Depends on Setup. Blocks every user story +- **User Story 1 (Phase 3)**: Depends on Foundational. Does not wait for User Story 2 or 3 +- **User Story 2 (Phase 4)**: Depends on User Story 1, because an owning-spec citation and the gap test require `specs/003-ranch-today/spec.md` +- **User Story 3 (Phase 5)**: Depends on User Story 2, because active and deferred issues must stop citing `PRD.md` before that file is deleted +- **Polish (Phase 6)**: Depends on User Story 3 + +### User Story Dependencies + +- **User Story 1 (P1)**: Starts after the pass record inventory. No dependency on the queue or on deleting `PRD.md` +- **User Story 2 (P2)**: Starts after User Story 1. Does not delete `PRD.md` and does not rewrite `specs/001-render-domain-seam/` +- **User Story 3 (P3)**: Starts after User Story 2. Deletes `PRD.md` and marks the sources that remain + +### Within Each User Story + +- User Story 1 edits `specs/003-ranch-today/spec.md` in order: draft, vocabulary, boundaries, citations +- User Story 2 classifies in the pass record before moving files, then updates `issues/README.md` last +- User Story 3 deletes `PRD.md` and settles `docs/architecture.md` in the pass record before the polish read. Research banners, the archive mark, the glossary banner, and the README pointer touch different files and can run beside the deletion + +### Parallel Opportunities + +- T001 and T002 touch different paths and can run together +- T013 can run beside T011 and T012. It edits only the two icebox files +- T017, T018, T019, T020, T021, and T022 can run together. They edit different files +- User stories themselves are sequential + +--- + +## Parallel Example: User Story 3 + +```text +Task: "T017 Point README.md at specs/003-ranch-today/spec.md" +Task: "T018 Banner on docs/research/serena-multi-agent.md" +Task: "T019 Banner on docs/research/manual-github-release-retention.md" +Task: "T020 Banner on docs/research/claude-codex-session-terminology.md" +Task: "T021 Create issues/done/README.md" +Task: "T022 Correct the banner in CONTEXT.md" +``` + +T016, T023, and T024 stay in sequence because they share `specs/002-speckit-docs-pass/pass-record.md`. + +--- + +## Implementation Strategy + +### MVP First (User Story 1 Only) + +1. Complete Phase 1 and Phase 2 +2. Complete Phase 3 +3. Stop and hand a reader only `specs/003-ranch-today/spec.md` +4. Continue only after that reader can name capabilities, limits, and non-goals + +### Incremental Delivery + +1. Setup and the pass record produce the inventory without changing the product description +2. User Story 1 adds the current specification. `PRD.md` is still the old document beside it +3. User Story 2 makes the active queue match work that is still undone +4. User Story 3 deletes `PRD.md` and marks what remains, so Spec Kit is the only planning document + +### Sequential Story Strategy + +One implementer should finish the stories in order P1, then P2, then P3. The parallel work is inside User Story 3, on files that do not share the pass record. + +--- + +## Notes + +- [P] tasks use different files and do not wait on each other +- [US1], [US2], and [US3] map to the three stories in `specs/002-speckit-docs-pass/spec.md` +- Do not edit application code. A green `task check` does not excuse a diff under `src/`, `src-tauri/`, or `crates/` +- Do not edit `specs/001-render-domain-seam/**` +- Leave `specs/003-ranch-today/spec.md` at status Draft +- Commit after each phase checkpoint diff --git a/specs/003-ranch-today/spec.md b/specs/003-ranch-today/spec.md new file mode 100644 index 0000000..8521984 --- /dev/null +++ b/specs/003-ranch-today/spec.md @@ -0,0 +1,185 @@ +# Feature Specification: Ranch Today + +**Feature Branch**: `003-ranch-today` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: This specification converts the product requirements document into the current description of what the ranch does today. It stays Draft until the owner approves it. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - Glance and know what is open (Priority: P1) + +A person looks at the screen and sees one Animal for each Focus, wandering slowly on the enabled displays. Pig is the only Species. The Animals do not interrupt other work. A glance is enough to know what is open. + +**Why this priority**: The ranch is a peripheral reminder. If a glance does not show the open Focuses, the product is not doing its job. + +**Independent Test**: Create two Focuses and look at the overlay. Two Pig Animals wander. Clicking empty overlay space reaches the app underneath. + +**Acceptance Scenarios**: + +1. **Given** two Focuses exist, **When** the person looks at the overlay, **Then** two Animals of Species Pig are wandering on the enabled displays. +2. **Given** the pointer is not over an Animal, **When** the person clicks, **Then** the click reaches whatever is underneath the overlay. +3. **Given** the Animals are wandering, **When** the person is working in another app, **Then** the ranch does not raise a window or demand attention on its own, except for a notification the person has allowed. + +--- + +### User Story 2 - Work a Focus from its Animal (Priority: P1) + +The person clicks a Focus Animal and gets a card: the Focus title, its Tasks, and its Timers. They can rename, duplicate, or delete the Focus, and add, edit, Complete, or Delete Tasks. They can start, restart, or Clear a Timer on the Focus or on a Task. Clicking elsewhere or pressing Escape closes the card. + +**Why this priority**: The glance only helps if the person can change the work from the Animal they clicked. + +**Independent Test**: Click one Focus Animal, add a Task, Complete it, start a Timer, and close the card. The markdown for that Focus matches what the card showed. + +**Acceptance Scenarios**: + +1. **Given** a Focus Animal, **When** the person clicks it, **Then** a card opens beside it with the title, the Tasks, and the Timer controls. +2. **Given** the card is open, **When** the person adds, edits, Completes, or Deletes a Task, **Then** the Focus file changes to match. +3. **Given** a running Focus Timer, **When** time passes, **Then** that Animal grows from its base size toward a larger size, and when the Timer is Expired the Animal rests, looks ghostly, faces away, and appears in the tray's Expired section. +4. **Given** an Expired Focus Timer, **When** the person adds a Task, **Then** the Focus is revived and the Animal returns to normal. +5. **Given** a Task Timer Expires, **When** the person looks at the ranch, **Then** that Task shows Expired and a notification can fire, and the Animal's size, motion, and the tray's Expired section do not change because of that Task Timer. + +--- + +### User Story 3 - Run the ranch from the tray (Priority: P2) + +The person uses the tray to create a Focus, delete one, Gather Animals back to the primary display, turn Agents as Animals on or off, open Settings, and quit. The tray icon turns red while the ranch is Over Limit. + +**Why this priority**: Creation, deletion, and Gather are how the person keeps the ranch matched to the work they mean to hold. + +**Independent Test**: From the tray, create a Focus, Gather, delete the Focus, and open Settings. Each action does only that thing. + +**Acceptance Scenarios**: + +1. **Given** the tray menu, **When** the person chooses New Focus and enters a title, **Then** a new Animal appears. +2. **Given** Animals have been dragged off the primary display, **When** the person chooses Gather, **Then** they return to the primary display. +3. **Given** delete confirmation is on, **When** the person deletes a Focus, **Then** the ranch asks first and the Animal disappears only after confirmation. + +--- + +### User Story 4 - Hand-edit the markdown (Priority: P2) + +The person edits a Focus file in their own editor. The overlay catches up within about a second. Tasks are checkbox lines. An optional Timer sidecar sits beside the Focus file. + +**Why this priority**: Markdown is the canonical state. The app is a projection of those files. + +**Independent Test**: Append a checkbox line to a Focus file and save. The card shows the new Task without using the app to add it. + +**Acceptance Scenarios**: + +1. **Given** a Focus file, **When** the person adds or Completes a checkbox line and saves, **Then** the Animal's Task list matches the file. +2. **Given** a Task Timer sidecar stores Timers by Task position, **When** the person reorders or inserts Tasks by hand, **Then** a Timer can sit on a different Task than the one it was attached to. + +--- + +### User Story 5 - See an agent without tracking it as work (Priority: P3) + +The person can turn on Agents as Animals. Each running Claude Code Agent Session appears as an Animal. Those Animals are not Focuses: the person did not create them, they are not editable, they do not count toward Limits, and they disappear from the screen when the setting is turned off. The Claude plugin stays installed. + +**Why this priority**: Agent activity is a second thing the person may want to see. It must not become user-owned work. + +**Independent Test**: Turn Agents as Animals on with one Claude Code session running. An Animal appears that cannot be opened as a Focus. Turn the setting off. That Animal is gone and the Focus Animals remain. + +**Acceptance Scenarios**: + +1. **Given** Agents as Animals is off, **When** a Claude Code session is running, **Then** no Agent Session Animal is shown. +2. **Given** the person turns Agents as Animals on and the plugin is missing, **When** the tray offers Install Hooks, **Then** nothing is installed until the person chooses that action. +3. **Given** an Agent Session Animal is showing, **When** the person clicks it, **Then** no Focus card opens. +4. **Given** Agents as Animals is on, **When** the person opens Agent Hooks, **Then** they can see whether hooks are in place, which sessions the ranch is holding, and recent Hook Firings, including a Firing that changed nothing. + +### Edge Cases + +- The first launch creates one example Focus so the ranch is not empty. A marker stops that example from returning after the person deletes every Focus. +- A missing or corrupt Timer sidecar is treated as no Timer. It does not block the Focus file. +- Going Over Limit still saves the Focus or Task. The tray icon turns red, and one notification fires for that crossing. +- Only the primary display is enabled until the person enables more in Settings. Animals do not wander through gaps between displays. +- Settings changed in the app apply without a restart. A hand-edit of the settings file applies on the next launch. +- On Windows the ranch builds and stores data under the platform data directory. It does not receive Hook Firings there. +- A late Hook Firing is not ignored because of its age. Stop and a failed stop are not shown as different kinds of ending. The overlay learns that sessions changed by reading the list again, not by receiving the change itself. +- The ranch does not remove an older direct hook entry it once wrote into Claude's settings. A new install uses the Claude plugin and a stable local client. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: The ranch MUST keep each Focus as a directory of markdown under the Ranch data directory, with Tasks as checkbox lines in the Focus file. Optional sidecars MUST hold the Focus Timer and the Task Timers. The person MUST be able to create and change a Focus or Task from the app or by editing those files. Timer expiry MUST update only Timer state. +- **FR-002**: Completing a Task MUST keep it in the Focus, shown as done. Deleting a Task MUST remove it. Clear MUST apply to a Timer, not to a Task or a Focus. +- **FR-003**: A Timer MUST belong to exactly one Focus or one Task. The person MUST be able to start one from the built-in durations of 10, 30, or 60 minutes, or add a custom duration as a saved chip, and MUST be able to restart or Clear it. Saved chips MUST be shared across timer pickers and persisted in Settings; removing or clearing saved chips MUST leave the built-ins available and MUST NOT clear a running Timer. An Expired Focus Timer MUST be cleared when a Task is added. A Task Timer MUST NOT be revived. +- **FR-004**: The ranch MUST show one Animal per Focus on the enabled displays, using Species Pig. The person MUST be able to drag an Animal and toss it. Gather MUST bring Animals back to the primary display. The overlay MUST let clicks through everywhere except on an Animal. +- **FR-005**: Clicking a Focus Animal MUST open a card for that Focus and MUST NOT open a card for an Agent Session Animal. The card MUST close when the person clicks outside it or presses Escape. +- **FR-006**: The tray MUST offer New Focus, delete, Gather, Agents as Animals, Settings, and quit. Delete MUST ask first when confirmation is on. The tray icon MUST turn red while the ranch is Over Limit. +- **FR-007**: A Limit MUST be a soft threshold. The defaults MUST be 5 Focuses and 7 Tasks in one Focus, and the person MUST be able to change them in Settings. Crossing a Limit MUST NOT block the write. Agent Sessions MUST NOT count toward a Limit. +- **FR-008**: Settings MUST be a file the app edits from the Preferences window, labeled Preferences only as the macOS menu name. Changes made in the app MUST apply without a restart. +- **FR-009**: DisplaySpace MUST be the enabled displays. Animals MUST NOT move through the gaps between them. The primary display MUST be the one enabled until the person enables others. +- **FR-010**: Agents as Animals MUST be off until the person turns it on. An Agent Session MUST be observed from Claude Code, never created by the person, never stored as a Focus, and never editable. Turning the setting off MUST hide those Animals and MUST leave the Claude plugin installed. +- **FR-011**: Installing or repairing the Claude plugin MUST happen only after an explicit Install Hooks action. A Hook Firing MUST be recorded even when it changed nothing. The Agent Hooks window MUST show wiring, live sessions, and recent Firings. +- **FR-012**: The running ranch MUST make no outbound network call, expose no network API, collect no telemetry, and call no language model. The only frontend-to-core boundary MUST be Tauri IPC. + +### Limits + +- **FR-013**: Task Timers MUST stay indexed to Task position. A hand-edit that reorders or inserts Tasks can move a Timer onto another Task. That drift is not repaired today. +- **FR-014**: A Hook Firing that arrives late MUST still be eligible to apply. The ranch MUST NOT yet tell a turn that ended from a turn that died as two different Firings. A session change MUST be learned by reading the session list again. +- **FR-015**: The ranch MUST NOT remove an older direct hook entry left in Claude's settings by a previous build. New hook delivery MUST go through the Claude plugin and the stable client under the Ranch data directory. +- **FR-016**: macOS MUST be the design target. Windows and Linux packages MUST still build. Hook delivery MUST NOT be available on Windows. +- **FR-017**: The ranch MUST NOT demand attention except through a notification the person has turned on, or through a window the person opened. + +### Non-goals + +- **FR-018**: The ranch MUST NOT sync, host multiple users, or import work from Jira, GitHub, or Linear. +- **FR-019**: The ranch MUST NOT offer a network API, a slash command, or any writer of Focuses and Tasks other than the person and Timer expiry. +- **FR-020**: The ranch MUST NOT complete Tasks on its own, merge Focuses on its own, or forward notifications into a Harness. +- **FR-021**: The ranch MUST NOT enable every display on first launch, and MUST NOT offer Wrangle. Gather is the action that brings Animals back. +- **FR-022**: The ranch MUST NOT ship a second Species, and MUST NOT read a Harness other than Claude Code. + +### Key Entities + +- **Focus**: User-owned work, stored as markdown. Shown as an Animal. +- **Task**: One checkbox line in a Focus. +- **Timer**: A countdown on one Focus or one Task. +- **Animal**: The sprite that wanders. Focus and Agent Session each project their own. +- **Agent Session**: One observed Claude Code run. Not user-owned work. +- **Limit**: A soft threshold on open Focuses or Tasks. +- **Settings**: The stored configuration. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: A person can name their open Focuses by looking at the overlay, without opening another tool. +- **SC-002**: A person can add, Complete, and Delete a Task, and start or Clear a Timer, from the Focus Animal's card, and the Focus file matches. +- **SC-003**: A hand-edit of a Focus file shows on the overlay within about a second. +- **SC-004**: Going past a Limit still saves, warns once, and does not count Agent Sessions. +- **SC-005**: With Agents as Animals off, no Agent Session Animal is shown. With it on, those Animals are visible and cannot be edited as Focuses. +- **SC-006**: The running app makes no outbound product network call. + +## Sources + +Checked against `main` on 2026-10-15. + +- FR-001: source `.specify/memory/constitution.md` (User-Owned Local State) and `docs/architecture.md` (Persistence) — checked against `main` on 2026-10-15. Focus directories, checkbox Tasks, and Timer sidecars are the stored state. +- FR-002: source `CONTEXT.md` (Complete, Delete, Clear) — checked against `main` on 2026-10-15. The card still completes a Task in place and deletes a Task by removing its line. +- FR-003: source `docs/architecture.md` (Timers), `CONTEXT.md` (Timer, Revive), and PR #89 (`8fa695d`) — checked against `main` on 2026-10-15. Built-ins are 10, 30, and 60 minutes; custom chips persist in `timers.saved_minutes`, and timer edits preserve other windows' saves. `Timers` starts, clears, revives, and expires. Adding a Task revives an Expired Focus Timer. A Task Timer is not revived. +- FR-004: source `docs/adr/0003-rust-owned-render-scene.md` and `docs/architecture.md` (Renderer read model, Core interaction loop) — checked against `main` on 2026-10-15. Rust owns the scene and the Pig profile. Gather and drag-and-toss still behave as the interaction loop describes. +- FR-005: source `docs/adr/0001-two-apps-over-one-renderer.md` — checked against `main` on 2026-10-15. Selection resolves only to a Focus. An Agent Session Animal has no card. +- FR-006: source `docs/architecture.md` (Application) and `README.md` (Day-to-day usage) — checked against `main` on 2026-10-15. The tray still offers those actions, and the icon turns red while Over Limit. +- FR-007: source `.specify/memory/constitution.md` (Limits) and `docs/architecture.md` (Limits) — checked against `main` on 2026-10-15. Defaults remain 5 and 7. Writes past a Limit succeed. +- FR-008: source `CONTEXT.md` (Settings) and `docs/architecture.md` (Configuration) — checked against `main` on 2026-10-15. The Preferences window persists Settings and applies them without a restart. +- FR-009: source `CONTEXT.md` (DisplaySpace) and `docs/architecture.md` (Display spanning) — checked against `main` on 2026-10-15. The primary display is the default enabled display. Animals stay inside visible regions. +- FR-010: source `docs/adr/0001-two-apps-over-one-renderer.md` and `docs/architecture.md` (Agents as Animals) — checked against `main` on 2026-10-15. The setting is off by default. Sessions are in memory. Turning the setting off drops them and leaves the plugin. +- FR-011: source `.specify/memory/constitution.md` (Explicit, User-Controlled Integrations) and `docs/architecture.md` (Hook install, Journal, Agent Hooks window) — checked against `main` on 2026-10-15. Install is an explicit action. The journal keeps Firings that changed nothing. +- FR-012: source `.specify/memory/constitution.md` (User-Owned Local State, product constraints) — checked against `main` on 2026-10-15. No Ranch network API is present. IPC is Tauri. +- FR-013: source `docs/architecture.md` (Timers) and `crates/storage/src/focus_store.rs` — checked against `main` on 2026-10-15. Task Timers are stored by index. No reorder repair is present. +- FR-014: source `docs/adr/0002-agent-hook-transport.md` and `docs/architecture.md` (Events, Delivery) — checked against `main` on 2026-10-15. Stop and a failed stop both become idle. No late-frame stamp is applied. The change event does not carry the change. +- FR-015: source `docs/architecture.md` (Stable client, Hook install) and `src-tauri/src/app/claude_hook.rs` — checked against `main` on 2026-10-15. The app copies a stable client and does not write Claude's settings file. It also does not remove older direct entries. +- FR-016: source `.specify/memory/constitution.md` (Product and Architecture Constraints) and `docs/architecture.md` (Windows) — checked against `main` on 2026-10-15. Windows still compiles. The hook transport is not available there. +- FR-017: source `.specify/memory/constitution.md` (ambient and peripheral) — checked against `main` on 2026-10-15. Notifications are settings-gated. The overlay does not steal focus. +- FR-018: source `PRD.md` (Out of scope) — checked against `main` on 2026-10-15. No sync and no external aggregators are present. `PRD.md` was removed after this check. +- FR-019: source `.specify/memory/constitution.md` and `docs/architecture.md` (Writers) — checked against `main` on 2026-10-15. The proposal queue and localhost HTTP API are gone. Writers are the person and Timer expiry. +- FR-020: source `PRD.md` (Non-goals) — checked against `main` on 2026-10-15. No auto-complete and no notification forwarding are present. `PRD.md` was removed after this check. +- FR-021: source `issues/icebox/021-all-monitors-default.md` and `issues/icebox/022-wrangle.md` — checked against `main` on 2026-10-15. Both remain deferred. Gather exists. All-displays default and Wrangle do not. +- FR-022: source `CONTEXT.md` (Species, Harness) and `docs/adr/0001-two-apps-over-one-renderer.md` — checked against `main` on 2026-10-15. Pig is the only Species. Claude Code is the only Harness the ranch reads. + +The record of the shipped render-domain work is `specs/001-render-domain-seam/spec.md`. This specification does not restate it. diff --git a/specs/004-task-timer-hand-edits/spec.md b/specs/004-task-timer-hand-edits/spec.md new file mode 100644 index 0000000..1856573 --- /dev/null +++ b/specs/004-task-timer-hand-edits/spec.md @@ -0,0 +1,52 @@ +# Feature Specification: Task Timers Survive Hand Edits + +**Feature Branch**: `004-task-timer-hand-edits` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: Issue 056. A Task Timer stays on the Task the person attached it to when they reorder or insert Tasks by editing the Focus file. The current product records the opposite limit in `specs/003-ranch-today/spec.md` FR-013. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - The Timer stays with the Task (Priority: P1) + +The person attaches a Timer to a Task, then edits the Focus file by hand and moves that Task or inserts another Task above it. The Timer is still on the original Task. + +**Why this priority**: Hand-editing is a supported way to change Tasks. A Timer that silently moves is the person losing track of the work they timed. + +**Independent Test**: Start a Timer on the second Task. Insert a new Task above it in the file and save. The Timer is still on the Task that had it, not on the new line. + +**Acceptance Scenarios**: + +1. **Given** a Timer on a Task, **When** the person inserts a Task above it and saves, **Then** the Timer remains on the original Task. +2. **Given** a Timer on a Task, **When** the person reorders the checkbox lines and saves, **Then** the Timer remains on the original Task. +3. **Given** two Tasks whose text is identical and one has a Timer, **When** the person reorders them, **Then** the ranch does not pretend to know which line the Timer belongs to. The behavior for that case is stated and tested. + +### Edge Cases + +- Editing the text of the timed Task. +- Deleting the timed Task from the file by hand. +- A corrupt Task Timer sidecar still degrades to no Timers and does not block the Focus. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: After a hand-edit that inserts or reorders Tasks, a Task Timer MUST remain attached to the Task the person attached it to. +- **FR-002**: The Focus file MUST stay plain checkbox lines. This feature MUST NOT add a network API or a second writer of Focuses. +- **FR-003**: If the attachment cannot be known, as with two identical Task lines, the ranch MUST follow one stated rule and MUST test that rule. +- **FR-004**: A decision that changes the Focus file format MUST be an accepted decision record before the format changes. A repair that does not change the file format does not need one. + +### Non-goals + +- **FR-005**: This feature MUST NOT revive Task Timers, change Focus Timer growth, or change which Animal is drawn. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: Inserting a Task above a timed Task leaves the Timer on the timed Task. +- **SC-002**: Reordering checkbox lines leaves each Timer on the Task it was attached to, except for the stated ambiguous case. +- **SC-003**: A person can still hand-edit a Focus file and see the overlay catch up. diff --git a/specs/005-late-hook-frame/spec.md b/specs/005-late-hook-frame/spec.md new file mode 100644 index 0000000..37e150d --- /dev/null +++ b/specs/005-late-hook-frame/spec.md @@ -0,0 +1,61 @@ +# Feature Specification: A Late Hook Frame Does Not Rewrite the Past + +**Feature Branch**: `005-late-hook-frame` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: Issue 059, under accepted ADR-0002. A Hook Firing that arrives late does not change the Agent Session, and the Agent Hooks window can tell a turn that ended from a turn that died. Today both failures are a limit in `specs/003-ranch-today/spec.md` FR-014. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - An old frame changes nothing (Priority: P1) + +A Hook Firing that describes an older moment than the one the ranch already applied does not move the Agent Session Animal and does not replace the session the ranch is holding. + +**Why this priority**: A late Firing that overwrites a newer one makes the Animal lie about the session. + +**Independent Test**: Apply a newer Firing, then deliver an older one for the same session. The Animal and the held session stay on the newer Firing. + +**Acceptance Scenarios**: + +1. **Given** the ranch has applied a Firing for a session, **When** an older Firing for that session arrives, **Then** the session and its Animal stay as the newer Firing left them. +2. **Given** a Firing is the newest for that session, **When** it arrives, **Then** the ranch applies it. + +--- + +### User Story 2 - Ended and died look different (Priority: P2) + +In the Agent Hooks window, a turn that ended and a turn that died are two different Firings. The person can tell which one happened. + +**Why this priority**: Both are an ending, and today the ranch cannot show which. + +**Independent Test**: Produce one normal end and one failed end. The window shows them as different Firings. + +**Acceptance Scenarios**: + +1. **Given** a turn ends normally, **When** the person opens Agent Hooks, **Then** that Firing is marked as an end. +2. **Given** a turn dies without a normal end, **When** the person opens Agent Hooks, **Then** that Firing is marked as a failed end, not as the same kind of Firing as a normal end. + +### Edge Cases + +- A Firing the ranch could not read is still shown. +- The client still exits quietly when the ranch is not listening. +- No new Harness event is added by this feature. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: A Hook Firing older than the one already applied for that Agent Session MUST NOT change that session. +- **FR-002**: A normal end and a failed end MUST be distinguishable in the Agent Hooks window. +- **FR-003**: An Agent Session MUST NOT gain a stored transport field, and this feature MUST NOT add a Harness event. +- **FR-004**: The hook client MUST stay dependency-free and MUST still exit without output when the ranch is not listening. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: An older Firing does not change the Animal or the held session. +- **SC-002**: A person can tell a normal end from a failed end in Agent Hooks without reading the raw payload. diff --git a/specs/006-unheard-turn-ends/spec.md b/specs/006-unheard-turn-ends/spec.md new file mode 100644 index 0000000..1c9dfb1 --- /dev/null +++ b/specs/006-unheard-turn-ends/spec.md @@ -0,0 +1,49 @@ +# Feature Specification: An Unheard Turn Stops Looking Busy + +**Feature Branch**: `006-unheard-turn-ends` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: Issue 060, under accepted ADR-0002. An Agent Session whose turn ended without the ranch hearing about it stops being drawn as working, without restarting the app. Today the ranch keeps showing that session as working until it hears an end. + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - The Animal rests when the turn is over (Priority: P1) + +The person is watching an Agent Session Animal that is walking because the session is working. The turn ends and the ranch never receives the ending Firing. Without a restart, the Animal stops being drawn as working. + +**Why this priority**: A walking Animal means the agent is mid-turn. Leaving it walking after the turn is over is a false glance. + +**Independent Test**: Hold a session in the working state, drop the ending Firing, and let the ranch notice the turn is over. The Animal rests. The app was not restarted. + +**Acceptance Scenarios**: + +1. **Given** an Agent Session is shown as working, **When** its turn has ended and no ending Firing arrived, **Then** the Animal stops being shown as working without an app restart. +2. **Given** an Agent Session is shown as working, **When** the turn is still going, **Then** the Animal keeps being shown as working. +3. **Given** an Agent Session is already resting, **When** the ranch looks for unheard endings, **Then** that session stays resting. +4. **Given** the ranch has no way to tell whether the turn ended, **When** it looks, **Then** it leaves the session as it is rather than forcing it to rest. + +### Edge Cases + +- Agents as Animals is turned off. No session Animal is shown, and this check does not create one. +- The ranch does not remove the session just because the turn went quiet. Removal remains the ending Firing or turning the setting off. +- This feature does not read the text of a session transcript. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: An Agent Session shown as working MUST stop being shown as working, without an app restart, when its turn has ended and the ranch did not receive the ending Hook Firing. +- **FR-002**: A session whose turn is still going MUST keep being shown as working. +- **FR-003**: A session the ranch cannot judge MUST be left unchanged. +- **FR-004**: This check MUST NOT delete the session, MUST NOT read transcript text, and MUST NOT run in a way that delays accepting a Hook Firing. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: After an unheard end, the Animal is resting and the app was not restarted. +- **SC-002**: A session that is still working is not forced to rest. +- **SC-003**: A session the ranch cannot judge is unchanged. diff --git a/specs/007-one-hook-delivery/spec.md b/specs/007-one-hook-delivery/spec.md new file mode 100644 index 0000000..11bb9ac --- /dev/null +++ b/specs/007-one-hook-delivery/spec.md @@ -0,0 +1,48 @@ +# Feature Specification: One Hook Firing Arrives Once + +**Feature Branch**: `007-one-hook-delivery` + +**Created**: 2026-10-15 + +**Status**: Draft + +**Input**: Issue 062, under accepted ADR-0002. A hook entry the ranch wrote can be removed by the ranch, and one Hook Firing is delivered once. Today a new install uses the Claude plugin and a stable client, and an older direct entry in Claude's settings is left in place (`specs/003-ranch-today/spec.md` FR-015). + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - One firing, one delivery (Priority: P1) + +The person has Agents as Animals on. One thing happening in Claude Code produces one Hook Firing in the Agent Hooks window, not a second copy that changed nothing. + +**Why this priority**: A doubled Firing makes the journal lie and will double any later reaction to a change. + +**Independent Test**: Trigger one Claude Code event that the ranch handles. The Agent Hooks window shows one Firing for it. + +**Acceptance Scenarios**: + +1. **Given** a single Claude Code event the ranch handles, **When** it is delivered, **Then** the Agent Hooks window shows one Firing. +2. **Given** an older direct hook entry the ranch wrote for its own socket, **When** the person installs or repairs hooks, **Then** that entry is removed and a current install remains. +3. **Given** a hook entry that names a different socket or a different program, **When** the person installs or repairs hooks, **Then** that entry is left alone. + +### Edge Cases + +- Windows has no hook delivery. This feature does not add one. +- Turning Agents as Animals off still leaves the Claude plugin installed. +- Two different Ranch data directories are not a supported setup. This feature does not delete a hook aimed at some other socket. + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: One handled Claude Code event MUST produce one Hook Firing. +- **FR-002**: An install or repair MUST remove an older direct hook entry the ranch wrote for its own socket, and MUST leave an entry that names a different socket or a different program. +- **FR-003**: The client path a new install uses MUST NOT change because the app was launched from a different directory. +- **FR-004**: This feature MUST NOT write a hook entry as a side effect of launching the app. Install and repair remain an explicit person action. + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: One handled event shows one Firing in Agent Hooks. +- **SC-002**: After install or repair, an older direct entry for this ranch's socket is gone, and an entry for a different socket is still there. +- **SC-003**: Launching the app from another directory does not create a second client path in the hook entry. diff --git a/specs/008-claude-session-storage/contracts/archive-health.md b/specs/008-claude-session-storage/contracts/archive-health.md new file mode 100644 index 0000000..75996e7 --- /dev/null +++ b/specs/008-claude-session-storage/contracts/archive-health.md @@ -0,0 +1,77 @@ +# Claude Archive Health Contract + +## Purpose + +Provide one aggregate-only testing surface for the Claude archive without creating an archive +browser, graph view, raw-row query API, or second database. The contract is read-only and cannot +enable, disable, repair, delete, or otherwise mutate ingestion. + +## Menu and window lifecycle + +- Every build contains an unchecked `Developer Mode` item in the app's Window menu. +- On launch, Developer Mode is off and `Claude Archive Health…` is absent from the menu. +- Enabling Developer Mode appends the health item for this process only. +- Disabling Developer Mode removes the item and closes the health window if it is open. +- Repeated enable/disable operations are idempotent and do not create duplicate items or windows. +- Developer Mode is never written to Settings and is off after every restart. +- Opening the item focuses the existing health window or creates one separate from the overlay and + the existing Agent Hooks debug window. +- Both the open handler and Tauri command verify current Developer Mode state; a stale/forged window + cannot read the projection after the mode is disabled. + +## Read projection + +The generated Rust/TypeScript projection contains exactly: + +| Field | Shape | Meaning | +|-------|-------|---------| +| `availability` | `ready`, `empty`, or `unavailable` | Database-read state; empty means all four counts are zero | +| `schema_version` | integer or NULL | `PRAGMA user_version`; NULL only when unavailable | +| `database_bytes` | non-negative integer | Sum of existing main DB, WAL, and SHM metadata lengths | +| `session_count` | non-negative integer or NULL | Aggregate `claude_archive_sessions` rows | +| `receipt_count` | non-negative integer or NULL | Aggregate `claude_hook_receipts` rows | +| `source_count` | non-negative integer or NULL | Aggregate `claude_transcript_sources` rows | +| `record_count` | non-negative integer or NULL | Aggregate `claude_transcript_records` rows | +| `last_successful_ingest_at` | RFC3339 string or NULL | Latest committed receipt or transcript-batch time | +| `dropped_jobs_this_run` | non-negative integer | Queue admissions rejected since process start | +| `errors_this_run` | ordered category/count rows | Operational errors since process start | + +The worker initializes persisted aggregates transaction-consistently when it opens the database and +publishes a new immutable snapshot only after successful commits. `last_successful_ingest_at` is +derived from the maximum committed receipt `received_at` and transcript source `last_synced_at`. +The byte count is refreshed from filesystem metadata for `ranch.db` and existing `ranch.db-wal` and +`ranch.db-shm` files; paths themselves never cross IPC. + +Allowed error categories are a closed enum: + +- `database_unavailable` +- `database_write_failed` +- `transcript_path_rejected` +- `transcript_read_failed` +- `transcript_retry_exhausted` +- `worker_closed` + +Queue-full/closed rejection increments `dropped_jobs_this_run`; it is not also counted as an error. +Persisted record `parse_error` values are not runtime errors. Merely opening or polling the window +must not increment any counter. + +## Presentation states + +- `ready`: show the schema, file footprint, four counts, last successful ingest, and `this run` + counters. +- `empty`: show the same zero aggregates plus an explicit “no archived data” state. +- `unavailable`: show a content-free database-unavailable state and any current-run counters; never + turn the failure into zero persisted counts. +- Loading remains distinct from all three returned states. + +## Forbidden projection + +The command type and rendered view contain none of the following: + +- session, receipt, source, record, prompt, message, or agent identifiers; +- filesystem paths, offsets, ordinals, hashes, or raw rows; +- prompts, assistant messages, tool names/inputs/results, command output, or source content; +- database handles, arbitrary query strings, or mutation commands. + +Tests inspect both the generated type shape and rendered DOM so adding a forbidden field fails the +contract rather than relying on CSS to hide it. diff --git a/specs/008-claude-session-storage/contracts/claude-ingestion.md b/specs/008-claude-session-storage/contracts/claude-ingestion.md new file mode 100644 index 0000000..ad19d71 --- /dev/null +++ b/specs/008-claude-session-storage/contracts/claude-ingestion.md @@ -0,0 +1,135 @@ +# Claude Archive Ingestion Contract + +## Input boundary + +The lockstep prototype plugin contract is exactly version `0.2.0`: the existing five lifecycle +registrations plus `SubagentStop` mapped to archive-only verb `observe`. Contract validation rejects +every other manifest version, event table, wrapper, or executable until the user explicitly runs +Install/Repair. There is no handshake, verb alias, or mixed-version adapter. The hook client's +bounded/silent behavior and wire frame remain: + +```text +ASCII transport verb + newline + exact UTF-8 JSON payload bytes +``` + +The archive path consumes an owned copy after the full bounded frame has been read. It does not +change Claude's hook stdout, stderr, or exit status. + +## Processing order + +For one received frame: + +1. Parse a Claude-specific transport action. Unknown verbs are silently ignored. `observe` has no + harness-neutral `HookAction` projection. +2. If archival is on, attempt to admit an immutable job containing action, receipt time, and exact + payload to the bounded worker queue. Successful admission is an "accepted archive firing." A + full/closed queue rejects the archive job, increments a content-free dropped-job counter, and + never blocks or fails Claude. +3. Independently, if Agents as Animals is on and the verb is a lifecycle action, apply it to the + journal/`LiveSessions`. `observe` always bypasses this path. Neither preference gates the other. +4. The single archive worker parses only lookup fields. When `session_id` is non-empty, it upserts + the Claude Archive Session before inserting the Hook Receipt in the same transaction so the + immediate foreign key is satisfied. Missing/invalid session ids are stored as NULL. +5. Treat `transcript_path` as a main-transcript hint and `agent_transcript_path` as a subagent- + transcript hint. Validate and schedule each present hint independently. +6. Synchronize newly completed records in bounded batches. +7. Commit transcript rows and the new cursor together. A failure rolls back that batch and leaves + the previous cursor retryable. + +The live path does not wait for transcript synchronization. Archive failure does not reverse a +live Agent Session update and never reaches Claude Code. + +## Path validation + +A transcript is readable only when all conditions hold: + +- the payload value is an absolute path; +- the path exists and names a regular file at read time; +- both the candidate and configured Claude `projects/` directory are canonicalized; +- the candidate is a descendant of that canonical projects directory; +- the filename/session correlation is not contradictory to the Hook Firing; +- symlink resolution does not escape the projects directory. + +The authoritative Claude configuration directory is resolved once at Ranch startup in this order: + +1. non-empty `claude.config_dir` in `settings.yaml`; +2. non-empty `CLAUDE_CONFIG_DIR` inherited by the Ranch process; +3. `$HOME/.claude` (or the platform home equivalent). + +The trusted projects root is `/projects`. A custom Claude environment that is +not inherited by Ranch must set `claude.config_dir`; a hook-provided transcript path never defines +or widens the trusted root. + +Missing or lagging paths are retryable, not corrupt. Invalid/escaping paths are rejected and logged +without reading their content. + +## Incremental JSONL rules + +- `byte_cursor` points to the first byte not committed into a transcript record. +- Read from that offset and split on newline delimiters without loading the complete file. +- Split the delimiter (`\n` or `\r\n`) from JSON/content bytes without trimming either; persist the + delimiter separately so concatenating `raw_json || record_delimiter` reconstructs source framing. +- A newline-terminated record is complete even when JSON parsing fails; store it with a parse error. +- A non-newline tail does not advance `byte_cursor` and is not persisted separately. The next sync + rereads it from that cursor, so bytes are never both prepended and reread. +- Every valid main or subagent path hint schedules an immediate sync plus bounded delayed retries. + `Stop`, `StopFailure`, `SessionEnd`, and `SubagentStop` use the terminal retry profile: retry until + two consecutive `(length, mtime, boundary digest)` observations are unchanged, subject to the + documented attempt/time cap. This lets asynchronous final rows land without polling forever. +- On the second stable read, a non-newline tail that parses as exactly one complete JSON value may + be committed. Otherwise the cursor stays at its start and the condition remains content-free in + diagnostics. +- Insert transcript rows and advance cursor/ordinal in one transaction. +- `boundary_sha256` is SHA-256 over `[max(0, byte_cursor - 4096), byte_cursor)`. If the file shrinks + below the cursor, the platform file identity changes, or that exact window no longer matches, + mark the active generation superseded and create the replacement generation in the same + transaction before reading from offset zero. + +## Tolerant projection + +Parse each complete raw record to `serde_json::Value` only after retaining the original bytes for +the transaction. Extract fields by path and type. Missing, unknown, or type-changed fields become +NULL plus an error category when appropriate; they do not reject the raw record. + +No record-type allowlist controls persistence. + +## Backpressure and lifecycle + +- One worker owns the Turso connection and cursor state. +- The worker is one Tokio single-consumer task spawned by the Tauri composition root on the + existing runtime; blocking transcript reads run through `spawn_blocking` and never occupy the + socket thread. +- Job ordering follows socket receipt order. +- Transcript synchronization is coalesced by canonical path so a burst of hooks does not re-read + the same range concurrently. +- Retry schedules survive coalescing and are bounded to a named attempt/time policy in code; tests + use a paused/injected clock rather than sleeps. +- Disabling archival and checking the admission gate share one linearization point. Every firing + after disable is rejected; every job admitted before it remains worker-owned and finishes exactly + once. Re-enabling allows only new firings and performs no historical census. +- App shutdown asks the worker to finish its current receipt transaction and then stops; it does + not make the hook client wait. +- Queue saturation/closure before admission increments `dropped_jobs_this_run`. An accepted-job, + database, or transcript failure increments only its bounded content-free error category. Neither + blocks or fails Claude; a later transcript sync can recover transcript rows, while a firing + rejected before queue admission has no receipt. +- After bootstrap and every successful archive transaction, the worker publishes an immutable + aggregate `ArchiveHealthSnapshot`; UI reads never execute arbitrary SQL or alter job ordering. + +## Diagnostics contract + +Allowed diagnostic values: + +- receipt id, session id, event name, canonical path; +- source id, generation, ordinal, byte offset, byte length; +- payload/record digest; +- error category and database migration version. + +Forbidden diagnostic values: + +- raw payloads or transcript lines; +- prompts, assistant text, tool inputs/results, command output, or source-file contents. + +The internal diagnostics above are not the archive-health UI contract. That UI may receive only +the aggregate fields in [archive-health.md](archive-health.md), never receipt/session/source/record +identifiers, paths, offsets, or digests. diff --git a/specs/008-claude-session-storage/contracts/data-root-migration.md b/specs/008-claude-session-storage/contracts/data-root-migration.md new file mode 100644 index 0000000..7bacd9e --- /dev/null +++ b/specs/008-claude-session-storage/contracts/data-root-migration.md @@ -0,0 +1,40 @@ +# Ranch Data-Root Migration Contract + +## Paths + +| Platform | Legacy default | New default | +|----------|----------------|-------------| +| macOS/Linux | `$HOME/.adhd-ranch` | `$HOME/.adhd` | +| Windows with `APPDATA` | `%APPDATA%\adhd-ranch` | `%APPDATA%\adhd` | +| Windows fallback | `%USERPROFILE%\.adhd-ranch` | `%USERPROFILE%\.adhd` | + +An explicit `ADHD_RANCH_HOME` is neither a legacy nor a new default. It is used exactly as supplied. + +## Startup algorithm + +The application prepares the data root before resolving Settings, Focuses, database, stable hook +client, or socket paths: + +1. Resolve whether the root is explicit or platform-default. +2. For an explicit root, create it if needed and return it without migration. +3. For a default root, inspect the legacy and new paths without creating either one first. +4. Legacy only: rename the whole legacy directory to the new sibling path. +5. Neither: create the new directory. +6. New only: use it unchanged. +7. Both: return a conflict error and write to neither directory. +8. Apply user-only directory permissions where supported. +9. Only then initialize Settings, Focuses, `ranch.db`, hook client, and hook socket below the returned + root. + +## Failure and rollback + +- A failed rename leaves the legacy directory authoritative and startup stops before any new-root + write. +- A successful same-parent rename is the migration commit point. +- An older Ranch version can be restored by stopping Ranch and renaming `.adhd` back to + `.adhd-ranch`; it ignores `ranch.db`. +- The migration never copies, merges, deletes, or resolves conflicts file-by-file. +- The plugin wrapper must resolve the same new default root in the release that enables this + migration; otherwise it could continue sending to the legacy socket. +- The rapid-prototype exception for the unshipped archive schema/protocol does not apply here: + existing Focus, Timer, Settings, client, and socket state still receive this whole-root migration. diff --git a/specs/008-claude-session-storage/contracts/ranch-db-v1.sql b/specs/008-claude-session-storage/contracts/ranch-db-v1.sql new file mode 100644 index 0000000..af48d9d --- /dev/null +++ b/specs/008-claude-session-storage/contracts/ranch-db-v1.sql @@ -0,0 +1,121 @@ +-- Ranch database schema contract, version 1. +-- Raw BLOB columns are authoritative; projected columns are nullable indexes. +-- Relational Claude archive only: no graph/node-edge or generic cross-tool tables. + +PRAGMA foreign_keys = ON; + +-- Turso Connection::execute_batch does not add a transaction. The runtime +-- migration adapter must execute this contract with these transaction bounds +-- and verify foreign_keys on every newly opened connection. +BEGIN IMMEDIATE; + +CREATE TABLE claude_archive_sessions ( + session_id TEXT PRIMARY KEY CHECK (length(trim(session_id)) > 0), + first_seen_at TEXT NOT NULL, + last_seen_at TEXT NOT NULL, + ended_at TEXT, + first_cwd TEXT, + latest_cwd TEXT, + latest_transcript_path TEXT, + title TEXT, + model TEXT, + last_hook_event TEXT +); + +CREATE TABLE claude_hook_receipts ( + receipt_id INTEGER PRIMARY KEY, + received_at TEXT NOT NULL, + transport_action TEXT NOT NULL, + session_id TEXT REFERENCES claude_archive_sessions(session_id), + hook_event_name TEXT, + prompt_id TEXT, + agent_id TEXT, + cwd TEXT, + transcript_path TEXT, + agent_transcript_path TEXT, + payload_sha256 BLOB NOT NULL CHECK (length(payload_sha256) = 32), + raw_payload BLOB NOT NULL, + parse_error TEXT +); + +CREATE INDEX claude_hook_receipts_by_session + ON claude_hook_receipts(session_id, received_at); +CREATE INDEX claude_hook_receipts_by_event + ON claude_hook_receipts(hook_event_name, received_at); +CREATE INDEX claude_hook_receipts_by_prompt + ON claude_hook_receipts(prompt_id); +CREATE INDEX claude_hook_receipts_by_digest + ON claude_hook_receipts(payload_sha256); + +CREATE TABLE claude_transcript_sources ( + source_id INTEGER PRIMARY KEY, + session_id TEXT NOT NULL REFERENCES claude_archive_sessions(session_id), + source_kind TEXT NOT NULL CHECK (source_kind IN ('main', 'subagent')), + agent_id TEXT, + canonical_path TEXT NOT NULL, + generation INTEGER NOT NULL CHECK (generation > 0), + file_identity TEXT, + opened_at TEXT NOT NULL, + last_synced_at TEXT NOT NULL, + superseded_at TEXT, + byte_cursor INTEGER NOT NULL DEFAULT 0 CHECK (byte_cursor >= 0), + next_ordinal INTEGER NOT NULL DEFAULT 0 CHECK (next_ordinal >= 0), + observed_length INTEGER NOT NULL DEFAULT 0 CHECK (observed_length >= 0), + observed_mtime INTEGER, + boundary_sha256 BLOB CHECK (boundary_sha256 IS NULL OR length(boundary_sha256) = 32), + UNIQUE (canonical_path, generation) +); + +CREATE UNIQUE INDEX one_active_claude_transcript_generation + ON claude_transcript_sources(canonical_path) + WHERE superseded_at IS NULL; +CREATE INDEX claude_transcript_sources_by_session + ON claude_transcript_sources(session_id, opened_at); + +CREATE TABLE claude_transcript_records ( + source_id INTEGER NOT NULL REFERENCES claude_transcript_sources(source_id), + ordinal INTEGER NOT NULL CHECK (ordinal >= 0), + byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0), + byte_length INTEGER NOT NULL CHECK (byte_length >= 0), + raw_sha256 BLOB NOT NULL CHECK (length(raw_sha256) = 32), + raw_json BLOB NOT NULL, + record_delimiter BLOB NOT NULL CHECK (record_delimiter IN (X'', X'0A', X'0D0A')), + parse_error TEXT, + record_type TEXT, + entry_uuid TEXT, + parent_uuid TEXT, + logical_parent_uuid TEXT, + record_session_id TEXT, + record_session_id_snake TEXT, + recorded_at TEXT, + prompt_id TEXT, + agent_id TEXT, + is_sidechain INTEGER CHECK (is_sidechain IS NULL OR is_sidechain IN (0, 1)), + message_role TEXT, + message_id TEXT, + model TEXT, + PRIMARY KEY (source_id, ordinal), + UNIQUE (source_id, byte_offset) +); + +CREATE INDEX claude_transcript_records_by_type + ON claude_transcript_records(record_type); +CREATE INDEX claude_transcript_records_by_uuid + ON claude_transcript_records(entry_uuid); +CREATE INDEX claude_transcript_records_by_parent + ON claude_transcript_records(parent_uuid); +CREATE INDEX claude_transcript_records_by_logical_parent + ON claude_transcript_records(logical_parent_uuid); +CREATE INDEX claude_transcript_records_by_prompt + ON claude_transcript_records(prompt_id); +CREATE INDEX claude_transcript_records_by_agent + ON claude_transcript_records(agent_id); +CREATE INDEX claude_transcript_records_by_session_time + ON claude_transcript_records(record_session_id, recorded_at); +CREATE INDEX claude_transcript_records_by_snake_session_time + ON claude_transcript_records(record_session_id_snake, recorded_at); +CREATE INDEX claude_transcript_records_by_message + ON claude_transcript_records(message_id); + +PRAGMA user_version = 1; +COMMIT; diff --git a/specs/008-claude-session-storage/data-model.md b/specs/008-claude-session-storage/data-model.md new file mode 100644 index 0000000..e89f489 --- /dev/null +++ b/specs/008-claude-session-storage/data-model.md @@ -0,0 +1,319 @@ +# Data Model: Claude Session Archive + +## Boundary + +`ranch.db` owns durable Claude integration evidence only in this feature. Focus Markdown, timer +sidecars, Settings YAML, and the in-memory `AgentSession` roster keep their current authorities. +Raw Claude payload bytes are authoritative. Every parsed column is a rebuildable index. + +Schema version 1 is ordinary relational Turso/SQLite with exactly the four Claude-specific tables +below. It has no graph engine, generic node/edge layer, graph API, or shared cross-tool entities. + +## Claude's observed source structures + +### Hook input envelope + +Fields documented as common across Claude hook events: + +| Field | Shape | Archive treatment | +|------|-------|-------------------| +| `session_id` | string | Session correlation key; nullable only when the payload is malformed | +| `prompt_id` | UUID string, optional before first prompt | Indexed nullable correlation key | +| `transcript_path` | absolute path string | Validated synchronization hint; never treated as trusted without canonicalization | +| `agent_transcript_path` | absolute path string on `SubagentStop` | Validated subagent synchronization hint | +| `cwd` | absolute path string | Session metadata and Pen input, preserved in raw payload | +| `scratchpad_dir` | path string, optional | Raw-only in this slice | +| `permission_mode` | enum string, event-dependent | Raw-only in this slice | +| `effort` | object, event-dependent | Raw-only in this slice | +| `hook_event_name` | string | Indexed event discriminator | +| `agent_id`, `agent_type` | optional subagent identifiers | Raw payload; `agent_id` may be indexed when present | +| event-specific fields | object members | Preserved raw; normalized only when a future consumer requires them | + +### Transcript record envelope + +Message-bearing records observed by the available typed corpus include `user`, `assistant`, +`system`, `attachment`, and `progress`. Metadata records include permission mode, prompts, titles, +agent identity/color/settings, tags, summaries, PR links, mode, worktree state, content replacement, +file-history and attribution snapshots, queue operations, context-collapse markers, bridge/session +markers, and artifact coordination. Current local data also contains `cost-state`, demonstrating +that the known set is not closed. + +Common or broadly useful fields are mapped as nullable indexes: + +| Source JSON field | Column | Notes | +|------------------|--------|-------| +| `type` | `record_type` | No closed enum constraint | +| `uuid` | `entry_uuid` | Absent on many metadata rows | +| `parentUuid` | `parent_uuid` | Nullable at roots and compaction boundaries | +| `logicalParentUuid` | `logical_parent_uuid` | Preserves logical ancestry across compaction when present | +| `sessionId` | `record_session_id` | Kept separate from the hook-correlated archive session | +| `session_id` | `record_session_id_snake` | Separate projection; may differ on resumed/internal records | +| `timestamp` | `recorded_at` | Source timestamp, stored as text without reinterpretation | +| `promptId` | `prompt_id` | Correlates records with hook/telemetry prompt identity | +| `agentId` | `agent_id` | Subagent/sidechain identity | +| `isSidechain` | `is_sidechain` | Nullable integer boolean | +| `message.role` | `message_role` | Nullable string, not a constrained enum | +| `message.id` | `message_id` | Nullable message identity; not assumed unique per record | +| `message.model` | `model` | Nullable model identifier | + +All remaining fields stay inside `raw_json`. + +## Database entities + +### `claude_archive_sessions` + +One durable Claude-specific row per hook-observed Claude session. + +| Column | Type | Rules | +|--------|------|-------| +| `session_id` | TEXT | Primary key; non-empty after trimming | +| `first_seen_at` | TEXT | Required RFC3339 receipt time | +| `last_seen_at` | TEXT | Required; monotonic by receipt order | +| `ended_at` | TEXT NULL | Latest observed SessionEnd time; historical only, not liveness authority | +| `first_cwd` | TEXT NULL | First valid hook cwd | +| `latest_cwd` | TEXT NULL | Latest valid hook cwd | +| `latest_transcript_path` | TEXT NULL | Latest validated path hint | +| `title` | TEXT NULL | Best-effort hook/transcript projection | +| `model` | TEXT NULL | Best-effort hook/transcript projection | +| `last_hook_event` | TEXT NULL | Latest received event name | + +Validation: + +- This row MUST NOT be converted directly into the harness-neutral live `AgentSession`. +- SessionEnd records an observation; resume may update the row later without deleting history. +- Missing or invalid session ids do not create a session row; their Hook Receipts are still kept. + +### `claude_hook_receipts` + +One immutable row per delivery successfully admitted to the bounded archive worker queue while +archival is enabled. Queue rejection is counted diagnostically but creates no receipt. + +| Column | Type | Rules | +|--------|------|-------| +| `receipt_id` | INTEGER | Primary key generated by the database | +| `received_at` | TEXT | Required RFC3339 Ranch receipt time | +| `transport_action` | TEXT | Existing Ranch verb/action, retained for transport diagnostics | +| `session_id` | TEXT NULL | Foreign key when parseable | +| `hook_event_name` | TEXT NULL | Source event from payload | +| `prompt_id` | TEXT NULL | Prompt correlation id | +| `agent_id` | TEXT NULL | Subagent identity when present | +| `cwd` | TEXT NULL | Source working directory | +| `transcript_path` | TEXT NULL | Exact payload value; validation status is separate | +| `agent_transcript_path` | TEXT NULL | Exact subagent payload value; validation status is separate | +| `payload_sha256` | BLOB | SHA-256 digest of exact payload bytes | +| `raw_payload` | BLOB | Exact UTF-8 JSON bytes from the transport, excluding frame header | +| `parse_error` | TEXT NULL | Content-free parse/validation category; never embeds prompt text | + +Indexes: `(session_id, received_at)`, `(hook_event_name, received_at)`, `prompt_id`, and +`payload_sha256`. + +Duplicate deliveries intentionally produce separate `receipt_id` values. The digest allows later +projections to identify equivalence without destroying receipt evidence. + +### `claude_transcript_sources` + +One physical transcript path generation and its committed incremental-read cursor. + +| Column | Type | Rules | +|--------|------|-------| +| `source_id` | INTEGER | Primary key | +| `session_id` | TEXT | Required foreign key to archive session | +| `source_kind` | TEXT | `main` or `subagent` | +| `agent_id` | TEXT NULL | Subagent identity when supplied; NULL for main source | +| `canonical_path` | TEXT | Required canonical regular file within configured Claude `projects/` root | +| `generation` | INTEGER | Starts at 1 and increments for the same path after replacement/truncation | +| `file_identity` | TEXT NULL | Platform-available device/inode or equivalent identity | +| `opened_at` | TEXT | First sync time for this generation | +| `last_synced_at` | TEXT | Latest successful cursor commit | +| `superseded_at` | TEXT NULL | Set when another generation replaces this one | +| `byte_cursor` | INTEGER | First unread byte; non-negative | +| `next_ordinal` | INTEGER | Next record ordinal; non-negative | +| `observed_length` | INTEGER | File length at last successful sync | +| `observed_mtime` | INTEGER NULL | Platform timestamp used only as a change hint | +| `boundary_sha256` | BLOB NULL | SHA-256 of `[max(0, byte_cursor - 4096), byte_cursor)` | + +Constraints and indexes: + +- Unique `(canonical_path, generation)`. +- At most one non-superseded generation per canonical path. +- `byte_cursor` is the first unread byte. An incomplete tail is not persisted separately and is + reread from that offset on the next sync. +- `byte_cursor`, inserted records, and the exact boundary digest update in one transaction. +- A canonical path may correlate to only the session id supplied by its validated Hook Firing for + that generation; a mismatch creates a diagnostic and no read. + +### `claude_transcript_records` + +One immutable source record from one transcript generation. + +| Column | Type | Rules | +|--------|------|-------| +| `source_id` | INTEGER | Foreign key to transcript source | +| `ordinal` | INTEGER | Zero-based order within the generation | +| `byte_offset` | INTEGER | Source offset of the first raw byte | +| `byte_length` | INTEGER | Raw byte count excluding newline delimiter | +| `raw_sha256` | BLOB | Digest of exact `raw_json || record_delimiter` bytes | +| `raw_json` | BLOB | Authoritative JSON/content bytes, including malformed/unknown complete records | +| `record_delimiter` | BLOB | Exact `LF`, `CRLF`, or empty framing bytes for a stable final value | +| `parse_error` | TEXT NULL | Content-free error category | +| `record_type` | TEXT NULL | Best-effort `type` projection | +| `entry_uuid` | TEXT NULL | Best-effort `uuid` projection | +| `parent_uuid` | TEXT NULL | Best-effort `parentUuid` projection | +| `logical_parent_uuid` | TEXT NULL | Best-effort `logicalParentUuid` projection | +| `record_session_id` | TEXT NULL | Best-effort `sessionId` projection | +| `record_session_id_snake` | TEXT NULL | Best-effort `session_id` projection | +| `recorded_at` | TEXT NULL | Best-effort `timestamp` projection | +| `prompt_id` | TEXT NULL | Best-effort prompt id projection | +| `agent_id` | TEXT NULL | Best-effort agent id projection | +| `is_sidechain` | INTEGER NULL | `0`, `1`, or NULL | +| `message_role` | TEXT NULL | Best-effort `message.role` | +| `message_id` | TEXT NULL | Best-effort `message.id` | +| `model` | TEXT NULL | Best-effort `message.model` | + +Primary key: `(source_id, ordinal)`. Additional unique guard: `(source_id, byte_offset)`. + +Indexes: `record_type`, `entry_uuid`, `parent_uuid`, `logical_parent_uuid`, `prompt_id`, `agent_id`, +`message_id`, `(record_session_id, recorded_at)`, and `(record_session_id_snake, recorded_at)`. + +### Schema version + +`PRAGMA user_version` is the database schema version. Each bundled migration: + +1. checks the current version; +2. runs inside one transaction; +3. creates or changes only the next version; +4. updates `user_version` last; +5. rolls back completely on failure. + +The migration SQL contains explicit `BEGIN IMMEDIATE`/`COMMIT` bounds because Turso's batch API +does not create a transaction. Every newly opened writer connection separately enables and verifies +`PRAGMA foreign_keys = ON`. + +Version 1 contains only the four Claude archive tables and their indexes. + +While this archive remains unshipped rapid-prototype state, the current version-1 contract may be +replaced in lockstep and fixture/developer archive databases may be recreated; no reader, writer, or +migration for earlier prototype snapshots is required. The current schema still bootstraps and +fails transactionally. This exception does not apply to the whole-root migration or existing Focus, +Timer, and Settings data. + +### Archive preference + +Stored in `settings.yaml`, not `ranch.db`, because it is user-editable application configuration: + +```yaml +claude: + archive_enabled: false + config_dir: null +``` + +Missing `archive_enabled` means false. `config_dir` is optional; when absent, Ranch uses the +inherited `CLAUDE_CONFIG_DIR`, then the platform Claude default. This preference does not replace +`agents.enabled`; live rendering and durable Claude retention are independent choices. + +### `ArchiveHealthSnapshot` (read model, not a table) + +One immutable, aggregate-only projection published by the archive worker after bootstrap and each +successful commit. It is rebuilt from the current database at startup and is never persisted as a +fifth entity. + +| Field | Shape | Rules | +|-------|-------|-------| +| `availability` | `ready`, `empty`, or `unavailable` | `empty` means the database is readable and all four counts are zero | +| `schema_version` | integer NULL | Current `user_version`; NULL only when unavailable | +| `database_bytes` | non-negative integer | Sum of existing `ranch.db`, `ranch.db-wal`, and `ranch.db-shm` metadata lengths | +| `session_count` | non-negative integer NULL | Exact aggregate table count; NULL when unavailable | +| `receipt_count` | non-negative integer NULL | Exact aggregate table count; NULL when unavailable | +| `source_count` | non-negative integer NULL | Exact aggregate table count; NULL when unavailable | +| `record_count` | non-negative integer NULL | Exact aggregate table count; NULL when unavailable | +| `last_successful_ingest_at` | RFC3339 string NULL | Latest committed Hook Receipt or transcript-batch time | +| `dropped_jobs_this_run` | non-negative integer | Rejected queue admissions since process start | +| `errors_this_run` | ordered list of category/count | Finite content-free operational categories since process start | + +The persisted half is initialized with one aggregate query. Afterward it changes only after a +successful archive transaction. `last_successful_ingest_at` is the maximum committed receipt time +or transcript source `last_synced_at`, not a Claude source timestamp. Runtime counters reset on +every launch. Queue saturation increments only `dropped_jobs_this_run`; accepted-job failures +increment an error category and do not retroactively become dropped jobs. Per-record `parse_error` +values are database facts, not runtime error counters. + +The Tauri/webview projection MUST NOT contain session ids, paths, ordinals, digests, raw rows, +prompts, messages, tool data, or source content. Internal content-free diagnostics may still use +the identifiers allowed by the ingestion contract; that is a separate channel. + +### `DeveloperModeState` (process state, not a setting) + +One injected boolean owned by the Tauri composition root. It starts `false` on every process launch, +is changed only by the explicit app-menu toggle, is never written to `settings.yaml`, and controls +whether the Archive Health menu item/window is available. Disabling it closes the health window but +does not alter archive ingestion or archive consent. + +## Relationships + +```text +Claude Archive Session (1) +├── (0..*) Claude Hook Receipt +└── (0..*) Claude Transcript Source + └── (0..*) Claude Transcript Record + +Archive Preference ──enables new writes only──> Archive Worker +Live Agent Session ──separate in-memory projection──> Render Scene +Archive Worker ──publishes aggregates only──> Archive Health Snapshot +Developer Mode State ──reveals temporarily──> Archive Health Window +``` + +## State transitions + +### Data-root preparation + +```text +explicit ADHD_RANCH_HOME ──> use exact root; no migration +new root only ──> use new root +legacy root only ──> atomic rename ──> use new root +neither root ──> create new root +both roots ──> conflict; no writes +``` + +### Transcript source generation + +```text +unseen path ──validated──> generation 1 active +active ──append──> same generation, cursor advances transactionally +active ──partial tail──> same generation, cursor remains at tail start; retry rereads bytes +active ──replacement/truncation──> old generation superseded + new generation active +active ──missing/lagging file──> unchanged; bounded delayed retry remains scheduled +``` + +### Archive preference + +```text +missing/off ──explicit user opt-in──> on +on ──user disables──> off (new admission stops; accepted queue drains; rows retained) +off ──user re-enables──> on (new receipts resume; no historical census) +``` + +The admission gate and preference update have one linearization point: every firing after the +disable transition is rejected, while every job admitted before it remains worker-owned and +finishes exactly once. + +### Developer Mode + +```text +app launch ──> off; Archive Health item absent +off ──explicit menu toggle──> on; item appended +on ──menu toggle──> off; item removed and health window closed +process restart ──> off regardless of prior state +``` + +## Validation rules + +- Canonical transcript path must be absolute, a regular file, and below the canonical configured + Claude `projects/` root after resolving symlinks. Root order is explicit `claude.config_dir`, + app-inherited `CLAUDE_CONFIG_DIR`, then the platform default; the hook hint never defines it. +- Hook payloads remain bounded by the existing transport limit. Transcript records do not inherit + that hook-frame limit; reads stream by line and transaction batch. +- Diagnostics may include session id, path, byte offset, record type, digest, and error category, + but never raw prompt, message, tool input, or tool output. +- The archive worker is the only writer to these tables in version 1. +- Foreign keys are enabled for every connection. +- Database and sidecar permissions are user-only where supported. diff --git a/specs/008-claude-session-storage/plan.md b/specs/008-claude-session-storage/plan.md new file mode 100644 index 0000000..19057b1 --- /dev/null +++ b/specs/008-claude-session-storage/plan.md @@ -0,0 +1,340 @@ +# Implementation Plan: Claude Session Archive + +**Branch**: `008-claude-session-storage` | **Date**: 2026-09-28 | **Spec**: [spec.md](spec.md) + +**Input**: Feature specification from `specs/008-claude-session-storage/spec.md` + +## Summary + +Introduce the first Ranch database as a local-only Turso file at `~/.adhd/ranch.db`, with an +atomic migration of the complete legacy `.adhd-ranch` root before any application store opens. +Add a Claude-specific archive worker behind the existing hook boundary: it stores every opted-in +raw Hook Receipt, incrementally tails hook-provided main and subagent transcript paths, preserves +every complete JSONL record byte-for-byte, and extracts a small rebuildable index. Ranch owns this +tolerant mapping rather than adopting a closed third-party transcript model. The in-memory +`LiveSessions` reducer remains the sole live presence/Activity authority, so persisted history +never resurrects Agent Animals. Storage remains ordinary Claude-specific relational tables in the +single Turso/SQLite database—no graph engine, generic node/edge layer, or second database. A +session-only Developer Mode menu reveals a separate aggregate archive-health window backed by a +sanitized snapshot; it never exposes identifiers, paths, or record content. + +Deliver in four vertical slices: data-root migration plus empty database bootstrap; explicit +archive opt-in plus raw Hook Receipts; incremental lossless transcript ingestion and schema indexes; +then the aggregate archive-health diagnostic surface. + +## Technical Context + +**Language/Version**: Rust 2021 with a workspace baseline raised from the currently inaccurate +declared 1.77 to Rust 1.90; POSIX shell for the Claude plugin wrapper; TypeScript 5.9/React 18 for +the integration preference and archive-health surfaces. + +**Primary Dependencies**: Pin `turso` 0.8.0-pre.14 with default features disabled and no `sync` +feature; existing `serde`/`serde_json`; direct `sha2` dependency for stable 32-byte digests; +existing Tokio/Tauri async runtime and filesystem APIs; dev-only SQLite reader for the engine- +escape test. Do not add a Claude transcript crate. Current Turso resolution requires Rust 1.90 +(`roaring` is the highest known floor), while the existing lock already exceeds the manifest's +declared 1.77. Slice 1 updates the workspace declaration and proves macOS/Linux/Windows targets; +failure returns to ADR-0004 rather than pinning a fragile transitive graph or changing engines. + +**Storage**: Existing Markdown/YAML files below the Ranch data root remain authoritative for +Focuses, Timers, and Settings. New embedded Turso/SQLite-compatible file at `/ranch.db` +stores schema version 1: Claude archive sessions, raw Hook Receipts, transcript source generations, +and raw transcript records plus nullable indexes. Version 1 has no cross-tool, graph, or generic +relationship tables. Aggregate health is a read model, not another persisted entity. + +**Testing**: Rust unit tests for pure extraction, path/root resolution, migration decisions, and +cursor transitions; storage integration tests against temporary local databases and JSONL +fixtures; existing Unix hook socket tests; Settings/UI tests for explicit opt-in and disclosure; +menu/window tests for session-only Developer Mode and aggregate-only health; `task check`; +`task check:windows`; packaged Linux CI compile gate. + +**Target Platform**: Tauri v2 desktop app. macOS is the primary runtime target; Unix hook ingestion +continues on macOS/Linux; Windows does not receive hooks yet but the workspace and database/path +code must compile and the data-root migration must behave correctly there. The archive is a Tokio +single-consumer task spawned through Tauri's existing runtime; blocking transcript reads use +`spawn_blocking`. + +**Project Type**: Local-first desktop application with Rust domain/storage/command crates, a Rust +Tauri host, and a React/TypeScript webview. + +**Performance Goals**: Keep the hook client's current 250 ms write bound and silent exit behavior; +perform no transcript reads on the socket accept thread; stream from the committed byte cursor with +memory bounded by the largest record plus one transaction batch; make a no-change sync proportional +to metadata checks rather than transcript size; ingest representative multi-megabyte transcripts +without loading the whole file. + +**Constraints**: Zero runtime network calls, credentials, telemetry, remote database, or sync; +raw Claude content never appears in logs/events/UI diagnostics; user-only permissions on database +artifacts; exact raw-byte preservation; unknown/malformed complete records survive; no historical +directory census; no archive-to-render projection; database migrations and data-root move must be +rollback-safe. Archive admission is bounded and best-effort; disabling rejects new admissions while +accepted jobs finish. The unshipped archive schema and app/plugin protocol may change in lockstep +without compatibility shims, but existing user-owned Ranch data retains its migration guarantees. + +**Scale/Scope**: Single-user local archive with one writer, concurrent hook producers, transcripts +from bytes to multi-megabytes, and a lifetime corpus that may reach gigabytes. Version 1 supports +only hook-observed Claude sessions, four tables, narrow indexes, and no browsing/search/export or +retention UI. The only archive UI is an aggregate diagnostic view hidden behind session-only +Developer Mode. + +## Constitution Check + +*GATE: Passed before Phase 0 research and re-checked after Phase 1 design.* + +### I. User-Owned Local State — PASS + +- Focus Markdown and timer sidecars remain canonical and are moved atomically with the entire data + root. +- The archive is local plaintext under the user's data root, defaults off, has explicit disclosure, + and enables neither Turso defaults nor its `sync` feature; the resolved graph has no HTTP/TLS + runtime client. +- Both-root conflicts stop without merge, deletion, or overwrite. Database migrations are + transactional and retryable. + +### II. Independent Domains, Shared Renderer — PASS + +- `ClaudeArchiveSession` is vendor-specific durable evidence and is not the harness-neutral live + `AgentSession`. +- `LiveSessions` remains in memory and solely owns present Activity; database rows never create + Animals after restart. +- No Focus, Task, Timer, renderer, Species, or Pen persistence is added to SQL. + +### III. Functional Core, I/O at the Edges — PASS + +- Envelope extraction, path/root decision rules, generation transitions, and cursor planning are + pure functions over immutable inputs. +- Turso, filesystem reads, permissions, clocks, and worker/runtime details stay in `crates/storage` + and the Tauri composition root. +- The worker and its archive sink hide meaningful ordering, transaction, and schema-drift + complexity rather than forwarding calls. +- The archive-health command reads a sanitized snapshot published by the worker; React receives no + database handle, raw row, identifier, or path. + +### IV. Explicit, User-Controlled Integrations — PASS + +- Archive consent is distinct from existing Agent rendering and defaults false for upgrades. +- `SubagentStop` adds one archive-only `observe` verb so its transcript can be captured without + changing parent Activity; the wrapper also adopts the new data root. +- By explicit owner direction, the unshipped archive wire/schema contract changes in lockstep during + rapid prototyping. The plugin manifest moves to exact contract version `0.2.0`; installation/repair + replaces and validates the complete plugin. This satisfies protocol versioning without providing + mixed-version adapters, negotiation, or backward readers/writers. Existing Focus, Timer, Settings, + and data-root compatibility remain unaffected. +- The UI discloses the plaintext copy before opt-in. Disabling rejects new jobs immediately and + drains already accepted work without silently removing history. + +### V. Observable Completion in Small Slices — PASS + +- The accepted spec provides behavior and measurable outcomes. +- Accepted ADR-0004 records the reversal of ADR-0002's transcript-ingestion rejection while keeping + its live transport decision. +- Four review slices each have one observable promise and targeted proof before the full gate. + +### VI. Evidence Is Not Authority — PASS + +- Current code and local transcript inspection are recorded as observations, not inherited + requirements. +- ADR-0001/0002/0003 are retained only for their accepted boundaries. ADR-0004 is the accepted new + authority for raw archive ingestion. +- Third-party crates are research evidence; Ranch's own mapping is the chosen contract. +- The relational-only, Claude-specific v1 schema and aggregate-only debug view are present owner + decisions recorded in the current spec rather than inferred future architecture. + +### Post-design re-check + +PASS. The database contract keeps raw records authoritative, the ingestion contract keeps I/O at +the storage edge, the archive-health contract exposes only aggregates, the exact plugin version +makes the lockstep prototype protocol explicit, and the data-root contract supplies conflict and +rollback behavior. No constitution exception remains. + +## Project Structure + +### Documentation (this feature) + +```text +specs/008-claude-session-storage/ +├── spec.md +├── plan.md +├── research.md +├── data-model.md +├── quickstart.md +└── contracts/ + ├── claude-ingestion.md + ├── data-root-migration.md + ├── archive-health.md + └── ranch-db-v1.sql +``` + +### Source Code (repository root) + +```text +Cargo.toml +Cargo.lock + +crates/domain/src/ +├── agents/ +│ └── claude_code/ +│ ├── archive.rs # pure Claude archive entities/envelope projection +│ ├── archive_health.rs # aggregate-only diagnostic read model +│ └── mod.rs +└── settings.rs # archive_enabled plus optional Claude config root + +crates/storage/src/ +├── claude_archive/ +│ ├── mod.rs # narrow archive interface and construction +│ ├── database.rs # Turso adapter and transactional writes +│ ├── migrations.rs # ordered schema migrations/user_version +│ ├── transcript.rs # streaming tail, path validation, generation detection +│ ├── health.rs # sanitized snapshot + current-run counters +│ └── worker.rs # DB ordering, drain semantics, health publication +├── agent_hooks/ +│ ├── journal.rs # existing bounded UI journal remains content-free +│ └── server/ # submits owned frame to live and archive paths +└── lib.rs + +crates/storage/tests/ +├── claude_archive.rs # byte fidelity, idempotency, lag, malformed/unknown rows +├── data_root_migration.rs # path-state matrix and rollback behavior +├── fixtures/claude/ # synthetic, non-secret hook/transcript fixtures +└── agent_hook_socket.rs # existing transport contract plus archive isolation + +crates/commands/src/ +└── archive_health.rs # read-only command over sanitized storage snapshot + +src-tauri/src/app/ +├── mod.rs # prepare root, migrate DB, compose worker/sinks +├── menu.rs # Developer Mode toggle + dynamic health item lifecycle +├── paths.rs # explicit/default root resolution and ranch.db path +└── agent_hooks.rs # independent live and archive routing + +plugins/adhd-ranch-hooks/scripts/send-hook + # resolves `.adhd` default; override unchanged + +src/ +├── archive-health.tsx # separate diagnostic window entry +├── api/archiveHealth.ts # typed Tauri reader +└── components/ + ├── ArchiveHealthWindow.tsx # aggregate-only ready/empty/unavailable states + ├── ArchiveHealthWindow.test.tsx + └── ... # existing integration preference/disclosure surface + +archive-health.html +vite.config.ts # archive-health multi-page entry +knip.json # archive-health frontend entry + +README.md +docs/architecture.md +docs/adr/0004-local-claude-session-archive.md +``` + +**Structure Decision**: Keep the Claude archive vocabulary under the existing Claude integration +namespace, place all Turso/filesystem/runtime behavior in one deep `claude_archive` storage module, +and compose it beside—not inside—the harness-neutral `LiveSessions` reducer. Publish one sanitized +health snapshot from that module rather than letting a UI query arbitrary rows. No new crate is +needed: the existing `domain`, `storage`, `commands`, and Tauri boundaries already match the pure- +model/side-effect split. + +## Delivery Slices + +### Slice 1 — One data root and a usable empty database + +**Completion promise**: An upgrade with only the legacy default root starts from `.adhd` with every +existing file intact and a migrated, reopenable schema-v1 `ranch.db`; ambiguous roots are untouched +and rejected. + +Implementation: + +- Raise the workspace Rust baseline to 1.90 and prove pinned local-only Turso under package targets. +- Add pure default/explicit root resolution and migration decision tests. +- Prepare/move the root before current Settings/Focus path resolution. +- Add database path, explicit transactional schema-v1 migration, per-connection foreign keys, + permissions, Turso reopen, and clean-shutdown SQLite reopen/integrity/read tests. +- Update the plugin wrapper's default path in the same slice so hooks do not split across roots. +- Update README/current architecture guidance in this slice; leave historical records untouched. + +Proof: data-root state-matrix tests, database create/reopen/user-version tests, existing Focus and +Settings tests, Unix plugin contract tests, workspace/Windows compile checks. + +### Slice 2 — Explicit opt-in writes lossless Hook Receipts + +**Completion promise**: After the user explicitly enables Claude archiving, every Hook Firing +successfully admitted to the bounded archive queue creates a queryable raw receipt without changing +live Agent behavior or exposing content in diagnostics; rejected admissions are counted. + +Implementation: + +- Add `claude.archive_enabled` with false default, Settings round-trip, preference control, and + plaintext disclosure. +- Add pure Hook Receipt envelope extraction and digesting. +- Add the bounded queue, dropped-job counter, and single async archive worker; upsert the session + before its immediate-FK receipt insert in one Turso transaction. +- Route an owned payload copy to the archive worker beside the current `LiveSessions`/journal path. +- Split the current coupled gate: archive admission follows `claude.archive_enabled`, while live + lifecycle projection alone follows `agents.enabled`. +- Gate admission from the latest archive preference: disabling rejects new work immediately while + the worker drains every already accepted job exactly once. +- Keep the in-memory debug journal bounded and content-free. + +Proof: opt-in/off tests, exact receipt-byte/digest tests, duplicate-receipt tests, database failure +isolation, deterministic saturation/drop-count and disable-while-queued tests, existing hook socket +timeout/silent-failure tests, live session/render regression tests. + +### Slice 3 — Incremental transcript generations and Ranch-owned mapping + +**Completion promise**: Hook-observed Claude main and subagent transcripts are archived +incrementally with exact raw records, unknown shapes preserved, bounded settle retries idempotent, +and detected truncation/replacement retained as a new generation. + +Implementation: + +- Resolve the Claude config root from `claude.config_dir`, app-inherited `CLAUDE_CONFIG_DIR`, or the + platform default, then validate canonical paths against its `projects/` child. +- Register `SubagentStop` with the archive-only `observe` verb and ingest + `agent_transcript_path` beside main `transcript_path` without touching `LiveSessions`. +- Parse the wire verb into a Claude-specific transport action and project only lifecycle verbs into + the existing harness-neutral `HookAction`; keep `observe` out of `LiveSessions` entirely. +- Bump the exact plugin contract to `0.2.0`; extend runtime validation to check the manifest version, + event table, wrapper bytes, and executable bit, and make only explicit Install/Repair replace a + mismatch. Startup reports an unhealthy installation without mutating it. Add no old-verb shim, + handshake, mixed-version path, or schema compatibility code. +- Add streaming JSONL tailer, partial-tail handling, source cursors, generation detection, and + transactional batch commits. +- Extract the stable nullable envelope defined in `data-model.md`; never gate storage on type. +- Coalesce repeated sync hints by path and schedule immediate plus bounded delayed retries; terminal + hooks settle only after two unchanged metadata/boundary observations or the retry cap. +- Add synthetic fixtures for known, unknown (`cost-state`), malformed, partial, split-message, + duplicate, replaced, resumed, and sidechain records. + +Proof: byte-for-byte fixture comparison, three-pass/reopen idempotency, generation preservation, +custom-config-root/path escape rejection, delayed-final-row capture, multi-megabyte streaming test, +zero archive-derived Animals, user-only DB/WAL/SHM permissions, network-denied runtime proof, and +full gates. + +### Slice 4 — Aggregate archive health behind session-only Developer Mode + +**Completion promise**: In every build, enabling Developer Mode for the current app run reveals a +read-only archive-health menu item whose window reports only approved aggregates; restarting hides +the item and resets run-local counters without changing persisted archive facts. + +Implementation: + +- Add a non-persisted `DeveloperModeState`, unchecked on every launch, plus an always-present + `Developer Mode` check item. Enabling dynamically appends `Claude Archive Health…` to the Window + submenu; disabling removes it and closes the window. Retain the submenu and item handles/IDs so + repeated toggles are idempotent and never change Settings YAML. +- Have the archive worker publish a sanitized snapshot after bootstrap and each committed receipt + or transcript batch: schema version, aggregate table counts, last successful ingest time, and + total bytes for `ranch.db` plus existing WAL/SHM sidecars. +- Track dropped jobs and a bounded enum of content-free error categories in memory for the current + run; label them `this run` and reset them naturally at process start. +- Add a read-only commands/Tauri boundary over that snapshot and a separate archive-health window + following the existing Agent Hooks debug-window pattern. Both the menu open handler and command + authorize against live `DeveloperModeState`, so a stale or forged webview cannot read after the + toggle is disabled. +- Render loading, empty, ready, and unavailable states. Never return identifiers, paths, record + rows, raw JSON, prompts, tool data, or source content to the webview. + +Proof: pure aggregate/snapshot tests, command redaction tests, component state tests, dynamic-menu +idempotency tests, release-profile host/menu tests plus a packaged smoke, restart/reset proof, +direct SQL/file-size parity against synthetic fixtures, and ingestion-isolation tests while the +window polls. diff --git a/specs/008-claude-session-storage/quickstart.md b/specs/008-claude-session-storage/quickstart.md new file mode 100644 index 0000000..aa97675 --- /dev/null +++ b/specs/008-claude-session-storage/quickstart.md @@ -0,0 +1,186 @@ +# Quickstart Validation: Claude Session Archive + +This guide validates the implemented feature without reading or modifying the user's real Claude +or Ranch data. Run commands from the repository root. + +## Prerequisites + +- Rust 1.90 toolchain and frontend dependencies required by the repository. +- `task`, `cargo-shear`, Node/npm, and the Windows cross-check prerequisites documented by + `Taskfile.yaml`. +- Synthetic fixtures under `crates/storage/tests/fixtures/claude/`; do not use a personal + `~/.claude/projects` transcript in automated tests or commits. + +## 1. Prove the database dependency and schema + +```sh +cargo check -p adhd-ranch-storage --all-targets +cargo test -p adhd-ranch-storage claude_archive -- --nocapture +``` + +Expected: + +- local-only Turso compiles with defaults and the `sync` feature disabled and no HTTP/TLS runtime + client in the resolved graph; +- a temporary `ranch.db` opens, migrates to `PRAGMA user_version = 1`, closes, and reopens; +- the four tables and indexes in [ranch-db-v1.sql](contracts/ranch-db-v1.sql) match the runtime + migration; +- `.tables` contains only the four Claude-specific archive tables—no graph, node/edge, or generic + cross-tool tables—and `ranch.db` is the only database; +- a cleanly closed/checkpointed Turso file reopens through the dev-only SQLite reader, passes an + integrity check, and returns the seeded raw row; +- every writer connection reports foreign keys enabled, and an injected mid-migration failure + leaves no partial schema before a successful retry; +- no test needs Turso credentials or a network service. + +## 2. Validate default data-root migration + +```sh +cargo test -p adhd-ranch data_root -- --nocapture +cargo test -p adhd-ranch-storage data_root_migration -- --nocapture +``` + +Expected state matrix: + +| Initial state | Outcome | +|---------------|---------| +| legacy only | complete directory renamed to new root; contents byte-identical | +| new only | new root used unchanged | +| neither | new root created | +| both | conflict returned; neither root changed | +| explicit `ADHD_RANCH_HOME` | exact override used; no default migration | + +Also confirm the plugin contract test expects `.adhd/adhd-ranch-hook` and +`.adhd/agent-hooks.sock` while preserving the explicit override path. + +## 3. Validate raw Hook Receipt persistence + +```sh +cargo test -p adhd-ranch-storage hook_receipt -- --nocapture +cargo test -p adhd-ranch-storage --test agent_hook_socket -- --nocapture +``` + +Expected: + +- archive disabled: no database receipt, existing live-session behavior unchanged; +- archive enabled: exact payload bytes and SHA-256 digest match the fixture; +- a first receipt upserts its session before the immediate foreign-key insert; +- duplicate deliveries create separate receipts with the same digest; +- queue saturation rejects admission, increments only the content-free dropped-job counter, and + does not block the socket client; +- accepted-job/database/transcript failures increment their current-run error categories without + incrementing the dropped-admission count; +- disabling archiving at a controlled queue barrier rejects every later firing while all earlier + accepted jobs finish exactly once with no partial transaction; +- invalid JSON is retained with a parse error and no raw content is logged; +- an unavailable database does not change the hook client's silent failure/timeout contract. + +Also run the plugin contract tests and verify exact lockstep version `0.2.0`, six events including +`SubagentStop -> observe`, `.adhd` wrapper paths, rejection of every mismatched contract, and +explicit Install/Repair replacement. There is no compatibility adapter or implicit startup repair. + +## 4. Validate transcript mapping and cursor recovery + +```sh +cargo test -p adhd-ranch-storage transcript -- --nocapture +cargo test -p adhd-ranch-storage transcript_generation -- --nocapture +``` + +Expected: + +- every completed fixture line is byte-identical after concatenating `raw_json` and its preserved + `record_delimiter`, including LF, CRLF, and stable non-newline final values; +- main `transcript_path` and `SubagentStop.agent_transcript_path` fixtures both ingest, while the + archive-only subagent verb leaves parent live Activity unchanged; +- known envelope fields are indexed and unknown fields remain in the raw record; +- the unknown `cost-state` fixture persists without a closed-enum failure; +- a malformed complete line persists with `parse_error`; +- a partial trailing line waits for a later append; +- a row appended after the terminal hook is captured by bounded settle retries without another + firing, and retry tests use an injected/paused clock; +- three replays, including one database reopen, add no duplicate transcript records; +- file truncation/replacement supersedes generation 1 and creates generation 2 without altering + generation 1; +- default, inherited-env, and explicit `claude.config_dir` roots resolve in order; paths outside the + canonical selected projects fixture are rejected without being read. + +## 5. Validate live/archive separation + +```sh +cargo test -p adhd-ranch-storage live_sessions -- --nocapture +cargo test -p adhd-ranch-commands agent_sessions -- --nocapture +cargo test -p adhd-ranch-commands render_scene -- --nocapture +``` + +Expected: + +- archived rows alone yield no live Agent Sessions after restart; +- a new Hook Firing still updates `LiveSessions` and the render scene as before; +- disabling Agent rendering does not alter archive history; +- disabling Claude archive drains accepted work, stops new receipts, and does not delete existing + rows; +- `observe` never creates, updates, or ends a live Agent Session, including when archiving is on and + Agents as Animals is off. + +## 6. Validate aggregate archive health and Developer Mode + +```sh +cargo test -p adhd-ranch-commands archive_health -- --nocapture +cargo test -p adhd-ranch menu -- --nocapture +npm test -- --run ArchiveHealthWindow +``` + +Expected: + +- Developer Mode exists in development and release configurations, begins off, is never persisted, + and the Archive Health item is absent until the menu toggle enables it; +- disabling Developer Mode removes the item and closes the window; restart returns it to off; +- ready/empty/unavailable states follow [archive-health.md](contracts/archive-health.md); +- schema version, combined DB/WAL/SHM byte size, four row counts, and last successful commit match + direct fixture observations; +- dropped-job and bounded error-category counts are labeled `this run`, are not double-counted, and + reset after restart while persisted aggregates remain; +- generated command types and rendered DOM contain no identifiers, paths, offsets, digests, raw + rows, prompts, messages, tool data, or source content; +- polling/opening the window neither changes counters nor delays archive ingestion. + +## 7. Run repository gates + +```sh +task check +task check:windows +``` + +Expected: lint, type checking, Rust/web tests, generated-type drift checks, release-profile clippy, +and the Windows workspace check all pass. CI must also pass its packaged Linux build/compile lane. + +Also run the archive integration suite in its network-denied/instrumented harness and verify zero +outbound connection attempts. On supported platforms, assert user-only modes for `ranch.db` and any +WAL/SHM sidecars after create, write, close, and reopen. + +## 8. Manual local smoke test + +Use a temporary explicit data root so the smoke test cannot move or write real Ranch state: + +```sh +RANCH_SMOKE_ROOT="$(mktemp -d)" +ADHD_RANCH_HOME="$RANCH_SMOKE_ROOT" task dev +``` + +In the app: + +1. Confirm Claude archiving is off by default. +2. Read the plaintext-data disclosure and enable archiving explicitly. +3. Run a disposable Claude session that uses the installed Ranch hooks. +4. Confirm `$RANCH_SMOKE_ROOT/ranch.db` exists and the Agent appears only while the live hook state + says it is present. +5. Quit and reopen Ranch using the same explicit root. Confirm archive rows remain but no historical + Agent appears until another live Hook Firing arrives. +6. Disable archiving and confirm a subsequent Hook Firing creates no new archive receipt. +7. Enable Developer Mode from the app menu, open Claude Archive Health, and confirm only aggregates + appear. Disable Developer Mode and confirm the item/window disappears. +8. Restart and confirm Developer Mode and all `this run` counters are off/zero while database counts + and last successful ingest remain. + +Remove the temporary directory after the app and any database shell are closed. Do not point this +smoke test at personal Claude transcripts when capturing logs or test artifacts. diff --git a/specs/008-claude-session-storage/research.md b/specs/008-claude-session-storage/research.md new file mode 100644 index 0000000..10fa54f --- /dev/null +++ b/specs/008-claude-session-storage/research.md @@ -0,0 +1,349 @@ +# Phase 0 Research: Claude Session Archive + +## Decision: Preserve raw Claude records; do not adopt a transcript crate as authority + +**Decision**: Store each Hook Firing payload and each completed transcript JSONL line as raw bytes. +Extract a narrow nullable index with `serde_json::Value`. Do not deserialize into a closed enum +before the authoritative copy is committed. + +**Rationale**: Claude documents transcript location and retention but does not publish a stable +transcript JSON schema. The current local corpus includes a `cost-state` record that is not in +`claude-code-transcripts` 0.1.12. That crate's `#[serde(other)] Unknown` variant preserves parse +continuity but not the unknown payload when reserialized, and its known structs do not flatten +unrecognized fields, so known variants also lose newly added members. Raw-first storage makes +schema drift a projection concern instead of a data-loss event. Claude also warns that transcripts +contain every prompt, tool read, command output, and possible credential, so this decision includes +explicit opt-in and local plaintext disclosure. + +**Alternatives considered**: + +- [`claude-code-transcripts`](https://crates.io/crates/claude-code-transcripts): closest match for a + comprehensive typed Rust model and useful fixture/round-trip evidence, but unsuitable as the sole + archival representation because unknown variants lose their bodies. +- [`claude-session-parser`](https://crates.io/crates/claude-session-parser): useful streaming usage, + chat, and activity projections, but deliberately not a lossless storage model. +- [`txcript`](https://crates.io/crates/txcript): useful cross-harness conversion layer, but its + published Rust 1.96 requirement exceeds the planned Rust 1.90 baseline and its + conversion model is broader than this slice. +- [`smc-cli-cc`](https://crates.io/crates/smc-cli-cc): a search-oriented library, not a storage or + round-trip schema authority. +- [`agent-sessions`](https://crates.io/crates/agent-sessions): useful reference for byte offsets, + CR/LF-preserving framing, and incomplete-tail handling, but its model is not Ranch's durable + schema and adopting it does not solve unknown-field preservation. +- [`cc-session-jsonl`](https://crates.io/crates/cc-session-jsonl): typed convenience parser with the + same payload-free unknown/field-loss limitation as other closed models. +- Copy whole JSONL files: preserves bytes but provides weak idempotency and lookup, and duplicates + entire files on every change unless another index is invented beside them. + +## Decision: Model Claude's structures in two layers + +**Decision**: Map only stable envelopes into columns and retain every event-specific structure in +the raw payload. The mapped transcript envelope includes record type, entry UUID, parent and logical +parent UUIDs, both observed `sessionId` and `session_id` spellings, timestamp, prompt id, agent id, +sidechain flag, message role, message id, and model. The mapped hook envelope includes session id, +prompt id, main/subagent transcript paths, cwd, event name, and receipt time. + +**Rationale**: Current Claude transcript records include message-bearing `user`, `assistant`, +`system`, `attachment`, and `progress` shapes plus many metadata records such as titles, modes, +summaries, file-history snapshots, worktree state, queue operations, cost state, and internal +coordination markers. Their common envelope is useful for ancestry and correlation lookups; the +variant bodies change too quickly to normalize without a concrete consumer. Claude's official +[hook reference](https://code.claude.com/docs/en/hooks) defines the common hook fields and event +extensions, making that envelope a stronger contract than the transcript body. + +**Alternatives considered**: + +- Normalize every content block and metadata subtype now: rejected as a second implementation of a + private schema with no current query consumer. +- Store only JSON: rejected because session, prompt, ancestry, type, and time lookups are already + required to validate ingestion and are expensive to derive repeatedly. + +## Decision: Hooks are receipts and synchronization hints, not the archive payload + +**Decision**: Persist the raw Hook Receipt after successful queue admission, then use +`transcript_path` and `agent_transcript_path` to schedule incremental transcript synchronization. +Register `SubagentStop` with an archive-only transport verb so it does not affect live parent +Activity. Every hint gets immediate and bounded delayed retries; terminal events settle after two +unchanged observations or a retry cap. Do not manufacture Claude transcript rows from hook inputs. + +**Rationale**: Hook JSON and transcript JSONL have different schemas and cadences. The official +[hook documentation](https://code.claude.com/docs/en/hooks#common-input-fields) states that the +transcript is written asynchronously and may not yet include the current turn. Hooks provide the +session identity and exact file path needed to synchronize, while Stop exposes +`last_assistant_message` for consumers that need current final text. A retryable cursor reconciles +the lag without blocking Claude's hook process. + +**Alternatives considered**: + +- Treat each hook as a transcript row: rejected because it invents a third schema and still omits + most message and tool data. +- Read the entire transcript synchronously inside the hook client: rejected because it violates the + client's bounded, dependency-light, silent-failure contract. +- Poll all Claude project directories: rejected for this slice because it expands privacy scope and + couples Ranch to undocumented project-directory naming. + +## Decision: Keep archive history separate from live Agent Session truth + +**Decision**: Continue to apply Hook Firings to `LiveSessions` for current Activity and render +projection. Add archival as a sibling/decorator side effect. Never rebuild live Agent Sessions from +database rows on startup. + +**Rationale**: A historical transcript proves that a session existed, not that its process still +exists. Rehydrating live state would create stale Animals and violate ADR-0001's independent domain +boundary. The database is evidence for future Claude features; `LiveSessions` remains the present +tense. + +**Alternatives considered**: + +- Replace `LiveSessions` with a SQL-backed repository: rejected because persistence cannot answer + liveness after a restart. +- Keep the archive completely outside the hook pipeline: rejected because the hook provides the + supported session id and transcript path correlation keys. + +## Decision: Use embedded Turso in local-only mode + +**Decision**: Pin `turso` 0.8.0-pre.14, disable default features, and open +`/ranch.db` with `turso::Builder::new_local`. Do not enable the `sync` feature. Raise the +workspace Rust baseline to 1.90 and prove all packaged targets in Slice 1. Isolate the API inside +`crates/storage`. + +**Rationale**: Turso's current [local-development guidance](https://github.com/tursodatabase/turso-docs/blob/main/local-development.mdx) +recommends an in-process local database and shows `Builder::new_local`; no server or credentials are +needed. The engine uses SQLite-compatible files, and Turso documents a path back to SQLite-compatible +readers in its [compatibility guarantees](https://github.com/tursodatabase/turso/blob/main/COMPAT.md). +Local-only mode fits the constitution's no-network runtime rule. With defaults and `sync` disabled, +the resolved graph has no HTTP/TLS runtime client, although Turso still unconditionally includes +sync protocol/data packages. The current graph requires Rust 1.90 (`roaring` is the highest known +floor), while this repository's existing lock already contains dependencies newer than its +declared Rust 1.77. Updating the honest workspace baseline is safer than pinning a brittle +transitive graph. The adapter boundary contains the risk of the crate's pre-1.0 API and undeclared +MSRV. + +**Alternatives considered**: + +- `libsql`: mature Turso lineage and stable releases, but the current Turso documentation now + recommends the `turso` package for embedded local databases. +- `rusqlite`: mature and simple, but does not follow the owner's Turso direction. +- Turso Cloud or embedded replication: rejected because the product must make no runtime network + calls and store no provider credentials. + +## Decision: Keep schema version 1 relational and Claude-specific + +**Decision**: Use ordinary Turso/SQLite tables, foreign keys, and indexes in the single +`ranch.db`. Add no graph-native engine, graph sidecar, generic node/edge layer, graph query API, or +cross-tool session/event/artifact/relationship tables. Generalize only when a second integration +provides concrete common queries. + +**Rationale**: Parent UUIDs, logical parents, sessions, prompts, and subagents are already +queryable through focused relational indexes. A generic graph model today would be speculative and +would not improve raw-data fidelity. The user's future visualization goal is preserved by keeping +raw records and stable source identities, not by guessing cross-tool ontology in Claude-only v1. + +**Alternatives considered**: + +- Replace Turso with an embedded graph database: rejected by present owner direction and because it + adds a second technology before a graph query exists. +- Add generic nodes/edges beside Claude tables: rejected until another integration demonstrates + shared identity and relationship semantics. +- Derive a relationship visualization now: rejected; this feature exposes only aggregate health. + +## Decision: One serialized archive worker owns database and transcript I/O + +**Decision**: Start one Tokio single-consumer archive task through Tauri's existing runtime after +database migration. The socket path records the in-memory live change as today and uses bounded +`try_send` admission for an owned raw frame. The worker owns the Turso connection, serializes +receipt writes and transcript cursor updates in explicit transactions, sends blocking transcript +reads through `spawn_blocking`, and reports failures through content-free diagnostics. Disabling +archival closes the admission gate atomically while every job already accepted remains owned by the +worker and finishes exactly once. + +**Rationale**: The current hook server accepts on a dedicated blocking thread and invokes a +synchronous sink. Turso's Rust API is async. A dedicated worker creates one meaningful boundary: +the hook server never holds an async runtime or database connection, and database ordering and +transaction ownership stay local. Transcript parsing may touch multi-megabyte files and therefore +must not occupy the socket accept loop. + +**Alternatives considered**: + +- Block the accept loop on Turso and transcript reads: rejected because one large transcript can + delay every subsequent Hook Firing. +- Give each firing its own connection/task: rejected because it weakens ordering and complicates + cursor races for no expected throughput benefit. +- Put Turso in domain types: rejected by the functional-core/I/O-edge rule. +- Cancel queued work when archival is disabled: rejected because accepted jobs would lose their + receipt guarantee and could strand transcript batches between planned operations. + +## Decision: Cursor by byte offset and retain file generations + +**Decision**: Track canonical path, generation, observed file identity metadata, byte cursor, +completed-line ordinal, last size/mtime, and SHA-256 of the exact bytes +`[max(0, cursor - 4096), cursor)`. The cursor always identifies the first unread byte; an incomplete +tail is reread from there and is not persisted separately. Insert transcript rows under a unique +`(source_id, ordinal)` key. If the file shrinks, its identity changes, or the boundary window no +longer matches, supersede the old generation and create the new one in the same transaction. + +**Rationale**: Byte offsets support streaming and exact raw preservation. UUIDs cannot be the sole +key because metadata rows may lack them and newer Claude versions may split one logical assistant +message over several records. Generations prevent a resumed/replaced file from silently rewriting +history. A transaction commits inserted rows and the new cursor together, making retries +idempotent. + +**Alternatives considered**: + +- Key by transcript UUID only: rejected because many record types have no UUID and repeated content + blocks can share message identity. +- Key by raw hash only: rejected because identical records at different positions are distinct + source facts. +- Update archived rows in place after truncation: rejected because it destroys evidence and makes + recovery ambiguous. + +## Decision: Resolve one trusted Claude projects root + +**Decision**: Resolve Claude's config directory once at app startup from explicit +`claude.config_dir` in Ranch settings, then `CLAUDE_CONFIG_DIR` inherited by the app, then the +platform home default `.claude`. Validate every main or subagent transcript against the canonical +`projects/` child. A hook-provided path never defines or widens the root. + +**Rationale**: Claude may run with a custom config directory that the desktop process did not +inherit. An explicit setting makes that case testable and avoids guessing a root from an untrusted +path hint. Canonical descendant checks still reject relative paths, symlink escapes, and unrelated +regular files. + +**Alternatives considered**: + +- Infer the root from each `transcript_path`: rejected because any local socket sender could widen + the read boundary. +- Support only `~/.claude`: rejected because it silently breaks documented custom configurations. + +## Decision: Make database migrations and engine escape executable contracts + +**Decision**: Include explicit transaction bounds around each schema migration, set and verify +foreign keys on every writer connection, and test clean shutdown/checkpoint followed by reopen, +integrity check, and reads through a dev-only SQLite reader. + +**Rationale**: Turso's `Connection::execute_batch` does not create a transaction and +`PRAGMA foreign_keys` is connection-local. Turso documents SQLite file compatibility but also has +SQL-semantic and journaling differences, so a tested escape is stronger than assuming that the file +format alone makes rollback safe. + +**Alternatives considered**: + +- Rely on a multi-statement batch being atomic: rejected because it can leave a partial schema. +- Describe SQLite compatibility without testing another reader: rejected because it overstates + reversibility of a pre-1.0 engine. + +## Decision: Migrate the whole default data root before opening stores + +**Decision**: Add a startup preparation step that resolves explicit versus default roots. When only +the legacy default exists, rename the complete directory to the new root on the same volume. When +both exist, stop without writes. Only after preparation may Settings, Focuses, sockets, the stable +hook client, and `ranch.db` be opened. + +**Rationale**: Moving individual children risks split-brain state and a plugin wrapper pointing at +the wrong socket/client. A same-parent directory rename is atomic on supported default layouts. +The explicit environment override is a user contract and must not be interpreted as legacy data. + +**Alternatives considered**: + +- Fall back to the legacy root forever: rejected because the rename would never complete and new + installs would diverge from upgraded installs. +- Copy then delete: rejected because interruption can leave two apparently valid roots. +- Auto-merge when both exist: rejected because there is no safe winner for Focuses or Settings. + +## Decision: Separate archive opt-in from Agent rendering + +**Decision**: Add a Claude-specific archive preference, default false, disclosed alongside hook +installation. Agent rendering remains controlled by `agents.enabled`; archive writes are controlled +by the new preference. Existing users do not begin copying transcript content merely by upgrading. + +**Rationale**: Displaying live session identity is materially different from duplicating complete +prompts and tool output. The constitution requires external integration effects to be explicit and +user-controlled. Separate switches also preserve the independent live/archive semantics. + +**Alternatives considered**: + +- Reuse `agents.enabled`: simpler, but silently broadens an existing display preference into a + sensitive retention choice. +- Treat plugin installation as permanent archive consent: rejected because existing installations + predate this behavior and no longer represent informed consent. + +## Decision: Version one lockstep prototype plugin contract without compatibility adapters + +**Decision**: Bump the exact Ranch Claude plugin contract to `0.2.0`, add the sixth +`SubagentStop -> observe` mapping, and require app validation/explicit Install or Repair to replace +every mismatched version, event table, wrapper, or executable. Keep the existing +`verb\n` frame and silent 250 ms client. Add no handshake, alias, old reader, +mixed-version path, or schema compatibility layer. + +The existing validator already compares the complete event table, wrapper bytes, and executable +bit, but currently asserts the manifest version only in a test. The implementation must move the +exact `0.2.0` check into runtime validation so status and Install/Repair share one contract. + +**Rationale**: The owner explicitly chose rapid lockstep prototyping over backward compatibility. +An exact manifest version still makes the breaking protocol explicit and satisfies the +constitution's versioning rule. The current installer already owns full-contract validation and +explicit repair; startup must report mismatch rather than mutating a user installation. Existing +Focus, Timer, Settings, and whole-root migration guarantees are outside this prototype exception. + +At the socket boundary, parse a Claude-specific transport action. Archive admission independently +follows `claude.archive_enabled`; only start/working/idle/end project into harness-neutral +`HookAction` when `agents.enabled`; `observe` never reaches `LiveSessions`. + +**Alternatives considered**: + +- Support old and new verbs or negotiate a frame version: rejected because no released archive + consumer needs compatibility and the user explicitly declined it. +- Put `Observe` into the live `HookAction` enum: rejected because it is archive evidence, not a + live Activity transition. +- Auto-repair on startup: rejected because plugin mutation requires explicit user action. + +## Decision: Publish aggregate archive health as a sanitized in-memory read model + +**Decision**: After database bootstrap and each successful receipt or transcript commit, the +single worker publishes an immutable `ArchiveHealthSnapshot`. It contains availability, schema +version, aggregate counts for the four Claude tables, the latest successful commit timestamp, and +the combined byte size of existing `ranch.db`, WAL, and SHM files. A separate current-run metrics +object contributes rejected-admission count and counts keyed by a bounded, content-free error enum. +The Tauri command returns only this projection; it never performs arbitrary UI-directed SQL. + +**Rationale**: The worker can establish a transaction-consistent initial count and update it only +after commits, so UI polling does not contend for the writer or expose raw rows. On restart, the +worker rebuilds persisted aggregates from the database while current-run counters naturally reset. +Separating persisted facts from runtime metrics also avoids pretending that database-unavailable +errors can always be written into the failed database. + +`last_successful_ingest_at` is the latest successful receipt or transcript batch commit time, not a +source timestamp. Database size is the sum of metadata lengths for the main file and any existing +`-wal`/`-shm` sidecars at snapshot refresh. Persisted per-row `parse_error` values remain database +facts; runtime error counters are operational categories and never include their messages. + +**Alternatives considered**: + +- Let the webview issue aggregate SQL: rejected because React must remain view-only and must not + receive a database capability. +- Persist diagnostic counters: rejected because they are session-local and cannot reliably record + failures while the database is unavailable. +- Reuse the existing hook-firing debug feed: rejected because it exposes session identifiers and + is a different diagnostic contract. + +## Decision: Gate the aggregate view with non-persisted Developer Mode + +**Decision**: Include Developer Mode in every build as process-local Tauri state initialized off. +An explicit check item is always present in the Window menu. Because Tauri menu items have no +visibility setter, enabling the mode appends a separate Archive Health item to the retained Window +submenu and disabling removes it and closes the window. Repeated transitions are idempotent. The +state is never written to Settings and resets off on every launch; both the open handler and the +read command check it directly. + +**Rationale**: Packaged builds need the same diagnostic proof as development builds, but ordinary +users should not see a temporary test surface. A separate window follows the existing Agent Hooks +debug-window pattern and keeps diagnostics out of the ambient overlay. Session-only state avoids a +new durable preference and makes each use intentional. + +**Alternatives considered**: + +- Compile the view only in debug builds: rejected because packaged behavior could not be tested. +- Persist Developer Mode: rejected because a temporary diagnostic surface should not remain + enabled across normal launches. +- Add archive health to the existing Agent Hooks window: rejected because that window currently + exposes identifiers and event rows forbidden by the archive-health contract. diff --git a/specs/008-claude-session-storage/spec.md b/specs/008-claude-session-storage/spec.md new file mode 100644 index 0000000..8ba532a --- /dev/null +++ b/specs/008-claude-session-storage/spec.md @@ -0,0 +1,361 @@ +# Feature Specification: Claude Session Archive + +**Feature Branch**: `008-claude-session-storage` + +**Created**: 2026-09-28 + +**Status**: Approved for planning + +**Input**: User description: "Create a clear Claude-data entity, map Claude Code's on-disk session structures, and use the existing hook path to write equivalent session data into a local Turso database. Rename the default Ranch application-data directory from `.adhd-ranch` to `.adhd` and store `ranch.db` there." + +## Clarifications + +### Session 2026-09-28 + +- Q: What should “graph database” mean for Ranch’s durable storage? → A: No graph database for + this feature; use only the local Turso/SQLite database. +- Q: How much cross-tool structure should schema version 1 introduce now? → A: Keep version 1 + Claude-specific and generalize only when a second integration supplies concrete shared concepts. +- Q: Should this feature include any relationship visualization or browsing interface? → A: Add a + basic developer-only debug overview that can be opened from the app menu for testing. +- Q: What information should the first archive debug overview display? → A: Aggregate health only: + schema version, database size, counts, last ingest time, dropped jobs, and error categories. +- Q: If the archive worker is overloaded while Ranch is running, what loss guarantee should apply + to raw Hook Receipts? → A: Use bounded best-effort admission, count rejected receipts, and never + delay Claude. +- Q: In which builds should the archive-health view be available? → A: Include it in every build, + hidden behind an explicit Developer Mode toggle in the app menu. +- Q: What time period should the debug view’s dropped-job and error-category counts cover? → A: + Show current-app-run counters that reset when Ranch restarts. +- Q: How should the new `SubagentStop` archive verb remain compatible with older Ranch apps and + installed plugins? → A: It does not need backward compatibility; the app, plugin, and unshipped + archive schema may change together during rapid prototyping. +- Q: What should happen to archive jobs already accepted when the user disables archiving? → A: + Finish accepted jobs atomically while rejecting every new Hook Firing after disable. +- Q: Should Developer Mode remain enabled after Ranch restarts? → A: No; it is session-only and + resets to off on every app launch. + +## User Scenarios & Testing + +### User Story 1 - Upgrade to One Ranch Data Home (Priority: P1) + +As an existing Ranch user, I keep my Focuses, Settings, and hook installation working after the +default application-data directory changes from `.adhd-ranch` to `.adhd`, and the new database is +created alongside that state. + +**Why this priority**: Every later database write depends on one unambiguous data root. Losing or +splitting existing user-owned state would make the archive unsafe to ship. + +**Independent Test**: Start the app against a fixture containing only the legacy data root, then +verify that the complete directory is moved to the new root, `ranch.db` is initialized there, and +the existing Focuses and Settings still load unchanged. + +**Acceptance Scenarios**: + +1. **Given** the default legacy root exists and the new root does not, **When** Ranch starts, + **Then** Ranch atomically moves the legacy root to the new location before opening any stores. +2. **Given** no Ranch data root exists, **When** Ranch starts, **Then** it creates `.adhd`, creates + `ranch.db`, and continues to create the existing Focus and Settings files below that root. +3. **Given** `ADHD_RANCH_HOME` is explicitly set, **When** Ranch starts, **Then** it uses that exact + directory and performs no default-root rename. +4. **Given** both default roots already exist, **When** Ranch starts, **Then** it refuses to merge + them automatically, leaves both unchanged, and reports an actionable conflict. + +--- + +### User Story 2 - Preserve Claude Session Data (Priority: P2) + +As a Ranch user who opted into the Claude integration, I have a local archive of the Claude hook +receipts and transcript records Ranch observed while it was running, so later Ranch features can +understand a session without re-reading Claude's private file layout. + +**Why this priority**: This is the first durable Claude-data capability and the reason for adding +the database. + +**Independent Test**: Replay fixture hook payloads that point to a representative Claude JSONL +transcript, then compare every complete source record byte-for-byte with its archived raw value and +query the session, event type, prompt, parent, and timestamp indexes. + +**Acceptance Scenarios**: + +1. **Given** a valid Hook Firing for a Claude session, **When** Ranch accepts it into the archive + queue, **Then** Ranch records the raw hook payload and its stable common fields in `ranch.db`. +2. **Given** the firing names a valid Claude transcript under Claude's configured `projects/` + directory, **When** Ranch processes the firing, **Then** it archives every newly completed JSONL + record from that transcript without rewriting the raw record. +3. **Given** a `SubagentStop` firing names `agent_transcript_path`, **When** Ranch processes it, + **Then** it archives that subagent transcript under the parent session without changing the + parent's live Activity. +4. **Given** Claude adds a record type or field Ranch does not understand, **When** the record is + ingested, **Then** its raw bytes remain queryable and the unknown shape does not abort the + session ingest. +5. **Given** the same transcript is visited by several firings or after an app restart, **When** it + is synchronized again, **Then** already archived transcript records are not duplicated. + +--- + +### User Story 3 - Keep Live Agent Behavior Independent (Priority: P3) + +As a Ranch user, Claude archiving does not make the overlay slower or resurrect stale Agent +Sessions: the existing live session reducer remains the authority for what is drawn now, while the +database is historical evidence. + +**Why this priority**: Persisted history and live presence have different truth and retention +rules. Combining them would reverse the accepted Focus/Agent/renderer boundaries and create ghost +Animals after restart. + +**Independent Test**: Ingest a complete archived session, restart Ranch, and verify that no Agent +Animal appears until a new live Hook Firing arrives; also verify that hook delivery remains silent +and bounded when the database or transcript cannot be read. + +**Acceptance Scenarios**: + +1. **Given** archived Claude sessions exist, **When** Ranch starts, **Then** no Agent Session is + reconstructed solely from the archive. +2. **Given** a database write or transcript read fails, **When** a Claude hook runs, **Then** the + hook client still exits silently and within its existing time bound. +3. **Given** Agents as Animals is disabled, **When** hooks fire, **Then** Ranch does not begin a new + archive without the user-visible integration opt-in defined by this feature. + +--- + +### User Story 4 - Inspect Archive Health During Development (Priority: P4) + +As a Ranch developer or tester, I can open a basic archive-health overview from the app menu to +confirm that Claude data is being recorded without using a database shell. + +**Why this priority**: The archive is otherwise invisible in this feature, making integration and +fixture testing unnecessarily indirect. This is a diagnostic surface, not an end-user archive. + +**Independent Test**: Ingest synthetic main and subagent fixtures, open the debug overview from the +menu, and verify that its schema version, database size, aggregate row counts, last-ingest time, +dropped-job count, and error-category counts match direct observations without displaying session +identifiers or raw prompt, message, tool, or source-code content. + +**Acceptance Scenarios**: + +1. **Given** any development or packaged build, **When** the tester enables Developer Mode and + selects the archive-health item from the app menu, **Then** Ranch opens the aggregate overview. +2. **Given** Developer Mode is off, **When** the app menu is displayed, **Then** the archive-health + item is hidden from normal users. +3. **Given** Developer Mode was enabled, **When** Ranch restarts, **Then** Developer Mode is off and + the archive-health item is hidden again. +4. **Given** no archived data or an unavailable database, **When** the overview opens, **Then** it + shows an explicit empty or unavailable state without affecting hook ingestion. +5. **Given** archived records contain sensitive content, **When** the overview renders, **Then** it + displays only the approved diagnostic projection and never raw payload or transcript content. + +### Edge Cases + +- Claude's transcript file does not exist yet or lags the Hook Firing that names it. +- Claude writes final main- or subagent-transcript rows after the last lifecycle hook has returned. +- The transcript ends with a partially written JSONL record. +- A complete transcript line is malformed JSON or contains a record type unknown to Ranch. +- Claude truncates, replaces, forks, or resumes a transcript at the same path. +- Two hook processes for one session arrive concurrently or duplicate the same logical event. +- The bounded archive queue is full; the receipt is rejected, the dropped-job count advances, and + Claude continues without waiting for durable admission. +- A hook-supplied transcript path is relative, is a symlink escape, is outside the configured + Claude `projects/` root, or names a non-regular file. +- The database is locked, corrupt, read-only, or the disk fills during a transaction. +- The app crashes between moving the data directory and opening the database. +- The user rolls back to an older Ranch build after the directory migration. +- The legacy and new data roots both exist because a previous manual move was incomplete. +- The debug overview opens while ingestion is active, before any rows exist, or while the database + is unavailable. +- The installed plugin and running app use different prototype archive contracts; Ranch reports the + integration as unhealthy and requires install/repair rather than translating either version. +- The user disables archiving while jobs are queued; no new jobs are admitted, and already accepted + jobs finish without partial receipt or transcript transactions. + +## Requirements + +### Functional Requirements + +- **FR-001**: The default Ranch data root MUST be `.adhd` under the user's home directory on Unix + and `adhd` under the platform application-data directory on Windows. +- **FR-002**: An explicit `ADHD_RANCH_HOME` MUST remain authoritative and MUST NOT be renamed or + migrated automatically. +- **FR-003**: When only the legacy default root exists, startup MUST move the complete legacy root + to the new default root before any component reads or writes Ranch state. +- **FR-004**: When both default roots exist, startup MUST NOT merge, delete, or overwrite either + root automatically. +- **FR-005**: The local database MUST be stored at `/ranch.db`; the feature MUST use no + remote database, credentials, replication, telemetry, or other outbound network behavior. +- **FR-006**: Database schema changes MUST be ordered, versioned, transactional, and safe to retry + after interruption. +- **FR-007**: The Claude archive MUST distinguish a Claude-specific persisted session record from + the harness-neutral, in-memory Agent Session used by the renderer. +- **FR-008**: A Hook Firing is accepted for archival only after successful admission to the archive + worker queue. For every accepted firing, Ranch MUST preserve the complete input payload and + extract the stable common fields needed for lookup: session id, hook event, prompt id when + present, agent id when present, working directory, `transcript_path`, `agent_transcript_path`, + and receipt time. Admission MUST be bounded and non-blocking; rejected admissions MUST increment + a content-free dropped-job counter and MUST NOT use a durable overflow inbox or delay Claude. +- **FR-009**: Ranch MUST use hook-provided `transcript_path` and `agent_transcript_path` values as + synchronization hints and MUST NOT discover sessions by crawling all of Claude's `projects/` + directory in this feature. `SubagentStop` MUST use an archive-only transport action that never + changes the parent session's live Activity. The prototype action requires a matching app/plugin + contract and MUST NOT add a compatibility shim or mixed-version protocol path. +- **FR-010**: Ranch MUST read a transcript only when its canonical path is a regular file within + the configured Claude `projects/` directory. The config directory MUST resolve from an explicit + Ranch setting, then the app's inherited `CLAUDE_CONFIG_DIR`, then the platform default; a hook + path MUST NOT widen this root. Rejected paths MUST be observable in diagnostics without exposing + transcript content. +- **FR-011**: Every completed transcript record MUST retain its exact content and line-delimiter + bytes plus nullable, best-effort indexes for record type, entry id, parent id, logical parent id, + session id, + timestamp, prompt id, agent id, sidechain flag, message role, message id, and model. Camel-case + `sessionId` and snake-case `session_id` MUST remain separate nullable projections. +- **FR-012**: Unknown record types and unknown fields MUST be retained in full. Typed projections + MUST never be the sole copy of a Claude record. +- **FR-013**: A malformed but complete transcript record MUST be retained with its parse error; + an incomplete trailing record MUST remain pending until it becomes complete or a final stable + read determines that it is the last complete value. +- **FR-014**: Transcript synchronization MUST be incremental and idempotent across duplicate Hook + Firings and application restarts. Every valid path hint MUST schedule bounded delayed retries; + terminal main/subagent events MUST settle on two unchanged observations so asynchronous final + records do not require a later Hook Firing. +- **FR-015**: A detected transcript replacement or truncation MUST create a new source generation + rather than overwriting or silently attaching new bytes to the old generation. Detection MUST + compare file identity when available and the exact committed 4 KiB boundary window. +- **FR-016**: Hook receipts MAY record duplicate deliveries as separate observations, but each MUST + carry a payload digest so downstream projections can identify equivalent deliveries. +- **FR-017**: Database writes and transcript reads MUST occur behind the existing storage and + integration boundaries; domain modules MUST remain free of filesystem, database, Tauri, and + async-runtime dependencies. +- **FR-018**: The in-memory live Agent Session reducer MUST remain the sole authority for current + Agent Session presence and Activity. Archived sessions MUST NOT create Animals after restart. +- **FR-019**: The hook client MUST remain dependency-light, bounded, silent on every failure path, + and unable to delay or fail Claude Code. It MUST NOT open the database or transcript itself. +- **FR-020**: Archival MUST be local-only and user-controlled. The integration surface MUST state + that Claude transcripts can contain prompts, source code, tool output, and secrets and that + Ranch stores a plaintext local copy while archival is enabled. +- **FR-021**: The database and its sidecar files MUST be created with user-only access on supported + platforms wherever the platform exposes equivalent permissions. +- **FR-022**: Disabling archival MUST immediately reject new archive jobs while allowing previously + accepted jobs to finish atomically. The integration surface MUST disclose that disabling stops + new capture but does not cancel admitted work or delete existing history. Deletion and retention + management are outside this feature. +- **FR-023**: The first release MUST archive only sessions whose Hook Firings reach a running Ranch + after the user opts in. Historical backfill, cloud sync, Codex ingestion, general-purpose archive + browsing, full text search, and archive-derived renderer behavior are out of scope. +- **FR-024**: Current executable tests, plugin wrapper paths, socket paths, client placement, Focus + paths, Settings paths, README guidance, and current architecture documentation MUST use the new + default data-root name in the root-migration slice. Historical ADRs/issues remain unchanged. +- **FR-025**: Every newly opened writer connection MUST enable and verify foreign keys. Every + schema migration MUST include explicit transaction bounds because the selected Turso batch API + does not add them, and an interrupted migration MUST be retryable without partial schema. +- **FR-026**: `ranch.db` MUST remain the feature's only database and MUST use ordinary relational + Turso/SQLite tables, foreign keys, and indexes. A graph-native engine, separate graph sidecar, + generic node/edge storage layer, and graph query API are outside this feature. +- **FR-027**: Schema version 1 MUST contain only Claude-specific archive entities and MUST NOT add + speculative cross-tool session, event, artifact, or relationship tables. Shared relational + entities require a later feature grounded in at least one additional integration. +- **FR-028**: Every build MUST include an explicit, session-only Developer Mode toggle in the app + menu. Developer Mode MUST default to off on every launch and MUST NOT be persisted. The read-only + Claude archive-health item MUST remain hidden until Developer Mode is enabled. Its overview is + limited to schema version, database size, aggregate session/receipt/source/record counts, + persisted last successful ingest time, and current-app-run dropped-job and content-free error- + category counts that reset on restart and are labeled `this run`. It MUST expose no session + identifiers, paths, raw payload, transcript content, or record-level rows and MUST remain + independent from live rendering and ingestion success. +- **FR-029**: During rapid prototyping, the app-side archive protocol, installed Ranch plugin, hook + client, and unshipped `ranch.db` archive schema MAY change in lockstep without backward-compatible + readers, writers, migrations, or protocol negotiation. Installation/repair MUST validate and + replace the complete plugin contract rather than support a mixed version. This exception MUST NOT + weaken the `.adhd-ranch` migration or compatibility of existing Focus, Timer, and Settings data. + +### Key Entities + +- **Claude Archive Session**: Durable Claude-specific identity and metadata for one observed Claude + Code run. It references Hook Receipts and one or more transcript source generations; it is not + the live Agent Session shown by the renderer. +- **Claude Hook Receipt**: One immutable receipt of the exact JSON payload delivered by a Claude + hook, together with arrival metadata and a digest. Duplicate deliveries remain separate facts. +- **Claude Transcript Source**: One physical transcript path and generation, including the cursor + and fingerprint needed to resume incremental reads and detect replacement or truncation. It is + labeled as a main or subagent source and carries the subagent id when available. +- **Claude Transcript Record**: One raw JSONL record from a transcript plus nullable lookup fields. + Raw bytes are authoritative; extracted fields are disposable projections. +- **Archive Preference**: The user's explicit choice to permit or stop new local Claude archive + writes. It is independent from whether archived data already exists. +- **Schema Migration**: One ordered, transactional database-version transition applied exactly + once. + +## Success Criteria + +### Measurable Outcomes + +- **SC-001**: A legacy-root migration fixture retains 100% of files and file contents and loads the + same Focuses and Settings from the new root. +- **SC-002**: Replaying a representative Claude transcript archives 100% of its complete lines with + byte-identical raw payloads, including main and subagent sources and at least one record type + unknown to the typed projection. +- **SC-003**: Replaying the same Hook Firings and transcript three times, including once after + reopening the database, creates zero duplicate transcript records. +- **SC-004**: A truncation/replacement fixture preserves both generations and never mutates the raw + records archived from the first generation. +- **SC-005**: Archived sessions produce zero Agent Animals after restart until a new live Hook + Firing establishes current presence. +- **SC-006**: Hook-client failure behavior and its existing 250 ms write bound remain unchanged + when the app, database, or transcript is unavailable. +- **SC-007**: Runtime network instrumentation observes zero outbound connections while creating, + migrating, writing, and querying `ranch.db`. +- **SC-008**: The repository quality gate and packaged-platform compile checks pass with the chosen + database dependency and all generated artifacts current. +- **SC-009**: Database, WAL, and shared-memory artifacts have user-only permissions on supported + platforms, and a network-denied/instrumented create-migrate-write-query run makes zero outbound + connection attempts. +- **SC-010**: For synthetic fixtures, every aggregate value in the debug overview matches direct + database/file observations, its empty/unavailable states render deterministically, and automated + UI assertions find zero identifiers, paths, raw prompts, messages, tools, or source-code content. + Packaged-build tests verify that the item is hidden before Developer Mode is enabled and opens + afterward. Restart tests verify that Developer Mode returns to off, row counts and last successful + ingest persist, and counters labeled `this run` reset to zero. +- **SC-011**: Saturating the archive queue increments the dropped-job count by the exact number of + rejected jobs while the hook client's existing silent behavior and 250 ms write bound remain + unchanged; a later accepted path hint can still synchronize transcript records. +- **SC-012**: A deliberately mismatched prototype plugin/app fixture is reported unhealthy and is + corrected by the existing install/repair workflow; no compatibility adapter is invoked and the + Claude hook still fails silently. +- **SC-013**: In a deterministic queued-job fixture, disabling archiving admits zero subsequent + Hook Firings, completes every previously accepted job exactly once, and leaves no partial receipt + or transcript batch. + +## Assumptions + +- "Use Turso" means an embedded, local, SQLite-compatible database file. Turso Cloud and sync are + not requested and would conflict with the product's local-only runtime constraint. +- "All Claude data" means the exact Hook Firings plus complete main- and subagent-transcript + records exposed by hooks for sessions Ranch observes while it is running after opt-in. It does + not mean a census or backfill of every historical file under Claude's config directory. +- The user direction in this specification intentionally revisits ADR-0002's rejection of + transcript ingestion. A new ADR must supersede only that rejected option while preserving the + accepted live-state transport and renderer boundaries. +- Claude's transcript schema is private and changes over time. Raw-byte preservation is therefore + the compatibility contract; extracted columns are best-effort indexes. +- Existing Focus Markdown and timer sidecars remain canonical user-owned state. `ranch.db` first + owns only the Claude archive and its migrations. +- Relationship visualization and graph modeling may be reconsidered after additional harnesses or + concrete cross-tool queries exist; this feature MUST NOT add speculative graph infrastructure. +- Stable raw payloads and source identities, rather than premature shared entities, are the + compatibility path for future integrations. +- Hook Receipt completeness is explicitly best-effort under overload. Transcript synchronization + remains retryable, but Ranch does not claim recovery of a rejected raw hook payload. +- The owner explicitly accepts lockstep breaking changes for the prototype archive protocol and + unshipped archive schema. This does not authorize breaking existing user-owned Ranch data. + +## Source Provenance + +- **Present owner direction**: this request establishes the new `.adhd` root, local `ranch.db`, + Claude structure mapping, and hook-fed persistence intent. +- **Accepted decisions retained**: ADR-0001 keeps Focus and Agent Session domains independent; + ADR-0002 keeps hook delivery push-based, bounded, and independent from live transcript polling; + ADR-0003 keeps renderer composition downstream of the harness-neutral Agent Session model. +- **Verified current observation**: current `main` reduces Claude payloads to session id, working + directory, Pen, and Activity and stores live sessions only in memory. +- **External contract**: Claude's current hook documentation supplies `session_id`, `prompt_id`, + `transcript_path`, `cwd`, and `hook_event_name`; `SubagentStop` additionally supplies + `agent_id` and `agent_transcript_path`. The documentation warns that transcript writes are + asynchronous. diff --git a/specs/README.md b/specs/README.md new file mode 100644 index 0000000..3c36689 --- /dev/null +++ b/specs/README.md @@ -0,0 +1,24 @@ +# Feature specifications + +| Feature | State | Next step | +| --- | --- | --- | +| [001 — Render Domain Seam](001-render-domain-seam/spec.md) | Implemented in [PR #88](https://github.com/killallgit/adhd-ranch/pull/88) | Use its [validation record](001-render-domain-seam/tasks.md#phase-7-convergence) for renderer changes. | +| [002 — Spec Kit Docs Pass](002-speckit-docs-pass/spec.md) | Documentation converted; new product and follow-on specs remain Draft | Review [the pass record](002-speckit-docs-pass/pass-record.md). | +| [003 — Ranch Today](003-ranch-today/spec.md) | Draft description of the shipped product, including timer chips from PR #89 | Review with the owner before treating it as governing requirements. | +| [004 — Task Timer Hand Edits](004-task-timer-hand-edits/spec.md) | Draft; not implemented | Revisit issue 056's scope. | +| [005 — Late Hook Frame](005-late-hook-frame/spec.md) | Draft; not implemented | Revisit issue 059's scope. | +| [006 — Unheard Turn Ends](006-unheard-turn-ends/spec.md) | Draft; not implemented | Revisit issue 060's scope. | +| [007 — One Hook Delivery](007-one-hook-delivery/spec.md) | Draft; not implemented | Revisit issue 062's scope. | +| [008 — Claude Session Archive](008-claude-session-storage/spec.md) | Approved for planning; design artifacts retained, implementation not started | Revalidate scope, then generate `tasks.md` and shipping issues. | + +## Continue the discussion + +Start with Ranch Today and the [active issue queue](../issues/README.md). The +[constitution](../.specify/memory/constitution.md), [accepted ADRs](../docs/adr/), and +[glossary](../CONTEXT.md) retain their authority. Saving or renumbering a draft does not approve it. + +The archive design was preserved from `chore/project-foundation` as spec 008 because spec 002 is +now the documentation pass. Its [accepted ADR-0004](../docs/adr/0004-local-claude-session-archive.md) +and [four delivery slices](008-claude-session-storage/plan.md#delivery-slices) remain available for +review. Dependency versions, the Rust baseline, and platform support need revalidation before +implementation. The application still uses `.adhd-ranch` and has no archive database. From 2594355e286b05a19d6dc06c129513e20f1dce23 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 15 Oct 2026 19:19:16 -0700 Subject: [PATCH 2/4] chore: consolidate orchestrator and Spec Kit host setup --- .claude/agents/builder.md | 38 ++++++ .claude/agents/hall-monitor.md | 53 ++++++++ .claude/agents/orchestrator.md | 123 +++++-------------- .claude/agents/reviewer.md | 33 +++++ .claude/settings.json | 3 +- .codex/agents/builder.toml | 38 ++++++ .codex/agents/hall-monitor.toml | 53 ++++++++ .codex/agents/reviewer.toml | 34 +++++ .codex/config.toml | 50 ++++++++ .cursor/agents/builder.md | 38 ++++++ .cursor/agents/hall-monitor.md | 53 ++++++++ .cursor/agents/reviewer.md | 34 +++++ .cursor/rules/orchestrator.mdc | 50 ++++++++ .specify/init-options.json | 4 +- .specify/integration.json | 8 +- .specify/integrations/claude.manifest.json | 2 +- .specify/integrations/codex.manifest.json | 2 +- .specify/integrations/speckit.manifest.json | 12 +- .specify/scripts/bash/check-prerequisites.sh | 8 +- .specify/scripts/bash/common.sh | 2 +- .specify/scripts/bash/setup-tasks.sh | 4 +- .specify/templates/checklist-template.md | 8 +- .specify/templates/plan-template.md | 14 +-- .specify/templates/tasks-template.md | 2 +- 24 files changed, 540 insertions(+), 126 deletions(-) create mode 100644 .claude/agents/builder.md create mode 100644 .claude/agents/hall-monitor.md create mode 100644 .claude/agents/reviewer.md create mode 100644 .codex/agents/builder.toml create mode 100644 .codex/agents/hall-monitor.toml create mode 100644 .codex/agents/reviewer.toml create mode 100644 .cursor/agents/builder.md create mode 100644 .cursor/agents/hall-monitor.md create mode 100644 .cursor/agents/reviewer.md create mode 100644 .cursor/rules/orchestrator.mdc diff --git a/.claude/agents/builder.md b/.claude/agents/builder.md new file mode 100644 index 0000000..25b965a --- /dev/null +++ b/.claude/agents/builder.md @@ -0,0 +1,38 @@ +--- +name: builder +description: "Lane agent started only by the orchestrator. Implements one lane of a spec in its own git worktree, runs the gate, and returns a build report." +tools: "Read, Grep, Glob, Bash, Edit, Write, Skill" +skills: follow-the-rules +--- + +You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. + +Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. + +Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. + +Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. + +Satisfy the acceptance checks the brief gives this lane, following `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. Run `task check` in the worktree. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. When it fails, fix the cause, or stop and report the failure. Commit on the lane's branch, staging files by name. + +On a later round the brief carries reviewer findings and hall-monitor rows. Fix each one, or say in the report why it does not apply. + +## Output + +Return only the build report. + +```markdown +## Done +What now satisfies the lane's acceptance checks. + +## Gate +The command and what it returned. + +## Departures +Where you left the spec or the conventions, and why. None, when there are none. + +## Not done +Checks you could not run, and anything a person still has to verify. +``` + +Generated by agent-setup. diff --git a/.claude/agents/hall-monitor.md b/.claude/agents/hall-monitor.md new file mode 100644 index 0000000..12fa8db --- /dev/null +++ b/.claude/agents/hall-monitor.md @@ -0,0 +1,53 @@ +--- +name: hall-monitor +description: "Lane agent started only by the orchestrator. Checks one lane against the follow-the-rules skill and this codebase's established patterns, out to callers, callees, and tests. Read-only." +tools: "Read, Grep, Glob, Bash, Skill" +skills: follow-the-rules +--- + +You check one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals against two standards you did not write: the `follow-the-rules` skill is the principles, the surrounding code is the patterns, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` adds this repository's own rules. Enforce them; invent none. + +Invoke the `follow-the-rules` skill before reading any code, and read the example it links for each language under review. When it cannot be loaded, return `rules unavailable` and stop. + +## Scope + +The brief names the branch, the worktree path, and the files; otherwise take `git diff --name-only main...`. The worktree path is absolute: run every command there and give every file tool an absolute path under it, because a relative path lands in the primary checkout. Skip lockfiles, generated files, and vendored trees. Read each file whole. + +You are read-only: `git diff`, `log`, `show`, `status`, and `blame`, and nothing that edits, commits, or switches branches. + +## Follow the execution tree + +For every symbol the diff added or changed, walk one hop each way, further when a signature, return type, error, or invariant changed: + +- Callers: a caller broken by the new behavior is a finding, even outside the diff. +- Callees: the change hand-rolls something a neighbouring module already provides. +- Tests: a changed behavior with no changed test is a finding. +- Dead ends: code whose only caller is its own test is dead, and so is that test. + +## Establish the pattern before judging + +Read the two or three nearest files that do the same kind of work. Divergence from a pattern established in several places is a finding; something seen once is not a pattern. When the pattern itself breaks a rule, the rule wins; say so. + +## Verify before you report + +Every row is a claim about code you read. Grep before calling code dead. Cite the duplicate, and the two files that establish a pattern. Name the simpler version before asking for a simplification. Drop any finding you cannot substantiate. + +## Severity + +- `VIOLATION`: a numbered rule in `follow-the-rules`. +- `PATTERN`: breaks how this codebase already does the same thing, or a caller, contract, or test elsewhere. +- `SMELL`: one of the flexible rules in `follow-the-rules`. + +Linter-owned formatting and naming taste get no row. + +## Output + +Table rows only, no header, no summary: + +``` +| | | | | | +``` + +When nothing breaks, return exactly `clean: `. + +Generated by agent-setup. diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md index fcf6be6..9dfef3b 100644 --- a/.claude/agents/orchestrator.md +++ b/.claude/agents/orchestrator.md @@ -1,111 +1,50 @@ --- name: orchestrator -description: Use this agent when work needs to be split across several coding agents and coordinated, rather than written directly — it plans, delegates, verifies, and reports, and never edits code itself. Typical triggers include the user asking to run or coordinate multiple agents on an issue or slice, a task large enough to break into independent pieces that can run in parallel, a request to supervise or check work another agent already produced, and any ask that names an orchestrator, a coordinator, or "manage the agents". Do not use it for a single focused change one agent can finish alone. See "When to invoke" in the agent body for worked scenarios. -model: inherit -color: magenta -tools: ["Agent", "SendMessage", "ListAgents", "TaskStop", "Read", "Grep", "Glob", "Bash", "AskUserQuestion"] +description: "The main session's role here. Runs a spec as parallel builder lanes in git worktrees, each checked by a reviewer and a hall-monitor." --- -You are the orchestrator for adhd-ranch. You decompose work, delegate it to coding agents, verify what comes back, and report. You do not write code. +These instructions are for the main session only. If you were started as a subagent, such as a builder, reviewer, or hall-monitor, ignore this file and follow your own instructions. -That constraint is structural: you hold no `Edit`, `Write`, or `NotebookEdit` tool. It is also a discipline. When a fix is one line and delegating feels slower than doing it, you still delegate. An orchestrator that edits "just this once" stops being one, and the human loses the single place that knows what every agent is doing. +# Orchestrator -Your `Bash` access exists to inspect and verify — `git`, `task`, `gh`, `cat`, `grep`. Never use it to mutate tracked source. Writing a file through a shell redirect is code work wearing a different hat. +You are the main session in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Work with independent parts becomes lanes: a `builder` per lane writes the code, a `reviewer` and a `hall-monitor` check it, and you write none of it. A single small change with no independent parts, you make yourself. -## When to invoke +A spec or plan is whatever the user names. Ask for acceptance checks when it has none. -- **A slice splits cleanly.** An issue touches a Rust crate and the React layer, and the two halves share only a type boundary. Brief one agent per half, run them concurrently, then reconcile at the seam yourself. -- **Work needs supervision, not authorship.** An agent reports a slice finished. You re-run the gate, read the diff against the issue's Completion promise, and either accept it or send the same agent a correction round. -- **The path is unclear enough to cost a wrong turn.** Send a read-only `Explore` or `Plan` agent first, decide from what it finds, then brief the implementer with the answer in hand. -- **Several independent tasks are queued.** The user hands you three unrelated chores. Fan them out, track them, report once with a per-task verdict. +- Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. +- Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` +- Default branch: `main` +- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. -Do not invoke yourself for a single bounded change. One agent, or the main session, does that faster. +## Loop -## Core responsibilities +1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. +2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. +3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. +4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. +6. As each builder returns, run `task check` in its worktree. +7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. +8. Send findings to the same builder (in Claude Code, `SendMessage` to its agent ID), or, where a host cannot continue a finished subagent, to a new builder with the original brief, its last report, and the findings. Repeat steps 6 and 7. After two rounds with findings left, stop the lane and put it in front of the user. +9. A lane is ready when the gate passes, the reviewer says PASS, and hall-monitor returns `clean`. When the user asks, integrate ready lanes one at a time onto `main`, as the note says. Push only when the user asks. -1. Turn a request into bounded, independently verifiable units of work. -2. Write briefs complete enough that an agent with no prior context can succeed. -3. Delegate, choosing concurrency and model per unit. -4. Verify every claim against the repository rather than against the agent's report. -5. Hold delegated work to this repo's contract, listed below. -6. Report one consolidated verdict to the human, including what you did not finish. +When hall-monitor returns `rules unavailable`, this host cannot load the `follow-the-rules` skill and no lane can reach `clean`. Stop starting hall-monitors, tell the user once, and ask whether a reviewer PASS alone makes a lane ready. -## Delegation process +## A brief contains -1. **Read before briefing.** Read the issue file, the target modules, and `CLAUDE.md`. A brief written from a guess produces a diff written from a guess. -2. **Cut the work.** Prefer units that can be verified alone. If two units must edit the same file, they are one unit — concurrent agents editing one file clobber each other. -3. **Brief each unit.** See the contract below. -4. **Dispatch.** Send independent units in a single message so they run concurrently. Background them so the human can interject; only set `run_in_background: false` when your very next step depends on that one result and nothing else can usefully proceed. Pass `model` per call — mechanical edits do not need the model that planned them. +The observable end state; the spec location and this lane's acceptance checks; the worktree path and branch; the files the lane may touch and the files it must leave alone; the gate; and the worktree and git note, verbatim. - Never spawn another orchestrator. Subagents can nest, so a coordinator that delegates to a coordinator is possible and pointless: it spends the spawn-depth and concurrency budget on coordination and leaves less of it for the work. Delegate to agents that implement, review, or explore. -5. **Verify.** Re-run `task check`. Read the actual diff. Confirm the Completion promise holds. -6. **Correct in place.** Use `SendMessage` to the same agent by name, so it keeps its context. A fresh `Agent` call restarts from zero and usually repeats the mistake. -7. **Report.** +## Verification -## What a brief must contain +A builder's report is a claim. Read `git diff --stat`, then the hunks that matter. Reproduce a blocker before re-planning, and check "flaky", "pre-existing", and "out of scope" yourself. Look for weakened tests, silenced checks, commented-out code, scope past the brief, edits in the primary checkout instead of the worktree, and the seam where two lanes meet. -An agent starts with no memory of this conversation. Every brief carries: +## Report -- The goal, stated as the observable end state, not the steps. -- Exact file paths, and the module boundary the work must stay inside. -- The relevant rules from `CLAUDE.md` quoted, not referenced. -- How the agent proves it worked — usually `task check`, plus the specific acceptance criteria. -- What is out of scope, when scope creep is a live risk. +- **Verdict**: per lane, its commit, the reviewer's verdict, hall-monitor's result, and whether it holds. +- **Verified**: the commands you ran and what they returned. +- **Not done**: work left out, blocked, or left for a person, and why. +- **Next**: the next action, or the decision you need. -Never write "follow the project conventions." Name them. +Stop and ask the user when a lane needs a decision only they can make: a contract conflict, an ambiguous acceptance check, or a destructive or outward-facing step. -## The contract you enforce - -From `CLAUDE.md` and `issues/README.md`. Delegated work that violates these is not done, however confidently it is reported. - -- **Shipping a PR follows the `ship-pr` skill** — issue linked and archived, local gate green, rebased on the real base, PR opened, at least one review, findings resolved, squash-merge, issue close confirmed. Invoke it rather than re-deriving the steps; it carries the CodeRabbit rate-limit fallback this repo hits often and the `Closes #N` keyword without which a linked issue silently stays open. -- **`task check` is the gate** — lint, typecheck, tests, ts-rs drift. Green before any PR. Run `task check:windows` too whenever the diff touches `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml` or `Cargo.lock` — the paths that trigger the `windows` workflow. Do not narrow that to changes where you spotted a `#[cfg(unix)]`; not spotting one is the failure mode. -- **Layer boundaries.** `crates/domain` is pure — no I/O, no Tauri, no async runtime. `storage` adapts disk and watchers. `commands` holds use cases. `src-tauri/src/{ui_bridge,display,app}` is the host. React `components/` are view-only — no `fetch`, no direct I/O. -- **No global mutable state.** No `static mut`, no `lazy_static!`/`OnceCell` for shared mutable state, no module-level `let mut`. A `global`-style variable is always a bug here; flag it and have it fixed. -- **Program to interfaces** — traits at Rust module boundaries, `interface`/`type` at TypeScript ones. Never depend on a concrete class across modules. -- **Issue queue.** Lowest-numbered open issue whose Blocked-by entries are all merged. Never pick from `issues/done/` or `issues/icebox/`. -- **Branches.** `/` where type is `feat`, `chore`, `fix`, `spike`, or `hotfix`. Rebase onto the branch's actual base — read it, never assume `main`, because rebasing a stacked branch onto `main` drags in commits it never meant to carry. Rebase; never merge the base in. -- **PRs.** Title `[]: `. Body links the issue file and quotes the Completion promise verbatim. No co-author attribution. Squash-merge. -- **Diff size.** Small enough for a human to review in fifteen minutes. If a brief cannot meet that, the unit was cut too coarse. -- **Comments explain why, never what.** Agents that narrate their own code are producing noise; send it back. - -## Verification standards - -**Everything an agent hands back is a claim, and every claim gets validated. No exceptions.** - -This cuts both ways, and the second half is the one that gets skipped: - -- **"It's done."** Validate before believing it. Run the gate yourself. Read the diff, not the summary — `git diff --stat` for shape, then the hunks that matter. Confirm the Completion promise is observably true, which is a stronger bar than the tests passing. -- **"It's blocked."** Validate before accepting it. An agent reporting a problem is as likely to be wrong as one reporting success, and a false blocker is more expensive: it stops work that was never actually stopped. Reproduce the failure yourself before you re-plan around it. - -Claims that sound like bad news get waved through because nobody wants to argue with them. Check them anyway: - -- "That test is flaky" — run it again. Flaky and broken-by-this-diff look identical from one run. -- "That failure is pre-existing" — check out the base and run it there. This one is wrong often. -- "That's out of scope" — compare against the brief you wrote. Sometimes true, sometimes a boundary being redrawn after the fact. -- "The API doesn't support that" — read the source or the docs. Agents infer capability from memory and infer it wrong. -- "I couldn't find it" — search yourself before concluding it isn't there. - -Watch for the specific failures agents produce under pressure: a test weakened to pass, a check silenced instead of satisfied, dead code left commented out, scope quietly widened past the brief. When two agents touched adjacent code, read the seam — neither one was looking at it. - -You are the only thing standing between a confident report and `main`. - -## Output format - -Report to the human as: - -**Verdict** — one line per unit: what it was, which agent did it, and whether it holds. - -**Verified** — what you ran and what it returned. Name the commands. - -**Not done** — work you left out, blocked, or rejected, and why. Never let this be implied by omission. - -**Next** — the single clearest next action, or the decision you need from the human. - -## Edge cases - -- **A unit needs a decision only the human can make** — a contract conflict, an ambiguous promise, a destructive or outward-facing step. Stop that unit and use `AskUserQuestion`. `issues/README.md` is explicit: flag the human, do not silently skip. -- **An agent goes wrong or runs away.** `TaskStop` it, then decide whether to re-brief or take a different cut. Do not let a second agent try to repair the first one's half-finished diff. -- **An agent reports blocked.** Get the specific blocker before re-dispatching. "Try again" wastes a full run. -- **The work turns out to be one unit.** Say so and hand it to a single agent. Manufactured parallelism costs more than it returns. -- **You are running as a subagent.** You cannot converse with the human mid-flight — `AskUserQuestion` has no one to answer it. Do everything that does not depend on the decision, then surface the question in your final report as a blocking item. +Generated by agent-setup. diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.md new file mode 100644 index 0000000..7a80915 --- /dev/null +++ b/.claude/agents/reviewer.md @@ -0,0 +1,33 @@ +--- +name: reviewer +description: "Lane agent started only by the orchestrator. Reviews one lane's diff against its spec and returns PASS or CHANGES. Changes no code." +tools: "Read, Grep, Glob, Bash, Skill" +--- + +You review one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. You did not write this code. The builder's report is a claim; check it against the code. + +The brief names the spec, the lane's acceptance checks, the branch, and the absolute worktree path. Run every command there and give every file tool an absolute path under it: a relative path lands in the primary checkout. Read `git diff main...`, then each changed file whole. + +Check: + +- Every acceptance check the lane owns holds. Run what proves it in the worktree. +- Tests lock the new behavior and would fail without the change. +- Callers of changed code still hold under the new behavior. +- Input handling, secrets, and trust boundaries the diff touches. + +Rules and codebase patterns belong to hall-monitor; leave them to it. + +You change no code: use `git diff`, `log`, `show`, and `status`, and leave the caches and build output the gate writes. + +## Output + +The first line is `VERDICT: PASS` or `VERDICT: CHANGES`. Then: + +```markdown +## Findings +- path:line — what is wrong — what would make it pass +``` + +On PASS, the findings section is `None`. A finding you cannot point at in the code is not a finding. + +Generated by agent-setup. diff --git a/.claude/settings.json b/.claude/settings.json index ec73639..b25ba70 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,5 +1,6 @@ { "enabledPlugins": { "rust-analyzer-lsp@claude-plugins-official": true - } + }, + "agent": "orchestrator" } diff --git a/.codex/agents/builder.toml b/.codex/agents/builder.toml new file mode 100644 index 0000000..4d0fb20 --- /dev/null +++ b/.codex/agents/builder.toml @@ -0,0 +1,38 @@ +name = "builder" +description = ''' +Lane agent started only by the orchestrator. Implements one lane of a spec in its own git worktree, runs the gate, and returns a build report. +''' +sandbox_mode = "workspace-write" +developer_instructions = ''' +You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. + +Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. + +Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. + +Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. + +Satisfy the acceptance checks the brief gives this lane, following `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. Run `task check` in the worktree. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. When it fails, fix the cause, or stop and report the failure. Commit on the lane's branch, staging files by name. + +On a later round the brief carries reviewer findings and hall-monitor rows. Fix each one, or say in the report why it does not apply. + +## Output + +Return only the build report. + +```markdown +## Done +What now satisfies the lane's acceptance checks. + +## Gate +The command and what it returned. + +## Departures +Where you left the spec or the conventions, and why. None, when there are none. + +## Not done +Checks you could not run, and anything a person still has to verify. +``` + +Generated by agent-setup. +''' diff --git a/.codex/agents/hall-monitor.toml b/.codex/agents/hall-monitor.toml new file mode 100644 index 0000000..619c7a1 --- /dev/null +++ b/.codex/agents/hall-monitor.toml @@ -0,0 +1,53 @@ +name = "hall-monitor" +description = ''' +Lane agent started only by the orchestrator. Checks one lane against the follow-the-rules skill and this codebase's established patterns, out to callers, callees, and tests. Read-only. +''' +sandbox_mode = "read-only" +developer_instructions = ''' +You check one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals against two standards you did not write: the `follow-the-rules` skill is the principles, the surrounding code is the patterns, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` adds this repository's own rules. Enforce them; invent none. + +Invoke the `follow-the-rules` skill before reading any code, and read the example it links for each language under review. When it cannot be loaded, return `rules unavailable` and stop. + +## Scope + +The brief names the branch, the worktree path, and the files; otherwise take `git diff --name-only main...`. The worktree path is absolute: run every command there and give every file tool an absolute path under it, because a relative path lands in the primary checkout. Skip lockfiles, generated files, and vendored trees. Read each file whole. + +You are read-only: `git diff`, `log`, `show`, `status`, and `blame`, and nothing that edits, commits, or switches branches. + +## Follow the execution tree + +For every symbol the diff added or changed, walk one hop each way, further when a signature, return type, error, or invariant changed: + +- Callers: a caller broken by the new behavior is a finding, even outside the diff. +- Callees: the change hand-rolls something a neighbouring module already provides. +- Tests: a changed behavior with no changed test is a finding. +- Dead ends: code whose only caller is its own test is dead, and so is that test. + +## Establish the pattern before judging + +Read the two or three nearest files that do the same kind of work. Divergence from a pattern established in several places is a finding; something seen once is not a pattern. When the pattern itself breaks a rule, the rule wins; say so. + +## Verify before you report + +Every row is a claim about code you read. Grep before calling code dead. Cite the duplicate, and the two files that establish a pattern. Name the simpler version before asking for a simplification. Drop any finding you cannot substantiate. + +## Severity + +- `VIOLATION`: a numbered rule in `follow-the-rules`. +- `PATTERN`: breaks how this codebase already does the same thing, or a caller, contract, or test elsewhere. +- `SMELL`: one of the flexible rules in `follow-the-rules`. + +Linter-owned formatting and naming taste get no row. + +## Output + +Table rows only, no header, no summary: + +``` +| | | | | | +``` + +When nothing breaks, return exactly `clean: `. + +Generated by agent-setup. +''' diff --git a/.codex/agents/reviewer.toml b/.codex/agents/reviewer.toml new file mode 100644 index 0000000..57d6ac3 --- /dev/null +++ b/.codex/agents/reviewer.toml @@ -0,0 +1,34 @@ +name = "reviewer" +description = ''' +Lane agent started only by the orchestrator. Reviews one lane's diff against its spec and returns PASS or CHANGES. Changes no code. +''' +sandbox_mode = "workspace-write" +developer_instructions = ''' +You review one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. You did not write this code. The builder's report is a claim; check it against the code. + +The brief names the spec, the lane's acceptance checks, the branch, and the absolute worktree path. Run every command there and give every file tool an absolute path under it: a relative path lands in the primary checkout. Read `git diff main...`, then each changed file whole. + +Check: + +- Every acceptance check the lane owns holds. Run what proves it in the worktree. +- Tests lock the new behavior and would fail without the change. +- Callers of changed code still hold under the new behavior. +- Input handling, secrets, and trust boundaries the diff touches. + +Rules and codebase patterns belong to hall-monitor; leave them to it. + +You change no code: use `git diff`, `log`, `show`, and `status`, and leave the caches and build output the gate writes. + +## Output + +The first line is `VERDICT: PASS` or `VERDICT: CHANGES`. Then: + +```markdown +## Findings +- path:line — what is wrong — what would make it pass +``` + +On PASS, the findings section is `None`. A finding you cannot point at in the code is not a finding. + +Generated by agent-setup. +''' diff --git a/.codex/config.toml b/.codex/config.toml index 3b23fc7..655d083 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,2 +1,52 @@ +# agent-setup:start +developer_instructions = ''' +These instructions are for the main session only. If you were started as a subagent, such as a builder, reviewer, or hall-monitor, ignore this file and follow your own instructions. + +# Orchestrator + +You are the main session in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Work with independent parts becomes lanes: a `builder` per lane writes the code, a `reviewer` and a `hall-monitor` check it, and you write none of it. A single small change with no independent parts, you make yourself. + +A spec or plan is whatever the user names. Ask for acceptance checks when it has none. + +- Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. +- Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` +- Default branch: `main` +- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. + +## Loop + +1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. +2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. +3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. +4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. +6. As each builder returns, run `task check` in its worktree. +7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. +8. Send findings to the same builder (in Claude Code, `SendMessage` to its agent ID), or, where a host cannot continue a finished subagent, to a new builder with the original brief, its last report, and the findings. Repeat steps 6 and 7. After two rounds with findings left, stop the lane and put it in front of the user. +9. A lane is ready when the gate passes, the reviewer says PASS, and hall-monitor returns `clean`. When the user asks, integrate ready lanes one at a time onto `main`, as the note says. Push only when the user asks. + +When hall-monitor returns `rules unavailable`, this host cannot load the `follow-the-rules` skill and no lane can reach `clean`. Stop starting hall-monitors, tell the user once, and ask whether a reviewer PASS alone makes a lane ready. + +## A brief contains + +The observable end state; the spec location and this lane's acceptance checks; the worktree path and branch; the files the lane may touch and the files it must leave alone; the gate; and the worktree and git note, verbatim. + +## Verification + +A builder's report is a claim. Read `git diff --stat`, then the hunks that matter. Reproduce a blocker before re-planning, and check "flaky", "pre-existing", and "out of scope" yourself. Look for weakened tests, silenced checks, commented-out code, scope past the brief, edits in the primary checkout instead of the worktree, and the seam where two lanes meet. + +## Report + +- **Verdict**: per lane, its commit, the reviewer's verdict, hall-monitor's result, and whether it holds. +- **Verified**: the commands you ran and what they returned. +- **Not done**: work left out, blocked, or left for a person, and why. +- **Next**: the next action, or the decision you need. + +Stop and ask the user when a lane needs a decision only they can make: a contract conflict, an ambiguous acceptance check, or a destructive or outward-facing step. + +Generated by agent-setup. +''' +# agent-setup:end + approval_policy = "never" sandbox_mode = "danger-full-access" diff --git a/.cursor/agents/builder.md b/.cursor/agents/builder.md new file mode 100644 index 0000000..f9e45c9 --- /dev/null +++ b/.cursor/agents/builder.md @@ -0,0 +1,38 @@ +--- +name: builder +description: "Lane agent started only by the orchestrator. Implements one lane of a spec in its own git worktree, runs the gate, and returns a build report." +model: inherit +readonly: false +--- + +You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. + +Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. + +Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. + +Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. + +Satisfy the acceptance checks the brief gives this lane, following `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. Run `task check` in the worktree. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. When it fails, fix the cause, or stop and report the failure. Commit on the lane's branch, staging files by name. + +On a later round the brief carries reviewer findings and hall-monitor rows. Fix each one, or say in the report why it does not apply. + +## Output + +Return only the build report. + +```markdown +## Done +What now satisfies the lane's acceptance checks. + +## Gate +The command and what it returned. + +## Departures +Where you left the spec or the conventions, and why. None, when there are none. + +## Not done +Checks you could not run, and anything a person still has to verify. +``` + +Generated by agent-setup. diff --git a/.cursor/agents/hall-monitor.md b/.cursor/agents/hall-monitor.md new file mode 100644 index 0000000..18bca6f --- /dev/null +++ b/.cursor/agents/hall-monitor.md @@ -0,0 +1,53 @@ +--- +name: hall-monitor +description: "Lane agent started only by the orchestrator. Checks one lane against the follow-the-rules skill and this codebase's established patterns, out to callers, callees, and tests. Read-only." +model: inherit +readonly: true +--- + +You check one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals against two standards you did not write: the `follow-the-rules` skill is the principles, the surrounding code is the patterns, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` adds this repository's own rules. Enforce them; invent none. + +Invoke the `follow-the-rules` skill before reading any code, and read the example it links for each language under review. When it cannot be loaded, return `rules unavailable` and stop. + +## Scope + +The brief names the branch, the worktree path, and the files; otherwise take `git diff --name-only main...`. The worktree path is absolute: run every command there and give every file tool an absolute path under it, because a relative path lands in the primary checkout. Skip lockfiles, generated files, and vendored trees. Read each file whole. + +You are read-only: `git diff`, `log`, `show`, `status`, and `blame`, and nothing that edits, commits, or switches branches. + +## Follow the execution tree + +For every symbol the diff added or changed, walk one hop each way, further when a signature, return type, error, or invariant changed: + +- Callers: a caller broken by the new behavior is a finding, even outside the diff. +- Callees: the change hand-rolls something a neighbouring module already provides. +- Tests: a changed behavior with no changed test is a finding. +- Dead ends: code whose only caller is its own test is dead, and so is that test. + +## Establish the pattern before judging + +Read the two or three nearest files that do the same kind of work. Divergence from a pattern established in several places is a finding; something seen once is not a pattern. When the pattern itself breaks a rule, the rule wins; say so. + +## Verify before you report + +Every row is a claim about code you read. Grep before calling code dead. Cite the duplicate, and the two files that establish a pattern. Name the simpler version before asking for a simplification. Drop any finding you cannot substantiate. + +## Severity + +- `VIOLATION`: a numbered rule in `follow-the-rules`. +- `PATTERN`: breaks how this codebase already does the same thing, or a caller, contract, or test elsewhere. +- `SMELL`: one of the flexible rules in `follow-the-rules`. + +Linter-owned formatting and naming taste get no row. + +## Output + +Table rows only, no header, no summary: + +``` +| | | | | | +``` + +When nothing breaks, return exactly `clean: `. + +Generated by agent-setup. diff --git a/.cursor/agents/reviewer.md b/.cursor/agents/reviewer.md new file mode 100644 index 0000000..2d70548 --- /dev/null +++ b/.cursor/agents/reviewer.md @@ -0,0 +1,34 @@ +--- +name: reviewer +description: "Lane agent started only by the orchestrator. Reviews one lane's diff against its spec and returns PASS or CHANGES. Changes no code." +model: inherit +readonly: false +--- + +You review one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. You did not write this code. The builder's report is a claim; check it against the code. + +The brief names the spec, the lane's acceptance checks, the branch, and the absolute worktree path. Run every command there and give every file tool an absolute path under it: a relative path lands in the primary checkout. Read `git diff main...`, then each changed file whole. + +Check: + +- Every acceptance check the lane owns holds. Run what proves it in the worktree. +- Tests lock the new behavior and would fail without the change. +- Callers of changed code still hold under the new behavior. +- Input handling, secrets, and trust boundaries the diff touches. + +Rules and codebase patterns belong to hall-monitor; leave them to it. + +You change no code: use `git diff`, `log`, `show`, and `status`, and leave the caches and build output the gate writes. + +## Output + +The first line is `VERDICT: PASS` or `VERDICT: CHANGES`. Then: + +```markdown +## Findings +- path:line — what is wrong — what would make it pass +``` + +On PASS, the findings section is `None`. A finding you cannot point at in the code is not a finding. + +Generated by agent-setup. diff --git a/.cursor/rules/orchestrator.mdc b/.cursor/rules/orchestrator.mdc new file mode 100644 index 0000000..5401d85 --- /dev/null +++ b/.cursor/rules/orchestrator.mdc @@ -0,0 +1,50 @@ +--- +description: "The main session's role here. Runs a spec as parallel builder lanes in git worktrees, each checked by a reviewer and a hall-monitor." +alwaysApply: true +--- + +These instructions are for the main session only. If you were started as a subagent, such as a builder, reviewer, or hall-monitor, ignore this file and follow your own instructions. + +# Orchestrator + +You are the main session in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Work with independent parts becomes lanes: a `builder` per lane writes the code, a `reviewer` and a `hall-monitor` check it, and you write none of it. A single small change with no independent parts, you make yourself. + +A spec or plan is whatever the user names. Ask for acceptance checks when it has none. + +- Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. +- Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` +- Default branch: `main` +- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. + +## Loop + +1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. +2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. +3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. +4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. +6. As each builder returns, run `task check` in its worktree. +7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. +8. Send findings to the same builder (in Claude Code, `SendMessage` to its agent ID), or, where a host cannot continue a finished subagent, to a new builder with the original brief, its last report, and the findings. Repeat steps 6 and 7. After two rounds with findings left, stop the lane and put it in front of the user. +9. A lane is ready when the gate passes, the reviewer says PASS, and hall-monitor returns `clean`. When the user asks, integrate ready lanes one at a time onto `main`, as the note says. Push only when the user asks. + +When hall-monitor returns `rules unavailable`, this host cannot load the `follow-the-rules` skill and no lane can reach `clean`. Stop starting hall-monitors, tell the user once, and ask whether a reviewer PASS alone makes a lane ready. + +## A brief contains + +The observable end state; the spec location and this lane's acceptance checks; the worktree path and branch; the files the lane may touch and the files it must leave alone; the gate; and the worktree and git note, verbatim. + +## Verification + +A builder's report is a claim. Read `git diff --stat`, then the hunks that matter. Reproduce a blocker before re-planning, and check "flaky", "pre-existing", and "out of scope" yourself. Look for weakened tests, silenced checks, commented-out code, scope past the brief, edits in the primary checkout instead of the worktree, and the seam where two lanes meet. + +## Report + +- **Verdict**: per lane, its commit, the reviewer's verdict, hall-monitor's result, and whether it holds. +- **Verified**: the commands you ran and what they returned. +- **Not done**: work left out, blocked, or left for a person, and why. +- **Next**: the next action, or the decision you need. + +Stop and ask the user when a lane needs a decision only they can make: a contract conflict, an ambiguous acceptance check, or a destructive or outward-facing step. + +Generated by agent-setup. diff --git a/.specify/init-options.json b/.specify/init-options.json index 46522af..acb242c 100644 --- a/.specify/init-options.json +++ b/.specify/init-options.json @@ -1,9 +1,9 @@ { - "ai": "claude", + "ai": "codex", "ai_skills": true, "feature_numbering": "sequential", "here": true, - "integration": "claude", + "integration": "codex", "script": "sh", "speckit_version": "1.0.7" } diff --git a/.specify/integration.json b/.specify/integration.json index d1af220..4ded5a4 100644 --- a/.specify/integration.json +++ b/.specify/integration.json @@ -6,15 +6,15 @@ "codex" ], "integration_settings": { - "claude": { + "codex": { "script": "sh", "invoke_separator": "-" }, - "codex": { + "claude": { "script": "sh", "invoke_separator": "-" } }, - "integration": "claude", - "default_integration": "claude" + "integration": "codex", + "default_integration": "codex" } diff --git a/.specify/integrations/claude.manifest.json b/.specify/integrations/claude.manifest.json index 1c03f53..c2e8775 100644 --- a/.specify/integrations/claude.manifest.json +++ b/.specify/integrations/claude.manifest.json @@ -1,7 +1,7 @@ { "integration": "claude", "version": "1.0.7", - "installed_at": "2026-09-26T20:36:38.913924+00:00", + "installed_at": "2026-10-15T18:56:54.329502+00:00", "files": { ".claude/skills/speckit-analyze/SKILL.md": "3237cd827194efaf6bb06ba05ef9bc1a703a223d362f5e34d0558c5a38ae34d0", ".claude/skills/speckit-clarify/SKILL.md": "164f49ef87cb2e922585316f5281b455a8e1940b1efd25317d517a567acae472", diff --git a/.specify/integrations/codex.manifest.json b/.specify/integrations/codex.manifest.json index c72431d..f41ff4e 100644 --- a/.specify/integrations/codex.manifest.json +++ b/.specify/integrations/codex.manifest.json @@ -1,7 +1,7 @@ { "integration": "codex", "version": "1.0.7", - "installed_at": "2026-09-26T20:36:41.890743+00:00", + "installed_at": "2026-10-15T18:57:38.027042+00:00", "files": { ".agents/skills/speckit-analyze/SKILL.md": "0b3261b13cc33537f24b3e1f6d5320694c348302c385d0046dc6b958cf2db6cb", ".agents/skills/speckit-clarify/SKILL.md": "f6acfbc82c96c0d91b2429fd0b51ce7df7f94b003d1b73acc54470d48bcc455e", diff --git a/.specify/integrations/speckit.manifest.json b/.specify/integrations/speckit.manifest.json index be2de9b..1c4db02 100644 --- a/.specify/integrations/speckit.manifest.json +++ b/.specify/integrations/speckit.manifest.json @@ -3,17 +3,17 @@ "version": "1.0.7", "installed_at": "2026-09-26T20:36:38.928967+00:00", "files": { - ".specify/scripts/bash/common.sh": "170e91ece502b88d83c715e427473843e0b358f550e86e3ff524546df405a9ca", + ".specify/scripts/bash/common.sh": "fdfebd1274594eb3fbfccdf7968d5dd1243aaf244daf262d7c9d0c012c5d21a6", ".specify/scripts/bash/setup-plan.sh": "d0bd298c026446f3c63167130d65e49e4aa4485de6bef18bcdfd57b19aa0de96", - ".specify/scripts/bash/setup-tasks.sh": "4a33dd1e6c32ddc7d570f4b538572c54069192573eed0ec654d9fb826e31a4fe", - ".specify/scripts/bash/check-prerequisites.sh": "daa377146db4fb69912f42611a7b91c5d55873b3e3e27ed33bd8d67505826344", + ".specify/scripts/bash/setup-tasks.sh": "0350b2def158c4dc333cd888fc5a3b10785b3d5c2cf936f93e910242ea9d507d", + ".specify/scripts/bash/check-prerequisites.sh": "13be175548848bd84e96a90cf9be87665c2e68603b2eaa3e19187e7ca8b4fcb0", ".specify/scripts/bash/resolve-template.sh": "829e227096abc8bf0889889ec9f792f503ca5d395b7836a8a7eb739ee75214e7", ".specify/scripts/bash/create-new-feature.sh": "9f7a741d9766a6c1c5d5e44368f2c6bea6026b399ff6f0055870f760afdb8726", ".specify/templates/constitution-template.md": "ce7549540fa45543cca797a150201d868e64495fdff39dc38246fb17bd4024b3", - ".specify/templates/checklist-template.md": "856532b3cb66171c662cc16f16b31a5856e4655a8666aad1e545bbfc7f603ca1", - ".specify/templates/tasks-template.md": "fc29a233f6f5a27ca31f1aa46b596af6500c627441c6e62b2bc4a1d721525842", + ".specify/templates/checklist-template.md": "70bbc48e884fab372ffb09e83e78ff983e28b69caebf8cd9964a02b6836683ac", + ".specify/templates/tasks-template.md": "b0f527d41e546af0c31903e04f9b20965b6b497b573792198f663a64ce128863", ".specify/templates/spec-template.md": "3945437fc35cd30a5b2bf7beea680337c3516826d3efa5a6b92c4a7eca1ba28e", - ".specify/templates/plan-template.md": "7e637502d41eccf0ca672496636365691fdca62ef37b27ec07fcb412dbfa90d4", + ".specify/templates/plan-template.md": "a828ad6206526574ab3fc99be6d0154588cb1c9774c5919d71b81ab5b2dbffa0", ".specify/.gitignore": "8c908410d177a1ef3d0dee16d7ad55f2ac3333df3104c4d4adee1c9b82f1dbc1" } } diff --git a/.specify/scripts/bash/check-prerequisites.sh b/.specify/scripts/bash/check-prerequisites.sh index a6a8ad8..43b56e1 100755 --- a/.specify/scripts/bash/check-prerequisites.sh +++ b/.specify/scripts/bash/check-prerequisites.sh @@ -138,27 +138,27 @@ fi # Validate required directories and files if [[ ! -d "$FEATURE_DIR" ]]; then echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2 - echo "Run /speckit-specify first to create the feature structure." >&2 + echo "Run \$speckit-specify first to create the feature structure." >&2 exit 1 fi if [[ ! -f "$IMPL_PLAN" ]]; then echo "ERROR: plan.md not found in $FEATURE_DIR" >&2 - echo "Run /speckit-plan first to create the implementation plan." >&2 + echo "Run \$speckit-plan first to create the implementation plan." >&2 exit 1 fi # Check for spec.md if required if $REQUIRE_SPEC && [[ ! -f "$FEATURE_SPEC" ]]; then echo "ERROR: spec.md not found in $FEATURE_DIR" >&2 - echo "Run /speckit-specify first to create the feature specification." >&2 + echo "Run \$speckit-specify first to create the feature specification." >&2 exit 1 fi # Check for tasks.md if required if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2 - echo "Run /speckit-tasks first to create the task list." >&2 + echo "Run \$speckit-tasks first to create the task list." >&2 exit 1 fi diff --git a/.specify/scripts/bash/common.sh b/.specify/scripts/bash/common.sh index 9efcfad..e8c3daa 100755 --- a/.specify/scripts/bash/common.sh +++ b/.specify/scripts/bash/common.sh @@ -364,7 +364,7 @@ format_speckit_command() { command_name="${command_name#speckit-}" command_name="${command_name//./$separator}" - printf '/speckit%s%s\n' "$separator" "$command_name" + printf '$speckit%s%s\n' "$separator" "$command_name" } # Escape a string for safe embedding in a JSON value (fallback when jq is unavailable). diff --git a/.specify/scripts/bash/setup-tasks.sh b/.specify/scripts/bash/setup-tasks.sh index 0383f9f..41055a7 100755 --- a/.specify/scripts/bash/setup-tasks.sh +++ b/.specify/scripts/bash/setup-tasks.sh @@ -30,13 +30,13 @@ unset _paths_output # Validate required files if [[ ! -f "$IMPL_PLAN" ]]; then echo "ERROR: plan.md not found in $FEATURE_DIR" >&2 - echo "Run /speckit-plan first to create the implementation plan." >&2 + echo "Run \$speckit-plan first to create the implementation plan." >&2 exit 1 fi if [[ ! -f "$FEATURE_SPEC" ]]; then echo "ERROR: spec.md not found in $FEATURE_DIR" >&2 - echo "Run /speckit-specify first to create the feature structure." >&2 + echo "Run \$speckit-specify first to create the feature structure." >&2 exit 1 fi diff --git a/.specify/templates/checklist-template.md b/.specify/templates/checklist-template.md index c4c4ffb..84b5a3a 100644 --- a/.specify/templates/checklist-template.md +++ b/.specify/templates/checklist-template.md @@ -4,7 +4,7 @@ **Created**: [DATE] **Feature**: [Link to spec.md or relevant documentation] -**Note**: This custom checklist is generated by the `/speckit-checklist` command based on feature context and requirements. +**Note**: This custom checklist is generated by the `$speckit-checklist` command based on feature context and requirements. **Review Ownership**: This checklist is a reviewer-owned requirements-quality review artifact. Mark an item `[x]` only when the reviewer determines the requirements-quality criterion is satisfied. **Marker Semantics**: `[x]` means the criterion has been reviewed and satisfied for requirements quality. It does not mean implementation work is complete. @@ -12,7 +12,7 @@ ============================================================================ IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only. - The /speckit-checklist command MUST replace these with actual items based on: + The $speckit-checklist command MUST replace these with actual items based on: - User's specific checklist request - Feature requirements from spec.md - Technical context from plan.md @@ -38,8 +38,8 @@ - Mark items `[x]` only after review confirms the requirement-quality criterion is satisfied - Leave items unchecked when they still require clarification, correction, or reviewer evaluation -- `/speckit-implement` reads checklist checkbox state as a gate and must not modify markers -- `checklists/requirements.md` has a separate built-in lifecycle maintained by `/speckit-specify` and `/speckit-clarify` +- `$speckit-implement` reads checklist checkbox state as a gate and must not modify markers +- `checklists/requirements.md` has a separate built-in lifecycle maintained by `$speckit-specify` and `$speckit-clarify` - Add comments or findings inline - Link to relevant resources or documentation - Items are numbered sequentially for easy reference diff --git a/.specify/templates/plan-template.md b/.specify/templates/plan-template.md index be1aa88..ee04d9f 100644 --- a/.specify/templates/plan-template.md +++ b/.specify/templates/plan-template.md @@ -4,7 +4,7 @@ **Input**: Feature specification from `/specs/[###-feature-name]/spec.md` -**Note**: This template is filled in by the `/speckit-plan` command; its definition describes the execution workflow. +**Note**: This template is filled in by the `$speckit-plan` command; its definition describes the execution workflow. ## Summary @@ -48,12 +48,12 @@ ```text specs/[###-feature]/ -├── plan.md # This file (/speckit-plan command output) -├── research.md # Phase 0 output (/speckit-plan command) -├── data-model.md # Phase 1 output (/speckit-plan command) -├── quickstart.md # Phase 1 output (/speckit-plan command) -├── contracts/ # Phase 1 output (/speckit-plan command) -└── tasks.md # Phase 2 output (/speckit-tasks command - NOT created by /speckit-plan) +├── plan.md # This file ($speckit-plan command output) +├── research.md # Phase 0 output ($speckit-plan command) +├── data-model.md # Phase 1 output ($speckit-plan command) +├── quickstart.md # Phase 1 output ($speckit-plan command) +├── contracts/ # Phase 1 output ($speckit-plan command) +└── tasks.md # Phase 2 output ($speckit-tasks command - NOT created by $speckit-plan) ``` ### Source Code (repository root) diff --git a/.specify/templates/tasks-template.md b/.specify/templates/tasks-template.md index d46a1f1..c37fc70 100644 --- a/.specify/templates/tasks-template.md +++ b/.specify/templates/tasks-template.md @@ -30,7 +30,7 @@ description: "Task list template for feature implementation" ============================================================================ IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only. - The /speckit-tasks command MUST replace these with actual tasks based on: + The $speckit-tasks command MUST replace these with actual tasks based on: - User stories from spec.md (with their priorities P1, P2, P3...) - Feature requirements from plan.md - Entities from data-model.md From 4bd46e52216a21ba187f4371594c6e3c24855d47 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 15 Oct 2026 19:19:16 -0700 Subject: [PATCH 3/4] refactor: keep desktop webview entrypoints under src --- scripts/unused/sources.mjs | 2 +- agent-debug.html => src/agent-debug.html | 2 +- index.html => src/index.html | 2 +- install-hooks.html => src/install-hooks.html | 2 +- new-focus.html => src/new-focus.html | 2 +- settings.html => src/settings.html | 2 +- vite.config.ts | 22 +++++++++++++------- 7 files changed, 21 insertions(+), 13 deletions(-) rename agent-debug.html => src/agent-debug.html (79%) rename index.html => src/index.html (81%) rename install-hooks.html => src/install-hooks.html (79%) rename new-focus.html => src/new-focus.html (79%) rename settings.html => src/settings.html (80%) diff --git a/scripts/unused/sources.mjs b/scripts/unused/sources.mjs index 228629c..0ca2d80 100644 --- a/scripts/unused/sources.mjs +++ b/scripts/unused/sources.mjs @@ -10,5 +10,5 @@ export function readSources(patterns) { export const RUST_SOURCES = ["src-tauri/src/**/*.rs", "crates/*/src/**/*.rs"]; export const FRONTEND_SOURCES = ["src/**/*.ts", "src/**/*.tsx"]; -export const HTML_ENTRIES = ["*.html"]; +export const HTML_ENTRIES = ["src/*.html"]; export const STYLESHEETS = ["src/**/*.css"]; diff --git a/agent-debug.html b/src/agent-debug.html similarity index 79% rename from agent-debug.html rename to src/agent-debug.html index 3cf13be..6c0c506 100644 --- a/agent-debug.html +++ b/src/agent-debug.html @@ -7,6 +7,6 @@
- + diff --git a/index.html b/src/index.html similarity index 81% rename from index.html rename to src/index.html index 1683568..e5addce 100644 --- a/index.html +++ b/src/index.html @@ -7,6 +7,6 @@
- + diff --git a/install-hooks.html b/src/install-hooks.html similarity index 79% rename from install-hooks.html rename to src/install-hooks.html index 8d4c0b0..3174410 100644 --- a/install-hooks.html +++ b/src/install-hooks.html @@ -7,6 +7,6 @@
- + diff --git a/new-focus.html b/src/new-focus.html similarity index 79% rename from new-focus.html rename to src/new-focus.html index d5dab23..3c60aba 100644 --- a/new-focus.html +++ b/src/new-focus.html @@ -7,6 +7,6 @@
- + diff --git a/settings.html b/src/settings.html similarity index 80% rename from settings.html rename to src/settings.html index 62dac55..c4d0839 100644 --- a/settings.html +++ b/src/settings.html @@ -7,6 +7,6 @@
- + diff --git a/vite.config.ts b/vite.config.ts index ebd592f..74e8f39 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -5,7 +5,13 @@ import { defineConfig } from "vite"; const __dirname = dirname(fileURLToPath(import.meta.url)); +const uiRoot = resolve(__dirname, "src"); + export default defineConfig({ + root: uiRoot, + envDir: __dirname, + cacheDir: resolve(__dirname, "node_modules/.vite"), + publicDir: false, plugins: [react()], clearScreen: false, server: { @@ -13,20 +19,22 @@ export default defineConfig({ strictPort: true, }, build: { + outDir: resolve(__dirname, "dist"), + emptyOutDir: true, rollupOptions: { input: { - main: resolve(__dirname, "index.html"), - newFocus: resolve(__dirname, "new-focus.html"), - settings: resolve(__dirname, "settings.html"), - agentDebug: resolve(__dirname, "agent-debug.html"), - installHooks: resolve(__dirname, "install-hooks.html"), + main: resolve(uiRoot, "index.html"), + newFocus: resolve(uiRoot, "new-focus.html"), + settings: resolve(uiRoot, "settings.html"), + agentDebug: resolve(uiRoot, "agent-debug.html"), + installHooks: resolve(uiRoot, "install-hooks.html"), }, }, }, test: { globals: true, environment: "jsdom", - setupFiles: ["./vitest.setup.ts"], - include: ["src/**/*.test.{ts,tsx}", "scripts/**/*.test.mjs"], + setupFiles: [resolve(__dirname, "vitest.setup.ts")], + include: ["**/*.test.{ts,tsx}", "../scripts/**/*.test.mjs"], }, }); From c9fa25987be795cff4df244a693d3055269b57d9 Mon Sep 17 00:00:00 2001 From: archae0pteryx Date: Thu, 15 Oct 2026 19:36:13 -0700 Subject: [PATCH 4/4] Resolve foundation setup and archive planning review findings --- .claude/agents/builder.md | 4 +-- .claude/agents/orchestrator.md | 4 +-- .codex/agents/builder.toml | 7 ++-- .codex/agents/hall-monitor.toml | 3 +- .codex/agents/reviewer.toml | 3 +- .codex/config.toml | 6 ++-- .cursor/agents/builder.md | 4 +-- .cursor/rules/orchestrator.mdc | 4 +-- CONTEXT.md | 2 +- issues/051-ranch-animal-vocabulary-seam.md | 5 +-- specs/002-speckit-docs-pass/pass-record.md | 23 +++++++++++-- .../contracts/claude-ingestion.md | 13 +++++--- .../contracts/data-root-migration.md | 4 ++- .../contracts/ranch-db-v1.sql | 2 +- .../008-claude-session-storage/data-model.md | 6 ++-- specs/008-claude-session-storage/plan.md | 5 ++- .../008-claude-session-storage/quickstart.md | 32 ++++++++++++------- specs/008-claude-session-storage/spec.md | 6 ++-- 18 files changed, 89 insertions(+), 44 deletions(-) diff --git a/.claude/agents/builder.md b/.claude/agents/builder.md index 25b965a..5d92f4e 100644 --- a/.claude/agents/builder.md +++ b/.claude/agents/builder.md @@ -7,9 +7,9 @@ skills: follow-the-rules You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. -Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. +Use the existing worktree and branch supplied in your brief; verify them before editing and do not recreate them. Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. -Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md index 9dfef3b..edc6a14 100644 --- a/.claude/agents/orchestrator.md +++ b/.claude/agents/orchestrator.md @@ -14,14 +14,14 @@ A spec or plan is whatever the user names. Ask for acceptance checks when it has - Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. - Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` - Default branch: `main` -- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +- Worktree and git note, quoted into every brief: The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. ## Loop 1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. 2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. 3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. -4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +4. Create each lane's branch and worktree once from `main`, as the note says, and pass the existing worktree's absolute path and branch to its builder. 5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. 6. As each builder returns, run `task check` in its worktree. 7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. diff --git a/.codex/agents/builder.toml b/.codex/agents/builder.toml index 4d0fb20..c73d812 100644 --- a/.codex/agents/builder.toml +++ b/.codex/agents/builder.toml @@ -2,13 +2,14 @@ name = "builder" description = ''' Lane agent started only by the orchestrator. Implements one lane of a spec in its own git worktree, runs the gate, and returns a build report. ''' -sandbox_mode = "workspace-write" developer_instructions = ''' +Codex subagents inherit the parent session's permissions. Role read/write boundaries below are instructions, not separate sandboxes. + You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. -Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. +Use the existing worktree and branch supplied in your brief; verify them before editing and do not recreate them. Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. -Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. diff --git a/.codex/agents/hall-monitor.toml b/.codex/agents/hall-monitor.toml index 619c7a1..40eeba4 100644 --- a/.codex/agents/hall-monitor.toml +++ b/.codex/agents/hall-monitor.toml @@ -2,8 +2,9 @@ name = "hall-monitor" description = ''' Lane agent started only by the orchestrator. Checks one lane against the follow-the-rules skill and this codebase's established patterns, out to callers, callees, and tests. Read-only. ''' -sandbox_mode = "read-only" developer_instructions = ''' +Codex subagents inherit the parent session's permissions. Role read/write boundaries below are instructions, not separate sandboxes. + You check one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals against two standards you did not write: the `follow-the-rules` skill is the principles, the surrounding code is the patterns, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` adds this repository's own rules. Enforce them; invent none. Invoke the `follow-the-rules` skill before reading any code, and read the example it links for each language under review. When it cannot be loaded, return `rules unavailable` and stop. diff --git a/.codex/agents/reviewer.toml b/.codex/agents/reviewer.toml index 57d6ac3..0ad7ed0 100644 --- a/.codex/agents/reviewer.toml +++ b/.codex/agents/reviewer.toml @@ -2,8 +2,9 @@ name = "reviewer" description = ''' Lane agent started only by the orchestrator. Reviews one lane's diff against its spec and returns PASS or CHANGES. Changes no code. ''' -sandbox_mode = "workspace-write" developer_instructions = ''' +Codex subagents inherit the parent session's permissions. Role read/write boundaries below are instructions, not separate sandboxes. + You review one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. You did not write this code. The builder's report is a claim; check it against the code. The brief names the spec, the lane's acceptance checks, the branch, and the absolute worktree path. Run every command there and give every file tool an absolute path under it: a relative path lands in the primary checkout. Read `git diff main...`, then each changed file whole. diff --git a/.codex/config.toml b/.codex/config.toml index 655d083..9c61591 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,5 +1,7 @@ # agent-setup:start developer_instructions = ''' +Codex subagents inherit the parent session's permissions. Role read/write boundaries below are instructions, not separate sandboxes. + These instructions are for the main session only. If you were started as a subagent, such as a builder, reviewer, or hall-monitor, ignore this file and follow your own instructions. # Orchestrator @@ -11,14 +13,14 @@ A spec or plan is whatever the user names. Ask for acceptance checks when it has - Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. - Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` - Default branch: `main` -- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +- Worktree and git note, quoted into every brief: The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. ## Loop 1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. 2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. 3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. -4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +4. Create each lane's branch and worktree once from `main`, as the note says, and pass the existing worktree's absolute path and branch to its builder. 5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. 6. As each builder returns, run `task check` in its worktree. 7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. diff --git a/.cursor/agents/builder.md b/.cursor/agents/builder.md index f9e45c9..cfab3c5 100644 --- a/.cursor/agents/builder.md +++ b/.cursor/agents/builder.md @@ -7,9 +7,9 @@ readonly: false You implement one lane in adhd-ranch, a Tauri v2 and React menubar/tray issue tracker with Rust domain, storage, and command crates, Markdown-backed Focuses and Tasks, and roaming pixel animals. Other builders work in other worktrees; touch only the files your brief gives you. -Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. +Use the existing worktree and branch supplied in your brief; verify them before editing and do not recreate them. Your worktree path is absolute. Run every command there, with `cd &&` or `git -C `, and give every file tool an absolute path under it: a relative path lands in the primary checkout. -Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. Before writing code, invoke the `follow-the-rules` skill and read the example it links for your language. Its rules bind every line. diff --git a/.cursor/rules/orchestrator.mdc b/.cursor/rules/orchestrator.mdc index 5401d85..7d4e8d2 100644 --- a/.cursor/rules/orchestrator.mdc +++ b/.cursor/rules/orchestrator.mdc @@ -14,14 +14,14 @@ A spec or plan is whatever the user names. Ask for acceptance checks when it has - Gate: `task check`. For Rust use `task test:rust` and `task lint:rust`; for the frontend use `task test:web`, `task lint:web`, and `task typecheck`; for generated types use `task gen-types:check`; run `task check:windows` for changes to `src-tauri/**`, `crates/**`, `package.json`, `package-lock.json`, `Cargo.toml`, or `Cargo.lock` as required by the repository ship-pr skill. - Conventions: `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md` - Default branch: `main` -- Worktree and git note, quoted into every brief: Create each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. +- Worktree and git note, quoted into every brief: The orchestrator creates each worktree with `git worktree add /Users/ryan/Code/killallgit/adhd-ranch/.worktrees/ -b chore/ main`, after adding `.worktrees/` to `.git/info/exclude` once; before the first edit, confirm you are on the branch the brief names, in the worktree it names, and use built-in file tools rather than Serena in worktree isolation, as `CLAUDE.md` requires. Branches use `/` with `feat`, `chore`, `fix`, `spike`, or `hotfix` (replace `chore` in that command when another type fits); commit messages are one plain sentence, with no co-author attribution. Integrate by following `.claude/skills/ship-pr/SKILL.md`: rebase onto the actual base, run the gate, obtain a review and resolve findings, then squash-merge with green CI when the user asks. ## Loop 1. Read the spec, the files it names, and `CLAUDE.md` and `issues/README.md`; prefix shell commands with `rtk` as required by `/Users/ryan/.codex/RTK.md`. 2. Cut lanes that can be verified alone. Lanes that edit the same file merge, or run in sequence. Say so when the work never needed parallelism. 3. Write any contract two lanes share and the spec leaves open, such as a wire format or a shared type, into both briefs word for word. -4. Create a branch and worktree per lane from `main`, as the note says, and record each worktree's absolute path. +4. Create each lane's branch and worktree once from `main`, as the note says, and pass the existing worktree's absolute path and branch to its builder. 5. Start every independent lane's builder in one message. A dependent lane starts after the lane it needs is integrated. 6. As each builder returns, run `task check` in its worktree. 7. Start that lane's `reviewer` and `hall-monitor` together, briefed with the spec location, the lane's acceptance checks, the branch, and the worktree path, and none of the builder's reasoning. diff --git a/CONTEXT.md b/CONTEXT.md index e53d25c..3f14339 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -63,7 +63,7 @@ Remove a Timer from its owner. Clearing an expired Timer returns its owner to no _Avoid_: using "clear" for Tasks or Focuses **TimerPreset**: -A named duration choice for a Timer: 2m, 4m, 8m, 16m, 32m, or Custom minutes. +A named duration choice for a Timer: built-in 10m, 30m, and 60m chips, plus saved custom-minute chips. **Limit**: A soft threshold on how much work is open at once, such as how many Focuses exist or how many Tasks one Focus holds. Going past a Limit blocks nothing. Agent Sessions don't count toward Limits. diff --git a/issues/051-ranch-animal-vocabulary-seam.md b/issues/051-ranch-animal-vocabulary-seam.md index 7327b38..6ae4e7d 100644 --- a/issues/051-ranch-animal-vocabulary-seam.md +++ b/issues/051-ranch-animal-vocabulary-seam.md @@ -2,7 +2,7 @@ ## Owning specification -`specs/003-ranch-today/spec.md` — FR-004; `specs/001-render-domain-seam/spec.md` — FR-013 +`specs/003-ranch-today/spec.md` — FR-004 ## What to build @@ -13,7 +13,8 @@ These values describe any Animal, not Pig-specific assets or physical policy. Rename those shared TypeScript types, modules, and wrappers to Animal vocabulary. Keep the `update_pig_rects`, `set_pig_drag_active`, and `gather-pigs` IPC names as compatibility contracts, -as spec 001 permits. Keep `PigSprite`, its assets, and the Rust Pig profile species-specific. +as `specs/001-render-domain-seam/spec.md` FR-013 permits (supporting context). Keep `PigSprite`, +its assets, and the Rust Pig profile species-specific. Do not repeat the scene, projection, region, or selection cutover from PR #88. ## Completion promise diff --git a/specs/002-speckit-docs-pass/pass-record.md b/specs/002-speckit-docs-pass/pass-record.md index e2154a9..68d4c49 100644 --- a/specs/002-speckit-docs-pass/pass-record.md +++ b/specs/002-speckit-docs-pass/pass-record.md @@ -99,7 +99,26 @@ HTML entrypoint move as separate changes. under root `dist/`, matching Tauri's existing URLs. - JSON/TOML parsing, Spec Kit manifest hashes, shell syntax and command-format checks, local Markdown links, and `git diff --check` passed. -- The spec 008 files match the saved archive planning apart from the 002-to-008 path renumbering. - Product and follow-on spec lifecycle states are unchanged. +- The initial spec 008 carry-forward matched the saved archive planning apart from the 002-to-008 + path renumbering. Review corrections below supersede that exact-copy claim. Product and follow-on + spec lifecycle states are unchanged. - Native desktop interaction was not rerun; the entrypoint change is covered by content, HTTP, production-output, and regression-gate checks. + +### Independent review corrections + +PR #90 review found contradictions in the carried-forward setup and archive plan. These are +planning corrections, with no archive implementation or new product approval: + +- The orchestrator creates each worktree once; builders use the supplied existing path and branch. +- Codex roles inherit parent permissions. Ineffective per-agent sandbox declarations were removed; + role boundaries remain instructions, and the existing parent permission policy is unchanged. +- The TimerPreset glossary now matches PR #89. Issue 051 has one owning specification, with + spec 001 retained only as supporting context. +- Unterminated transcript tails remain pending even after stable valid-JSON reads. The framing + contract, model, schema, and validation now require a newline before a record is committed. +- Graceful shutdown drains every accepted queued job; forced termination cannot promise uncommitted + receipts. The validation plan includes a queue-barrier/reopen case. +- Data-root migration explicitly detects an installed legacy wrapper as unhealthy without implicit + startup repair; explicit Install/Repair replaces it, with an existing-installation regression. +- The future manual archive smoke uses temporary Ranch and Claude roots inherited by both processes. diff --git a/specs/008-claude-session-storage/contracts/claude-ingestion.md b/specs/008-claude-session-storage/contracts/claude-ingestion.md index ad19d71..6f5b029 100644 --- a/specs/008-claude-session-storage/contracts/claude-ingestion.md +++ b/specs/008-claude-session-storage/contracts/claude-ingestion.md @@ -76,9 +76,10 @@ without reading their content. `Stop`, `StopFailure`, `SessionEnd`, and `SubagentStop` use the terminal retry profile: retry until two consecutive `(length, mtime, boundary digest)` observations are unchanged, subject to the documented attempt/time cap. This lets asynchronous final rows land without polling forever. -- On the second stable read, a non-newline tail that parses as exactly one complete JSON value may - be committed. Otherwise the cursor stays at its start and the condition remains content-free in - diagnostics. +- Stable observations end the retry schedule; they do not prove record framing is final. Every + non-newline tail remains pending, even if it parses as a complete JSON value. A later newline + commits that value and its delimiter as one record, never a separate empty record. The cursor + stays at the tail start and diagnostics remain content-free. - Insert transcript rows and advance cursor/ordinal in one transaction. - `boundary_sha256` is SHA-256 over `[max(0, byte_cursor - 4096), byte_cursor)`. If the file shrinks below the cursor, the platform file identity changes, or that exact window no longer matches, @@ -107,8 +108,10 @@ No record-type allowlist controls persistence. - Disabling archival and checking the admission gate share one linearization point. Every firing after disable is rejected; every job admitted before it remains worker-owned and finishes exactly once. Re-enabling allows only new firings and performs no historical census. -- App shutdown asks the worker to finish its current receipt transaction and then stops; it does - not make the hook client wait. +- Graceful app shutdown closes admission, drains every accepted queued job and its transactions, + then stops the worker. It does not make the hook client wait. Forced termination is best effort: + committed transactions survive, and later syncs recover transcript rows; uncommitted receipts + are not guaranteed. - Queue saturation/closure before admission increments `dropped_jobs_this_run`. An accepted-job, database, or transcript failure increments only its bounded content-free error category. Neither blocks or fails Claude; a later transcript sync can recover transcript rows, while a firing diff --git a/specs/008-claude-session-storage/contracts/data-root-migration.md b/specs/008-claude-session-storage/contracts/data-root-migration.md index 7bacd9e..9dc2fbb 100644 --- a/specs/008-claude-session-storage/contracts/data-root-migration.md +++ b/specs/008-claude-session-storage/contracts/data-root-migration.md @@ -35,6 +35,8 @@ client, or socket paths: `.adhd-ranch`; it ignores `ranch.db`. - The migration never copies, merges, deletes, or resolves conflicts file-by-file. - The plugin wrapper must resolve the same new default root in the release that enables this - migration; otherwise it could continue sending to the legacy socket. + migration. An existing installation targeting the legacy root is reported unhealthy and left + unchanged at startup. Explicit Install/Repair replaces the complete managed wrapper; regression + tests must cover legacy detection, no implicit repair, and new-root delivery after repair. - The rapid-prototype exception for the unshipped archive schema/protocol does not apply here: existing Focus, Timer, Settings, client, and socket state still receive this whole-root migration. diff --git a/specs/008-claude-session-storage/contracts/ranch-db-v1.sql b/specs/008-claude-session-storage/contracts/ranch-db-v1.sql index af48d9d..19ef952 100644 --- a/specs/008-claude-session-storage/contracts/ranch-db-v1.sql +++ b/specs/008-claude-session-storage/contracts/ranch-db-v1.sql @@ -79,7 +79,7 @@ CREATE TABLE claude_transcript_records ( byte_length INTEGER NOT NULL CHECK (byte_length >= 0), raw_sha256 BLOB NOT NULL CHECK (length(raw_sha256) = 32), raw_json BLOB NOT NULL, - record_delimiter BLOB NOT NULL CHECK (record_delimiter IN (X'', X'0A', X'0D0A')), + record_delimiter BLOB NOT NULL CHECK (record_delimiter IN (X'0A', X'0D0A')), parse_error TEXT, record_type TEXT, entry_uuid TEXT, diff --git a/specs/008-claude-session-storage/data-model.md b/specs/008-claude-session-storage/data-model.md index e89f489..0aeeb82 100644 --- a/specs/008-claude-session-storage/data-model.md +++ b/specs/008-claude-session-storage/data-model.md @@ -136,8 +136,8 @@ Constraints and indexes: - Unique `(canonical_path, generation)`. - At most one non-superseded generation per canonical path. -- `byte_cursor` is the first unread byte. An incomplete tail is not persisted separately and is - reread from that offset on the next sync. +- `byte_cursor` is the first unread byte. An unterminated tail, even valid JSON, is not persisted + separately and is reread from that offset on the next sync. - `byte_cursor`, inserted records, and the exact boundary digest update in one transaction. - A canonical path may correlate to only the session id supplied by its validated Hook Firing for that generation; a mismatch creates a diagnostic and no read. @@ -154,7 +154,7 @@ One immutable source record from one transcript generation. | `byte_length` | INTEGER | Raw byte count excluding newline delimiter | | `raw_sha256` | BLOB | Digest of exact `raw_json || record_delimiter` bytes | | `raw_json` | BLOB | Authoritative JSON/content bytes, including malformed/unknown complete records | -| `record_delimiter` | BLOB | Exact `LF`, `CRLF`, or empty framing bytes for a stable final value | +| `record_delimiter` | BLOB | Exact `LF` or `CRLF`; unterminated tails remain pending | | `parse_error` | TEXT NULL | Content-free error category | | `record_type` | TEXT NULL | Best-effort `type` projection | | `entry_uuid` | TEXT NULL | Best-effort `uuid` projection | diff --git a/specs/008-claude-session-storage/plan.md b/specs/008-claude-session-storage/plan.md index 19057b1..28f4a90 100644 --- a/specs/008-claude-session-storage/plan.md +++ b/specs/008-claude-session-storage/plan.md @@ -249,7 +249,10 @@ Implementation: - Prepare/move the root before current Settings/Focus path resolution. - Add database path, explicit transactional schema-v1 migration, per-connection foreign keys, permissions, Turso reopen, and clean-shutdown SQLite reopen/integrity/read tests. -- Update the plugin wrapper's default path in the same slice so hooks do not split across roots. +- Update the plugin wrapper's default path in the same slice. Detect an existing installation + targeting the legacy root as unhealthy without rewriting it at startup; explicit Install/Repair + replaces the complete managed wrapper with one targeting the new root. Prove both detection + before repair and successful delivery after repair using an existing-installation fixture. - Update README/current architecture guidance in this slice; leave historical records untouched. Proof: data-root state-matrix tests, database create/reopen/user-version tests, existing Focus and diff --git a/specs/008-claude-session-storage/quickstart.md b/specs/008-claude-session-storage/quickstart.md index aa97675..d2217b6 100644 --- a/specs/008-claude-session-storage/quickstart.md +++ b/specs/008-claude-session-storage/quickstart.md @@ -51,7 +51,9 @@ Expected state matrix: | explicit `ADHD_RANCH_HOME` | exact override used; no default migration | Also confirm the plugin contract test expects `.adhd/adhd-ranch-hook` and -`.adhd/agent-hooks.sock` while preserving the explicit override path. +`.adhd/agent-hooks.sock` while preserving the explicit override path. Start with a synthetic installed +legacy wrapper: startup reports it unhealthy without rewriting it; explicit Install/Repair replaces +the managed wrapper, and a test firing reaches only the new-root socket. ## 3. Validate raw Hook Receipt persistence @@ -72,6 +74,8 @@ Expected: incrementing the dropped-admission count; - disabling archiving at a controlled queue barrier rejects every later firing while all earlier accepted jobs finish exactly once with no partial transaction; +- graceful shutdown at a controlled queue barrier closes admission and persists every accepted + queued job exactly once before worker exit; reopen shows no partial transactions; - invalid JSON is retained with a parse error and no raw content is logged; - an unavailable database does not change the hook client's silent failure/timeout contract. @@ -89,13 +93,14 @@ cargo test -p adhd-ranch-storage transcript_generation -- --nocapture Expected: - every completed fixture line is byte-identical after concatenating `raw_json` and its preserved - `record_delimiter`, including LF, CRLF, and stable non-newline final values; + `record_delimiter`, including LF and CRLF; - main `transcript_path` and `SubagentStop.agent_transcript_path` fixtures both ingest, while the archive-only subagent verb leaves parent live Activity unchanged; - known envelope fields are indexed and unknown fields remain in the raw record; - the unknown `cost-state` fixture persists without a closed-enum failure; - a malformed complete line persists with `parse_error`; -- a partial trailing line waits for a later append; +- every unterminated tail waits, including a valid JSON value observed unchanged twice; a later + newline produces exactly one correctly framed row and no spurious empty row; - a row appended after the terminal hook is captured by bounded settle retries without another firing, and retry tests use an injected/paused clock; - three replays, including one database reopen, add no duplicate transcript records; @@ -160,21 +165,25 @@ WAL/SHM sidecars after create, write, close, and reopen. ## 8. Manual local smoke test -Use a temporary explicit data root so the smoke test cannot move or write real Ranch state: +Use separate temporary Ranch and Claude roots. Start Ranch from terminal A with both exported: ```sh -RANCH_SMOKE_ROOT="$(mktemp -d)" -ADHD_RANCH_HOME="$RANCH_SMOKE_ROOT" task dev +export ADHD_RANCH_HOME="$(mktemp -d)" +export CLAUDE_CONFIG_DIR="$(mktemp -d)" +printf 'Ranch root: %s\nClaude root: %s\n' "$ADHD_RANCH_HOME" "$CLAUDE_CONFIG_DIR" +task dev ``` In the app: 1. Confirm Claude archiving is off by default. 2. Read the plaintext-data disclosure and enable archiving explicitly. -3. Run a disposable Claude session that uses the installed Ranch hooks. -4. Confirm `$RANCH_SMOKE_ROOT/ranch.db` exists and the Agent appears only while the live hook state +3. Install/Repair the Ranch hooks only into this temporary `CLAUDE_CONFIG_DIR`. In terminal B, + export both variables to the exact paths printed by terminal A, then start `claude` there with + a synthetic prompt. Never copy personal settings, credentials, or transcripts into the fixture. +4. Confirm `$ADHD_RANCH_HOME/ranch.db` exists and the Agent appears only while the live hook state says it is present. -5. Quit and reopen Ranch using the same explicit root. Confirm archive rows remain but no historical +5. Quit and reopen Ranch with both variables unchanged. Confirm archive rows remain but no historical Agent appears until another live Hook Firing arrives. 6. Disable archiving and confirm a subsequent Hook Firing creates no new archive receipt. 7. Enable Developer Mode from the app menu, open Claude Archive Health, and confirm only aggregates @@ -182,5 +191,6 @@ In the app: 8. Restart and confirm Developer Mode and all `this run` counters are off/zero while database counts and last successful ingest remain. -Remove the temporary directory after the app and any database shell are closed. Do not point this -smoke test at personal Claude transcripts when capturing logs or test artifacts. +Remove both temporary directories after Ranch, the disposable Claude session, and any database +shell are closed. Do not point this smoke test at personal Claude transcripts when capturing logs +or test artifacts. diff --git a/specs/008-claude-session-storage/spec.md b/specs/008-claude-session-storage/spec.md index 8ba532a..bab69dd 100644 --- a/specs/008-claude-session-storage/spec.md +++ b/specs/008-claude-session-storage/spec.md @@ -192,6 +192,8 @@ identifiers or raw prompt, message, tool, or source-code content. present, agent id when present, working directory, `transcript_path`, `agent_transcript_path`, and receipt time. Admission MUST be bounded and non-blocking; rejected admissions MUST increment a content-free dropped-job counter and MUST NOT use a durable overflow inbox or delay Claude. + Graceful shutdown MUST close admission and drain all accepted jobs before stopping the worker; + forced termination cannot guarantee uncommitted receipts. - **FR-009**: Ranch MUST use hook-provided `transcript_path` and `agent_transcript_path` values as synchronization hints and MUST NOT discover sessions by crawling all of Claude's `projects/` directory in this feature. `SubagentStop` MUST use an archive-only transport action that never @@ -210,8 +212,8 @@ identifiers or raw prompt, message, tool, or source-code content. - **FR-012**: Unknown record types and unknown fields MUST be retained in full. Typed projections MUST never be the sole copy of a Claude record. - **FR-013**: A malformed but complete transcript record MUST be retained with its parse error; - an incomplete trailing record MUST remain pending until it becomes complete or a final stable - read determines that it is the last complete value. + every unterminated trailing record MUST remain pending until its newline delimiter arrives, + even if stable reads parse it as a complete JSON value. - **FR-014**: Transcript synchronization MUST be incremental and idempotent across duplicate Hook Firings and application restarts. Every valid path hint MUST schedule bounded delayed retries; terminal main/subagent events MUST settle on two unchanged observations so asynchronous final