Skip to content

Watch chunk 1: daemon reload at the loop wrap, bloom build --watch - #34

Merged
ninjudd merged 3 commits into
mainfrom
feat/watch-build
Aug 6, 2026
Merged

ninjudd merged 3 commits into
mainfrom
feat/watch-build

Conversation

@ninjudd

@ninjudd ninjudd commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

First chunk of the watch plan (watch.md §4.1): the daemon side of swap-at-wrap, and the headless watch verb. Chunk 2 (play --loop --watch composing the two, the field demo, docs-root paragraphs) follows on its own PR.

Daemon (bloom-audiod 0.4)

  • New reload op: opens and prepares the new file's reader at request time, then a fine position poll (20 ms, running only while a takeover is pending) swaps it in when the position moves backwards — the reader wrapping. You always hear whole passes (§1.1); the swap lands within one poll tick of the wrap. The recorded successor (sample-exact double-buffered bar-synced swap) stays deliberately not-now.
  • Broadcast reloaded event when the takeover actually sounds — emitted from the heartbeat, so a watching client prints the swap at swap time, not request time.
  • Latest-wins: a second reload before the wrap replaces the queued one; a fresh load supersedes any queued takeover; reload without a looping stream is an error; a paused/stopped transport swaps immediately without starting.
  • Protocol stays v1 (additive op); version-guarding follows the load+loop precedent (0.3).

bloom build --watch

The loop body per §2: FSEvents via recursive fs.watch on the project root filtered to everything but .bloom/ (self-trigger) and .git/; ~300 ms write-burst debounce; check first — a red project prints diagnostics and keeps the last good outputs (§1.2), since a half-saved file mid-edit is the common case; then a rebuild through the normal engine and an output-hash comparison per label (§1.3): hash moved ⇒ ↻ label <shortHash>, hash same ⇒ · no audible change. Only one build in flight — a change landing mid-build discards that report (its artifacts still land in the CAS, warm for later) and re-runs the body (§2 coalescing).

Tests (239 passing)

  • watch.test.ts (real FS events, shrunk debounce): baseline sets no change; a parameter edit reports exactly the moved label; a broken YAML prints diagnostics and the recovery reports against the last good baseline; a comment-only edit rebuilds to all-cache-hits silence; abort resolves.
  • play-daemon.test.ts (real binary, null output): reload answers with the queued file's shape while the old pass keeps playing, then the reloaded event fires at the wrap and status shows the successor path, still playing, still looping; reload without a looping stream rejects.

Proven live on field: bloom build --watch creek, then a keys fader nudge reports one moved mix hash from a sum-only rebuild, and the revert reports the original hash straight from cache.

Also moves the watch line from next.md to now.md and updates watch.md's status to chunk-1-in-flight.


Note

Medium Risk
Changes live playback transport (wrap-time source swap) and long-running watch rebuild loops; behavior is well-tested but affects core audition and build paths.

Overview
Watch mode chunk 1 adds the daemon takeover primitive and a headless rebuild loop; play --loop --watch is explicitly deferred to chunk 2.

bloom-audiod 0.4 introduces a reload op that pre-opens the successor file and swaps readers at the next loop wrap (20 ms position poll while pending). Latest reload wins; load clears a queued reload; non-looping streams reject reload. When the swap actually sounds, the heartbeat broadcasts a reloaded event with the new path.

bloom build --watch watches the project (excluding .bloom/ and .git/), debounces edits, check-gates (diagnostics only, last good hashes retained), rebuilds through the normal engine, and reports labels whose output sha256 changed (↻ vs · no audible change). One build in flight; mid-build changes discard the report and re-run.

Docs move watch from next to now and mark watch.md chunk 1 in flight. Tests cover FS-driven watch behavior and daemon reload at wrap.

Reviewed by Cursor Bugbot for commit ac90bdb. Configure here.

The watch plan's first chunk (watch.md §4.1). The daemon (0.4) gains a
reload op: the new file is opened and prepared at request time, and a
fine position poll swaps it in at the next wrap — whole passes only
(§1.1), with a broadcast "reloaded" event when the takeover actually
sounds. A fresh load supersedes any queued takeover, and reload
without a looping stream is an error.

bloom build --watch is the headless loop body (§2): FSEvents on the
project root (everything but .bloom/ and .git/), ~300 ms write-burst
debounce, check first — a red project prints diagnostics and keeps the
last good outputs (§1.2) — then a rebuild through the normal engine
and an output-hash comparison per label (§1.3): hash moved is
reported, hash same is silence. One build in flight; a mid-build
change discards the report and re-runs (§2 coalescing).

Tested: the watch loop against real FS events (baseline, hash-moved
reporting, red-project recovery, no-op silence, abort), and the
daemon takeover end-to-end against the real binary in null-output
mode. Proven live on field: a fader nudge under watch reports one
moved mix hash, the revert reports the original hash back — both from
a sum-only rebuild.

@ninjudd ninjudd left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at head ac90bdb. One P2 and two P3s, inline. The P2 is the loop body's one uncaught path: any loader throw kills the watch session with a raw Node stack — the opposite of §1.2's promise. Everything else I could check holds, several claims verified by execution against the real daemon binary and the real normalize rule.

Method: the checkout is on feat/watch-play (chunk 2), so I reviewed ac90bdb from a git archive copy in my scratchpad and never touched your tree. native/ is byte-identical between the two heads and the built binary reports 0.4.0 and carries the reload op, so the daemon tests ran against the PR's daemon via BLOOM_AUDIOD. 239/239 pass, typecheck clean, including reload takes over the looping stream at the wrap and the Siri determinism test that flaked on CI for #31.

Verified by execution — the watch loop, on a scratch project with the real normalize rule (afconvert, not the fake runner):

  • The reported hash is the truth: a sample_rate edit printed ↻ //songs/creek/sounds:pad-96k 372cc41eb74c, and shasum of the materialized .bloom/out/.../pad-96k.wav is 372cc41eb74c…. Hash moved ⇒ one line, correct label, correct bytes.
  • A comment-only edit prints · no audible change — §1.3's cache-hit claim, live.
  • Debounce coalesces: five rewrites inside the window produced exactly one report, of the final state.
  • The .bloom/ exclusion holds: quiet windows after a build produce no output at all, so materializing into .bloom/out does not self-trigger.
  • Starting red works as cli.ts claims: diagnostics print immediately, and repairing the file prints the baseline and watching for changes.
  • Renaming the watched label away → build failed: pattern matched no labels: … and the watch survives; restoring it reports correctly against the old baseline.
  • Multi-label watch works: build --watch 'creek/...' baselined three labels and an edit to one reported exactly that one (see the §5 thread — this answers an open question the plan still lists as undecided).
  • Ctrl-C ends the session cleanly.

Verified by execution — the daemon, including two PR-body claims no test pins:

  • Latest-wins: reload(a) then reload(b) before the wrap → exactly one reloaded event, for b, and status follows.
  • A fresh load supersedes a queued takeover: reload(a) then load(c, loop) → zero swaps afterwards, still c, still playing, still looping — no phantom takeover a pass later.
  • The shipped test's own assertions (queued file's shape answered immediately, old pass still playing, event at swap time, playing/looping preserved) pass against the real binary in null-output mode.

Verified by reading, no issue found:

  • The "message thread only" comment on PendingReload is true: Server::handleLine takes a MessageManagerLock around every dispatch, so reload(), startTimer, and pendingReload are touched under the same discipline as load — and startTimer from the socket thread is legal because of that lock.
  • applyReload's ordering is the shipped load() ordering — transport.stop() → setSource(nullptr) → replace readerSource — so AudioTransportSource's callback lock guarantees the audio thread (or the null clock) is never inside the source being destroyed. ~Player gaining stopTimer() is the right catch.
  • The single-flight/stale loop has no interleaving hole: the only await in the body is the build, and everything from if (stale) continue through the while condition to finally { building = false } is synchronous, so a timer callback can't slip between "loop exits" and "building cleared" and lose a change.
  • §1.1's citations now read correctly — clip-looping.md's status line does record the native loop ("gapless in the daemon"), playback.md genuinely has zero mentions of looping, and the text now says so instead of citing it. The #32 finding is properly fixed.
  • --watch is opt-in on build with the plain path untouched; reloaded is additive on the event union; protocol stays 1; the daemon bump follows the 0.3 precedent.

Four footnotes, no threads:

  1. Editor lock files turn the project red for the length of an edit. yamlFiles (project.ts:139) filters on .yaml with no dotfile skip, so Emacs's .#pad-96k.yaml lock symlink is read as a sound file — I watched check: songs/creek/sounds/.#pad-96k.yaml: unreadable: ENOENT print on every burst until I removed it. Pre-existing in check, but watch is the first thing that reads the tree while an editor is holding it, which is exactly when the lock exists. One-line fix (skip names starting with .) is safe — a leading-dot filename can't be a valid sound name anyway.
  2. Nothing pins the .bloom//.git/ exclusion, and its failure mode is an infinite rebuild loop that none of the current tests would fail on. Cheap test: after the baseline, assert no second onOutcomes arrives within 2× debounce.
  3. Removing a watched label reports · no audible change — literally true of the outputs that remain, but a label leaving the build is worth a word if §5's reporting format grows.
  4. Chunk 2 reminder: the reload version guard wants minor < 4 on the play.ts:106 pattern. The real case isn't a stale build, it's a 0.3 daemon still alive from before the upgrade (300 s idle timeout).

Comment thread src/commands/watch.ts Resolved
Comment thread native/audiod/src/player.cpp Resolved
Comment thread docs/projects/all/watch.md Resolved
ninjudd added 2 commits August 6, 2026 10:46
P2: loadProject sat outside the loop body's guard, so a loader throw
(dangling symlink under songs/, a file where a directory belongs)
escaped void runBody() as an unhandled rejection and killed the watch
— the one thing §1.2 says it must never do. The loader is now guarded
like the build, routing to onError, and the timer invocation catches
as a last resort. Test reproduces the reviewer's dangling-symlink
crash and asserts the same session recovers.

P3: reload against a paused transport rewound to 0 and turned the
pause into a stop, discarding a human's position. A stopped transport
still swaps immediately; a paused one now holds — the takeover stays
queued and lands at the wrap after resume. Header contract updated;
test pins state, path, and sample across a paused reload, then the
takeover on resume.

P3: watch.md §5's multi-target question was answered by this PR and
left open, contradicting decision 4's "the multi-label form" — now
recorded as resolved with the shipped reporting format.

@ninjudd ninjudd left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed at head 7fc36d7. All three fixes are real and I verified each one independently of the tests you added — same scratchpad git archive method, your checkout untouched. 241/241 pass, typecheck clean (239 + the two new tests). No new threads; nothing blocking from me.

P2 — the loader throw. Fixed, and the shape is right. Both of my triggers, replayed against a live watch on this head:

  • dangling symlink under songs/ → build failed: ENOENT … stat …/songs/ghost, session alive
  • songs/creek/takes as a regular file → build failed: ENOTDIR … scandir …/takes, session alive

and then a real parameter edit after both wrecks reported ↻ //songs/creek/sounds:pad-96k e85908974779 against the intact baseline, with ctrl-c still clean. Routing the load through onError was the fix I'd have picked; the .catch on the timer is the part I didn't ask for and is the one that actually makes the guarantee total — the inner guards can be regressed by a later edit, that one can't. Your new test uses the exact repro, which is the right thing to pin.

P3 — the paused reload. Fixed, and you took the better of the three options. Measured against the rebuilt binary, not the test:

  • paused at sample 61955 → after reload: state = paused, sample = 61955, path unchanged, zero swaps. The old head gave sample = 0, state = stopped on the same probe — exact inversion.
  • the held takeover does land: resume a 3 s pass from ~0.85 s in, and status flips to the successor at the wrap (~2.6 s later), with the reloaded event 44 ms behind the swap — heartbeat latency, exactly as designed. (An earlier probe of mine appeared to show a missing event; that was my sleep landing inside the null clock's real-time drift, not a dropped broadcast. Worth saying out loud since I nearly filed it.)
  • a stopped transport still swaps immediately without starting — the unchanged half stayed unchanged.

Queueing rather than clamping is the choice I'd argue for too: it makes the whole feature one sentence — the takeover only ever lands at a seam — instead of two rules with an exception. transportState() == "stopped" as the discriminator is also better than isPlaying(), since it folds "loaded but never played" and "stopped at 0" into the same no-position-worth-keeping case.

P3 — §5. Recorded. The bullet now says what happened, why it was predictable (it fell out of the engine loop, as the plan guessed), and what the format is — with decision 4's "multi-label form" tied back in. Struck-through-plus-resolution keeps the bullet in place for anyone who cited it, which is the right instinct in this repo.

Two footnotes, no threads, neither worth a fix commit on its own:

  1. onError's CLI line prints build failed: in front of loader failures now — build failed: ENOENT … stat …/songs/ghost reads like the build when it was the load. One hook for both is fine; the prefix is what's slightly off. If chunk 2 touches this printer anyway, dropping the prefix (or making it watch:) would read truer.
  2. The 20 ms poll now runs for the whole duration of a pause, where before the timer stopped as soon as the transport wasn't playing. It's a no-op tick on the message thread and I'd leave it, but it's a real consequence of the fix rather than an accident — worth knowing if the daemon ever needs to go quiet while idle.

The two footnotes from the first pass (no dotfile filter in yamlFiles, so an Emacs lock file reads as a sound; and nothing pinning the .bloom/ exclusion, whose failure mode is an infinite rebuild loop no current test would catch) are untouched — both were footnotes and both are fine to carry.

CI: the run on 7fc36d7 is still queued; a712844 never got one, which is the dropped synchronize event your nudge commit names. Worth a green check before you merge, since the fix commit's daemon change is the part CI has never built.

@ninjudd
ninjudd merged commit 8a683c1 into main Aug 6, 2026
0 of 2 checks passed
ninjudd added a commit that referenced this pull request Aug 6, 2026
Second and final chunk of the watch plan ([watch.md
§4.2](docs/projects/all/watch.md)), on top of #34.

## play --loop --watch

Composes the watch-build loop with blocking playback (§1.4): the same
pattern is watch-built beside the play; when the played label's output
hash moves, the native loop queues a daemon reload — `↻ <label>
<shortHash> at the next wrap` when queued, `↻ swapped at the wrap` when
the takeover actually sounds (the daemon's `reloaded` broadcast,
surfaced through a new `onReloaded` play hook). A `--from` region loop
takes the requeue path instead: no wrap to swap at, so the freshest
artifact is consulted at every pass load (`currentPath` on PlayOptions,
per §2's last bullet). Requires `--loop` and exactly one label;
`--click` is refused for now — the click bakes into a CLI-side temp file
a swap would silently drop. Version-guarded against pre-0.4 daemons
following the `load`+`loop` precedent. Watch errors print with their
phase (`load failed:` / `build failed:` / `watch failed:`) — closing the
#34 review footnote about loader crashes reading as build failures.

## Atomic materialize (a real bug the walk found)

`materialize` copied into the stable `.bloom/out/...` path **in place**
— truncating the very file the daemon streams while looping, violating
§1.6's "the old mix keeps looping". It now lands by copy-to-temp +
rename so the playing pass keeps its inode until the swap, with a test
pinning the fresh-inode behavior.

## The §3 definition-of-done walk, run against field

Scripted with the null-output daemon, every edit reverted, tree clean
after:
- clip position edit → `↻ mix:main` queued
- fader nudge → `↻` (latest-wins replaced the queued takeover)
- `.scd` edit → real re-render, `↻`, then `↻ swapped at the wrap`
- broken YAML → diagnostics printed, **loop kept playing**; the fix
recovered silently (identical content, all cache hits)
- `bloom fmt` → "already canonical", nothing rebuilt, nothing swapped
- `bloom choose still-water-keys --variant 2` from another shell → `↻` —
live variant A/B inside the loop
- the final revert swapped back to the exact original mix hash, and
ctrl-c ended cleanly

The audible version is one command away: `bloom play creek --loop
--watch`.

## Tests (244 passing) and docs

New: `onReloaded` surfaced through a native-loop play (the watch
composition in miniature, real daemon); `currentPath` repointing a
requeue pass; materialize-by-rename. Docs: build-graph.md gains the
watch section under caching; playback.md's follow-ups record the reload
op; watch.md status → implemented with only the `status`-visibility
question left open; the now.md watch line retires.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes live playback and build output materialization (all cached
builds get rename-based writes); behavior is well-tested with the daemon
but affects the critical edit-while-listening path.
> 
> **Overview**
> Completes **watch mode chunk 2**: **`bloom play <patterns> --loop
--watch`** runs **`watchBuild`** beside blocking playback. When the
single looped label’s output hash moves, a native loop queues
**`reload`** at the wrap (`↻ swapped at the wrap` via **`onReloaded`**);
**`--from`** region loops use **`currentPath`** so each pass loads the
freshest file. **`--watch`** requires **`--loop`**, one label, daemon
≥0.4, and refuses **`--click`** for now.
> 
> Fixes a **watch bug**: **`materialize`** now **copy-to-temp + rename**
instead of copying in-place, so a looping daemon reader is not truncated
under an open path (inode test added).
> 
> Watch/CLI errors report **`load` / `build` / `watch`** phase instead
of generic “build failed”. Docs mark watch implemented; **`now.md`**
drops the watch line.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
92f944b. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
ninjudd added a commit that referenced this pull request Aug 7, 2026
…nce (#38)

The no-thread footnotes from the #34/#35/#37 reviews. Each was too small
to justify its own PR; together they justify one.

### `bloom build` claimed cache hits that never happened

Assets and chosen variants printed `cached` — but nothing executed and
nothing came out of the cache; they are committed files the build only
pointed at. Outcomes now carry `committed`, the print says `source`, and
the three status words pad to a common width so the labels line up:

```
cached  //songs/creek/tracks:drums → /Users/justin/…/field/.bloom/out/songs/creek/tracks/drums.wav
source  //songs/creek/sounds:still-water-keys → /Users/justin/…/field/songs/creek/audio/still-water-keys/1.wav
built   //songs/creek/mix:main → /Users/justin/…/field/.bloom/out/songs/creek/mix/main.wav
```

(Paths are absolute and elided here for width — that is pre-existing
behaviour from #35, and it does swamp the alignment this buys. Printing
them relative to the project root is a follow-up, not something to
change
quietly inside a cleanup PR.)

### One spelling for the committed path

It was computed in three places by two spellings (`assetFilePath` and an
inline `join`), which were drifting apart by construction.
`sourceFilePath` covers assets and generation labels alike.

### `withClick` left a hash describing a different file

The returned Playable's `path` pointed at the clicked copy while
`sha256` still described the source. `--click` and `--watch` don't
compose today, so nothing was wrong yet — but watch seeds its baseline
from that field, so the next composition is exactly where it would have
bitten. It re-hashes.

### Quitting before the wrap now leaves evidence

A pending takeover froze as a `└` that reads as *about to happen*, when
ctrl-c means it never will. Verified live under a pty in a scratch
clone:

```
  [1] 7.3                     └51a757a22efb
  51a757a22efb built, never sounded (stopped before the wrap)
```

### The seeded-baseline window

A seeded baseline can report drift before the play's own first load, and
a reload with nothing to take over from errors. The takeover is held
until the first load opens the block, then released.

### Editor dotfiles are not project files

Emacs writes `.#track.yaml` — a dangling symlink — while a buffer is
unsaved. It ends in `.yaml`, so the loader read it and threw ENOENT,
which under `--watch` meant merely *opening* a track file ended the
rebuild.

### Tests

The `.bloom/` watch exclusion had nothing pinning it. The new test
settles the watcher before probing, because "nothing happened because of
what I just did" is only measurable from a quiet baseline — the
fixture's own writes can still be in FSEvents' pipeline when the
baseline lands, and an absolute event count blames the probe for them.
(That is what the first draft of this test did, and it failed; the
`fs.watch` filenames were never the problem.) Plus the committed/rule
outcome flags, the click re-hash, the dotfile, and three teardown cases.

`pnpm typecheck` exit 0, 271/271 green, and `bloom build` re-run against
the field clone for the status column.

Deliberately **not** here: bounding the beat scheduler's prints by the
loop length (#37 review). It needs the loop length from `status` and is
a
scheduler behavior change, not cleanup.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Localized CLI/watch/build and loader filtering changes with broad test
coverage; no auth, persistence, or protocol changes beyond existing
reload behavior.
> 
> **Overview**
> This PR bundles small **watch/build UX fixes** from #34/#35/#37 review
footnotes: clearer build output, safer `play --watch` reload timing, and
fewer watch false failures.
> 
> **Build reporting:** `BuildOutcome` adds **`committed`** for assets
and chosen variants (nothing was executed or cache-hit). `bloom build`
prints **`source`** instead of **`cached`** for those labels, with
padded status columns via **`buildStatus`**.
> 
> **Paths and hashes:** Committed file paths are unified in
**`sourceFilePath`** (replaces duplicated asset/generation path logic).
**`withClick`** now sets **`sha256`** from the clicked temp WAV
(**`sha256FileSync`**) so path and hash stay aligned for watch
baselines.
> 
> **`play --watch`:** Rebuilds that arrive before the first daemon load
are **held** (`heldForStart`) until **`onItem`** opens the block, then
**`takeover`** runs—avoiding reload errors when nothing is looping yet.
> 
> **TTY teardown:** **`LoopDisplay.end()`** prints that a pending hash
**built but never sounded** if you ctrl-c before the wrap (docs updated
in **`watch.md`**).
> 
> **Watch stability:** YAML discovery skips **dot-prefixed** files (e.g.
Emacs **`.#…yaml`**). Tests add **`quiet()`**, assert **`.bloom/`**
writes do not retrigger watch, and cover committed outcomes, click
re-hash, and teardown cases.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1bfeb2b. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
@ninjudd
ninjudd deleted the feat/watch-build branch September 28, 2026 04:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant