Skip to content

fix: persist watcher wakes across supervision gaps - #29

Merged
kunchenguid merged 4 commits into
mainfrom
fm/fm-wakequeue-p1-w2
Jun 20, 2026
Merged

kunchenguid merged 4 commits into
mainfrom
fm/fm-wakequeue-p1-w2

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Implement Phase 1 of GitHub issue #27 for firstmate supervision reliability. Preserve the current one-shot watcher model while adding a durable tab-separated state/.wake-queue, atomic fm-wake-drain.sh, portable mkdir-based watcher singleton and queue locks, enqueue-before-suppress semantics for signal/stale/check/heartbeat wake paths, guard warnings for pending queued wakes, and minimal AGENTS.md/README documentation noting P2/P3 are deferred. Add fast behavior tests using temp state roots for concurrent append/drain safety, catch-up signals, stale enqueue ordering, singleton enforcement, atomic drain dedupe, stale lock reclaim, guard warning behavior, plus CI coverage for those tests.

What Changed

  • Added a durable tab-separated state/.wake-queue with locked enqueue/drain helpers so watcher wakes are recorded before suppression markers advance and can be recovered atomically after interruptions.
  • Hardened watcher and guard behavior around singleton locks, stale heartbeat recovery, queued wake warnings, and recovery ordering so operators drain pending wakes before re-arming supervision.
  • Documented the queued wake recovery flow and added focused shell tests plus CI coverage for queue safety, watcher catch-up paths, stale lock handling, and guard warnings.

Risk Assessment

✅ Low: Captain, the change is well-bounded to watcher queueing and documentation, and I did not identify material correctness or recovery regressions in the diff.

Testing

Inspected the watcher, guard, drain, CI, and docs changes, ran the focused wake-queue behavior suite via both shell and exact CI-style invocation, and produced a manual CLI transcript showing catch-up signal detection, durable queue persistence, guard warning, drain dedupe, and empty queue after drain; all checks passed.

Evidence: Behavior test output
ok - concurrent append plus drain preserves queue records
ok - signal written while no watcher runs is caught on next run
ok - stale wake is queued before suppressor state is advanced
ok - check output is queued before cadence suppression
ok - simultaneous watcher starts leave exactly one live process
ok - two atomic drains cannot consume the same records twice
ok - drain collapses obvious duplicate heartbeat and signal records
ok - killed watcher stale lock is reclaimed
ok - live watcher lock with stale heartbeat is actionable
ok - guard warns when queued wakes are pending
ok - guard orders watcher re-arm after queued wake drain
Evidence: Manual wake-queue CLI transcript
Manual durable wake queue CLI verification
State root: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state

$ printf status > state/task.status  # done while no watcher process is running
status: done: queued while no watcher process was running

$ PATH=<fake tmux> FM_STATE_OVERRIDE=<state> bin/fm-watch.sh
watcher stdout: signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status

$ cat state/.wake-queue  # before drain
queue-before: 1781944964	1	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status
queue-before: 1781944964	2	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status

$ FM_STATE_OVERRIDE=<state> FM_GUARD_GRACE=999999 bin/fm-guard.sh 2>&1
guard stderr: WARNING: queued wakes pending - drain them with bin/fm-wake-drain.sh before anything else.

$ FM_STATE_OVERRIDE=<state> bin/fm-wake-drain.sh
drain stdout: 1781944964	2	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status

$ test ! -s state/.wake-queue && printf "queue empty"
queue empty
Evidence: Queued signal before drain
1781944964	1	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status
1781944964	2	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status
Evidence: Drain output after dedupe
1781944964	2	signal	task.status	signal: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state/task.status
Evidence: Guard pending-queue warning
WARNING: queued wakes pending - drain them with bin/fm-wake-drain.sh before anything else.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (2) ✅
  • ⚠️ bin/fm-watch.sh:22 - The singleton path trusts any live PID in .watch.lock and exits before checking whether the watcher heartbeat is stale. If the current watcher is alive but wedged, the guard will tell the operator to re-arm the watcher, but every re-arm attempt just prints already running, leaving supervision without a working watcher. Reclaim based on a stale heartbeat or return an actionable failure instead of silently no-oping.
  • ⚠️ AGENTS.md:196 - The recovery checklist drains queued wakes only after reading status files, peeking orphan panes, and surfacing decisions. That conflicts with the new section 8 rule that recovery must drain the durable queue first, so a restarted agent can still consume state out of order. Move fm-wake-drain.sh ahead of the status/pane reads in this checklist.

🔧 Fix: Captain, harden watcher recovery flow
2 warnings still open:

  • ⚠️ bin/fm-guard.sh:36 - When queued wakes exist and the watcher beacon is also stale or missing, the guard now prints both "drain them ... before anything else" and the old final "Restart it NOW, before anything else" instruction. That is the main missed-wake recovery path, so the tool gives contradictory ordering and can steer the operator to re-arm before draining the durable queue. Make the liveness instruction conditional, for example: drain queued wakes first, then re-arm the watcher.
  • ⚠️ AGENTS.md:188 - The recovery checklist drains and removes queued wake records before acquiring the single-firstmate session lock. If a restarted or secondary firstmate session runs this while another live session holds state/.lock, it can consume that session's wake queue and only then discover it must operate read-only. Acquire the session lock before the destructive drain, while still draining before pane/status inspection.

🔧 Fix: Captain, fix queued wake recovery ordering
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-wake-queue.test.sh
  • tests/fm-wake-queue.test.sh
  • Manual CLI scenario with FM_STATE_OVERRIDE=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVJ1ZJZWJWZZ3RN96XFWP4JF/wakequeue-signal-e2e/state: created task.status while no watcher was running, ran bin/fm-watch.sh, inspected state/.wake-queue, ran bin/fm-guard.sh, drained with bin/fm-wake-drain.sh, and verified the queue was empty
  • git status --short --ignored to confirm testing left no transient files in the worktree
⚠️ **Document** - 1 error
  • 🚨 Captain, I’m blocked by conflicting instructions: AGENTS.md says I must not edit worktrees directly and must delegate project-specific work, while this task explicitly requires documentation-only edits in the current worktree. Please confirm whether I should make the docs edits here or stop without modifying the worktree.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kyokosawada

Copy link
Copy Markdown

Shipped. The phone app is built and in use on main: it reaches the machine and shows the fleet (#38, #39), opens a pane as chat (#40), answers by voice (#41) and keyboard (#44), watches a pane live and flags the one that needs you (#42), and reports failures plainly (#43). A first working Viu is on the phone. Closing as delivered.

@maaz-codes

Copy link
Copy Markdown

The Land Inspection agent, on n8n

The ministry already hosts and maintains n8n. That is the best available answer
to who runs this in a year, which is the question the whole project turns on.
This lane takes that answer seriously and builds the shape that survives it.

n8n owns the clock, the pause, the approval queue and the run history a
successor can click through. Python owns everything that computes, signs or
sends.
An evaluation of n8n 2.36.7 ran twelve experiments and proved both
halves: n8n hosts a genuine agent loop, and it cannot host this agent's hard
parts. Its Code node cannot require('crypto'), it ships no Word node among 308,
no JavaScript library anywhere implements the bidi isolate rule that stops
-3.2% rendering as %3.2-, and it deletes its own execution history after
fourteen days.

Where it stands

Practice suite 43 of 43
selftest 64 checks, synthetic records only
Generated months checked against an independent implementation 330, every figure agreeing, no clean month raising a question
The sealed suite's own families, rehearsed on the live workbook reproduction from an unseen path, an identity-preserving rewrite, determinism, state isolation — all clean
Prompt injection, live model, three payloads refused 3 of 3
The live workbook after every run byte-identical

The three months the section head confirmed reproduce exactly, cell for cell, and
so does 2025-10 — the month where every counting rule visibly parts company.

What it does that is worth arguing about

It stops. Exit 10, no documents, and the question in words she would use,
with both readings and their figures and the rows behind them. Eight fault
classes, each asking the same question — would a second honest reading give a
different published figure?
— and silent when the answer is no. All nineteen
months in the live workbook close without raising one.

It never tells you the data is clean. result.json carries checks_run[]:
one line per check, each a count taken during the run, in fixed words this
build owns. There is no sentence anywhere that a model wrote about the data.
That is not a general principle we happened to hold — it is the answer to a
specific attack another lane demonstrated tonight, where a model wrote "no
irregularities were found in the data"
into an approval pack while the payload
sat in that data.

The closing phase has no send capability in it. Not restricted, absent.
Five tools, no sixth. The same attack that reached send on another foundation
three runs out of three has nothing here to reach, and
tests/injection_probe.py runs it against a live model to show that rather than
claim it.

The approval covers what she was shown. Every figure, every ruling that was
in force, every note, every question, every document. Delete a note naming a
thirty-four-point rise after approval and the approval stops verifying —
otherwise her signature ends up on a quieter document than the one she read.

A stale ruling announces itself. rules_applied[] carries every ruling in
force, including ones that changed nothing, each with its scope, its date, and
its measured effect: "changed the figures for this month: establishments 97.0%
to 94.8%"
, computed by closing the month again without it.

Three defects found the expensive way, recorded rather than tidied away

  1. ~/.landagent was shared with two other builds on this machine, and a
    ruling this build had never been given had already changed every published
    figure in one run, reporting a clean close. State now resolves as --state,
    then LANDAGENT_STATE, then a directory inside the working tree, with no
    shared fallback. docs/state-isolation.md records what was and was not
    exposed, checked rather than assumed.
  2. A vehicle both caught and corrected in one month was counted twice. Every
    published month still reproduced, because no published month contains one.
    Reproducing twelve real months proves less than it feels like it proves.
  3. A licence number retyped in Arabic-Indic digits splits one company in two.
    The denominator gains one and the ratio moves silently. It stops and asks,
    because folding two spellings into one identity would change a published
    denominator on our own judgement, and identity belongs to the section.

Not merged

The captain picks in the morning. Two other lanes are building the same agent on
different foundations.

@maaz-codes

Copy link
Copy Markdown

Where this lane ended

43 of 43 on the practice suite. The engineering below is the part I would defend; the argument
for this lane is the part above it.

The lane's argument, in one paragraph

The ministry already hosts and maintains n8n, and that is the best available answer to who runs this
in a year
. So: n8n owns the clock, the pause, the approval queue and a run history a successor can
click through; Python owns everything that computes, signs or sends.
The workflow was imported and
run end to end against a live n8n 2.36.7, and the gate refused an unapproved resume. ⚠️ Honestly:
the hybrid removes about one week of the three-to-four weeks of IT, and it removes the easy week.

What it does remove entirely is the list of instance-wide n8n changes a ministry admin must approve,
which is now empty, and the fourteen-day retention default as a reason to refuse — because the record
lives on our side, EXECUTIONS_DATA_SAVE_ON_SUCCESS=none becomes a reasonable setting rather than a
loss, and that removes the classification problem in the same move.

Measured

Practice suite 43 of 43
selftest 81 checks, synthetic records only
Guards broken on purpose and seen to fire 39 behaviours
Generated months against an independent implementation 360+, every figure agreeing
Injection, live model, three payloads refused 3 of 3
Approved pack rebuilt from its own recorded trail byte for byte
Bad input at every entry point nothing answered from absence
The live workbook after every run byte-identical

tests/run_all.sh "<workbook>" runs all of it.

The two things worth the captain's attention

⭐ Rendering one finished document and looking at it found the entire rules section in English
inside an Arabic document, on a page where every character check passed and every figure was right.
The spec says plainly that it checks characters and does not render — so no suite on any foundation
could have found it. Then reading it found the sentence explaining a movement replaced by a line
saying the sentence had been withheld, on every month that moved. Rendering catches what a document
looks like; reading catches what it says. Both are now written into the README as required steps
before hand-over.

⭐ A confidentiality audit of the produced pack found three of four categories of internal material
on a page addressed to the Finance Department: the Head of Section named as the source of a
statement, our own tally of which rules reproduce which months, and a characterisation of how her
record was typed. Fixed at the data level — documents read only public_* fields with no fallback —
because a convention would not have held.

What is not proven, named rather than hidden

  • Nobody who reads Arabic has read a document this build produced. I looked at one; I am not the
    reader.
  • It has never run in a container, which is what the cyber review actually reviews.
  • It has never touched a mail server. "It sends once she approves" is unproven; only the
    refusal path is demonstrated.
  • The workflow ran against a local n8n, never the ministry's, whose edition, version and node
    exclusions are unknown. Four questions can kill this lane in one word each.
  • The injection result is one model. The structural argument — there is no send capability to
    reach — is what should hold, not the observation.

data/report.md in the lane home carries the full account, including what a maintainer must not
undo
: thirteen controls, each with one line on what breaks if it is removed.

Not merged.

BenjaminLu added a commit to BenjaminLu/firstmate that referenced this pull request Sep 19, 2026
A project clone commonly carries an `upstream` fork parent beside
`origin`, and gh-axi may resolve that one. Verified against this clone:
`gh-axi pr view 29` returned kunchenguid#29 - a different,
already merged pull request by another author - instead of the
#29 under review, with no error and entirely
plausible output. `gh-axi pr checks 29` reported that other pull
request's checks the same way. The mismatch surfaces only on a write,
and then as a confusing message about blank shas.

A reviewer following a brief built on bare commands would read a
stranger's pull request, review it, and post findings on the wrong
repository. Every gh-axi command the review brief generates and the
pr-review skill prints now carries -R <owner>/<repo>, taken from the
reviewed pull request's own URL, which is the only authority on where
that pull request is. The head checkout goes through `gh-axi pr checkout`
rather than a hand-written fetch from `origin`, for the same reason.

docs/verification/pr-review.md records this and the two other vendor
facts the contract states: GitHub refuses an approve review on a pull
request opened by the same account, so the reviewer posts a comment
review carrying its verdict in the body, and that review reads back
through `gh-axi pr view --reviews`.

Tests cover the new brief kind and its dispatch, including a direct
assertion that no gh-axi command in a generated review brief omits its
repository. Each new assertion was confirmed to fail against a mutated
source before being trusted.
BenjaminLu added a commit to BenjaminLu/firstmate that referenced this pull request Sep 19, 2026
)

* feat(bin): review a pull request with a dedicated reviewer crewmate

Replace the in-session validation pipeline as the default rigor for a
direct-PR ship with a reviewer that posts its findings on the pull
request, where the captain can read them.

bin/fm-brief.sh --review <github-pr-url> writes the reviewer contract and
is its single owner: the four disciplines carried over from the pipeline
(a finding is one instance of a class, read the primary source and name
what you could not verify, separate a defect from a preference, and never
decide a finding that would widen what the captain asked for), the
numbered finding format, and the requirement that the review be posted
and read back. A review is scout-shaped in every mechanical respect, so
it is spawned and torn down as a scout and writes the local pointer the
scout teardown gate requires.

bin/fm-dispatch.sh --review dispatches one in a single call and refuses a
brief whose review shape disagrees with the call.

The new pr-review skill owns the path end to end - who pushes, when the
pull request opens, who reviews, the merge gate, and what happens when
checks are red - plus how firstmate rules on findings, posts the captain's
words verbatim, and lands fixes one finding per commit. It states
explicitly that this is one pass and not a pipeline: no rounds, no
counters, no re-review requirement.

AGENTS.md states the path in one bullet and points at the skill. The
no-mistakes pipeline's code and documentation are untouched; projects that
select it are unaffected.

* fix(bin): name the repository on every gh-axi call a review makes

A project clone commonly carries an `upstream` fork parent beside
`origin`, and gh-axi may resolve that one. Verified against this clone:
`gh-axi pr view 29` returned kunchenguid#29 - a different,
already merged pull request by another author - instead of the
#29 under review, with no error and entirely
plausible output. `gh-axi pr checks 29` reported that other pull
request's checks the same way. The mismatch surfaces only on a write,
and then as a confusing message about blank shas.

A reviewer following a brief built on bare commands would read a
stranger's pull request, review it, and post findings on the wrong
repository. Every gh-axi command the review brief generates and the
pr-review skill prints now carries -R <owner>/<repo>, taken from the
reviewed pull request's own URL, which is the only authority on where
that pull request is. The head checkout goes through `gh-axi pr checkout`
rather than a hand-written fetch from `origin`, for the same reason.

docs/verification/pr-review.md records this and the two other vendor
facts the contract states: GitHub refuses an approve review on a pull
request opened by the same account, so the reviewer posts a comment
review carrying its verdict in the body, and that review reads back
through `gh-axi pr view --reviews`.

Tests cover the new brief kind and its dispatch, including a direct
assertion that no gh-axi command in a generated review brief omits its
repository. Each new assertion was confirmed to fail against a mutated
source before being trusted.

* docs(scripts): record the review brief and its dispatch note in the toolbelt index

* fix(bin): validate a review URL on the dispatch path that reuses a brief

fm-dispatch.sh's own contract is to validate every input before touching
anything, but --review was checked only by bin/fm-brief.sh. A brief that
already exists is reused without calling it, so on that path nothing
stood between a malformed or non-GitHub URL and the backlog note that
records it. The check now runs at step 1 through the shared PR parser,
where the contract says it belongs, and a test drives the reuse path
specifically.

* style(bin): match the scope discipline's wording to the finding field it names

The discipline said to mark a finding `widens scope: yes` while the
template field is `Widens scope:`, so the instruction did not name the
field the reviewer is filling in.

Also split a two-sentence line in the pr-review skill to keep the repo's
one-sentence-per-line rule.
NewAiCoder added a commit to NewAiCoder/firstmate that referenced this pull request Sep 26, 2026
…tream-3

chore(harness): sync fork main with upstream/main (repair ancestry break)
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
* Add capability outcome log and dispatch-time evidence reader.

Record harness/model/effort outcomes at teardown, rank or advise within
cost-allowed dispatch profiles, and keep scout-tax suggestions advisory.

* fix(tests): symlink capability lib in gotmp teardown fixtures.

Teardown now sources fm-capability-lib.sh, so the fake FM_HOME bin/
must expose it the same way as the other sourced helpers.
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
…nguid#31)

* Polish onboarding and port verify for beginner-safe touch-ups.

Name the firstmate folder in the slug-test prompt, treat missing jq as an
advisory in the Herdr protocol probe, avoid exit in the pasted checkpoint,
and label verify's un-failable .env check as VERIFY_INFO.

* Fix backend conformance fixture for capability-lib source.

fm-teardown.sh gained a source of fm-capability-lib.sh in kunchenguid#29; the old-vs-new
shim must symlink that sibling or the extracted BASE_REF teardown aborts.
@nicolevanderhoeven

Copy link
Copy Markdown

Screenshots and applied migrations (author's note)

fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 18, 2026
…ream-catchup-2026-11-08

feat(bin): catch up with upstream firstmate through 47e07b4
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.

4 participants