Skip to content

Open the daemon's input side: arm, record, stop, crash-safe capture (recording.md chunk 1) - #166

Merged
ninjudd merged 3 commits into
mainfrom
recording-input-side
Sep 7, 2026
Merged

ninjudd merged 3 commits into
mainfrom
recording-input-side

Conversation

@ninjudd

@ninjudd ninjudd commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Recording waited behind realtime, and realtime has shipped its four chunks, so this is the first slice of recording.md: the daemon opens its device duplex only when something arms, captures one input channel into a transaction under .field/recording/ that survives the daemon dying, and finalizes a take on stop. field record drives it and ends with the take's path. Landing the take in the project — audio/<name>/, the ledger row, takes.yaml, the record: entry — is chunk 2 and is not here.

What the daemon does now

arm {track, device?, input} reopens the device with one input channel active and answers with the device's declared input and output latency. record {at?} locates the bed when asked, starts the transport if it is stopped, and captures from the next callback block; that block's transport position is latched as started_at_samples, so the first captured sample and its placement describe the same instant. stop and pause finalize and return the take's manifest, and a take event carries it to every connection, which is how a field record blocking in one terminal learns that field transport stop in another ended it. recordings lists every transaction; recover {transaction} patches one a dead daemon left behind. hello grows record in features and a pid; status grows a record block with the one V1 meter, the armed input's peak since the last read. An armed or recording daemon never idle-exits.

Decisions worth arguing with

  • One append-only WAV plus a journal, not chunk files. take.wav is float32 mono at the device's rate, written block by block with header sizes at zero; finalize patches them, and an unpatched header is what marks a transaction incomplete. journal.json records what fsync has reached the disk with. Recovery patches from the file size and keeps the journal's count beside it as the power-loss floor (plan §12.1).
  • Float32, not 24-bit. The callback delivers float; writing it unchanged is §3's "bytes stay pure" applied to depth. The plan's example ledger row said 24 as an illustration (§12.2).
  • Latencies recorded, not applied. Input and output latency ride the arm response and the manifest separately; which one placement subtracts is the loopback measurement §3 puts against real hardware in chunk 2 (§12.3).
  • The three product questions in §11 are answered — bare - record:, takes.yaml with takes:, and stop auto-chooses the new take — because this is the pull request that makes the readiness claim. Chunk 2 builds them as written; if any is wrong, the plan is where to say so.
  • Under a take the daemon refuses locate, load, device.select, a second arm, disarm, and defers default-output following and the rate switch a load prefers, because each restarts the device and gaps the capture. A session swap is allowed: it carries the transport (§12.8).

Three things I found along the way and fixed: the null clock's relative sleep ran a tenth slow (a frame count measures what a position readout never noticed), so it paces against an absolute deadline now; the recover op first took the transaction under id, which is the request's own field — the response came back with a string id and the client hung, so it takes transaction; and, caught by CI on the first head, the heartbeat's own status() read was consuming the peak meter every 250 ms, so a client saw a quarter-second window instead of the peak since its last read — only the status op consumes it now.

Not verified here

The microphone prompt for a detached daemon on macOS, the duplex open on an Apollo, and the latency arithmetic all wait for a hardware session (§12.10). A denied microphone looks like an input whose meter reads silent, which is why the meter names silence instead of drawing an empty bar. Two known limits: a take past 4 GB would need RF64, and frames the FIFO refuses are counted in dropped and reported, not recovered.

Testing

Build both halves first, from the repo root:

pnpm build:native && pnpm build

The suite: 46 files, 695 tests, all green here. The new file runs the input side against the null daemon — a gapless take against a playing file, channel selection, the refusals, an armed daemon outliving its idle timeout, a SIGKILL mid-take followed by recovery of a gapless file, field record end to end, and a stop from a second connection.

pnpm test
pnpm exec vitest run src/commands/record-daemon.test.ts

By hand without hardware, in a scratch project (null mode; the sawtooth on input 1 is what gets recorded):

mkdir /tmp/rec-probe && cd /tmp/rec-probe && export FIELD_AUDIOD_NULL=1
field init --name probe && field song create creek && field track create creek lead-vocal
node -e 'import("/Users/justin/amnesiac/field/dist/audio/wav.js").then(({ writeWavFloat32 }) => writeWavFloat32("tone.wav", 48000, [new Float32Array(48000*8).fill(0.1)]))'
field import tone.wav --song creek
printf 'name: main\ninputs:\n  - audio: tone\n    anchor: absolute\n    at: 0\n' > songs/creek/tracks/main.yaml
field record creek/track:lead-vocal --at 1.2     # ctrl-c after a few seconds
field record --list
field transport quit

You should see live creek (nothing was loaded, so it loaded the song), armed null input 1 (48000 Hz, latency in 0 / out 0 samples), recording take-… from 1.2.1 (0:00.5), a position-and-meter line refreshing in place, and on ctrl-c a take take-… complete .field/recording/take-…/take.wav (N frames, N/48000 s), started at sample 24000 line. The frame count should be about elapsed seconds × 48000; a take noticeably shorter than the time you waited is the bug the absolute-deadline clock fixed. Before this branch, field record did not exist and field transport status never showed an armed: or recording: line.

The crash path by hand: start a take as above, then from another terminal pkill -9 field-audiod. The blocking field record exits with field-audiod stopped answering mid-take (…); the take is recoverable — field record --list, then field record --recover take-…. field record --list (which respawns the daemon) shows the transaction incomplete with its frames on disk, .field/audiod.log has a recoverable take line, and field record --recover <id> finalizes it; field record --list then says recovered, and the recovered WAV's header frame count matches the file (the test also proves the recovered audio is gapless).

On the Apollo, from examples/bloom with the mix looping in one terminal (field play creek --loop) and in another:

field devices                                    # now two lists; inputs carry channel counts
field record creek/track:lead-vocal --input 1 --at 17

macOS should prompt for microphone access the first time (the prompt is attributed to the terminal that spawned field); if the meter reads silent while you sing, it did not, and System Settings › Privacy › Microphone is where to look. The take lands under examples/bloom/.field/recording/, which is gitignored with the rest of .field/; nothing in the project changes yet. The daemon this branch builds is 0.12.0 — field transport quit first if an older one is running, since the CLI refuses to record against a daemon without the record feature.

https://claude.ai/code/session_01CVAnQW78ZkZfxZ2GdKV886

…recording.md chunk 1)

Recording waited behind realtime, and realtime has shipped its four chunks, so this is the first slice of recording.md: the daemon opens its device duplex only when something arms, captures one input channel into a transaction under .field/recording/ that survives the daemon dying, and finalizes a take on stop. `field record` drives it and ends with the take's path; landing the take in the project is chunk 2.

The transaction is one append-only float32 WAV with its header patched at finalize, plus a journal of what fsync has reached the disk with — an unpatched header is what marks it incomplete, and recover patches it from the file size. The callback latches the transport position of the first captured block, so placement and the first sample describe the same instant; latencies are recorded as the device reports them and applied by nothing yet. The null clock grows an input whose sawtooth lets the tests prove a take is gapless, including across a SIGKILL and recovery, and it now paces against an absolute deadline because a frame count measured the drift a position readout never noticed.

The plan flips to in-progress and answers its open questions in §11 and §12; the three product choices there (record entry spelling, takes.yaml, auto-choose) are settled for chunk 2 to build and are the part of this change to argue with.

Claude-Session: https://claude.ai/code/session_01CVAnQW78ZkZfxZ2GdKV886

@minjudd minjudd left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔭 Projector review · model claude-opus-5[1m] · effort xhigh · CHANGES REQUESTED · took 2m 34s

1 finding thread: 0 resolved, 1 open — this review opens it.

This is the only one of the open pull requests that is actually current with main, and it shows: merge base is 7185f90, which is main's head, it uses docs/projects/recording/readme.md rather than the retired all/ layout, and project check passes on it. Typecheck is clean and the suite is 669 passed / 25 skipped with one failure, which is the finding below and is about the test rather than the daemon.

I checked the WAV writer by deriving the layout independently rather than reading the constants back. Walking writeHeader field by field — RIFF/size/WAVE, an 18-byte fmt chunk (format 3, mono, rate, rate×4, block align 4, 32 bits, cbSize 0), a fact chunk, then data — puts the fact frame count at offset 46, the data size at 54, and the total header at 58 bytes. The file declares exactly those three:

constexpr long headerBytes = 58;
constexpr long factFramesAt = 46;
constexpr long dataSizeAt = 54;

patchHeader's RIFF value is (headerBytes - 8) + dataSize, which is right — everything after the size field itself — and framesOnDisk's (size - headerBytes) / 4 is right for mono float32. The 32-bit ceiling comment checks out too: 2^30 frames at 48 kHz is 6.2 hours, so "six hours" is the honest number rather than a round one.

The audio-thread contract holds. push() is noexcept, takes no lock, allocates nothing, and does two memcpys into a preallocated ring behind AbstractFifo, counting the shortfall into droppedFrames instead of blocking — so an overrun shortens the take and says so in the manifest rather than glitching the callback. That matches what the header comment promises.

The crash-safety claim is tested and the test passes, which is the part I would otherwise have wanted to reproduce by hand: "a daemon killed mid-take leaves a recoverable transaction, and recover finalizes it gapless" is green, and the design it exercises — data on disk with a zeroed header, the header itself being the incompleteness marker, recover() patching from file size — is coherent with what I read in capture.cpp.

The readiness gate passes, and cleanly. This flips the plan from status: draft / priority: later to status: in-progress / priority: now, which is an executable-readiness claim, so it owns every question open at the flip. All five bullets in §11 carry an explicit dated disposition: four Resolved 2026-09-06 with a section reference and the reasoning, one Deferred 2026-09-06, deliberately with an argument for why nothing in chunks 1–3 reads it. Nothing in §11 is left hanging.

One note on where this sits relative to everything else open: #157, #158, #160, #161 and #163 are all still on the pre-#164 docs layout and none of them merges. This one does, so it is not waiting on that stack.

Comment thread src/commands/record-daemon.test.ts Resolved
… latency guarantee

The test asserted the first captured block landed within two blocks of the requested position, which is a claim about how promptly the audio callback gets scheduled — not this code's guarantee, and one a busy runner broke: the latch landed three blocks late inside the parallel suite while passing every time alone (minjudd's finding on #166). The correctness claim is the floor, never earlier than asked; the ceiling stays to catch a daemon latching wildly late, at eight blocks, with a comment so it is not tightened back.

Claude-Session: https://claude.ai/code/session_01CVAnQW78ZkZfxZ2GdKV886
…beat's

The peak meter is "the largest |sample| since the last status read", and the heartbeat reads status four times a second for its own state and device events — so it was resetting the meter, and every client saw at most a quarter-second window. On a sawtooth spanning ±1 once a second that is a quarter of the ramp, which is what CI measured: 0.48 where the test expected the ramp's peak. Locally the window happened to land near the top. Player::status takes consumePeak; the status op passes true and the heartbeat keeps the default.

Claude-Session: https://claude.ai/code/session_01CVAnQW78ZkZfxZ2GdKV886

@minjudd minjudd left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔭 Projector review · model claude-opus-5[1m] · effort xhigh · APPROVED · took 2m 51s

1 finding thread: 1 resolved, 0 open.

d09bd35 is clean. Both commits in the range do what they say, and I checked the second one against the binary rather than taking the test's word for it.

b8b737a — the latch ceiling. Widened to eight blocks with the distinction stated in the comment: the floor is the correctness claim, the ceiling is a sanity bound. That is the right split, and writing down why is what stops it being tightened back by someone reading it as a latency budget.

d09bd35 — the meter fix, which is the real one. The diagnosis is correct and the fix is minimal in the right way. Player::status(bool consumePeak = false) defaults to non-consuming, so the safe behaviour is what a new call site gets by accident; server.cpp's status op is the only caller passing true. I checked that claim directly — the only other player.status() call sites in native/ are main.cpp:42 and :74, both the heartbeat's, both taking the default:

$ grep -rn "player.status" native/audiod/src/
native/audiod/src/main.cpp:42:        lastKnownDevice = player.status()
native/audiod/src/main.cpp:74:        auto status = player.status();
native/audiod/src/server.cpp:363:        auto s = player.status (true); // a client read consumes the meter

So there is exactly one consumer, which is what the header comment's "peak since the last client read" now actually means.

I verified the binary under test is this head, not a stale one, because nine passing tests prove nothing if the daemon predates the fix:

$ nm -C field-audiod | grep 'Player::status'
000000010000e590 T Player::status(bool)

status(bool) rather than status(), so the tests are exercising the new code. record-daemon.test.ts passes 9/9, including the input_peak > 0.9 assertion that CI failed at 0.482666671276093.

The CI failure you cite is exactly as described — run 34068664394, record-daemon.test.ts:141, expected 0.482666671276093 to be greater than 0.9. Worth noting for anyone reading the older pull requests in this repo: that run took eleven minutes, so the Actions spending cap that was failing every check in about three seconds has cleared, and CI results are meaningful again.

Full suite and typecheck at this head, locally:

Test Files  45 passed | 1 skipped (46)
Tests       670 passed | 25 skipped (695)
tsc --noEmit  exit 0

Nothing failed, including plan-limits.test.ts, which had been failing in my environment for unrelated reasons on earlier heads.

One observation I am deliberately not filing, since it predates this range and the impact is nil: the meter's update at player.cpp:890-891 is a load-then-store rather than an atomic maximum, so it can race the consuming exchange and attribute one block's peak to the adjacent window. For a VU meter that is invisible, and the audio thread is the only writer, so there is no lost-update case between writers. Mentioned only so it is a known property rather than a surprise if the widget ever wants a tighter meter.

What remains is a human approval. This loop reviews and reports; it does not vouch on anyone's behalf, so this is a COMMENT review carrying an approved verdict rather than a GitHub approval. CI on this head was still in_progress when I submitted, so the green above is my local run — worth letting the linux job finish before merging. Draft state is untouched, as it should be on someone else's pull request.

@ninjudd
ninjudd merged commit e7f862b into main Sep 7, 2026
1 check passed
@ninjudd
ninjudd deleted the recording-input-side branch September 7, 2026 14:39
ninjudd added a commit that referenced this pull request Sep 7, 2026
…he track (recording.md chunk 2) (#167)

Chunk 2 of [recording.md](docs/projects/recording/readme.md): a take the
daemon finalized was a path under `.field/recording/` after #166; now it
is a take of the project. `field record` ends by landing it — the bytes
move to `audio/<node>/<take>.wav` and pin in the song's ledger where
imported audio pins, a row goes into `audio/<node>/takes.yaml`, the new
take is chosen, the transaction is removed — and the next `field build`
places it where it was sung.

## The committed half

One bare entry, mirroring `generative:` with a person where the model
was:

```yaml
# songs/creek/tracks/lead-vocal.yaml
name: lead-vocal
inputs:
  - record:
```

Its record node is named like a gen node's (the track, or
`<track>-<id>`), claims `audio/<node>/` in the song's namespace the same
way, and an entry with no takes yet builds as silence with `check`
warning — `input 1 ("record") has no takes yet — field record
creek/track:lead-vocal` — rather than refusing, so the mix can be placed
and looped before the first take exists (plan §4). Takes with none
chosen, a chosen name no row carries, a row whose asset is not in the
ledger or whose bytes live outside `audio/<node>/`, a takes file naming
another node, and a `takes.yaml` no entry claims are all errors.

## The record

```yaml
# songs/creek/audio/lead-vocal/takes.yaml
record: lead-vocal
chosen: take-20260907-110009
takes:
  - asset: take-20260907-110009
    started_at_samples: 120000
    musical_position: [3, 2]
    latency: 0
    device: "null"
    input: 1
    monitoring: apollo-direct
    console_preset: vocal-tracking
    recorded_at: 2026-09-07T11:00:09.190-04:00
```

The bytes pin in the ledger under the take's name, so the row carries
the record and never a hash. `started_at_samples` is on the recording
track's timeline, counted from the record entry's own `at` (zero for a
bare entry), at the track's rate; `latency` is the device's declared
round trip in the same samples; the take sounds at the entry's window
start plus their difference and nothing else — `musical_position` is
what the song's map said at capture and is never arithmetic.

## Decisions worth arguing with (plan §13)

- **Placement is on the track's timeline, counted from the record
entry's own `at`, converted once at landing.** The daemon reports the
start on the bed's timeline; landing subtracts the track's origin on the
song (the `at`s summed down its first placement path from `main`,
`land.ts` `trackOrigin`), scales bed samples to track samples, and
subtracts the entry's window start — the same reading the graph makes
when it adds that start back, so the entry's placement fields behave
like every other kind's and moving the entry's `at` moves its takes. A
track placed more than once records against its earliest placement and
the take line says so; a track the song never places keeps its own
timeline from zero. Rejected: storing the song position and resolving at
build time, which would glue a take to the song and make it slide when
the track moved. Known limit: track-local `time:` maps are not consulted
on the origin walk.
- **Latency is input + output latency as declared.** The reasoning is in
§13.2; the loopback measurement §3 asks for is still owed to a hardware
session, and the row is where a measured correction lands per take.
- **The graph expands the entry before planning** (`withTakes` in
`graph.ts`): an absolute `audio:` window over the chosen take at
`entry.at + started_at − latency`, reading into the take when that is
negative. Nothing downstream — planner, render, live compile, freeze —
learns recording exists.
- **One record entry per track for now.** A second would need the take
to say which node it lands in.
- **`field choose <song>/<node> --take <name>`** moves `chosen`;
`--variant` and `--take` are exclusive.

`import.ts` gained `openLedger`/`appendLedgerRow`, which `importAsset`
and landing now share; `importAsset`'s behaviour and output are
unchanged.

## Testing

From the repo root (no native changes in this PR; the 0.12.0 daemon from
#166 is what it drives):

```sh
pnpm build && pnpm test
```

47 files, 714 tests, green here. New: `src/commands/land.test.ts`
(origin walk over nested and repeated placements, landing with a nonzero
origin and latency, a take starting before the track, a record entry
with its own `at`, rate conversion, refusals, `chooseTake`), the `record
entries` block in `src/model/project.test.ts` (every diagnostic above,
the namespace claim, canonical formatting), and the daemon end-to-end in
`record-daemon.test.ts` now lands its take and builds the stem — silence
to `started_at_samples`, the gapless sawtooth after.

By hand, null mode, in a scratch project:

```sh
mkdir /tmp/land-probe && cd /tmp/land-probe && export FIELD_AUDIOD_NULL=1
field init --name probe && field song create creek && field track create creek lead-vocal
node -e 'import("/Users/justin/amnesiac/field/dist/audio/wav.js").then(({ writeWavFloat32 }) => writeWavFloat32("tone.wav", 48000, [new Float32Array(48000*8).fill(0.1)]))'
field import tone.wav --song creek
printf 'name: main\ninputs:\n  - audio: tone\n    anchor: absolute\n    at: 0\n  - track: lead-vocal\n    at: [2]\n' > songs/creek/tracks/main.yaml
field record creek/track:lead-vocal                # refused: no `record:` entry
printf 'name: lead-vocal\ninputs:\n  - record:\n' > songs/creek/tracks/lead-vocal.yaml
field check                                        # warning: no takes yet; ok
field record creek/track:lead-vocal --at 3.2 --console-preset vocal-tracking   # ctrl-c after a few seconds
cat songs/creek/audio/lead-vocal/takes.yaml
field check                                        # ok, no warning
field build creek/track:lead-vocal && field explain creek/track:lead-vocal
field transport quit
```

The take line reads `take creek/lead-vocal ← take-… at bar 3.2, chosen
(audio/lead-vocal/take-….wav, N s)`. The row's `started_at_samples`
should be `120000`: bar 3.2 is 4.5 s into the song and `lead-vocal` sits
at bar 2 (2 s), so 2.5 s on the track — before this branch there was no
row, and a wrong origin subtraction shows up here as `216000`. `explain`
shows the stem's one clip at `start: 120000`. `field record --list` is
empty afterwards because the transaction was removed; record a second
take and `field choose creek/lead-vocal --take <first name>` moves
`chosen` back.

On the Apollo, from `examples/bloom`: add `- record:` to
`songs/creek/tracks/lead-vocal.yaml`'s inputs, then `field record
creek/track:lead-vocal --input 1 --at 17` with the mix looping in
another terminal, and `field build creek && field play creek`
afterwards. What is wrong shows up as the vocal sitting late by the
round trip — the `latency` on the row is the device's claim, and that is
the loopback measurement still owed.

https://claude.ai/code/session_01CVAnQW78ZkZfxZ2GdKV886
ninjudd added a commit that referenced this pull request Oct 10, 2026
The merge of main brought in recording (#166 to #170) and the remote
(#171, #172), and the manual predated both. It now has a "Record a take"
section and a "Share a project through a remote" section, rows for
record, login, logout, clone, push and pull, `fetched` in the build
vocabulary, `choose --take`, the input device list, and FIELD_REMOTE and
FIELD_TOKEN.

The play section said a live song refuses `--click` and `--from` with
`--loop`. Both work: the engine synthesizes the click, and `--from` with
`--loop` is a region loop on the live session. The section now says
what each does.

The `--version`, `devices`, `transport status`, `export` and `import`
transcripts are rerun at this head, and the install section says every
stem renders through field-audiod, not only effect inserts.
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.

2 participants