Skip to content

fix: harden away-mode escalation delivery - #54

Merged
kunchenguid merged 7 commits into
mainfrom
fm/afk-invx-i5
Jun 23, 2026
Merged

kunchenguid merged 7 commits into
mainfrom
fm/afk-invx-i5

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Fix the away-mode (/afk) sub-supervisor failure root-caused in data/afk-invx-i5/report.md, where the daemon (bin/fm-supervise-daemon.sh) supervised for 9.5 hours overnight and surfaced nothing: two crewmate pipelines parked at their gates and no escalation ever reached firstmate.

Three fixes, all flowing from one underlying bug — the composer-empty detector only recognized a BARE prompt glyph, but claude (the firstmate harness) draws its input box with box-drawing borders ('│ > … │'), so every idle claude pane was misread as 'pending input' and the daemon deferred 100% of escalations.

(1) RC1a — border-aware composer detection. New shared primitive lib bin/fm-tmux-lib.sh strips the harness's composer box borders (literal-string substitution, bash-3.2 / locale safe) before deciding empty-vs-pending. Deliberate choice: structural border-strip rather than enumerating per-harness regexes, keeping FM_BUSY_REGEX/FM_COMPOSER_IDLE_RE override hooks. The daemon's pane_is_busy/pane_input_pending become thin delegations so existing call sites and unit tests stay stable.

(2) RC1b — max-defer escape so the daemon can never silently wedge. If anything stays buffered past FM_MAX_DEFER_SECS (default 300), housekeeping forces one delivery that bypasses the composer guard on an idle pane (the busy-guard still holds); if even the forced submit can't be confirmed, a rate-limited wedge alarm fires (ERROR log + durable state/.subsuper-inject-wedged marker + tmux status-line flash). The force is throttled to once per max-defer window via the marker so a wedged composer isn't retyped every tick. Accepted tradeoff: a force could merge with a human half-typed line, but only after 300s of failure and only while afk (captain away) — far better than the 9.5h silent no-op.

(3) RC2 — verified submit, shared between the daemon and bin/fm-send.sh via fm_tmux_submit_core. Types once, retries Enter only (never retypes), and confirms via the same border-aware detector, fixing the parallel false 'Enter swallowed' ACK. Deliberate split: the daemon is STRICT (clears its buffer only on a confirmed-empty composer; an unreadable pane is NOT treated as delivered), while fm-send is LENIENT (exits non-zero only on a positively-confirmed swallow; an unreadable pane is assumed sent) so the change can't regress the many existing fm-send steers. fm-send now exits non-zero when a steer's Enter is positively swallowed so firstmate learns it did not land.

Also added 8 regression tests in tests/fm-wake-queue.test.sh (the bug existed because the prior pane_input_pending tests only covered bare prompts, never a bordered composer) and updated docs (.agents/skills/afk/SKILL.md, AGENTS.md §8). Scope: this was a scout investigation promoted to ship; no behavior change beyond these fixes.

What Changed

  • Added shared tmux composer detection and submit helpers that recognize bordered input boxes, preserve idle/busy overrides, and let fm-send.sh report confirmed swallowed submits.
  • Hardened the AFK supervisor daemon so buffered escalations defer safely, use a bounded max-defer escape, and record/clear durable wedge markers without unsafe forced retyping.
  • Updated away-mode docs and expanded wake-queue regression coverage for bordered composers, verified submits, AFK defer behavior, and wedge catch-up.

Risk Assessment

✅ Low: Captain, the change is well-scoped to AFK tmux submission/composer detection with focused regression coverage and no material review findings found.

Testing

Inspected the changed afk and tmux submit paths, ran the focused regression shell suite and private-socket afk E2E test, then captured a preserved private-tmux transcript showing the end-user behavior: pending input is not merged with daemon text, the digest is delivered after the pane goes idle, and a swallowed Enter still produces one clean sentinel-prefixed escalation.

Evidence: private tmux afk evidence transcript

scenario_a_before_enter_digest_count=0 scenario_a_human_lines=1 scenario_a_injection_lines=1 scenario_b_digest_count=1 scenario_b_user_lines=0 scenario_b_digest_hex_prefix=1f manual private-tmux afk evidence passed

manual private-tmux afk evidence
supervisor_pane=%0
scenario_a=partial input defers, then clean injection after idle
scenario_a_before_enter_digest_count=0
scenario_a_human_lines=1
scenario_a_injection_lines=1
scenario_a_submitted_log:
  68756d616e2064726166742074657874	human draft text	user
  1f53757065727669736f7220657363616c61746520282020202020202031206576656e74287329293a2066616b652d63312e7374617475733a20646f6e653a2050522068747470733a2f2f6578616d706c652e746573742f70722f313030202863617463682d616c6c207363616e2920287072652d726561643b2072652d61726d206e6f74206e656564656420e280942077617463686572206461656d6f6e2d6d616e6167656429	�Supervisor escalate (       1 event(s)): fake-c1.status: done: PR https://example.test/pr/100 (catch-all scan) (pre-read; re-arm not needed — watcher daemon-managed)	injection
scenario_b=first Enter swallowed, retry submits one clean injection
scenario_b_digest_count=1
scenario_b_user_lines=0
scenario_b_digest_hex_prefix=1f
scenario_b_submitted_log:
  1f53757065727669736f7220657363616c61746520282020202020202031206576656e74287329293a2066616b652d63312e7374617475733a20646f6e653a2050522068747470733a2f2f6578616d706c652e746573742f70722f323030202863617463682d616c6c207363616e2920287072652d726561643b2072652d61726d206e6f74206e656564656420e280942077617463686572206461656d6f6e2d6d616e6167656429	�Supervisor escalate (       1 event(s)): fake-c1.status: done: PR https://example.test/pr/200 (catch-all scan) (pre-read; re-arm not needed — watcher daemon-managed)	injection
manual private-tmux afk evidence passed
Evidence: afk inject private-socket E2E output

ok - Scenario A: partial input defers injection; digest arrives clean after idle ok - Scenario B: swallowed Enter produces exactly one clean digest all e2e injection tests passed

ok - Scenario A: partial input defers injection; digest arrives clean after idle
ok - Scenario B: swallowed Enter produces exactly one clean digest
all e2e injection tests passed
Evidence: wake queue and afk regression output

Targeted regression transcript with 57 ok lines, including bordered composer idle detection, bordered submit ACK, max-defer alarm and recovery, and fm-send nonzero exits on confirmed swallow.

ok - supervise daemon state root is scoped by FM_HOME
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
ok - routine signal self-handles
ok - captain-relevant status verbs escalate
ok - check + unknown escalate; heartbeat self-handles
ok - transient stale self-handles and records a persistence marker
ok - stale + terminal status escalates immediately
ok - persistent stale escalates after threshold and clears its marker
ok - resumed (busy) stale clears its marker without escalating
ok - multiple escalations flush as a single batched digest
ok - batch flush measures max-delay from the first append, not the last
ok - catch-all scan escalates a missed terminal once, not twice
ok - handle_wake routes routine->self and captain->escalate
ok - INJECT_SKIP forces self-handle, bypassing captain-relevant classification
ok - is_wake_reason distinguishes watcher wake reasons from singleton-status stdout
ok - terminal-stale escalate removes its marker so housekeeping does not re-escalate
ok - captain signal escalate marks seen so the catch-all scan does not re-fire
ok - _collapse_newlines replaces newlines with literal separator
ok - afk flag absent: daemon does not inject, buffer preserved
ok - afk flag present: daemon injects with sentinel marker prefix
ok - injected digest is single-line (no embedded newlines)
ok - busy-guard defers injection when supervisor pane is busy
ok - marker detection: marker -> stay afk, no marker -> exit afk
ok - /afk invocation is exempt from afk exit (no self-cancel)
ok - should_exit_afk returns false when afk is not active
ok - strip_injection_marker removes the sentinel marker cleanly
ok - pane_input_pending detects partial input on the cursor line
ok - pane_input_pending: blank cursor line is not pending
ok - pane_input_pending: bare prompts are not pending (idle)
ok - pane_input_pending honors FM_COMPOSER_IDLE_RE after border stripping
ok - composer guard defers injection when pane has pending input
ok - swallowed Enter: type-once + Enter-retry, no concatenation
ok - normal inject: exactly one digest, one Enter, no duplicates
ok - classify_signal dedupes against the catch-all scan seen marker
ok - classify_stale dedupes against the signal path seen marker
ok - pane_input_pending: an idle bordered composer is NOT pending (afk-invx-i5)
ok - pane_input_pending: text inside a bordered composer is still pending
ok - submit-ACK confirms a submit when the composer returns to a bordered-empty box
ok - submit-ACK reports pending on a persistently swallowed Enter (type-once)
ok - max-defer on an empty stuck pane types once, alarms, and preserves the buffer
ok - max-defer flushes and clears the buffer on an empty bordered pane
ok - max-defer on a pending composer alarms without typing
ok - normal flush clears a stale wedge marker
ok - below MAX_DEFER: no inject, no alarm, buffer preserved
ok - max-defer does not flush or alarm while afk is inactive
ok - fm-send exits non-zero on a confirmed swallow, zero on a clean submit
ok - fm-send exits non-zero when initial text send fails
Evidence: manual submitted-line log

Raw submitted-line log from the preserved private tmux evidence run. The digest hex starts with 1f, proving the sentinel-prefixed daemon injection reached the pane as an injection.

1f53757065727669736f7220657363616c61746520282020202020202031206576656e74287329293a2066616b652d63312e7374617475733a20646f6e653a2050522068747470733a2f2f6578616d706c652e746573742f70722f323030202863617463682d616c6c207363616e2920287072652d726561643b2072652d61726d206e6f74206e656564656420e280942077617463686572206461656d6f6e2d6d616e6167656429	�Supervisor escalate (       1 event(s)): fake-c1.status: done: PR https://example.test/pr/200 (catch-all scan) (pre-read; re-arm not needed — watcher daemon-managed)	injection

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (5) ✅
  • ⚠️ bin/fm-tmux-lib.sh:57 - The shared composer detector no longer honors the previously documented FM_COMPOSER_IDLE_RE override. It now only accepts the hard-coded prompt glyphs here, then the busy regex, so any installation that used the override for a custom empty prompt will classify an idle composer as pending until max-defer forces delivery, and fm-send.sh can falsely report a swallowed Enter. Reapply FM_COMPOSER_IDLE_RE after border stripping before falling back to the built-in prompt list.
  • ⚠️ bin/fm-supervise-daemon.sh:429 - A successful normal flush does not clear a prior .subsuper-inject-wedged marker. If a forced inject fails while the supervisor pane is busy, the marker is written; when the pane later becomes idle, the regular batch flush can deliver and clear the buffer through this path, but the stale marker remains for catch-up reporting and also throttles later max-defer force attempts. Clear the wedge marker on any confirmed successful inject, not only on successful forced injects.

🔧 Fix: Fix AFK idle override and wedge cleanup
2 warnings still open:

  • ⚠️ bin/fm-supervise-daemon.sh:501 - The max-defer escape can raise a false wedge while afk is inactive. Buffered escalations are expected to sit quietly when state/.afk is absent, but this block still forces a flush after FM_MAX_DEFER_SECS; inject_msg then fails the presence gate and inject_wedge_alarm writes .subsuper-inject-wedged/flashes tmux for a normal off-afk buffer. Gate the max-defer force/alarm on afk_active "$state" or treat afk-inactive as an ordinary defer.
  • ⚠️ bin/fm-send.sh:58 - fm-send.sh can now report success when the initial tmux send-keys -l fails. fm_tmux_submit_core maps that positive transport failure to unknown, and fm-send.sh treats anything except pending as success, so a pane disappearing between resolve and send silently drops a steer that used to fail under set -e. Return a distinct failure for the initial send error, or make fm-send.sh fail on that case while staying lenient for post-submit readback unknowns.

🔧 Fix: Harden AFK defer and send failure handling
1 warning still open:

  • ⚠️ AGENTS.md:568 - The new wedge marker is created so failed forced injections are not silent, but the primary afk return contract still only tells firstmate to summarize .subsuper-escalations. If the forced inject could not reach the pane, this marker may be the only durable signal after the status-line flash is gone, so add state/.subsuper-inject-wedged to the return/recovery catch-up instructions.

🔧 Fix: Document AFK wedge catch-up
1 warning still open:

  • ⚠️ bin/fm-supervise-daemon.sh:611 - Forced max-defer delivery can retype the same escalation into a composer that already contains the previous failed injection. A normal flush that typed the digest but got a swallowed Enter leaves that text in the composer and preserves the buffer; once max-defer fires, this bypasses the pending-input guard and calls the submit primitive, which types the digest again before pressing Enter. Try Enter-only first when the pending composer already holds an unsent daemon digest, or avoid bypassing the guard for that case.

🔧 Fix: Captain, prevent forced AFK digest retyping
1 error still open:

  • 🚨 bin/fm-supervise-daemon.sh:632 - Forced max-defer now treats any pending composer as if it already contains the daemon digest. If the pending text is a human draft, an unsupported prompt false-positive, or any other non-daemon content, this branch sends Enter only; when the composer clears, escalate_flush clears .subsuper-escalations even though the escalation digest was never typed. Only use the Enter-only path after confirming the pending composer contains this daemon digest, otherwise preserve the buffer and alarm/defer.

🔧 Fix: Remove unsafe AFK force delivery
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • git diff --stat 2a2fe0566e63b883ec53dc3e34dc14306689f989..925188c2b0a15401ac248fab40fcaa6c9a2744d5 and changed-file inspection for the tmux/afk paths.
  • bash tests/fm-wake-queue.test.sh > /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVTS9SETQG83GGNV0GWP7VSR/fm-wake-queue.out 2>&1
  • bash tests/fm-afk-inject-e2e.test.sh > /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVTS9SETQG83GGNV0GWP7VSR/fm-afk-inject-e2e.out 2>&1
  • Manual private-tmux daemon scenario via inline bash -s, captured to /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVTS9SETQG83GGNV0GWP7VSR/afk-private-tmux-transcript.out: pending human input deferred injection, idle pane received a clean daemon digest, and a swallowed Enter retried into exactly one sentinel-prefixed injection.
  • git status --short after testing to confirm no working-tree artifacts were left.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

… submit

Root-causes afk-invx-i5, where away-mode supervised 9.5h and surfaced nothing.

- Composer detection now strips the harness's box borders before deciding, so an
  idle bordered claude composer ("│ > … │") reads as empty, not pending input.
  The old check only matched a bare prompt, so every idle claude pane looked like
  pending input and the daemon deferred 100% of escalations.
- Add a max-defer escape: anything buffered past FM_MAX_DEFER_SECS (default 300)
  forces one delivery (bypassing the composer guard on an idle pane); if even
  that cannot confirm a submit, a rate-limited wedge alarm fires (ERROR log +
  state/.subsuper-inject-wedged marker + status-line flash). The daemon can no
  longer silently wedge forever.
- Submit is now verified against the same border-aware detector, fixing the
  parallel false "Enter swallowed" ACK. fm-send.sh shares the one primitive
  (bin/fm-tmux-lib.sh) and exits non-zero on a positively-confirmed swallow, so
  a steer that does not land is no longer silent.

Tests: bordered idle composer reads not-pending; bordered text still pending;
submit-ACK confirms on a bordered-empty composer and reports pending on a
persistent swallow; max-defer forces+alarms on a stuck pane, recovers on an idle
one, and stays quiet below threshold; fm-send exits non-zero on a swallow.
@kunchenguid
kunchenguid merged commit e4fbed5 into main Jun 23, 2026
4 checks passed
@kunchenguid
kunchenguid deleted the fm/afk-invx-i5 branch June 23, 2026 19:13
leo1oel added a commit to leo1oel/nemo that referenced this pull request Jun 23, 2026
Ports the intent of upstream e4fbed5 (kunchenguid#54, afk-invx-i5) onto the herdr-backed
sub-supervisor — adapted to herdr pane-text reading, no tmux, no fm-tmux-lib.sh.

Root cause (afk-invx-i5): away-mode supervised 9.5h and surfaced nothing because
composer detection matched only a BARE prompt, so an idle *bordered* Claude
composer ("│ > … │") read as pending input and the daemon deferred 100% of
escalations forever.

Three fixes:

- Border-aware composer detection. New shared primitive bin/fm-herdr-lib.sh
  (sourced by both the daemon and fm-send.sh, herdr-only) strips Claude's box
  borders ("│ ┃ ║ |") before deciding empty-vs-pending, and handles both the
  bare ❯/> prompt and the bordered "│ > … │" form. An idle composer reads NOT
  pending; FM_COMPOSER_IDLE_RE still overrides empty matching after stripping.
  pane_input_pending now delegates to this primitive; the bare-prompt path is
  generalized, not regressed.

- Max-defer escape. A digest buffered past FM_MAX_DEFER_SECS (default 300, 0
  disables) forces one normal flush; if a submit still cannot be confirmed, a
  loud RATE-LIMITED wedge alarm fires — an ERROR log line, a durable
  state/.subsuper-inject-wedged marker, and a `herdr notification show` status
  flash on the supervisor client. A guard false-positive becomes a visible
  stall, never an unbounded silent no-op.

- Verified submit, shared primitive. inject_msg verifies the submit landed with
  the same border-aware detector (turn-started OR confirmed-empty composer) and
  preserves the buffer on an unknown/unconfirmed pane (strict). fm-send.sh shares
  the same primitive and EXITS NON-ZERO on a positively-confirmed swallow (Enter
  swallowed, text still in composer), so a steer that does not land is no longer
  silent.

Docs: .agents/skills/afk/SKILL.md (border-aware note, max-defer escape + wedge
marker, surface it on the "while you were out" catch-up) and AGENTS.md §8 synced.

Tests: tests/fm-supervise-daemon.test.sh gains bordered-composer detection,
verified submit-ACK on a bordered composer, and the max-defer escape (quiet
below threshold, alarms on a stuck pane, recovers on idle); new tests/fm-send.test.sh
covers the non-zero exit on a confirmed swallow. shellcheck clean; all 6 suites green.
augustomklee added a commit to augustomklee/firstmate that referenced this pull request Jun 24, 2026
Port upstream batch 2: away-mode reliability (kunchenguid#54) + Claude ghost text (kunchenguid#59)
@leandrotcawork

Copy link
Copy Markdown

Reviewer: Claude Sonnet 5.5 (claude-sonnet-5-5)

Rules read: AGENTS.md, .agents/skills/conexus-review/SKILL.md, docs/reference/checklist.md, docs/guides/delivery.md (L2, L5, L7, L9, L12, L13, L19) at origin/main 7364445. The card as the PR carries it (docs/steps/e05-duas-empresas.md, byte-identical to PR #50 at f64ebb5). Reviewed: e14260783e7fc050a3b8b9cafc065c6a8b389d58 (fetched with git fetch origin pull/54/head, sha confirmed). The grant PRs developmentconexus-ops/conexus#53 and developmentconexus-ops/conexus#55 were read as well (body and file list; U7's migration through its body).

Ran

Everything else is "read". I did not rerun the CI suites, and I called no outside service (no Neon, Cloudflare, GitHub Actions).

  • git diff --stat origin/feat/conexus-e042-build...e142607: 66 files, +11013/-139. Read in full: platform/database.ts, the five migrations, identity/tables.ts, operations/clients.ts, identity/clients.ts, auth.ts, admission.ts, first-person.ts, invitations.ts (scope parts), isolation.test.ts, client-deletion.test.ts, database.check.ts, removals.json entries, catalog.test.ts, test-database.ts, delete-client-dialog.tsx, alert-dialog.tsx, client.tsx, clients.tsx, two-companies.test.ts, boundaries.md additions, decision 0039. Not read line by line: the generated snapshot.json files, components.md, register-client-form.test.tsx (only the new test), delete-client-dialog.test.tsx, sign-up.test.ts, invitations.test.ts.
  • node scripts/check-docs.ts at the commit: document-too-long: docs/roadmap.md: 1510 words, the ceiling is 1500, document-too-long: docs/steps/e05-duas-empresas.md: 4002 words, the ceiling is 4000, second-card: docs/steps: ...e042..., ...e05.... docs/roadmap.md is 1499 words on origin/main and on feat/conexus-e042-build; this PR takes it to 1510.
  • PostgreSQL 18 in Docker (postgres:18, my own container, stopped at the end), the repository's 19 migrations applied in order, then the isolation test's seed (Ana/Bruno/Carla/Davi, operator Operadora, companies A and B). SQL probes as SET LOCAL ROLE of each scope role with set_config('conexus.*', ..., true):
    • E1 hub_company in A, UPDATE auth."user" SET role='admin' WHERE id='person-ab' (a fellow member): succeeds, returns person-ab | admin.
    • E1-fix same, after REVOKE UPDATE ON auth."user" FROM hub_company; GRANT UPDATE (updated_at) ON auth."user" TO hub_company: SELECT ... FOR SHARE and FOR NO KEY UPDATE still work (the row locks the grant is for); the role update fails with permission denied for table user.
    • E2 hub_company in A, SELECT id, user_id FROM auth.session: returns B's person's session (no RLS on auth.session).
    • E2b hub_invitation, SELECT id, user_id, password FROM auth.account: returns every account row with its password hash (no RLS on auth.account).
    • E3 hub_company calling auth.is_installation_administrator('person-op'): permission denied for function (EXECUTE is only hub_operator's). E3b a non-administrator in hub_operator can ask whether any person id is an administrator and learns t: a one-bit leak to a role the program enters only after admission.
    • E5 hub_invitation can UPDATE auth.company SET name=... on the invitation's company (table-wide UPDATE, there to lock the row).
    • E6 hub_invitation in B's invitation scope reads member-b, member-ab-b (id, user_id, role) and auth.user rows of the inviter and the invitee only: A2's member read is exactly the invitation's company.
    • E7 hub_runtime in phase 1 counts all companies (the declared transition policy).
    • Recursion inside a rolled-back transaction I replaced the operator's auth.member policy by one that checks exists (select 1 from auth."user" u where u.id = <person> and u.role = 'admin') inline, and dropped administrators_select: ERROR: infinite recursion detected in policy for relation "member". With the migrated helper the same read returns 2 rows. So the card's native policy does recurse on PostgreSQL 18.
  • Library lines checked at the installed Better Auth 1.7.8: organization/routes/crud-org.mjs:255 (disableOrganizationDeletion answers before reading the session) and :264 (the native route asks for a membership), organization/adapter.mjs:370 (deleteOrganization deletes members, invitations, company), crud-invites.mjs:275-279 (accept counts the members for the limit). All match what boundaries.md cites. auth.handler is called from only three places (identity/routes.ts sign-in, reset-password, and the invitation attempt counter), so no native organization route is mounted.
  • Visual QA (T23): see the section at the end.

Findings

  1. Bloqueia The step makes npm run docs fail on its own documents, and it will keep failing after L5 clears. The card is 4002 words against the 4000 ceiling of docs/steps/*.md, and docs/roadmap.md goes from 1499 to 1510 against its 1500 ceiling (the approval line this PR adds). The PR body names the card's 4002 and blames only L5 for red docs; the roadmap overrun is not mentioned. Evidence: scripts/check-docs.ts:24 (4000) and :68-85 (words() is split(/\s+/), the same count as wc -w); output above. Breaks: delivery L5 and the document ceilings, red CI (L12). Cost: Se for assim para produção, o fundador perde um main verde quando a etapa entrar, porque o job de documentos continua vermelho mesmo depois que o cartão da 4.2 sai de docs/steps. Fix: trim 3 words from the card (the founder approved this text, so he sees the trim) and 11 words from the roadmap; no decision changes.
  2. Fechamento (decide before the founder approves the lists of feat(db): step 5 scope roles and their grants, phase 1 (step 5, U2) developmentconexus-ops/conexus#53 and feat(db): the Hub's login loses its reach on a company's tables, phase 2 (step 5, U7) developmentconexus-ops/conexus#55) The scope roles hold table-wide UPDATE only to lock a row, and the row policies they sit under are FOR ALL, so a transaction in one scope can change columns it should never touch. E1 above: a COMPANY transaction promotes a fellow member to installation admin, which is exactly the column every operator policy and the helper trust. The same shape: hub_invitation can UPDATE the company and any person its invitation names; hub_operator can UPDATE any owner or administrator row. No route does it today, so nothing is lost in this step's use script; it appears when a later change forgets a column list, which is the failure this step exists to contain. Evidence: migrations/20261017040314_company_scope_roles/migration.sql (GRANT SELECT, UPDATE ON TABLE auth."user", auth.session TO hub_company, GRANT SELECT, UPDATE ON TABLE auth.company ... TO hub_invitation, ...), identity/tables.ts (policy(SCOPE_ROLES.COMPANY, 'all', ...) on auth.user); probes E1, E1-fix, E5. Breaks: card A (a forgotten filter must not widen); data D10 least privilege. Recommendation: in feat: add treehouse setup hook and manual PR validation flow #53 use GRANT UPDATE (updated_at) (or the one column a lock needs) wherever the verb is only there to lock; E1-fix shows FOR SHARE and FOR NO KEY UPDATE still work. Real UPDATEs (the invitation's status, revision, the invited person's password fields) keep their column lists.
  3. Issue futura auth.session, auth.account and auth.verification have no row policy, and scope roles hold table-wide grants on them (hub_company SELECT, UPDATE on auth.session; hub_invitation SELECT, INSERT, UPDATE on auth.session, SELECT, INSERT on auth.account, SELECT, INSERT, DELETE on auth.verification). A query in the invitation scope that forgets its filter reads every person's password hash (E2b) and, in a company scope, every session token (E2). The card's list of policed tables is the four company tables and auth.user, so this is outside the card, and before step 5 the login reached the same rows. Trigger: before more scoped code arrives (step 6 or the Builder), add user_id = person policies on those three tables; the pattern is the one auth.user already uses.
  4. Fechamento The card's closing for the policy is not done: the card says "Fechamento (L19): arquitetura e 0012 citam a política". docs/architecture.md and docs/decisions/0012-*.md do not mention 0039 (grep 0039 finds only docs/index.md). Decision 0039 in this PR also does not record the two provisional A pieces (the helper, the invitation's member read); its Result (B1 to B8 local, B1 to B5 on Neon) lives in feat: add optional tasks-axi groundwork #55 and omits what the card's U1 asked it to carry: "PostgreSQL 18 (patch in the result)", the Result per item, and the setup. The PR body's "7 of 7" Neon count is not in the record.
  5. Fechamento Departures not declared under L7: (a) U1 says the 0039 record enters main in a PR of its own before the proof code; it is in this build PR as "proposed". (b) This PR contains feat: add treehouse setup hook and manual PR validation flow #53's migration and grant lines (20261017040314_company_scope_roles, database-grants.sql), although the body says the lists are in their own PRs and nothing merges before the founder's word; merging fix: harden away-mode escalation delivery #54 merges the list. The stack must merge feat: add treehouse setup hook and manual PR validation flow #53 first and fix: harden away-mode escalation delivery #54 must not be merged on its own. (c) Departure 1 (lock order) changes 4.2's correct(), while the card's F5 says "a construção para se um não valer". It is a real fix: the body reports a 40P01 deadlock between a deletion and a renewal and between 4.2's correction and a renewal. The same defect is in fix(watcher): preserve PR-check wakes before suppression #52 alone, so the lock order should also land in feat: the Operations Central registers a client, and its administrator joins as first owner (step 4.2) developmentconexus-ops/conexus#52, or the 4.2 release carries a deadlock until this step merges. I do not think any of these is a new founder decision.
  6. Fechamento Unscoped doors typed as full transactions. Database.installation and libraryInstallation hand out the same CommandTx as a scoped command, so "open a transaction without scope does not compile" (criterion 7, database.check.ts) holds for read, command and libraryCommand only. Callers today are database.ts (migration and login checks), status.ts and first-person.ts (checked with grep). In phase 1 they reach every company row through the transition policy; phase 2 closes them in the database. Narrow installation to the type its callers need (execute plus the hub.starts table), and add a dependency-cruiser rule that only status, platform and first-person may name installation. Related: asPerson restores the company scope only on success (database.ts, no try/finally); safe today because every error there aborts the transaction, unsafe the day a caller catches it.
  7. Fechamento Small: identity/tables.ts has two comments back to back on runtime_sign_in ("The login signs people in and reads them for the library, outside any scope." / "The login signs people in, outside any scope (step 3)."). The "Provisional until the founder's word" comments in tables.ts and boundaries.md must go when he answers. Criterion 14's test reloads by cleanup() and then navigates to the list itself (register-client-form.test.tsx), so the app shows nothing that "pergunta" after a reload on the new-client page; the founder's J says "mostra o estado atual e pergunta" and the card narrowed it to "lista atual". Worth one sentence from the founder at the use script. The concurrency test accepts [200, 404, 422] for the losing accept (client-deletion.test.ts); the final-state assertions (zero rows, link 404, no orphans) carry it, so it can fail where it matters.

Judgments the brief asked for

(1) Declared departures (L7). 1 lock order: accepted, see finding 5(c). 2 operator invitation SELECT with a company: needed, because PostgreSQL reads the row through SELECT before a filtered DELETE (checked in the policy text); fine. 3 UPDATE to lock rows: correct about PostgreSQL, but the verb is wider than the need; finding 2. 4 first person through libraryInstallation: correct, nobody is signed in; it is the unscoped door of finding 6. 5 phase-2 harness and CI matrix leg: good, it is what makes criterion 17 true from U3. 6 planted failures on hub_invitation: same assertions, right role. 7 test file split: Biome's 300 lines, fine. 8 deleteCompany takes the company lock itself: harmless, held twice. 9 losing accept answers 422: 4.1's code, fine. 10 AlertDialog hand-built on Base UI 1.9.0 instead of the shadcn registry: the sheet in this repo is also "copied from shadcn base-nova"; same primitive, same dress; fine, but say that no registry diff was made. 11 notice search parameter: the address keeps ?notice=deleted after a reload (QA); a Fechamento, the card's "Notice" has no timeout and a bookmarked address repeats it. 12 V55 variants: fine. None of them is a new founder decision.

(2) The two provisional A decisions. I agree with A for both.

  • The helper. The recursion is real (probe above, 42P17 on PostgreSQL 18). The B alternative (the operator reads every auth.user row) breaks criterion 18 for a non-administrator in OPERATOR, who would read every person; C drops the admin check on members, which the card's S11 forbids. The SECURITY DEFINER function is the documented PostgreSQL way out of policy recursion (it is also what Supabase recommends; I cite that from memory, "read"). The implementation is tight: owner hub_administrators (NOLOGIN, NOINHERIT, NOBYPASSRLS, no other object, membership given to the migrating owner and revoked in the same migration), SET search_path = pg_catalog with every object schema-qualified, REVOKE ALL FROM PUBLIC, EXECUTE only for hub_operator (E3), column grants SELECT (id, role) on auth.user plus its own policy role = 'admin'. What it leaks: one bit, whether a given person id is an administrator, to a role the program enters after admitOperator (E3b). Two small notes: it is STABLE and not inlinable, so a large operator read evaluates it per row (wrap it as (select auth.is_installation_administrator(...)) if the client list ever grows); and the record 0039 must name it (finding 4).
  • hub_invitation reads the company's members. Needed in two places, not one: Better Auth's accept counts members (crud-invites.mjs:275-279) and 4.1's link view runs not exists (select 1 from member ...) for firstOwner (invitation-reads.ts:100). Without the policy that not exists is true for every invitation, because RLS hides the rows: a fail-open, not an error. Probe E6 shows the read is limited to the invitation's company and exposes user_id and role of its members to the holder of the link. The B alternative (no read, membershipLimit: Infinity, count in the Hub) would still break firstOwner. Agree with A.

(3) A: the typed context. read, command and libraryCommand take a Scope; ids are branded, so a string from a body does not compile (database.check.ts compiles in isolation.test.ts "o tipo"); SET LOCAL ROLE is a constant of the program; set_config(..., true) values are bound; a failed entry is DATABASE_UNAVAILABLE before the work runs (B5 test revokes a membership). Pool reuse: both settings are transaction-local; the test shows one backend serving A, B (with a savepoint rolled back) and no scope. Better Auth's own queries run on libraryOrm outside any transaction as hub_runtime; only sign-in, reset-password and the attempt counter use it, and in phase 2 hub_runtime has no grant on a company table. Background work: the post-commit mail is a new scoped transaction (mailInvitation takes a scope). Open doors: installation, libraryInstallation, libraryOrm are not mandatory-scope by type (finding 6); in phase 1 they reach company rows through runtime_transition, which is the declared H. The context is mandatory by type for every company query that the Hub's code can open.

(4) Every policy against the matrix. Read each of the 31 policies in the three policy migrations against the card's table: every cell matches, plus the two declared additions (operator invitation SELECT with a company; invitation scope SELECT on members). hub_company on operations.client, hub_person on it and hub_invitation on it have neither grant nor policy. Criterion 18 is tested for ANA (a non-administrator) and an id with no person: both read zero rows from the five tables, change zero rows of operations.client, and the INSERT into auth.company is refused with 42501; the administrator reads all (isolation.test.ts "operador sem papel"). Removal operator-policy-admin-only only strips the check from auth.member's SELECT policy; the test reads all five tables, so a removal on any of them is caught too (read, not run).

(5) The nine proofs. B1 catalog.test.ts "as quatro tabelas ... sem FORCE" plus the snapshot equality and "sem contexto" (a test that changes the role, not a re-login). B2 to B4 assert literal rows from a seed, with the positive for A beside each negative (T10). B5 covers commit, rollback and savepoint on one backend. B6 relies on the unchanged 4.1/4.2 suites (CI). B7 client-deletion.test.ts "fora" and "apagar só pela Central": both assert 404 and unchanged rows. B8 removals.json: six entries, each with its own test; I read the finds and replaces and judged them as catching what they claim (not run). B9: the Neon proof (B1 to B5, phase 1 and 2, on a deleted branch) is in the PR body and in #55's Result, but the Result has no PostgreSQL patch, no per-item list and no setup, so the record cannot be checked without the builder's word. I called nothing on Neon: "read".

(6) H: staged activation. Phase 1 alone is safe in the sense the card needs: RLS is on and runtime_transition / runtime_sign_in keep v0.4.2 running on the migrated database (the SECOND_PHASE harness and the CI phase: [1, 2] leg prove the suite on both). Phase 2 alone (#55): drops the four transition policies and the hub_runtime grants; the full server suite is reported 269 of 269 on it and the catalog test "na fase 2" asserts 42501 on the four tables. Rollback to v0.4.2 after phase 2 is not possible by design (H says so; the founder confirms in U7). Grant lists vs code: they match what the code needs in the sense that each verb was found by running the suite, but not "no more": finding 2 (UPDATE only to lock) and finding 3.

(7) Deleting a client and J. The server flow is the card's: one libraryCommand in OPERATOR {companyId}, lockCompany first, admitOperator, client row FOR UPDATE, 412 on revision, 422 on name, delete client, deleteOrganization via the adapter, post-condition (company gone, else INTERNAL_UNEXPECTED), 204 after commit. A non-operator, an owner included, gets 404 from RLS and admission; a replay gets the same 404 as an unknown id (the test compares both bodies without the trace id). CLIENT_DELETED logs ids and the trace, and the test greps the output for the CNPJ, names and e-mails. People, accounts and sessions are unchanged (counts compared). The CNPJ is free again (the test registers it anew). One thing to know: the sessions' active-organization id keeps pointing at the deleted company (D18, declared). J: finding 7.

(8) The card's size. 4002 words, covered by finding 1 (with the roadmap).

Verdict

request changes: finding 1 (the step's own documents break the docs ceilings, so main would be red); findings 2 to 7 are for the closing, and finding 2 should be decided together with the founder's word on the grant lists. The design itself (typed scope, native row policy, the definer helper, the member read) holds up under my probes, and I found no cross-company read or write through the Hub's code paths.

Visual QA (T23), what I ran and saw

I wrote a scratch Playwright test on the repository's own harness (tests/e2e/live-hub.ts): the real Hub on PostgreSQL 18 in Docker (a container I started and stopped), the web built by Vite, the mail provider faked at its HTTP door, the repository's pinned playwright-core 1.63.0 with the cached headless Chromium. Three windows (the operator, A's owner, B's owner) walked the card's use script: register A and B, accept both invitations, A's owner sees only A and opens B's address (Página não encontrada), the operator opens B, the "Apagar cliente" dialog, a partial name, the full name, confirm, the list with "Cliente apagado.", B's owner reloads (NotFound), Suas empresas empty, B's invitation link (NotFound). The run passed, and the fixed problems list (page errors and CSP messages) stayed empty.

Screenshots (all taken, 1366x800, 390x844 and 320x640, light and dark, full page), each named <step>-<width>-<theme>.png: 01-cliente-aguardando, 02-suas-empresas-A, 03-B-nao-encontrada, 04-lista, 05-cliente-B-ativo, 06-dialogo-vazio, 07-dialogo-nome-parcial, 08-dialogo-pronto, 09-lista-apagado, 10-dono-B-recarrega, 11-dono-B-vazio. I opened 08 at 1366 light, 07 at 320 dark, 09 at 390 dark, 03 at 320 light, 11 at 390 light and 05 at 320 dark and looked at them: the dialog is centered and readable at every width, the confirm button is the one filled danger button and looks disabled until the full name is typed, the focus ring is on the field, the list shows "Cliente apagado." above the remaining client, NotFound and the empty Suas empresas read well in both themes. I did not open every one of the 66 files; the page-width check below covers all of them.

Measured in the page: document.documentElement.scrollWidth - innerWidth was 0 in every capture (no horizontal scroll at 1366, 390 or 320, light or dark). Focus on opening the dialog is the field "Digite o nome do cliente". Enter in the empty field leaves the dialog open and sends nothing. Tab from the field goes to Cancelar, then, in headless Chromium, through Base UI's focus-guard span and body before returning to the field (two presses to wrap); that is Base UI's modal behaviour, and it means "focus stays inside" is true up to the browser's own chrome. I pressed no key to close with Escape and did not test a cut connection or the 412 path in the browser (those are covered by delete-client-dialog.test.tsx, "read").

Console: no CSP message and no page error. The browser logged four Failed to load resource: 404 lines: API reads that answer NOT_FOUND by design (A's owner on B's address, B's owner's reload, B's link) and one after the confirm click; I did not trace which request it was. After the deletion the address is /operations/clients?notice=deleted and stays so after a reload (checked in the URL), so a copied or reloaded address keeps the notice parameter; whether the "Cliente apagado." text reappears I did not wait for (my assertion counted it before the page rendered), so that part is "read" from clients.tsx.

fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
…id#54)

* Build gateway v2 core protocols

* no-mistakes(review): Harden gateway v2 serving loop, connections, and recovery

* no-mistakes(review): Gate gateway v2 channel readiness on database and liveness

* no-mistakes(document): Document gateway v2 adapter contract, refresh stale gateway docs

* no-mistakes(document): Declare dedicated gateway-v2 capability in fork surface
@zNeoj

zNeoj commented Nov 10, 2026

Copy link
Copy Markdown

Puesta al día con pacov5 (head c1fc31c): merge (no rebase) de origin/pacov5, que ya trae los PR 53, 55 y 57. Conflictos resueltos conservando los dos lados: AGENTS.md y los dos .csproj; al fusionarse IGeneracionRepositorio, los tres repositorios falsos de las pruebas implementan los métodos de ambos lados (sin cambiar comportamiento). El diff contra pacov5 queda sólo con la sección 6.2. Compilado y probado en la VM: 801 pruebas, 800 correctas, 1 omitida (en pacov5 puro: 738, 1 omitida). El PR queda sin conflictos y listo para revisión.

@brunolitman

Copy link
Copy Markdown

Verification (HCP speculative plan-only runs, nothing applied)

Both runs uploaded this branch (19ce65c) as a speculative, plan-only configuration version. Logs: data/dhr-prod-noop-guard/plan-dev.log and plan-prod.log in the Firstmate home.

  • terraform fmt and validate: pass.
  • Prod (dsd-se-migrations-al-legacy-alea-dhr-prod, run-hUbKF4vA5TLahUic): Plan: 0 to add, 0 to change, 0 to destroy, no errors. The prod workspace already supplies allowed_api_cidrs (added 2026-11-06), and this passing plan uses the workspace variables, so no default or dummy value is needed.
  • Dev (dsd-se-migrations-al-legacy-alea-dhr-dev, run-cojfUePeWf9nizAS): 57 moved entries, and Plan: 2 to add, 0 to change, 2 to destroy. The 2 add and 2 destroy are the replacement of aws_ecs_task_definition.this[0] and aws_ecs_task_definition.migration[0] (cannot_update after drift on both).
  • Baseline drift, not caused by this PR: a plan-only run of unmodified develop (1991dae) on the same dev workspace (run-3ErJmkh3FkybThNR) shows the identical two task definition replacements (Plan: 2 to add, 0 to change, 2 to destroy). They exist on develop today, independent of this change. This PR adds only the 57 moves.
  • Moved blocks vs single-instance resources: 57 moved blocks for 57 single-instance resources (all 66 resource blocks: 57 single-instance, 5 already using count, 4 using for_each, which keep their addresses). No single-instance resource is missing a move. All 12 data sources are gated.

Risk

Merging to develop and applying the dev workspace performs state-only moves (resource[0] addresses) for 57 resources, plus whatever the dev workspace already has pending: the two ECS task definition replacements above. The ecs_service ignores task definition changes, and skip_destroy is set on the bootstrap task definition, but review the dev plan before confirming any apply. The prod workspace has no state and stays empty. required_version moves to >= 1.7.0 because the tasks_https import block now uses for_each.

fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 18, 2026
…and talk impossible to miss (kunchenguid#54)

* feat(bin): show the whole queue on the Factory pane and make answers and talk impossible to miss

The pane said only "N in line" per factory, so a long queue was invisible.
A line under the count line now counts every job nobody has started, by what
will start it: starts on its own, in line, on hold, and waiting on the owner
with dated deferrals counted apart. Each factory carries its own counts, and
what is held or still waits on other work is read as the backlog's adapter
reads it, so a blocker that was finished and archived holds nothing up.

Closed work no longer reads as finished: only a merged change, a landing or a
report reads landed or finished; work closed without one reads closed.

In NEEDS YOU only the highlighted call opens as a card; the rest stay one line
with their factory and how long they have waited.

An answer, keep, or talk now opens one outlined box that floats over a dimmed
pane, under the row it is about. A confirmation takes only enter, esc or
another option key, so a stray key cannot drop it, and the pane says in plain
words whether the note was sent, not sent, or cancelled. An answered call says
so on its card until it is acted on.

t listens at once where the desk voice is set up: the words appear in the box
while they are spoken, the note goes when the speaker stops or presses enter,
and the first typed key switches to typing. Without a microphone recorder or
the speech key the box is typed and says so.

* fix(bin): bound what a spoken note costs, drop a cancelled one for good, and name held calls by what they wait on

Review findings on the Factory pane's new talk box and queue.

A note cancelled while it was being written down could still be written down
and uploaded once the writing under way returned, and left its recording on
disk. A dropped note now stops the writing under way, starts no other, and
leaves no file, on esc, on a typed key and on quit.

Showing the words while speaking re-sent the whole recording every second, so
a long note cost the speech service far more than its length. Only the newest
eight seconds are written down now, at most every two seconds, a failed
writing waits before it is tried again, and the note that is sent is one
writing down of the whole recording when the speaker finishes.

The per-call sent history is cut down to one marker: an answered call reads
"answered HH:MM, waiting for Starship" and marks the option picked, also after
a restart, until the call is settled. Pickup and reply tracking and the extra
rows on the card are gone.

A decision held for the owner that other open work still blocks is counted as
waiting on other work, in the queue line and on its factory's page. Only an
aged hold is called an older call; any other is one more that waits on the
owner.

* no-mistakes(review): Drop confirm-time option swap and fix queue wrap example

* no-mistakes(test): Pace stand-in mic by clock and squeeze borders locale-safely

* no-mistakes(document): Correct Factory pane notice duration and retry wording
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