Repository navigation
feat(supervision): token-efficient sub-supervisor (closes #27) - #30
Conversation
|
This is genuinely strong work - the classifier core is clean and well-tested, and the robustness shell (flock, crash backoff, pane-gone guard, signal-trapped flush, leaning on the #29 queue as the lossless backstop) is the right shape. The part I want to think through with you is the injection path, since it's the load-bearing piece and it's the one the original deferral called the hard part. A few risks I see in
None of this is a knock on the design - it's the right architecture and I'd like to run it. I mainly want the injection proven on the actual harness before trusting it to drive a walk-away fleet, since that's the part the fake-tmux tests can't really exercise. What's your read - have you hit any of these live, and how were you picturing the human-in-the-pane case? (Heads up too: this couldn't go through the no-mistakes pipeline because of the fork-routing gap (#293) - we're fixing that separately, which should unblock your contribution flow.) |
|
Thanks for the careful read — these are exactly the right risks to stress. Quick takes + what I'll harden:
On proving it live: agreed — that's the load-bearing piece and unit/fake-tmux tests can't exercise it. I'm dogfooding the daemon on this very fleet right now (it's how I get these wakes), so I'll harden these four + run it against the real harness (incl. the human-in-the-pane case) before asking you to trust it for walk-away. Appreciate the push to get the injection right. |
Where I've landed on the framingAfter thinking through the "is this universally good?" question, my conclusion is that the sub-supervisor should ship as neither a standalone opt-in daemon nor a default-on behavior change. Its value is genuinely conditional: triaging wakes in bash (instead of waking the firstmate LLM with full context) is exactly right when I've walked away, and a downgrade when I'm at the keyboard and want full judgment and immediate responsiveness. The token win and the behavior change are the same mechanism, so it can't be made invisibly universal. The boundary that matters isn't user identity, it's presence. So the plan:
Net: the daemon is the away-mode engine, presence is the boundary, |
|
This makes complete sense — presence is exactly the right boundary, and your framing solves the two problems (inject-into-live-pane + self-cancellation) with one mechanism. Agreeing to the full direction:
The insight that the marker and the busy-guard are the same problem (daemon and human sharing one input channel) is the one I was missing — solving them together under Implementing now and will update this PR. Will dogfood across real away stretches before asking you to trust it for walk-away. |
|
Thanks for turning this around so quickly - the A few things before we take another look:
Once those three are in place, give me a ping and we'll do the next review pass. Appreciate the careful work. |
|
Thanks — on it. Working through all three:
Will ping once the rebase lands and CI is green. |
…up, crash env knob
eecb4f9 to
eb76cb1
Compare
Pivot the sub-supervisor from always-on opt-in to presence-gated via an /afk skill, per the maintainer's design direction (PR #30 comments). The daemon is the away-mode engine: it injects ONLY when state/.afk is present. Invoking /afk sets that flag and starts the daemon; any real (unmarked) message clears it and firstmate resumes full per-wake responsiveness. This makes the token-saving tradeoff consented and explicit, and shrinks the inject-into-a-live-pane hazard (in afk mode, by definition no human is typing). In-band sentinel marker (FM_INJECT_MARK, ASCII 0x1f): every daemon injection is prefixed with a byte a human would never type. Firstmate's contract: leading marker = internal escalation (stay afk); no marker = captain is back (exit afk). /afk invocations are exempt so they don't self-cancel. Bias ambiguous cases toward exit. Four injection fixes folded under /afk: - Single-line digest (newlines collapsed to literal separator) - Busy-guard on the supervisor pane (defer when pane_is_busy) - Turn-started confirmation (verify content changed, bounded retry) - Auto-discovered supervisor pane (FM_SUPERVISOR_TARGET > %48 > fallback) Orthogonal to yolo: afk changes surfacing aggressiveness, not approval authority. Tests: 34/34 (26 existing + 8 new afk/presence-gating tests). shellcheck clean.
eb76cb1 to
952bbb0
Compare
|
All three are in place — ready for the next review pass:
Your turn whenever you're ready. |
|
Thanks for the thorough implementation - the Findings (3 HIGH)
Plus medium: the marker is detected ( What passed: marker delivery + classification, exit-on-unmarked-message, missing-target fail-safe, single-line digest. How to catch these yourselves before reporting backThe gap is that afk-mode dogfooding on a live fleet structurally can't exercise the human-in-the-pane case - in afk mode nobody's typing, so the busy-guard and partial-composer collision never fire. Those paths have to be proven in a deterministic harness where you script both the human and the swallowed Enter:
Bake those two into a private-socket e2e test in the PR and they'll catch this class of bug before it reaches us. Ping when the three HIGH items are fixed and that e2e is green, and we'll re-review. |
…mit, portable lock Address the maintainer's in-depth review on PR #30 (3 HIGH + medium + lows): HIGH 1 — Busy-guard misses human's half-typed line: Add pane_input_pending() that detects non-empty content on the cursor line (via cursor_y + capture-pane). A human's partial input or a previous injection's unsent text now defers injection instead of corrupting the shared input channel. HIGH 2 — Turn-started confirmation duplicates/concatenates: Rewrite inject_msg to type-once + Enter-retry. The digest is typed once via send-keys -l; if the composer still has text after Enter (swallowed Enter), retry Enter only — never retype the digest. Submit ack = composer is empty after Enter (checked via pane_input_pending). HIGH 3 — Daemon won't start without flock: Replace flock -n with the repo's portable mkdir-based lock helper (fm-wake-lib.sh: fm_lock_try_acquire / fm_lock_release). No macOS dependency. Medium — Marker never stripped: Add strip_injection_marker() helper that removes the sentinel prefix before classification/relay. Low (a) — Duplicate status in one digest: classify_signal and classify_stale now check the seen-status marker before escalating, so a status escalated by the signal path, stale path, or catch-all scan is not re-escalated by another. Low (b) — Wrong-but-resolving fallback undetectable: Log the target resolution source (FM_SUPERVISOR_TARGET / TMUX_PANE / FALLBACK) at startup so a wrong fallback is visible. Required new test — Private-socket e2e: tests/fm-afk-inject-e2e.test.sh: exercises the two scenarios afk-mode dogfooding structurally cannot reach (human-in-the-pane, swallowed-Enter) on an isolated tmux socket with real watcher-driven escalations. Closes maintainer review on PR #30.
… self-check
Lint fixes for CI:
- SC1091: add '# shellcheck source=bin/fm-wake-lib.sh' before dynamic source
- SC2015: replace 'A && B || C' cleanup pattern with 'rm -rf ${VAR:-} || true'
E2e test robustness:
- Add pane_input_pending environment self-check: types text into the
supervisor pane, verifies pane_input_pending detects it via cursor_y +
capture-pane. If the tmux environment doesn't support echo-based
detection (CI runners may differ), the test skips with diagnostics
instead of failing. The unit tests in fm-wake-queue.test.sh still cover
the pane_input_pending logic comprehensively.
|
Merged - thank you for the careful work on this. You took the design direction we converged on and implemented it faithfully: presence-gated Special credit for building the private-socket e2e test from the methodology we shared - that kind of deterministic coverage is exactly what catches this class of bug before it ships. Appreciate the back-and-forth on getting the injection path right. Do you have a handle on X? I'd love to post about this feature and acknowledge your contribution here! |
* feat(bin): add experimental Tern runtime backend (kunchenguid#24) * feat(backend): add experimental Tern session backend Adds bin/backends/tern.sh (one Tern session per home, one fm-<id> tab per task, target tern:<session>/<block>), runtime detection from TERN_PANE with TERM_PROGRAM=tern, process-level agent state, plugin-fed busy state, a window-side Tern plugin that publishes agent state and colors task tabs, PI_TUI_NATIVE=0 for Tern task panes, bin/fm-tern-autostart.sh, the omp idle hint in the shared composer placeholder set, tests, and docs. * test: clear the Tern pane marker in the shared test library Suites run from a Tern pane otherwise auto-detect the tern backend where they expect the no-marker tmux fallback. * no-mistakes(review): Close exited Tern task blocks on kill; test fm-send routing * no-mistakes(test): Gate Tern agent-state file on writer window pid, not age * no-mistakes(document): Add Tern to stale backend lists across docs * no-mistakes(lint): Silence intentional SC2016 warnings in Tern backend tests * no-mistakes(ci): Lint 1 (ci-2) was caused by this PR, and I fixed it. ShellCheck SC2034 fired on `tests/fm-backend-tern.test.sh:101` because the test reset the Tern state-file cache with the assignment `FM_BACKEND_TERN_STATE_FILE_CACHED=`, a variable that is only read inside the sourced `bin/backends/tern.sh`. The invariant is that the shared lint must pass on every changed shell file, and that assignment was the only site that broke it. I changed the line to `unset FM_BACKEND_TERN_STATE_FILE_CACHED`. The behaviour is the same because tern.sh reads the variable as `${FM_BACKEND_TERN_STATE_FILE_CACHED:-}`, so unset and empty both force a fresh lookup. `bin/fm-lint.sh tests/fm-backend-tern.test.sh` now passes with the pinned ShellCheck 0.11.0, and `tests/fm-backend-tern.test.sh` passes with no failures. Behavior portable serial 2 (ci-1) was not caused by this PR, so I made no code change for it. The only failing test was `tests/fm-calm-pi-extension.test.sh`, with the error "grep disappeared from /export calm.html HTML while calm mode was on". The PR doesn't touch any Calm or Pi extension files. CI installs `@earendil-works/pi-coding-agent` unpinned (`.github/workflows/ci.yml:111,224`), so this run got Pi 1.0.4. The 1.0.x line came out on 2026-10-01 at 19:15, after main's last green run at 02:04 that day, and 1.0.4 was published on 2026-10-05. With Pi 1.0.4 installed locally in temp, the test failed the same way on this branch and on the untouched base commit b95d776. The failure comes from upstream Pi 1.0.4 changing its `/export` HTML, not from the Tern backend. It needs a separate Calm/Pi compatibility fix or a pinned Pi version in CI, both outside this PR's scope * fix(bin): publish Tern plugin state on a fresh window's first scan (kunchenguid#25) * tern plugin: publish current-format state as soon as window_pid is known window.luau's last_signature started equal to the empty string, which is also the signature of a window with no agent panes and no fm-* task tabs. A freshly loaded window that resolves window_pid before any pane/tab activity therefore skipped its first scan's write forever, leaving a stale or old-format agents.json from an earlier window in place for however long the window stayed idle - the reader in bin/backends/tern.sh then trusted that stale file as current. Fix: start last_signature as nil, a sentinel no real signature (including the empty one) can ever equal, so the first scan after window_pid is known always publishes. Writes stay change-driven after that. Adds a regression test that drives the real window.luau through a stubbed window-host API via the luau CLI, reproducing the exact empty-signature race and asserting the first write happens in current format (version, window_pid, blocks). Skips cleanly without luau on PATH, matching this suite's existing jq/tern skip convention. * docs: note window.luau's first-write guarantee and its luau-driven test * fix(bin): keep omp workers' worktrees clean and read the running-agent hint as an idle composer (kunchenguid#28) * fix(spawn): opt omp workers out of ONNX Runtime telemetry so no :memory:.ses lands in the worktree omp's local tiny-model worker runs onnxruntime-node 1.30 with the worktree as its cwd. Inside the worker sandbox its Microsoft 1DS telemetry cannot write its database under ~/Library, falls back to an in-memory store, and writes an untracked ':memory:.ses' stamp into the worktree, which made fm-teardown.sh refuse cleanup of finished work. Every omp launch now carries ORT_DISABLE_TELEMETRY=1, ORT's own whole-process opt-out. * fix(composer): read omp's running-agent hint as an idle composer While a subagent runs, omp 18.6.1 right-aligns '←← to see N running agent(s)' on its empty composer row. Its bright keycap survived ghost stripping, so the row read as pending input and doorbells to a worker waiting on its subagent were skipped until the subagent finished. The hint joins the shared idle-placeholder set beside omp's thinking-effort hint; typed text stays pending. A status row carrying the right-aligned session title is pinned as furniture too. * fix(bin): stop Tern tab flicker from omp worker titles and keep firstmate-agents within the timer budget (kunchenguid#30) * tern: keep firstmate-agents inside the timer budget; stop omp title spinner in Tern workers * docs: record Tern 0.6.2 title-overlay and plugin timing evidence * no-mistakes(review): Test Tern omp overlay; stop pid lookup starving scans * no-mistakes(document): Document why plugin pid lookup skips consecutive ticks * no-mistakes(document): Show Tern overlay in omp launch shape * fix(bin): let fm_backend_source load the tern adapter Main now preflights each backend adapter and its sibling libraries from an explicit per-backend list and refuses any backend missing from it, so the ported Tern adapter could not be sourced at all. Add tern with the three libraries bin/backends/tern.sh sources. * docs(verification): record the Tern 0.8.3 live run of the ported backend * docs: add CHANGELOG entry for the Tern runtime backend --------- Co-authored-by: Daniel Kuykendall IV <danielkuykendall23@gmail.com> Co-authored-by: wangyao <wangyao@zhuozhuo.io>
…unchenguid#30) Add fm-home-port verify and advisory --warn-machine-local (shared PII patterns via fm-leak-lib.sh with the CI leak guard), fm-bootstrap manifest for cross-machine toolchain fidelity, and document step-zero push-before-bootstrap. Stale pre-merge branch fallback was already removed in kunchenguid#26.
…ship room (kunchenguid#30) * feat(bin): wake the first mate when something new arrives in a Mothership room Add Mothership monitoring, a per-room setting that is off by default. config/mothership-monitor holds one `<room> = on|off` line per joined room; a room not listed, or the file absent, is off and nothing runs. bin/fm-procevent-mothership.sh is a built-in process-event adapter. Each switched-on room long-polls `mothership pull --from <place> --wait 55 --max 50`, a read that leaves plain pull's saved place alone, so the monitor keeps its own place under state/mothership/. The place moves only after the runner has durably captured a batch (autohandle), a move with nothing for the ship is saved inside the source so the long poll does not spin, an unreachable room costs one attempt a minute, and a refused key or repeated unexplained failures end the source with one wake. The first mate reads each capture with `read`, tells the owner in plain words, and runs `told`, which records what was told so a batch captured twice after a crash is told once. It only reads and tells: room text is data, and taking a request on still needs the owner's yes. `on` checks the room is joined and the link supports `position`, seeds the place from plain pull's saved place or the room's current end, and lists open requests; `off` hands the place back. Session start runs `ensure` to arm on rooms and retire the rest, printing MOTHERSHIP_MONITOR lines for problems. Docs: a configuration section, the process-event-sources handling steps, the bootstrap diagnostic, the home layout entries, scripts.md and the changelog. Tests use a scripted stand-in for the link with invented members, including a run through the real runner. * no-mistakes(review): Drop on --now and keep the told mark contiguous * no-mistakes(review): Warn instead of wedging when an earlier batch was never told * no-mistakes(review): Drop the told gap warning and simplify empty moves * no-mistakes(document): Clarify that Mothership told acknowledges the capture itself * no-mistakes(ci): Root cause: "Full suite" only collects the results of the other jobs. It failed because "Behavior portable serial 9" hit GitHub's 30-minute job limit and was cancelled at 30m15s, while running the 26th of its 27 scripts. No test failed; every script that finished exited 0. How this PR caused it: CI splits the serial tests into 13 shards using a table of expected durations (portable_serial_weight_hints in bin/fm-test-run.sh). The PR adds tests/fm-procevent-mothership.test.sh with no entry, so it was counted at the 45000 ms default. It also made tests/fm-bootstrap.test.sh take 159898 ms, while its entry still said 50965. Those two wrong numbers changed which tests share each shard. Shard 9 got fm-remote-secondmate-lifecycle-e2e (entry 345655 ms, real about 778000) plus other slow work. On main that shard already takes 27m43s. Invariant: every serial test this change adds or makes slower must have a measured duration entry, so the split does not push a shard past the job limit. The only places this applies are those two rows. Fix: - bin/fm-test-run.sh: added `tests/fm-procevent-mothership.test.sh 21282` and changed `tests/fm-bootstrap.test.sh` from 50965 to 159898. Both are the Ubuntu durations measured in this PR's CI run 42535380691. - docs/fm-test-portable-shards.md: recorded both values and the run they came from, as that doc requires, with a note that a full table refresh is still due. Verification: - tests/fm-test-run.test.sh passed all 47 cases (exit 0). - `bin/fm-test-run.sh --check-coverage` passes (serial_max_ms=1112995, under the 1200000 budget). - `bin/fm-fork-surface.sh check` reports OK. - I replayed the shard split against the real per-test durations from this run and main's last green run. Before the fix, shard 9 comes out at 30.0 minutes, which matches the timeout. After it, the slowest shard is about 27.9 minutes, the same margin main has today. Not changed (reported only): many other entries in the table are also too low, and most of that was already true on main. With every entry corrected, the 13 shards would each take about 21.8 minutes. That is over the 20-minute target the coverage check enforces, so it would also need a 14th serial shard, which means changing ci.yml, windows-wsl.yml and the docs. That is CI capacity work outside this PR and was not done. The cancelled "Behavior portable serial 9" check (ci-2) is the same timeout this fix addresses * no-mistakes(review): Bound Mothership link calls and correct shard hint note * no-mistakes(review): Report Mothership link timeouts plainly in ensure and on * no-mistakes(document): Document the 20 second Mothership link bound
Intent
Close #27's chat-mode wake-routing gap (the P2 layer #29 deferred) with a presence-gated sub-supervisor: the daemon self-handles routine wakes in bash and escalates only captain-relevant events as one batched digest, cutting ~65–75% of supervision tokens — but only while the captain is away (
/afk). When the captain is present, full per-wake responsiveness is the default. This pivot follows the maintainer's design direction (comment): the token win and the behavior change are the same mechanism, so the boundary that matters is presence, not user identity.What Changed
Presence-gating via
/afk(the pivot). The daemon is neither default-on nor standalone opt-in — it is presence-gated. The new/afkskill (.agents/skills/afk/SKILL.md) is the trigger: invoking it sets a durablestate/.afkflag and starts the daemon. The daemon injects escalations only while that flag exists; when afk is off, it self-handles and stays quiet, and the base one-shotfm-watch.shprotocol is active. Exit is automatic: any real (unmarked) message clears the flag, flushes a "while you were out" catch-up, and resumes full per-wake responsiveness. No/backneeded.In-band sentinel marker (the load-bearing detail). The daemon injects into the same pane the captain types into, so an escalation would otherwise cancel afk the moment it fired. Fix: every injection is prefixed with
FM_INJECT_MARK(ASCII unit separator, 0x1f) — invisible and untypable. Firstmate's contract: leading marker → internal escalation (stay afk); no marker → captain is back (exit afk)./afkinvocations are exempt so they don't self-cancel. Bias ambiguous cases toward exit (a false exit is self-correcting). The marker travels with the message text — no reliance on non-portable harness-level typed-vs-injected detection.Four injection fixes (from the maintainer's review, folded under
/afk):-separator, so submission viasend-keys+ Enter is unambiguous regardless of TUI composer behavior.pane_is_busyon firstmate's own pane and defers (leaves the escalation buffered) if it is in use. Belt-and-suspenders in afk mode, but protects against firstmate being mid-turn.send-keys+ Enter, verifies the pane content changed; a swallowed Enter triggers a bounded retry (FM_INJECT_CONFIRM_RETRIES, default 3) so an escalation is never lost silently.FM_SUPERVISOR_TARGET, then$TMUX_PANE(inherited from the launching pane), thenfirstmate:0fallback with a warning. Replaces the hardcoded default.Orthogonal to yolo. afk changes how aggressively firstmate surfaces things, not who approves what. "Away" never means "approves more."
Files
bin/fm-supervise-daemon.sh: presence-gating (afk_active/afk_enter/afk_exit), sentinel marker (FM_INJECT_MARK), afk-exit contract (should_exit_afk), single-line digest (_collapse_newlines), busy-guard + turn-confirmation + auto-discover ininject_msg, auto-discovery at startup (discover_supervisor_target)..agents/skills/afk/SKILL.md(new): the/afkskill — sets the durable flag, ensures the daemon is running, documents the exit contract and marker.AGENTS.md§8: sub-supervisor section rewritten for presence-gating (/afktrigger, marker contract, exit rules, four injection fixes). §5 recovery re-enters afk ifstate/.afksurvives a restart. §2 layout documentsstate/.afk.README.md: sub-supervisor overview, toolbelt entry, and config section updated for presence-gating.tests/fm-wake-queue.test.sh: +8 new tests (34 total) covering afk-absent-no-inject, afk-present-marker-prefix, single-line digest, busy-guard deferral, marker detection,/afkturn exemption, and afk-inactive no-exit.The core watcher, the durable wake-queue, the singleton lock, and
fm-wake-drain.share untouched. The lossless backstop holds regardless of afk state.Risk Assessment
✅ Low. The change is bounded to the daemon's injection path, a new skill file, docs, and tests. The lossless backstop (
fm-wake-drain.sh+state/.wake-queue) holds: escalations that arrive while afk is off buffer instate/.subsuper-escalationsand are flushed on the next catch-up. The marker and busy-guard are additive safety layers. The daemon is not armed until the captain explicitly invokes/afk.Testing
bash tests/fm-wake-queue.test.sh— 34/34 ok (11 wake-queue + 15 sub-supervisor classifier + 8 afk/presence-gating).shellcheck bin/*.sh tests/*.sh— clean.Closes #27.
AI disclosure: Human-reviewed (autonomous crewmate implementation per the maintainer's design direction in PR #30 comments; no-mistakes-validated on prior commits).