Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Supervisor agent can direct siblings from the Agent tab

Cursor Agent335a68fa4c18
diff --git a/docs/adr/0146-ambient-peer-wakes-are-not-authoritative.md b/docs/adr/0146-ambient-peer-wakes-are-not-authoritative.md
new file mode 100644
index 00000000..f7d715b0
--- /dev/null
+++ b/docs/adr/0146-ambient-peer-wakes-are-not-authoritative.md
@@ -0,0 +1,32 @@
+# 0146. Ambient peer wakes are not task-authoritative; daddy directives are
+
+Status: accepted 2026-09-21
+
+## Context
+
+ADR 0004 parks peer bodies and injects a one-line `[peer]` wake. That wake
+was still a user-role history line, appended at every root step — including
+tool-result continuation and immediately after `attempt_completion`. Ambient
+coordination then became the newest instruction and could restart a finished
+turn (#1137).
+
+A supervisor ("daddy") agent on the GUI Agent tab needs the opposite: an
+explicit directive that *may* steer or wake a named sibling.
+
+## Decision
+
+- Ambient mailbox wakes coalesce by generation, never inject during tool
+ continuation, and never start an idle turn after `attempt_completion` until
+ a later human prompt. `action=inbox` retires the stale `[peer]` lines.
+- A `[daddy]` directive (`peer_message action=direct` / `/daddy`) is named
+ control. An idle root may start a turn on it even after completion. The GUI
+ Agent tab sends the same prefix into the target conversation.
+- Children in one process stay on `agent_message`. Daddy is the
+ cross-session path. Surface chrome differs; the engine path is shared by
+ REPL, TUI, and `graff acp`.
+
+## Consequences
+
+Parked ambient mail remains readable on the next human turn. Completing a
+task no longer reopens on a greeting. Revisit if a structured control
+channel replaces the prefixed DM.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c44ef9ed..a3c2b57b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -165,6 +165,7 @@ record only when you need the evidence or the edge cases.
| [0143](0143-release-desktop-is-com-codegraff-app.md) | Packaged Codegraff.app is `com.codegraff.app`. `dev.*` identities are local rebuilds only. |
| [0144](0144-claim-asks-on-accord.md) | Claim conflicts ping the owner on Accord/JSONL; the model does not broker handoff in chat. |
| [0145](0145-live-claims-are-accord-progress.md) | Claim acquire/release/handoff replicate as replaceable Accord progress; the JSON ledger stays canonical. |
+| [0146](0146-ambient-peer-wakes-are-not-authoritative.md) | Ambient `[peer]` wakes are not a new task; `[daddy]` directives are explicit supervisor control. |
## When to write one
diff --git a/gui/src/app/projections/agents.test.ts b/gui/src/app/projections/agents.test.ts
index 64f131cc..342a8f64 100644
--- a/gui/src/app/projections/agents.test.ts
+++ b/gui/src/app/projections/agents.test.ts
@@ -5,7 +5,14 @@ import type {
SessionMessage,
} from "@/services/desktop/types/contracts";
-import { buildAgentOverview, formatAgentActivityLabel } from "./agents";
+import {
+ buildAgentOverview,
+ canDirect,
+ currentSupervisorTitle,
+ formatAgentActivityLabel,
+ formatDaddyDirective,
+ type AgentOverviewItem,
+} from "./agents";
function view(messages: SessionMessage[]): ConversationViewSnapshot {
return {
@@ -241,3 +248,67 @@ describe("formatAgentActivityLabel", () => {
);
});
});
+
+function overviewItem(
+ overrides: Partial<AgentOverviewItem> = {},
+): AgentOverviewItem {
+ return {
+ id: "item",
+ agentId: "forge",
+ conversationId: "conversation-1",
+ conversationTitle: "Fix login",
+ workspacePath: "/code/project",
+ kind: "orchestrator",
+ label: "Main agent",
+ detail: "Ready",
+ status: "idle",
+ followup: null,
+ isCurrentConversation: false,
+ sequence: 0,
+ ...overrides,
+ };
+}
+
+describe("daddy directives", () => {
+ test("canDirect allows orchestrators and running children, not failed ones", () => {
+ expect(canDirect(overviewItem({ kind: "orchestrator", status: "idle" }))).toBe(
+ true,
+ );
+ expect(
+ canDirect(overviewItem({ kind: "subagent", status: "running" })),
+ ).toBe(true);
+ expect(
+ canDirect(overviewItem({ kind: "subagent", status: "completed" })),
+ ).toBe(false);
+ expect(
+ canDirect(overviewItem({ kind: "orchestrator", status: "failed" })),
+ ).toBe(false);
+ });
+
+ test("formatDaddyDirective uses the engine prefix and names children", () => {
+ expect(formatDaddyDirective(overviewItem(), "run the tests")).toBe(
+ "[daddy] run the tests",
+ );
+ expect(
+ formatDaddyDirective(
+ overviewItem({ kind: "subagent", label: "Review implementation" }),
+ "stop editing",
+ ),
+ ).toBe("[daddy] for Review implementation: stop editing");
+ });
+
+ test("currentSupervisorTitle is the focused orchestrator", () => {
+ const current = overviewItem({
+ isCurrentConversation: true,
+ conversationTitle: "Fix login",
+ });
+ const other = overviewItem({
+ id: "other",
+ conversationTitle: "Other task",
+ });
+ expect(
+ currentSupervisorTitle({ active: [other, current], recent: [] }),
+ ).toBe("Fix login");
+ expect(currentSupervisorTitle({ active: [other], recent: [] })).toBeNull();
+ });
+});
diff --git a/gui/src/app/projections/agents.ts b/gui/src/app/projections/agents.ts
index 63aea3a0..ec2c0f19 100644
--- a/gui/src/app/projections/agents.ts
+++ b/gui/src/app/projections/agents.ts
@@ -248,6 +248,34 @@ export function buildAgentOverview({
* One spoken-style summary of the overview, used as the control-pane trigger's
* aria-label/title so the button announces the same thing the pane shows.
*/
+/** Orchestrators and live children can take a supervisor directive. */
+export function canDirect(item: AgentOverviewItem): boolean {
+ if (item.kind === "orchestrator") return item.status !== "failed";
+ return item.status === "running";
+}
+
+/** Same `[daddy]` prefix the engine parks and idle-wakes on. */
+export function formatDaddyDirective(
+ item: AgentOverviewItem,
+ text: string,
+): string {
+ const body = text.trim();
+ if (item.kind === "subagent") {
+ return `[daddy] for ${item.label}: ${body}`;
+ }
+ return `[daddy] ${body}`;
+}
+
+export function currentSupervisorTitle(
+ overview: Pick<AgentOverviewSnapshot, "active" | "recent">,
+): string | null {
+ const items = [...overview.active, ...overview.recent];
+ const current = items.find(
+ (item) => item.kind === "orchestrator" && item.isCurrentConversation,
+ );
+ return current?.conversationTitle ?? null;
+}
+
export function formatAgentActivityLabel(
overview: Pick<AgentOverviewSnapshot, "totalActive" | "needsInput">,
): string {
diff --git a/gui/src/components/agent-control/AgentControlPane.test.tsx b/gui/src/components/agent-control/AgentControlPane.test.tsx
index 2894762a..0ca1897e 100644
--- a/gui/src/components/agent-control/AgentControlPane.test.tsx
+++ b/gui/src/components/agent-control/AgentControlPane.test.tsx
@@ -58,6 +58,7 @@ function renderContent(snapshot: AgentOverviewSnapshot): string {
onCancelStop={() => {}}
onConfirmStop={() => {}}
onAnswerFollowup={() => {}}
+ onDirect={() => {}}
/>,
);
}
@@ -160,6 +161,21 @@ describe("AgentControlPaneContent", () => {
expect(markup).toContain('aria-label="Answer"');
});
+ test("shows the supervisor banner and Direct on a living orchestrator", () => {
+ const snapshot = overview([
+ item("orch", "idle", {
+ kind: "orchestrator",
+ isCurrentConversation: true,
+ conversationTitle: "Fix login",
+ label: "Main agent",
+ }),
+ ]);
+ const markup = renderContent(snapshot);
+ expect(markup).toContain("Supervisor");
+ expect(markup).toContain("Directing from Fix login");
+ expect(markup).toContain('aria-label="Direct Main agent"');
+ });
+
test("subagents never carry followup controls", () => {
const followup: FollowupRequest = {
followupId: "followup-3",
diff --git a/gui/src/components/agent-control/AgentControlPane.tsx b/gui/src/components/agent-control/AgentControlPane.tsx
index e0518470..7d070212 100644
--- a/gui/src/components/agent-control/AgentControlPane.tsx
+++ b/gui/src/components/agent-control/AgentControlPane.tsx
@@ -11,7 +11,9 @@ import {
} from "lucide-react";
import {
+ currentSupervisorTitle,
formatAgentActivityLabel,
+ formatDaddyDirective,
type AgentOverviewItem,
type AgentOverviewSnapshot,
type AgentOverviewStatus,
@@ -23,6 +25,8 @@ import * as desktopClient from "@/services/desktop/client";
import type { FollowupRequest } from "@/services/desktop/types/contracts";
import { Button } from "@/components/ui/Button";
+import { DaddyDirectForm, DaddySupervisorBanner } from "./DaddyDirect";
+
const STATUS_LABELS: Record<AgentOverviewStatus, string> = {
running: "Working",
"needs-input": "Needs input",
@@ -155,6 +159,7 @@ interface AgentControlCardProps {
onCancelStop: () => void;
onConfirmStop: (item: AgentOverviewItem) => void;
onAnswerFollowup: (followup: FollowupRequest, answer: FollowupAnswer) => void;
+ onDirect: (item: AgentOverviewItem, text: string) => void;
}
function AgentControlCard({
@@ -165,6 +170,7 @@ function AgentControlCard({
onCancelStop,
onConfirmStop,
onAnswerFollowup,
+ onDirect,
}: AgentControlCardProps) {
const canStop = item.kind === "orchestrator" && item.status === "running";
const followup = item.kind === "orchestrator" ? item.followup : null;
@@ -239,6 +245,8 @@ function AgentControlCard({
onAnswer={(answer) => onAnswerFollowup(followup, answer)}
/>
) : null}
+
+ <DaddyDirectForm item={item} onDirect={onDirect} />
</div>
);
}
@@ -252,6 +260,7 @@ export function AgentControlPaneContent({
onCancelStop,
onConfirmStop,
onAnswerFollowup,
+ onDirect,
}: {
overview: AgentOverviewSnapshot;
stopPendingId: string | null;
@@ -261,6 +270,7 @@ export function AgentControlPaneContent({
onCancelStop: () => void;
onConfirmStop: (item: AgentOverviewItem) => void;
onAnswerFollowup: (followup: FollowupRequest, answer: FollowupAnswer) => void;
+ onDirect: (item: AgentOverviewItem, text: string) => void;
}) {
const cardHandlers = {
onSelect,
@@ -268,6 +278,7 @@ export function AgentControlPaneContent({
onCancelStop,
onConfirmStop,
onAnswerFollowup,
+ onDirect,
};
return (
@@ -294,6 +305,8 @@ export function AgentControlPaneContent({
</header>
<div className="agent-control-scroll">
+ <DaddySupervisorBanner title={currentSupervisorTitle(overview)} />
+
<section aria-label="Active agents">
<div className="space-y-1.5">
{overview.active.length > 0 ? (
@@ -413,6 +426,17 @@ export function AgentControlPane({
});
}
+ function handleDirect(item: AgentOverviewItem, text: string) {
+ void desktopClient
+ .sendPrompt({
+ workspacePath: item.workspacePath,
+ conversationId: item.conversationId,
+ agentId: item.kind === "orchestrator" ? item.agentId : null,
+ prompt: formatDaddyDirective(item, text),
+ })
+ .catch(() => null);
+ }
+
const label = formatAgentActivityLabel(overview);
return (
@@ -455,6 +479,7 @@ export function AgentControlPane({
onCancelStop={() => setStopPendingId(null)}
onConfirmStop={handleConfirmStop}
onAnswerFollowup={handleAnswerFollowup}
+ onDirect={handleDirect}
/>
</div>
</>
diff --git a/gui/src/components/agent-control/DaddyDirect.test.tsx b/gui/src/components/agent-control/DaddyDirect.test.tsx
new file mode 100644
index 00000000..a69d2ca7
--- /dev/null
+++ b/gui/src/components/agent-control/DaddyDirect.test.tsx
@@ -0,0 +1,70 @@
+import { describe, expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import type { AgentOverviewItem } from "@/app/projections/agents";
+
+import { DaddyDirectForm, DaddySupervisorBanner } from "./DaddyDirect";
+
+function item(
+ overrides: Partial<AgentOverviewItem> = {},
+): AgentOverviewItem {
+ return {
+ id: "orch",
+ agentId: "forge",
+ conversationId: "conversation-1",
+ conversationTitle: "Fix login",
+ workspacePath: "/code/project",
+ kind: "orchestrator",
+ label: "Main agent",
+ detail: "Ready",
+ status: "idle",
+ followup: null,
+ isCurrentConversation: false,
+ sequence: 0,
+ ...overrides,
+ };
+}
+
+describe("DaddySupervisorBanner", () => {
+ test("names the current chat as the supervisor", () => {
+ const markup = renderToStaticMarkup(
+ <DaddySupervisorBanner title="Fix login" />,
+ );
+ expect(markup).toContain("Supervisor");
+ expect(markup).toContain("Directing from Fix login");
+ });
+
+ test("explains how to start when no chat is focused", () => {
+ const markup = renderToStaticMarkup(
+ <DaddySupervisorBanner title={null} />,
+ );
+ expect(markup).toContain("Open a chat to supervise from it");
+ });
+});
+
+describe("DaddyDirectForm", () => {
+ test("offers Direct on a living orchestrator", () => {
+ const markup = renderToStaticMarkup(
+ <DaddyDirectForm item={item()} onDirect={() => {}} />,
+ );
+ expect(markup).toContain('aria-label="Direct Main agent"');
+ expect(markup).toContain("Direct");
+ });
+
+ test("hides Direct on a failed orchestrator or finished child", () => {
+ const failed = renderToStaticMarkup(
+ <DaddyDirectForm
+ item={item({ status: "failed" })}
+ onDirect={() => {}}
+ />,
+ );
+ expect(failed).toBe("");
+ const done = renderToStaticMarkup(
+ <DaddyDirectForm
+ item={item({ kind: "subagent", status: "completed", label: "Scout" })}
+ onDirect={() => {}}
+ />,
+ );
+ expect(done).toBe("");
+ });
+});
diff --git a/gui/src/components/agent-control/DaddyDirect.tsx b/gui/src/components/agent-control/DaddyDirect.tsx
new file mode 100644
index 00000000..c10f56fc
--- /dev/null
+++ b/gui/src/components/agent-control/DaddyDirect.tsx
@@ -0,0 +1,92 @@
+import { useState } from "react";
+
+import {
+ canDirect,
+ type AgentOverviewItem,
+} from "@/app/projections/agents";
+import { Button } from "@/components/ui/Button";
+
+export function DaddySupervisorBanner({
+ title,
+}: {
+ title: string | null;
+}) {
+ return (
+ <section className="daddy-supervisor" aria-label="Supervisor">
+ <h3 className="agent-overview-section-title">Supervisor</h3>
+ <p className="daddy-supervisor-copy">
+ {title != null
+ ? `Directing from ${title}. Send a directive to another agent on this tab.`
+ : "Open a chat to supervise from it. Directives steer the chosen agent; they are not ambient peer mail."}
+ </p>
+ </section>
+ );
+}
+
+export function DaddyDirectForm({
+ item,
+ disabled,
+ onDirect,
+}: {
+ item: AgentOverviewItem;
+ disabled?: boolean;
+ onDirect: (item: AgentOverviewItem, text: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [text, setText] = useState("");
+
+ if (!canDirect(item)) return null;
+
+ return (
+ <div className="daddy-direct">
+ {open ? (
+ <form
+ className="daddy-direct-form"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const trimmed = text.trim();
+ if (trimmed.length === 0) return;
+ onDirect(item, trimmed);
+ setText("");
+ setOpen(false);
+ }}
+ >
+ <input
+ value={text}
+ onChange={(event) => setText(event.target.value)}
+ placeholder={
+ item.kind === "subagent"
+ ? "Steer this child via its parent…"
+ : "Tell this agent what to do…"
+ }
+ aria-label={`Direct ${item.label}`}
+ className="agent-control-followup-input"
+ />
+ <Button size="xs" type="submit" disabled={text.trim().length === 0 || disabled}>
+ Direct
+ </Button>
+ <button
+ type="button"
+ className="agent-control-followup-dismiss"
+ onClick={() => {
+ setOpen(false);
+ setText("");
+ }}
+ >
+ Cancel
+ </button>
+ </form>
+ ) : (
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={disabled}
+ aria-label={`Direct ${item.label}`}
+ onClick={() => setOpen(true)}
+ >
+ Direct
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/gui/src/styles/agent-control.css b/gui/src/styles/agent-control.css
index 0a3d09b5..ebe334da 100644
--- a/gui/src/styles/agent-control.css
+++ b/gui/src/styles/agent-control.css
@@ -299,6 +299,28 @@
color: var(--destructive);
}
+.daddy-supervisor {
+ margin-bottom: 1rem;
+}
+
+.daddy-supervisor-copy {
+ padding-inline: 0.25rem;
+ color: color-mix(in oklab, var(--muted-foreground) 82%, transparent);
+ font-size: 0.6875rem;
+ line-height: 1.35;
+}
+
+.daddy-direct {
+ margin: 0.125rem 0 0.375rem 2.25rem;
+}
+
+.daddy-direct-form {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.375rem;
+}
+
.agent-overview-empty {
display: flex;
align-items: center;
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 21e83ff8..43f96a3c 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -254,6 +254,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
const cleaned = try cite_markup.dupe(self.arena, raw);
const result = if (!@import("builtin").is_test and self.pr_verification == .draft) try std.fmt.allocPrint(self.arena, "Draft handoff — CI is not verified.\n\n{s}", .{cleaned}) else cleaned;
self.completed = result;
+ if (!self.sub) @import("peer_wake.zig").noteCompleted();
if (!self.sub) task_outcome.noteGoalCompleted(self);
// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).
// A --goal standing objective is exempt: the completion is recorded above, the steering stays, and only /goal clear|pause|<new> retires it.
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index e52d5343..a2631752 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -45,6 +45,7 @@ pub const commands = [_]Item{
.{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },
.{ .name = "/never", .usage = "/never [<text>|rm <id-or-text>]", .desc = "standing constraints that ride every brief; bare opens a searchable picker (TTY) or lists them, rm <id-or-text> retires one (alias /constraint)" },
.{ .name = "/tell", .usage = "/tell <session|all> <text>", .desc = "message a running graff: <session> is a DM (only it hears, any folder); all broadcasts to every graff on this device; /sessions lists who's around" },
+ .{ .name = "/daddy", .usage = "/daddy <session> <text>", .desc = "direct one live graff as the supervisor — control, not ambient room mail; /sessions lists who's around" },
.{ .name = "/peek", .usage = "/peek <session>", .desc = "see what a live co-resident session is doing right now (its transcript tail)" },
.{ .name = "/routes", .usage = "/routes [<set>|add <set> <frontier|mid|small> <provider/model>]", .desc = "your own priced model lanes across providers — view the set and which seat wins each lane now" },
.{ .name = "/plan", .desc = "toggle plan mode: read-only explore + propose; writes/edits denied" },
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index 67ea274d..f3b3733c 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -466,6 +466,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
}
if (try @import("commands_resume.zig").tryHandle(root, keys, arena, line, out)) return true;
if (std.mem.startsWith(u8, line, "/tell") and (line.len == 5 or line[5] == ' ' or line[5] == '\t')) return peer_channel.tellCommand(root, arena, line, out); // #469
+ if (try @import("daddy.zig").slashCommand(root, arena, line, out)) return true;
if (std.mem.startsWith(u8, line, "/peek") and (line.len == 5 or line[5] == ' ' or line[5] == '\t')) return peer_channel.peekCommand(root, arena, line, out); // #469
if (std.mem.startsWith(u8, line, "/routes") and (line.len == 7 or line[7] == ' ' or line[7] == '\t')) return route_set.command(root, keys, arena, line, out); // user-defined priced lanes
if (std.mem.eql(u8, line, "/sessions")) {
diff --git a/src/daddy.zig b/src/daddy.zig
new file mode 100644
index 00000000..01847a6a
--- /dev/null
+++ b/src/daddy.zig
@@ -0,0 +1,224 @@
+//! Supervisor ("daddy") directives: explicit control of sibling sessions
+//! and a slash/tool surface shared by REPL, TUI, and GUI (`graff acp`).
+//!
+//! Ambient peer mail stays a parked mailbox (ADR 0004 / #1137). A daddy
+//! directive is a named DM whose body is prefixed `[daddy]`. Idle roots
+//! may start a turn on that prefix even after `attempt_completion`; busy
+//! roots still only see it at the next step (same as `/tell`).
+//!
+//! Children inside one process stay on `agent_message`. This module is
+//! the cross-session supervisor path.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const agent_mod = @import("agent.zig");
+const peer_inbox = @import("peer_inbox.zig");
+const peer_target = @import("peer_target.zig");
+const presence = @import("presence.zig");
+const tools_mod = @import("tools.zig");
+const Owner = @import("worktree_lease.zig").Owner;
+
+const Agent = agent_mod.Agent;
+const ExecResult = tools_mod.ExecResult;
+
+pub const prefix = "[daddy] ";
+
+pub fn isDirective(s: []const u8) bool {
+ const t = std.mem.trimStart(u8, s, " \t\r\n");
+ return std.mem.startsWith(u8, t, "[daddy]");
+}
+
+pub fn formatBody(arena: Allocator, text: []const u8) ![]const u8 {
+ const t = std.mem.trim(u8, text, " \t\r\n");
+ if (t.len == 0) return error.EmptyDirective;
+ if (isDirective(t)) return t;
+ return std.fmt.allocPrint(arena, "{s}{s}", .{ prefix, t });
+}
+
+pub fn stripPrefix(s: []const u8) []const u8 {
+ const t = std.mem.trimStart(u8, s, " \t\r\n");
+ if (std.mem.startsWith(u8, t, prefix)) return std.mem.trim(u8, t[prefix.len..], " \t\r\n");
+ if (std.mem.startsWith(u8, t, "[daddy]")) return std.mem.trim(u8, t["[daddy]".len..], " \t\r\n");
+ return t;
+}
+
+pub fn parkedDirectives() bool {
+ return peer_inbox.anyTextPrefixed("[daddy]");
+}
+
+pub fn formatSteer(arena: Allocator, text: []const u8) []const u8 {
+ const body = stripPrefix(text);
+ return std.fmt.allocPrint(arena, "[daddy] directive — {s}", .{body}) catch "[daddy] directive waiting — peer_message action=inbox";
+}
+
+pub const Slash = struct { target: []const u8, text: []const u8 };
+
+pub fn parseSlash(line: []const u8) ?Slash {
+ if (!std.mem.startsWith(u8, line, "/daddy")) return null;
+ if (line.len > 6 and line[6] != ' ' and line[6] != '\t') return null;
+ const rest = std.mem.trim(u8, line["/daddy".len..], " \t");
+ const split = std.mem.indexOfAny(u8, rest, " \t") orelse return null;
+ const target = rest[0..split];
+ const text = std.mem.trim(u8, rest[split + 1 ..], " \t");
+ if (target.len == 0 or text.len == 0) return null;
+ return .{ .target = target, .text = text };
+}
+
+fn peerListText(arena: Allocator, peers: []const Owner) []const u8 {
+ var buf: std.ArrayList(u8) = .empty;
+ for (peers) |p| {
+ const line = std.fmt.allocPrint(arena, "\"{s}\" (pid {d})", .{ p.session_id, p.pid }) catch continue;
+ buf.appendSlice(arena, line) catch {};
+ buf.appendSlice(arena, ", ") catch {};
+ }
+ const items = buf.items;
+ return if (items.len >= 2) items[0 .. items.len - 2] else items;
+}
+
+fn isLocal(peers: []const Owner, session_id: []const u8, my_identity: []const u8) bool {
+ for (peers) |p| {
+ if (std.mem.eql(u8, p.session_id, session_id)) return std.mem.eql(u8, p.identity, my_identity);
+ }
+ return true;
+}
+
+fn postDirect(io: Io, arena: Allocator, text: []const u8, to: []const u8, everyone: []const Owner) bool {
+ const cross_folder = to.len > 0 and !isLocal(everyone, to, presence.ownIdentity());
+ if (cross_folder) return presence.postToDevice(io, arena, text, to, false);
+ return presence.postTo(io, arena, text, to);
+}
+
+pub fn send(self: *Agent, session: []const u8, text: []const u8) !ExecResult {
+ const body = formatBody(self.arena, text) catch return .{
+ .text = "daddy: empty text — say what the other agent should do",
+ .is_error = true,
+ };
+ const everyone = presence.liveAllPeers(self.io, self.arena);
+ if (session.len == 0) return .{
+ .text = "daddy: name the session to direct (title, saved-session base, id, or pid). Not a room broadcast.",
+ .is_error = true,
+ };
+ if (std.mem.eql(u8, session, "all")) return .{
+ .text = "daddy: \"all\" is not a control target — name one session. Ambient room posts stay on peer_message action=send.",
+ .is_error = true,
+ };
+ const to: []const u8 = switch (peer_target.resolvePeer(everyone, session)) {
+ .one => |p| p.session_id,
+ .none => return .{
+ .text = try std.fmt.allocPrint(self.arena, "daddy: no live peer matches \"{s}\" — live now: {s}", .{ session, peerListText(self.arena, everyone) }),
+ .is_error = true,
+ },
+ .ambiguous => return .{
+ .text = try std.fmt.allocPrint(self.arena, "daddy: more than one live peer matches — name one: {s}", .{peerListText(self.arena, everyone)}),
+ .is_error = true,
+ },
+ };
+ if (!postDirect(self.io, self.arena, body, to, everyone)) return .{
+ .text = "daddy: delivery failed — the presence registry is unavailable",
+ .is_error = true,
+ };
+ return .{
+ .text = try std.fmt.allocPrint(self.arena, "directed \"{s}\" — they read this as supervisor control at their next step (or an idle root starts a turn). Re-direct with session=\"{s}\".", .{ to, to }),
+ .is_error = false,
+ };
+}
+
+/// /daddy <session> <text>: user-facing supervisor control, same post as
+/// `peer_message action=direct`.
+pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ if (!std.mem.startsWith(u8, line, "/daddy")) return false;
+ if (line.len > 6 and line[6] != ' ' and line[6] != '\t') return false;
+ const parsed = parseSlash(line);
+ if (parsed == null) {
+ try out.writeAll("usage: /daddy <session> <text> — direct one live graff (title, base, id, or pid). Not a room broadcast.\n");
+ const everyone = presence.liveAllPeers(root.io, arena);
+ if (everyone.len == 0) try out.writeAll(" (no live peers right now)\n") else try out.print(" live now: {s}\n", .{peerListText(arena, everyone)});
+ try out.flush();
+ return true;
+ }
+ const result = try send(root, parsed.?.target, parsed.?.text);
+ try out.print("{s}\n", .{result.text});
+ try out.flush();
+ return true;
+}
+
+/// Idle wake text when a directive is parked — allowed after completion.
+pub fn takeIdleText(arena: Allocator, buf: []u8) ?[]const u8 {
+ if (!parkedDirectives()) return null;
+ const wake = formatSteer(arena, "waiting");
+ const copy = @min(wake.len, buf.len);
+ @memcpy(buf[0..copy], wake[0..copy]);
+ return buf[0..copy];
+}
+
+test "isDirective: prefix only" {
+ try std.testing.expect(isDirective("[daddy] stop the publish"));
+ try std.testing.expect(isDirective(" [daddy] hold"));
+ try std.testing.expect(!isDirective("[peer] 1 unread"));
+ try std.testing.expect(!isDirective("please finish"));
+}
+
+test "formatBody: prefixes once and rejects empty" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expectEqualStrings("[daddy] hold gui/src", try formatBody(a, "hold gui/src"));
+ try std.testing.expectEqualStrings("[daddy] already", try formatBody(a, "[daddy] already"));
+ try std.testing.expectError(error.EmptyDirective, formatBody(a, " "));
+}
+
+test "parseSlash: target and text; usage is null" {
+ const ok = parseSlash("/daddy reviewer pause the PR") orelse return error.ExpectedSlash;
+ try std.testing.expectEqualStrings("reviewer", ok.target);
+ try std.testing.expectEqualStrings("pause the PR", ok.text);
+ try std.testing.expect(parseSlash("/daddy") == null);
+ try std.testing.expect(parseSlash("/daddyonly x") == null);
+ try std.testing.expect(parseSlash("/tell reviewer hi") == null);
+}
+
+test "stripPrefix and formatSteer stay one line" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expectEqualStrings("pause the PR", stripPrefix("[daddy] pause the PR"));
+ const steer = formatSteer(a, "[daddy] pause the PR");
+ try std.testing.expect(std.mem.startsWith(u8, steer, "[daddy]"));
+ try std.testing.expect(std.mem.indexOf(u8, steer, "pause the PR") != null);
+ try std.testing.expect(std.mem.indexOfScalar(u8, steer, '\n') == null);
+}
+
+test "send refuses empty, all, and a missing session" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var root: Agent = undefined;
+ root.arena = arena_state.allocator();
+ root.io = std.testing.io;
+ const empty = try send(&root, "reviewer", " ");
+ try std.testing.expect(empty.is_error);
+ const all = try send(&root, "all", "stop");
+ try std.testing.expect(all.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, all.text, "all") != null);
+ const missing = try send(&root, "no-such-peer", "stop");
+ try std.testing.expect(missing.is_error);
+}
+
+test "parkedDirectives sees a [daddy] body and takeIdleText fires after completion" {
+ peer_inbox.resetForTest();
+ @import("peer_wake.zig").resetForTest();
+ defer {
+ peer_inbox.resetForTest();
+ @import("peer_wake.zig").resetForTest();
+ }
+ @import("peer_wake.zig").noteCompleted();
+ try std.testing.expect(!@import("peer_wake.zig").idlePeerAllowed());
+ try std.testing.expect(!parkedDirectives());
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-dad", .text = "[daddy] switch to the tests" }}, &.{});
+ try std.testing.expect(parkedDirectives());
+ var buf: [128]u8 = undefined;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const idle = takeIdleText(arena_state.allocator(), &buf) orelse return error.ExpectedDaddyIdle;
+ try std.testing.expect(std.mem.indexOf(u8, idle, "[daddy]") != null);
+}
diff --git a/src/main.zig b/src/main.zig
index d0995be5..97f038a3 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -590,7 +590,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("goal_flow.zig");
_ = @import("goal_todo.zig");
_ = @import("goal_pacing.zig");
- _ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };
+ _ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("peer_wake.zig"), @import("daddy.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };
_ = @import("acp_agents.zig");
_ = @import("subagent_activity.zig");
_ = @import("subagent_recovery.zig");
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index 67926528..86d13438 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -35,9 +35,9 @@ const ExecResult = tools_mod.ExecResult;
const Owner = worktree_lease.Owner;
pub const tool_name = "peer_message";
-pub const tool_desc = "Ping a co-resident session, list who is live, read parked inbound, or transfer an artifact claim. action=list | inbox | send (default) | claim | release | handoff | status. session is a DM (visible title, saved-session base, id/pid/name/goal); omit for this folder's room. Presence is device-local. Not \"all\".";
+pub const tool_desc = "Ping a co-resident session, list who is live, read parked inbound, direct one as supervisor, or transfer an artifact claim. action=list | inbox | send (default) | direct | claim | release | handoff | status. session is a DM (visible title, saved-session base, id/pid/name/goal); omit for this folder's room (send only). Presence is device-local. Not \"all\".";
pub const tool_schema =
- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox", "claim", "release", "handoff", "status"], "description": "send (default): ping a peer. list: who is live. inbox: read+clear parked inbound. claim/release/handoff/status: repository-scoped artifact ownership (kind+key)."}, "session": {"type": "string", "description": "who to ping or hand a claim to: exact visible title, exact saved-session base, unique normalized title/slug, id, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Presence is device-local. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}, "kind": {"type": "string", "enum": ["branch", "issue", "commit", "pull_request", "publication"], "description": "artifact kind for claim/release/handoff/status"}, "key": {"type": "string", "description": "artifact key: branch name, issue number, commit SHA, or PR number"}, "repo": {"type": "string", "description": "GitHub repository for claim/release/handoff/status, as owner/name or host/owner/name; defaults to the workspace CLI repository. Use the same repository for release or handoff."}}}
+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox", "direct", "claim", "release", "handoff", "status"], "description": "send (default): ping a peer. list: who is live. inbox: read+clear parked inbound. direct: supervisor control of one named session. claim/release/handoff/status: repository-scoped artifact ownership (kind+key)."}, "session": {"type": "string", "description": "who to ping, direct, or hand a claim to: exact visible title, exact saved-session base, unique normalized title/slug, id, pid, unique name fragment, or unique goal fragment (omit = this folder's room for send). Named targets are DMs. Presence is device-local. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send and direct)"}, "kind": {"type": "string", "enum": ["branch", "issue", "commit", "pull_request", "publication"], "description": "artifact kind for claim/release/handoff/status"}, "key": {"type": "string", "description": "artifact key: branch name, issue number, commit SHA, or PR number"}, "repo": {"type": "string", "description": "GitHub repository for claim/release/handoff/status, as owner/name or host/owner/name; defaults to the workspace CLI repository. Use the same repository for release or handoff."}}}
;
/// Whether the named session sits in MY worktree (routes the post: worktree
@@ -89,10 +89,14 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {
.is_error = true,
};
peer_idle.noteInboxConsumed();
+ @import("peer_wake.zig").retireInjects(&self.messages);
return .{ .text = text, .is_error = false };
}
+ if (std.mem.eql(u8, action, "direct")) {
+ return @import("daddy.zig").send(self, tools_mod.json_args.str(obj, "session") orelse "", tools_mod.json_args.str(obj, "text") orelse "");
+ }
if (!std.mem.eql(u8, action, "send")) return .{
- .text = "peer_message action must be send, list, inbox, claim, release, handoff, or status",
+ .text = "peer_message action must be send, list, inbox, direct, claim, release, handoff, or status",
.is_error = true,
};
const text = tools_mod.json_args.str(obj, "text") orelse "";
@@ -240,8 +244,15 @@ pub fn deliverInbound(root: *Agent) void {
renderPeerBlock(sink, root.io, true, &.{}, &.{summary});
}
if (peer_inbox.parkHeard(local_msgs, device_msgs) == 0) return;
- // History gets the wake only (ADR 0004). Bodies wait in the ring.
- root.messages.append(@import("session_wake.zig").message(root.arena, peer_context.capInject(peer_inbox.formatWake(root.arena))) catch return) catch {};
+ // History gets at most one `[peer]` wake per mailbox generation, and
+ // never during tool continuation (#1137). Bodies wait in the ring.
+ const wake_mod = @import("peer_wake.zig");
+ const gen = peer_inbox.generation();
+ if (wake_mod.decide(root.messages.items, gen) == .inject) {
+ const wake = @import("session_wake.zig").message(root.arena, peer_context.capInject(peer_inbox.formatWake(root.arena))) catch return;
+ wake_mod.insertWake(&root.messages, wake) catch {};
+ wake_mod.markInjected(gen);
+ }
}
/// Emit the drain's visible half as one bracketed unit: a blank notice, the
diff --git a/src/peer_idle.zig b/src/peer_idle.zig
index 10450c5d..00bcd432 100644
--- a/src/peer_idle.zig
+++ b/src/peer_idle.zig
@@ -16,6 +16,7 @@ var last_woken_unread: usize = 0;
pub fn resetForTest() void {
last_woken_unread = 0;
+ @import("peer_wake.zig").resetForTest();
}
fn ingest(io: Io, arena: Allocator) void {
@@ -41,6 +42,11 @@ pub fn takeIdleWake(io: Io, buf: []u8) ?[]const u8 {
var fba = std.heap.FixedBufferAllocator.init(&scratch);
const arena = fba.allocator();
ingest(io, arena);
+ if (@import("daddy.zig").takeIdleText(arena, buf)) |t| {
+ last_woken_unread = peer_inbox.unread();
+ return t;
+ }
+ if (!@import("peer_wake.zig").idlePeerAllowed()) return null;
const n = peer_inbox.unread();
if (n == 0 or n <= last_woken_unread) return null;
last_woken_unread = n;
diff --git a/src/peer_inbox.zig b/src/peer_inbox.zig
index 05d337ec..ecda2c56 100644
--- a/src/peer_inbox.zig
+++ b/src/peer_inbox.zig
@@ -70,6 +70,34 @@ pub fn pending() bool {
return g_len > 0 or g_dropped > 0;
}
+/// Mailbox generation: unread count plus the parked bodies. Same state
+/// produces the same value so a wake can be coalesced (#1137).
+pub fn generation() u64 {
+ var h = std.hash.Wyhash.init(0);
+ h.update(std.mem.asBytes(&g_len));
+ h.update(std.mem.asBytes(&g_dropped));
+ var i: usize = 0;
+ while (i < g_len) : (i += 1) {
+ const p = itemAt(i);
+ h.update(fromSlice(p));
+ h.update(textSlice(p));
+ h.update(std.mem.asBytes(&p.dm));
+ h.update(std.mem.asBytes(&p.device));
+ }
+ return h.final();
+}
+
+/// True when any parked body starts with `want` (daddy directives).
+pub fn anyTextPrefixed(want: []const u8) bool {
+ var i: usize = 0;
+ while (i < g_len) : (i += 1) {
+ const text = textSlice(itemAt(i));
+ const t = std.mem.trimStart(u8, text, " \t\r\n");
+ if (std.mem.startsWith(u8, t, want)) return true;
+ }
+ return false;
+}
+
/// Add saved loss after restoring the array, preserving any restore evictions.
pub fn restoreDropped(v: std.json.Value) void {
const count = switch (v) {
@@ -384,6 +412,19 @@ test "formatList: title and saved-session base lead the line" {
try testing.expect(std.mem.indexOf(u8, text, "device-local") != null);
}
+test "generation is stable for the same bodies and anyTextPrefixed sees [daddy]" {
+ resetForTest();
+ defer resetForTest();
+ const empty = generation();
+ try testing.expectEqual(empty, generation());
+ _ = parkHeard(&.{msg("s-a", "[daddy] hold the tree", "")}, &.{});
+ const once = generation();
+ try testing.expect(once != empty);
+ try testing.expectEqual(once, generation());
+ try testing.expect(anyTextPrefixed("[daddy]"));
+ try testing.expect(!anyTextPrefixed("[peer]"));
+}
+
test "inbox JSON round-trip: restoreJson rebuilds the ring" {
resetForTest();
defer resetForTest();
diff --git a/src/peer_wake.zig b/src/peer_wake.zig
new file mode 100644
index 00000000..42c72c63
--- /dev/null
+++ b/src/peer_wake.zig
@@ -0,0 +1,239 @@
+//! #1137: ambient peer wakes are mailbox state, not a new task.
+//!
+//! `deliverInbound` used to append a user-role `[peer]` wake at every root
+//! step, including tool-result continuations and after `attempt_completion`.
+//! The model then treated coordination traffic as the newest instruction.
+//!
+//! Rules:
+//! - one inject per mailbox generation (unread + bodies)
+//! - no inject while tools are being continued
+//! - no idle auto-turn after a completed attempt until a human prompt
+//! - `action=inbox` retires stale `[peer]` injects
+//!
+//! Daddy directives (`daddy.zig`) are explicit control and use a separate
+//! path; they are not these ambient wakes.
+
+const std = @import("std");
+const Value = std.json.Value;
+
+const peer_context = @import("peer_context.zig");
+const peer_inbox = @import("peer_inbox.zig");
+const session_wake = @import("session_wake.zig");
+
+pub const Decision = enum { skip_empty, skip_coalesced, skip_continuation, inject };
+
+var last_injected_gen: u64 = 0;
+var suppress_idle: bool = false;
+
+pub fn resetForTest() void {
+ last_injected_gen = 0;
+ suppress_idle = false;
+}
+
+pub fn lastInjected() u64 {
+ return last_injected_gen;
+}
+
+pub fn markInjected(generation: u64) void {
+ last_injected_gen = generation;
+}
+
+pub fn noteCompleted() void {
+ suppress_idle = true;
+}
+
+pub fn idlePeerAllowed() bool {
+ return !suppress_idle;
+}
+
+fn isHumanUserTurn(m: Value) bool {
+ if (m != .object) return false;
+ const role = m.object.get("role") orelse return false;
+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;
+ return !session_wake.isNotice(m) and !peer_context.isPeerInject(m);
+}
+
+/// A later human prompt lifts the post-completion idle latch.
+pub fn noteTurnStart(messages: []const Value) void {
+ var i = messages.len;
+ while (i > 0) {
+ i -= 1;
+ const m = messages[i];
+ if (session_wake.isNotice(m) or peer_context.isPeerInject(m)) continue;
+ if (isHumanUserTurn(m)) suppress_idle = false;
+ return;
+ }
+}
+
+/// Last non-wake message is a tool result or an assistant tool-call batch.
+pub fn isMidToolContinuation(messages: []const Value) bool {
+ var i = messages.len;
+ while (i > 0) {
+ i -= 1;
+ const m = messages[i];
+ if (session_wake.isNotice(m) or peer_context.isPeerInject(m)) continue;
+ if (m != .object) continue;
+ const role = m.object.get("role") orelse continue;
+ if (role != .string) continue;
+ if (std.mem.eql(u8, role.string, "tool")) return true;
+ if (std.mem.eql(u8, role.string, "assistant")) {
+ if (m.object.get("tool_calls")) |tc| {
+ if (tc == .array and tc.array.items.len > 0) return true;
+ }
+ }
+ return false;
+ }
+ return false;
+}
+
+pub fn decide(messages: []const Value, generation: u64) Decision {
+ if (generation == 0 or !peer_inbox.pending()) return .skip_empty;
+ if (generation == last_injected_gen) return .skip_coalesced;
+ if (isMidToolContinuation(messages)) return .skip_continuation;
+ return .inject;
+}
+
+/// Keep the human task as the newest authoritative user turn.
+pub fn insertWake(messages: *std.json.Array, wake: Value) !void {
+ if (messages.items.len > 0 and isHumanUserTurn(messages.items[messages.items.len - 1])) {
+ try messages.insert(messages.items.len - 1, wake);
+ } else {
+ try messages.append(wake);
+ }
+}
+
+/// Inbox consume retires the stale `[peer]` lines for this mailbox generation.
+pub fn retireInjects(messages: *std.json.Array) void {
+ var i: usize = 0;
+ while (i < messages.items.len) {
+ if (peer_context.isPeerInject(messages.items[i])) {
+ _ = messages.orderedRemove(i);
+ continue;
+ }
+ i += 1;
+ }
+ last_injected_gen = 0;
+}
+
+fn userText(arena: std.mem.Allocator, s: []const u8) !Value {
+ return try @import("messages.zig").textMessage(arena, "user", s);
+}
+
+fn asstTools(arena: std.mem.Allocator) !Value {
+ return std.json.parseFromSliceLeaky(Value, arena, "{\"role\":\"assistant\",\"content\":null,\"tool_calls\":[{\"function\":{\"name\":\"read_file\"}}]}", .{});
+}
+
+fn toolResult(arena: std.mem.Allocator) !Value {
+ return std.json.parseFromSliceLeaky(Value, arena, "{\"role\":\"tool\",\"name\":\"read_file\",\"content\":\"ok\"}", .{});
+}
+
+test "#1137 mid-tool continuation is not an authoritative user turn" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ peer_inbox.resetForTest();
+ defer peer_inbox.resetForTest();
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-peer", .text = "hold the tree" }}, &.{});
+
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "inspect src/peer_channel.zig"));
+ try msgs.append(try asstTools(a));
+ try msgs.append(try toolResult(a));
+ try std.testing.expect(isMidToolContinuation(msgs.items));
+ const gen = peer_inbox.generation();
+ try std.testing.expectEqual(Decision.skip_continuation, decide(msgs.items, gen));
+ try std.testing.expectEqualStrings("inspect src/peer_channel.zig", @import("messages.zig").latestUserText(msgs.items));
+}
+
+test "#1137 same mailbox generation is idempotent" {
+ resetForTest();
+ defer resetForTest();
+ peer_inbox.resetForTest();
+ defer peer_inbox.resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-a", .text = "one" }}, &.{});
+ const gen = peer_inbox.generation();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "keep going"));
+ try std.testing.expectEqual(Decision.inject, decide(msgs.items, gen));
+ markInjected(gen);
+ try std.testing.expectEqual(Decision.skip_coalesced, decide(msgs.items, gen));
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-a", .text = "one" }}, &.{});
+ try std.testing.expectEqual(Decision.skip_coalesced, decide(msgs.items, peer_inbox.generation()));
+}
+
+test "#1137 completed turn does not idle-wake on ambient mail" {
+ resetForTest();
+ defer resetForTest();
+ peer_inbox.resetForTest();
+ defer peer_inbox.resetForTest();
+ try std.testing.expect(idlePeerAllowed());
+ noteCompleted();
+ try std.testing.expect(!idlePeerAllowed());
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-b", .text = "ping" }}, &.{});
+ try std.testing.expect(!idlePeerAllowed());
+}
+
+test "#1137 a later human turn lifts the latch and can see parked mail" {
+ resetForTest();
+ defer resetForTest();
+ peer_inbox.resetForTest();
+ defer peer_inbox.resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ noteCompleted();
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "s-c", .text = "waiting" }}, &.{});
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "what is left in the inbox?"));
+ noteTurnStart(msgs.items);
+ try std.testing.expect(idlePeerAllowed());
+ try std.testing.expect(peer_inbox.pending());
+ const wake = peer_inbox.formatWake(a);
+ try std.testing.expect(std.mem.indexOf(u8, wake, "unread") != null);
+ try std.testing.expectEqual(Decision.inject, decide(msgs.items, peer_inbox.generation()));
+}
+
+test "#1137 insertWake keeps the human as the newest user turn" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "do the refactor"));
+ const wake = try session_wake.message(a, "[peer] 1 unread from s-x — parked; peer_message action=inbox when relevant");
+ try insertWake(&msgs, wake);
+ try std.testing.expectEqual(@as(usize, 2), msgs.items.len);
+ try std.testing.expect(peer_context.isPeerInject(msgs.items[0]));
+ try std.testing.expect(isHumanUserTurn(msgs.items[1]));
+ try std.testing.expectEqualStrings("do the refactor", @import("messages.zig").latestUserText(msgs.items));
+}
+
+test "#1137 inbox consume retires stale wakes" {
+ resetForTest();
+ defer resetForTest();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var msgs = std.json.Array.init(a);
+ try msgs.append(try userText(a, "task"));
+ try msgs.append(try session_wake.message(a, "[peer] 1 unread from s-x — parked; peer_message action=inbox when relevant"));
+ markInjected(42);
+ retireInjects(&msgs);
+ try std.testing.expectEqual(@as(usize, 1), msgs.items.len);
+ try std.testing.expectEqual(@as(u64, 0), lastInjected());
+ try std.testing.expectEqualStrings("task", msgs.items[0].object.get("content").?.string);
+}
+
+test "empty mailbox does not inject" {
+ resetForTest();
+ defer resetForTest();
+ peer_inbox.resetForTest();
+ defer peer_inbox.resetForTest();
+ try std.testing.expectEqual(Decision.skip_empty, decide(&.{}, 0));
+}
diff --git a/src/turn_inbox.zig b/src/turn_inbox.zig
index ca157fe3..c58d71b9 100644
--- a/src/turn_inbox.zig
+++ b/src/turn_inbox.zig
@@ -10,6 +10,7 @@ const session_wake = @import("session_wake.zig");
const main_mod = @import("main.zig");
pub fn deliver(self: *Agent) !void {
+ @import("peer_wake.zig").noteTurnStart(self.messages.items);
@import("peer_channel.zig").deliverInbound(self);
try @import("subagent_feedback.zig").deliverToAgent(self);
@import("job_notify.zig").deliver(self);