Commit Graph

237 Commits

Author SHA1 Message Date
Levi Neuwirth 407ab75bdf
Merge pull request #53 from levineuwirth/task-25-stale-styling
Fix stale TUI styling after edits
2026-05-27 12:57:38 +00:00
Levi Neuwirth 9718958c4c Fix stale TUI styling after edits 2026-05-26 11:15:23 -04:00
Levi Neuwirth 7cf79aeec0
Merge pull request #43 from levineuwirth/worktree-pmacs-gpu-decorations
Session 5: Phase A — Decorations consumption (diagnostics as fg)
2026-05-25 17:50:05 +00:00
Levi Neuwirth 4e6f894d00 tests: tune M6 hosted perf profile 2026-05-25 13:43:28 -04:00
Levi Neuwirth 6fe69fd2b8 tests: widen backoff timing signal 2026-05-25 13:32:54 -04:00
Levi Neuwirth 3e36a6c57a tests: stabilize hosted perf gates 2026-05-25 13:20:18 -04:00
Levi Neuwirth 1ae2e7365e tests: quarantine macOS PTY marker cases 2026-05-25 13:02:46 -04:00
Levi Neuwirth f9f8dd0c54 process: signal PTY foreground group 2026-05-25 12:55:58 -04:00
Levi Neuwirth 40da07538a tests: harden macOS REPL PTY acceptance 2026-05-25 11:49:43 -04:00
Levi Neuwirth 304e54089f
M4.6 — diag.next / diag.previous commands bound to M-g n / M-g p (task #23) (#51)
Adds diagnostic navigation to the TUI/editor surface. Reuses the
existing `pmacs.diag.next` / `previous` walkers (which already wrap
around) and the cross-file jump ring so `M-,` returns from a
diagnostic jump just like an LSP definition jump.

Surface:
* `pmacs.command.define { name = "diag.next" / "diag.previous" }`
* `pmacs.keymap.bind { sequence = "M-g n" / "M-g p" }` — Emacs's
  `next-error` / `previous-error` chord.

The command walks the diag store for the active buffer's attached URI,
falls back to a status-line message ("no LSP server" / "no diagnostics
in buffer") rather than faulting when there's nothing to jump to. On a
hit it pushes the jump ring, moves the cursor via `pmacs.editor` motion
primitives (so every overlay observer sees the navigation), and sets a
status line of the form `diag (warning): ...`.

Test verifies the commands are registered, bindings exist, and the
no-server status path lands.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 21:54:54 +00:00
Levi Neuwirth c414954820
M4.6 — attach DiagnosticView to TUI windows (closes task #23) (#50)
The TUI's `DiagnosticView` has existed in `src/diag.rs` since v0.1 but
was never instantiated, so the local-grid renderer never painted
diagnostic underlines. This wires the view in the same way
`LspStyleView` and `SyntaxHighlightView` are wired — a Lua binding
that pushes the overlay onto the active window, driven from
`lsp.lua`'s `attach_buffer` flow with the standard per-buffer dedup
table.

* `DiagnosticView::kind()` returns `"diagnostic"` so
  `pmacs.window._overlay_kinds()` can verify attachment.
* `pmacs.diag._attach_view(buf, uri)` mirrors `pmacs.lsp._attach_style`
  exactly: requires active window's buffer matches `buf`, constructs
  `DiagnosticView::new(uri, store)`, pushes as overlay.
* `lsp.lua` calls `pmacs.diag._attach_view` from `attach_buffer` and
  tracks pushed buffers in `diag_viewed_buffers` to prevent
  double-attach on repeated `attach_buffer` calls.

Scope is intentionally narrow: view attachment only. Navigation
bindings, statusline summary, and gutter signs remain follow-ups
under task #23.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 21:10:36 +00:00
Levi Neuwirth 0902a9e173 Revert "session 5 fixup: clear styling on CrdtOp ..."
The clear-on-CrdtOp change broke the producer's incremental-update
contract. The producer ships dirty-range spans only on `full=false`
frames; the frontend is expected to retain non-dirty spans across
edits. Emptying both vectors meant the frontend ended up with only
the small dirty-range spans, missing the rest of the viewport — all
colors disappeared after an edit.

Reverting here. The proper fix lives in pmacs core (T M11.7):
producer must force `full=true` on generation transitions so the
frontend gets a complete replacement set on every text edit. Once
that lands, session-5's CrdtOp handler doesn't need to clear
anything — the next frame's `full=true` does it via
`replace_style_spans` / `replace_decorations`.

This reverts commit 49785c4. Returns the consumer behavior to
session-5's original "one-frame stale" artifact pending the core
fix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:32:47 -04:00
Levi Neuwirth abd6f46eee session 5 fixup: clear styling on CrdtOp to kill stale-position artifacts
Surfaced during session-5 manual validation (probe #3, the bet-#1
shape from the framing pass): editing at a diagnostic boundary
left stale color fragments visible against now-different text. The
session-4 PR documented this as a "one-frame stale" artifact, but
in practice the LSP re-analysis window stretches the wrong-color
period to 100ms–5s — human-perceptible and confusing.

Mechanism: CrdtOp updates `current_text` but `current_spans` /
`current_decorations` still index into pre-edit byte positions.
`reshape()` paints them at those stale positions against the new
text, producing colored fragments over wrong characters until the
producer ships an updated frame. Between CrdtOp arrival and
clangd's next publishDiagnostics (LSP debounce + re-analysis), no
Decorations frame ships at all (the producer's
`changed_intervals(prev, curr)` sees identical sets because clangd
hasn't republished yet).

Fix: drop both vectors in the CrdtOp arm before `set_text`. Tree-
sitter re-emits StyleSpans within ~one frame; LSP decorations
re-emit when clangd republishes. Cost = a brief uncolored window
per edit. Gain = no wrong-position color persists.

Manual revalidation (post-rebase on #44 + #45 + #46):
edit-at-boundary in the TUI now drops the old diagnostic color
cleanly. New diagnostic colors paint once clangd republishes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:32:47 -04:00
Levi Neuwirth 2076a3682d session 5: Phase A — Decorations consumption (diagnostics as fg)
Second Phase A session. pmacs-gpu now consumes
`InstanceMessage::Decorations` with the same M11.4 dirty-merge shape
as `StyleSpans`. Diagnostic kinds render as foreground color
overrides; background-needing kinds (selection, search match, current
line) accumulate in state but stay unpainted pending a quad pipeline.

What's wired

- `State.current_decorations: Vec<Decoration>`, sorted by
  `range.start`, cleared on `BufferSnapshot` like `current_spans`.
- `apply_attach_message` gains a `Decorations` arm — `full=true` →
  `replace_decorations`, `full=false` → `merge_decorations` (M11.4
  clip/drop/split, structurally identical to `merge_style_spans`).
- `reshape()` rewritten as a sorted-boundary sweep over both spans
  and decorations: every coverage edge becomes a chunk break.
  Effective fg color = first matching decoration with a renderable
  color, else span color, else default.
- `decoration_kind_to_color`: red error / yellow warning / blue info
  / dim hint; selection/search/current-line return `None`.

Session-5 findings (rule iii, both deferred)

- **M11.4 merge logic duplicated** between `StyleSpan` and
  `Decoration`. Structural-but-minor; defer until a third instance
  surfaces (peer-cursor decorations from `PresenceUpdate` are the
  likely third point) so the generic shape is inducted from three
  examples, not two.
- **Background-kind decorations need a wgpu quad pipeline**. glyphon
  0.11 / cosmic-text 0.18 `Attrs` is foreground-only. Structural —
  new render pass + composition story with text. Its own session,
  not absorbed into Phase A.

Adversarial-verification framing

Probe #5 (active diagnostics + multi-frontend `PresenceUpdate`
overlap) — the diagnostics half is exercised; PresenceUpdate is its
own family and isn't consumed yet. Probe #3 (viewport-boundary
edges) gets re-tested: `merge_decorations` is the same code shape as
`merge_style_spans`, so an edge-case finding there would replicate.

Gates

`cargo fmt`; `cargo clippy --all-targets --workspace -D warnings`
clean; lib 1303 + protocol 11 = 1314; m4 83; m11_5 (--features crdt)
2.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:32:47 -04:00
Levi Neuwirth 8db0485839
T M11.9 — handle_remote_crdt_op fires buffer.after-edit (closes session-5 root cause) (#49)
Surfaced when PR #48's diag-store stale-flag turned out to have no
observable effect on session-5 validation: the wrong-position-color
artifact persisted even though the stale-flag suppression chain was
in place.

## Root cause (the *actual* one)

The M10.10 optimistic-apply layer routes plain-char keystrokes
(EOL-eligible, no Ctrl-modifier, etc.) as `FrontendEvent::CrdtOp`
rather than `FrontendEvent::Key`. The daemon dispatches CrdtOps via
`handle_remote_crdt_op`, which applies the buffer edit and queues
the op for broadcast — but **does not fire `buffer.after-edit`**.

`buffer.after-edit` was only fired by `dispatch_key` (editor.rs:506)
after a Key-path edit. The CrdtOp path bypassed it entirely.

The downstream LSP hook in `builtin/runtime/lsp.lua:379` calls
`pmacs.lsp.did_change` on every `buffer.after-edit`. With CrdtOp
edits not firing the hook, `did_change_full` (and therefore
`textDocument/didChange`) was never sent to clangd for the bulk of
typing activity. clangd's view of the document silently froze at
whatever state the last Key-path edit (find-file, keystrokes
through the minibuffer, modifier-combinations) had left it in.

Downstream symptoms, all silent:

- **Diagnostics frozen at pre-edit byte positions** — the
  session-5 visible artifact.
- **LSP semantic tokens stale** (for grammar-less languages where
  semantic_render uses LSP not tree-sitter — i.e. C++).
- **Inlay hints stale**.
- **Hover/go-to-definition/rename can return wrong-position
  results** if a CrdtOp edit moved positions since the last Key
  edit.

PR #47 (full=true on generation transition) and PR #48 (diag-store
stale-flag) were correctness fixes on the producer side, but they
depended on `did_change` actually firing to trigger their effects.
With did_change silenced, both were dormant for any CrdtOp edit.

## Fix

In `handle_remote_crdt_op`, when `edit_opt` is `Some` (the import
produced a text delta), after notifying views:

1. Set `active_frontend = source` so the hook's
   `pmacs.window.buffer()` resolves to the right buffer (matches
   the pattern `dispatch_key` uses).
2. Fire `buffer.after-edit` via `editor.lua_host.run_hook(...)`.

This makes the Lua observer chain (LSP `did_change` and any future
consumers) see CrdtOp-path edits identically to Key-path edits.

## Regression test

`daemon::tests::handle_remote_crdt_op_fires_after_edit_hook`
(crdt-gated):

1. Upgrade the active buffer to CRDT-backed
2. Install a Lua `buffer.after-edit` hook that bumps a global
3. Build a peer LoroDoc from the buffer snapshot, edit on the peer,
   export the op
4. Call `handle_remote_crdt_op` with the op
5. Assert the global counter is `1`

Pre-fix, the counter stays at `0`.

## Gates

| Gate | Result |
|---|---|
| `cargo fmt --check` | clean |
| `clippy --features crdt --workspace -D warnings` | clean |
| `clippy --workspace -D warnings` (no crdt) | clean |
| `cargo test --features crdt --lib` | 1483 (+1) |
| `cargo test --lib` (no crdt) | 1319 (test crdt-gated) |
| `m4_acceptance --features crdt` | 83 |
| `m11_5_semantic_acceptance --features crdt` | 2 |

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 19:31:56 +00:00
Levi Neuwirth 886239480e
T M11.8 — diag-store stale-flag closes LSP-re-analysis-gap surface (#48)
Surfaced during session-5 manual validation as the final iteration
of bet #1 from the framing pass: edits that shift byte positions
left old diagnostic colors painted over post-edit text in both
`pmacs-gpu` and (now-visible) the TUI. Persisted for the full LSP
re-analysis window (100ms–5s).

PR #47 fixed the StyleSpans side via generation-tracked full=true
emission, but Decorations remained vulnerable: the producer's diff
shipped old diagnostics from the diag store, whose entries were
indexed at pre-edit byte positions until clangd republished.

Fix: a per-URI `stale_uris` flag in `DiagnosticStore`. The LSP
layer's `did_change_full` marks the URI stale right after sending
the notification; the next `publishDiagnostics` absorb path's
`set` clears it. The `semantic_render` producer reads `is_stale`
and skips diagnostic emission entirely while stale.

Effect: between an edit and clangd's next publish, the producer
ships zero diagnostic decorations. Frontend's replace/merge clears
old positions cleanly. Brief uncolored window (≤ LSP re-analysis
latency) replaces the previous wrong-position-color persistence.
The correct visual tradeoff: honest emptiness over deceptive
staleness.

Files changed:

- `src/diag.rs` — `DiagnosticStore` gains `stale_uris: HashSet<String>`;
  new `mark_stale` / `is_stale` API; `set` and `clear` reset the
  flag on the assumption that absorption / explicit removal mean
  the LSP has caught up.
- `src/lsp.rs` — `LspManager::did_change_full` calls
  `diag_store.lock().mark_stale(uri)` after `send_notification`.
- `src/semantic_render.rs` — `scoped_decorations` reads `is_stale`
  alongside `for_uri`; when stale, suppresses the diagnostic
  loop (selection and other non-diagnostic kinds still emit).

Tests (all crdt-gated where they reference semantic_render):

- `diag::tests::stale_flag_default_false`
- `diag::tests::mark_stale_sets_flag` (per-URI scoping)
- `diag::tests::set_clears_stale_flag`
- `diag::tests::empty_set_clears_stale_flag_too`
- `diag::tests::clear_drops_stale_flag`
- `semantic_render::tests::diagnostics_suppressed_while_diag_store_stale`
  — assert no diagnostic kinds emit while stale; assert they
  re-emit after a fresh `set` clears the flag.

Gates: cargo fmt + clippy (workspace, with/without `crdt`) clean;
lib 1482 (+6) with crdt; 1319 (+6) without; m4 83; m11_5 2.

This is approach (A) from the session-5 ask: track per-URI freshness
relative to buffer edits, suppress emission until LSP catches up.
Approach (B) — clangd's didChange/publishDiagnostics version
matching — would be more precise but requires plumbing version
tracking through the LspManager's document state, which is a
larger change deferred. The stale-flag captures the same semantic
("any edit since last publish ⇒ stale") at a cheaper cost.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 19:01:10 +00:00
Levi Neuwirth 36a53f8d5a
T M11.7 — producer forces full=true on generation transition (#47)
Surfaced during session-5 manual validation (probe #3, the bet-#1
shape from the framing pass): editing at a diagnostic boundary in
the TUI left stale color fragments visible in pmacs-gpu against
shifted text.

Root cause: SemanticRenderState ships `full=true` styling only on
viewport-region changes, not on text-edit transitions. When the
buffer's CRDT generation advances (an edit) but the viewport stays
the same, the producer ships an incremental — but the frontend's
cached spans + decorations are indexed at *pre-edit* byte
positions. The incremental only ships dirty-range items, expecting
the frontend to retain everything else; combined with shifted
positions, the result is wrong-position color persisting until
the next viewport change.

Fix: track `generation` per buffer in `LastFrame`. Force `full=true`
when generation differs from the last-shipped value, so the
frontend's next `replace_*` operation rebuilds the cache wholesale
at the new positions.

Tradeoff: one extra full-viewport ship per edit. Negligible over
the local Unix socket; bounded by viewport size; and exactly what
the contract requires after position shifts.

Affects both diff-shaped families:

- `StyleSpans` — tree-sitter / LSP semantic tokens
- `Decorations` — diagnostics + selection

`InlineAdornments` uses whole-set replacement (M11.2-level
suppression), not dirty-segment diff, so doesn't have the same
issue. Tracking `generation` in its `LastFrame` for struct
uniformity; predicate unchanged.

Regression test: `full_resync_on_generation_transition` upgrades a
buffer to CRDT-backed, lands an initial full frame, edits the
buffer to bump `version_scalar`, asserts the next StyleSpans +
Decorations both ship `full=true`.

Gates: cargo fmt + clippy (workspace, with/without `crdt`) clean;
lib 1476 (+1) with crdt; 1313 unchanged without (new test is
crdt-gated); m4 83; m11_5 2.

This closes the bet-#1 surface for the consumer side. A separate
follow-up to session-5 PR #43 will document the resolution.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 15:43:16 +00:00
Levi Neuwirth 875669a49c
semantic_render: resolve URI from vp.buffer_id, not active_buffer (#46)
Surfaced during session-5 manual validation: pmacs-gpu opened a file
that had 8 LSP diagnostics in the shared store (verified via the
debug.diag-status command on the TUI side), yet pmacs-gpu's
`Decorations` message arrived empty.

Root cause: three sites in `semantic_render.rs` resolved the lookup
URI from `core.active_buffer_path()` — the *editor's* active buffer.
In a multi-frontend setup (TUI + pmacs-gpu attached at once), the
daemon's per-tick render loop temporarily flips `active_frontend`
to each fid before that frontend's frame. Each frontend has its own
`FrontendView` with its own active window; pmacs-gpu's was
registered against a fresh scratch buffer at attach time (the v0.1
default in `handle_session_established`). So when the producer
ran for pmacs-gpu, `active_buffer_path()` returned `None` — the
scratch has no file path — and the diag / inlay / LSP-semantic-token
lookups all came back empty.

Fix: route the URI through `vp.buffer_id` via a new
`buffer_file_uri(core, buffer_id)` helper. Single-frontend case is
unchanged (the active buffer equals the projected buffer); multi-
frontend now finds the right URI.

Three sites updated:

- `scoped_decorations` (line 366) — diagnostics
- `inline_adornments_msg` (line 425) — inlay hints
- `lsp_scoped_style_spans` (line 701) — LSP semantic tokens for
  grammar-less languages

Regression test: `decorations_use_vp_buffer_not_active_buffer`
constructs the multi-frontend shape (LOCAL's active is scratch; a
second buffer with a file path holds a seeded diagnostic; the
viewport projects the second buffer) and asserts the decoration
surfaces.

Separately surfaced (not fixed here, documented in task #23):
`DiagnosticView` is defined in `diag.rs` but never attached to any
buffer. The TUI grid path has no diagnostic underline rendering as
a result — an unrelated M4.6 incompleteness from v0.1's initial
commit. Tracked as its own thread; will need a framing pass for
scope (view attach? navigation bindings? statusline summary?
gutter signs?).

Gates: cargo fmt + clippy (workspace, with/without `crdt`) clean;
lib 1475 (+1) with crdt; 1313 (+1) without; m4 83; m11_5 2.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:56:26 +00:00
Levi Neuwirth 7ec314ad78
T M11.6 — DispatchIdle signal closes optimistic-apply blindness (#45)
The attach-mode optimistic-apply layer (M10.10) classifies any
plain-char keystroke as `Insert(c)` and applies it directly to the
local CRDT mirror, bypassing the daemon's keymap dispatcher. The
documented limitation ("the optimistic layer doesn't track keymap-
prefix state") also covered the minibuffer-active case, which
surfaced during session-5 manual validation: characters typed into a
`C-x C-f` prompt were optimistically inserted into the previously-
active document instead of routed to the minibuffer.

The fix is a daemon→frontend wire signal indicating whether the
daemon's *next* key event would be intercepted (minibuffer or pending
prefix) vs would self-insert. The frontend gates the optimistic-apply
path on this; when not idle, every keystroke round-trips as
`FrontendEvent::Key`.

Protocol changes (pmacs-protocol):

- `PROTOCOL_VERSION` 3 → 4; `SUPPORTED_PROTOCOL_VERSIONS` adds 4.
- New `InstanceMessage::DispatchIdle { idle: bool }`.

Daemon (`src/editor.rs`, `src/daemon.rs`):

- `EditorState::dispatch_idle()` — true iff `dispatcher.pending`
  empty AND `minibuffer.is_active() == false`.
- Per-tick emission: `last_dispatch_idle_sent: HashMap<FrontendId,
  bool>` tracks the last-broadcast value per session; emission fires
  on first frame after attach (absent entry) and on transitions.
- Gated on `crdt_replica` AND `negotiated_protocol_version >= 4` so
  older peers don't hard-error on the unknown variant. Same gating
  shape as the M10.5 CrdtOp and M11.1 SemanticFrame bumps.

Frontend (`src/attach.rs`):

- New `dispatch_idle: bool` (cfg `crdt`); default `false`
  (pessimistic — optimistic apply only activates after the daemon
  explicitly says idle).
- DispatchIdle messages consumed in the drain loop; they don't
  participate in `present_messages` batches.
- Optimistic-apply branch gated on `dispatch_idle`. When false, the
  branch returns false (forces fallthrough to the round-trip
  `forward_event` path).

Tests:

- `editor::tests::dispatch_idle_*` — fresh, prefix-pending, prefix-
  resolved, minibuffer-open/cancelled.
- `protocol::tests::dispatch_idle_round_trips_through_postcard` —
  wire encoding both polarities.
- `protocol::tests::protocol_version_is_four_for_dispatch_idle` +
  `supported_protocol_versions_includes_one_through_four` — pin the
  new version constants.

Gates: cargo fmt + clippy (workspace, with/without `crdt`) clean;
lib 1474 (+5 from 1469 baseline) with crdt; 1312 (+4) without;
m4 83; m11_5 (--features crdt) 2.

Acknowledged remaining gap: plain-char Lua bindings (e.g. binding
`q` to a command) still surface optimistic-apply divergence —
optimistic doesn't know "is this char bound to a non-self-insert
command in the current keymap." Rare in practice; revisit if anyone
hits it. Documented at session-5 finding time.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 13:49:48 +00:00
Levi Neuwirth ce2f997b84
minibuffer: Escape cancels session (#44)
Add `KeyCode::Esc => MinibufferAction::Cancel` to
`MinibufferAction::from_chord`'s no-modifier branch. Matches Emacs
convention; surfaced during session 5 manual validation of the
session-4/5 pmacs-gpu work — there was no way to abandon a `C-x C-f`
prompt without typing `C-g`, which is awkward for muscle-memory users.

Adds four unit tests covering the chord dispatcher (Escape→Cancel,
C-g→Cancel, Enter→Accept, char→SelfInsert); none existed before, so
this also seeds the test set for the dispatch table.

C-g remains a Cancel binding — Escape is added in parallel, not
substituted. Both work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 01:35:02 +00:00
Levi Neuwirth 32b529eea5
session 4: Phase A — StyleSpans consumption + rich-text rendering (#42)
First Phase A session. pmacs-gpu now sends FrontendEvent::Viewport
back to the daemon after BufferSnapshot lands, receives the resulting
InstanceMessage::StyleSpans frames, and renders the rope with
per-span colors via cosmic-text's set_rich_text.

What's wired:
- AttachClient gains a write-side Arc<Mutex<UnixStream>> and the
  assigned FrontendId from Hello; new send_viewport method emits
  FrontendEvent::Viewport. The mutex is over-cautious for our
  single-threaded event loop but future-proofs against multi-window
  emission.
- State adds current_buffer_id and current_spans (sorted by
  range.start). BufferSnapshot bootstraps both, then the App's
  user_event handler emits a follow-up Viewport via
  AttachClient::send_viewport.
- StyleSpans handling distinguishes full vs incremental:
  * full=true: replace_style_spans drops prior, takes segments as
    authoritative for the declared viewport.
  * full=false: merge_style_spans applies the M11.4 dirty-segment
    rule — spans fully inside a dirty range drop; spans straddling
    a dirty edge get clipped to outside the range (with the
    straddles-both-edges case splitting into two); new spans append;
    re-sort by start.
- reshape() walks current_text + current_spans, emits (substr,
  Attrs) chunks at every span boundary (with .min(text_len) clamps
  for safety against stale spans past EOF), calls set_rich_text.
- cell_color_to_glyphon converts cell::Color to glyphon::Color via
  the standard xterm-style 256-color palette (16 ANSI + 6x6x6 cube +
  24-step grayscale). Default → None so the renderer's default
  Attrs color stays.

Adversarial verification scope (Phase A probes):
- #1 non-ASCII source: exercised through the UTF-16 col/byte
  conversion already in pmacs's producer side; pmacs-gpu just renders
  what the wire delivers. Non-ASCII files should show correct
  styling at the right byte positions.
- #3 viewport-boundary tokens: the merge_style_spans path is exactly
  bet #1 from the framing pass ('StyleSpans/Decorations dirty-segment
  edges at viewport boundaries — headless-test-blind-spot probe').
  Edits near a span edge exercise the clip-and-merge logic.
- #6 CRLF line endings: implicit — pmacs's rope uses byte offsets so
  styling spans naturally include or exclude the \r as the producer
  decided. pmacs-gpu doesn't special-case line endings.

Known limitation (session 4 acceptable artifact, documented in
set_text): CrdtOp + StyleSpans arrive separately. CrdtOp updates text;
StyleSpans for the new generation comes one tick later. Between the
two, current_spans points at pre-edit byte positions while the text
is post-edit — visually stale for one frame. The .min(text_len) clamp
in reshape() keeps it safe; the artifact is brief.

Headless test gap: there's no Rust-level test of merge_style_spans
or the rich-text segmentation. Phase A's framing intentionally
chose manual validation over headless tests for these paths (the
adversarial probes are visual). A Phase A audit doc lands at session
close with the predicted-vs-actual scoring; per-method unit tests
for the merge logic could land then if findings argue for them.

Gates: fmt; clippy --all-targets -D warnings clean across the whole
workspace; lib 1303 + pmacs-protocol 11 = 1314; m4_acceptance 83;
m11_5_semantic_acceptance --features crdt 2.

Manual validation pending — same daemon+TUI+pmacs-gpu setup as
session 3, now showing colored text in the GPU window.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:28:53 +00:00
Levi Neuwirth f59c022d64
Merge pull request #41 from levineuwirth/worktree-pmacs-gpu-attach-loop
Session 3: pmacs-gpu attach loop + rope reconstruction
2026-05-20 17:12:21 +00:00
Levi Neuwirth 1506975ddb session 3 commit 3/3: doc the daemon's --features crdt requirement
Surfaced during manual validation: the pmacs-gpu window sits on
'(connecting...)' forever when attaching to a daemon built without
--features crdt. Handshake succeeds (negotiation reports semantic_render
+ crdt_replica as agreed by both sides), but the daemon's
crdt_replica default is cfg!(feature='crdt')=false in that build, so
send_buffer_snapshots() never fires and pmacs-gpu has nothing to
render.

Classified small under rule (iii). The structural answer (should the
daemon return a clearer signal when crdt_replica was negotiated but
isn't actually compiled in?) is genuine but deferred; for session 3
the failure mode is now documented inline at the build-AttachRequest
site so the next user to hit it recognizes the symptom.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:12:13 -04:00
Levi Neuwirth 62cee9118c session 3 commit 2/2: attach mode + loro rope reconstruction
pmacs-gpu now has two run modes:
- no args: hello-world (session-2 behavior preserved)
- --attach <socket>: connect to a pmacs daemon, negotiate
  semantic_render + crdt_replica, import BufferSnapshot into a local
  loro replica, render the rope text. Live CrdtOp updates apply as
  they arrive.

Architecture:
- pmacs-gpu/src/attach.rs (new): UnixStream connect + Hello /
  AttachRequest handshake on the main thread; spawns a reader thread
  that pumps decoded InstanceMessage frames through the winit
  EventLoopProxy as AppEvent::Attach(AttachEvent::Message). Clean EOF
  or transport errors surface as AttachEvent::Disconnected. Reader
  thread holds the read half of the stream; AttachClient retains the
  write half (unused yet — session 4 wires FrontendEvents back).
- pmacs-gpu/src/main.rs: ApplicationHandler<AppEvent> with a
  user_event handler that dispatches Message variants. BufferSnapshot
  builds a fresh LoroDoc, imports the snapshot bytes, extracts text
  via doc.get_text('body').to_string(), and re-shapes the glyphon
  buffer. CrdtOp passes the op bytes through doc.import (loro
  accepts both shapes), re-extracts text, re-shapes. Other
  InstanceMessage variants are intentionally ignored at session 3.
- Font size dropped from 48pt to 16pt now that we may render full
  files (the hello-world 48pt was fine for one line, awful for code).
- Initial text is '(connecting...)' in attach mode, 'hello, pmacs' in
  hello-world; attach failure falls back to '(attach failed; see
  stderr)' so the window still opens.

One small finding logged in attach.rs's connect() doc: AttachRequest's
initial_size field is a CellSize (rows × cols), nominally
TUI-shaped. Sent as a placeholder (24×80) — a structural answer
('what does initial size mean for a pixel frontend?') belongs in its
own protocol thread, not session 3. Classified under rule (iii) as
deferred.

Container id for the loro text container ('body') hardcoded to match
pmacs::crdt::CrdtState — second finding worth pre-recording: the
container name is a wire-adjacent convention that isn't carried on
the wire itself. Both ends have to agree out-of-band. Not blocking
for session 3 but a structural smell for the producer arc. Logged
as deferred (rule iii structural; the answer is probably 'thread the
container id through BufferSnapshot' but it's not session-3 scope).

Gates: cargo fmt, cargo clippy --all-targets -D warnings (whole
workspace) clean; lib 1303 + pmacs-protocol 11 = 1314 unchanged;
m4_acceptance 83; m11_5_semantic_acceptance --features crdt 2.

Manual validation pending — agent environment is headless. User
walks through: start a pmacs daemon, run pmacs-gpu --attach <socket>,
confirm the window renders the daemon's file contents.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 12:23:04 -04:00
Levi Neuwirth dd9d36926d session 3 commit 1/N: move transport codec to pmacs-protocol
Surfaced as session 3's first finding: pmacs-gpu can't attach to a
daemon without the length-prefix postcard codec
(read_message / write_message / TransportError / MAX_FRAME_BYTES),
but session 1 left those in the main pmacs crate. The wire-types
crate's boundary as drawn in session 1 didn't include the framing
codec — a real frontend needs both.

Classified as small under rule (iii) and absorbed in session 3.
Structural lesson recorded: transport is part of the wire contract,
not internal to the daemon.

src/transport.rs is now a re-export shim ('pub use
pmacs_protocol::transport::*;') so existing internal callers
(crate::transport::* in attach.rs, daemon.rs, attach_reconnect.rs)
keep working. Net test count unchanged: 11 transport tests now run
under 'cargo test -p pmacs-protocol' instead of 'cargo test --lib',
total 1314 across both crates.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 12:07:32 -04:00
Levi Neuwirth 6a9aa57f69
Merge pull request #40 from levineuwirth/worktree-pmacs-gpu-hello-world
Session 2: pmacs-gpu workspace + wgpu/winit/glyphon hello-world
2026-05-20 15:48:42 +00:00
Levi Neuwirth a706864e04 session 2: pmacs-gpu workspace + wgpu/winit/glyphon hello-world
Adds the pmacs-gpu binary crate to the workspace. wgpu 29.0 + winit
0.30 + glyphon 0.11 (cosmic-text 0.18 via re-export) + pollster +
env_logger; pmacs-protocol in the dep graph but not consumed yet
(session 3 wires the attach loop).

The binary opens an 800x200 window titled 'pmacs-gpu hello-world',
sets up wgpu against its surface, configures glyphon with the bundled
JetBrains Mono Regular, and renders 'hello, pmacs' once per redraw.
Close button or Escape exits. Resize re-configures the surface and
glyphon viewport. Surface acquisition matches wgpu 29's
CurrentSurfaceTexture enum (success/suboptimal render through; lost/
outdated re-configure; timeout/occluded skip the frame).

Bundled assets: pmacs-gpu/fonts/JetBrainsMono-Regular.ttf (268 KB)
and pmacs-gpu/fonts/OFL.txt. Font shipped as required by the SIL
Open Font License 1.1.

One finding surfaced during the move and absorbed under rule (iii)
of the framing pass (small / no structural change): the design doc
recorded JetBrains Mono as Apache 2.0; the actual license has been
OFL since the family's open-source release. Doc corrected in
docs/pmacs-gpu-design.md.

Gates: cargo fmt + cargo clippy --all-targets -D warnings clean for
the whole workspace; cargo test --lib still 1314 (pmacs main crate
untouched); m4_acceptance 83; m11_5_semantic_acceptance --features
crdt 2.

Visual confirmation pending — agent environment is headless, so
'window opens, text renders' is user-side validation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:37:26 -04:00
Levi Neuwirth dab2a48bb0
Merge pull request #39 from levineuwirth/worktree-protocol-crate-extraction
Session 1: pmacs-protocol crate extraction
2026-05-20 14:00:41 +00:00
Levi Neuwirth a820e91389 session 1 commit 4/4: message envelopes moved to pmacs-protocol
The big move that completes session 1. Wire types moved from
src/protocol.rs to pmacs-protocol/src/message.rs:

- Input event family: Key, Modifiers, KeyEvent, MouseButton, MouseKind,
  MouseEvent, FrontendEvent (and its variants — Resize, KeyEvent,
  MouseEvent, Resume, Pause, Detach, ResizeAck, CrdtOp, Viewport).
- Instance-side message family: CursorState, InstanceSignal,
  GoodbyeReason, InstanceMessage (Hello/Cursor/CellDelta/CursorByte/
  CrdtOp/BufferSnapshot/Goodbye/PresenceUpdate + the SemanticFrame
  variants).
- SelectionSnapshot.
- SemanticFrame family components: StyleSpan, StyleSegment,
  DecorationKind, Decoration, DecorationSegment, AdornmentPlacement,
  AdornmentContent, InlineAdornment, BlockAdornment, ResourceBody.
- Handshake: PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS,
  is_supported_protocol_version, InstanceIdentity, InstanceCapabilities,
  FrontendCapabilities, NegotiatedCapabilities, negotiate_capabilities,
  Hello, AttachRequest.

What stays in src/protocol.rs:
- AttachTarget / AttachError / AttachTargetParseError /
  AttachTargetValidationError / AttachTargetError / AttachmentHandle
  (CLI / binding internals, not wire).
- crossterm_translate submodule (the crossterm ↔ pmacs-protocol-types
  translation layer; sits at the binding boundary, not on the wire).
- Existing tests (wire-format roundtrip + AttachTarget + crossterm
  translation), unchanged — they reach the moved types through the
  'pub use pmacs_protocol::*' re-export.

Mechanical rewrites inside the moved chunk: crate::buffer::BufferId →
crate::BufferId, crate::rope::Position → crate::Position,
crate::rope::CrdtOp → crate::CrdtOp (the message module is inside
pmacs-protocol; identity types live at the crate root).

Feature re-added on pmacs-protocol: 'crdt' (was removed in commit 3
as I'd thought CrdtOp was the only feature-gated thing — but
InstanceCapabilities::default and FrontendCapabilities::default both
call cfg!(feature = 'crdt') for their multi_frontend / crdt_replica /
semantic_render defaults). Re-added with a doc comment explaining why.
The parent pmacs crate's 'crdt' feature now activates
'pmacs-protocol/crdt' so the cfg!() check evaluates consistently in
both crates.

Full gate green: fmt, clippy --all-targets -D warnings, lib 1314,
m4_acceptance 83, m8_1/m8_9/m8_10 10/26/19, m9_1 18, m5_8 5,
m11_5_semantic_acceptance --features crdt 2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:55:27 -04:00
Levi Neuwirth 5ffc47aa33 session 1 commit 3/4: CrdtOp moved to pmacs-protocol
CrdtOp { peer_id: u64, bytes: Vec<u8> } moves from src/rope.rs to
pmacs-protocol::crdt. The type is unconditional (not #[cfg]-gated),
matching the original's 'always present to avoid feature-flag
proliferation through every Edit consumer' decision: the parent
pmacs crate's 'crdt' feature gates loro and op application, not
wire shape.

Removed the unused 'crdt' feature stub I'd added to
pmacs-protocol/Cargo.toml at session start; nothing in pmacs-protocol
needs it.

src/rope.rs adds 'pub use pmacs_protocol::CrdtOp;' so existing
crate::rope::CrdtOp imports keep resolving.

Lib gate: still 1314 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:32:09 -04:00
Levi Neuwirth 2c04102aad session 1 commit 2/4: cell wire types moved to pmacs-protocol
Moves Cell, Glyph, Style, Color, UnderlineStyle, CellCoord, CellSize,
DiffSpan, Attachment to pmacs-protocol::cell. CellGrid (borrowed-slice
render surface) and fn diff() (rendering helper) stay in src/cell.rs
since they're instance-side rendering machinery, not wire shapes.

src/cell.rs gains 'pub use pmacs_protocol::{Cell, Glyph, Style, ...};'
at the top so every existing internal import (crate::cell::Cell, etc.)
keeps resolving. The cell-module tests live alongside CellGrid + diff
and reference the re-exported types via 'use super::*' — same as
before; no test changes needed.

Lib gate: still green (no regressions, 1314 passing).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:20:24 -04:00
Levi Neuwirth 14341d958e session 1 commit 1/4: workspace + identity types moved to pmacs-protocol
Workspace skeleton: root Cargo.toml becomes a workspace with members
[".", "pmacs-protocol"]; [workspace.dependencies] pins serde,
postcard, thiserror so both crates use byte-identical versions (the
wire format depends on it). pmacs main package keeps its existing
shape (no file moves); it just gains pmacs-protocol as a path
dependency.

Identity types moved: BufferId (from buffer.rs), FrontendId + ByteRange
(from protocol.rs), Position type alias (from rope.rs). All four are
self-contained — no custom-type dependencies — so the first stage of
the move can land atomically without dragging cell/message types along.

src/buffer.rs / src/protocol.rs / src/rope.rs each gain a 'pub use
pmacs_protocol::...' re-export for the moved names, so existing
internal imports (crate::buffer::BufferId, crate::rope::Position, etc.)
continue to resolve unchanged. New consumers (pmacs-gpu, debug tools)
will depend on pmacs-protocol directly.

One visibility change: BufferId::from_raw was pub(crate); promoted to
pub with a doc note that it's not stable API for external consumers.
The (crate) restriction was advisory only — external deserialization
already worked via the derived Deserialize, so making it pub doesn't
widen the actual surface, just makes it honest.

Lib gate: 1314 passed, no regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:11:33 -04:00
Levi Neuwirth f7cea2ec3a
Merge pull request #38 from levineuwirth/worktree-gpu-design-framing
docs: pmacs-gpu design note (framing pass closed)
2026-05-20 12:51:40 +00:00
Levi Neuwirth 1dc36f7cd4 docs: pmacs-gpu design note (framing pass closed)
Post-v1.0 design artifact for the GPU/GUI frontend. Inherits the
contract boundary from semantic-frontend-protocol.md and applies the
M10-matured framing discipline to a multi-month effort:

- Toolkit: wgpu + custom + cosmic-text + glyphon. Unambiguous.
  Records the against-gpui case so the decision isn't relitigated.
- Scope: A (read-only viewer, ~2-3 weeks, adversarial verification of
  the producer arc) → B (TUI parity, 2-3 months after A) → C
  (beyond-TUI, 3-4 months after B). Sequential, not alternative.
  ~6 months to parity, ~9-10 to beyond-TUI; recorded honestly at
  decision time.
- Phase A's framing is adversarial verification, not "build a viewer
  that works." Six static probes + one temporal probe drive the
  corpus; the viewer is the artifact of having done so.
- Predicted findings: five categorical bets, scored as a category
  matrix not a count, methodology recorded before data lands.
- Finding feedback loop: classification rule (iii) pre-authorized —
  small absorbs into Phase A, structural deferred per the
  verification-milestone premise-check.
- Distribution: workspace + separate pmacs-gpu binary. pmacs-protocol
  crate extraction as a discrete 4-hour prerequisite PR before any
  GPU work.
- Q#1 (visual motion) committed to stance β: frontend implements
  visual motion; instance stays pixel-pure. Phase A starts with
  (β-impl) — recompute wrap on motion events — with documented
  upgrade path to (α-impl) if smooth scroll lands.
- Cursor scope at v0.1: blink, multi-cursor rendering, peer cursors.
  Multi-cursor commands out of scope.
- Font: bundle JetBrains Mono + Lua override; tofu fallback for
  missing glyphs; real fallback chain is v0.2+.
- Rhythm: cadence relaxes from hour-level to daily-PR for larger
  features; discipline anchor moves from per-PR to per-session.
- Audit artifacts: this doc is the design artifact; per-phase audit
  material lands in separate per-phase audit docs (M10.x pattern).

Session plan: 1 = pmacs-protocol extraction; 2 = pmacs-gpu workspace
+ hello-world; 3 = attach loop; 4+ = Phase A proper.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 08:47:45 -04:00
Levi Neuwirth f98a885014
Merge pull request #37 from levineuwirth/worktree-tui-tree-sitter-cpp-dual-authority
tree-sitter-cpp/c + dual-authority styling (real C++ colors)
2026-05-20 00:40:08 +00:00
Levi Neuwirth 0935efd454 M_B3: tree-sitter-cpp/c + dual-authority TUI styling
Drops the policy-A exclusivity that left grammar-backed languages
without LSP semantic refinement. Adds tree-sitter-c (.c/.h) and
tree-sitter-cpp (.cpp/.cc/.cxx/.hpp/...) to the bundle so the grid
TUI gets lexical highlighting (keywords / strings / operators) on
first open. The Lua attach in builtin/runtime/lsp.lua now pushes
LspStyleView whenever an LSP server is up, regardless of grammar
presence; with both views attached the cell-painter pipeline runs
SyntaxHighlightView first (lexical) then LspStyleView (semantic)
and their styles compose through crate::overlay::merge_styles. The
result is the VSCode / Zed "TextMate + LSP semantic tokens" model
on a terminal grid: keywords colored by tree-sitter, identifiers
refined by clangd's semantic tokens.

`.h` is ambiguous C / C++; the `c` BUILTIN_LANGUAGES entry claims it
to match the LSP filetype map's default. Users who want `.h` parsed
as C++ can override via Lua (extension → language map).

Note the tree-sitter-c / -cpp crates expose `HIGHLIGHT_QUERY`
(singular), matching tree-sitter-md's `HIGHLIGHT_QUERY_BLOCK`
convention; tree-sitter-rust / -lua use `HIGHLIGHTS_QUERY` (plural).
Same bundled highlights.scm either way.

Regression guard: builtin_languages_include_c_and_cpp asserts the
language entries exist and claim their canonical extensions. The
LspStyleView module doc rewritten to reflect dual-authority
composition; the existing headline test's comment updated (the
test fixture still attaches only LspStyleView directly, so its
asserted cells reflect the LSP authority alone — Lua-level
attach_buffer is what exercises composition end-to-end).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:39:07 -04:00
Levi Neuwirth 98923bf250
Merge pull request #36 from levineuwirth/worktree-tui-lsp-theme-polish
LSP styling polish: theme covers LSP token types + modifier-aware lookup
2026-05-20 00:20:44 +00:00
Levi Neuwirth 1652837486 M_B1.1: theme + modifier polish for LSP styling
The grid TUI's M_B1 LspStyleView shipped functional but the default
theme only covered tree-sitter capture names. clangd / rust-analyzer
/ gopls emit LSP-spec SemanticTokenTypes that didn't intersect — so
`LLAMA_LOG_ERROR`, namespace names, parameters, fields, etc. fell
through to default and rendered uncolored. This brings the default
theme up to the LSP vocabulary so what the LSP layer ships actually
paints.

Theme additions (Theme::default_dark): macro, namespace, parameter,
property, class, struct, enum, interface, enumMember, modifier,
decorator, regexp, typeParameter. Refactored default_dark to a
data-driven (name, style) table — cuts the function from ~170 lines
to ~70, and adding a new theme entry now means appending one row
rather than 6 lines of `by_capture.insert(...)`.

LspStyleView::render now builds the lookup name as `<type>.<first-
modifier>` when modifiers are set, else just `<type>`. Theme::lookup's
dotted-prefix walk falls back to base if a refined entry isn't
defined, so the change is a strict refinement: themes that want to
target e.g. `function.defaultLibrary` (clangd's standard-library
modifier) can, themes that don't see no behavior change. Allocation
is skipped in the no-modifier case via `Cow::Borrowed`.

Tests: default_dark_covers_lsp_token_types regression-guards the
LSP-vocabulary coverage; lsp_style_view_uses_modifier_in_capture_lookup
proves a modifier-refined theme entry wins over the base.

The bigger polish (real C++ keyword/string coloring) needs
tree-sitter-cpp + dropping policy A's exclusivity so grammar-backed
languages get both views — separate thread, intentionally out of
scope here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:17:14 -04:00
Levi Neuwirth d867600aa3
Merge pull request #35 from levineuwirth/worktree-tui-lsp-style-view
LspStyleView: LSP-driven syntax coloring in the TUI (C++ colors!)
2026-05-19 23:52:56 +00:00
Levi Neuwirth c660d55881 M_B1: LspStyleView — LSP-driven syntax coloring in the TUI
Closes the visible "C++ has no syntax coloring in the grid TUI" gap.
Sibling of SyntaxHighlightView: a View impl that paints LSP semantic
tokens as cell styles, attached for buffers with no bundled
tree-sitter grammar. Same policy A (one styling authority per buffer)
the semantic-frontend producer arc enforces, applied to the grid
renderer the user actually uses today.

Mechanics: every render re-derives the buffer's URI from
buf.file_path() and pulls (encoding, legend) via the existing
LspManager::semantic_style_context plus tokens via for_uri. Per
visible line, tokens are converted from LSP encoding units to byte
ranges via char_to_byte, then to display columns via the existing
byte_range_to_display_cols (UTF-8 + tab aware). Theme::lookup
resolves token type names through the same dotted-prefix mechanism
the tree-sitter capture names use, so "function", "variable",
"type", "keyword" land on the existing theme vocabulary with no new
style names. Default-styled spans skip the per-cell loop, matching
SyntaxHighlightView's short-circuit.

Wiring: pmacs.lsp._attach_style binding pushes the overlay on the
active window (mirrors pmacs.parse._attach_highlight). install_lsp
and make_lsp_manager take SharedSyntaxRegistry so the binding can
hand the LspStyleView the shared ThemeHandle; editor.rs caller
updated. builtin/runtime/lsp.lua's attach_buffer attaches the view
when pmacs.parse.language_for_path returns nil (grammar-less
signal), dedup'd via a styled_buffers set that mirrors syntax.lua's
highlighted_buffers.

Test: lsp_style_view_paints_cells_from_semantic_tokens — seeds an
Initialized fake LSP client (using the cfg(test) helper from the
producer arc) on a /tmp/x.cpp buffer with one token, asserts the
expected cells are styled per the theme face and the cell just past
the token range is unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:48:50 -04:00
Levi Neuwirth 413b484c2d
Merge pull request #34 from levineuwirth/worktree-semantic-file-style-summary
FileStyleSummary minimap producer (resolves Open Q#2)
2026-05-19 23:25:30 +00:00
Levi Neuwirth c692710321 M1+M2: FileStyleSummary (minimap producer, Q#2 resolved) + doc
New InstanceMessage::FileStyleSummary { buffer_id, generation, lines:
Vec<Style> }: a coarse whole-file styling summary for a Zed/VSCode-
style minimap, resolving the design note's Open Q#2. One dominant
Style per source line (by byte count across the producer's current
spans); the frontend maps minimap rows to one or more lines.

Producer scoped_file_summary reuses scoped_style_spans with a whole-
buffer synthetic viewport, so policy A's authority pick (tree-sitter
for grammar-backed languages, LSP semantic tokens otherwise) is
inherited automatically — no separate styling path. file_style_summary_msg
is keyed on the buffer's CRDT generation: an idle buffer at the same
generation pays nothing (the whole-file summary is the expensive bit
on large files, so re-emit only after edits). First frame for a
buffer always emits; the existing first-frame test updated to expect
3 messages (StyleSpans + Decorations + FileStyleSummary).

Per-line dominant style is the v1 representation. Future refinements
(fixed-N bands; whole-file RLE style runs) are recorded in the design
note as straightforward extensions if a real frontend prefers them.

Structural gating same as the other semantic families: the daemon
only constructs a SemanticRenderState for sessions that negotiated
semantic_render, so non-semantic sessions never receive it. Grid TUI
adds the variant to its ignore list. Round-trip fixture covers it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:23:20 -04:00
Levi Neuwirth bd0668492c
Merge pull request #33 from levineuwirth/worktree-lsp-inline-adornments
Step 3+5: InlineAdornments producer (LSP inlay hints) — completes the producer arc
2026-05-19 20:01:08 +00:00
Levi Neuwirth 8ec3abcad5 Step 3+5: InlineAdornments producer from LSP inlay hints + doc update
scoped_inline_adornments (free fn, mirrors scoped_style_spans) reads
the inlay-hint store via for_uri and maps each InlayHint to an
InlineAdornment { at, AtOffset, Text{padded label, default style} },
clipped to the declared viewport (anchor in [vis_start, vis_end)).
Step 0 established inlay columns are already byte offsets by the time
they reach the store (inbound_converted rewrites the Position-shaped
InlayHint.position), so line_col_to_byte is exact with no per-server
encoding — unlike semantic-token styling.

inline_adornments_msg does the suppression: the InlineAdornments wire
variant has no generation/full/segments, so this is M11.2-level only
(whole-set re-send on any change, nothing when byte-identical, and
never an empty frame when there is nothing to say — no spam).

Tests: clip-to-viewport + padding + AtOffset, suppress-then-resync,
no-emit-without-hints; the old never-emitted invariant is split into
block_adornments_and_fold_state_still_never_emitted (Block/Fold are
still unwired) plus inline_adornments_not_emitted_without_hints.
assert_semantic_only now admits InlineAdornments.

Step 5 (folded): docs/semantic-frontend-protocol.md moves StyleSpans
(policy A) + InlineAdornments out of "declared, not wired", and adds
two deferred Open questions — per-byte tree-sitter/LSP blend, and
multiple-servers-one-URI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:00:44 -04:00
Levi Neuwirth dab106b08f
Merge pull request #32 from levineuwirth/lsp-real-server-hardening
T M4.5: derive LSP rootUri from the opened file's project (real-server hardening)
2026-05-19 19:59:47 +00:00
Levi Neuwirth 5180a627d1 T M4.5: derive LSP rootUri from the opened file's project (real-server hardening)
The default-bundle auto-attach path (lsp.lua ensure_server) never
forwarded cwd/root_uri to pmacs.lsp.spawn, so build_initialize fell
back to std::env::current_dir() — every auto-attached server received
the *editor's* cwd as rootUri regardless of which project the opened
file belonged to. Module-strict servers (gopls, rust-analyzer) return
nothing unless launched from the project dir; the fake-LSP and clangd
(which finds compile_flags near the file) masked this, gopls exposes
it. Same shape as the #26 transport bugs: lenient fakes hid a gap
strict real servers fall straight into.

Fix: project_root_for(language, path) in lsp.lua —
config[lang].root override -> pmacs.project.detect marker walk (the
canonical detector, honors set_search_boundary) -> the file's own
directory. attach_buffer resolves the path before ensure_server;
spawn now carries cwd/root_uri. Single-root only (fixes which root
the one per-language server uses); one-server-per-root multi-root
scoping stays deferred post-v0.1 (documented: first file of a
language fixes that server's root). New documented
pmacs.lsp.config[lang].root key.

Tests:
- m4_26: deterministic — new fake "rooturi" mode +
  PMACS_FAKE_LSP_ROOT_SINK side-channel; asserts the rootUri sent
  through a real find_or_open auto-attach is the go.mod dir, not the
  cwd, not the file's own dir.
- m4_27: PATH-gated real gopls — documentSymbol + hover round-trip is
  end-to-end proof of the fix against a real strict server.
- m4_28: PATH-gated real clangd — diagnostics arriving is the #26
  deferred-notification-flush + URI-absolutization regression guard;
  also exercises semantic tokens + documentSymbol.

No other latent bugs surfaced; gopls & clangd both clean through the
fixed path. rust-analyzer / basedpyright not installed here, so their
real end-to-end validation is still pending (the fix benefits them
identically — Cargo.toml / pyproject.toml are detect markers).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:56:13 -04:00
Levi Neuwirth 1e4b98ae1b
Merge pull request #31 from levineuwirth/worktree-lsp-stylespans-lsp-fallback
Step 2: StyleSpans LSP-semantic-token authority (policy A) — C++ now colors
2026-05-19 19:22:31 +00:00
Levi Neuwirth 0c9e46de6c Step 2: StyleSpans LSP-semantic-token authority (policy A) + tests
Languages with no bundled tree-sitter grammar (C/C++, …) had empty
StyleSpans — the visible "no C++ syntax coloring" gap. scoped_style_spans
now applies per-language styling authority (policy A): a grammar-backed
language stays tree-sitter-only (unchanged); a grammar-less buffer falls
through to lsp_scoped_style_spans, which reads the semantic-token store
(for_uri), resolves the owning server's encoding + legend via
LspManager::semantic_style_context, converts UTF-16 start/length to byte
per line with char_to_byte (now pub(crate); semantic-token data is NOT
byte-rewritten upstream, unlike inlay hints — see Step 0), names the
token via the legend, maps through the existing Theme::lookup, and drops
default-style spans. Output is shape-identical to the tree-sitter path,
so the M11.4 diff pipeline consumes it unchanged. Never two authorities
on one buffer: a still-parsing grammar-backed buffer returns empty
rather than briefly borrowing LSP styling.

Step 4 folded in: golden tests in the semantic_render module —
cpp_style_comes_from_lsp_when_no_tree_sitter_grammar (headline),
suppression (M11.4 reuse), incremental-on-token-change, and honest
empty-without-tokens. A #[cfg(test)] LspManager::insert_initialized_
test_client supplies a synthetic Initialized client (legend caps +
encoding) with no process, so the producer path is exercised without
a live server.

Per-byte tree-sitter/LSP blend and multi-server-same-uri merge remain
deferred open questions (recorded in the design note by Step 5).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 15:22:03 -04:00
Levi Neuwirth b306d414c6
Merge pull request #30 from levineuwirth/lsp-langservers-tier1
T M4.5: Tier 1 language-server configs (ts/js, lua, bash, toml, zig)
2026-05-19 19:17:18 +00:00
Levi Neuwirth e0e176fe4d T M4.5: Tier 1 language-server configs (ts/js, lua, bash, toml, zig)
Ship single-binary LSP servers pre-wired in the default bundle so a
user who installs the server gets attachment with no init.lua:

- typescript-language-server (--stdio) for the typescript /
  typescriptreact / javascript / javascriptreact language ids
- lua-language-server (settings.Lua present-not-null for the
  workspace/configuration pull)
- bash-language-server (start subcommand)
- taplo (lsp stdio; settings.taplo present-not-null)
- zls (no args)

Plus the pmacs.lsp.filetypes extension->language map entries
(ts/mts/cts, tsx, js/mjs/cjs, jsx, sh, bash, toml, zig, zon, lua),
keeping the same idempotent `or` guard so init.lua overrides win.

m4_25 asserts every config table and the filetype map resolve to
the documented values (binary-independent, spawns nothing).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:15:41 -04:00