Skip to content

Commit caa93c6

Browse files
fix(omp): harden idle-turn supervision and wake delivery (#129)
* fix(bin): derive watcher beacon staleness grace from poll cadence Port of upstream kunchenguid/firstmate kunchenguid#3946, adapted: the fork has no away-mode daemon predicate, so only the shared derivation and its two in-scope readers change. fm-claude-stop-autoarm.sh required the watcher beacon fresh within the flat FM_GUARD_GRACE default (300s), but a healthy watcher touches the beacon once per cycle and can legitimately age up to FM_POLL seconds between touches, so a long-poll home reads stale mid-wait and the hook misjudges a live cycle as down. fm-wake-lib.sh gains fm_poll_derived_grace, the single owner of the max(300, FM_POLL + 60) formula. fm-watch.sh's own pre-acquisition beacon-staleness check and the auto-arm hook both derive their default grace from it, and the hook now exports its resolved FM_GUARD_GRACE to the fm-watch-arm.sh invocations so arm and check agree on one value. * fix(bin): count only actor-presentable wake rows and retire unusable rows Port of upstream kunchenguid/firstmate kunchenguid#3950, adapted to the fork's SCOPED drain and OMP branch-grant machinery. A branch grant already excluded its rows from a main drain, but fm-guard.sh still counted every queued row as pending for the calling actor, so main was told to run a drain that could only print nothing for as long as the branch held the grant. And a queue row that lost the five appended fields or its numeric sequence was counted as queued while it could never be claimed, presented, or named by an --ack-through cutoff, wedging the queue permanently. fm-wake-lib.sh gains the shared per-actor helpers: fm_wake_grant_rows_valid, fm_wake_branch_owner_matches, fm_wake_branch_grant_live, and fm_wake_actor_pending_count - the last reports a pending row when a queue exists but cannot be counted, so an unreadable queue still raises the alarm. fm-wake-drain.sh and fm-wake-grant.sh now delegate their grant row-list and owner-record reads to the library. A main drain retires structurally unusable rows under the queue lock and reports them verbatim (a branch drain never does), and a main drain left with only branch-held rows names the holder instead of exiting silently. fm-guard.sh warns only for rows the calling actor can itself present or retire, and gives main a distinct held-by-branch advisory when that is the whole non-empty queue. tests/fm-wake-queue.test.sh covers the branch-held warning boundary end to end, the uncountable-queue alarm, and main-only retirement. * fix(bin): gate secondmate wake-loop stall alerts on real queue no-progress Port of upstream kunchenguid/firstmate kunchenguid#3943, which lands the detector's final form on this fork (the fork had no foreign-queue stall check at all, so the whole feature arrives already fixed). The watcher now reads the oldest structurally valid actionable row in every endpoint-recorded local secondmate home's durable wake queue, and times the interval since that position last changed instead of the row's age. A queue that is draining is not stalled, so a moved oldest row - drain progress, or a queue reprovisioned under the same task id that restarts its sequence anywhere - ends the no-progress episode and starts a fresh observation interval, recorded by state/.secondmate-wake-progress-<task> as the same epoch-sequence row identity the stall receipts use. Declared external-wait pause rows are not actionable evidence, and a mate provably inside an active turn (an exact busy verdict bounded by FM_BUSY_TURN_MAX_SECS) never escalates. One keyed check notification covers each no-progress episode across watcher and handling crashes; the foreign queue is only ever read. FM_SECONDMATE_WAKE_STALL_SECS defaults to 180 and is the backstop behind the active-turn gate, not a substitute for it. Fork adaptation: the parent watcher keeps its secondmate home-beacon rule, so the ported tests give the fixture mate a fresh .last-watcher-beat under its (stubbed or real) clock to isolate the stall detector; assertions are unchanged from upstream. tests/fm-wake-queue.test.sh covers progress tracking, once-per-episode alerting, declared-pause exclusion, reprovisioned-generation reset, active-turn deferral, and marker symlink rejection. * fix(bin): never type doorbells into dead panes; recover them instead Port of upstream kunchenguid#3823, adapted: the fork's task-inbox ring reserves return code 6 for a positively dead or missing endpoint (codes 3-5 are OMP-native and Hermes-lock outcomes here). The doorbell line itself is now a shell no-op (": ...") with quoted, printable-only paths, so even a liveness race that loses to an exiting agent runs nothing in a bare shell. The watcher escalates a dead/missing endpoint's unhandled record once through the ordinary stale wake - over stale busy-state evidence - instead of walking the re-ring ladder, and fm-send reports the skipped doorbell as recovery, not a re-ring. Remote secondmate send inherits the rc-6 recovery notice through fm-send without a new branch. Secondmate restart also resolves all arrived persist answers before any timeout decision and rechecks at the decision boundary, so a reply landing at the deadline wins over the fallback nudge. Regression coverage: doorbell shell-noop across real shells, control-byte path rejection, dead/missing ring skip, watcher escalate-once-without- ringing, dead-pane override of stale busy state, and the resolution/timeout boundary race. Fake tmux inventories across the suite now list recorded windows and answer pane_current_command so the recovery-grade endpoint check exercises real paths. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(omp): prove the doorbell turn instead of trusting triggerTurn The task-inbox doorbell claimed `.delivered` the moment sendMessage returned, but OMP can downgrade `triggerTurn` to append-only delivery on an idle, non-streaming session: the steer was accepted and reported received while no turn ever ran, leaving an idle worker stranded with an unhandled durable record. The extension now renames an accepted request to `.awaiting-turn` when no turn is open and settles it to `.delivered` only on a `turn_start` or `agent_start` proving the turn actually began. A steer that lands while a turn is open is still delivered immediately, since it joins that turn. When the bound passes with no turn, the extension re-drives the same instruction through `sendUserMessage` - a user prompt an idle session cannot defer - and a failed re-drive reports `.failed` rather than stranding silently. Requests left `.awaiting-turn` by a dead generation re-queue as `.pending` on the next activation. Installs on runtimes without the event or user-prompt surface keep the prior accept-only semantics. On the shell side, `fm_omp_task_doorbell_request_existing` reports an awaiting-turn request as in-flight, so fm-send honestly reports a downgraded doorbell as queued (exit 4 semantics) rather than received while the extension's own recovery still wakes the worker. Regression coverage drives the downgrade end to end: an accepted sendMessage with no turn event stays unproven, the bounded grace re-drives the identical instruction through sendUserMessage exactly once, a firing turn_start settles without any re-drive, an open turn delivers the steer immediately, a failing re-drive reports failed, and a dead generation's unsettled proof re-enters delivery on activate. The suite's tmux fake also now lists the recorded task window so the recovery-grade endpoint check exercises the live path instead of classifying the fixture missing. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(bin): bound detached procevent runners to their owning home's lease A runner is detached into its own process group so it survives the turn that started it, and on its own that lets a runner outlive its whole home: once reparented to init, nothing bounds its lifetime, so a blocking source child - and everything it spawns - can poll forever after the home that owns the work is gone. This is the upstream kunchenguid#3904 port, adapted to the fork's simpler procevent (no extension subsystem or capture reservations). Every claim now records the canonical physical state root with its device, inode, owner, and mode, and every claimed runner spawns a detached owner guard in a separate process group. The guard re-reads the recorded root's .owner-lease marker - refreshed by register, handled, reconcile, sweep, and an attached start's keepalive - and after two consecutive checks cannot prove both the root identity and a fresh lease, it signals the runner's whole process group. Runner descendants inherit FM_PROCEVENT_IN_RUNNER so they cannot keep their own lease alive; a confused agent that deliberately strips the marker is out of scope. Reconcile no longer signals a leaderless surviving group: once the leader is gone, PID/PGID reuse makes the group's provenance unprovable, so the claim stays owned and uncertain instead of risking a foreign group or a second poller on one canonical source. Retirement and reconcile take their signal through an identity-and-leadership-gated group path, and a launch floor paces relaunches per registration generation so a crash-looping source cannot spin. Fork deviations from upstream: the state-root check requires ownership and canonicality but not a private mode (operational homes use group-readable state roots), the serialized launch-floor section releases the source lock at the stamp write because this caller holds no further locked work, central storage keeps its distinct commit point, and the usage window is widened to keep the durability-boundary line visible. Regression coverage: an orphaned runner's group is stopped by its guard after the home's lease expires, a crashed leader's ambiguous group is preserved rather than signalled or replaced, and the registration replacement test now waits for the old generation's source to actually start so the launch-floor supersede check cannot eat the race. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(omp): latch a provider-broken branch with a bounded cooldown probe A settled branch prompt whose last assistant message carries stopReason "error" is a provider failure OMP reports on the message instead of rejecting prompt(), so the old code never latched: every later wake kept paying for a predictably broken branch turn before its settlement could reject to main. Port of upstream kunchenguid#3497, adapted to the fork's extension shape (generation-only guards, offer.accept(promise) settlement). Two consecutive settled provider errors now latch the branch off and merge a captain-facing health note. While latched, main keeps every wake except one recovery probe after each cooldown, which starts at five minutes and doubles to a one-hour ceiling; a probe that ends in a durable fm_branch_report clears the latch with a second note, and a failed probe reschedules by the current cooldown. A settled prompt that produced no durable outcome now rejects its settlement instead of silently claiming its granted wake rows. The branch record keeps its SessionManager so the settled-prompt scan can read only the entries the prompt appended. The strict typecheck also caught two stale errors from the earlier doorbell work: the doorbell options builder returned a Required<> literal missing turnGraceMs, and its `on` property signature could not accept the runtime's overloaded event subscription - the latter is now a method declaration so the parameter stays bivariant. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(omp): start a fresh supervision branch conversation per main session Port of upstream kunchenguid#3600. A branch conversation that outlives its main session keeps reasoning from an older thread's accumulated memory, which competes with today's generated prompt and current fleet rules. The OMP extension kept one persistent conversation keyed on a durable pointer, so /new, /resume, /fork, and reload all reopened the stale thread. The branch record is now scoped to the extension generation: createBranch reopens only a conversation it built under the current generation, and both session_start and session_switch advance the generation, drop the live handle (beginDispose + dispose), and re-anchor the mirror so the fresh branch receives the new main session's dialog from its start. The durable outcome store, not the conversation, carries unacknowledged outcomes across the boundary. The on-disk pointer remains a record for operators and the effort picker's model lookup, not a reopen source. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(omp): give the supervision branch main's live model registry Port of upstream kunchenguid#3871 by equivalent mechanism. A provider an extension registered into main's runtime at run time is invisible to a freshly discovered registry, so pinning or following such a model built a branch that could not resolve its own model. OMP's createAgentSession already takes a modelRegistry option, so instead of upstream's provider-by-provider config copy into an isolated ModelRuntime, the branch session now receives main's live registry directly - read-only sharing: the branch never installs, converts, or overwrites credentials or registrations. The resolve and picker paths already read that same registry, so the build, the pin resolution, and the picker now agree on one model catalog. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(bin/omp): route decision-owned signal and stale wake batches to main Port of upstream kunchenguid#3776. A needs-decision status append, a captain-held status transfer surfaced through the no-verb signal path, or a blocked pending-reply escalation is owned by the captain and must stay on main. The previous logic only forced the check-kind class to main, so a coalesced signal batch that also contained routine rows could end up split: the decision row to the branch, the rest to main, which loses the single-actor ordering the per-actor acknowledgement contract depends on. The bash side now: - `status_span_first_actionable_record` returns a side-band flag when its span carries a needs-decision, a captain-held declaration, or a pending- reply escalation, without changing the event text it already returns. - `signal_files_actionable` surfaces those files (even when the captain-held line is otherwise non-actionable) and populates `FM_SIGNAL_NEEDS_DECISION_FILES`. - The watcher appends the row payload as `needs-decision:$files` for exactly the flagged files; other files in the same batch keep the ordinary reason. The OMP dispatch side now: - `scopeForUnreadWake` parses each mapped task's `.status` log to detect an open needs-decision or a current captain-held declaration, and excludes those rows from `eligibleSeqs` while populating `needsDecisionKeys`. - `offerWakeToBranch` in `fm-primary-omp.ts` cross-references the current signal or stale trigger keys against every unread decision-owned row by task identity: any overlap forces the entire coalesced batch to main. - Heartbeat handling remains independent, and a decision-owned row in one task does not affect eligibility for other tasks. Also fixed a pre-existing full-lint `SC2031` info note in `tests/fm-afk-launch.test.sh` by disabling it file-wide, so the canonical lint run is green again. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(core/omp/pi): settle watcher delivery on runtime acceptance, consume on turn start Port of upstream kunchenguid#3513. A follow-up queued while main is streaming joins that run as a user message without raising before_agent_start, so waiting for the model to consume the wake stalled the successor chain: no successor started, later wakes were not delivered, and the turn-end guard re-armed by hand. The shared core now: - Treats sendFollowUp resolution as delivery; consumption is tracked only to let a session replacement replay a wake the runtime accepted but had not yet read. - Keeps accepted-but-unconsumed wakes in a per-generation unconsumedWakes map keyed by the pending token. - Consumes a wake when the runtime starts a turn carrying the exact wake text: before_agent_start for an idle main, message_start for a streaming main. - Does not mark a pending row delivered or finish cleanup until the wake is consumed or the branch owns it. - Skips over unconsumed rows when picking the next pending record, so the successor chain keeps moving while waiting for a streaming main to read the prior wake. - Defers a verified successor's failure close when the pipeline is still delivering the wake it was started for; the retry runs once that delivery settles. - Adds armRetired so a child the core itself killed does not earn a deferred retry. The Pi and OMP adapters both gain a message_start handler that extracts the user message text and passes it to watch.acknowledgeWake. Documentation in docs/omp-supervision-branch.md now states the delivery versus consumption boundary for main fall-back follow-ups. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * no-mistakes(review): Make supervision provider latch recoverable after transient failures * no-mistakes(review): Correlate doorbells and latch rejected supervision prompts * no-mistakes(review): Correlate doorbell turn proofs and recover prompt failures * no-mistakes(review): Correlate synchronous turn proofs to each doorbell dispatch * no-mistakes(review): Correlate turn proof and redrive uncorrelated doorbells * no-mistakes(test): Fix procevent sweep claims and OMP turn handler coexistence * no-mistakes(test): Preserve claim-only sources for reliable home sweeps * no-mistakes(test): Disabled unreliable turn observation for generated OMP workers * no-mistakes(document): Updated stale branch-session documentation * no-mistakes(review): Enforce state-root identity before ownership and stale-claim decisions * no-mistakes(review): Requeue unreadable awaiting-turn requests for redelivery * no-mistakes(document): Correct stale supervision and process-event verification docs --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 8a5de1e commit caa93c6

46 files changed

Lines changed: 2968 additions & 368 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.omp/extensions/fm-branch-supervision-omp.ts‎

Lines changed: 251 additions & 49 deletions
Large diffs are not rendered by default.

‎.omp/extensions/fm-primary-omp.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ function runGuard(event: SessionStopEvent): Promise<ProcessResult> {
212212
export default function (omp: ExtensionAPI) {
213213
if (!primaryIntegrationApplies()) return;
214214
publishNativeProcessIdentity();
215-
const taskInboxDoorbell = installTaskInboxDoorbell(omp);
215+
const taskInboxDoorbell = installTaskInboxDoorbell(omp, { observeTurns: false });
216216
let pendingStartupNudge = "";
217217

218218
// Hidden next-turn delivery with triggerTurn. OMP schedules an internal
@@ -234,6 +234,24 @@ export default function (omp: ExtensionAPI) {
234234
);
235235
};
236236

237+
// The text OMP carries in a user message_start: sendMessage wraps a string
238+
// as one text part, so the joined text parts equal the sent content.
239+
function userMessageText(content: unknown): string {
240+
if (typeof content === "string") return content;
241+
if (!Array.isArray(content)) return "";
242+
const parts: string[] = [];
243+
for (const part of content) {
244+
if (
245+
typeof part === "object" && part !== null &&
246+
(part as { type?: unknown }).type === "text" &&
247+
typeof (part as { text?: unknown }).text === "string"
248+
) {
249+
parts.push((part as { text: string }).text);
250+
}
251+
}
252+
return parts.join("\n");
253+
}
254+
237255
// Durable rows are the whole persistence: only fm-wake-drain acknowledgement
238256
// removes them, so an interruption leaves the next session event able to
239257
// re-notify. At most one notification is sent per session event, and the
@@ -259,7 +277,26 @@ export default function (omp: ExtensionAPI) {
259277
const heartbeat = /^heartbeat($|:)/.test(message);
260278
const isCheckTrigger = /^check:/.test(message);
261279
const scope = scopeForUnreadWake(state, heartbeat);
262-
const eligible = !isCheckTrigger && scope.eligible;
280+
// A signal close containing a needs-decision status file, or a stale close
281+
// for a captain-held task, gets the identical main-only treatment as a
282+
// check-kind trigger. The cross-reference deliberately includes every
283+
// unread decision row: until that row is read, a later signal or stale
284+
// trigger for the same task stays on main. Other tasks and heartbeat
285+
// handling remain independent.
286+
const triggerKeys = /^signal:/.test(message)
287+
? message
288+
.slice("signal:".length)
289+
.split(/\s+/)
290+
.filter(Boolean)
291+
.map((path) => path.split("/").pop() ?? path)
292+
: /^stale:/.test(message)
293+
? [message.slice("stale:".length).trim().split(/\s+/, 1)[0]].filter(Boolean)
294+
: [];
295+
const taskIdentity = (key: string): string =>
296+
scope.taskByWakeKey[key] ?? scope.taskByWakeKey[key.replace(/^fm-/, "")] ?? key;
297+
const needsDecisionTasks = new Set(scope.needsDecisionKeys.map(taskIdentity));
298+
const isNeedsDecisionTrigger = triggerKeys.some((key) => needsDecisionTasks.has(taskIdentity(key)));
299+
const eligible = !isCheckTrigger && !isNeedsDecisionTrigger && scope.eligible;
263300
const offer = createBranchDispatchOffer(message, scope.projects, heartbeat, eligible);
264301
omp.events?.emit?.(FM_BRANCH_DISPATCH_EVENT, offer);
265302
return offer.accepted ? offer.settlement : null;
@@ -322,6 +359,7 @@ export default function (omp: ExtensionAPI) {
322359
});
323360

324361
omp.on("turn_start", () => {
362+
taskInboxDoorbell.notifyTurnStart();
325363
publishTaskTurnStarted();
326364
});
327365

@@ -350,6 +388,11 @@ export default function (omp: ExtensionAPI) {
350388
};
351389
});
352390

391+
omp.on("message_start", (event) => {
392+
if (event.message.role !== "user") return;
393+
watch.acknowledgeWake(userMessageText(event.message.content));
394+
});
395+
353396
omp.on("session_stop", async (event): Promise<SessionStopEventResult | undefined> => {
354397
if (event.stop_hook_active) return undefined;
355398
const result = await runGuard(event);

‎.omp/extensions/lib/fm-branch-dispatch.ts‎

Lines changed: 152 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { readdirSync, readFileSync } from "node:fs";
1+
import { lstatSync, readdirSync, readFileSync } from "node:fs";
22
import { runCommandAsync } from "./fm-async-exec.ts";
33

44
// Shared wake-dispatch handshake between the OMP watcher adapter (the
@@ -47,10 +47,20 @@ export interface UnreadWakeScope {
4747
* either mode.
4848
*/
4949
corrupted: boolean;
50+
/**
51+
* The exact "key" field of every decision-owned signal or stale row this
52+
* scan excluded. Signal rows are marked by bin/fm-watch.sh; stale rows are
53+
* decision-owned when their task has an open needs-decision or its current
54+
* declaration is captain-held. fm-primary-omp.ts cross-references these
55+
* keys against the current trigger so its entire coalesced batch is forced
56+
* to main.
57+
*/
58+
needsDecisionKeys: string[];
59+
taskByWakeKey: Record<string, string>;
5060
}
5161

52-
const EMPTY_SCOPE: UnreadWakeScope = { status: "empty", eligible: false, projects: [], eligibleSeqs: [], eligibleTasks: [], corrupted: false };
53-
const UNSAFE_SCOPE: UnreadWakeScope = { status: "unsafe", eligible: false, projects: [], eligibleSeqs: [], eligibleTasks: [], corrupted: true };
62+
const EMPTY_SCOPE: UnreadWakeScope = { status: "empty", eligible: false, projects: [], eligibleSeqs: [], eligibleTasks: [], corrupted: false, needsDecisionKeys: [], taskByWakeKey: {} };
63+
const UNSAFE_SCOPE: UnreadWakeScope = { status: "unsafe", eligible: false, projects: [], eligibleSeqs: [], eligibleTasks: [], corrupted: true, needsDecisionKeys: [], taskByWakeKey: {} };
5464

5565
// scopeForUnreadWake is the single owner of branch-eligibility classification
5666
// (docs/omp-supervision-branch.md "Components and their owners" and
@@ -65,6 +75,12 @@ const UNSAFE_SCOPE: UnreadWakeScope = { status: "unsafe", eligible: false, proje
6575
// (.omp/extensions/fm-primary-omp.ts forces every check-kind TRIGGER to main), so nothing
6676
// starves by being left behind.
6777
//
78+
// A signal row whose payload is "needs-decision:"-prefixed, or a stale row
79+
// for a task with an open needs-decision or a current captain-held declaration,
80+
// gets the identical treatment: excluded from eligibleSeqs, never a scan veto,
81+
// and forced to main on its own triggering close (fm-primary-omp.ts's
82+
// offerWakeToBranch). Heartbeat handling remains independent.
83+
//
6884
// That applies to a heartbeat review too, and it is the whole point: a
6985
// heartbeat used to be deferred to main merely because some unrelated check
7086
// row happened to be sitting unread, which put a routine fleet review in the
@@ -81,6 +97,71 @@ const UNSAFE_SCOPE: UnreadWakeScope = { status: "unsafe", eligible: false, proje
8197
// this repo's fm_wake_append could never have produced (an unknown kind, or a
8298
// line that fails the structural tab-field check) also still vetoes the whole
8399
// scan - that is queue corruption, not an everyday mixed queue.
100+
function statusLineVerb(line: string): string {
101+
const beforeColon = line.split(":", 1)[0].split("[", 1)[0].trim();
102+
const words = beforeColon.split(/\s+/);
103+
if (!words.some((word) => word.startsWith("corr="))) return beforeColon;
104+
return words.filter((word, index) => index === 0 || !/^corr=[0-9a-f]{16}$/i.test(word)).join(" ");
105+
}
106+
107+
function decisionKey(line: string): string | null {
108+
const colon = line.indexOf(":");
109+
const beforeColon = colon < 0 ? line : line.slice(0, colon);
110+
const beforeMatch = beforeColon.match(/\[key=([^\]]*)\]/);
111+
const noteMatch = beforeMatch || colon < 0 ? null : line.slice(colon + 1).trimStart().match(/^\[key=([^\]]*)\]/);
112+
const key = (beforeMatch ?? noteMatch)?.[1] ?? "default";
113+
return /^[A-Za-z0-9._-]+$/.test(key) ? key : null;
114+
}
115+
116+
function statusLineNote(line: string): string {
117+
const colon = line.indexOf(":");
118+
if (colon < 0) return line;
119+
const note = line.slice(colon + 1).trimStart();
120+
if (/\[key=[^\]]*\]/.test(line.slice(0, colon))) return note;
121+
const match = note.match(/^\[key=([A-Za-z0-9._-]+)\]/);
122+
return match ? note.slice(match[0].length).trimStart() : note;
123+
}
124+
125+
interface StaleDecisionCacheEntry {
126+
version: string;
127+
config: string;
128+
decisionOwned: boolean;
129+
}
130+
131+
const staleDecisionCache = new Map<string, StaleDecisionCacheEntry>();
132+
133+
function statusFileVersion(path: string): string | null {
134+
try {
135+
const stat = lstatSync(path);
136+
if (stat.isSymbolicLink()) throw new Error("status path is a symbolic link");
137+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
138+
} catch (error) {
139+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
140+
throw error;
141+
}
142+
}
143+
144+
function hasOpenNeedsDecision(
145+
lines: readonly string[],
146+
resolveVerb: string,
147+
heldVerb: string,
148+
reservedPrefixes: readonly string[],
149+
): boolean {
150+
const open = new Map<string, "needs-decision" | "blocked">();
151+
for (const line of lines) {
152+
const verb = statusLineVerb(line);
153+
if (!["needs-decision", "blocked", resolveVerb, heldVerb].includes(verb)) continue;
154+
const key = decisionKey(line);
155+
if (!key) continue;
156+
const note = statusLineNote(line);
157+
const reservedPrefix = reservedPrefixes.find((prefix) => key.startsWith(prefix));
158+
if (reservedPrefix && !(note.startsWith(reservedPrefix) && note.slice(reservedPrefix.length).includes(":"))) continue;
159+
if (verb === "needs-decision" || verb === "blocked") open.set(key, verb);
160+
else open.delete(key);
161+
}
162+
return [...open.values()].includes("needs-decision");
163+
}
164+
84165
export function scopeForUnreadWake(state: string, heartbeat: boolean): UnreadWakeScope {
85166
let queue = "";
86167
try {
@@ -105,6 +186,8 @@ export function scopeForUnreadWake(state: string, heartbeat: boolean): UnreadWak
105186
if (project) {
106187
metadata.set(task, project);
107188
taskByKey.set(task, task);
189+
taskByKey.set(`${task}.status`, task);
190+
taskByKey.set(`${task}.turn-ended`, task);
108191
if (window) {
109192
metadata.set(window, project);
110193
taskByKey.set(window, task);
@@ -117,6 +200,14 @@ export function scopeForUnreadWake(state: string, heartbeat: boolean): UnreadWak
117200

118201
const eligibleSeqs: string[] = [];
119202
const eligibleTasks = new Set<string>();
203+
const needsDecisionKeys: string[] = [];
204+
const staleDecisionOwnership = new Map<string, boolean>();
205+
const resolveVerb = process.env.FM_CLASSIFY_RESOLVE_VERB || "resolved";
206+
const heldVerb = process.env.FM_CLASSIFY_CAPTAIN_HELD_VERB || "captain-held";
207+
const reservedPrefixes = (process.env.FM_CLASSIFY_RESERVED_KEY_PREFIXES || "pending-reply-")
208+
.split(/\s+/)
209+
.filter(Boolean);
210+
const decisionConfig = `${resolveVerb}${heldVerb}${reservedPrefixes.join("")}`;
120211
for (const line of rows) {
121212
const fields = line.split("\t");
122213
if (fields.length < 5 || !/^[0-9]+$/.test(fields[1])) return UNSAFE_SCOPE;
@@ -136,11 +227,59 @@ export function scopeForUnreadWake(state: string, heartbeat: boolean): UnreadWak
136227
let project = "";
137228
let task = "";
138229
if (kind === "signal") {
230+
const payload = fields[4] ?? "";
231+
if (/^needs-decision:/.test(payload)) {
232+
// Main-owned exactly like a check-kind row above: a needs-decision
233+
// status append surfaced through the actionable signal path is
234+
// excluded from what the branch may claim without vetoing the scan
235+
// (docs/omp-supervision-branch.md "Autonomy").
236+
needsDecisionKeys.push(key);
237+
continue;
238+
}
139239
task = key.replace(/\.(?:status|turn-ended)$/, "");
140240
project = metadata.get(task) ?? "";
141241
} else if (kind === "stale") {
142242
task = taskByKey.get(key) ?? taskByKey.get(key.replace(/^fm-/, "")) ?? "";
143243
project = metadata.get(key) ?? metadata.get(key.replace(/^fm-/, "")) ?? "";
244+
if (task) {
245+
const statusPath = `${state}/${task}.status`;
246+
if (!staleDecisionOwnership.has(statusPath)) {
247+
let version: string | null;
248+
try {
249+
version = statusFileVersion(statusPath);
250+
} catch {
251+
return UNSAFE_SCOPE;
252+
}
253+
let decisionOwned = false;
254+
if (version) {
255+
const cached = staleDecisionCache.get(statusPath);
256+
if (cached?.version === version && cached.config === decisionConfig) {
257+
decisionOwned = cached.decisionOwned;
258+
} else {
259+
let statusLines: string[];
260+
try {
261+
statusLines = readFileSync(statusPath, "utf8").split(/\r?\n/).filter((line) => /\S/.test(line));
262+
if (statusFileVersion(statusPath) !== version) return UNSAFE_SCOPE;
263+
} catch {
264+
return UNSAFE_SCOPE;
265+
}
266+
decisionOwned = hasOpenNeedsDecision(statusLines, resolveVerb, heldVerb, reservedPrefixes) ||
267+
statusLineVerb(statusLines.at(-1) ?? "") === heldVerb;
268+
staleDecisionCache.set(statusPath, { version, config: decisionConfig, decisionOwned });
269+
if (staleDecisionCache.size > 512) {
270+
staleDecisionCache.delete(staleDecisionCache.keys().next().value!);
271+
}
272+
}
273+
} else {
274+
staleDecisionCache.delete(statusPath);
275+
}
276+
staleDecisionOwnership.set(statusPath, decisionOwned);
277+
}
278+
if (staleDecisionOwnership.get(statusPath)) {
279+
needsDecisionKeys.push(key);
280+
continue;
281+
}
282+
}
144283
} else {
145284
// A kind fm_wake_append never emits: structural corruption, not an
146285
// ordinary main-only row.
@@ -159,7 +298,16 @@ export function scopeForUnreadWake(state: string, heartbeat: boolean): UnreadWak
159298
// empty eligible set, so reading eligibility off the claim set rather than
160299
// off the heartbeat flag changes no pre-existing outcome and keeps a
161300
// heartbeat from being offered with nothing to hand over.)
162-
return { status: eligible ? "safe" : "unsafe", eligible, projects: [...projects], eligibleSeqs, eligibleTasks: [...eligibleTasks], corrupted: false };
301+
return {
302+
status: eligible ? "safe" : "unsafe",
303+
eligible,
304+
projects: [...projects],
305+
eligibleSeqs,
306+
eligibleTasks: [...eligibleTasks],
307+
corrupted: false,
308+
needsDecisionKeys,
309+
taskByWakeKey: Object.fromEntries(taskByKey),
310+
};
163311
}
164312

165313
// The exact state-relative filename bin/fm-wake-drain.sh reads for a

0 commit comments

Comments
 (0)