From 7e6638fad74b828ff753ec8c2391bb22d9e06757 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Mon, 19 Oct 2026 23:04:29 -0500 Subject: [PATCH] chore(opencode): untrack runtime state and stale backups under .opencode/ (#367) Remove tracked per-machine runtime state (pilot/pilot.pid, artifact-index/context.db), stale *.bak configs whose live files moved to .jsonc, the themes.bak/ duplicate, and the whole backup/ duplicate tree (all 22 files verified byte-identical to their live copies, and themes.bak/vibrant-ink.json identical to themes/vibrant-ink.json, so nothing archival is lost). Add .opencode/.gitignore covering *.pid, /artifact-index/, *.bak, *.bak.*, /themes.bak/ and /backup/ so they do not return. No code in the repo references context.db or pilot.pid (git grep clean outside the removed backup tree); the root build-openchamber-fork.log half of #367 was already fixed by #377. --- .opencode/.gitignore | 10 + .opencode/artifact-index/context.db | Bin 98304 -> 0 bytes .opencode/backup/artifact-index/context.db | Bin 98304 -> 0 bytes .opencode/backup/command/devcontainer.md | 9 - .../backup/command/plannotator-annotate.md | 6 - .opencode/backup/command/plannotator-last.md | 3 - .../backup/command/plannotator-review.md | 6 - .opencode/backup/command/workspaces.md | 8 - .opencode/backup/command/worktree.md | 11 - .opencode/backup/commands/autoresearch.md | 76 -- .opencode/backup/commands/update.md | 76 -- .opencode/backup/dcp.jsonc | 7 - .opencode/backup/pilot/pilot.pid | 1 - .../plans/2026-03-20_cursor_enhancements.md | 855 ------------------ .../backup/plans/2026-03-21_peer-discovery.md | 441 --------- .../plans/2026-03-24-tags-v2-iroh-docs.md | 588 ------------ .../backup/plans/2026-03-24-tags-v2-polish.md | 314 ------- .../2026-03-25-tags-binary-search-autotag.md | 337 ------- .../plans/2026-03-25-testing-ci-overhaul.md | 236 ----- .../plans/htmx-to-datastar-migration.md | 600 ------------ .../backup/plans/prosemirror-content-modes.md | 545 ----------- .../backup/plugins/autoresearch-context.ts | 43 - .opencode/backup/scripts/backup-state.sh | 411 --------- .opencode/backup/skills/autoresearch/SKILL.md | 479 ---------- .opencode/opencode.json.bak | 43 - .opencode/pilot/pilot.pid | 1 - .opencode/settings.json.bak | 108 --- .opencode/themes.bak/vibrant-ink.json | 78 -- .opencode/tui.json.bak | 4 - 29 files changed, 10 insertions(+), 5286 deletions(-) create mode 100644 .opencode/.gitignore delete mode 100644 .opencode/artifact-index/context.db delete mode 100644 .opencode/backup/artifact-index/context.db delete mode 100644 .opencode/backup/command/devcontainer.md delete mode 100644 .opencode/backup/command/plannotator-annotate.md delete mode 100644 .opencode/backup/command/plannotator-last.md delete mode 100644 .opencode/backup/command/plannotator-review.md delete mode 100644 .opencode/backup/command/workspaces.md delete mode 100644 .opencode/backup/command/worktree.md delete mode 100644 .opencode/backup/commands/autoresearch.md delete mode 100644 .opencode/backup/commands/update.md delete mode 100644 .opencode/backup/dcp.jsonc delete mode 100644 .opencode/backup/pilot/pilot.pid delete mode 100644 .opencode/backup/plans/2026-03-20_cursor_enhancements.md delete mode 100644 .opencode/backup/plans/2026-03-21_peer-discovery.md delete mode 100644 .opencode/backup/plans/2026-03-24-tags-v2-iroh-docs.md delete mode 100644 .opencode/backup/plans/2026-03-24-tags-v2-polish.md delete mode 100644 .opencode/backup/plans/2026-03-25-tags-binary-search-autotag.md delete mode 100644 .opencode/backup/plans/2026-03-25-testing-ci-overhaul.md delete mode 100644 .opencode/backup/plans/htmx-to-datastar-migration.md delete mode 100644 .opencode/backup/plans/prosemirror-content-modes.md delete mode 100644 .opencode/backup/plugins/autoresearch-context.ts delete mode 100755 .opencode/backup/scripts/backup-state.sh delete mode 100644 .opencode/backup/skills/autoresearch/SKILL.md delete mode 100644 .opencode/opencode.json.bak delete mode 100644 .opencode/pilot/pilot.pid delete mode 100644 .opencode/settings.json.bak delete mode 100644 .opencode/themes.bak/vibrant-ink.json delete mode 100644 .opencode/tui.json.bak diff --git a/.opencode/.gitignore b/.opencode/.gitignore new file mode 100644 index 0000000000..be3f85d61d --- /dev/null +++ b/.opencode/.gitignore @@ -0,0 +1,10 @@ +# Runtime state and local backups under .opencode/ (#367) +# These are per-machine, regenerated by the tooling that uses them, +# and must never be committed: a tracked PID is stale on arrival and +# a tracked SQLite index churns on every run. +*.pid +/artifact-index/ +*.bak +*.bak.* +/themes.bak/ +/backup/ diff --git a/.opencode/artifact-index/context.db b/.opencode/artifact-index/context.db deleted file mode 100644 index 3fefa1930c8c9b92820edb11705a86d62dd63932..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 98304 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 SAOHd&00JP;CD8l(fBy%sR4+&X diff --git a/.opencode/backup/artifact-index/context.db b/.opencode/backup/artifact-index/context.db deleted file mode 100644 index 3fefa1930c8c9b92820edb11705a86d62dd63932..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 98304 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 SAOHd&00JP;CD8l(fBy%sR4+&X diff --git a/.opencode/backup/command/devcontainer.md b/.opencode/backup/command/devcontainer.md deleted file mode 100644 index 3156aa1897..0000000000 --- a/.opencode/backup/command/devcontainer.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -description: Target a devcontainer - /devcontainer , off. Or remove: /devcontainer rm , or rm all ---- - -Call the `devcontainer` tool with `target` set to: $ARGUMENTS - -If no arguments provided, call `devcontainer` with no target to show current status. - -If a `rm` command returns a message asking for confirmation, ask the user if they want to proceed. If they agree, call the tool again with the same arguments plus `confirmed: true`. diff --git a/.opencode/backup/command/plannotator-annotate.md b/.opencode/backup/command/plannotator-annotate.md deleted file mode 100644 index 88208532a3..0000000000 --- a/.opencode/backup/command/plannotator-annotate.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: Open interactive annotation UI for a markdown file ---- - -The Plannotator Annotate has been triggered. Opening the annotation UI... -Acknowledge "Opening annotation UI..." and wait for the user's feedback. diff --git a/.opencode/backup/command/plannotator-last.md b/.opencode/backup/command/plannotator-last.md deleted file mode 100644 index 8001428b78..0000000000 --- a/.opencode/backup/command/plannotator-last.md +++ /dev/null @@ -1,3 +0,0 @@ ---- -description: Annotate the last assistant message ---- diff --git a/.opencode/backup/command/plannotator-review.md b/.opencode/backup/command/plannotator-review.md deleted file mode 100644 index 4e040efd9d..0000000000 --- a/.opencode/backup/command/plannotator-review.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: Open interactive code review for current changes ---- - -The Plannotator Code Review has been triggered. Opening the review UI... -Acknowledge "Opening code review..." and wait for the user's feedback. diff --git a/.opencode/backup/command/workspaces.md b/.opencode/backup/command/workspaces.md deleted file mode 100644 index 2acae36335..0000000000 --- a/.opencode/backup/command/workspaces.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -description: Manage workspaces - /workspaces [cleanup] ---- - -Call the `workspaces` tool with action set to: $ARGUMENTS - -If no arguments provided, list all workspaces with status. -If 'cleanup' provided, identify stale workspaces for removal. diff --git a/.opencode/backup/command/worktree.md b/.opencode/backup/command/worktree.md deleted file mode 100644 index 371e509b1d..0000000000 --- a/.opencode/backup/command/worktree.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -description: Target a git worktree - /worktree or off ---- - -Call the `worktree` tool with: -- `target`: $ARGUMENTS -- `workdir`: the current working directory (use the directory you are working in) - -If no arguments provided, call `worktree` with no target to show current status. - -Example: `worktree(target: "feature-branch", workdir: "/path/to/repo")` diff --git a/.opencode/backup/commands/autoresearch.md b/.opencode/backup/commands/autoresearch.md deleted file mode 100644 index 0f878535f1..0000000000 --- a/.opencode/backup/commands/autoresearch.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -description: Start or resume autoresearch experiment loop (optional args: off|dashboard) ---- - -# Autoresearch Command - -You are starting or resuming an autonomous experiment loop. - -## Handle arguments - -Arguments: $ARGUMENTS - -### If arguments = "off" - -Create a `.autoresearch-off` sentinel file in the current directory: -```bash -touch .autoresearch-off -``` -Then tell the user autoresearch mode is paused. It can be resumed by running `/autoresearch` again (which will delete the sentinel). - -### If arguments = "dashboard" - -Regenerate `autoresearch-dashboard.md` based on the current state: - -1. Read `autoresearch.jsonl` to get all experiment results -2. Count total runs, kept, discarded, crashed -3. Find baseline metric (first result after config header) -4. Find best metric and which run achieved it -5. Calculate delta percentages vs baseline -6. Generate dashboard markdown with: - - Title: `# Autoresearch Dashboard: ` - - Summary line with counts - - Baseline and best values - - Table of ALL runs in current segment with commit, metric, status, description -7. Write the dashboard to `autoresearch-dashboard.md` in the current directory using the Write tool -8. Confirm to the user that the dashboard has been saved to disk - -Include dashboard generation instructions from the SKILL.md (lines 198-217): - -```markdown -# Autoresearch Dashboard: - -**Runs:** 12 | **Kept:** 8 | **Discarded:** 3 | **Crashed:** 1 -**Baseline:** : (#1) -**Best:** : (#8, -26.2%) - -| # | commit | | status | description | -|---|--------|---------------|--------|-------------| -| 1 | abc1234 | 42.3s | keep | baseline | -| 2 | def5678 | 40.1s (-5.2%) | keep | optimize hot loop | -| 3 | abc1234 | 43.0s (+1.7%) | discard | try vectorization | -... -``` - -Include delta percentages vs baseline for each metric value. Show ALL runs in the current segment (not just recent ones). - -### If `autoresearch.md` exists in the current directory (resume) - -This is a resume. Do the following: - -1. Delete `.autoresearch-off` if it exists -2. Read `autoresearch.md` to understand the objective, constraints, and what's been tried -3. Read `autoresearch.jsonl` to reconstruct state: - - Count total runs, kept, discarded, crashed - - Find baseline metric (first result in current segment) - - Find best metric and which run achieved it - - Identify which secondary metrics are being tracked -4. Read recent git log: `git log --oneline -20` -5. If `autoresearch.ideas.md` exists, read it for experiment inspiration -6. Continue the loop from where it left off — pick up the next experiment - -### If `autoresearch.md` does NOT exist (fresh start) - -1. Delete `.autoresearch-off` if it exists -2. Invoke the `autoresearch` skill to set up the experiment from scratch -3. If arguments were provided (other than "off"), use them as the goal description to skip/answer the setup questions diff --git a/.opencode/backup/commands/update.md b/.opencode/backup/commands/update.md deleted file mode 100644 index 24a6e2e021..0000000000 --- a/.opencode/backup/commands/update.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -description: Update AGENTS.md - review and refresh project instructions -agent: build ---- - -# Update AGENTS.md - -Review and update the project's AGENTS.md file to ensure it remains accurate and context-efficient. - -## Instructions - -$ARGUMENTS - -## Locate AGENTS.md - -Search from pwd upward to filesystem root, then check `~/.config/opencode/AGENTS.md`. Use first found. - -If found outside the repo and not in `~/.config/opencode/` or `~/`, **ask the user to confirm** before proceeding. - -## If no specific instructions provided - -Review the current AGENTS.md and verify it's up-to-date by checking: - -### Core Details (always include in AGENTS.md) -- **Primary language/framework** - is this still accurate? -- **Core purpose** - one-line description still correct? -- **Essential commands** - is the primary quality check command listed (e.g., `just check`)? -- **Critical warnings** - any "never do X" rules still valid? -- **File structure** - does the tree reflect current layout? - -### Context Efficiency Review -- **Inline vs reference**: Can any code examples be replaced with file links? -- **Command lists**: Is only the essential command shown, with a link to justfile/makefile for others? -- **Dependencies**: Are only core libraries listed, not exhaustive lists? -- **Redundant prose**: Can any explanations be tightened? - -### Propose Changes as Questions - -Do NOT make changes autonomously. Present findings using the question tool with Y/n options (custom input is always available for nuanced responses): - -``` -Proposed AGENTS.md updates: - -1. [Structure] src/commands/ now has 3 new files - add to tree? (Y/n) -2. [Commands] `just check` renamed to `just verify` - update? (Y/n) -3. [Tighten] Error handling section is 15 lines, could be 3 - condense? (Y/n) -4. [Remove] "Store Access" code example duplicates pattern in store.rs:45 - remove? (Y/n) -5. [Add] New critical rule needed: never delete .env.example? (y/N) -``` - -Use `(Y/n)` for recommended changes, `(y/N)` for optional/uncertain ones. - -After user responds, apply only the approved changes. - -## If specific instructions provided - -If the instructions modify or focus one of the review steps above (e.g., "pay extra attention to file structure" or "skip command review"), run the full review process with that adjustment applied. - -Otherwise, implement the requested changes directly. **However, ask questions first if:** -- The change is major (removing sections, restructuring, changing critical rules) -- The request is ambiguous or could be interpreted multiple ways -- You need clarification on scope, intent, or priorities -- Any detail—major or minor—is unclear - -After implementation: -- Verify the file remains context-efficient -- Ensure no critical rules were accidentally removed -- Confirm essential details (language, purpose, key commands) are still present - -## Guiding Principles - -- **Minimize tokens**: Every line should earn its place in context -- **Link over inline**: Reference files instead of duplicating content -- **One essential command**: Show the primary command, link to the rest -- **Preserve critical rules**: Never remove warnings/constraints without explicit approval -- **Historical accuracy**: If documenting architecture decisions, follow the datetime folder protocol in the existing AGENTS.md diff --git a/.opencode/backup/dcp.jsonc b/.opencode/backup/dcp.jsonc deleted file mode 100644 index 773640b848..0000000000 --- a/.opencode/backup/dcp.jsonc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/Opencode-DCP/opencode-dynamic-context-pruning/master/dcp.schema.json", - "compress": { - "maxContextLimit": "80%", - "minContextLimit": "40%" - } -} diff --git a/.opencode/backup/pilot/pilot.pid b/.opencode/backup/pilot/pilot.pid deleted file mode 100644 index ade1ba6909..0000000000 --- a/.opencode/backup/pilot/pilot.pid +++ /dev/null @@ -1 +0,0 @@ -1748136 \ No newline at end of file diff --git a/.opencode/backup/plans/2026-03-20_cursor_enhancements.md b/.opencode/backup/plans/2026-03-20_cursor_enhancements.md deleted file mode 100644 index 4bf3ccc70f..0000000000 --- a/.opencode/backup/plans/2026-03-20_cursor_enhancements.md +++ /dev/null @@ -1,855 +0,0 @@ -# Collaborative Cursor Enhancements - -**Created**: 2026-03-20T05:04:09Z -**Status**: Planning -**Package**: `pkgs/id` - -## Overview - -This document describes enhancements to the collaborative editing cursor system in the `id` web interface. The changes improve cursor visibility feedback, hover interactions, tooltip organization, and debug logging capabilities. - -## Feature Matrix - -| # | Feature | Files | Priority | -|---|---------|-------|----------| -| 1 | Debug logging (flags + env vars + default) | `main.rs`, `cli.rs` | High | -| 2 | Strobing slows as cursors fade (1s→3s), stops at min | `cursors.ts`, `editor.css` | High | -| 3 | Strobing stops on WebSocket disconnect | `cursors.ts` | Medium | -| 4 | Hover → 100% opacity, no strobing, cursor bolder | `cursors.ts`, `editor.css` | High | -| 5 | Hover → top z-index | `cursors.ts`, `editor.css` | Medium | -| 6 | 1s delay before restoring state after hover | `cursors.ts` | Medium | -| 7 | Horizontal tooltip stacking with merged bars | `cursors.ts`, `editor.css` | High | -| 8 | Local cursor → same-line cursors fully visible | `cursors.ts` | Medium | -| 9 | Reconnect cleanup (1s timer) | `cursors.ts`, `collab.ts` | Medium | - -## Key Design Decisions - -| Decision | Choice | Rationale | -|----------|--------|-----------| -| Line detection | DOM rendered y-position | Most accurate for actual visual overlap | -| Merged bar hover | Hovered user's cursor + tooltip → 100% + bolder | Highlights specific user, cursor line thickens | -| Strobe engine | CSS hybrid (JS sets `--strobe-duration`, `--strobe-state`) | Browser handles animation, more efficient than RAF loop | -| Strobe transition | Smooth duration interpolation | Duration smoothly changes from 1s→3s as opacity fades | -| Log priority | flags > env vars > default | CLI flags override environment | -| Same-position cursors | Stack NO divider, cursor color = most recent | Visual clarity, recent activity emphasized | -| Overlapping different-position tooltips | Stack WITH divider between position groups | Divider distinguishes separate cursor positions | -| Within position group order | Most recent activity = leftmost | Active users more prominent | -| Between position group order | Cursor position ascending | Predictable, matches document flow | - -## Implementation Order - -Dependencies require this sequence: - -0. **Documentation** (create comprehensive docs file per guidelines) -1. **Debug logging** (Rust, independent) -2. **Reconnect cleanup** (foundation for connection state) -3. **Strobing stops on disconnect** (uses connection state) -4. **CSS hybrid strobe setup** (JS controls CSS custom properties) -5. **Hover behavior** (opacity + no strobe + z-index + 1s delay) -6. **Local cursor same-line detection** (uses DOM line detection) -7. **Horizontal tooltip stacking** (most complex, do last) - ---- - -## Detailed Specifications - -### 1. Debug Logging - -**Goal**: Enable debug-level logging by default, with multiple override mechanisms. - -**Priority Order** (first match wins): -1. `--debug` flag → `debug` -2. `--log-level ` flag → specified level -3. `RUST_LOG` env var → value (existing behavior) -4. `LOG_LEVEL` env var → value -5. `DEBUG` env var (if truthy) → `debug` -6. Default → `debug` (changed from `info`) - -**CLI Changes** (`src/cli.rs`): - -Add global flags to `Cli` struct: -```rust -#[derive(Parser, Debug)] -pub struct Cli { - /// Enable debug logging (equivalent to --log-level debug) - #[arg(long, global = true)] - pub debug: bool, - - /// Set log level (trace, debug, info, warn, error) - #[arg(long, global = true, value_name = "LEVEL")] - pub log_level: Option, - - #[command(subcommand)] - pub command: Option, -} -``` - -**Logging Initialization** (`src/main.rs`): - -```rust -fn get_log_level(cli: &Cli) -> String { - // 1. --debug flag - if cli.debug { - return "debug".to_string(); - } - // 2. --log-level flag - if let Some(ref level) = cli.log_level { - return level.clone(); - } - // 3. RUST_LOG env (signal to use EnvFilter default) - if std::env::var("RUST_LOG").is_ok() { - return String::new(); - } - // 4. LOG_LEVEL env - if let Ok(level) = std::env::var("LOG_LEVEL") { - return level; - } - // 5. DEBUG env (truthy check) - if let Ok(debug) = std::env::var("DEBUG") { - if !debug.is_empty() && debug != "0" && debug.to_lowercase() != "false" { - return "debug".to_string(); - } - } - // 6. Default - "debug".to_string() -} -``` - ---- - -### 2. Strobing Slows as Cursors Fade - -**Goal**: Cursor strobe cycle slows from 1s to 3s as opacity decreases, stops entirely at minimum opacity (≤0.3). - -**Current State**: -- CSS animation: `cursor-blink 1s ease-in-out infinite` -- Animation oscillates opacity 1.0 → 0.7 → 1.0 - -**New Behavior (CSS Hybrid Approach)**: -- JS sets CSS custom properties on each cursor element -- Browser handles animation via CSS `animation-duration: var(--strobe-duration)` -- Strobe cycle duration varies smoothly with opacity: - - Opacity 1.0 → 1000ms cycle - - Opacity 0.3 → 3000ms cycle - - Opacity ≤0.3 → No strobing (`--strobe-state: paused`) -- Formula: `duration_ms = 1000 + ((1.0 - opacity) / 0.7) * 2000` -- Duration transitions smoothly as opacity fades - -**Implementation** (`web/src/cursors.ts`): - -```typescript -// Strobe state tracking (for hover pause/resume) -interface StrobeInfo { - element: HTMLElement; - baseOpacity: number; - paused: boolean; -} - -const strobeInfos = new Map(); -let connectionState: 'connected' | 'disconnected' = 'connected'; - -function getStrobeDurationMs(opacity: number): number { - if (opacity <= 0.3) return 0; // No strobing - return 1000 + ((1.0 - opacity) / 0.7) * 2000; -} - -function updateCursorStrobe(clientID: string | number, element: HTMLElement, opacity: number): void { - const durationMs = getStrobeDurationMs(opacity); - const shouldStrobe = durationMs > 0 && connectionState === 'connected'; - - // Set CSS custom properties - element.style.setProperty('--strobe-duration', `${durationMs}ms`); - element.style.setProperty('--strobe-state', shouldStrobe ? 'running' : 'paused'); - element.style.setProperty('--base-opacity', String(opacity)); - - strobeInfos.set(clientID, { element, baseOpacity: opacity, paused: false }); -} - -function pauseCursorStrobe(clientID: string | number): void { - const info = strobeInfos.get(clientID); - if (info) { - info.paused = true; - info.element.style.setProperty('--strobe-state', 'paused'); - info.element.style.opacity = '1'; // Full opacity on hover - } -} - -function resumeCursorStrobe(clientID: string | number): void { - const info = strobeInfos.get(clientID); - if (info && connectionState === 'connected') { - info.paused = false; - const durationMs = getStrobeDurationMs(info.baseOpacity); - info.element.style.setProperty('--strobe-state', durationMs > 0 ? 'running' : 'paused'); - info.element.style.opacity = String(info.baseOpacity); - } -} - -function unregisterCursorStrobe(clientID: string | number): void { - strobeInfos.delete(clientID); -} -``` - -**CSS Changes** (`web/styles/editor.css`): - -```css -.collab-cursor { - position: relative; - border-left: 2px solid; - margin-left: -1px; - margin-right: -1px; - pointer-events: auto; /* Changed from none for hover */ - - /* CSS custom properties for JS control */ - --strobe-duration: 1000ms; - --strobe-state: running; - --base-opacity: 1; - - /* Strobe animation controlled by custom properties */ - animation: cursor-strobe var(--strobe-duration) ease-in-out infinite; - animation-play-state: var(--strobe-state); - - /* Smooth transition when duration changes */ - transition: --strobe-duration 0.5s ease; -} - -@keyframes cursor-strobe { - 0%, 100% { opacity: var(--base-opacity); } - 50% { opacity: calc(var(--base-opacity) * 0.7); } -} - -/* When strobing is paused, ensure stable opacity */ -.collab-cursor[style*="--strobe-state: paused"] { - opacity: var(--base-opacity); -} -``` - -**Note**: The `transition` on `--strobe-duration` enables smooth interpolation of strobe speed as the cursor ages. If browser support is inconsistent, we can fall back to discrete duration steps. - ---- - -### 3. Strobing Stops on WebSocket Disconnect - -**Goal**: When WebSocket disconnects, all cursor strobing stops immediately. - -**Implementation** (`web/src/cursors.ts`): - -```typescript -export function setConnectionState(state: 'connected' | 'disconnected'): void { - connectionState = state; - - // Update all cursor strobe states - strobeInfos.forEach((info) => { - if (state === 'disconnected') { - // Pause strobing, set to base opacity - info.element.style.setProperty('--strobe-state', 'paused'); - info.element.style.opacity = String(info.baseOpacity); - } else if (!info.paused) { - // Resume strobing (unless hover-paused) - const durationMs = getStrobeDurationMs(info.baseOpacity); - info.element.style.setProperty('--strobe-state', durationMs > 0 ? 'running' : 'paused'); - } - }); -} -``` - ---- - -### 4-6. Hover Behavior - -**Goals**: -- Hover on cursor line OR label → 100% opacity, no strobing -- Hover on merged bar segment → highlights ONLY that user's cursor and tooltip segment -- Hovered cursor line becomes bolder (thicker border) -- Hover brings cursor group to top z-index -- 1s delay before returning to previous state after hover - -**Key Behavior for Merged Bars**: -When hovering a segment in a merged bar, only that specific user's elements are highlighted: -- That segment in the bar → 100% opacity -- That user's cursor line → 100% opacity + bolder (3px instead of 2px) -- Other segments in the bar remain at their current opacity -- The bar itself elevates z-index - -**Implementation** (`web/src/cursors.ts`): - -```typescript -// Hover state -let hoveredCursorID: string | number | null = null; -let hoverRestoreTimer: ReturnType | null = null; - -function setupHoverHandlers(container: HTMLElement, editorView: EditorView): void { - // Use event delegation for cursor hover - container.addEventListener('mouseenter', (event: MouseEvent) => { - const target = event.target as HTMLElement; - - // Check if hovering a segment within a merged bar - const segment = target.closest('.collab-cursor-bar-segment'); - const cursorEl = target.closest('.collab-cursor'); - const barEl = target.closest('.collab-cursor-bar'); - - if (!segment && !cursorEl && !barEl) return; - - // Cancel pending restore - if (hoverRestoreTimer) { - clearTimeout(hoverRestoreTimer); - hoverRestoreTimer = null; - } - - // Determine which client ID is being hovered - let clientID: string | number | null = null; - - if (segment) { - // Hovering a specific segment in merged bar - clientID = segment.getAttribute('data-client-id'); - } else if (cursorEl) { - // Hovering a standalone cursor - clientID = cursorEl.getAttribute('data-client-id'); - } - - if (!clientID) return; - - hoveredCursorID = clientID; - - // Highlight ONLY this user's cursor and tooltip - const state = strobeStates.get(clientID); - if (state) { - state.paused = true; - state.element.style.opacity = '1'; - state.element.classList.add('collab-cursor-hovered'); // Makes cursor bolder - } - - // If in a merged bar, highlight only this segment - if (segment) { - segment.classList.add('collab-cursor-segment-hovered'); - // Elevate the entire bar's z-index - barEl?.classList.add('collab-cursor-bar-elevated'); - } - - // For standalone cursor, elevate it - if (cursorEl) { - cursorEl.classList.add('collab-cursor-hovered'); - } - }, true); - - container.addEventListener('mouseleave', (event: MouseEvent) => { - const target = event.target as HTMLElement; - const segment = target.closest('.collab-cursor-bar-segment'); - const cursorEl = target.closest('.collab-cursor'); - const barEl = target.closest('.collab-cursor-bar'); - - if (!segment && !cursorEl && !barEl) return; - - const clientID = hoveredCursorID; - if (!clientID) return; - - // 1s delay before restoring - hoverRestoreTimer = setTimeout(() => { - hoveredCursorID = null; - - // Restore this user's cursor - const state = strobeStates.get(clientID); - if (state) { - state.paused = false; - state.element.style.opacity = String(state.baseOpacity); - state.element.classList.remove('collab-cursor-hovered'); - } - - // Remove segment highlight - if (segment) { - segment.classList.remove('collab-cursor-segment-hovered'); - barEl?.classList.remove('collab-cursor-bar-elevated'); - } - - // Remove standalone cursor highlight - if (cursorEl) { - cursorEl.classList.remove('collab-cursor-hovered'); - } - - // Refresh decorations - editorView.dispatch(editorView.state.tr); - }, 1000); - }, true); -} -``` - -**CSS**: - -```css -/* Standalone cursor hover - bolder line */ -.collab-cursor-hovered { - z-index: 1000 !important; - border-left-width: 3px !important; /* Bolder cursor line */ -} - -.collab-cursor-hovered .collab-cursor-label { - opacity: 1 !important; -} - -/* Merged bar elevation */ -.collab-cursor-bar-elevated { - z-index: 1000 !important; -} - -/* Individual segment hover within merged bar */ -.collab-cursor-segment-hovered { - opacity: 1 !important; - /* Subtle highlight to show which segment is active */ - box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.3); -} -``` - ---- - -### 7. Horizontal Tooltip Stacking with Merged Bars - -**Goal**: -- Tooltips stack horizontally in whitespace between lines -- Handle cursor position grouping and overlap intelligently -- Each segment matches user's cursor color - -**Three Scenarios**: - -**Scenario 1: Cursors don't touch → No merging, no dividers** -Each tooltip stands alone with its own color. -``` -┌─────────┐ ┌─────────┐ ┌─────────┐ -│ Alice │ │ Bob │ │ Carol │ -└─────────┘ └─────────┘ └─────────┘ - pink blue green - ↑ ↑ ↑ - pos 10 pos 50 pos 100 -``` - -**Scenario 2: Same cursor position → Stack with NO divider** -Multiple users at exact same position stack together. The cursor line uses the most recently active user's color. -``` -┌─────────────────────────────┐ -│ Carol │ Alice │ Bob │ ← no dividers between segments -└─────────────────────────────┘ - green pink blue - ↑ - all at pos 50 - cursor line color = Carol's green (most recent) - - Sort within group: most recent activity = leftmost -``` - -**Scenario 3: Different positions but tooltips overlap → Stack WITH divider between position groups** -Groups ordered by cursor position ascending. Within each group, most recent = leftmost. -``` -┌───────────────────────┬─────────┐ -│ Alice │ Bob │ Carol │ -└───────────────────────┴─────────┘ - pos 10 │ pos 12 - ↑ - divider here (different positions) - - - Left group (pos 10): Alice & Bob at same pos, Alice more recent - - Right group (pos 12): Carol alone - - Groups ordered by position ascending (10, then 12) -``` - -**Key Rules**: -| Condition | Behavior | -|-----------|----------| -| Same position | Stack, NO divider, cursor color = most recent user | -| Different position, tooltips overlap | Stack WITH divider between groups | -| Within a position group | Sort by activity (most recent = leftmost) | -| Between groups | Sort by cursor position ascending | - -**Line Detection** (DOM-based): - -```typescript -function getCursorLineY(element: HTMLElement): number { - const rect = element.getBoundingClientRect(); - return rect.top; -} - -function groupCursorsByRenderedLine( - cursorElements: Map -): Map { - const LINE_THRESHOLD = 5; // pixels - cursors within this are "same line" - const groups = new Map(); - - cursorElements.forEach((el, clientID) => { - const y = getCursorLineY(el); - - // Find existing group within threshold - let foundGroup = false; - for (const [groupY, ids] of groups) { - if (Math.abs(y - groupY) < LINE_THRESHOLD) { - ids.push(clientID); - foundGroup = true; - break; - } - } - - if (!foundGroup) { - groups.set(y, [clientID]); - } - }); - - return groups; -} -``` - -**Cursor Data Structure**: - -```typescript -interface CursorForMerge { - clientID: string | number; - head: number; // Document position - name: string; - color: string; - lastUpdate: number; // Timestamp for activity ordering - opacity: number; -} - -// Group cursors by exact document position -interface PositionGroup { - position: number; - cursors: CursorForMerge[]; // Sorted by lastUpdate desc (most recent first) - mostRecentColor: string; // Cursor line color for this position -} -``` - -**Grouping and Overlap Detection**: - -```typescript -function groupCursorsByPosition(cursors: CursorForMerge[]): PositionGroup[] { - const positionMap = new Map(); - - // Group by exact position - cursors.forEach(cursor => { - const existing = positionMap.get(cursor.head) || []; - existing.push(cursor); - positionMap.set(cursor.head, existing); - }); - - // Convert to PositionGroup[], sort each group by activity - const groups: PositionGroup[] = []; - positionMap.forEach((groupCursors, position) => { - // Sort by lastUpdate descending (most recent = first/leftmost) - groupCursors.sort((a, b) => b.lastUpdate - a.lastUpdate); - groups.push({ - position, - cursors: groupCursors, - mostRecentColor: groupCursors[0].color, - }); - }); - - // Sort groups by position ascending - groups.sort((a, b) => a.position - b.position); - - return groups; -} - -function doTooltipsOverlap(groups: PositionGroup[], charWidthPx: number): boolean { - if (groups.length <= 1) return false; - - const LABEL_PADDING = 12; - const MIN_GAP = 4; - - for (let i = 0; i < groups.length - 1; i++) { - const curr = groups[i]; - const next = groups[i + 1]; - - // Calculate total width of current group's tooltips - const currWidth = curr.cursors.reduce((sum, c) => - sum + (c.name.length * charWidthPx) + LABEL_PADDING, 0); - - // Distance between positions in pixels - const posDiff = (next.position - curr.position) * charWidthPx; - - if (posDiff < currWidth + MIN_GAP) { - return true; - } - } - return false; -} -``` - -**Merged Bar DOM Creation**: - -```typescript -function createMergedBar(groups: PositionGroup[]): HTMLElement { - // Groups already sorted by position ascending - // Within each group, cursors sorted by activity (most recent first) - - const bar = document.createElement('span'); - bar.className = 'collab-cursor-bar'; - - groups.forEach((group, groupIndex) => { - // Add divider BETWEEN position groups (not within) - if (groupIndex > 0) { - const divider = document.createElement('span'); - divider.className = 'collab-cursor-bar-divider'; - bar.appendChild(divider); - } - - // Add all cursors in this position group (no dividers between them) - group.cursors.forEach((cursor) => { - const segment = document.createElement('span'); - segment.className = 'collab-cursor-bar-segment'; - segment.style.backgroundColor = cursor.color; - segment.style.color = isLightColor(cursor.color) ? '#000' : '#fff'; - segment.style.opacity = String(cursor.opacity); - segment.textContent = cursor.name; - segment.setAttribute('data-client-id', String(cursor.clientID)); - segment.setAttribute('data-position', String(cursor.head)); - bar.appendChild(segment); - }); - }); - - return bar; -} - -// Get cursor line color for a position (most recent user's color) -function getCursorLineColor(group: PositionGroup): string { - return group.mostRecentColor; -} -``` - -**CSS for Merged Bar**: - -```css -.collab-cursor-bar { - position: absolute; - top: -1.4em; - left: 0; - display: flex; - flex-direction: row; - align-items: stretch; - font-size: 10px; - font-family: var(--font-mono); - border-radius: 3px; - overflow: hidden; - white-space: nowrap; - user-select: none; - z-index: 10; - backdrop-filter: blur(2px); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); - pointer-events: auto; -} - -.collab-cursor-bar-segment { - padding: 2px 6px; - transition: opacity 0.3s ease; -} - -.collab-cursor-bar-divider { - width: 2px; - background: rgba(255, 255, 255, 0.6); - flex-shrink: 0; -} -``` - ---- - -### 8. Local Cursor Triggers Same-Line Visibility - -**Goal**: Remote cursors on the same rendered line as local cursor get full opacity and resume strobing. - -**Implementation**: - -```typescript -function isOnSameLineAsLocal( - remoteCursorEl: HTMLElement, - localSelection: Selection, - editorView: EditorView -): boolean { - const LINE_THRESHOLD = 5; - - // Get local cursor's rendered position - const localCoords = editorView.coordsAtPos(localSelection.head); - const localY = localCoords.top; - - // Get remote cursor's rendered position - const remoteY = getCursorLineY(remoteCursorEl); - - return Math.abs(localY - remoteY) < LINE_THRESHOLD; -} -``` - -In decoration creation: -```typescript -// Check if on same line as local cursor -const isOnLocalLine = localSelection && isOnSameLineAsLocal(cursorWidget, localSelection, view); -const displayOpacity = isOnLocalLine || isHovered ? 1.0 : opacity; -``` - ---- - -### 9. Reconnect Cleanup - -**Goal**: After Init message, wait 1s then remove cursors not refreshed by server. - -**Implementation** (`web/src/cursors.ts`): - -```typescript -let reconnectCleanupTimer: ReturnType | null = null; -let freshCursorIDs: Set = new Set(); -let cleanupEditorView: EditorView | null = null; - -export function setCleanupEditorView(view: EditorView): void { - cleanupEditorView = view; -} - -export function onInitReceived(): void { - if (reconnectCleanupTimer) { - clearTimeout(reconnectCleanupTimer); - } - - freshCursorIDs = new Set(); - - reconnectCleanupTimer = setTimeout(() => { - if (cleanupEditorView && connectionState === 'connected') { - performReconnectCleanup(); - } - reconnectCleanupTimer = null; - }, 1000); -} - -export function markCursorFresh(clientID: string | number): void { - freshCursorIDs.add(clientID); -} - -function performReconnectCleanup(): void { - if (!cleanupEditorView) return; - - const pluginState = cursorPluginKey.getState(cleanupEditorView.state); - if (!pluginState) return; - - const staleCursors: (string | number)[] = []; - pluginState.cursors.forEach((_, clientID) => { - if (!freshCursorIDs.has(clientID)) { - staleCursors.push(clientID); - } - }); - - staleCursors.forEach(clientID => { - removeCursor(cleanupEditorView!, clientID); - unregisterCursorStrobe(clientID); - }); - - freshCursorIDs.clear(); -} - -// Update setConnectionState to cancel timer on disconnect -// (Note: setConnectionState also handles strobe pause/resume - see Section 3) -export function setConnectionState(state: 'connected' | 'disconnected'): void { - connectionState = state; - - // Pause/resume strobing for all cursors - strobeInfos.forEach((info) => { - if (state === 'disconnected') { - info.element.style.setProperty('--strobe-state', 'paused'); - info.element.style.opacity = String(info.baseOpacity); - } else if (!info.paused) { - const durationMs = getStrobeDurationMs(info.baseOpacity); - info.element.style.setProperty('--strobe-state', durationMs > 0 ? 'running' : 'paused'); - } - }); - - // Cancel reconnect cleanup timer on disconnect - if (state === 'disconnected' && reconnectCleanupTimer) { - clearTimeout(reconnectCleanupTimer); - reconnectCleanupTimer = null; - } -} -``` - -**Update** (`web/src/collab.ts`): - -```typescript -// In MSG.CURSOR handler: -markCursorFresh(clientID); -updateCursor(...); - -// After editor init: -setCleanupEditorView(editorInstance.view); -``` - ---- - -## Files Modified Summary - -| File | Changes | -|------|---------| -| `pkgs/id/src/cli.rs` | Add `debug: bool`, `log_level: Option` to `Cli` | -| `pkgs/id/src/main.rs` | Add `get_log_level()`, update tracing init, parse CLI before init | -| `pkgs/id/web/src/cursors.ts` | CSS hybrid strobe control, hover system, DOM line detection, merged bars with activity reordering, reconnect cleanup | -| `pkgs/id/web/src/collab.ts` | Call `markCursorFresh()`, `setCleanupEditorView()`, `setConnectionState()` | -| `pkgs/id/web/styles/editor.css` | CSS custom properties for strobe (`--strobe-duration`, `--strobe-state`), merged bar styles with dividers, hover states | - ---- - -## Testing Plan - -### Manual Testing - -1. **Debug logging**: - - `id serve` → debug output appears - - `RUST_LOG=warn id serve` → warn level only - - `id serve --debug` → debug level - - `id serve --log-level trace` → trace level - - `LOG_LEVEL=error id serve` → error level - - `DEBUG=1 id serve` → debug level - -2. **Strobing**: - - Two browsers, move cursor → strobe at ~1s - - Wait 30s → strobe slows - - Wait 60s → strobe stops (static at 0.3) - - Disconnect WebSocket → all strobing stops - - Reconnect → strobing resumes - -3. **Hover**: - - Hover cursor line → 100% opacity, no strobe - - Hover label → same behavior - - Mouse away → 1s delay before restore - - Re-hover within 1s → stays at 100% - -4. **Z-index**: - - Create overlapping cursors - - Hover one → appears on top - -5. **Tooltip stacking**: - - Two cursors same position → stacked labels, NO divider, cursor color = most recent - - Two cursors different positions but tooltips overlap → merged bar WITH divider between groups - - Within same position group: most recent = leftmost - - Between groups: ordered by position ascending - - Each segment matches user color - -6. **Local cursor visibility**: - - Remote cursor idles on line - - Move local cursor to same line → remote becomes fully visible - - Move away → remote fades normally - -7. **Reconnect cleanup**: - - Two clients connected - - Disconnect one, wait, reconnect - - Stale cursor removed after 1s - ---- - -## Risks and Mitigations - -| Risk | Mitigation | -|------|------------| -| CSS custom property transitions not supported | Fall back to discrete duration steps (1s, 2s, 3s) | -| Animation duration change causes reset | Use `animation-delay` manipulation or accept brief glitch | -| DOM line detection during scroll | Use `getBoundingClientRect()` which accounts for scroll | -| Hover events lost on decoration rebuild | Track hover state separately, re-apply after refresh | -| Race between reconnect cleanup and new cursors | `markCursorFresh()` called before cleanup runs | -| Label width estimation inaccurate | Use `getBoundingClientRect()` for actual measurement | -| Merged bar reordering causes visual jump | Add CSS transition for segment position changes | - ---- - -## Future Enhancements - -- Animated transition when bars merge/split -- Touch support (long-press for hover behavior) -- Configurable timing constants via settings -- Cursor movement trails -- Keyboard navigation to jump between cursors diff --git a/.opencode/backup/plans/2026-03-21_peer-discovery.md b/.opencode/backup/plans/2026-03-21_peer-discovery.md deleted file mode 100644 index 0b15fc3d32..0000000000 --- a/.opencode/backup/plans/2026-03-21_peer-discovery.md +++ /dev/null @@ -1,441 +0,0 @@ -# Peer Discovery via iroh-gossip + distributed-topic-tracker - -**Status:** Complete (Phases 0-6, 8 done; Phase 7 is future work) -**Created:** 2026-03-21 -**Updated:** 2026-03-22 -**Goal:** Enable all online `id` servers to discover and list each other using iroh-gossip with automatic DHT-based bootstrapping via `distributed-topic-tracker`, without interfering with the existing `META_ALPN` protocol used for blob operations. - ---- - -## Context - -Currently, `id` servers have no mechanism to discover each other. Clients must already know a server's node ID to connect. This plan adds gossip-based peer discovery where servers advertise their presence (node ID, name, blob count) on a shared gossip topic, plus an RPC mechanism for querying known peers and a depth-based crawler for recursive peer discovery. - -### Key Dependencies (already in Cargo.toml, unused in source) - -- `iroh-gossip = { version = "0.96", features = ["net"] }` -- gossip pub/sub transport -- `distributed-topic-tracker` (git dep) -- automatic peer bootstrapping via BitTorrent mainline DHT, wraps iroh-gossip with zero-config discovery, encrypted/signed DHT records, and partition healing - -### Design Decisions - -1. **`distributed-topic-tracker` for bootstrapping** -- provides automatic peer discovery via BitTorrent DHT. Handles the hard problem of finding initial peers without any manual configuration. Wraps iroh-gossip with additional features: encrypted DHT records, Ed25519-signed announcements, bubble merge (partition healing), and split-brain detection. -2. **Gossip uses its own built-in ALPN** -- no new custom ALPN needed. Registered with the Router alongside meta and blobs. -3. **`ListPeers` added to `MetaRequest`/`MetaResponse`** -- pragmatic extension to the meta protocol for querying known peers via RPC. **Must be appended as the last variant** in both enums to preserve postcard wire compatibility (postcard uses positional enum discriminants). -4. **Depth-based crawling** -- the `peers` command supports `--depth N` to recursively query peers of peers, building a broader view of the network. Includes safeguards: `--max-peers` cap and per-crawl timeout. -5. **Global default topic with override** -- a well-known default topic (`id-peer-discovery-v1`) and secret allows all `id` servers to find each other automatically. Users can override with `--topic` and `--topic-secret` for private networks. -6. **Layered bootstrapping** -- primary: DHT auto-discovery; supplementary: `--bootstrap ` for manual peer specification (useful for restricted networks, development, and testing). -7. **Server vs. caller modes** -- `--discover` flag tells the server to update its own peer list; default just returns results to the caller. - -### Security Model - -**Addressed by `distributed-topic-tracker`:** -- **Access control**: The shared `initial_secret` (topic secret) acts as a bearer token -- only nodes with the secret can decrypt DHT records and join the discovery topic -- **Signed records**: DHT records are Ed25519-signed, preventing spoofing of bootstrap announcements -- **Encrypted transport**: HPKE encryption on DHT records with per-minute key rotation - -**Known limitations (document, don't block on):** -- The default global secret is public knowledge -- anyone can join the default topic -- `PeerAnnouncement` messages over gossip are not individually authenticated (a node could theoretically claim any `node_id` in a broadcast, though the gossip layer attributes messages to the sending peer) -- No rate limiting on gossip messages within the topic beyond what iroh-gossip provides -- Private topics are only as secure as the shared secret distribution - ---- - -## Phase 0: Design Documentation - -**Status:** Complete - -Per project conventions ("document first, then implement"), create the design document before any code changes. - -### Tasks - -- [ ] Create `pkgs/id/docs/_feature_peer-discovery/` folder -- [ ] Write design document covering: - - Feature overview and motivation - - Architecture: `distributed-topic-tracker` + iroh-gossip + `PeerDiscovery` application layer - - Topic identity model (global default + override) - - `PeerAnnouncement` wire format (postcard) - - Bootstrapping hierarchy (DHT auto-discovery → manual `--bootstrap` → future Pkarr/DNS) - - Depth-based crawling algorithm with safeguards - - Security model and known limitations - - CLI flags and usage examples - - Web page design - - Link back to this plan file -- [ ] Add "References" section linking to this plan - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/docs/..._feature_peer-discovery/` | **Create** | - ---- - -## Phase 1: Core Types & Discovery Module - -**Status:** Complete -**New file:** `pkgs/id/src/discovery.rs` - -### Tasks - -- [ ] Define discovery constants: - - `DEFAULT_TOPIC: &str = "id-peer-discovery-v1"` (used with `TopicId::new()`) - - `DEFAULT_TOPIC_SECRET: &[u8] = b"id-public-discovery-v1"` (default shared secret for public network) - - `ANNOUNCE_INTERVAL: Duration = Duration::from_secs(30)` (broadcast frequency) - - `STALE_THRESHOLD: Duration = Duration::from_secs(120)` (4 missed heartbeats) - - `STALE_CHECK_INTERVAL: Duration = Duration::from_secs(60)` (cleanup frequency) -- [ ] Define `PeerAnnouncement` struct (Serialize/Deserialize via postcard): - - `node_id: NodeId` - - `name: Option` - - `blob_count: u64` - - `timestamp_secs: u64` -- [ ] Define `PeerInfo` struct (in-memory, not serialized): - - `announcement: PeerAnnouncement` - - `last_seen: Instant` -- [ ] Implement `PeerDiscovery` struct (`Arc>>`): - - `new() -> Self` - - `update(announcement: PeerAnnouncement)` -- insert/update peer - - `peers() -> Vec` -- return non-stale peers (>`STALE_THRESHOLD` = stale) - - `remove_stale(max_age: Duration)` -- prune expired entries - - `count() -> usize` -- [ ] Add `pub mod discovery;` to `pkgs/id/src/lib.rs` -- [ ] Add re-exports for `PeerAnnouncement`, `PeerInfo`, `PeerDiscovery` -- [ ] Unit tests for `PeerAnnouncement` serialization roundtrip -- [ ] Unit tests for `PeerDiscovery` (update, stale removal, count) - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/discovery.rs` | **Create** | -| `pkgs/id/src/lib.rs` | Modify (add module + re-exports) | - ---- - -## Phase 2: Protocol Extension -- ListPeers RPC - -**Status:** Complete -**Modifies:** `pkgs/id/src/protocol.rs` - -### Tasks - -- [ ] **Append** `ListPeers` variant to `MetaRequest` as the **last variant** (critical: postcard uses positional discriminants; inserting mid-enum breaks wire compat) -- [ ] **Append** `ListPeers { peers: Vec }` variant to `MetaResponse` as the **last variant** -- [ ] Update `MetaProtocol` struct to hold optional `PeerDiscovery`: - - Change `MetaProtocol::new(store, peer_discovery)` signature - - Store `Option` field -- [ ] Handle `MetaRequest::ListPeers` in the `accept()` method: - - If `PeerDiscovery` is available, return current peers - - If not, return empty list -- [ ] Update all call sites of `MetaProtocol::new()` (serve.rs) -- [ ] Unit tests for `ListPeers` request/response serialization - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/protocol.rs` | Modify | - -### Notes - -- `MetaProtocol::new()` signature change affects `serve.rs` (Phase 3 handles this) -- The `PeerDiscovery` is `Option` so non-serve contexts (tests, etc.) don't need it - ---- - -## Phase 3: Gossip Integration in Server - -**Status:** Complete -**Modifies:** `pkgs/id/src/commands/serve.rs`, `pkgs/id/src/cli.rs` - -### Tasks - -- [ ] Add CLI flags to `Serve` command: - - `--bootstrap ` -- comma-separated node IDs for manual supplementary bootstrapping - - `--topic ` -- gossip topic name (default: `DEFAULT_TOPIC`) - - `--topic-secret ` -- shared secret for topic access control (default: `DEFAULT_TOPIC_SECRET`) -- [ ] In `cmd_serve()`: - 1. Create `PeerDiscovery::new()` - 2. Create `Gossip::builder().spawn(endpoint.clone()).await?` - 3. Register gossip with Router: `.accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone())` - 4. Pass `PeerDiscovery` to `MetaProtocol::new(&store_handle, Some(peer_discovery.clone()))` - 5. Create `RecordPublisher` with topic and secret (from CLI flags or defaults) - 6. Call `gossip.subscribe_and_join_with_auto_discovery_no_wait(record_publisher)` (non-blocking variant -- don't block serve startup on DHT) - 7. If `--bootstrap` provided, additionally join those peers via `sender.join_peers()` - 8. Spawn background task: - - Every `ANNOUNCE_INTERVAL` (~30s): broadcast `PeerAnnouncement` with current blob count (from store tags count) - - Listen for incoming gossip events, deserialize `PeerAnnouncement`, call `peer_discovery.update()` - - Every `STALE_CHECK_INTERVAL` (~60s): call `peer_discovery.remove_stale(STALE_THRESHOLD)` - 9. Print `peers: gossip enabled (topic: )` on startup -- [ ] Pass `PeerDiscovery` into web `AppState` if web feature is enabled -- [ ] Gracefully shut down gossip on Ctrl+C - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/commands/serve.rs` | Modify (major) | -| `pkgs/id/src/cli.rs` | Modify (add flags to `Serve`) | - -### API Pattern - -```rust -use distributed_topic_tracker::{AutoDiscoveryGossip, RecordPublisher, TopicId}; -use iroh_gossip::net::Gossip; - -let gossip = Gossip::builder().spawn(endpoint.clone()).await?; - -// Register with router -let router = Router::builder(endpoint) - .accept(META_ALPN, meta) - .accept(BLOBS_ALPN, blobs) - .accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone()) - .spawn(); - -// Setup auto-discovery -let topic_id = TopicId::new(topic_name); -let record_publisher = RecordPublisher::new( - topic_id, - signing_key.verifying_key(), - signing_key, - None, // default secret rotation - topic_secret, -); - -// Non-blocking join -- DHT discovery runs in background -let topic = gossip - .subscribe_and_join_with_auto_discovery_no_wait(record_publisher) - .await?; -let (sender, mut receiver) = topic.split().await?; - -// Optionally join manual bootstrap peers -if !bootstrap_nodes.is_empty() { - sender.join_peers(bootstrap_nodes, None).await?; -} -``` - -### Notes - -- Use `_no_wait` variant so the server starts accepting connections immediately while DHT bootstrapping proceeds in the background -- `distributed-topic-tracker` automatically handles: DHT publishing, bubble merge, message overlap merge, and periodic record refresh -- The server's broadcast loop (PeerAnnouncement) is application-level, on top of the transport - ---- - -## Phase 4: `peers` CLI Command - -**Status:** Complete -**New file:** `pkgs/id/src/commands/peers.rs` - -### Tasks - -- [ ] Add `Peers` variant to `Command` enum in `cli.rs`: - ``` - Peers { - --gossip Use gossip only (join topic, collect announcements) - --rpc Use RPC only (query server's ListPeers) - --depth N Recursive depth (default 1, -1 = unlimited) - --max-peers N Hard cap on total peers discovered (default 1000) - --timeout N Per-crawl timeout in seconds (default 30) - --discover Tell server to update its peer list - --bootstrap Comma-separated seed node IDs - --topic Gossip topic name (default: DEFAULT_TOPIC) - --topic-secret Shared secret (default: DEFAULT_TOPIC_SECRET) - --no-relay Disable relay servers - node: Option Optional specific node to query - } - ``` -- [ ] Create `cmd_peers()` function: - 1. If `--rpc` (or default with serve running): send `MetaRequest::ListPeers` to local serve - 2. If `--gossip`: create endpoint, join gossip topic via auto-discovery, listen for N seconds, collect announcements - 3. Default: try RPC first, fall back to gossip - 4. **Depth crawling (with safeguards):** - - Depth 0: return initial results (from gossip and/or provided bootstrap peers) - - Depth 1+: for each discovered peer, connect and send `MetaRequest::ListPeers`, merge results - - Depth -1: keep crawling until no new peers found **or** `--max-peers` cap hit **or** `--timeout` exceeded - - Track visited nodes to avoid cycles - - Log warning when max-peers cap is hit - 5. If `--discover`: also send discovered peers back to the local server (future: via a new RPC or gossip broadcast) - 6. Print results: `\t\t\t` -- [ ] Add to `commands/mod.rs` re-exports -- [ ] Add to `main.rs` command dispatch -- [ ] CLI parsing tests - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/commands/peers.rs` | **Create** | -| `pkgs/id/src/commands/mod.rs` | Modify | -| `pkgs/id/src/cli.rs` | Modify | -| `pkgs/id/src/main.rs` | Modify (command dispatch) | - ---- - -## Phase 5: REPL Integration - -**Status:** Complete - -### Tasks - -- [ ] Add `peers` command to `execute_repl_command()` in `runner.rs`: - - In connected mode (serve running): send `MetaRequest::ListPeers` and display - - In local mode: print "no serve running, peers unavailable" -- [ ] Add `peers` to `print_help()` -- [ ] Support `peers @NODE_ID` to query a specific remote node's peer list - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/repl/runner.rs` | Modify | - ---- - -## Phase 6: Web Page (feature-gated under `web`) - -**Status:** Complete - -### Tasks - -- [ ] Add `PeerDiscovery` (or `Option`) to `AppState` in `web/mod.rs` -- [ ] Add `/peers` route in `web/routes.rs`: - - Handler queries `PeerDiscovery` state - - Returns HTML table of peers (node ID, name, blob count, last seen) - - Supports HTMX partial rendering -- [ ] Add `render_peers_page()` in `web/templates.rs`: - - Terminal-styled table matching existing theme - - Each peer row shows: node ID (truncated), name, blob count, relative time since last seen - - Auto-refresh via HTMX polling (every ~10s) -- [ ] Wire `PeerDiscovery` from `cmd_serve()` into `AppState` construction -- [ ] Add navigation link to peers page in existing templates - -### Files - -| File | Action | -|------|--------| -| `pkgs/id/src/web/mod.rs` | Modify | -| `pkgs/id/src/web/routes.rs` | Modify | -| `pkgs/id/src/web/templates.rs` | Modify | -| `pkgs/id/src/commands/serve.rs` | Modify (pass PeerDiscovery to web) | - ---- - -## Phase 7: Manual Bootstrap Fallback & Future Enhancements - -**Status:** Not started (future work, not needed for MVP) - -### Covered by Phase 3 - -The `--bootstrap ` flag in Phase 3 provides manual peer specification as a supplementary bootstrap mechanism. This is useful when: -- DHT traffic is blocked by firewalls -- Running in restricted/isolated networks -- Local development and testing -- The BitTorrent DHT is slow or unreachable - -### Bootstrap Hierarchy - -1. **Primary**: `distributed-topic-tracker` auto-discovery via BitTorrent mainline DHT (automatic, zero-config) -2. **Supplementary**: `--bootstrap ` for manual peer specification (combined with DHT results) -3. **Future stretch goal**: Pkarr/DNS-based discovery (publish known node IDs to DNS for another discovery channel) - -### Practical Workflow - -With DHT auto-discovery: -1. Server A starts -- publishes to DHT, waits for peers -2. Server B starts -- finds Server A via DHT, joins automatically -3. All subsequent servers discover the network via DHT - -Without DHT (restricted network): -1. Server A starts with no bootstrap -- gossip topic is empty -2. Server B starts with `--bootstrap ` -- discovers A -3. Server C starts with `--bootstrap ` -- discovers both - -### Future: Pkarr/DNS Bootstrap - -- Publish a well-known node ID to DNS (e.g., `_id-bootstrap.example.com`) -- On startup, resolve DNS to find initial bootstrap peers -- Acts as a third discovery channel alongside DHT and manual bootstrap -- Not needed for MVP -- DHT + manual bootstrap covers all practical scenarios - ---- - -## Phase 8: Testing & Polish - -**Status:** Complete (cargo check, cargo test, cargo fmt all pass; cargo clippy blocked by pre-existing E0514 environment issue) - -### Tasks - -- [ ] Run `just check` and fix any issues -- [ ] Verify all new tests pass -- [ ] Update module-level docstrings in modified files -- [ ] Update design document with any implementation-time changes -- [ ] Document security limitations in module-level docs -- [ ] Test scenarios: - - Two servers discovering each other via DHT (if testable without real DHT) - - Manual bootstrap between two local servers - - `peers` CLI command output formatting - - `peers --depth` crawling with cycle detection - - `peers --max-peers` cap enforcement - - REPL `peers` command - - Web `/peers` page (if web feature enabled) - - Stale peer removal - - Private topic with custom secret - ---- - -## Implementation Order - -1. **Phase 0** -- Design documentation (doc-first per project conventions) -2. **Phase 1** -- Core types (discovery.rs) -- no dependencies -3. **Phase 2** -- Protocol extension (ListPeers) -- depends on Phase 1 types -4. **Phase 3** -- Server gossip integration -- depends on Phase 1 + 2 -5. **Phase 4** -- CLI `peers` command -- depends on Phase 2 (uses ListPeers RPC) -6. **Phase 5** -- REPL integration -- depends on Phase 2 -7. **Phase 6** -- Web page -- depends on Phase 1 + 3 -8. **Phase 7** -- Bootstrap fallback (mostly done in Phase 3, this is documentation/future work) -9. **Phase 8** -- Testing + polish - -Phases 4, 5, and 6 are independent of each other and can be done in any order after Phase 3. - ---- - -## Key Risk: API Version Compatibility - -### iroh-gossip v0.96 - -The `Gossip::builder().spawn()` API needs verification against v0.96 docs. The plan assumes: -- `Gossip::builder().spawn(endpoint).await?` creates the gossip instance -- Events include `Event::Received`, `Event::NeighborUp`, `Event::NeighborDown` -- Broadcasting is done via the `GossipSender` handle - -### distributed-topic-tracker - -The crate is pinned via git dependency. The `pkgs/dht/` prototype uses v0.2.5 with iroh-gossip v0.95, while `pkgs/id/` uses iroh-gossip v0.96. **Verify that `distributed-topic-tracker` is compatible with iroh-gossip v0.96** before starting Phase 3. If not, the crate may need updating or the integration approach adjusted. - -Key API assumed: -- `AutoDiscoveryGossip` trait on `Gossip` -- `subscribe_and_join_with_auto_discovery_no_wait(RecordPublisher)` returns `Topic` -- `Topic::split()` returns `(GossipSender, GossipReceiver)` -- `GossipSender::broadcast(Vec)` for sending -- `GossipReceiver::next()` for receiving events - ---- - -## Appendix: File Change Summary - -| File | Phase | Action | -|------|-------|--------| -| `pkgs/id/docs/..._feature_peer-discovery/` | 0 | **Create** | -| `pkgs/id/src/discovery.rs` | 1 | **Create** | -| `pkgs/id/src/lib.rs` | 1 | Modify | -| `pkgs/id/src/protocol.rs` | 2 | Modify | -| `pkgs/id/src/commands/serve.rs` | 3, 6 | Modify (major) | -| `pkgs/id/src/cli.rs` | 3, 4 | Modify | -| `pkgs/id/src/commands/peers.rs` | 4 | **Create** | -| `pkgs/id/src/commands/mod.rs` | 4 | Modify | -| `pkgs/id/src/main.rs` | 4 | Modify | -| `pkgs/id/src/repl/runner.rs` | 5 | Modify | -| `pkgs/id/src/web/mod.rs` | 6 | Modify | -| `pkgs/id/src/web/routes.rs` | 6 | Modify | -| `pkgs/id/src/web/templates.rs` | 6 | Modify | diff --git a/.opencode/backup/plans/2026-03-24-tags-v2-iroh-docs.md b/.opencode/backup/plans/2026-03-24-tags-v2-iroh-docs.md deleted file mode 100644 index 5fcba6df34..0000000000 --- a/.opencode/backup/plans/2026-03-24-tags-v2-iroh-docs.md +++ /dev/null @@ -1,588 +0,0 @@ -# Tags v2: iroh-docs Metadata with Tuple-Encoded Keys & Real-time Web Integration - -## Summary - -Replace the current single-blob `MetaDoc` system (`src/tags.rs`) with an **iroh-docs** backed metadata store. Implement **FoundationDB-style tuple encoding** for binary keys with prefix-queryable structure at any depth. Wire real-time tag updates through a dedicated **WebSocket** endpoint to the web UI. Introduce a **multi-namespace** architecture with a system namespace and per-file namespaces. - -**Three layers:** -1. **Tuple encoding module** — binary key encoding with prefix queries at any depth -2. **iroh-docs metadata layer** — storage, sync, namespaces, API -3. **WebSocket & web UI** — display, CRUD, real-time updates - ---- - -## Design Decisions - -### Tuple encoding over postcard/msgpack/cbor - -**Problem:** Keys are binary and contain complex data (strings, integers, arrays). Need prefix queries at any depth — including mid-field (e.g., "all strings starting with 'read'"). - -**Why not postcard:** Length-prefixed strings prevent mid-field prefix queries. `serialize("two") = [03, t, w, o]` and `serialize("twelve") = [06, t, w, e, l, v, e]` don't share a byte prefix despite sharing character prefix "tw". - -**Why not msgpack/cbor:** Same length-prefix problem for strings. Array wrappers break field-boundary prefix queries. Non-canonical encoding risks (msgpack). - -**Solution:** FoundationDB-style tuple layer encoding where string bytes appear RAW (only `\0` escaped as `\0\xFF`, terminated by `\0`). Mid-field prefix = just omit the terminator. - -**Integers:** Big-endian encoding with byte count in type tag. Big-endian is required for lexicographic sort order to match numeric order (little-endian native on x86/ARM but byte-swap is 1 cycle via `u64::to_be_bytes()`). - -### iroh-docs over single-blob MetaDoc - -| Single-blob MetaDoc (current) | iroh-docs | -| ------------------------------------ | ------------------------------------------ | -| Load-modify-save bottleneck | Per-entry writes, no contention | -| No sync | Built-in sync via gossip between peers | -| No provenance | Author signatures (ed25519) on every entry | -| No entry timestamps | Automatic timestamp on every entry | -| No change notifications | `subscribe()` → real-time LiveEvent stream | -| JSON parse entire doc for any query | Prefix queries on binary keys | - -### Multi-namespace architecture - -- **System namespace** — default read/write target, associated with this iroh node. Holds cross-cutting metadata (tags for all files). One gossip topic, one sync boundary. -- **Per-file namespaces** — each friendly name gets its own iroh-doc. Enables per-file sync granularity, per-file sharing (DocTicket), per-file access control. -- Namespace mapping stored in system namespace: key `("_ns", filename)` → namespace_id bytes. - -### Separate WebSocket for tags (not extending collab) - -- Collab WebSocket is **per-document** — tied to ProseMirror content collaboration -- Tags are **cross-document metadata** — different lifecycle, different consumers -- Main page needs tag updates for ALL files simultaneously -- Clean separation of concerns - -### Persistent store - -- `Docs::persistent(path)` with `fs-store` feature — metadata survives restarts -- Store path: `{store_path}/docs/` - ---- - -## Layer 1: Tuple Encoding Module - -### Type tags and sort order - -``` -Tag(s) Type Payload -0x00 Null none (escaped to 0x00 0xFF inside nested tuples) -0x01 Bytes raw + escape(0x00→0x00 0xFF) + 0x00 terminator -0x02 String same as bytes, typed as UTF-8 -0x05 Tuple/Array recursive elements + 0x00 end -0x06 False none -0x07 True none -0x0C–0x13 Neg int 8–1 bytes ones-complement big-endian -0x14 Zero none -0x15–0x1C Pos int 1–8 bytes big-endian -0x21 Float64 8 bytes sort-adjusted IEEE 754 -``` - -Sort order: `null < bytes < string < tuple < false < true < -big…-small < 0 < small…big < float` - -### Encoding examples - -**Strings** — bytes appear raw, only `\0` escaped: -``` -"readme" → [02, r, e, a, d, m, e, 00] -"read" → [02, r, e, a, d, 00] -"re\0ad" → [02, r, e, 00, FF, a, d, 00] // \0 escaped as 0x00 0xFF -"" → [02, 00] // just type tag + terminator -``` - -**Booleans** — zero-byte payload: -``` -false → [06] -true → [07] -``` - -**Integers** — big-endian, byte count in type tag: -``` -0 → [14] -1 → [15, 01] -255 → [15, FF] -256 → [16, 01, 00] --1 → [13, FE] // ones-complement of 0x01 --256 → [12, FE, FF] // ones-complement of [0x01, 0x00] --1000 → [12, FC, 17] // ones-complement of [0x03, 0xE8] -i64::MIN → [0C, 7F, FF, FF, FF, FF, FF, FF, FF] -i64::MAX → [1C, 7F, FF, FF, FF, FF, FF, FF, FF] -``` - -**Float64** — sort-adjusted IEEE 754: -``` -Positive: flip sign bit only → 0.0 < 1.0 < inf ✓ -Negative: flip ALL bits → -inf < -1.0 < -0.0 ✓ --0.0 canonicalized to +0.0 -NaN rejected (encode returns error) -``` - -**Nested tuples/arrays:** -``` -("a", [1, 2]) → [02, 61, 00, 05, 15, 01, 15, 02, 00] - ^^^^^^^^ ^^ ^^^^^^ ^^^^^^ ^^ - "a" [ 1 2 ] - -[null, 1] → [05, 00, FF, 15, 01, 00] - ^^ ^^^^^ ^^^^^^ ^^ - [ null 1 ] - (null escaped as 0x00 0xFF inside nested tuple) -``` - -**Structs** — positional encoding (field names from schema, not encoded): -``` -{a: 1, b: [0,1,2,3], c: null} → - [15, 01, 05, 14, 15, 01, 15, 02, 15, 03, 00, 00] - ^^^^^^ ^^ ^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^ ^^ - a=1 [ 0 1 2 3 ] null -``` - -### Prefix query patterns - -``` -// Field-boundary prefix (exact field match, then any suffix): -all tags for "README.md": - prefix = [02, R,E,A,D,M,E,.,m,d, 00] // complete string + terminator - -// Mid-field prefix (partial string match): -all files starting with "READ": - prefix = [02, R,E,A,D] // string tag + partial, NO terminator - -// Multi-field prefix: -all "label" tags for "README.md": - prefix = [02, R,E,A,D,M,E,.,m,d, 00, 02, l,a,b,e,l, 00] - -// Mid-array prefix (inside nested array, before end marker): -a=1, b starts with [0, 1]: - prefix = [15, 01, 05, 14, 15, 01] // int(1) + array_start + int(0) + int(1) - matches {a:1, b:[0,1,2,3]} and {a:1, b:[0,1,5]} -``` - -### Null disambiguation inside nested tuples - -Inside a nested tuple, `0x00` is ambiguous (null element vs end-of-tuple): -- `0x00 0xFF` = null element (escaped) -- bare `0x00` = end of nested tuple - -This uses the same escape mechanism as strings/bytes. The decoder tracks nesting depth. - -### Rust API - -```rust -/// A decoded tuple element (owned). -pub enum TupleValue { - Null, - Bytes(Vec), - String(String), - Tuple(Vec), - Bool(bool), - Int(i64), - Float(f64), -} - -/// Builder for encoding tuple keys. -pub struct TupleEncoder { buf: Vec, nested: bool } - -impl TupleEncoder { - pub fn new() -> Self; - - // Full field encoding (type tag + payload + terminator) - pub fn null(&mut self) -> &mut Self; - pub fn bytes(&mut self, b: &[u8]) -> &mut Self; - pub fn string(&mut self, s: &str) -> &mut Self; - pub fn bool(&mut self, v: bool) -> &mut Self; - pub fn int(&mut self, v: i64) -> &mut Self; - pub fn float(&mut self, v: f64) -> Result<&mut Self>; // rejects NaN - pub fn array(&mut self, f: impl FnOnce(&mut Self)) -> &mut Self; - - // Prefix encoding (no terminator/end marker — for "starts with" queries) - pub fn string_prefix(&mut self, s: &str) -> &mut Self; - pub fn bytes_prefix(&mut self, b: &[u8]) -> &mut Self; - pub fn array_prefix(&mut self, f: impl FnOnce(&mut Self)) -> &mut Self; - - pub fn build(self) -> Vec; -} - -/// Decode all elements from tuple-encoded bytes. -pub fn decode(bytes: &[u8]) -> Result>; -``` - -Accessor methods on `TupleValue`: `as_str()`, `as_bytes()`, `as_int()`, `as_float()`, `as_bool()`, `as_tuple()`, `is_null()`. - -### Implementation scope - -~500-600 lines of Rust in `src/tuple.rs`. Zero new dependencies. Thorough tests: -- Encode/decode roundtrip for all types (null, bytes, string, bool, int, float, tuple) -- Integer boundaries (0, 1, -1, 255, 256, i64::MIN, i64::MAX) -- String edge cases (empty, contains `\0`, unicode) -- Float edge cases (+0.0, -0.0 canonical, ±inf, NaN rejected) -- Nested tuples (empty, with nulls, deeply nested) -- Sort order within types and across type boundaries -- Prefix query correctness (field-boundary, mid-field, mid-array) -- Struct encoding ({a: 1, b: [0,1,2,3], c: null}) - -### Files - -| File | Change | -|------|--------| -| `src/tuple.rs` | **New** — tuple encoding module | -| `src/lib.rs` | Add `pub mod tuple;` | - ---- - -## Layer 2: iroh-docs Metadata - -### 2.1 Dependency - -**Cargo.toml:** -```toml -iroh-docs = { version = "0.97", features = ["fs-store"] } -``` - -### 2.2 Initialize iroh-docs in `src/commands/serve.rs` - -**Problem:** `Docs::spawn()` requires `Gossip`, but gossip is only created when `!no_gossip`. - -**Solution:** Always create Gossip. Only register `GOSSIP_ALPN` on router when gossip enabled. - -```rust -// Always (needed for Docs even in no-gossip mode) -let gossip = Gossip::builder().spawn(endpoint.clone()).await?; -let docs = Docs::persistent(&store_path.join("docs")) - .spawn(endpoint.clone(), store.clone(), gossip.clone()) - .await?; -let author_id = docs.author_default().await?; -let meta_doc = get_or_create_meta_doc(&docs, &store_path).await?; - -// Register ALPN -router = router.accept(iroh_docs::net::ALPN, docs.clone()); - -// Only when gossip enabled -if !no_gossip { - router = router.accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone()); - // ... existing gossip logic ... -} -``` - -**`get_or_create_meta_doc`:** -- Check `{store_path}/meta-doc-id` file for stored NamespaceId -- If found: `docs.open(id)` — reuse existing -- If not found: `docs.create()`, save NamespaceId to file -- Run migration check (2.5) - -### 2.3 Update AppState (`src/web/mod.rs`) - -```rust -pub struct AppState { - pub store: Store, // existing — iroh-blobs - pub meta_doc: Doc, // NEW — system metadata document - pub author_id: AuthorId, // NEW — this node's author for writes - pub tag_broadcast: Arc, // NEW — real-time tag event broadcaster - pub collab: Arc, - pub assets: AssetUrls, - pub peers: Option, - pub node_id: String, -} -``` - -### 2.4 Rewrite `src/tags.rs` — iroh-docs backed API - -**Key schema using tuple encoding:** - -```rust -// Single-value tag: subject + key → value in entry bytes -key = TupleEncoder::new().string("README.md").string("created").build() -val = b"1711152000" - -// Multi-value tag: subject + key + value → empty entry -key = TupleEncoder::new().string("README.md").string("label").string("rust").build() -val = b"" - -// Namespace mapping (system namespace only): -key = TupleEncoder::new().string("_ns").string("README.md").build() -val = namespace_id_bytes - -// Complex future tag with integer: -key = TupleEncoder::new().string("README.md").string("version").int(3).build() -val = b"" -``` - -**API:** - -```rust -/// A resolved tag entry with full metadata from iroh-docs. -pub struct TagEntry { - pub subject: String, - pub key: String, - pub value: String, - pub author: AuthorId, - pub timestamp: u64, -} - -// === Core CRUD === -pub async fn set_tag(doc: &Doc, author: AuthorId, subject: &str, key: &str, value: &str) -> Result<()>; -pub async fn get_tags(doc: &Doc, subject: &str) -> Result>; -pub async fn get_tag(doc: &Doc, subject: &str, key: &str) -> Result>; -pub async fn remove_tag(doc: &Doc, author: AuthorId, subject: &str, key: &str) -> Result<()>; -pub async fn remove_all_tags(doc: &Doc, author: AuthorId, subject: &str) -> Result<()>; - -// === Multi-value === -pub async fn add_multi_tag(doc: &Doc, author: AuthorId, subject: &str, key: &str, value: &str) -> Result<()>; -pub async fn get_multi_tags(doc: &Doc, subject: &str, key: &str) -> Result>; -pub async fn remove_multi_tag(doc: &Doc, author: AuthorId, subject: &str, key: &str, value: &str) -> Result<()>; - -// === Convenience === -pub async fn set_created(doc: &Doc, author: AuthorId, name: &str) -> Result<()>; -pub async fn set_modified(doc: &Doc, author: AuthorId, name: &str) -> Result<()>; -pub async fn transfer_tags(doc: &Doc, author: AuthorId, old_name: &str, new_name: &str) -> Result<()>; -pub async fn add_archive_tag(doc: &Doc, author: AuthorId, name: &str, archive_name: &str) -> Result<()>; -pub async fn get_created_time(doc: &Doc, name: &str) -> Result>; -pub async fn get_modified_time(doc: &Doc, name: &str) -> Result>; - -// === Query === -pub async fn find_by_tag(doc: &Doc, key: &str, value: &str) -> Result>; -pub async fn list_all_tags(doc: &Doc) -> Result>; -``` - -**Implementation notes:** -- `set_tag` → `doc.set_bytes(author, tuple(subject, key), value.as_bytes())` -- `get_tags` → `doc.get_many(Query::single_latest_per_key().key_prefix(tuple_prefix(subject)))` then decode -- `remove_tag` → `doc.del(author, tuple(subject, key))` (inserts empty entry) -- `transfer_tags` → read all for old subject, write under new, delete old -- Uses `Query::single_latest_per_key()` for last-write-wins conflict resolution - -### 2.5 Migrate existing MetaDoc data - -On first startup with new system: -1. Check if old `.meta` blob tag exists: `store.tags().get(Tag::from(".meta"))` -2. If found: read blob → deserialize JSON `MetaDoc` -3. For each `MetaTag`: write as iroh-docs entry using tuple key encoding -4. Delete `.meta` blob tag -5. Log: "Migrated {n} metadata tags from .meta blob to iroh-docs" - -### 2.6 Update integration points - -All callers pass `(meta_doc, author_id)` from AppState: - -| File | Function | Change | -|------|----------|--------| -| `src/web/routes.rs` | `get_file_list()` | Use `get_tags(doc, name)` per file | -| `src/web/routes.rs` | `save_handler` | `set_modified(doc, author, name)` | -| `src/web/routes.rs` | `new_file_handler` | `set_created` + `set_modified` | -| `src/web/routes.rs` | `rename_handler` | `transfer_tags` + `add_archive_tag` | -| `src/protocol.rs` | rename handler | `transfer_tags(doc, author, old, new)` | -| `src/commands/repl.rs` | rename command | `transfer_tags(doc, author, old, new)` | - -Remove all `load_meta()`/`save_meta()` calls. - -### 2.7 Namespace management - -**System namespace:** -- Created once on first run, NamespaceId persisted to disk -- All tag operations default to this namespace -- Keys: `tuple(subject, tag_key, [tag_value])` - -**Per-file namespaces:** -- Created lazily on first request (or when sharing a specific file) -- Mapping stored in system namespace: `tuple("_ns", filename)` → namespace_id bytes -- Within file namespace: keys are `tuple(tag_key, [tag_value])` (no subject — namespace IS the subject) -- Enables: `meta_doc.share(ShareMode::Read, addr_options)` for per-file sharing - -```rust -pub async fn get_or_create_file_namespace( - docs: &DocsApi, - system_doc: &Doc, - author: AuthorId, - filename: &str, -) -> Result; - -pub async fn get_file_namespace( - docs: &DocsApi, - system_doc: &Doc, - filename: &str, -) -> Result>; -``` - -### 2.8 Subscribe to LiveEvents - -Background task on startup: - -```rust -fn spawn_tag_event_listener(doc: Doc, broadcast: Arc) { - tokio::spawn(async move { - let mut events = doc.subscribe().await?; - while let Some(Ok(event)) = events.next().await { - match event { - LiveEvent::InsertLocal { entry } | LiveEvent::InsertRemote { entry, .. } => { - let key_bytes = entry.key(); - if let Ok(fields) = tuple::decode(key_bytes) { - let is_delete = entry.content_len() == 0; - // Parse fields, construct TagEvent, broadcast - broadcast.emit(tag_event); - } - } - _ => {} - } - } - }); -} -``` - -### Layer 2 files - -| File | Change | -|------|--------| -| `Cargo.toml` | Add `iroh-docs = { version = "0.97", features = ["fs-store"] }` | -| `src/tags.rs` | **Complete rewrite** — tuple keys + iroh-docs CRUD + migration | -| `src/commands/serve.rs` | Init Gossip always, init Docs, create meta doc, spawn listener | -| `src/web/mod.rs` | Add `meta_doc`, `author_id`, `tag_broadcast` to AppState | -| `src/web/routes.rs` | Update all tag callers to new async API | -| `src/protocol.rs` | Update rename tag transfer | -| `src/commands/repl.rs` | Update rename tag transfer | - ---- - -## Layer 3: WebSocket & Web UI - -### 3.1 Tag CRUD REST API - -``` -GET /api/tags → list all tags (?subject=, ?key= filters) -GET /api/tags/:subject → list tags for a file -POST /api/tags → add tag { subject, key, value? } -DELETE /api/tags → remove tag { subject, key, value? } -``` - -JSON response: -```json -{ - "tags": [ - { "subject": "README.md", "key": "category", "value": "docs", "author": "abc123", "timestamp": 1711152000 } - ] -} -``` - -### 3.2 Tag WebSocket endpoint - -``` -/ws/tags → global tag updates (main page) -/ws/tags/:subject → tag updates for specific file (editor page) -``` - -Wire protocol (MessagePack for consistency with collab): -``` -[0, tags[]] → TagInit: full state on connect -[1, subject, key, value, author, timestamp] → TagSet: server→client -[2, subject, key] → TagRemove: server→client -[3, subject, key, value?] → TagSetRequest: client→server -[4, subject, key] → TagDeleteRequest: client→server -``` - -### 3.3 Tag broadcast infrastructure - -New module `src/web/tags_ws.rs`: - -```rust -pub struct TagBroadcast { - global: broadcast::Sender, - subjects: RwLock>>, -} - -pub enum TagEvent { - Set { subject: String, key: String, value: String, author: String, timestamp: u64 }, - Remove { subject: String, key: String }, -} - -impl TagBroadcast { - pub fn new() -> Self; - pub fn emit(&self, event: TagEvent); - pub fn subscribe_global(&self) -> broadcast::Receiver; - pub fn subscribe_subject(&self, subject: &str) -> broadcast::Receiver; -} -``` - -### 3.4 Main page tag display - -**FileInfo update:** -```rust -pub struct FileInfo { - // existing... - pub tags: Vec, // all user-visible tags -} -``` - -**Template changes:** -- Tag pills/badges beside each filename -- Color-coded by tag key -- System tags (created, modified, archived) shown as they are -- User tags shown as clickable pills -- Search bar gains `tag:key=value` filter syntax - -**Real-time:** -- Connect `/ws/tags` on page load -- On TagSet/TagRemove: update file row's tag display in-place - -### 3.5 Editor page tag display + CRUD - -- Tag section in header or sidebar -- All tags with author attribution -- "Add tag" form: key + optional value -- "x" button to remove tag pills -- Connect `/ws/tags/{filename}` on load -- Send TagSetRequest/TagDeleteRequest via WebSocket - -### 3.6 Client-side JavaScript - -In `web/src/tags.ts` (new module): - -```typescript -interface TagEntry { subject: string; key: string; value: string; author: string; timestamp: number; } -type TagEvent = { type: 'set'; subject: string; key: string; value: string; author: string; timestamp: number } - | { type: 'remove'; subject: string; key: string }; - -function initTagsWs(url: string, onEvent: (event: TagEvent) => void): WebSocket; -async function addTag(subject: string, key: string, value?: string): Promise; -async function removeTag(subject: string, key: string): Promise; -async function getTags(subject?: string): Promise; -function renderTagPills(container: Element, tags: TagEntry[]): void; -function renderTagEditor(container: Element, subject: string): void; -``` - -### Layer 3 files - -| File | Change | -|------|--------| -| `src/web/routes.rs` | Add `/api/tags` endpoints, `/ws/tags` routes | -| `src/web/tags_ws.rs` | **New** — TagBroadcast, WebSocket handler | -| `src/web/mod.rs` | Add `mod tags_ws` | -| `src/web/templates.rs` | Tag pills in file list, tag editor in editor page | -| `web/src/tags.ts` | **New** — WebSocket client, REST, UI | -| `web/src/main.ts` | Import and init tags module | -| `web/styles/terminal.css` | Tag pill/badge styling | - ---- - -## Implementation Order - -1. `src/tuple.rs` — tuple encoding (standalone, testable independently) -2. `Cargo.toml` + `src/commands/serve.rs` — iroh-docs init -3. `src/tags.rs` — rewrite with iroh-docs + tuple keys -4. Integration points — update all callers -5. Migration — MetaDoc → iroh-docs one-time migration -6. `src/web/tags_ws.rs` — broadcast infrastructure -7. REST API endpoints -8. WebSocket endpoints -9. Template updates (tag pills) -10. Client-side JS (tags.ts) - -Steps 1-5 are Phase 1 (iroh level). Steps 6-10 are Phase 2 (web UI). - ---- - -## Open Questions - -1. **Per-file namespace creation policy:** Eager (create on file creation) or lazy (create on first share/specific request)? - -2. **Tag sharing between peers:** When a peer connects, how do they learn the system namespace's NamespaceId? Options: include in gossip PeerAnnouncement, exchange during ALPN handshake, manual DocTicket. - -3. **Delete semantics:** `doc.del()` inserts empty entries that propagate via sync. Alternative: use sentinel value instead of `del()` to avoid uncontrollable delete propagation. Decision needed. - -4. **Conflict resolution:** `single_latest_per_key()` = last-write-wins. Should UI surface multi-author conflicts? - -5. **Internal tag filtering:** `created`, `modified`, `archived`, `_ns` are system tags. Show with different styling vs hide from user tag CRUD? diff --git a/.opencode/backup/plans/2026-03-24-tags-v2-polish.md b/.opencode/backup/plans/2026-03-24-tags-v2-polish.md deleted file mode 100644 index cb62220553..0000000000 --- a/.opencode/backup/plans/2026-03-24-tags-v2-polish.md +++ /dev/null @@ -1,314 +0,0 @@ -# Tags V2 Polish: Aliases, Tests, Playwright, Nix, Docs - -> **Status:** Draft -> **Date:** 2026-03-24 -> **Predecessor:** [2026-03-24-tags-v2-iroh-docs.md](./2026-03-24-tags-v2-iroh-docs.md) - -## Overview - -Complete the Tags V2 work with: REPL/CLI aliases (`tag`/`label`/`link`), comprehensive test coverage (unit + integration + Playwright E2E), Nix infrastructure for browser testing, fix nix flake check -L to 100%, documentation updates, and build.sh log level fix. - ---- - -## Task 1: REPL Tag Aliases (`label`, `link`) - -**Goal:** Allow `label` and `link` as interchangeable prefixes for all `tag` commands in both CLI and REPL. - -### 1a. CLI aliases (src/cli.rs) - -- **Line 807:** Change `#[command(subcommand)]` to `#[command(subcommand, aliases = ["label", "link"])]` on the `Tag(TagCommand)` variant -- **Line ~27 in docstring:** Add `label` and `link` to the CLI structure comment - -### 1b. REPL aliases (src/repl/runner.rs) - -- **Lines 356-404:** Every `"tag"` pattern match must also accept `"label"` and `"link"`: - - Line 356: `["tag", "set" | "add", ...]` → `["tag" | "label" | "link", "set" | "add", ...]` - - Line 360: Same pattern - - Line 364-371: Same for `del` variants - - Line 376-384: Same for `del` with value - - Line 397: `["tag", "search", key]` → `["tag" | "label" | "link", "search", key]` - - Line 401: Same for search with value -- **Lines 389-395:** The standalone `tags` command → also add `labels` and `links` as aliases -- **Help text (lines 505-509):** Update to mention `label`/`link` as aliases - -### 1c. Tests - -- **Unit test in cli.rs tests:** Verify `id label set X Y Z` and `id link set X Y Z` parse correctly -- **Unit test in runner.rs tests:** Verify `label set ...` and `link set ...` dispatch correctly - ---- - -## Task 2: Fix nix flake check -L (Critical - Unblocks Everything) - -**Goal:** Get `nix flake check -L` to 100% pass. - -### Root cause -`src/commands/tag.rs` is locally present but **untracked** by git. Nix copies only git-tracked files (`src = ./.;`), so `mod tag` in `commands/mod.rs` fails to resolve. - -### Fix -```bash -git add src/commands/tag.rs # Track the file -git add src/tags.rs src/tuple.rs # Track other new files -# Also track all other new/modified files from Tags V2 work -``` - -Then run `nix flake check -L` and fix any remaining failures iteratively. Pre-existing failures must be fixed (not deleted), tests can be rewritten if incorrect. - ---- - -## Task 3: New Unit Tests - -**Goal:** Add unit tests for all new code from Tags V2. - -### 3a. tags.rs (src/tags.rs) -Already has 22 tests. Verify coverage of `copy_all_tags()` — add if missing. - -### 3b. commands/tag.rs (src/commands/tag.rs) -Add tests for: -- `cmd_tag_set` argument parsing -- `cmd_tag_del` argument parsing -- `cmd_tag_list` argument parsing -- `cmd_tag_search` argument parsing - -### 3c. web/routes.rs — copy_handler -Add tests for: -- `CopyRequest`/`CopyResponse` serialization -- `copy_handler` success path -- `copy_handler` when source doesn't exist -- `copy_handler` when target already exists (archives) - -### 3d. web/templates.rs -Add tests for: -- `render_media_viewer` includes rename/copy buttons -- `render_binary_viewer` includes rename/copy buttons -- `render_editor` includes copy button - -### 3e. repl/runner.rs -Add tests for: -- `label` and `link` alias dispatch -- `labels`/`links` standalone aliases - -### 3f. cli.rs -Add tests for: -- `id label set X Y Z` parses correctly -- `id link del X Y` parses correctly -- `id label list` parses correctly -- `id link search K V` parses correctly - ---- - -## Task 4: New Integration Tests - -**Goal:** Add integration tests in `tests/cli_integration.rs` for tag commands. - -### 4a. Tag command tests (new module: `tag_tests`) -- `test_tag_set_and_list`: Put a file, set tags, verify `tag list` output -- `test_tag_del`: Set then delete a tag, verify gone -- `test_tag_search`: Set tags on multiple files, search by key/value -- `test_tag_label_alias`: Verify `id label set ...` works same as `id tag set ...` -- `test_tag_link_alias`: Verify `id link search ...` works same as `id tag search ...` - -### 4b. Copy command test (if CLI copy exists) -Check if `copy` is exposed as a CLI command — if not, test via REPL integration or skip. - ---- - -## Task 5: Playwright E2E Tests Setup - -**Goal:** Set up basic Playwright infrastructure and write foundational E2E tests for the web UI. - -### 5a. Infrastructure setup - -**Package setup:** -```bash -cd web && bun add -d @playwright/test -``` - -**Config file:** `web/playwright.config.ts` -- Projects: `chromium` and `firefox` -- `webServer` config to start `id serve --web` before tests -- Use environment variable for browser executable path (Nix compatibility): - ```typescript - use: { - channel: undefined, // Let Nix provide the browser - launchOptions: { - executablePath: process.env.PLAYWRIGHT_CHROMIUM_PATH || undefined, - } - } - ``` - -**Browser path handling for Nix:** -- In `nix-common.nix`, set env vars: - ```nix - PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH = "${pkgs.chromium}/bin/chromium"; - PLAYWRIGHT_FIREFOX_EXECUTABLE_PATH = "${pkgs.firefox}/bin/firefox"; - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"; - ``` -- In playwright config, read these env vars for `executablePath` - -### 5b. Nix dependencies (nix-common.nix) - -Add to `nativeBuildInputs`: -- `playwright-driver` (or `playwright-test` if available) -- `chromium` -- `firefox` - -Add shell hook environment variables: -```nix -PLAYWRIGHT_BROWSERS_PATH = "${pkgs.playwright-driver.browsers}"; -PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"; -``` - -### 5c. Justfile commands - -```just -# Run Playwright E2E tests -test-e2e: - cd web && bunx playwright test - -# Run Playwright tests for specific browser -test-e2e-chromium: - cd web && bunx playwright test --project=chromium - -test-e2e-firefox: - cd web && bunx playwright test --project=firefox -``` - -Add corresponding `nix run` apps in `flake.nix`. - -### 5d. Basic E2E test files - -**`web/e2e/home.spec.ts`** — Home page tests: -- Page loads with title containing "id" -- File list is visible -- New file form exists -- Can create a new file -- Search/filter input works - -**`web/e2e/editor.spec.ts`** — Editor tests: -- Navigate to a file and editor loads -- Rename button visible -- Copy button visible -- Can rename a file via prompt - -**`web/e2e/tags.spec.ts`** — Tag UI tests: -- Tags display on file list items -- Tag panel visible on editor page -- Can add a tag via inline form - -Each test runs against both Chromium and Firefox (via Playwright projects). - -### 5e. Flake.nix check integration - -Add `test-e2e` check if feasible (may need headless browser in nix sandbox — might need to skip or mark as `passthru` if sandboxing is an issue). - ---- - -## Task 6: build.sh Log Level Fix - -**Goal:** Update build.sh to set `RUST_LOG=info` instead of debug. - -### Analysis -`scripts/build.sh` (and `build.sh` which is a symlink to it) does NOT currently set any log level. The user likely wants the serve/run commands to default to `info` rather than `debug`. - -### Approach -- Check if `RUST_LOG` is set in the build script or justfile serve commands -- If the justfile `serve` command or `build.sh` sets `RUST_LOG=debug`, change it to `RUST_LOG=info` -- If neither sets it, add `export RUST_LOG="${RUST_LOG:-info}"` to `build.sh` so the built binary defaults to info unless overridden -- Also check `justfile` serve recipes for any `RUST_LOG=debug` settings - ---- - -## Task 7: Documentation Updates - -### 7a. README.md (new — replaces deleted brainstorm notes) - -Create a proper project README with: -- Project name and one-line description -- Feature list (P2P file sharing, metadata tags, web UI, REPL, etc.) -- Quick start / installation -- Usage examples (CLI, REPL, serve) -- Architecture overview (link to ARCHITECTURE.md) -- Development setup (nix develop) -- License - -### 7b. ARCHITECTURE.md (new) - -Create comprehensive architecture document: -- System overview diagram -- Module structure (src/ tree with descriptions) -- Data flow: put → store → protocol → peers -- Storage layer: iroh-blobs (content) + iroh-docs (metadata tags) -- Tag system: Alpha/Omega CRDT documents, tuple encoding -- Web UI architecture: Axum routes, templates, WebSocket collaboration -- REPL design: readline + preprocessing + command dispatch -- Peer discovery: DHT + gossip topics -- Build variants: lib vs web - -### 7c. WEB.md updates - -- Add copy API route (`POST /api/copy`) -- Document rename/copy buttons on all viewer pages -- Update API routes table -- Document tag UI (tag panel, inline add, bulk tag operations) - -### 7d. web/README.md updates - -- Add `copyFile()` to JavaScript API section -- Document tag-related WebSocket events (`TagEvent`) -- Update file structure if new files were added - -### 7e. docs/ feature documentation - -Create `docs/2026-03-24T00-00-00Z_feature_tag_aliases/` with: -- Link back to plan file -- Description of `tag`/`label`/`link` alias system -- REPL and CLI alias tables -- References - ---- - -## Task 8: Commit and Verify - -### 8a. Stage all files -```bash -git add -A # Track everything (respecting .gitignore) -``` - -### 8b. Run full verification -```bash -just check # Primary quality gate -nix flake check -L # Nix-level verification -``` - -### 8c. Commit -``` -feat(tags): complete tags v2 with aliases, copy UI, tests, and docs - -- Add tag/label/link aliases to CLI and REPL -- Add /api/copy route and copyFile() JS method -- Add rename/copy buttons to all viewer pages (editor, media, binary) -- Add tag UI: pills, inline add, bulk operations, search/filter -- Set up Playwright E2E tests with Chromium + Firefox -- Add unit tests for tag commands, copy handler, aliases -- Add integration tests for tag CLI commands -- Fix nix flake check -L (track all new files) -- Create ARCHITECTURE.md, proper README.md -- Update WEB.md, web/README.md with new features -- Set RUST_LOG default to info in build.sh -``` - ---- - -## Execution Order - -1. **Task 2** (Fix nix) — unblocks everything, just `git add` untracked files -2. **Task 1** (Aliases) — small code change -3. **Task 6** (build.sh) — small change -4. **Task 3** (Unit tests) — can run with `just test-unit` -5. **Task 4** (Integration tests) — requires binary build -6. **Task 5** (Playwright) — largest new infrastructure -7. **Task 7** (Documentation) — can be parallelized with tests -8. **Task 8** (Commit) — final verification - -Tasks 3, 4, 5, 7 can be partially parallelized. diff --git a/.opencode/backup/plans/2026-03-25-tags-binary-search-autotag.md b/.opencode/backup/plans/2026-03-25-tags-binary-search-autotag.md deleted file mode 100644 index c310c34d8b..0000000000 --- a/.opencode/backup/plans/2026-03-25-tags-binary-search-autotag.md +++ /dev/null @@ -1,337 +0,0 @@ -# Tags: Binary Keys/Values, Search Syntax, Auto-Tagging & CLI/REPL Parity - -**Date:** 2026-03-25 -**Branch:** `e2e-nix` -**Predecessor:** [Tags v2 Iroh Docs Plan](2026-03-24-tags-v2-iroh-docs.md) - ---- - -## Original Request (verbatim) - -> - repl and cli should be 1:1, ensure any diff in one is copied into the other, such as the aliases etc. -> - ensure docs keys can be bytes/binary allowing structured data. either key or value can be bytes and not just string. review the original tags v2 plan at .opencode/plans/2026-03-24-tags-v2-iroh-docs.md -> - ensure tag keys and values can be any length and any kind of bytes, but try to parse as utf8. cutoff in the ui/etc after a certain length. if it doesn't parse as utf8 then exclude as binary without a flag. -> - allow searching keys and values in the ui. strings ending with : mean keys, starting with : mean values key:value means that specific key. allow quotes to do regular search so ":key" looks for any file/key/value that is literally ":key". "key:":":value" looks for a key named "key:" with a value ":value". a file uploaded should automatically tag name,file,path tags to the file. all name/file/path keys should show as the name in the ui, but they should dedupe if they have the exact same hash, tag values, name of the file. make a migrate flag that automatically adds the name/file/path labels for all existing files which don't have them. -> - when you are done add appropriate unit/integration/playwright tests as-needed. -> - when you are done review all .md files across the repo and ensure they are up-to-date. -> - when you are done, nix flake check -L should pass 100%. fix any errors even if you dont think you made them. -> - when you are done, update all docstrings, comments, help text for all functions and objects in rust and typescript. - ---- - -## 1. Overview & Intent - -This plan transforms the tag system from string-only to arbitrary-bytes-capable, adds structured search syntax across CLI/REPL/Web, auto-tags uploaded files with name/file/path metadata, and ensures CLI and REPL are exact mirrors. The design philosophy: tags are arbitrary key-value byte pairs that are *displayed* as UTF-8 when possible, with graceful fallback for binary data. - ---- - -## 2. Architecture: Before & After - -### Before - -| Layer | Current State | -|---|---| -| **Tag struct** (`tags.rs`) | `subject: String, key: String, value: Option` | -| **Tuple encoding** (`tags.rs`) | Always uses `enc.string()` — binary data rejected | -| **Protocol** (`protocol.rs`) | `SetTag/DelTag/GetTags/SearchTags` — all `String` fields | -| **CLI** (`cli.rs`) | `TagCommand` variants use `String` — no binary support | -| **REPL** (`runner.rs`) | Pattern-matched tag commands — no `find` alias for search, has `tags` shorthand | -| **Web API** (`tags_ws.rs`) | REST/WS endpoints — all `String`, no search endpoint | -| **Put command** (`commands/put.rs`) | Stores blob + sets iroh tag — NO metadata auto-tagging | -| **Search** | Basic key/value string match only — no structured syntax | -| **Display** | No length cutoff, no binary indicator | - -### After - -| Layer | Target State | -|---|---| -| **Tag struct** (`tags.rs`) | `subject: Vec, key: Vec, value: Option>` with `Display` that tries UTF-8 | -| **Tuple encoding** (`tags.rs`) | Uses `enc.bytes()` for raw data; decode tries `as_str()` then falls back to `as_bytes()` | -| **Protocol** (`protocol.rs`) | Tag fields become `Vec`; serde as base64 for JSON compat; postcard handles natively | -| **CLI** (`cli.rs`) | Accepts string args; `--hex` flag for inputting binary; displays with UTF-8-try logic | -| **REPL** (`runner.rs`) | Exact 1:1 with CLI: same aliases, same subcommands, same flags | -| **Web API** (`tags_ws.rs`) | Base64-encoded byte fields; new `/api/tags/search` endpoint with query syntax | -| **Put command** (`commands/put.rs`) | Auto-creates `name`, `file`, `path` metadata tags after successful upload | -| **Search** | Structured syntax: `key:` (key filter), `:value` (value filter), `key:value` (pair), `"quoted"` (literal) | -| **Display** | UTF-8 attempted; binary shown as `` unless `--binary` flag; 256-char cutoff in UI | -| **Migration** | `id migrate-tags` command to backfill name/file/path for existing entries | - ---- - -## 3. Detailed Design - -### 3.1 Binary Keys & Values - -**Core change:** Replace `String` with `Vec` throughout the tag pipeline. - -**`TagValue` wrapper type** (new in `tags.rs`): -```rust -/// A tag field that stores arbitrary bytes but tries to display as UTF-8. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct TagValue(Vec); - -impl TagValue { - pub fn from_str(s: &str) -> Self { Self(s.as_bytes().to_vec()) } - pub fn from_bytes(b: Vec) -> Self { Self(b) } - pub fn as_bytes(&self) -> &[u8] { &self.0 } - pub fn as_str(&self) -> Option<&str> { std::str::from_utf8(&self.0).ok() } - pub fn is_utf8(&self) -> bool { std::str::from_utf8(&self.0).is_ok() } - pub fn display_lossy(&self) -> String { String::from_utf8_lossy(&self.0).into_owned() } - pub fn display_truncated(&self, max: usize) -> String { /* UTF-8 try, truncate, add "..." */ } -} -``` - -**Serde:** Serialize as base64 string for JSON (web API), raw bytes for postcard (protocol). - -**Tuple encoding changes in `tags.rs`:** -- `encode_alpha_key` / `encode_omega_key`: use `enc.bytes()` instead of `enc.string()` -- `decode_alpha_key` / `decode_omega_key`: try `as_str()`, fall back to `as_bytes()` - -**Display rules:** -- Try UTF-8 parse. If valid: display as string, truncated at 256 chars in UI. -- If invalid UTF-8: display as `` by default. Show hex with `--binary`/`--hex` flag. -- In web UI: show as `[binary: N bytes]` with a "copy hex" button. - -### 3.2 CLI/REPL Parity - -**Identified diffs to fix:** - -| Feature | CLI | REPL | Fix | -|---|---|---|---| -| Search alias `find` | ✅ `tag search` alias `find` | ❌ Only `tag search` | Add `find` to REPL patterns | -| `tags` shorthand | ❌ No shorthand | ✅ `tags\|labels\|links` lists all | Document as REPL-only interactive convenience (acceptable diff) | -| Help text | Via `--help` | Via `help tag` | Ensure identical descriptions | - -**REPL additions:** -- Add `find` as alias: `tag|label|link find|search [value]` -- Ensure all error messages match CLI wording - -### 3.3 Search Syntax - -**Grammar:** - -``` -search_term := quoted_string | key_value | key_only | value_only | bare_word -quoted_string := '"' '"' → literal search across subject/key/value -key_only := ':' → filter by key name -value_only := ':' → filter by value -key_value := ':' → filter by key AND value -bare_word := → search across subject/key/value -``` - -**Examples:** -- `name:` → all tags with key "name" -- `:myfile.txt` → all tags with value "myfile.txt" -- `name:myfile.txt` → tags with key "name" and value "myfile.txt" -- `":key"` → literal search for ":key" in any field -- `"key:"` → literal search for "key:" in any field -- `"key:":":value"` → key is literally "key:", value is literally ":value" - -**Implementation:** New `SearchQuery` parser in `tags.rs` with `parse_search_query(input: &str) -> Vec`. Applied in `search_tags()` method. - -**Where it applies:** -- CLI: `id tag search ` — query is the full search string -- REPL: `tag search ` -- Web UI: Search box in tags panel sends to `/api/tags/search?q=` - -### 3.4 Auto-Tagging on Upload - -**When:** After successful `put` (file or stdin) — both local and remote modes. - -**Tags created:** -- `name` → filename (basename, e.g., `photo.jpg`) -- `file` → filename (same as name, for alias compatibility) -- `path` → full original path as provided by user (e.g., `~/photos/photo.jpg`) - -For stdin: `name` and `file` = provided name, `path` = ``. - -**Files affected:** -- `commands/put.rs` — add `auto_tag()` call after successful store -- `tags.rs` — new `auto_tag(subject_hash: &str, filename: &str, path: &str)` method - -### 3.5 Display Name from Tags - -**In Web UI:** Files with `name`, `file`, or `path` tags display the tag value as the human-readable name instead of the hash. - -**Deduplication rule:** In file listings, if multiple entries have the same hash AND the same set of tag values AND the same display name → show only once. - -**Implementation:** In `routes.rs` and web frontend, when rendering file lists: -1. Query tags for each hash -2. Use first found of `name` > `file` > `path` as display name -3. Group by (hash, display_name, tag_set) for dedup - -### 3.6 Migration Command - -**New command:** `id migrate-tags` - -**Behavior:** -1. Scan all iroh blob tags (the name→hash mappings) -2. For each, check if `name`/`file`/`path` metadata tags exist -3. If missing, create them from the blob tag name -4. Report: `Migrated N files, skipped M already-tagged files` - -**CLI definition:** New `MigrateTags` variant in the command enum. -**REPL:** `migrate-tags` command. - -### 3.7 Web UI Search - -**New endpoint:** `GET /api/tags/search?q=` - -**Frontend changes (web/):** -- Add search input box to file list / tags panel -- Real-time filtering as user types (debounced 300ms) -- Results show matching files with highlighted matching key/value -- Binary values shown as `[binary: N bytes]` - ---- - -## 4. File-by-File Change List - -### Rust (`src/`) - -| File | Changes | -|---|---| -| `tags.rs` | Add `TagValue` type; change `Tag` struct fields to `TagValue`; update encode/decode to use `bytes()`; add `SearchQuery` parser; add `auto_tag()` method; add `migrate_tags()` method; update all methods to accept `impl Into` | -| `tuple.rs` | No changes needed (already supports bytes) | -| `protocol.rs` | Change `MetaRequest`/`MetaResponse` tag fields from `String` to `Vec`; add `MigrateTags` request/response; add `SearchTags` with query string | -| `cli.rs` | Add `--hex`/`--binary` flags to tag commands; add `MigrateTags` command; update help text | -| `commands/tag.rs` | Adapt to `TagValue`; handle display truncation; handle `--hex` flag | -| `commands/put.rs` | Call `auto_tag()` after successful put (both file and stdin paths) | -| `commands/serve.rs` | Handle new `MigrateTags` protocol message | -| `repl/runner.rs` | Add `find` alias for search; add `migrate-tags` command; ensure all aliases match CLI | -| `commands/repl.rs` | Add `migrate_tags()` method to ReplContext | -| `web/tags_ws.rs` | Change API types to use base64 for bytes; add `/api/tags/search` endpoint | -| `web/routes.rs` | Use tag display names for file listings; add dedup logic | -| `web/mod.rs` | No structural changes expected | - -### TypeScript (`web/`) - -| Area | Changes | -|---|---| -| Tags WebSocket client | Handle base64-encoded byte fields | -| Search component | New search input with structured query syntax | -| File list rendering | Display name from tags; dedup identical entries | -| Binary display | Show `[binary: N bytes]` with copy-hex action | - -### Tests - -| File | Changes | -|---|---| -| `src/tags.rs` (unit) | Tests for `TagValue`, binary encode/decode, `SearchQuery` parser, auto-tag, migration | -| `tests/cli_integration.rs` | Tag binary round-trip, search syntax, migrate-tags, auto-tag on put | -| `web/` (vitest) | Search component tests, binary display tests | -| Playwright (if configured) | E2E tag search flow, file upload with auto-tags | - ---- - -## 5. Execution Steps - -### Phase 1: Core Binary Support -1. Create `TagValue` type in `tags.rs` with UTF-8 try-parse, display, serde -2. Update `Tag` struct to use `TagValue` for subject/key/value -3. Update `encode_alpha_key`/`encode_omega_key` to use `enc.bytes()` -4. Update `decode_alpha_key`/`decode_omega_key` with bytes fallback -5. Update all `tags.rs` methods to accept `TagValue` -6. Run `just check` — fix compile errors across dependent files - -### Phase 2: Protocol & Transport -7. Update `MetaRequest`/`MetaResponse` tag variants to `Vec` -8. Update `commands/tag.rs` to convert between CLI strings and `TagValue` -9. Update `commands/serve.rs` handler for new types -10. Run `just check` - -### Phase 3: CLI/REPL Parity -11. Add `find` alias to REPL search command in `runner.rs` -12. Add `migrate-tags` command to REPL -13. Verify all aliases match between CLI and REPL -14. Update all help text to be identical -15. Run `just check` - -### Phase 4: Search Syntax -16. Implement `SearchQuery` parser in `tags.rs` -17. Wire `search_tags()` to use `SearchQuery` -18. Update CLI `tag search` to pass raw query string -19. Update REPL `tag search` / `tag find` to use query syntax -20. Add unit tests for parser edge cases -21. Run `just check` - -### Phase 5: Auto-Tagging & Migration -22. Add `auto_tag()` to `tags.rs` -23. Call `auto_tag()` from `commands/put.rs` after successful store -24. Add `migrate_tags()` to `tags.rs` -25. Add `MigrateTags` to CLI enum and protocol -26. Add `migrate-tags` command to REPL (from step 12) -27. Run `just check` - -### Phase 6: Web UI & API -28. Update `tags_ws.rs` API types for base64 byte fields -29. Add `/api/tags/search` endpoint with query syntax -30. Update web frontend: search box, binary display, display names, dedup -31. Run `just check` - -### Phase 7: Display & UX Polish -32. Add `--hex`/`--binary` flags to CLI tag commands -33. Implement 256-char truncation in CLI/REPL display -34. Binary values: `` default, hex with flag -35. Web UI: `[binary: N bytes]` with copy-hex button -36. Run `just check` - -### Phase 8: Tests -37. Unit tests: `TagValue`, search parser, auto-tag, migration, binary encode/decode -38. Integration tests: tag binary round-trip, search syntax, migrate-tags, auto-tag on put -39. Web tests (vitest): search component, binary display -40. Playwright tests if applicable: E2E search, upload auto-tag -41. Run `just check` - -### Phase 9: Documentation & Final Verification -42. Update all Rust docstrings, comments, help text -43. Update all TypeScript docstrings and comments -44. Review and update: README.md, WEB.md, TODO.md, ARCHITECTURE.md, AGENTS.md, web/README.md -45. Run `just check` -46. Run `just kill-serve` (build + deploy) -47. Run `nix flake check -L` — fix any errors -48. Final `just check` confirmation - ---- - -## 6. Expected End Result - -- **Tag keys and values** accept arbitrary bytes, stored via tuple `bytes()` encoding -- **Display** tries UTF-8, falls back to ``, honors `--hex` flag -- **CLI and REPL** are exact mirrors: same commands, same aliases, same flags, same help text -- **Search syntax** works everywhere: `key:`, `:value`, `key:value`, `"literal"`, bare words -- **File uploads** auto-tag with `name`, `file`, `path` metadata -- **Display names** in UI use name/file/path tag values instead of raw hashes -- **Dedup** in listings: identical hash + tags + name collapsed -- **Migration** command backfills name/file/path for existing files -- **Web UI** has search box, binary value display, display names -- **All tests pass**: `just check`, `nix flake check -L` -- **All docs current**: docstrings, comments, help text, .md files - ---- - -## 7. Todo List - -- [ ] **P1** Create `TagValue` type in `tags.rs` with bytes, UTF-8 try, display, serde -- [ ] **P1** Update `Tag` struct and all `tags.rs` methods to use `TagValue` -- [ ] **P1** Update tuple encoding in `tags.rs` to use `enc.bytes()` instead of `enc.string()` -- [ ] **P1** Update `MetaRequest`/`MetaResponse` in `protocol.rs` from `String` to `Vec` -- [ ] **P1** Update `commands/tag.rs` and `commands/serve.rs` for new types -- [ ] **P2** Add `find` alias and `migrate-tags` command to REPL (`runner.rs`) -- [ ] **P2** Verify and fix all CLI/REPL alias and help text parity -- [ ] **P2** Implement `SearchQuery` parser in `tags.rs` (key:, :value, key:value, "quoted") -- [ ] **P2** Wire search syntax through CLI, REPL, and web API -- [ ] **P3** Add `auto_tag()` in `tags.rs` — creates name/file/path tags -- [ ] **P3** Call `auto_tag()` from `commands/put.rs` after successful store -- [ ] **P3** Add `migrate_tags()` and `MigrateTags` command to CLI/REPL/protocol -- [ ] **P3** Update web API types for base64 byte fields -- [ ] **P3** Add `/api/tags/search` endpoint with query syntax -- [ ] **P4** Update web frontend: search box, binary display, display names, dedup -- [ ] **P4** Add `--hex`/`--binary` CLI flags; implement 256-char truncation -- [ ] **P5** Write unit tests: TagValue, search parser, auto-tag, migration, binary encode/decode -- [ ] **P5** Write integration tests: binary round-trip, search syntax, migrate-tags, auto-tag on put -- [ ] **P5** Write web tests (vitest) and Playwright tests as needed -- [ ] **P6** Update all Rust docstrings, comments, help text -- [ ] **P6** Update all TypeScript docstrings and comments -- [ ] **P6** Review and update all .md files (README, WEB, TODO, ARCHITECTURE, AGENTS, web/README) -- [ ] **P6** Run `just check`, `just kill-serve`, `nix flake check -L` — fix all errors diff --git a/.opencode/backup/plans/2026-03-25-testing-ci-overhaul.md b/.opencode/backup/plans/2026-03-25-testing-ci-overhaul.md deleted file mode 100644 index a6da06dbab..0000000000 --- a/.opencode/backup/plans/2026-03-25-testing-ci-overhaul.md +++ /dev/null @@ -1,236 +0,0 @@ -# Testing & CI Overhaul Plan - -Date: 2026-03-25 - -## Overview - -Comprehensive overhaul of testing infrastructure, CI pipeline, and nix integration. Goals: -- Make all tests work (including E2E) -- Add `test-all` / `check-all` aggregate commands -- Run `serve_tests` + E2E inside nix sandbox via NixOS VM integration tests -- Add `check-nix` justfile command -- GitHub Actions CI workflow -- Multi-port server support - -## Current State - -- **Unit tests**: 484 pass (in sandbox via `test-sandbox` which skips `serve_tests`) -- **Integration tests**: 64 total, 53 run in sandbox (11 `serve_tests` skipped — need network for iroh endpoint) -- **Web unit tests**: 113 pass via `bun test` -- **E2E tests**: 15 Playwright tests exist but **untested** (never verified to actually pass) -- **`nix flake check`**: 11 checks pass (all skip `serve_tests`, no E2E) -- **No GitHub CI**: No `.github/workflows/` directory exists -- **No `test-all`**: No aggregate that runs unit + integration + web + e2e -- **No `check-nix`**: No just command for `nix flake check` -- **Multi-port**: `id serve --web 0` already supports random port assignment, but iroh itself binds port 0 for its internal protocol. Multiple servers can run with separate `--data-dir` (via `ID_STORE_PATH` or workdir isolation) - -## Tasks - -### Task 1: Ensure nix-common installs playwright - -**Problem**: `nix-common.nix` has `chromium` and `firefox` and sets `PLAYWRIGHT_*` env vars, but does NOT include `playwright` itself as a package. The e2e tests use `bunx playwright test` which downloads playwright at runtime — this fails in nix sandbox (no network). - -**Solution**: -- Add `playwright-driver` (or `playwright-driver.browsers`) from nixpkgs to `nix-common.nix` -- Set `PLAYWRIGHT_BROWSERS_PATH` env var to point to nix-provided browsers -- Alternatively, since we use `bunx playwright`, ensure `@playwright/test` is installed via bun and browsers are provided via nix env vars (current approach may work — need to verify) -- Key: ensure `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` and `PLAYWRIGHT_FIREFOX_EXECUTABLE_PATH` point to working binaries - -**Files**: `nix-common.nix` - -### Task 2: Fix and verify E2E tests pass - -**Problem**: E2E tests were written but never verified to actually pass. The playwright config starts `../target/debug/id serve --web --port 4173 --ephemeral` as the webServer. - -**Steps**: -1. Build web variant: `just build` -2. Run `just test-e2e` and fix any failures -3. Common issues to check: - - Server startup timing (60s timeout may not be enough on slow builds) - - Selector accuracy (elements may have changed since tests were written) - - Port conflicts (4173 might be in use) - - Playwright browser installation (bun install may need to pull playwright browsers) - -**Files**: `e2e/tests/basic.spec.ts`, `e2e/playwright.config.ts` - -### Task 3: Add `test-all` and `check-all` recipes - -**Problem**: No single command runs ALL tests including E2E. - -**Solution**: -- `test-all`: runs `test test-web-unit test-web-typecheck test-e2e` (all tests, including serve_tests and e2e) -- `check-all`: runs `fix ci test-e2e` (or `fix test-all ...`) -- Add corresponding flake apps (not checks — these need network) - -**Files**: `justfile`, `flake.nix` - -### Task 4: Fix nix flake check — ensure current checks pass - -**Problem**: Need to verify `nix flake check` still passes after all changes. May have regressions from build tooling changes. - -**Steps**: -1. `git add -A` (ensure all files tracked) -2. `nix flake check --no-build` (evaluation) -3. Build individual checks to find issues -4. Fix any failures - -**Files**: `flake.nix`, various - -### Task 5: Multi-port server support - -**Problem**: User wants to "enable running multiple servers on different ports if possible." - -**Current state**: `id serve --web 0` already supports random port assignment. Multiple servers can coexist if they use different data directories (each server creates its own iroh endpoint). The `--ephemeral` flag uses in-memory storage, allowing multiple ephemeral servers. - -**Solution**: -- Verify multiple servers can run concurrently with `--web 0 --ephemeral` (integration tests already test this: `test_serve_web_multiple_random_ports`) -- Add `--iroh-port` flag to control the iroh protocol port (currently always 0 = random) -- Document multi-server usage in README/ARCHITECTURE - -**Files**: `src/cli.rs`, `src/commands/serve.rs`, documentation - -### Task 6: NixOS VM integration tests for serve_tests + E2E - -**Problem**: `serve_tests` and E2E tests need network access, which the nix sandbox doesn't provide. Solution: NixOS VM-based integration tests using `pkgs.testers.runNixOSTest` (or `pkgs.nixosTest`). - -**Approach** (based on reference articles): -1. Create a NixOS module for `id` service (`nix/id-module.nix`): - ```nix - { config, pkgs, lib, ... }: - let cfg = config.services.id; in { - options.services.id = { - enable = lib.mkEnableOption "id file sharing service"; - port = lib.mkOption { type = lib.types.port; default = 3000; }; - ephemeral = lib.mkOption { type = lib.types.bool; default = true; }; - package = lib.mkPackageOption pkgs "id" {}; - }; - config = lib.mkIf cfg.enable { - systemd.services.id = { - wantedBy = [ "multi-user.target" ]; - serviceConfig.ExecStart = "${cfg.package}/bin/id serve --web ${toString cfg.port} --ephemeral --no-relay"; - }; - }; - } - ``` - -2. Create NixOS test for serve functionality (`nix/tests/serve-test.nix`): - ```nix - { name = "id-serve-test"; - nodes.server = { pkgs, ... }: { - imports = [ ../id-module.nix ]; - services.id = { enable = true; port = 3000; package = id-web-package; }; - }; - testScript = '' - start_all() - server.wait_for_unit("id.service") - server.wait_for_open_port(3000) - server.succeed("curl -f http://localhost:3000/") - # Test file creation via API - server.succeed("curl -f -X POST http://localhost:3000/api/new -H 'Content-Type: application/json' -d '{\"name\":\"test.txt\"}'") - server.succeed("curl -f http://localhost:3000/ | grep test.txt") - ''; - } - ``` - -3. Create NixOS test for E2E with chromium (`nix/tests/e2e-test.nix`): - ```nix - { name = "id-e2e-test"; - nodes.server = { pkgs, ... }: { - imports = [ ../id-module.nix ]; - services.id = { enable = true; port = 4173; }; - environment.systemPackages = [ pkgs.chromium pkgs.bun ]; - # Copy e2e test files - }; - testScript = '' - start_all() - server.wait_for_unit("id.service") - server.wait_for_open_port(4173) - # Run playwright tests inside VM - server.succeed("cd /e2e && PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=... bunx playwright test --project=chromium") - ''; - } - ``` - -4. Register in `flake.nix` as checks: - ```nix - checks.nixos-serve = pkgs.testers.runNixOSTest (import ./nix/tests/serve-test.nix { inherit id-web-package; }); - checks.nixos-e2e = pkgs.testers.runNixOSTest (import ./nix/tests/e2e-test.nix { ... }); - ``` - -**Key considerations**: -- NixOS VM tests have full network (loopback), so `serve_tests` equivalent works -- E2E in VM is heavier (needs chromium in VM) — consider chromium-only for CI -- VMs boot fast (~5s) with KVM support -- GitHub Actions supports KVM (nested virtualization) -- These are x86_64-linux only - -**Files**: `nix/id-module.nix`, `nix/tests/serve-test.nix`, `nix/tests/e2e-test.nix`, `flake.nix` - -### Task 7: `check-nix` just command - -**Problem**: No just command to run `nix flake check -L`. - -**Solution**: -- Add `check-nix` recipe: `nix flake check -L` -- Add as flake app (NOT as a check — would cause infinite recursion) -- This is the "full nix CI" command - -**Files**: `justfile`, `flake.nix` - -### Task 8: GitHub Actions CI workflow - -**Problem**: No CI exists. - -**Solution**: Create `.github/workflows/check.yml`: -```yaml -name: CI -on: - push: - branches: [main] - pull_request: - -jobs: - check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: DeterminateSystems/nix-installer-action@main - - uses: DeterminateSystems/magic-nix-cache-action@main - - run: nix -L flake check -``` - -Key points: -- Uses DeterminateSystems nix installer (fast, reliable) -- Magic Nix Cache for caching builds between runs -- KVM is available on GitHub Actions (needed for NixOS VM tests) -- Single `nix -L flake check` runs everything -- Only runs on push to main + PRs - -**Files**: `.github/workflows/check.yml` - -### Task 9: Final verification - -1. `just check-all` passes locally -2. `nix flake check -L` passes (all checks including NixOS VM tests) -3. All tests accounted for: unit, integration, web, e2e, NixOS VM -4. GitHub Actions workflow is syntactically valid - -## Execution Order - -1. Task 1 (playwright in nix) — prerequisite for e2e -2. Task 2 (fix e2e) — needs to work before we can add to CI -3. Task 5 (multi-port) — may affect serve tests -4. Task 3 (test-all/check-all) — aggregates -5. Task 4 (nix flake check) — verify current state -6. Task 6 (NixOS VM tests) — the big one, needs working e2e + serve -7. Task 7 (check-nix) — simple, add after VM tests -8. Task 8 (GitHub CI) — add last, after everything works -9. Task 9 (final verification) - -## References - -- [NixOS tests with flakes](https://blakesmith.me/2024/03/11/how-to-run-nixos-tests-flake-edition.html) -- [NixOS integration tests on GitHub](https://nixcademy.com/posts/nixos-integration-test-on-github/) -- [Example repo](https://github.com/tfc/nixos-integration-test-example) -- [NixOS testing framework](https://blog.thalheim.io/2023/01/08/how-to-use-nixos-testing-framework-with-flakes/) -- Key pattern: `pkgs.testers.runNixOSTest ./test.nix` in flake checks diff --git a/.opencode/backup/plans/htmx-to-datastar-migration.md b/.opencode/backup/plans/htmx-to-datastar-migration.md deleted file mode 100644 index b4c5927a4c..0000000000 --- a/.opencode/backup/plans/htmx-to-datastar-migration.md +++ /dev/null @@ -1,600 +0,0 @@ -# HTMX to Datastar + DaisyUI/Tailwind Migration Plan - -## Summary - -Migrate the `pkgs/id` web UI from **HTMX 1.9.10 to Datastar** for reactive interactions and from **custom terminal CSS (~1200 lines) to DaisyUI v5 + Tailwind CSS v4** for styling. WebSocket endpoints (`/ws/collab/{doc_id}` and `/ws/tags`) remain unchanged. The migration follows a 4-phase CSS-first approach ensuring the application stays functional at the end of every phase. - -**Key architectural shifts:** -- Server responses for Datastar-triggered requests become SSE (`text/event-stream`) with `datastar-merge-fragments` events, via a typed `DatastarResponse` builder in Rust -- Full-page loads remain normal HTML; only Datastar-initiated requests return SSE fragments -- Tailwind CSS v4 with DaisyUI v5 replaces all custom CSS, using CSS-first configuration -- Three CRT terminal themes (sneak/arch/mech) are recreated as custom DaisyUI themes with monospace fonts, zero border-radius, and glow effects -- Build pipeline switches from CSS concatenation to Tailwind CLI processing via Bun - ---- - -## Original Prompt - -> update the website to use datastar instead of htmx and use daisyui/tailwind for styling and other features. keep the websockets as-is we dont want to use sse for the current uses of websockets. design a plan with a summary, then this exact prompt as new section followed by subsections for each feedback/response appended as the plan is developed. then go into details for design/intent/architecture, and then low level implementation details. create a phased todo task list with checkboxes going into small steps that must be done. then load the tasks and begin once approved. - -### Brainstorm Feedback & Decisions - -#### Branch 1: Server Response Architecture -**Decision: Full SSE with Typed Builder Pattern** -- Every Datastar-triggered route returns SSE (`text/event-stream`) with `datastar-merge-fragments` events -- Create a `DatastarResponse` builder in Rust with methods: `.merge_fragment()`, `.merge_signals()`, `.remove_fragments()`, `.execute_script()` -- Initial page load (`GET /`) serves a full HTML shell; subsequent navigations are SSE fragment updates targeting `#main` -- The `HX-Request` header detection is removed entirely; replaced by distinguishing initial page load vs Datastar-triggered request (presence of `datastar` query param or accept header) -- WebSocket endpoints remain completely untouched - -#### Branch 2: Build Pipeline -**Decision: Tailwind CLI v4 via Bun** -- Install `@tailwindcss/cli` and `daisyui` as Bun dev dependencies -- Single Tailwind input file (`web/src/input.css`) replaces the old `build-css.ts` concatenation script -- Build command: `bunx @tailwindcss/cli -i src/input.css -o dist/styles.css --minify` -- Add `@source "../src/web/templates.rs"` directive so Tailwind scans Rust template strings for class names -- Existing `build-manifest.ts` continues handling content-hash filenames -- Bun orchestrates all build steps; unified dev/watch mode - -#### Branch 3: Theme Strategy -**Decision: CRT Terminal Aesthetic on DaisyUI** -- 3 custom themes extending DaisyUI dark base: - - **sneak**: primary = blue (`oklch(0.65 0.20 250)`) - - **arch**: primary = green (`oklch(0.75 0.25 145)`) - - **mech**: primary = orange (`oklch(0.70 0.20 55)`) -- All themes share: `base-100` = `#000000`, `base-200` = `#0a0a0a`, `base-300` = `#111111` -- Zero border-radius: `--rounded-btn: 0; --rounded-box: 0; --rounded-badge: 0` -- Global monospace font stack via Tailwind `fontFamily` extend -- CRT effects (text-shadow glow, scanline overlay, flicker animation) in custom `@layer components`, not in theme config -- Theme switching via `data-theme` attribute on `` element (compatible with both DaisyUI and Datastar signals) - -#### Branch 4: Migration Phasing -**Decision: CSS-First, 4-Phase Approach** -- Phase 1: Build pipeline + theme setup (HTMX stays working) -- Phase 2: CSS/component migration page-by-page (HTMX still working, visual layer migrated) -- Phase 3: HTMX to Datastar conversion (SSE builder, route-by-route) -- Phase 4: Cleanup & polish (remove HTMX, dead CSS, visual QA) -- Application remains fully functional at the end of every phase - ---- - -## Design / Intent / Architecture - -### Current Architecture - -``` -Browser Axum Server - | | - |-- GET / (full page) -------->|-- renders full HTML (render_page + render_main_page_wrapper) - |<--- HTML document -----------| - | | - |-- GET /file/x (HX-Request) ->|-- detects HX-Request header - |<--- HTML fragment -----------|-- returns partial HTML (just #main content) - | | - |-- WS /ws/collab/{id} ------->|-- binary MessagePack (ProseMirror collab) - |-- WS /ws/tags -------------->|-- JSON text (tag change notifications) -``` - -### Target Architecture - -``` -Browser (Datastar SDK) Axum Server - | | - |-- GET / (initial) ---------->|-- returns full HTML shell with data-signals, data-on-load - |<--- HTML document -----------| - | | - |-- @get('/files') ----------->|-- returns SSE: datastar-merge-fragments - |<--- text/event-stream -------|-- fragment targets #main via data-merge-mode - | | - |-- @get('/file/x') ---------->|-- returns SSE: merge-fragments + merge-signals - |<--- text/event-stream -------| - | | - |-- WS /ws/collab/{id} ------->|-- UNCHANGED: binary MessagePack - |-- WS /ws/tags -------------->|-- UNCHANGED: JSON text -``` - -### DatastarResponse Builder (Rust) - -```rust -pub struct DatastarResponse { - fragments: Vec, - signals: Option, - scripts: Vec, - removals: Vec, -} - -impl DatastarResponse { - pub fn new() -> Self { ... } - - /// Add an HTML fragment to merge into the DOM - pub fn merge_fragment(mut self, selector: &str, html: &str, mode: MergeMode) -> Self { ... } - - /// Update reactive signals (client-side state) - pub fn merge_signals(mut self, signals: serde_json::Value) -> Self { ... } - - /// Remove elements matching selector - pub fn remove_fragments(mut self, selector: &str) -> Self { ... } - - /// Execute JavaScript on the client - pub fn execute_script(mut self, script: &str) -> Self { ... } - - /// Convert to Axum SSE response - pub fn into_response(self) -> axum::response::Sse> { ... } -} - -pub enum MergeMode { - Morph, // default - intelligent DOM diffing - Inner, // replace innerHTML - Outer, // replace outerHTML - Prepend, - Append, - Before, - After, - DeleteElement, -} -``` - -### Template Refactoring - -**Before (templates.rs):** -```rust -pub fn render_file_list(files: &[FileInfo], search: &str, page: u32) -> String { - let mut html = String::with_capacity(8192); - write!(html, r#"
"#); - write!(html, r#""#); - // ... renders full page or partial based on context - html -} -``` - -**After (templates.rs):** -```rust -pub fn render_file_list(files: &[FileInfo], search: &str, page: u32) -> String { - let mut html = String::with_capacity(8192); - write!(html, r#"
"#); - write!(html, r#""#); - // ... same template logic, different attributes - html -} -``` - -### Route Handler Refactoring - -**Before (routes.rs):** -```rust -async fn file_list(headers: HeaderMap, query: Query) -> impl IntoResponse { - let is_htmx = headers.get("HX-Request").is_some(); - let html = if is_htmx { - templates::render_file_list_content(&files, &query.search, query.page) - } else { - templates::render_page(&templates::render_file_list(&files, &query.search, query.page)) - }; - Html(html) -} -``` - -**After (routes.rs):** -```rust -// Initial page load - returns full HTML -async fn index(state: State) -> impl IntoResponse { - let files = state.list_files(1, 50, "").await; - let html = templates::render_page(&templates::render_file_list(&files, "", 1)); - Html(html) -} - -// Datastar-triggered - returns SSE fragments -async fn file_list_fragment(query: Query) -> impl IntoResponse { - let files = state.list_files(query.page, 50, &query.search).await; - DatastarResponse::new() - .merge_fragment("#file-list-content", - &templates::render_file_list_content(&files, &query.search, query.page), - MergeMode::Morph) - .merge_signals(json!({ "page": query.page, "search": query.search })) - .into_response() -} -``` - -### CSS Architecture - -**Input file (`web/src/input.css`):** -```css -@import "tailwindcss"; -@plugin "daisyui"; -@source "../../src/web/templates.rs"; - -/* === Custom DaisyUI Themes === */ -@plugin "daisyui/theme" { - name: "sneak"; - default: true; - prefersdark: true; - color-scheme: dark; - --color-primary: oklch(0.65 0.20 250); - --color-secondary: oklch(0.50 0.15 250); - --color-accent: oklch(0.70 0.22 250); - --color-base-100: #000000; - --color-base-200: #0a0a0a; - --color-base-300: #111111; - --color-base-content: oklch(0.85 0.02 250); - --color-info: oklch(0.65 0.20 250); - --color-success: oklch(0.72 0.22 145); - --color-warning: oklch(0.75 0.18 85); - --color-error: oklch(0.65 0.25 25); - --rounded-btn: 0; - --rounded-box: 0; - --rounded-badge: 0; - --border: 1px; - --depth: 0; -} - -@plugin "daisyui/theme" { - name: "arch"; - prefersdark: true; - color-scheme: dark; - --color-primary: oklch(0.75 0.25 145); - /* ... similar structure, green primary ... */ -} - -@plugin "daisyui/theme" { - name: "mech"; - prefersdark: true; - color-scheme: dark; - --color-primary: oklch(0.70 0.20 55); - /* ... similar structure, orange primary ... */ -} - -/* === CRT Terminal Effects === */ -@layer components { - .crt-glow { - text-shadow: 0 0 5px currentColor, 0 0 10px currentColor; - } - - .crt-scanlines::after { - content: ""; - position: fixed; - inset: 0; - background: repeating-linear-gradient( - 0deg, - rgba(0, 0, 0, 0.15) 0px, - rgba(0, 0, 0, 0.15) 1px, - transparent 1px, - transparent 2px - ); - pointer-events: none; - z-index: 9999; - } - - @keyframes crt-flicker { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.98; } - } -} - -/* === ProseMirror Editor Styles (preserved) === */ -@import "./editor.css"; -``` - -### Theme Mapping - -| Current CSS Property | DaisyUI Equivalent | Notes | -|---|---|---| -| `--bg-primary` (#000) | `base-100` | Main background | -| `--bg-secondary` (#0a0a0a) | `base-200` | Card/section background | -| `--bg-tertiary` (#111) | `base-300` | Elevated surfaces | -| `--text-primary` (theme color) | `base-content` | Main text | -| `--text-muted` | `base-content/50` | Opacity modifier | -| `--accent` (per theme) | `primary` | Theme accent color | -| `--accent-hover` | `primary-focus` | Hover state | -| `--success/warning/error` | `success/warning/error` | Direct mapping | -| `--border` | `base-content/20` | Border color | -| `--glow-color` | Custom `crt-glow` class | Via text-shadow | - -### Component Mapping - -| Current Custom CSS | DaisyUI Component | Tailwind Utilities | -|---|---|---| -| `.card` | `card bg-base-200` | - | -| `.btn` | `btn btn-primary btn-outline` | `font-mono uppercase` | -| `.file-item` | `card bg-base-200 hover:bg-base-300` | `p-3 border border-base-content/20` | -| `.search-input` | `input input-bordered` | `w-full font-mono bg-base-100` | -| `.pagination` | `join` + `btn btn-sm` | `font-mono` | -| `.header` | `navbar bg-base-200` | `border-b border-base-content/20` | -| `.footer` | `footer bg-base-200` | `border-t border-base-content/20` | -| `.tag` | `badge badge-outline` | `font-mono text-xs` | -| `.dropdown` | `dropdown` + `menu` | - | -| `.theme-btn` | `btn btn-circle btn-sm` | Custom gradient still needed | -| `.toggle-checkbox` | `toggle toggle-primary` | `toggle-sm` | -| Modal/dialog | `modal` | `modal-box bg-base-200` | -| Tabs (if any) | `tabs tabs-bordered` | - | - -### Datastar Attribute Mapping - -| HTMX Pattern | Datastar Equivalent | -|---|---| -| `hx-get="/url"` | `data-on-click="@get('/url')"` | -| `hx-post="/url"` | `data-on-click="@post('/url')"` | -| `hx-target="#el"` | Server-side: fragment targets `#el` in SSE | -| `hx-swap="innerHTML"` | Server-side: `MergeMode::Inner` | -| `hx-swap="outerHTML"` | Server-side: `MergeMode::Outer` | -| `hx-push-url="true"` | `data-on-click="@get('/url', {push: true})"` or use `window.history.pushState` in execute_script | -| `hx-trigger="keyup changed delay:300ms"` | `data-on-keyup__debounce.300ms="@get('/url')"` | -| `hx-trigger="every 10s"` | `data-on-load__interval.10000ms="@get('/url')"` | -| `hx-trigger="change"` | `data-on-change="@get('/url')"` | -| `hx-include="[name='search']"` | Automatic via `data-signals` (signals sent with every request) | -| `hx-select="#content"` | Server returns only the needed fragment | -| `htmx.ajax("GET", url, opts)` | `@get(url)` from JS or Datastar action | -| `htmx:afterSwap` event | `data-on-load` on fragment, or `execute_script` in SSE | -| `htmx:beforeRequest` event | `data-on-click` handler before `@get` | -| `htmx.process(el)` | Not needed (Datastar auto-processes new fragments) | - -### URL History / SPA Navigation - -Datastar doesn't have built-in URL push like HTMX's `hx-push-url`. Options: -1. Use `execute_script` in SSE response to call `window.history.pushState()` -2. Client-side wrapper: `data-on-click="$$pushUrl('/path'); @get('/path')"` -3. Custom Datastar plugin for URL management - -Recommended: Option 1 - server controls URL updates via `execute_script` in the SSE response, keeping all routing logic server-side. - ---- - -## Low-Level Implementation Details - -### Phase 1: Build Pipeline + Theme Setup - -#### 1.1 Install Dependencies -```bash -cd pkgs/id/web -bun add -d @tailwindcss/cli daisyui@latest -bun add @starfederation/datastar # add now, use in Phase 3 -bun remove htmx.org # defer to Phase 4 -``` - -#### 1.2 Create Tailwind Input File -Create `web/src/input.css` with: -- `@import "tailwindcss"` -- `@plugin "daisyui"` -- `@source "../../src/web/templates.rs"` (scan Rust templates for classes) -- `@source "./main.ts"` (scan TypeScript for classes) -- Three `@plugin "daisyui/theme"` blocks (sneak, arch, mech) -- CRT effect classes in `@layer components` -- ProseMirror styles imported from `./editor-compat.css` (extracted from current editor.css, stripped of redundant resets) - -#### 1.3 Update Build Scripts -Replace `build-css.ts` with Tailwind CLI invocation: -```json -{ - "scripts": { - "build:css": "bunx @tailwindcss/cli -i src/input.css -o dist/styles.css --minify", - "build:js": "bun build src/main.ts --outdir dist --entry-naming [name].[hash].js", - "build:manifest": "bun run scripts/build-manifest.ts", - "build": "bun run build:js && bun run build:css && bun run build:manifest", - "dev": "bun run build --watch" - } -} -``` - -Note: `build-manifest.ts` needs a small update - the CSS output is now `styles.css` (no hash from Tailwind CLI). Options: -- Post-process: read `dist/styles.css`, compute hash, rename to `styles.{hash}.css`, write manifest -- Or: modify `build-manifest.ts` to handle the unhashed CSS file by computing hash itself - -#### 1.4 Verify HTMX Still Works -At this point HTMX is still loaded and all `hx-*` attributes are intact. The only change is styling. Run the app and verify all pages render correctly with new Tailwind/DaisyUI classes (they won't yet - this is just pipeline verification). - -### Phase 2: CSS/Component Migration - -#### 2.1 Template Class Replacement Strategy -Work page-by-page through `templates.rs`, replacing custom CSS classes with Tailwind/DaisyUI equivalents. The HTMX attributes (`hx-get`, `hx-target`, etc.) remain untouched. - -**Order of pages:** -1. Layout shell (header, footer, page wrapper) - affects all pages -2. File list page - most complex, search + pagination + file items -3. Editor page - ProseMirror container, toolbar -4. Media viewer - relatively simple -5. Binary viewer - relatively simple -6. Peers page - auto-refresh table -7. Settings page - theme switcher, toggles - -#### 2.2 Layout Shell Migration -```rust -// Before: -write!(html, r#"
"#); - -// After: -write!(html, r#"