feat(control): structured loop-control fields end-to-end

Phase 1 of the sustainable autopilot-control refactor. Adds explicit
block-reason + no-op-count fields to the session.md handoff, plumbs
them through parser → desktop pusher → API → DB → React, and updates
the bash guard to read them directly. Eliminates the three-vocabulary
problem that caused the OC no-op spiral on 2026-06-08, where agent's
"health: critical — awaiting user" string collided with the bash
guard's first-word match.

Schema:
- ORCHESTRATION_TASK_SUMMARY_FIELDS gains "block-reason" + "no-op-count"
- SessionState gains blockReason?: string + noOpCount?: number
- project_states adds session_block_reason + session_no_op_count columns

Pipeline:
- control-fast-state.parseSession projects kebab-case → camelCase
- desktop pusher payload + runtime-state route + persistSessionIfNewer
  all carry the new fields
- /api/control/route + /api/control/stream re-emit them to React

Consumers:
- session-state.ts derivations prefer structured fields, fall back to
  content-sniffing for pre-2026-06-08 sessions
- autopilot-needs-fire bash guard reads block-reason + no-op-count
  directly; same fallbacks active
- agent-hook-bridge + fleetcrown-daemon handoff templates and the
  blocker_create SPACE prompt now instruct agents to emit the fields

Memory of why this exists: OC ran 21 no-op turns (~60k tokens) in an
hour because three layers parsed the agent's intent from free text
with different rules. Phase 2 (daemon owns the should-fire decision)
follows; bash guard's content-sniff fallbacks live until every agent
has rotated through the new template.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mao NakamotoandClaude Opus 4.7 committed 2026-06-08 15:50:30 +02:00
1 parent deda43539b
commit 729237cd69
13 files changed
+296 -21

No files matched your search

+8
View File
@@ -133,6 +133,12 @@ type ProjectRuntimePayload = {
sessionTests?: string
sessionTodos?: string
sessionHealth?: string
/** Structured loop-control fields written by the agent itself. See
* src/lib/orchestration/contract.ts and the OC 2026-06-08 incident.
* Sourced from `block-reason:` and `no-op-count:` lines in session.md;
* optional because pre-2026-06-08 sessions don't emit them. */
sessionBlockReason?: string
sessionNoOpCount?: number
sessionUpdatedAt?: number | null
}
@@ -177,6 +183,8 @@ function buildProjectRuntimePayload(openTabs: string[]): ProjectRuntimePayload[]
sessionTests: state.session?.tests,
sessionTodos: state.session?.todos,
sessionHealth: state.session?.health,
sessionBlockReason: state.session?.blockReason,
sessionNoOpCount: state.session?.noOpCount,
sessionUpdatedAt: state.session?.mtime ? Math.floor(state.session.mtime / 1000) : null,
}))
}
+8 -4
View File
@@ -555,12 +555,14 @@ autopilot_dispatch_and_inject() {
return 1
fi
session_update_block="When done, update ${session_file} with exactly these lines:
status: ready | working # 'ready' = fully done; auto-inject may fire. 'working' = more to do.
status: ready | working | blocked # 'ready' = fully done (auto-inject may fire); 'working' = more to do; 'blocked' = awaiting a human action you cannot take (no auto-inject)
done: <one sentence what you completed>
next: <one sentence what remains>
tests: <N pass · N fail, or 'no suite'>
todos: <count> TODOs
health: <good | needs attention | critical>"
health: <good | needs attention | critical>
block-reason: <awaiting_user | external_dependency | manual_pause | none> # 'none' (or omit) when status != blocked. Required when status: blocked.
no-op-count: <integer> # 0 if you did real work this turn. Increment from the previous value if this was a no-op turn (queue empty, nothing to pick)."
if [ -f "$session_file" ]; then
session=$(cat "$session_file")
@@ -818,12 +820,14 @@ handle_notification() {
base=$(get_prompt "$auto_key")
[ -z "$base" ] && exit 0
session_update_block="When done, update ${session_file} with exactly these lines:
status: ready | working # 'ready' = fully done; auto-inject may fire. 'working' = more to do.
status: ready | working | blocked # 'ready' = fully done (auto-inject may fire); 'working' = more to do; 'blocked' = awaiting a human action you cannot take (no auto-inject)
done: <one sentence what you completed>
next: <one sentence what remains>
tests: <N pass · N fail, or 'no suite'>
todos: <count> TODOs
health: <good | needs attention | critical>"
health: <good | needs attention | critical>
block-reason: <awaiting_user | external_dependency | manual_pause | none> # 'none' (or omit) when status != blocked. Required when status: blocked.
no-op-count: <integer> # 0 if you did real work this turn. Increment from the previous value if this was a no-op turn (queue empty, nothing to pick)."
if [ -f "$session_file" ]; then
session=$(cat "$session_file")
+3 -1
View File
@@ -412,12 +412,14 @@ When you finish the current task (or need to hand off), write your final status
$correct_handoff_file
Use exactly this format (one field per line):
status: ready | working # 'ready' = fully done; auto-inject may fire. 'working' = more to do.
status: ready | working | blocked # 'ready' = fully done (auto-inject may fire); 'working' = more to do; 'blocked' = awaiting a human action you cannot take (no auto-inject)
done: <one clear sentence of what you accomplished in this turn>
next: <precise next step or exact state to resume from>
tests: <N pass · N fail, or 'no suite'>
todos: <count of open TODO/FIXME/HACK items>
health: good | needs attention | critical
block-reason: <awaiting_user | external_dependency | manual_pause | none> # 'none' (or omit) when status != blocked. Required when status: blocked.
no-op-count: <integer> # 0 if you did real work this turn. Increment from the previous value if this was a no-op turn (queue empty, nothing to pick).
last-3-same-dir: yes | no
wip-or-revert-in-last-5: yes | no
tsc: pass | fail(N)
+5
View File
@@ -209,6 +209,9 @@ export async function GET() {
tests: dbState.sessionTests ?? "",
todos: dbState.sessionTodos ?? "",
health: dbState.sessionHealth ?? "",
...(dbState.sessionBlockReason ? { blockReason: dbState.sessionBlockReason } : {}),
...(dbState.sessionNoOpCount !== null && dbState.sessionNoOpCount !== undefined
? { noOpCount: dbState.sessionNoOpCount } : {}),
mtime: dbState.sessionUpdatedAt?.getTime() ?? 0,
}
: null);
@@ -234,6 +237,8 @@ export async function GET() {
sessionTests: session.tests,
sessionTodos: session.todos,
sessionHealth: session.health,
sessionBlockReason: session.blockReason,
sessionNoOpCount: session.noOpCount,
sessionUpdatedAt: new Date(sessionMtimeMs),
}).then((updated) => {
// Append only for the writer that won the timestamp race.
@@ -25,6 +25,10 @@ interface ProjectRuntimePatch {
sessionTests?: string;
sessionTodos?: string;
sessionHealth?: string;
/** Structured loop-control fields. See ProjectRuntimePayload in
* desktop/src/main/pusher.ts and src/lib/orchestration/contract.ts. */
sessionBlockReason?: string;
sessionNoOpCount?: number;
sessionUpdatedAt?: number | null; // epoch seconds (file mtime)
}
@@ -105,6 +109,8 @@ export async function POST(req: NextRequest) {
...(p.sessionTests !== undefined && { sessionTests: p.sessionTests }),
...(p.sessionTodos !== undefined && { sessionTodos: p.sessionTodos }),
...(p.sessionHealth !== undefined && { sessionHealth: p.sessionHealth }),
...(p.sessionBlockReason !== undefined && { sessionBlockReason: p.sessionBlockReason }),
...(p.sessionNoOpCount !== undefined && { sessionNoOpCount: p.sessionNoOpCount }),
}).catch((err) => console.error("[runtime-state] session write failed:", err));
}
}));
+12 -1
View File
@@ -36,7 +36,18 @@ function dbToFastState(
tabOpen: r.tabOpen,
activeAgents: r.activeAgents,
session: r.sessionDone || r.sessionNext
? { status: r.sessionStatus ?? "", done: r.sessionDone ?? "", next: r.sessionNext ?? "", tests: r.sessionTests ?? "", todos: r.sessionTodos ?? "", health: r.sessionHealth ?? "", mtime: r.sessionUpdatedAt?.getTime() ?? 0 }
? {
status: r.sessionStatus ?? "",
done: r.sessionDone ?? "",
next: r.sessionNext ?? "",
tests: r.sessionTests ?? "",
todos: r.sessionTodos ?? "",
health: r.sessionHealth ?? "",
...(r.sessionBlockReason ? { blockReason: r.sessionBlockReason } : {}),
...(r.sessionNoOpCount !== null && r.sessionNoOpCount !== undefined
? { noOpCount: r.sessionNoOpCount } : {}),
mtime: r.sessionUpdatedAt?.getTime() ?? 0,
}
: null,
currentPrompt: r.currentPromptKey
? { key: r.currentPromptKey, label: r.currentPromptLabel ?? r.currentPromptKey, startedAt: r.currentPromptStartedAt ? Math.floor(r.currentPromptStartedAt.getTime() / 1000) : 0, source: "inject" as const }
+84 -7
View File
@@ -8,8 +8,20 @@ import type { ProjectState } from "@/lib/control-types";
import { formatAgentRuntimeLabel } from "./control-presenter";
import { AgentSwitcherPopover } from "./agent-switcher-popover";
import type { AgentEntry } from "./agent-switcher-popover";
import {
agentLabel,
hasAgentLabelMismatch,
resolveDisplayedAgentId,
} from "@/lib/agent-resolution";
import { deriveLoopState } from "@/lib/session-state";
import { FEEDBACK_MEDIUM_MS, TOAST_MEDIUM_MS, TOAST_LONG_MS } from "@/lib/constants/timings";
/** Below this count, a no-op turn could be coincidence (queue drained between
* user turns). At or above, it's a pattern worth surfacing. The autopilot-
* needs-fire bash guard catches even count=1 to stop the spiral; this UI
* threshold is purely about how loudly to display it. */
const LOOP_NO_OP_DISPLAY_THRESHOLD = 2;
function statusChipClass(tone: "neutral" | "positive" | "warning" = "neutral", clickable = false) {
return cn(
"inline-flex min-h-11 sm:min-h-7 max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs leading-none transition-colors",
@@ -81,10 +93,22 @@ export function ProjectStatusChips({
? `Pending changes means files were edited in this project but are not saved into Git history yet. Branch: ${git.branch}. In Git, a commit is the checkpoint that records those changes.`
: `Branch: ${git?.branch}. No local file changes detected.`;
// localAgentId wins (reflects in-session switch before next API poll)
const effectiveAgentId = localAgentId ?? project.agentPref ?? (availableAgents?.[0]?.id ?? "");
const effectiveAgentId = resolveDisplayedAgentId(project, localAgentId, project.liveTab)
|| localAgentId
|| project.agentPref
|| (availableAgents?.[0]?.id ?? "");
const labelMismatch = hasAgentLabelMismatch(project, localAgentId, project.liveTab);
const canSwitchAgent = onSwitchAgent && availableAgents && availableAgents.length > 1;
// Loop state lives on a separate axis from per-turn agent state. An agent
// can be `ready` (current chip says "ready") while the autopilot loop is
// about to re-fire it for the 22nd no-op turn — invisible without this.
// See src/lib/session-state.ts and the OC 2026-06-08 incident analysis.
const loop = deriveLoopState(project.session);
const showAwaitingUser = loop.awaitingUser;
const showLoopSpiral =
!showAwaitingUser && loop.state === "firing" && (loop.noOpCount ?? 0) >= LOOP_NO_OP_DISPLAY_THRESHOLD;
const focusWorkspace = async (event: React.MouseEvent) => {
event.stopPropagation();
if (workspaceState === "loading") return;
@@ -136,11 +160,24 @@ export function ProjectStatusChips({
<button
type="button"
onClick={(e) => { e.stopPropagation(); if (!switchingAgent) setAgentPopoverOpen((v) => !v); }}
title={switchingAgent ? "Switching agent…" : `${runtimeLabel} — click to switch agent for this project`}
title={
switchingAgent
? "Switching agent…"
: labelMismatch
? `Live: ${project.activeAgents.map(agentLabel).join(", ")} — preference: ${agentLabel(localAgentId ?? project.agentPref ?? "?")}. Click to switch.`
: `${runtimeLabel} — click to switch agent for this project`
}
disabled={switchingAgent}
className={compact
? "flex items-center gap-1 text-text-secondary transition-colors hover:text-text-primary disabled:opacity-60"
: cn(statusChipClass(switchingAgent ? "neutral" : working ? "warning" : "neutral", !switchingAgent), "cursor-pointer disabled:cursor-default disabled:opacity-70")}
? cn(
"flex items-center gap-1 transition-colors hover:text-text-primary disabled:opacity-60",
labelMismatch ? "text-status-warning" : "text-text-secondary",
)
: cn(
statusChipClass(switchingAgent ? "neutral" : working ? "warning" : labelMismatch ? "warning" : "neutral", !switchingAgent),
"cursor-pointer disabled:cursor-default disabled:opacity-70",
labelMismatch && !switchingAgent && "ring-1 ring-status-warning/50 animate-pulse",
)}
>
{switchingAgent
? <><Loader2 className="h-3 w-3 shrink-0 animate-spin" /><span>Switching…</span></>
@@ -159,14 +196,54 @@ export function ProjectStatusChips({
</div>
) : (
<span
className={compact ? undefined : statusChipClass(working ? "warning" : "neutral")}
title={`Live agent in this workspace: ${runtimeLabel}. Source: local process scan on your machine (via daemon or direct). Not a cloud guess. If this says the wrong agent (e.g. "Claude" while you're running Grok), the tab name or active process detection may be stale — use the switcher or repair helper.`}
className={cn(
compact ? undefined : statusChipClass(working ? "warning" : labelMismatch ? "warning" : "neutral"),
labelMismatch && !compact && "ring-1 ring-status-warning/50",
)}
title={
labelMismatch
? `Detected ${project.activeAgents.map(agentLabel).join(", ")} running, but preference shows ${agentLabel(localAgentId ?? project.agentPref ?? "?")}. Open project settings or use Brain config to align.`
: `Live agent in this workspace: ${runtimeLabel}. Click the agent chip on an open tab to switch without typing quit commands in the terminal.`
}
>
{runtimeStateLabel}
{labelMismatch && !compact && (
<span className="ml-1 text-status-warning">· mismatch</span>
)}
</span>
)
)}
{/* Agent-declared "I'm blocked on you" state. Sourced from session.md
(health contains "awaiting user" OR status: blocked) — the agent
itself raises this via the blocker_create flow. Takes priority
over the loop-spiral chip because it tells the captain WHY the
loop isn't progressing. */}
{showAwaitingUser && (
<span
className={compact ? "text-status-warning" : statusChipClass("warning")}
title={`Agent is waiting on you. Last reported next step: "${project.session?.next ?? "(none)"}". Open the project's session handoff or check ~/.claude/sessions/${project.tab}.blockers/pending/ for the blocker file.`}
>
Awaiting you
</span>
)}
{/* Loop spiral detection. The agent writes `done: No-op turn #N.` when
the autopilot loop fires a turn with nothing to do; counting those
is the cheapest spiral-detector available. Visible only when the
agent is "ready" AND has logged N>=2 no-op turns. Once the bash
guard sees the same signal it stops firing, so this chip should
disappear within one tick of the next session.md write — if it
persists, the wrapper isn't calling autopilot-needs-fire. */}
{showLoopSpiral && (
<span
className={compact ? "text-status-warning" : statusChipClass("warning")}
title={`Autopilot loop has fired ${loop.noOpCount} consecutive no-op turns. The bash guard (~/.claude/bin/autopilot-needs-fire) should stop further firings; if you see this count keep climbing, the wrapper isn't calling the guard.`}
>
Looping · {loop.noOpCount} no-ops
</span>
)}
{/* Per-project pause indicator — makes the existing auto-continue toggle obvious at card level */}
{!autoContinueEnabled && (
<span
+7 -2
View File
@@ -171,7 +171,8 @@ export async function prependProjectPrompt(
type SessionFields = Pick<
NewProjectState,
"sessionStatus" | "sessionDone" | "sessionNext" | "sessionTests" | "sessionTodos" | "sessionHealth"
"sessionStatus" | "sessionDone" | "sessionNext" | "sessionTests" | "sessionTodos" | "sessionHealth" |
"sessionBlockReason" | "sessionNoOpCount"
>;
type RuntimeFields = Pick<
@@ -234,7 +235,11 @@ export async function persistProjectSessionIfNewer(
updatedAt: new Date(),
sessionUpdatedAt: patch.sessionUpdatedAt,
};
for (const key of ["projectId", "tabName", "sessionStatus", "sessionDone", "sessionNext", "sessionTests", "sessionTodos", "sessionHealth"] as const) {
for (const key of [
"projectId", "tabName", "sessionStatus", "sessionDone", "sessionNext",
"sessionTests", "sessionTodos", "sessionHealth",
"sessionBlockReason", "sessionNoOpCount",
] as const) {
const value = patch[key];
if (value !== undefined) (updateSet as Record<string, unknown>)[key] = value;
}
+5
View File
@@ -24,6 +24,11 @@ export const projectStates = pgTable("project_states", {
sessionTests: text("session_tests"),
sessionTodos: text("session_todos"),
sessionHealth: text("session_health"),
// 2026-06-08 — explicit loop-control fields added so the autopilot decision
// (skip vs. fire) reads structured data instead of content-sniffing the
// free-text done:/health: strings. See src/lib/orchestration/contract.ts.
sessionBlockReason: text("session_block_reason"), // 'awaiting_user' | 'external_dependency' | 'manual_pause' | null
sessionNoOpCount: integer("session_no_op_count"), // consecutive no-op turns; agent increments each turn
sessionUpdatedAt: timestamp("session_updated_at", { withTimezone: true }),
currentPromptKey: text("current_prompt_key"),
currentPromptLabel: text("current_prompt_label"),
+15 -1
View File
@@ -11,7 +11,21 @@ export function parseSession(tab: string, adapter = "claude"): SessionState | nu
const raw = fs.readFileSync(file, "utf-8");
const fields = parseSessionFile(raw);
const mtime = fs.statSync(file).mtimeMs;
return { ...fields, mtime };
// Project the kebab-case loop-control fields into camelCase SessionState
// shape. Kept narrow: only the two structured fields are surfaced; the
// other kebab fields (last-3-same-dir, wip-or-revert-in-last-5) stay in
// OrchestrationTaskSummary's purview and don't leak into ProjectState.
const blockReasonRaw = fields["block-reason"]?.trim();
const noOpCountRaw = fields["no-op-count"]?.trim();
const noOpCount = noOpCountRaw && /^\d+$/.test(noOpCountRaw)
? parseInt(noOpCountRaw, 10)
: undefined;
return {
...fields,
...(blockReasonRaw ? { blockReason: blockReasonRaw } : {}),
...(noOpCount !== undefined ? { noOpCount } : {}),
mtime,
};
} catch {
return null;
}
+17 -5
View File
@@ -22,17 +22,29 @@ export type CurrentPrompt = {
export type SessionState = {
/** Agent's self-reported lifecycle state: 'ready' = done, auto-inject may
* proceed; 'working' = mid-task, suppress auto-inject. Missing/undefined
* is treated as NOT ready by the auto-inject gates (conservative). Optional
* so legacy construction sites that don't yet plumb session_status can
* omit it during the back-compat window — they'll just suppress auto-fire
* which matches the user's stated intent. */
* proceed; 'working' = mid-task, suppress auto-inject; 'blocked' = agent
* has handed control back to the user (loop must not fire). Missing/
* undefined is treated as NOT ready by the auto-inject gates (conservative).
* Optional so legacy construction sites that don't yet plumb session_status
* can omit it during the back-compat window — they'll just suppress
* auto-fire which matches the user's stated intent. */
status?: string;
done: string;
next: string;
tests: string;
todos: string;
health: string;
/** Why the agent is blocked, when status: 'blocked' OR the agent's last
* turn was a no-op pending user input. SSOT for the "Awaiting you" chip.
* Sourced from `block-reason:` line in session.md. Optional because
* pre-2026-06-08 sessions don't emit it — deriveLoopState falls back to
* content-sniffing health/status for those. */
blockReason?: string;
/** Number of consecutive no-op turns the autopilot loop has fired. The
* agent increments this each turn it picks no work. Sourced from
* `no-op-count:` line in session.md. Pure metric — no business logic
* attached, the bash guard skips when this is >= 1. */
noOpCount?: number;
mtime: number; // epoch milliseconds
};
+10
View File
@@ -100,6 +100,14 @@ export const ORCHESTRATION_TASK_SUMMARY_FIELDS = [
"next",
// Retained for summaries written before LOOP v2.
"health",
// 2026-06-08 — explicit loop-control fields. Added because the OC no-op
// spiral surfaced that all three consumers (bash guard, React chips, agent)
// were parsing the same intent ("agent is blocked on user", "21 no-ops")
// out of free-text done:/health: strings with different rules. These fields
// are the SSOT; content-sniffs in session-state.ts + the bash guard remain
// as fallbacks for sessions written before agents started emitting them.
"block-reason", // "awaiting_user" | "external_dependency" | "manual_pause"
"no-op-count", // integer, monotonically incremented by the agent on each no-op turn
] as const;
export type OrchestrationTaskSummaryField = (typeof ORCHESTRATION_TASK_SUMMARY_FIELDS)[number];
@@ -116,6 +124,8 @@ export type OrchestrationTaskSummary = {
"wip-or-revert-in-last-5"?: string;
tsc?: string;
lint?: string;
"block-reason"?: string;
"no-op-count"?: string;
};
export type OrchestrationTaskStatus = {
+116
View File
@@ -0,0 +1,116 @@
/**
* Pure derivations from a project's SessionState (the YAML-ish handoff the
* agent itself writes to ~/.claude/sessions/<project>.md). The shape is
* already flowed end-to-end:
*
* agent writes session.md
* → desktop control-fast-state.readFastState parses it
* → desktop pusher.ts POSTs sessionStatus/sessionDone/sessionHealth/…
* → /api/control/runtime-state stores it
* → ControlData.projects[i].session reaches the React layer
*
* Until 2026-06-08 the React layer rendered exactly one fact from this:
* "working vs ready" (via project.currentPrompt, not even session.status).
* The OC no-op spiral that day showed why that's not enough — an agent
* stuck in `status: ready` with `done: No-op turn #21` looked identical
* to a genuinely idle project. These helpers derive the two states the
* chips need:
*
* - awaitingUser: agent is blocked on a human action (OAuth, deploy,
* credential) — firing the loop again wastes tokens
* - looping: agent's last `done:` line matches the no-op pattern,
* with the count parsed out of the agent's own `No-op turn #N.` text
*
* Both are content-sniffed because the session.md format is a free-text
* convention, not a schema. If the convention tightens later (e.g., a
* dedicated `awaiting_user: true` field), update the helpers — the
* consumer call sites already encode the intent.
*/
import type { SessionState } from "@/lib/control-types";
/**
* Read `noOpCount` from the structured field if the agent wrote one; otherwise
* sniff `done: No-op turn #N.` for back-compat with pre-2026-06-08 sessions.
* Returns null when neither source has a value.
*
* structured field 5 → 5
* "No-op turn #21" only → 21 (legacy path)
* "Fixed the bug" → null
*
* The split-source contract is intentional: agents that emit `no-op-count:`
* win unconditionally — the parser is the SSOT once the prompt template lands.
*/
export function parseNoOpCount(
doneOrSession: string | SessionState | undefined | null,
): number | null {
if (!doneOrSession) return null;
// Object form: prefer the structured field.
if (typeof doneOrSession === "object") {
if (typeof doneOrSession.noOpCount === "number") return doneOrSession.noOpCount;
return parseNoOpCountFromText(doneOrSession.done);
}
return parseNoOpCountFromText(doneOrSession);
}
function parseNoOpCountFromText(done: string | undefined | null): number | null {
if (!done) return null;
const match = done.match(/no-op\s+turn\s+#(\d+)/i);
return match ? parseInt(match[1]!, 10) : null;
}
/**
* True when the agent is blocked on a human action. Reads the structured
* `blockReason` field if present; otherwise content-sniffs `status: blocked`
* or `health: … awaiting user` for back-compat.
*
* Agents emitting the structured field win unconditionally — the moment all
* SPACE templates ship the new format, the content-sniff arm goes cold.
*/
export function isAwaitingUser(session: SessionState | null | undefined): boolean {
if (!session) return false;
if (session.blockReason) return true;
if (session.status?.toLowerCase().trim() === "blocked") return true;
return /awaiting\s+user/i.test(session.health ?? "");
}
/**
* Derived loop state — distinct from `status: ready | working` because the
* autopilot loop is a separate axis from the agent's per-turn lifecycle.
*
* firing → agent is `ready` and the wrapper will re-invoke it on the
* next tick. If noOpCount >= 1 it's a spiral.
* active → agent is mid-turn (status: working). Loop is implicitly alive.
* paused → agent is blocked on the user; the loop should NOT fire (and
* the patched autopilot-needs-fire guard ensures it doesn't).
* unknown → no session.md ever pushed (new project, daemon never seen).
*/
export type LoopState = "firing" | "active" | "paused" | "unknown";
export type DerivedLoopState = {
state: LoopState;
/** Pulled out of `done: No-op turn #N.` when present. */
noOpCount: number | null;
/** True when the agent's last write put it in a human-blocked state. */
awaitingUser: boolean;
};
export function deriveLoopState(session: SessionState | null | undefined): DerivedLoopState {
if (!session) {
return { state: "unknown", noOpCount: null, awaitingUser: false };
}
const awaitingUser = isAwaitingUser(session);
// Pass the whole session so the structured `noOpCount` field wins over
// content-sniffing `done:` text. Both paths still work — only the priority
// changes once agents start emitting the structured field.
const noOpCount = parseNoOpCount(session);
const status = session.status?.toLowerCase().trim();
if (awaitingUser) return { state: "paused", noOpCount, awaitingUser };
if (status === "working") return { state: "active", noOpCount, awaitingUser };
if (status === "ready") return { state: "firing", noOpCount, awaitingUser };
// Missing/unknown status — treat as firing-ish so the UI surfaces the
// count if a spiral is forming, but the bash guard suppresses real
// wake-ups (its default-fire only triggers when status semantics check out).
return { state: "firing", noOpCount, awaitingUser };
}