Skip to content

fix(bearings): preserve projections through inventory mismatches - #3129

Merged
kunchenguid merged 18 commits into
mainfrom
fm/fm-bearings-fix-bearings-fixes-projection-bug-policy-rev-77
Aug 26, 2026
Merged

kunchenguid merged 18 commits into
mainfrom
fm/fm-bearings-fix-bearings-fixes-projection-bug-policy-rev-77

Conversation

@kunchenguid

@kunchenguid kunchenguid commented Aug 26, 2026 •

Copy link
Copy Markdown
Owner

Intent

Reverse the Bearings projection-bug policy so a secondmate home with a mere backlog-vs-metadata inventory mismatch is no longer treated as fully unreadable, plus two captain-added companions and one captain-directed simplification, all in this one PR (#3129).

BACKGROUND: bin/fm-fleet-snapshot.sh's invalidity gate discarded ALL of a home's structured surfaces whenever any inventory-mismatch kind was set, and forced state:'unknown'. A scout reproduction showed this hid 28 open captain calls and a green PR awaiting merge across three working homes, while the main home already treats the identical mismatch as a harmless disclosure. The captain chose to reverse the strict-invalidity policy PR #875 deliberately introduced.

FIX A: the invalidity gate carves orphan_in_flight, unowned_current, and terminal_in_flight into the existing child_current_unavailable carve-out, so those homes stay partial-structured, keep decisions/holds/queued/landed/live work/endpoints, and leave unreadable[]. missing_backlog and unstructured_current DELIBERATELY stay on the discard path; their existing tests stay green untouched.

FIX B: those three kinds no longer collapse the summary state to 'unknown'; the real captain_decision / active_child_work / externally_held classification survives and invalidity carries the warning. Deliberate refinement: an unavailable CHILD state still collapses to unknown even when a mismatch masks it under strict-invalidity precedence, because a home with an unreadable child cannot be classified confidently. Consequently secondmate_landed.partial[] keys on partial-structured TRUST rather than an unknown state, behavior-identical for every pre-existing case.

CAPTAIN ADDENDUM 1 - RECONCILE HOOK: when the snapshot detects an inventory mismatch in a secondmate home, the parent asks THAT mate to reconcile its own books. Constraints: never auto-edit the mate's queue or metadata from the parent, never block the digest, use the existing steering transport, and do not nag on every recap.

CAPTAIN ADDENDUM 2 - WARNING SURFACE (C-small): optional 'kind' on board charted rows, default 'queued' plus 'warning'. Warning rows badge 'needs repair' (not 'waiting') and are EXCLUDED from the Charted Next count, including the charted_more truncation count. The captain explicitly ruled OUT a fifth board section. Optional-with-default keeps every existing payload valid.

CAPTAIN-DIRECTED SIMPLIFICATION (this is the current shape - earlier review rounds are superseded): the reconcile dedupe is a per-home COOLDOWN, not an episode-precise record. Prior rounds built an episode identity plus a monotonic snapshot 'observation' ordering generation plus pending/clear transitions, and each round surfaced another direction it got wrong - a clear hidden by strict-invalidity precedence, then an unsupported kind read as a clear, then non-atomic clear transitions. The captain judged the mechanism itself wrong and directed replacing it entirely. Now: one durable per-home timestamp at state/.reconcile-nudged, one nudge per FM_RECONCILE_COOLDOWN_SECONDS (4 hours, a named constant), a gentle re-nudge if the mismatch outlives the window, and nothing that can go stale, mis-order against a concurrent snapshot, or mis-classify a repair. The episode identity, ordering generation, snapshot 'observation' field, and pending/clear machinery are all DELETED, and the test that only covered the observation ordering is deleted with them. A known-undelivered send starts no cooldown so the next run retries; an unconfirmed send (exit 3) does start one, because a duplicate ask is worse than one the mate may already hold.

The reconcile send stays INLINE (no background child, no harness-native background task, no terminal-backed dispatcher: Pi has no native background and Codex forbids it, and an untracked child can be reaped to zero asks). It uses fm-send.sh's fire-and-forget plane, which arms no pending-reply expectation and is excluded from the steering inbox's re-ring and escalation ladder, because the parent expects no reply. bin/fm-teardown.sh now retires the cooldown record with the endpoint's other runtime artifacts so a reseeded id is not silenced by its predecessor's window.

OUT OF SCOPE, do not implement: a fifth board section; the parent-pointer backfill; raising FM_SNAPSHOT_SECONDMATE_TIMEOUT (a real but separate latent trigger); and the underlying per-home bookkeeping drift in the affected homes, which is those homes' own data, not code.

TESTS: assertions that pinned the OLD discard policy for orphan_in_flight, unowned_current, and terminal_in_flight were INVERTED on purpose across three suites, including one that demonstrates Fix B by asserting a home keeps active_child_work and its live worker through an orphan mismatch. unstructured_current and missing_backlog assertions are untouched and still pass. The reconcile suite drives the real fm-send inbox plane against a fake tmux backend and asserts durable steering records for the cooldown contract; its fire-and-forget test deliberately drives the signals apart, asserting the reconcile record stays quiet in a ladder that still returns 'ring' for an ordinary steer beside it, so the quiet verdict cannot pass vacuously. tests/fm-bearings-board-render.test.sh builds a real board and executes the SHIPPED template under a minimal DOM shim, asserting rendered badges, the stat strip, and the empty state rather than template source text.

This is firstmate's own shared tracked material, so firstmate-coding-guidelines applies: one sentence per line in tracked Markdown, plain dash never an em dash, no agent co-author, shellcheck-clean bin scripts via bin/fm-lint.sh, colocated tests named .test.sh, and tests that exercise behavior through an executable interface rather than asserting implementation source bytes. Note .github/workflows/ci.yml pins exact test counts (42 bearings, 15 fleet-view); the deleted observation test restores the bearings count to 42, so no workflow change is needed.

What Changed

  • Keep secondmate homes with orphan, unowned, or terminal inventory mismatches partially structured, preserving their classifications and projected work surfaces while reporting the invalidity.
  • Add cooldown-limited reconciliation nudges through a durable fire-and-forget steering path that avoids reply tracking and escalation.
  • Render integrity notices as non-dispatchable needs repair warnings excluded from Charted Next counts and truncation totals.

Risk Assessment

🚨 High: The reconcile path can still stall digest generation, issue multiple asks inside one cooldown window, re-ring acknowledged requests, and omit supported legacy mates.

Testing

Targeted snapshot, board, reconcile, inbox, local/remote transport, and fleet-view tests succeeded; end-to-end evidence shows the rendered warning UI excludes repair warnings from Charted Next and the reconcile path durably sends once before entering cooldown.

Evidence: Portable rendered Bearings board HTML

Source: Portable rendered Bearings board HTML

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bearings - fleet board</title>
<style>
/* ============================================================
   Bearings board - Firstmate Design System, inlined for portability.
   Tokens copied verbatim from myfirstmate priv/static/assets/app.css
   (the compiled adoption of .agents/skills/firstmate-design).
   ============================================================ */
@import url("https://fonts.googleapis.com/css2?family=Chango&family=Jost:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600;700&display=swap");

:root {
  --rust-700: #8f2f17; --rust-600: #a93a1f; --rust-500: #c0452a;
  --rust-400: #d35f3f; --rust-300: #e08365; --rust-100: #f4d8c9; --rust-050: #fbece3;
  --navy-700: #1a2238; --navy-600: #222c49; --navy-500: #2a3656;
  --navy-300: #6c7796; --navy-100: #d9deea;
  --gold-600: #b5791c; --gold-500: #e0a52e; --gold-300: #f0d38c; --gold-100: #f8ecc9;
  --ocean-600: #2f6688; --ocean-500: #3c7ea6; --ocean-200: #b6d4e2; --ocean-050: #e8f1f5;
  --sea-700: #234e3a; --sea-500: #2f6b4f; --sea-200: #b9d4c5; --sea-050: #e9f2ec;
  --paper-000: #fbf4e2; --paper-100: #f6ecd3; --paper-200: #f0e3c4; --paper-300: #e7d6ae;
  --cream-line: #ddc89c;
  --ink-900: #241c14; --ink-700: #3f3224; --ink-500: #6f5e46; --ink-300: #9c8a6c;
  --white: #fffdf7;
  --bg-page: var(--paper-100);
  --surface-card: var(--white);
  --surface-card-warm: var(--paper-000);
  --text-strong: var(--ink-900); --text-body: var(--ink-700);
  --text-muted: var(--ink-500); --text-faint: var(--ink-300);
  --border-default: var(--cream-line); --border-soft: var(--paper-300);
  --status-online: var(--sea-500); --status-online-soft: var(--sea-050);
  --status-warn: var(--gold-600); --status-warn-soft: var(--gold-100);
  --status-danger: var(--rust-600); --status-danger-soft: var(--rust-050);
  --status-info: var(--ocean-500); --status-info-soft: var(--ocean-050);
  --font-display: "Chango", "Cooper Black", Rockwell, Georgia, serif;
  --font-sans: "Jost", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
  --fs-h3: 1.4rem; --fs-h4: 1.15rem; --fs-base: 1rem; --fs-sm: 0.9375rem;
  --fs-xs: 0.8125rem; --fs-2xs: 0.6875rem;
  --ls-caps: 0.16em;
  --radius-xs: 6px; --radius-sm: 9px; --radius-md: 12px; --radius-banner: 7px;
  --radius-lg: 18px; --radius-pill: 999px;
  --shadow-sm: 0 1px 2px rgba(36, 28, 20, 0.06), 0 4px 10px rgba(36, 28, 20, 0.06);
  --shadow-hard: 4px 4px 0 var(--ink-900);
  --shadow-hard-sm: 3px 3px 0 var(--ink-900);
  --texture-paper: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.045'/%3E%3C/svg%3E");
  --focus-ring: 0 0 0 3px var(--gold-300);
  --container-app: 1180px;
}

* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
  font-family: var(--font-sans);
  color: var(--text-body);
  background: var(--bg-page);
  background-image: var(--texture-paper);
  line-height: 1.55;
  -webkit-font-smoothing: antialiased;
}
a { color: inherit; text-decoration: none; }

/* ---- fm-badge (enamel sign-pin), verbatim contract ---- */
.fm-badge {
  display: inline-flex; align-items: center; gap: 6px;
  font-size: var(--fs-2xs); font-weight: 800; line-height: 1;
  padding: 5px 9px 4px; text-transform: uppercase; letter-spacing: 0.07em;
  border-radius: var(--radius-xs); border: 1.5px solid var(--ink-900);
  box-shadow: 2px 2px 0 var(--ink-900); white-space: nowrap;
}
.fm-badge--online  { background: var(--sea-500);  color: var(--paper-000); }
.fm-badge--warn    { background: var(--gold-500); color: var(--navy-700); }
.fm-badge--danger  { background: var(--rust-600); color: var(--paper-000); }
.fm-badge--info    { background: var(--ocean-500); color: var(--paper-000); }
.fm-badge--neutral { background: var(--paper-000); color: var(--ink-900); }
.fm-badge--solid   { background: var(--rust-500); color: var(--paper-000); }

/* ---- fm-btn ---- */
.fm-btn {
  display: inline-flex; align-items: center; justify-content: center; gap: 8px;
  font-family: var(--font-sans); font-weight: 800; line-height: 1; white-space: nowrap;
  border: 2px solid transparent; border-radius: var(--radius-banner); cursor: pointer;
  text-decoration: none; transition: background 120ms, border-color 120ms, transform 120ms, box-shadow 120ms;
}
.fm-btn:focus-visible { outline: none; box-shadow: var(--focus-ring); }
.fm-btn:active { transform: translateY(1px); }
.fm-btn--sm { font-size: var(--fs-xs); padding: 8px 16px; }
.fm-btn--primary { background: var(--rust-500); color: var(--white); border-color: var(--ink-900); box-shadow: var(--shadow-hard-sm); }
.fm-btn--primary:hover { background: var(--rust-600); }
.fm-btn--gold { background: var(--gold-500); color: var(--navy-700); border-color: var(--ink-900); box-shadow: var(--shadow-hard-sm); }
.fm-btn--gold:hover { background: var(--gold-600); color: var(--white); }
.fm-btn[disabled] { opacity: 0.5; cursor: not-allowed; }

/* ---- fm-card ---- */
.fm-card {
  background: var(--surface-card); border: 1px solid var(--border-default);
  border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); overflow: hidden;
}
.fm-card--poster { border: 2px solid var(--ink-900); box-shadow: var(--shadow-hard); border-radius: var(--radius-md); }
.fm-card--warm { background: var(--surface-card-warm); }

/* ---- fm-sign (eyebrow section label) ---- */
.fm-sign {
  display: inline-flex; align-items: center; gap: 8px; font-weight: 800;
  text-transform: uppercase; letter-spacing: var(--ls-caps); font-size: var(--fs-xs);
  line-height: 1; white-space: nowrap;
}
.fm-sign--eyebrow { color: var(--rust-500); }
.fm-sign--muted { color: var(--ink-500); }
.fm-sign svg { width: 14px; height: 14px; }
.fm-ico { width: 1.15em; height: 1.15em; flex: none; vertical-align: -0.18em; }

/* ============================================================
   Board chrome (bb-*) - built on the same tokens
   ============================================================ */
.bb-nav {
  position: sticky; top: 0; z-index: 20;
  background: color-mix(in srgb, var(--paper-100) 86%, transparent);
  backdrop-filter: saturate(150%) blur(10px);
  border-bottom: 1px solid var(--border-default);
}
.bb-nav__inner {
  max-width: var(--container-app); margin: 0 auto; padding: 0 28px; height: 64px;
  display: flex; align-items: center; justify-content: space-between; gap: 16px;
}
.bb-brand { display: inline-flex; align-items: center; gap: 12px; }
.bb-brand__disc {
  display: grid; place-items: center; width: 34px; height: 34px; flex: none;
  border-radius: 999px; background: var(--rust-500); color: var(--paper-000);
  border: 2px solid var(--ink-900); box-shadow: var(--shadow-hard-sm);
}
.bb-brand__disc svg { width: 60%; height: 60%; }
.bb-brand__wm { font-family: var(--font-display); font-size: 23px; color: var(--text-strong); line-height: 1; }
.bb-meta-mono { font-family: var(--font-mono); font-size: var(--fs-xs); color: var(--text-faint); white-space: nowrap; }

.bb-main {
  max-width: var(--container-app); margin: 0 auto;
  padding: 26px 28px 72px; display: flex; flex-direction: column; gap: 22px;
}

/* stat strip */
.bb-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
.bb-stat {
  display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; min-width: 0;
  background: var(--surface-card-warm); border: 1px solid var(--border-soft); border-radius: var(--radius-md);
}
.bb-stat--call { background: var(--rust-050); border: 2px solid var(--rust-500); }
.bb-stat__num { font-family: var(--font-mono); font-size: var(--fs-h3); font-weight: 600; line-height: 1; color: var(--text-strong); }
.bb-stat--call .bb-stat__num { color: var(--rust-600); }
.bb-stat__label { font-family: var(--fon

... [21029 bytes truncated] ...

ot.appendChild(q);
    var answerLimit = el("span", "bb-limit");
    answerLimit.setAttribute("role", "alert");
    foot.appendChild(answerLimit);
    form.appendChild(foot);

    form.addEventListener("submit", function (ev) {
      ev.preventDefault();
      answerLimit.classList.remove("is-visible");
      var fd = new FormData(form);
      var value = fd.get("answer");
      var note = (fd.get("note") || "").trim();
      /* picked option, optionally annotated; a bare note is itself the answer */
      var answer = value ? (note ? value + " - " + note : value) : note;
      if (!answer) return;
      if (utf8ByteLength(answer) > 512) {
        answerLimit.textContent = "Answer is too long to queue (512 bytes maximum).";
        answerLimit.classList.add("is-visible");
        return;
      }
      if (window.lavish && window.lavish.queuePrompt) {
        /* close carries the composer-declared close mode: "release" frees a
           captain-gated work item instead of completing a question task */
        var ctxData = { question: item.key, answer: answer };
        if (item.close) ctxData.close = item.close;
        window.lavish.queuePrompt(
          "Captain's Call answer - " + item.title + ": " + answer,
          { tag: "choice", text: item.title + " -> " + answer, element: form,
            data: ctxData }
        );
      }
      card.classList.add("is-queued");
      /* deal the next card once this one is answered */
      setTimeout(function () { showCard(active < cards.length - 1 ? active + 1 : active); }, 450);
    });

    pad.appendChild(form);
    card.appendChild(pad);
    deck.appendChild(card);
  });

  /* stack navigation: one card at a time, dealt off the pile */
  var cards = Array.prototype.slice.call(deck.children);
  var active = 0;
  var stackCount = document.getElementById("bb-stack-count");
  var stackPrev = document.getElementById("bb-stack-prev");
  var stackNext = document.getElementById("bb-stack-next");
  var stackNav = stackCount.parentNode;
  function showCard(i) {
    active = Math.max(0, Math.min(cards.length - 1, i));
    cards.forEach(function (c, j) { c.hidden = j !== active; });
    var answered = deck.querySelectorAll(".is-queued").length;
    stackCount.textContent = "card " + (active + 1) + " of " + cards.length +
      (answered ? " · " + answered + " answered" : "");
    stackPrev.disabled = active === 0;
    stackNext.disabled = active === cards.length - 1;
    /* the pile thins as the deal approaches the bottom */
    deck.classList.toggle("bb-call--penult", active === cards.length - 2);
    deck.classList.toggle("bb-call--last", active === cards.length - 1);
  }
  if (cards.length) {
    stackPrev.addEventListener("click", function () { showCard(active - 1); });
    stackNext.addEventListener("click", function () { showCard(active + 1); });
    showCard(0);
  } else {
    deck.classList.add("bb-call--empty");
    deck.appendChild(el("div", "bb-empty", "Nothing needs your action right now."));
    stackNav.hidden = true;
  }

  /* Underway */
  var uw = document.getElementById("bb-underway");
  if (!data.underway.length) uw.appendChild(el("div", "bb-empty", "Nothing is underway."));
  data.underway.forEach(function (t) {
    var row = el("div", "bb-row");
    row.appendChild(badge(t.state === "working" ? "online" : "info", t.state));
    var main = el("div", "bb-row__main");
    main.appendChild(el("div", "bb-row__title", t.doing));
    /* captain-facing rows name the repo; the internal task id shows only when
       no repo is known */
    main.appendChild(el("div", "bb-row__sub", t.kind + " · " + (t.repo || t.id)));
    row.appendChild(main);
    uw.appendChild(row);
  });

  /* Landed */
  var ld = document.getElementById("bb-landed");
  if (!data.landed.length) ld.appendChild(el("div", "bb-empty", "No recent completions are in the current baseline."));
  data.landed.forEach(function (t) {
    var row = el("div", "bb-row");
    var chk = el("span", "bb-row__check");
    chk.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>';
    row.appendChild(chk);
    var main = el("div", "bb-row__main");
    main.appendChild(el("div", "bb-row__title", t.what));
    main.appendChild(el("div", "bb-row__sub", (t.repo || t.id) + " · " + t.owner));
    row.appendChild(main);
    if (t.pr_url) {
      var a = el("a", "bb-row__pr", "#" + t.pr_url.split("/").pop());
      a.href = t.pr_url; a.title = t.pr_url; a.target = "_blank"; a.rel = "noopener";
      row.appendChild(a);
    }
    ld.appendChild(row);
  });

  /* Charted Next + dispatch picker */
  var ch = document.getElementById("bb-charted");
  var bar = document.getElementById("bb-dispatch");
  var barCount = document.getElementById("bb-dispatch-count");
  var barBtn = document.getElementById("bb-dispatch-btn");
  var anyPickable = false;

  function pickedIds() {
    return Array.prototype.map.call(ch.querySelectorAll(".bb-pick:checked"), function (c) { return c.value; });
  }
  function refreshBar(limitMessage) {
    var n = pickedIds().length;
    barCount.textContent = limitMessage || (n ? n + " picked for dispatch" : "pick queued work to dispatch");
    barBtn.disabled = !n;
  }

  if (!chartedQueued(data.charted).length && !chartedMoreQueued) {
    ch.appendChild(el("div", "bb-empty", "Nothing is queued."));
  }
  data.charted.forEach(function (t) {
    var row = el("div", "bb-row");
    if (t.dispatchable && !isWarning(t)) {
      anyPickable = true;
      var pick = document.createElement("input");
      pick.type = "checkbox"; pick.className = "bb-pick"; pick.value = t.id;
      pick.setAttribute("aria-label", "Pick " + t.id + " for dispatch");
      pick.addEventListener("change", function () {
        if (pick.checked && utf8ByteLength(pickedIds().join(",")) > 512) {
          pick.checked = false;
          refreshBar("Selection limit reached (512 bytes maximum). ");
          return;
        }
        refreshBar();
      });
      row.appendChild(pick);
    } else {
      row.appendChild(el("span", "bb-pick-spacer"));
    }
    var main = el("div", "bb-row__main");
    main.appendChild(el("div", "bb-row__title", t.title));
    /* second line keeps the title uncrowded in the half-width column */
    var chSub = t.repo || t.id;
    main.appendChild(el("div", "bb-row__sub", t.reason ? t.reason + " · " + chSub : chSub));
    row.appendChild(main);
    if (isWarning(t)) row.appendChild(badge("danger", "needs repair"));
    else if (t.reason) row.appendChild(badge("warn", "waiting"));
    ch.appendChild(row);
  });
  var chartedShown = chartedQueued(data.charted).length;
  var chartedTotal = chartedShown + chartedMoreQueued;
  document.getElementById("bb-charted-sub").textContent =
    chartedMoreQueued ? "showing " + chartedShown + " of " + chartedTotal : "";
  if (chartedMoreQueued) {
    ch.appendChild(el("span", "bb-morechip", "+" + chartedMoreQueued + " more queued - ask firstmate for the full chart"));
  }
  if (chartedMoreWarnings) {
    ch.appendChild(el("span", "bb-morechip", "+" + chartedMoreWarnings + " more repair warning" + (chartedMoreWarnings === 1 ? "" : "s") + " - ask firstmate for the full chart"));
  }

  if (anyPickable) {
    bar.hidden = false;
    refreshBar();
    barBtn.addEventListener("click", function () {
      var ids = pickedIds();
      var dispatchAnswer = ids.join(",");
      if (!ids.length) return;
      if (utf8ByteLength(dispatchAnswer) > 512) {
        refreshBar("Selection is too long to queue (512 bytes maximum). ");
        return;
      }
      if (window.lavish && window.lavish.queuePrompt) {
        window.lavish.queuePrompt(
          "Dispatch order - start this queued work now: " + ids.join(", "),
          { tag: "choice", text: "Dispatch: " + ids.join(", "), element: bar,
            queueKey: "dispatch.charted",
            data: { question: "dispatch.charted", answer: dispatchAnswer } }
        );
      }
      bar.classList.add("is-queued");
    });
  }
  } catch (e) {
    renderBoardError("The board data could not be rendered");
  }
})();
</script>
</body>
</html>
Evidence: End-to-end reconcile transcript with durable fire-and-forget envelope and immediate cooldown behavior

Source: End-to-end reconcile transcript with durable fire-and-forget envelope and immediate cooldown behavior

End-to-end reconcile enqueue evidence

$ fm-secondmate-reconcile.sh notify --snapshot snapshot.json
sent: mate orphan_in_flight

$ fm-secondmate-reconcile.sh notify --snapshot snapshot.json  # immediate recap
cooldown: mate 0

Durable inbox records: 1
Record: reconcile-main/state/mate.inbox/001.msg
Cooldown epoch: 1787776569

Delivered fire-and-forget instruction body:
[fm-from-firstmate]⁣delivery=b590b5d0eaa1c030 Your home's backlog and its task metadata disagree, and only you can settle it: these in-flight backlog items have no task metadata in your home, so no worker is running them: stale-scout, watch-row

Please reconcile your own books: move each row to the section that matches reality, or clean up the leftover record. Nothing outside your home has been changed, and no reply is expected.

Durable record envelope:
schema=fm-task-inbox.v1
at=2026-08-26T20:36:07Z
delivery=fire-and-forget

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 4 errors
  • 🚨 bin/fm-secondmate-reconcile.sh:214 - The cooldown commit occurs after fm-send releases the endpoint metadata lock. A teardown can then acquire that lock, remove the inbox and reconcile record at bin/fm-teardown.sh:2822, and finish before this line recreates &lt;id&gt;.reconcile-nudged; reseeding the same ID within four hours is consequently suppressed by its predecessor. Commit or discard the cooldown while holding the lifecycle metadata lock and revalidate that the same endpoint still exists, so teardown and cooldown retirement serialize at their shared boundary.
  • ℹ️ docs/scripts.md:21 - The script catalog says reconciliation applies to a “new inventory-mismatch episode,” but the implementation and required contract now use a per-home four-hour cooldown independent of episode identity. Update the purpose clause to describe cooldown-limited nudges.

🔧 Fix: Serialize reconcile cooldown commits with mate lifecycle
2 errors still open:

  • 🚨 bin/fm-secondmate-reconcile.sh:204 - The required criterion says the reconcile hook must “never block the digest,” but the inline path now uses unbounded fm_lock_acquire_wait on the lifecycle control lock. A long-running teardown or relaunch therefore stalls /bearings indefinitely before digest composition. Use a non-blocking or tightly bounded acquisition and leave the cooldown unset so a later recap retries.
  • 🚨 bin/fm-secondmate-reconcile.sh:218 - The lifecycle serialization still does not verify that the endpoint matches the incarnation sampled by the snapshot. A snapshot can observe mate A, teardown and reseed the same ID can complete before line 204 acquires the lock, and this line then sends A's stale mismatch to mate B and records B's cooldown. Carry the sampled spawn_gen through the snapshot/reconcile row and compare it under the lifecycle lock before sending or committing the cooldown.

🔧 Fix: Reject stale reconcile snapshots across mate reincarnations
3 issues (2 errors, 1 warning) still open:

  • 🚨 bin/fm-secondmate-reconcile.sh:194 - The required hook must "never block the digest," but the inline path waits without a bound on the reconcile, lifecycle-control, and metadata locks, and holds the first two across fm-send. A teardown, concurrent recap, or delayed remote send can therefore stall /bearings indefinitely. Use non-blocking or tightly bounded lock acquisition and leave the cooldown unset so a later recap retries.
  • 🚨 bin/fm-secondmate-reconcile.sh:188 - The cooldown timestamp is captured once before processing any homes rather than when each nudge is delivered. If an earlier lock or remote send takes two hours, a later successful nudge receives a timestamp two hours old and can be sent again after only two more hours; cooldown checks for later homes also use stale time. Read the clock separately for each check and commit the successful nudge's actual delivery-time timestamp.
  • ⚠️ bin/fm-pending-reply-lib.sh:241 - The captain-directed simplification says the reconcile pending/clear machinery is "all DELETED," but this change still expands the shared pending-reply API with caller-selected correlation IDs, while bin/fm-send.sh:677-704 retains the associated FM_SEND_IDEMPOTENT bypass for ordinary reply-bearing sends. Fire-and-forget never calls this pending-reply path, and no current caller supplies FM_PENDING_REPLY_CORR_ID, so these are residual shared-transport changes from the superseded implementation rather than part of the cooldown design. Remove them or explicitly authorize retaining this broader behavior.

🔧 Fix: Start reconcile cooldown after delivery completes
2 issues (1 error, 1 warning) still open:

  • 🚨 bin/fm-secondmate-reconcile.sh:193 - The required hook must “never block the digest,” but the inline path waits without bounds on the reconcile lock, lifecycle-control lock, and metadata lock, and holds the first two across fm-send. A concurrent recap, teardown, or delayed remote send can therefore stall /bearings indefinitely. Use non-blocking or tightly bounded lock acquisition and leave the cooldown unset so a later recap retries.
  • ⚠️ bin/fm-pending-reply-lib.sh:241 - The captain-directed simplification says the reconcile pending machinery is “all DELETED,” but this change still adds caller-selected pending correlation IDs, while bin/fm-send.sh:677-704 retains the associated FM_SEND_IDEMPOTENT bypass for ordinary reply-bearing sends. Fire-and-forget does not use this pending-reply path and no production caller supplies FM_PENDING_REPLY_CORR_ID, so remove these residual shared-transport changes or explicitly authorize retaining them.

🔧 Fix: Keep reconcile sends nonblocking and remove pending residue
4 errors still open:

  • 🚨 bin/fm-secondmate-reconcile.sh:249 - The required criterion says reconciliation must “never block the digest,” but this inline call waits for all of fm-send, including synchronous backend doorbell operations and remote SSH delivery, with no deadline. A stalled backend command or unreachable remote can therefore stall /bearings indefinitely. Bound the send operation or split the required durable enqueue from best-effort notification while preserving the explicitly required inline design.
  • 🚨 bin/fm-secondmate-reconcile.sh:247 - Releasing the reconcile lock before sending leaves the one-nudge-per-window invariant unclaimed. Snapshot A can pass with orphan x and stall, snapshot B can pass after the mismatch changes to unowned y, and both derive the same delivery ID from the absent cooldown. Because inbox idempotency compares the full differing message bodies, both records are written and both asks are delivered within one window. Atomically claim the delivery identity at the durable enqueue boundary and distinguish newly-created from existing delivery without holding lifecycle locks across fm-send.
  • 🚨 bin/fm-send.sh:916 - The new local fire-and-forget idempotent path can return a record already moved into handled/, but unlike the remote path it still rings it. Concrete sequence: delivery succeeds, the mate handles the record, cooldown commit reports sent-unrecorded, and the next recap retries the same delivery. The resulting doorbell points at handled/*.msg and can make the mate act on the acknowledged reconcile request again. Mirror the remote handled-record guard and return success without ringing.
  • 🚨 bin/fm-secondmate-reconcile.sh:178 - The required hook asks every detected mismatching home, but this filter silently drops snapshots whose secondmate metadata predates spawn_gen. Legacy metadata without that field is explicitly supported elsewhere, so an upgraded long-lived mate can expose a mismatch yet receive zero reconcile asks. Either carry a supported legacy incarnation identity or explicitly obtain authorization to exclude legacy endpoints.
✅ **Test** - passed

✅ No issues found.

  • bin/fm-test-run.sh tests/fm-bearings-snapshot.test.sh tests/fm-secondmate-reconcile.test.sh tests/fm-bearings-board-render.test.sh tests/fm-bearings-board.test.sh tests/fm-task-inbox.test.sh tests/fm-send-remote-delivery.test.sh
  • bin/fm-test-run.sh tests/fm-fleet-snapshot-view.test.sh
  • Built a real fm-bearings-board.v1 through bin/fm-bearings-board.sh build and rendered it in headless Google Chrome.
  • Manually drove bin/fm-secondmate-reconcile.sh notify --snapshot twice through the real durable inbox plane, verifying one fire-and-forget record and cooldown suppression on the immediate recap.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Fix reconcile test subshell lint warning
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5

The PR should not merge until delayed snapshots can no longer start a cooldown that suppresses the current reconciliation need.

The current implementation validates endpoint incarnation but not snapshot freshness or the current mismatch, so an obsolete snapshot can still send and commit the same per-home cooldown that tests show suppresses a newer mismatch.

Files Needing Attention: bin/fm-secondmate-reconcile.sh

Reviews (3): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment thread bin/fm-fleet-snapshot.sh Outdated
Comment on lines +96 to +102
SNAPSHOT_OBSERVATION=$(perl -MTime::HiRes=clock_gettime,CLOCK_MONOTONIC -e \
'printf "%020.0f-%010d", clock_gettime(CLOCK_MONOTONIC) * 1000000000, $$') || exit 1
else
SNAPSHOT_OBSERVATION=$(date +%s%N 2>/dev/null || true)
case "$SNAPSHOT_OBSERVATION" in ''|*[!0-9]*) echo "fm-fleet-snapshot: cannot create an observation identity" >&2; exit 1 ;; esac
SNAPSHOT_OBSERVATION=$(printf '%020d-%010d' "$SNAPSHOT_OBSERVATION" "$$")
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Observation ordering regresses

After a host reboot, CLOCK_MONOTONIC restarts below the generation persisted before reboot, so the reconcile stale-check rejects fresh mismatch, clear, and retry transitions until uptime catches up. Overlapping snapshots can also be ordered by process startup rather than when each home is sampled, causing a later observation to be discarded as stale.

…nings as repairs

A backlog-vs-metadata inventory mismatch inside a secondmate home was being
reported as "we cannot read that home", which discarded that home's open
captain calls, queued work, landed work, and live workers from the whole
Bearings digest. The main home already treats the identical mismatch as a
harmless disclosure; this makes the secondmate path agree.

- fm-fleet-snapshot.sh: the invalidity gate now passes orphan_in_flight,
  unowned_current, and terminal_in_flight through the partial-structured
  carve-out alongside child_current_unavailable, so those homes keep their
  decisions, holds, queued, landed, and live work and leave unreadable[].
  missing_backlog and unstructured_current stay on the discard path, because
  there the backlog itself is untrustworthy.
- fm-fleet-snapshot.sh: the same three kinds no longer collapse the home's own
  classification to "unknown"; the real captain_decision / active_child_work /
  externally_held classification survives and invalidity carries the warning.
  An unavailable child state still collapses it, including when a mismatch
  masks it under strict-invalidity precedence.
- secondmate_landed.partial now keys on partial-structured trust rather than an
  unknown state, so an inventory-mismatch home is still disclosed as partial.

Ask the home that owns the wrong books to fix them:

- bin/fm-secondmate-reconcile.sh sends exactly one reconcile instruction per
  mismatch episode through the ordinary steering transport. A persistent
  mismatch keeps its episode identity and never re-nags; a changed mismatch
  earns one more ask; a repaired one is forgotten so a recurrence is asked
  about again. The parent never touches the mate's own files, and a failed send
  records nothing so the next run retries it.

Give integrity warnings their own look on the board:

- charted rows take an optional kind of "queued" (the default) or "warning".
  A warning badges "needs repair" instead of "waiting" and is excluded from the
  Charted Next count, so alarms stop reading as dispatchable queued work. No
  fifth board section, and every existing payload stays valid.

Tests pin the new policy behaviorally: the retained surfaces and classification
for all three mismatch kinds, the still-discarding unstructured_current and
missing_backlog cases, the once-per-episode reconcile ask through real durable
steering records, and the board rendering exercised through the shipped
template under a minimal DOM shim.
…r cooldown

The reconcile ask needed to fire once per problem without nagging on every
recap. The episode-precise record that tried to do that had to be correct in
every direction at once - order two concurrent snapshots, tell a repair from a
new problem, and never lose a clear - and each direction it got wrong either
swallowed a nudge or sent a duplicate.

A per-home cooldown removes the whole class. One durable timestamp per home,
one nudge per four hours, and nothing to get stale, mis-order, or
mis-classify: a home in mismatch is asked once, later recaps stay silent, and
a mismatch still sitting there after the window earns one gentle re-nudge.

- bin/fm-secondmate-reconcile.sh: state/<id>.reconcile-nudged holds the epoch
  second of the last ask; FM_RECONCILE_COOLDOWN_SECONDS names the window. The
  episode identity, ordering generation, pending/clear transitions, and
  delivery-identity reuse are all gone. A known-undelivered send starts no
  cooldown so the next run retries it; an unconfirmed one does, because a
  duplicate ask is worse than one the mate may already hold.
- bin/fm-fleet-snapshot.sh, bin/fm-bearings-snapshot.sh: drop the snapshot
  `observation` monotonic identity, which existed only to order those records.
- bin/fm-teardown.sh: retire the cooldown record with the endpoint's other
  runtime artifacts, so reseeding a retired id is not silenced by its
  predecessor's window.

The inline durable fire-and-forget send is unchanged, and the projection fix
and the warning surface are untouched.

Tests follow the behavior: the cooldown suite now pins one ask per window, the
re-nudge after it, the four-hour boundary, per-home independence, and that the
ask stays out of a re-ring ladder that still rings an ordinary steer beside it.
The obsolete observation-ordering test is deleted with the machinery it covered.
@kunchenguid
kunchenguid force-pushed the fm/fm-bearings-fix-bearings-fixes-projection-bug-policy-rev-77 branch from 3607c1b to 8fc89f3 Compare August 26, 2026 20:43
@kunchenguid kunchenguid changed the title fix(bearings): preserve inventory-mismatch home projections fix(bearings): preserve projections through inventory mismatches Aug 26, 2026
Comment thread bin/fm-secondmate-reconcile.sh Resolved
@kunchenguid
kunchenguid merged commit 60bedde into main Aug 26, 2026
10 of 13 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-bearings-fix-bearings-fixes-projection-bug-policy-rev-77 branch August 26, 2026 21:06