From 8607083df8461b34098eae6a77ad62ef22677744 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 16:07:22 +0000 Subject: [PATCH 1/2] fix(cli): return immediately when agent already matches agent wait --until Check the current agent list right after the baseline read. If any watched agent already satisfies --until, return triggered with the same JSON shape instead of waiting only for transitions. --- .../src/services/agent/agent-wait.service.ts | 28 +++++++++++++++- packages/cli/tests/commands/agent.test.ts | 14 ++++++++ .../services/agent/agent-wait.service.test.ts | 32 ++++++++++++++++++- 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/services/agent/agent-wait.service.ts b/packages/cli/src/services/agent/agent-wait.service.ts index c085611e..65e235e7 100644 --- a/packages/cli/src/services/agent/agent-wait.service.ts +++ b/packages/cli/src/services/agent/agent-wait.service.ts @@ -71,6 +71,23 @@ export function parseWaitUntil(value: string | undefined): AgentWaitCondition[] return [...new Set(tokens)] as AgentWaitCondition[]; } +/** Agents already in a target status (not `appeared`; that needs a transition). */ +export function matchingAgentStates( + agents: AgentInfo[], + until: Set, +): AgentWaitChange[] { + const changes: AgentWaitChange[] = []; + for (const agent of agents) { + const status = agent.status; + if (!(AGENT_WAIT_CONDITIONS as readonly string[]).includes(status)) continue; + const condition = status as AgentWaitCondition; + if (until.has(condition)) { + changes.push(toChange(agent, status, status)); + } + } + return changes; +} + /** * Changes between the last check and the current agents. Only transitions * count: an agent already in a target status does not fire again. @@ -144,7 +161,16 @@ export async function waitForAgentChanges( try { // Subscribe before the baseline so a change in between still wakes us. await source.subscribe(wake); - let lastSeen = toSeen(watched(await source.list())); + const initial = watched(await source.list()); + const initialMatches = matchingAgentStates(initial, until); + if (initialMatches.length > 0) { + return { + reason: "triggered", + elapsedMs: Date.now() - startedAt, + changes: initialMatches, + }; + } + let lastSeen = toSeen(initial); const changes = new Map(); let settleDeadline: number | null = null; diff --git a/packages/cli/tests/commands/agent.test.ts b/packages/cli/tests/commands/agent.test.ts index 20827ab4..f4a8908a 100644 --- a/packages/cli/tests/commands/agent.test.ts +++ b/packages/cli/tests/commands/agent.test.ts @@ -4333,6 +4333,20 @@ Waiting on user input`, await program.parseAsync(["node", "test", "agent", "wait", ...args]); } + it("prints a triggered JSON result when an agent is already waiting", async () => { + mockManager.listAgents.mockResolvedValue([running({ status: AgentStatus.WAITING })]); + + await runWait("--until", "waiting", "--timeout", "50", "--json"); + + const output = JSON.parse(logSpy.mock.calls[0][0] as string); + expect(output).toMatchObject({ + reason: "triggered", + changes: [{ name: "repo-a", type: "claude", pid: 10, from: "waiting", to: "waiting" }], + }); + expect(mockManager.listAgents).toHaveBeenCalledWith({ enriched: null }); + expect(process.exit).not.toHaveBeenCalled(); + }); + it("prints a triggered JSON result when an agent starts waiting", async () => { mockManager.listAgents .mockResolvedValueOnce([running()]) diff --git a/packages/cli/tests/services/agent/agent-wait.service.test.ts b/packages/cli/tests/services/agent/agent-wait.service.test.ts index 7b184fe3..7876fbf9 100644 --- a/packages/cli/tests/services/agent/agent-wait.service.test.ts +++ b/packages/cli/tests/services/agent/agent-wait.service.test.ts @@ -4,6 +4,7 @@ import { AGENT_WAIT_SETTLE_MS, agentWaitKey, diffAgentChanges, + matchingAgentStates, parseWaitUntil, waitForAgentChanges, type AgentWaitSource, @@ -116,6 +117,22 @@ describe("diffAgentChanges", () => { }); }); +describe("matchingAgentStates", () => { + it("reports agents already in a requested status", () => { + const until = new Set(parseWaitUntil("waiting")); + expect(matchingAgentStates([makeAgent({ status: AgentStatus.WAITING })], until)).toEqual([ + { name: "repo-a", type: "claude", pid: 10, from: "waiting", to: "waiting" }, + ]); + }); + + it("ignores agents outside --until and does not treat running as appeared", () => { + const until = new Set(parseWaitUntil("appeared")); + expect( + matchingAgentStates([makeAgent(), makeAgent({ status: AgentStatus.WAITING })], until), + ).toEqual([]); + }); +}); + describe("waitForAgentChanges", () => { beforeEach(() => { vi.useFakeTimers(); @@ -194,9 +211,22 @@ describe("waitForAgentChanges", () => { expect(outcome.elapsedMs).toBeLessThanOrEqual(1_000); }); - it("returns timeout with no changes at the deadline", async () => { + it("returns triggered immediately when an agent already matches --until", async () => { const source = makeSource([makeAgent({ status: AgentStatus.WAITING })]); const result = waitForAgentChanges({ source, until, timeoutMs: 5_000 }); + await vi.advanceTimersByTimeAsync(0); + + await expect(result).resolves.toMatchObject({ + reason: "triggered", + changes: [{ name: "repo-a", from: "waiting", to: "waiting" }], + }); + expect(source.list).toHaveBeenCalledTimes(1); + expect(source.close).toHaveBeenCalledTimes(1); + }); + + it("returns timeout with no changes at the deadline", async () => { + const source = makeSource([makeAgent()]); + const result = waitForAgentChanges({ source, until, timeoutMs: 5_000 }); await vi.advanceTimersByTimeAsync(5_000); await expect(result).resolves.toEqual({ reason: "timeout", elapsedMs: 5_000, changes: [] }); From 120e7999faf45479460cb1eef75313b6c7442f44 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 16:49:15 +0000 Subject: [PATCH 2/2] fix(cli): option C for agent wait initial match with --id only Check current state only for filtered waits. Every watched agent must already match --until for an immediate return; unfiltered waits stay transition-only. Update web docs and agent-orchestration skill. Co-authored-by: Hoang Nguyen --- .../src/services/agent/agent-wait.service.ts | 16 +++++---- packages/cli/tests/commands/agent.test.ts | 16 +++++++-- .../services/agent/agent-wait.service.test.ts | 36 +++++++++++++++++-- skills/agent-orchestration/SKILL.md | 2 +- .../docs/20-cross-vendor-agent-recipe.md | 2 +- .../docs/22-agent-wait-channel-ping-recipe.md | 4 +-- web/content/docs/8-agent-management.md | 6 +++- 7 files changed, 65 insertions(+), 17 deletions(-) diff --git a/packages/cli/src/services/agent/agent-wait.service.ts b/packages/cli/src/services/agent/agent-wait.service.ts index 65e235e7..016e9a24 100644 --- a/packages/cli/src/services/agent/agent-wait.service.ts +++ b/packages/cli/src/services/agent/agent-wait.service.ts @@ -162,13 +162,15 @@ export async function waitForAgentChanges( // Subscribe before the baseline so a change in between still wakes us. await source.subscribe(wake); const initial = watched(await source.list()); - const initialMatches = matchingAgentStates(initial, until); - if (initialMatches.length > 0) { - return { - reason: "triggered", - elapsedMs: Date.now() - startedAt, - changes: initialMatches, - }; + if (watch && initial.length > 0) { + const initialMatches = matchingAgentStates(initial, until); + if (initialMatches.length === initial.length) { + return { + reason: "triggered", + elapsedMs: Date.now() - startedAt, + changes: initialMatches, + }; + } } let lastSeen = toSeen(initial); const changes = new Map(); diff --git a/packages/cli/tests/commands/agent.test.ts b/packages/cli/tests/commands/agent.test.ts index f4a8908a..5b49a7e9 100644 --- a/packages/cli/tests/commands/agent.test.ts +++ b/packages/cli/tests/commands/agent.test.ts @@ -4333,10 +4333,13 @@ Waiting on user input`, await program.parseAsync(["node", "test", "agent", "wait", ...args]); } - it("prints a triggered JSON result when an agent is already waiting", async () => { + it("prints a triggered JSON result when --id targets an agent that is already waiting", async () => { mockManager.listAgents.mockResolvedValue([running({ status: AgentStatus.WAITING })]); + mockManager.resolveAgent.mockImplementation((id: string, agents: any[]) => + agents.find((agent) => agent.name === id), + ); - await runWait("--until", "waiting", "--timeout", "50", "--json"); + await runWait("--id", "repo-a", "--until", "waiting", "--timeout", "50", "--json"); const output = JSON.parse(logSpy.mock.calls[0][0] as string); expect(output).toMatchObject({ @@ -4347,6 +4350,15 @@ Waiting on user input`, expect(process.exit).not.toHaveBeenCalled(); }); + it("times out when an agent is already waiting but no --id filter is set", async () => { + mockManager.listAgents.mockResolvedValue([running({ status: AgentStatus.WAITING })]); + + await runWait("--until", "waiting", "--timeout", "1", "--json"); + + const output = JSON.parse(logSpy.mock.calls[0][0] as string); + expect(output).toMatchObject({ reason: "timeout", changes: [] }); + }); + it("prints a triggered JSON result when an agent starts waiting", async () => { mockManager.listAgents .mockResolvedValueOnce([running()]) diff --git a/packages/cli/tests/services/agent/agent-wait.service.test.ts b/packages/cli/tests/services/agent/agent-wait.service.test.ts index 7876fbf9..4b4e70b5 100644 --- a/packages/cli/tests/services/agent/agent-wait.service.test.ts +++ b/packages/cli/tests/services/agent/agent-wait.service.test.ts @@ -211,9 +211,15 @@ describe("waitForAgentChanges", () => { expect(outcome.elapsedMs).toBeLessThanOrEqual(1_000); }); - it("returns triggered immediately when an agent already matches --until", async () => { - const source = makeSource([makeAgent({ status: AgentStatus.WAITING })]); - const result = waitForAgentChanges({ source, until, timeoutMs: 5_000 }); + it("returns triggered immediately when every watched agent already matches --until", async () => { + const watched = makeAgent({ status: AgentStatus.WAITING }); + const source = makeSource([watched, makeAgent({ pid: 11, name: "repo-b" })]); + const result = waitForAgentChanges({ + source, + until, + timeoutMs: 5_000, + watch: new Set([agentWaitKey(watched)]), + }); await vi.advanceTimersByTimeAsync(0); await expect(result).resolves.toMatchObject({ @@ -224,6 +230,30 @@ describe("waitForAgentChanges", () => { expect(source.close).toHaveBeenCalledTimes(1); }); + it("blocks when a watched agent is not yet in --until even if another watched agent matches", async () => { + const waiting = makeAgent({ status: AgentStatus.WAITING }); + const running = makeAgent({ pid: 11, name: "repo-b" }); + const source = makeSource([waiting, running]); + const result = waitForAgentChanges({ + source, + until: parseWaitUntil("waiting"), + timeoutMs: 5_000, + watch: new Set([agentWaitKey(waiting), agentWaitKey(running)]), + }); + await vi.advanceTimersByTimeAsync(5_000); + + await expect(result).resolves.toMatchObject({ reason: "timeout", changes: [] }); + }); + + it("still blocks on transition when an agent already matches but the wait is unfiltered", async () => { + const source = makeSource([makeAgent({ status: AgentStatus.WAITING })]); + const result = waitForAgentChanges({ source, until, timeoutMs: 5_000 }); + await vi.advanceTimersByTimeAsync(5_000); + + await expect(result).resolves.toEqual({ reason: "timeout", elapsedMs: 5_000, changes: [] }); + expect(source.close).toHaveBeenCalledTimes(1); + }); + it("returns timeout with no changes at the deadline", async () => { const source = makeSource([makeAgent()]); const result = waitForAgentChanges({ source, until, timeoutMs: 5_000 }); diff --git a/skills/agent-orchestration/SKILL.md b/skills/agent-orchestration/SKILL.md index bb84c4c0..bad0e6a9 100644 --- a/skills/agent-orchestration/SKILL.md +++ b/skills/agent-orchestration/SKILL.md @@ -26,7 +26,7 @@ If the goal or agent ownership is unclear, run one scan/detail pass. Ask the use 2. Assess agents needing attention with `detail --tail 10`. 3. Act: approve, clarify, correct, delegate, relay, verify, or escalate. 4. Report one brief status line. -5. Run `ai-devkit agent wait --json` (add `--id`/`--group` to watch only your agents), then repeat. It blocks until an agent moves to waiting, idle, or exited, or until its 5-minute default timeout; `reason: "timeout"` is normal, so do a light scan and wait again. If your command timeout is shorter, run it in the background or raise that timeout. Never use a long `sleep`: harnesses block or kill it. +5. Run `ai-devkit agent wait --json` (add `--id`/`--group` to watch only your agents), then repeat. With `--id` or `--group`, the wait returns immediately when every watched agent already matches `--until`; unfiltered wait is transition-only. It otherwise blocks until an agent moves to waiting, idle, or exited, or until its 5-minute default timeout; `reason: "timeout"` is normal, so do a light scan and wait again. If your command timeout is shorter, run it in the background or raise that timeout. Never use a long `sleep`: harnesses block or kill it. ## Completion diff --git a/web/content/docs/20-cross-vendor-agent-recipe.md b/web/content/docs/20-cross-vendor-agent-recipe.md index ca55c71e..f47a0138 100644 --- a/web/content/docs/20-cross-vendor-agent-recipe.md +++ b/web/content/docs/20-cross-vendor-agent-recipe.md @@ -98,7 +98,7 @@ Pipe logs without pasting: npm test 2>&1 | ai-devkit agent send --id codex-worker --stdin ``` -For ongoing supervision (multiple workers), the lead loads **agent-orchestration**: after each pass, run `ai-devkit agent wait --json` (optional `--id codex-worker`), then `agent list --json` again. Default wait timeout is 300000 ms; `reason: "timeout"` is normal. Scan and wait again. Do not use long shell `sleep` calls inside harness sessions. +For ongoing supervision (multiple workers), the lead loads **agent-orchestration**: after each pass, run `ai-devkit agent wait --id codex-worker --json` (repeat `--id` for more workers). A filtered wait returns immediately when that worker is already waiting, idle, or exited per `--until`, so you do not need `agent list --json` first. For every running agent, use unfiltered `agent wait --json` (transition-only). Default wait timeout is 300000 ms; `reason: "timeout"` is normal. Scan and wait again. Do not use long shell `sleep` calls inside harness sessions. ### 6. Stop and cleanup diff --git a/web/content/docs/22-agent-wait-channel-ping-recipe.md b/web/content/docs/22-agent-wait-channel-ping-recipe.md index 827a306f..154a9854 100644 --- a/web/content/docs/22-agent-wait-channel-ping-recipe.md +++ b/web/content/docs/22-agent-wait-channel-ping-recipe.md @@ -173,7 +173,7 @@ Flags that matter here (from `ai-devkit agent wait --help`): | `--id ` | Repeatable; watch subset of agents | | `--group ` | Watch a named agent group (mutually exclusive with `--id`) | -`agent wait` only reports transitions. If an agent is already waiting when the command starts, you will not get a ping until it leaves `waiting` and enters it again. +The unfiltered `agent wait` line above watches every agent and only reports **transitions**. If an agent is already waiting when a loop iteration starts, you will not get a ping until it leaves `waiting` and enters it again. To ping when specific agents are already waiting, add repeatable `--id` flags (see the example in the table section). Filtered waits return immediately when every watched agent already matches `--until`. ## Part 4: Run in the background (tmux) @@ -241,7 +241,7 @@ If you connected Telegram with `--name personal`, change the `jq` paths accordin |--------|----------------| | `authorizedChatId` empty / Telegram send fails | Message the bot once while a bridge is running; `channel list` should show Authorized: yes | | Slack `not_in_channel` or `ok: false` | `SLACK_NOTIFY_CHAT_ID` must be the DM id from bridge `--debug`; bot needs `chat:write` | -| No pings but agents are waiting | `agent wait` only fires on changes. Nudge the agent or wait for the next transition | +| No pings but agents are waiting | Unfiltered `agent wait` only fires on transitions; nudge the agent or wait for the next transition. Or add `--id` per agent so an already-waiting worker triggers immediately | | Loop stops when SSH disconnects | Run the script inside tmux (or screen), not a bare SSH session | | Timeouts every 5 minutes, no ping | Normal when nothing changes (`reason: "timeout"`). The loop should keep going | | `No agent found matching` with `--id` | Run `ai-devkit agent list --json`; use exact `name` values | diff --git a/web/content/docs/8-agent-management.md b/web/content/docs/8-agent-management.md index 928ae1ce..4252d22b 100644 --- a/web/content/docs/8-agent-management.md +++ b/web/content/docs/8-agent-management.md @@ -186,7 +186,11 @@ Useful options: - `--timeout `: maximum wait (default `300000`, 5 minutes, to stay under harness command limits) - `-j, --json`: `{ reason, elapsedMs, changes[] }`, with each change carrying `name`, `type`, `pid`, `from`, `to` -The command only fires on changes. An agent that is already waiting when the command starts does not end the wait; it has to move into the state. Changes picked up in the same daemon sweep are reported together; the wait usually returns about a second after the change. A timeout exits `0` with `reason: "timeout"`. +Without `--id` or `--group`, the command only fires on **changes**. An agent that is already waiting when an unfiltered wait starts does not end the wait until it leaves the state and enters it again. + +With `--id` or `--group`, the wait first checks whether **every** watched agent already matches `--until`. If they do, it returns immediately with `reason: "triggered"` and the same JSON shape as a transition (`from` and `to` are the current status). Otherwise it blocks for changes like an unfiltered wait. + +Changes picked up in the same daemon sweep are reported together; the wait usually returns about a second after the change. A timeout exits `0` with `reason: "timeout"`. With the daemon running, waits react to its status events, so several waits on one machine share one process sweep. Without the daemon, the command checks local detection every 30 seconds.