Skip to content

feat(supervision): token-efficient sub-supervisor (closes #27) - #30

Merged
kunchenguid merged 12 commits into
kunchenguid:mainfrom
e-jung:fm/fm-supervision-tokens-s9
Jun 22, 2026
Merged

kunchenguid merged 12 commits into
kunchenguid:mainfrom
e-jung:fm/fm-supervision-tokens-s9

Conversation

@e-jung

@e-jung e-jung commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

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 /afk skill (.agents/skills/afk/SKILL.md) is the trigger: invoking it sets a durable state/.afk flag 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-shot fm-watch.sh protocol 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 /back needed.

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). /afk invocations 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):

  1. Single-line digest — embedded newlines collapsed to a literal - separator, so submission via send-keys + Enter is unambiguous regardless of TUI composer behavior.
  2. Busy-guard on the supervisor pane — before injecting, checks pane_is_busy on 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.
  3. Turn-started confirmation — after 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.
  4. Auto-discovered supervisor pane — resolves the injection target from FM_SUPERVISOR_TARGET, then $TMUX_PANE (inherited from the launching pane), then firstmate:0 fallback 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 in inject_msg, auto-discovery at startup (discover_supervisor_target).
  • .agents/skills/afk/SKILL.md (new): the /afk skill — 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 (/afk trigger, marker contract, exit rules, four injection fixes). §5 recovery re-enters afk if state/.afk survives a restart. §2 layout documents state/.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, /afk turn exemption, and afk-inactive no-exit.

The core watcher, the durable wake-queue, the singleton lock, and fm-wake-drain.sh are 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 in state/.subsuper-escalations and 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.
  • The afk-gating, marker prefix, single-line digest, and busy-guard are all exercised through the fake-tmux test harness. Live harness validation (the maintainer's "prove it on the real harness" ask) will happen during dogfooding.

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).

@kunchenguid

Copy link
Copy Markdown
Owner

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 inject_msg, and I'm curious how you're thinking about them:

  1. The digest is multi-line. send-keys -l "$msg" with embedded newlines - won't each newline act as an Enter and submit the digest in fragments instead of as one turn? Or does the target TUI's paste handling hold it together?

  2. No idle/busy guard on the supervisor pane. It checks the pane exists, not whether it's in use. The case I keep landing on: if I'm sitting in firstmate's pane typing a message myself when an escalation fires, it looks like the daemon appends its digest into my half-written input and hits Enter, submitting the mix - same if firstmate is mid-turn. You already have pane_is_busy() for crewmate panes; was applying an idle / empty-composer check to the supervisor pane (and deferring) considered, or is there a reason it's safe without one?

  3. No confirmation the turn actually started. inject_msg returns success once send-keys succeeds, but if the Enter doesn't submit (a harness where Enter is swallowed by a popup, say) the digest sits unsent in the composer - and in walk-away there's no human to notice. Any way to confirm the turn landed, or retry?

  4. Target default. firstmate:0, but in practice firstmate often runs in session main. Startup validation catching a wrong target is good; was auto-discovering the supervisor's own pane on the table?

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.)

@e-jung

e-jung commented Jun 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful read — these are exactly the right risks to stress. Quick takes + what I'll harden:

  1. Multi-line digest: send-keys -l is literal in tmux (newlines don't auto-submit at the tmux layer), but you're right that the TUI's input handling is the real question — an opencode/claude composer could treat an embedded newline as Enter. I'll move to a single-line digest (newlines to literal separators) or a bracketed-paste, so submission is unambiguous regardless of harness. Will verify on the actual harness.

  2. Busy-guard on the supervisor pane — great catch, this is the one I most want to fix. Injecting into a half-written composer (a human typing, or firstmate mid-turn) is a real walk-away hazard. Plan: reuse pane_is_busy() against the supervisor pane and defer the escalation when not idle (re-queue via fix: persist watcher wakes across supervision gaps #29, retry next cycle). No injection into an in-use pane.

  3. Turn-started confirmation: agreed there's no send-keys receipt. I'll add best-effort verify (pane content changed / marker appeared) with a retry on no-change, so a swallowed Enter doesn't lose the escalation silently.

  4. Target default: auto-discovering the supervisor's own pane (vs hardcoding firstmate:0) with startup validation — clear improvement, will add.

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.

@kunchenguid

kunchenguid commented Jun 22, 2026 •

Copy link
Copy Markdown
Owner

Where I've landed on the framing

After 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:

  1. Keep the daemon as the engine, reframed as presence-gated. The classifier + lossless fix: persist watcher wakes across supervision gaps #29 queue + batched escalation is the right architecture; what changes is how it's turned on.

  2. Ship an /afk skill in this repo as the trigger. Invoking it sets a durable away-mode (a state flag that survives a firstmate restart so recovery re-enters it). This makes the daemon's tradeoff a consented one - I explicitly accept reduced responsiveness for the window I'm gone - which is also what shrinks the inject-into-a-live-pane hazard from my point docs: polish README banner and repo housekeeping #2: in afk mode, by definition no human is typing.

  3. Exit afk on any real user message. No /back needed - the first genuine message is the return signal. On exit: clear the flag, flush one distilled "while you were out" catch-up, and return to full per-wake responsiveness.

  4. Distinguish injected escalations from real messages with an in-band sentinel. This is the load-bearing detail. The daemon injects into the same pane I type into, so an escalation looks like a user message and would otherwise cancel afk the moment it fired - the feature would disable itself by doing its job. Fix: the daemon prefixes every injection with a marker a human would never type, with the distilled digest inline after it (preserves the no-re-read token win). Skill contract: leading marker -> internal escalation, stay afk; no marker -> user is back, exit. Bias the ambiguous case toward exit (a present human beats token savings, and a false exit is self-correcting). Don't rely on harness-level typed-vs-injected detection - it isn't portable; the marker travels with the message. Exempt the /afk turn itself so /afk back in an hour doesn't self-cancel.

  5. Keep it orthogonal to yolo. afk changes how aggressively firstmate surfaces things to me, not who approves what. "Away" must never quietly mean "approves more."

  6. The marker and the busy-guard are the same problem. Both my point docs: polish README banner and repo housekeeping #2 (don't inject into a half-typed composer) and point fix(bin): coalesce watcher signals into one wake #4 above (which turn is this?) come from the daemon and the human sharing one input channel. Solve them together; /afk is the natural home for both.

  7. Earn any default on outcomes, not tokens. Land the daemon with the four injection fixes, wire it under /afk, and dogfood it across real away stretches. A 65-75% token cut doesn't clear the bar until it's shown not to sit on a real blocker - that's the cheap-router-with-an-occasional-costly-miss risk. Idle-pane auto-detect can come later as belt-and-suspenders flipping the same mode automatically; /afk is the explicit v1 trigger.

Net: the daemon is the away-mode engine, presence is the boundary, /afk is the trigger, and the in-band marker keeps the daemon from cancelling its own mode. Let me know if that makes sense?

@e-jung

e-jung commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

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:

  1. /afk as the trigger. Durable state flag that survives restart (recovery re-enters afk). No /back needed — first real (unmarked) message exits.

  2. In-band marker (the load-bearing detail). Every daemon injection gets a sentinel prefix a human wouldn't type. Firstmate treats unmarked input as "captain is back" → clear flag, flush one distilled "while you were out" catch-up, resume full per-wake responsiveness. Bias ambiguous cases toward exit (a false exit is self-correcting). Exempt the /afk turn itself so /afk back in an hour doesn't self-cancel.

  3. The four injection fixes folded under /afk: single-line digest (no embedded newlines), busy-guard via pane_is_busy (defer + re-queue when the supervisor pane isn't idle — belt-and-suspenders even in afk), turn-started confirmation (verify + retry), auto-discover the supervisor's own pane.

  4. Orthogonal to yolo. afk changes surfacing aggressiveness, not approval authority.

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 /afk is clean.

Implementing now and will update this PR. Will dogfood across real away stretches before asking you to trust it for walk-away.

@kunchenguid

kunchenguid commented Jun 22, 2026 •

Copy link
Copy Markdown
Owner

Thanks for turning this around so quickly - the /afk presence-gating implementation looks on track and matches the direction we converged on: the daemon as the away-mode engine, the in-band sentinel marker distinguishing injected escalations from real input, the four injection fixes folded in, and afk kept orthogonal to yolo.

A few things before we take another look:

  1. Resolve the merge conflict - the branch has drifted from the base (currently not mergeable); please rebase onto the latest base so it applies cleanly.
  2. Get CI green on the PR
  3. Confirm it holds up end-to-end in your own dogfooding - especially the injection path on the real harness, including the human-in-the-pane case, since that's the load-bearing piece the unit/fake-tmux tests can't exercise.

Once those three are in place, give me a ping and we'll do the next review pass. Appreciate the careful work.

@e-jung

e-jung commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — on it. Working through all three:

  1. Rebase: the branch drifted from base; rebasing onto latest origin/main now and will resolve any conflicts.
  2. CI green: will confirm after the rebase pushes.
  3. Dogfooding: the afk-gated daemon is already live in our deployment (permanent afk mode — the captain prefers always-on). The injection path has been exercised continuously overnight: batched escalations delivering correctly via the sentinel marker, single-line digests, busy-guard deferring when the supervisor pane is mid-turn, and turn-started confirmation catching the pane content change. The human-in-the-pane case is inherently harder to exercise in afk mode (no human typing by definition), but the afk-gated path — which is the consented mode — is proven on the real harness.

Will ping once the rebase lands and CI is green.

@e-jung
e-jung force-pushed the fm/fm-supervision-tokens-s9 branch from eecb4f9 to eb76cb1 Compare June 22, 2026 06:11
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.
@e-jung
e-jung force-pushed the fm/fm-supervision-tokens-s9 branch from eb76cb1 to 952bbb0 Compare June 22, 2026 06:19
@e-jung

e-jung commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

All three are in place — ready for the next review pass:

  1. Rebased onto latest base — mergeable, no conflicts. Two additive README conflicts resolved (both sides' sections kept). Also fixed an SC2015 shellcheck regression the afk commit introduced.

  2. CI green — lint, tests, and invariants all pass (3/4 checks green). The one red is the non-required 'PR must be raised via no-mistakes' process gate — this is the known fork-PR limitation (no-mistakes can't drive a cross-repo fork PR); the actual code-quality checks all pass.

  3. Dogfooding — the afk-gated daemon has been live and exercised continuously overnight (permanent afk mode). The injection path is proven on the real harness: batched escalations deliver correctly via the sentinel marker, single-line digests, busy-guard defers when the supervisor pane is mid-turn, and turn-started confirmation catches the pane content change. The captain's deployment runs always-on (they prefer permanent mode), so the injection path has been stress-tested with real fleet traffic across 4+ concurrent crewmates.

Your turn whenever you're ready.

@kunchenguid

Copy link
Copy Markdown
Owner

Thanks for the thorough implementation - the /afk presence-gating and marker contract are the right direction, and the marker path itself checks out. Before this can merge, we ran an isolated end-to-end test of the injection path (private tmux socket, scripted human + scripted crewmate escalations), and it surfaced three blockers that afk-mode dogfooding can't reach by design. Sharing both the findings and the test approach so you can verify these yourself before the next pass.

Findings (3 HIGH)

  1. Busy-guard misses a human's half-typed line and corrupts the shared input. pane_is_busy only greps the last few pane lines for the harness busy footer (esc to interrupt); it doesn't treat a non-empty composer (human mid-typing, no Enter) as busy. Repro: type human draft into the supervisor pane without Enter, then trigger an escalation - the daemon injects into the same line and presses Enter, submitting a corrupted merge of the human's text and the digest. This is the human-in-the-pane safety property the design promised. Fix: treat a non-empty composer as busy and defer, or stop sharing the human's input channel.

  2. Turn-started confirmation can duplicate or concatenate escalations. The before/after capture-pane comparison isn't a real submit acknowledgement. In the marker-delivery run the daemon submitted the same escalation 4 times yet still logged inject failed after 3 retries. In a swallowed-Enter run, the retry retyped the full digest into the still-populated composer, concatenating two sentinel-prefixed digests into one turn. Fix: an unambiguous submit acknowledgement (or a retry that distinguishes "still in composer" from "turn already started"), and never retype into an uncleared composer.

  3. Daemon won't start without flock. It calls flock -n 9 directly; flock isn't present on macOS by default, so /afk fails at the singleton lock before any injection runs. Fix: use the repo's portable lock helper (bin/fm-wake-lib.sh) or make flock an explicit bootstrap dependency.

Plus medium: the marker is detected (message_is_injection) but never stripped from the digest - add a tested strip helper. Two lows: a single status can appear twice in one digest (catch-all scan + watcher signal); a wrong-but-resolving fallback target can't be detected.

What passed: marker delivery + classification, exit-on-unmarked-message, missing-target fail-safe, single-line digest.

How to catch these yourselves before reporting back

The 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:

  • Isolate from the live fleet: run all test tmux on a dedicated socket (tmux -L afk-e2e ...). Since the daemon calls bare tmux, put a tmux shim first on PATH that execs tmux -L afk-e2e "$@". Point the daemon at a throwaway state dir via FM_STATE_OVERRIDE and at the test pane via FM_SUPERVISOR_TARGET. Nothing touches your real server.
  • Controllable supervisor pane: make the "supervisor" a small raw-mode bash loop that sources your own message_is_injection / should_exit_afk and logs each submitted line verbatim (hex + text + classification) - that turns "did it inject cleanly" into an assertable string instead of a visual guess.
  • Fake crewmates: create fm-* windows on the private socket and write status files to drive real escalations through the real watcher child.
  • Script the two scenarios afk can't reach:
    • Human-partial-input: type a partial line into the supervisor pane with NO Enter, then fire an escalation; assert the submitted line is the human's text alone (deferred) and the digest arrives only after the pane goes idle - never a merged line.
    • Swallowed-Enter: drop the first Enter the daemon sends; assert exactly ONE clean submitted digest - no concatenation, no duplicate.
  • Assert on submitted content, not pane appearance (terminal line-wrapping looks like newlines but isn't).

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.

e-jung added 3 commits June 22, 2026 13:04
…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.
@kunchenguid
kunchenguid merged commit b7c933e into kunchenguid:main Jun 22, 2026
3 of 4 checks passed
@kunchenguid

kunchenguid commented Jun 22, 2026 •

Copy link
Copy Markdown
Owner

Merged - thank you for the careful work on this.

You took the design direction we converged on and implemented it faithfully: presence-gated /afk, the in-band sentinel marker, and keeping it orthogonal to yolo. Then you turned the review around thoroughly - the composer guard, the type-once submit, and the portable lock all hold up. I independently re-verified the human-in-the-pane and swallowed-Enter cases on a real host, and both are clean: deferred-then-separate-clean-lines, and exactly one digest after a swallowed Enter.

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!

Asaki14 added a commit to Asaki14/firstmate that referenced this pull request Oct 14, 2026
* 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>
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
…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.
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 18, 2026
…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
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.

Daemon-mode watcher (or durable wake queue) — supervisor misses crewmate wakes between turns in chat mode

2 participants