For agentic workers: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking. Do not create git commits unless the user explicitly asks in the current task.
Goal: 明确 goal / background task 语义:goal completion verification 必须等当前 session 内所有 running background work settle,并且每条 <task-notification> 都先作为 model-only synthetic user input 进入模型后,才允许 goal verification。
Architecture: 继续复用当前 AgentRuntime 实例级 runtime command queue,不重写 subagent 体系。target-continuation 在 command 执行时检查 session projection 中的 running background task;task-notification command 在完成自己的 model turn 后,按队列状态决定是否触发 post-notification goal loop。
Tech Stack: TypeScript, AgentRuntime, runtime command queue, session event projection, Vitest.
task-notification 唤醒 main;notification 本身先进入模型上下文。apps/zcode-cli/packages/core/src/runtime/methods/target.ts
apps/zcode-cli/packages/core/src/runtime/methods/runtime-command-queue.ts
task-notification command 完成自己的 model turn 后,触发 post-notification goal loop。task-notification,本次 post check 直接跳过。apps/zcode-cli/packages/core/tests/runtime-tool-loop.test.ts
apps/zcode-cli/docs/design/v2/session-target.md
Files:
apps/zcode-cli/packages/core/src/runtime/methods/target.tsapps/zcode-cli/packages/core/tests/runtime-tool-loop.test.tsInterfaces:
hasRunningBackgroundTaskForGoalContinuation(this: AgentRuntimeInternal): Promise<boolean>executeTargetContinuationCommand(...) 在 verifier 前调用该 helper。this.rebuildProjection()projection.backgroundTasks[].statusChecklist:
Add this test near existing target continuation tests in apps/zcode-cli/packages/core/tests/runtime-tool-loop.test.ts:
it("defers goal completion verification while background tasks are still running", async () => {
const sessionId = createSessionId("runtime-target-defers-running-background");
const eventStore = createTestSessionEventStore();
const sessionStore = new RecordingSessionStore();
const requests: any[] = [];
await eventStore.append(
createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
cancellable: true,
command: "npm run test",
startedAt: new Date(0),
status: "running",
taskId: "bg_goal_running",
terminalId: "bg_goal_running",
toolCallId: "tool_bg_goal_running",
toolName: "Bash",
}),
);
const runtime = new AgentRuntime(
sessionId,
{ mode: "build", workingDirectory: "/tmp/zcode-runtime-target-bg-defer" },
{
eventStore,
modelAdapter: {
async generateText(request: any) {
requests.push(request);
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: "unexpected verifier request",
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
},
} as never,
sessionStore,
},
);
await runtime.ensureSessionPersistedForExternalActivity("/goal Wait for background");
await sessionStore.setTarget({
objective: "Wait for background output before verification",
sessionID: sessionId,
});
await expect(
runtime.continueActiveTargetIfIdle({ verifyBeforeContinue: true }),
).resolves.toBeNull();
expect(requests).toEqual([]);
});
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/runtime-tool-loop.test.ts -t "defers goal completion verification while background tasks are still running"
Expected before implementation: fail because one verifier model request is made.
target.tsAdd below targetContinuationCandidateForCommand(...):
export async function hasRunningBackgroundTaskForGoalContinuation(
this: AgentRuntimeInternal,
): Promise<boolean> {
const projection = await this.rebuildProjection();
return projection.backgroundTasks.some((task) => task.status === "running");
}
In executeTargetContinuationCommand(...), immediately after if (!target) return null;, add:
if (await hasRunningBackgroundTaskForGoalContinuation.call(this)) {
this.logger?.info("Goal continuation deferred while background tasks are running", {
...traceContextToLogContext(traceContext),
event: "target.continuation.deferred_background_running",
module: "core.runtime",
status: "waiting",
targetId: target.targetID,
});
return null;
}
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/runtime-tool-loop.test.ts -t "defers goal completion verification while background tasks are still running"
Expected after implementation: pass.
Phase 1 Pass Standard:
running.continueActiveTargetIfIdle({ verifyBeforeContinue: true }) resolves null instead of hanging or requeueing.Files:
apps/zcode-cli/packages/core/src/runtime/methods/runtime-command-queue.tsapps/zcode-cli/packages/core/tests/runtime-tool-loop.test.tsInterfaces:
executeTargetContinuationCommand.call(this, { traceContext, verifyBeforeContinue: true })this.runtimeCommandQueue.snapshot()hasPendingTaskNotificationCommand(this: AgentRuntimeInternal): booleancontinueTargetAfterTaskNotification(this: AgentRuntimeInternal, command: RuntimeCommand): Promise<void>Checklist:
Add this test near the existing "queues background notifications behind target completion verification" test in apps/zcode-cli/packages/core/tests/runtime-tool-loop.test.ts:
it("runs pending background notifications before goal completion verification", async () => {
const sessionId = createSessionId("runtime-target-notification-before-verifier");
const eventStore = createTestSessionEventStore();
const sessionStore = new RecordingSessionStore();
const requestOrder: string[] = [];
let verifierCount = 0;
const runtime = new AgentRuntime(
sessionId,
{ mode: "build", workingDirectory: "/tmp/zcode-runtime-target-notification-order" },
{
eventStore,
modelAdapter: {
async generateText(request: any) {
const latestText = providerContentToText(
request.messages.at(-1)?.content,
);
if (latestText.includes("<task-id>bg-notification-1</task-id>")) {
requestOrder.push("notification-1");
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: "processed notification 1",
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
}
if (latestText.includes("<task-id>bg-notification-2</task-id>")) {
requestOrder.push("notification-2");
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: "processed notification 2",
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
}
if (latestText.includes("Verify whether the active session goal")) {
verifierCount++;
if (verifierCount === 1) {
requestOrder.push("verifier-fail");
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: JSON.stringify({
nextAction: "Continue after both background notifications.",
passed: false,
reason: "The background results are now available.",
}),
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
}
requestOrder.push("verifier-pass");
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: JSON.stringify({
nextAction: "",
passed: true,
reason: "The goal is complete after the continuation.",
}),
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
}
requestOrder.push("continuation");
return {
finishReason: "stop",
model: request.model,
providerMetadata: undefined,
text: "continued target after notifications",
usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
};
},
} as never,
sessionStore,
},
);
await runtime.ensureSessionPersistedForExternalActivity("/goal Wait for notifications");
await sessionStore.setTarget({
objective: "Use both background notifications before verification",
sessionID: sessionId,
});
runtime.enqueueBackgroundTaskNotification({
text: "<task-notification><task-id>bg-notification-1</task-id><status>completed</status></task-notification>",
traceContext: { sessionId, traceId: "trace_bg_notification_1" },
});
runtime.enqueueBackgroundTaskNotification({
text: "<task-notification><task-id>bg-notification-2</task-id><status>completed</status></task-notification>",
traceContext: { sessionId, traceId: "trace_bg_notification_2" },
});
await waitForCondition(() => requestOrder.includes("continuation"));
expect(requestOrder).toEqual([
"notification-1",
"notification-2",
"verifier-fail",
"continuation",
"verifier-pass",
]);
});
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/runtime-tool-loop.test.ts -t "runs pending background notifications before goal completion verification"
Expected before implementation: fail because no verifier/continuation runs after notification commands, or verifier order is not guaranteed.
runtime-command-queue.tsAdd below hasActiveOrQueuedTurnWork(...):
function hasPendingTaskNotificationCommand(this: AgentRuntimeInternal): boolean {
return this.runtimeCommandQueue
.snapshot()
.some((candidate) => candidate.mode === "task-notification");
}
Add below hasPendingTaskNotificationCommand(...):
async function continueTargetAfterTaskNotification(
this: AgentRuntimeInternal,
command: RuntimeCommand,
): Promise<void> {
try {
while (!hasPendingTaskNotificationCommand.call(this)) {
const result = await executeTargetContinuationCommand.call(this, {
traceContext: command.traceContext,
verifyBeforeContinue: true,
});
if (!result) return;
}
} catch (error) {
this.logger?.warn("Goal continuation after background notification failed", {
...traceContextToLogContext(command.traceContext),
errorMessage: error instanceof Error ? error.message : String(error),
event: "target.continuation.after_background_notification_failed",
module: "core.runtime",
});
}
}
In the command.mode === "task-notification" branch, after await this.executeTurnCommand(...), add:
await continueTargetAfterTaskNotification.call(this, command);
The resulting branch should keep this order:
if (command.mode === "task-notification") {
const messageId = await persistBackgroundTaskNotificationCommand.call(
this,
command,
);
await this.executeTurnCommand(command.text, undefined, {
inputSource: "background_task",
inputVisibility: "model-only",
recordedInputMessageId: messageId,
skipInputRecord: true,
skipUserPromptSubmitHooks: true,
traceContext: command.traceContext,
});
await continueTargetAfterTaskNotification.call(this, command);
return;
}
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/runtime-tool-loop.test.ts -t "runs pending background notifications before goal completion verification"
Expected after implementation: pass.
Phase 2 Pass Standard:
inputSource: "background_task" before any goal verifier runs.task-notification command is already pending, the current notification does not start verifier.running, Phase 1 helper still defers verifier.Files:
apps/zcode-cli/docs/design/v2/session-target.mdInterfaces:
Checklist:
Add this paragraph under the goal continuation / completion verification section in apps/zcode-cli/docs/design/v2/session-target.md:
When an active goal exists and the session has running background tasks, goal completion verification is deferred. Background task completion notifications are model-only synthetic user inputs and must be delivered to the model before the verifier decides whether the goal is complete. If multiple notifications are pending, the runtime drains those notifications first and only starts goal verification after no pending task notification remains and no background task is still running.
Check:
rg -n "running background tasks|task notification|completion verification" apps/zcode-cli/docs/design/v2/session-target.md
Expected: the new paragraph is present once and does not mention external product names.
Phase 3 Pass Standard:
Files:
Checklist:
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/runtime-tool-loop.test.ts -t "background Bash|target continuation|target completion verification|background notifications"
Expected: all selected tests pass.
Run:
cd apps/zcode-cli/packages/core
./node_modules/.bin/vitest run tests/subagent-background.test.ts tests/runtime-command-queue.test.ts
Expected: all tests pass.
Run:
cd apps/zcode-cli/packages/core
../../../../node_modules/.bin/tsc --noEmit
Expected: command exits 0.
Run from repo root:
git diff --check
Expected: command exits 0.
Phase 4 Pass Standard:
git diff --check passes.task-notification still persists as model-only synthetic user input with source: "background_task".task-notification still skips user prompt submit hooks.running.