From 9bb29338a491564de48fc6f0e8ad4b6369025eec Mon Sep 17 00:00:00 2001 From: John Smith Date: Fri, 4 Dec 2026 11:47:22 -0500 Subject: [PATCH 1/2] fix: exempt non-handoff roles from idle-guard and remediate PR #72 regressions (0.21.2) Fixes #73 by deriving subagent idle-guard handoff eligibility from the canonical handoff role lists in handoff.ts (shared with authorize.ts) instead of a hand-maintained exemption set, so team/scout and other non-handoff roles are not nudged or marked stalled. Also fixes 5 regressions introduced in PR #72 (4eb8074..59d848b): restores the !cheap || guard in claimReadyTasks, converts CANONICAL_STATUS_BY_SHORT to a Map, restores ok: false on document-review error returns, and restores typeof string check in resolveUpdateDeclaration. Signed-off-by: John Smith --- CHANGELOG.md | 40 ++++++ agents/team/scout.md | 5 +- docs/ARTIFACTS.md | 6 +- package.json | 2 +- plugins/opencode-teamwork/authorize.ts | 15 +-- plugins/opencode-teamwork/document-review.ts | 18 +-- plugins/opencode-teamwork/handoff.ts | 13 +- plugins/opencode-teamwork/lemma.ts | 2 +- plugins/opencode-teamwork/package.json | 2 +- plugins/opencode-teamwork/subagent-hooks.ts | 12 +- plugins/opencode-teamwork/tools.ts | 18 +-- scripts/test-engine.mjs | 24 ++++ scripts/test-subagent-hooks.mjs | 122 +++++++++++++++++++ tests/runtime/spec/k-subagent-idle.test.ts | 38 ++++++ 14 files changed, 279 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fa1c74..a85f46c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,46 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.21.2] - 2026-12-04 + +### Fixed + +- **Derive subagent idle-guard handoff eligibility from canonical handoff roles (#73):** + - Exported `HANDOFF_ELIGIBLE_ROLES` and `isHandoffEligibleRole` from + `plugins/opencode-teamwork/handoff.ts` and reused `HANDOFF_ELIGIBLE_ROLES` + in `plugins/opencode-teamwork/authorize.ts` so the handoff role list has a + single source of truth. + - Updated `plugins/opencode-teamwork/subagent-hooks.ts` to gate the + `experimental.idle` handoff guard and `collectStalledChildren` on + `isHandoffEligibleRole(agent) && !ORCHESTRATOR_ROLES.has(agent)` instead of + the hand-maintained `HANDOFF_EXEMPT_TEAM_AGENTS` set. `team/scout` (and + other non-handoff roles such as `team/crafter`, + `team/formalization-reviewer`, `team/proposer`, and `team/referee`) no + longer get nudged for `teamwork_handoff` or marked `stalled`, while + handoff-eligible child roles (`team/worker`, `team/verifier`, + `team/falsifier`, `team/security-auditor`, `team/victory-auditor`, etc.) + keep the guard. + - Clarified in `docs/ARTIFACTS.md` and `agents/team/scout.md` that + `team/scout` is outside the continuity handoff matrix and does not have + access to `teamwork_handoff` or `teamwork_evidence`. + - Added L0 (`scripts/test-subagent-hooks.mjs`, `scripts/test-engine.mjs`) + and L1/L2 runtime (`tests/runtime/spec/k-subagent-idle.test.ts` K2) + regression coverage. +- **PR #72 refactor regressions:** + - Restored `!cheap ||` null-guard before `cheap.headSha !== current.headSha` + in `claimReadyTasks` (`plugins/opencode-teamwork/tools.ts`) so a failed + `captureGitBaselineCheap` when `current.headSha` is `undefined` marks the + claim `needs-inspection` instead of throwing `TypeError` inside the lock. + - Converted `CANONICAL_STATUS_BY_SHORT` to a `Map` (`tools.ts`) so both + `canonicalTaskStatus` and `teamwork_task_update` pre-capture lookups avoid + prototype-chain keys. + - Restored `ok: false` on `openBoundedDocumentFd` and + `checkDocumentSourceCombo` error returns in + `plugins/opencode-teamwork/document-review.ts`. + - Restored `typeof declaration !== "string"` in `resolveUpdateDeclaration` + (`plugins/opencode-teamwork/lemma.ts`) so direct `declaration: null` + updates do not throw `TypeError`. + ## [0.21.1] - 2026-12-03 ### Fixed diff --git a/agents/team/scout.md b/agents/team/scout.md index 017255d..0daaff5 100644 --- a/agents/team/scout.md +++ b/agents/team/scout.md @@ -30,7 +30,10 @@ every downstream agent is wrong. ## Output -Write to `.opencode/teamwork//scout-report.md`. Structure: +Write to `.opencode/teamwork//scout-report.md`. `team/scout` is +outside the continuity handoff matrix and does not have access to +`teamwork_handoff` or `teamwork_evidence`; deliver your findings via +`scout-report.md` and your final response. Structure: ```md # Scout Report diff --git a/docs/ARTIFACTS.md b/docs/ARTIFACTS.md index dd4ce50..8bb70fe 100644 --- a/docs/ARTIFACTS.md +++ b/docs/ARTIFACTS.md @@ -1045,6 +1045,8 @@ derived from the trusted caller and the scope — never supplied by the agent: | `team/security-auditor` | task (strict per-task audit) or run-level (pre-merge audit) | `handoffs/-security-auditor.md` / `handoffs/_run-security-auditor.md` | | `team/victory-auditor`, `team/sentinel`, `team/orchestrator` | run-level only (`taskId` omitted or `_run`) | `/handoffs/_run-.md` | +Roles outside this table — notably `team/scout` (as well as `team/crafter`, `team/formalization-reviewer`, `team/proposer`, and `team/referee`) — are not part of the continuity handoff matrix and are denied by `teamwork_handoff` (`AUTHZ_ROLE_DENIED`). A scout's `scout-report.md` and briefing serve as its continuity artifact, and the subagent idle-guard does not require a handoff from it. + The tool has no `agent` input: it uses `deriveCallerAgent` plus descent from the plan-time `rootSessionId`. Every handoff has exactly these five headings: @@ -2389,7 +2391,9 @@ and a run holds at most 32 of them. The tool returns: Cite the path from `teamwork_wave_record`; the strict gate re-hashes the file and FAILs if it is missing, resized, or edited. This records bytes, not a -verdict. +verdict. Access is restricted to worker, verifier, auditor, and sentinel roles; +`team/scout` does not have access to `teamwork_evidence` and delivers its +findings through `scout-report.md` and its response. ### `GATE_STATUS.md` (strict verification gate table) diff --git a/package.json b/package.json index 648690b..1d796aa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@heretek-ai/opencode-teamwork-v2", - "version": "0.21.1", + "version": "0.21.2", "description": "Antigravity-style multi-agent orchestration for OpenCode V2 — 14 agents, 2 commands, interactive model assignment on install.", "keywords": [ "opencode", diff --git a/plugins/opencode-teamwork/authorize.ts b/plugins/opencode-teamwork/authorize.ts index 3fec898..1114642 100644 --- a/plugins/opencode-teamwork/authorize.ts +++ b/plugins/opencode-teamwork/authorize.ts @@ -18,6 +18,8 @@ // // Zero runtime dependencies. Erasable TypeScript only. +import { HANDOFF_ELIGIBLE_ROLES } from "./handoff.ts" + const INSTALLED_TEAM_ROLES = new Set([ "team/crafter", "team/sentinel", @@ -121,18 +123,7 @@ const RULES: Record = { }, handoff: { actions: { - "*": [ - "team/worker", - "team/proof-worker", - "team/segment-reviewer", - "team/synthesizer", - "team/verifier", - "team/falsifier", - "team/security-auditor", - "team/victory-auditor", - "team/sentinel", - "team/orchestrator", - ], + "*": [...HANDOFF_ELIGIBLE_ROLES], }, requireRoot: true, }, diff --git a/plugins/opencode-teamwork/document-review.ts b/plugins/opencode-teamwork/document-review.ts index 66c329e..08e5e44 100644 --- a/plugins/opencode-teamwork/document-review.ts +++ b/plugins/opencode-teamwork/document-review.ts @@ -1347,13 +1347,13 @@ function readFdBounded(fd: number, maxBytes: number): { ok: true; full: Buffer } /** Open the resolved document no-follow and validate it; closes the fd on refusal. */ function openBoundedDocumentFd( resolved: string, -): { fd: number } | { error: string } { +): { ok: true; fd: number } | { ok: false; error: string } { let fd: number try { const nofollow = typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0 fd = openSync(resolved, fsConstants.O_RDONLY | nofollow) } catch (err: any) { - return { error: `refused: could not read document (${cleanDocText(err?.message || err?.code, 120)})` } + return { ok: false, error: `refused: could not read document (${cleanDocText(err?.message || err?.code, 120)})` } } const closeQuietly = (): void => { try { @@ -1365,17 +1365,17 @@ function openBoundedDocumentFd( st = fstatSync(fd) } catch (err: any) { closeQuietly() - return { error: `refused: could not read document (${cleanDocText(err?.message || err?.code, 120)})` } + return { ok: false, error: `refused: could not read document (${cleanDocText(err?.message || err?.code, 120)})` } } if (!st.isFile()) { closeQuietly() - return { error: "refused: document path is not a regular file" } + return { ok: false, error: "refused: document path is not a regular file" } } if (st.size > MAX_DOCUMENT_BYTES) { closeQuietly() - return { error: `refused: document exceeds ${MAX_DOCUMENT_BYTES} byte limit (${st.size} bytes)` } + return { ok: false, error: `refused: document exceeds ${MAX_DOCUMENT_BYTES} byte limit (${st.size} bytes)` } } - return { fd } + return { ok: true, fd } } function readPathDocument( @@ -1388,7 +1388,7 @@ function readPathDocument( let fd: number | undefined try { const opened = openBoundedDocumentFd(check.resolved) - if ("error" in opened) return opened + if (!opened.ok) return opened fd = opened.fd const contentRes = readFdBounded(fd, MAX_DOCUMENT_BYTES) if (!contentRes.ok) return contentRes @@ -1563,9 +1563,9 @@ function checkDocumentSourceCombo( hasPath: boolean, hasUrl: boolean, hasContent: boolean, -): { error: string } | null { +): { ok: false; error: string } | null { if (hasPath && (hasUrl || (hasContent && doc.content!.trim().length > 0))) { - return { error: "refused: document.path cannot be combined with document.url or document.content" } + return { ok: false, error: "refused: document.path cannot be combined with document.url or document.content" } } return null } diff --git a/plugins/opencode-teamwork/handoff.ts b/plugins/opencode-teamwork/handoff.ts index 228a15b..763f630 100644 --- a/plugins/opencode-teamwork/handoff.ts +++ b/plugins/opencode-teamwork/handoff.ts @@ -76,6 +76,12 @@ const TASK_SCOPED_HANDOFF_ROLES = [ /** These roles record run-level handoffs and must omit `taskId`. */ const RUN_LEVEL_HANDOFF_ROLES = ["team/victory-auditor", "team/sentinel", "team/orchestrator"] as const +/** Canonical list of all roles eligible to record a `teamwork_handoff`. */ +export const HANDOFF_ELIGIBLE_ROLES: readonly string[] = [ + ...TASK_SCOPED_HANDOFF_ROLES, + ...RUN_LEVEL_HANDOFF_ROLES, +] + interface HandoffCite { path: string sha256: string @@ -226,6 +232,11 @@ function isRunLevelRole(agent: string): boolean { return (RUN_LEVEL_HANDOFF_ROLES as readonly string[]).includes(agent) } +/** True when `agent` is allowed to record a task-scoped or run-level handoff. */ +export function isHandoffEligibleRole(agent: string): boolean { + return isTaskScopedRole(agent) || isRunLevelRole(agent) +} + /** * Resolve the caller's trusted agent and optional task id into a handoff scope. * Task-scoped roles (including the security auditor's per-task strict audit) @@ -236,7 +247,7 @@ export function resolveHandoffScope( agent: string, rawTaskId: unknown, ): { ok: true; taskKey: string; taskId?: string } | { ok: false; error: string } { - if (!isTaskScopedRole(agent) && !isRunLevelRole(agent)) { + if (!isHandoffEligibleRole(agent)) { return { ok: false, error: `refused: ${clean(agent, 64) || "this role"} may not record a handoff; nothing was written` } } const raw = typeof rawTaskId === "string" ? rawTaskId.trim() : "" diff --git a/plugins/opencode-teamwork/lemma.ts b/plugins/opencode-teamwork/lemma.ts index dcf9755..022cc27 100644 --- a/plugins/opencode-teamwork/lemma.ts +++ b/plugins/opencode-teamwork/lemma.ts @@ -3094,7 +3094,7 @@ function recordLemmaAttempt( function resolveUpdateDeclaration( declaration: string | undefined, ): { declaration?: string | null } | { error: string } { - if (declaration === undefined) return {} + if (typeof declaration !== "string") return {} const decl = declaration.trim() if (!decl) return { declaration: null } if (!isSafeLeanDeclarationName(decl)) { diff --git a/plugins/opencode-teamwork/package.json b/plugins/opencode-teamwork/package.json index 29b2739..c269b8d 100644 --- a/plugins/opencode-teamwork/package.json +++ b/plugins/opencode-teamwork/package.json @@ -1,6 +1,6 @@ { "name": "opencode-teamwork", - "version": "0.21.1", + "version": "0.21.2", "private": true, "type": "module", "description": "Vendored V2 port of opencode-teamwork (registers the /teamwork command family, ships the teamwork_* engine tools).", diff --git a/plugins/opencode-teamwork/subagent-hooks.ts b/plugins/opencode-teamwork/subagent-hooks.ts index 0151d83..ea40a92 100644 --- a/plugins/opencode-teamwork/subagent-hooks.ts +++ b/plugins/opencode-teamwork/subagent-hooks.ts @@ -1,5 +1,6 @@ import { existsSync, readFileSync } from "node:fs" import { join } from "node:path" +import { isHandoffEligibleRole } from "./handoff.ts" import { clean } from "./text-utils.ts" /** @@ -21,7 +22,12 @@ const ACTIVE_PHASES = new Set([ "MERGE", ]) -const HANDOFF_EXEMPT_TEAM_AGENTS = new Set(["team/sentinel", "team/crafter"]) +const ORCHESTRATOR_ROLES = new Set(["team/sentinel", "team/orchestrator"]) + +/** True when a tracked child subagent must record a `teamwork_handoff` before going idle. */ +function requiresChildHandoff(agent: string): boolean { + return isHandoffEligibleRole(agent) && !ORCHESTRATOR_ROLES.has(agent) +} type TrackedSubagent = { childSessionID: string @@ -285,7 +291,7 @@ function collectStalledChildren( ): TrackedSubagent[] { const stalledChildren: TrackedSubagent[] = [] for (const child of trackedSubagents.values()) { - if (child.parentSessionID !== sessionID || child.handoffRecorded) continue + if (child.parentSessionID !== sessionID || child.handoffRecorded || !requiresChildHandoff(child.agent)) continue if (child.runPath && hasRecentHandoff(child.runPath, child.agent, child.dispatchedAt, child.childSessionID)) { child.handoffRecorded = true child.stalled = false @@ -430,7 +436,7 @@ export async function registerSubagentAndIdleHooks( const runPath = await resolveActiveRunPath(ctx, root, sessionID, tracked, deps, readRunPhase) if (!runPath) return - if (tracked && !HANDOFF_EXEMPT_TEAM_AGENTS.has(agent)) { + if (tracked && requiresChildHandoff(agent)) { await handleTrackedChildIdle(ctx, sessionID, runPath, tracked, hasRecentHandoff) return } diff --git a/plugins/opencode-teamwork/tools.ts b/plugins/opencode-teamwork/tools.ts index 6dc6885..d385242 100644 --- a/plugins/opencode-teamwork/tools.ts +++ b/plugins/opencode-teamwork/tools.ts @@ -750,15 +750,16 @@ function normalizeTournamentTask(t: any): { } /** Canonical task statuses for legacy short aliases (`pass`/`fail`/`running`). */ -const CANONICAL_STATUS_BY_SHORT: Record = { - pass: "verified_pass", - fail: "verified_fail", - running: "worker_active", -} +const CANONICAL_STATUS_BY_SHORT = new Map([ + ["pass", "verified_pass"], + ["fail", "verified_fail"], + ["running", "worker_active"], +]) /** Legacy aliases resolve to the canonical node; unrecognised statuses stay `pending`. */ function canonicalTaskStatus(fromStatus: string, validStatuses: Set): string { - if (Object.hasOwn(CANONICAL_STATUS_BY_SHORT, fromStatus)) return CANONICAL_STATUS_BY_SHORT[fromStatus] + const short = CANONICAL_STATUS_BY_SHORT.get(fromStatus) + if (short !== undefined) return short return validStatuses.has(fromStatus) ? fromStatus : "pending" } @@ -3557,7 +3558,8 @@ async function claimReadyTasks(args: { if (current?.scope === "git" && cwd) { const cheap = captureGitBaselineCheap(cwd, `teamwork/base-${basename(run)}`) drifted = - cheap?.headSha !== current.headSha || + !cheap || + cheap.headSha !== current.headSha || cheap.diffHash !== current.diffHash || cheap.statusHash !== current.statusHash } @@ -11562,7 +11564,7 @@ export async function registerTeamworkTools(ctx: any, root: string) { let reportEvidence: { headSha?: string; baseSha?: string; diffHash?: string } | undefined if (preProtocol >= CLAIM_PROTOCOL) { const rawStatus = clean(input.status, 32) - const preStatus = CANONICAL_STATUS_BY_SHORT[rawStatus] ?? rawStatus + const preStatus = CANONICAL_STATUS_BY_SHORT.get(rawStatus) ?? rawStatus if (preStatus === "worker_active" || preStatus === "verifier_active") { const captureTask = { ...(preTask ?? {}), diff --git a/scripts/test-engine.mjs b/scripts/test-engine.mjs index f82ef54..3088eec 100644 --- a/scripts/test-engine.mjs +++ b/scripts/test-engine.mjs @@ -13,6 +13,7 @@ import { formatMissingToolchainRefusal, leanStatementMatches, LEAP_REQUIREMENT, + mutateLemmaNode, parseLeanAxiomOutput, parseLeanDeclarations, probeLemmaToolchain, @@ -21,6 +22,7 @@ import { validateLemmaPolicy, verifyLeanFile, } from "../plugins/opencode-teamwork/lemma.ts" +import { resolveAndReadDocument } from "../plugins/opencode-teamwork/document-review.ts" import { compareCandidates, classifyTournamentRoute, maskCodeAndQuotes, readBoundedRunFile, writeSafeRunFile } from "../plugins/opencode-teamwork/tournament.ts" import { clean, cleanBlock } from "../plugins/opencode-teamwork/text-utils.ts" import { BUDGET_HALT_PCT, budgetPercent, budgetThresholdReached } from "../plugins/opencode-teamwork/budget.ts" @@ -5975,6 +5977,13 @@ try { }) const cleanRep = readFileSync(join(docRoot, ".opencode", "teamwork", cleanRun, "DOCUMENT_REVIEW_REPORT.md"), "utf8") assert(!/[\u0085\u2028\u2029]/.test(cleanRep) && !cleanRep.includes("\x1b"), "Control chars must be stripped from DOCUMENT_REVIEW_REPORT.md") + + // PR #72 remediation: resolveAndReadDocument must return strict ok: false on combo and fd-open errors + const comboRefusal = await resolveAndReadDocument(docRoot, { path: "doc.md", url: "https://example.com" }) + assert.strictEqual(comboRefusal.ok, false, "source-combo refusal must set ok: false") + const missingRefusal = await resolveAndReadDocument(docRoot, { path: "nonexistent-doc.md" }) + assert.strictEqual(missingRefusal.ok, false, "openBoundedDocumentFd refusal must set ok: false") + console.log("✓ 9.7 Security (traversal, symlinks, SEGMENT_ID, sanitisation) passed") } finally { rmSync(docRoot, { recursive: true, force: true }) @@ -8357,6 +8366,15 @@ if (args.includes("doctor")) { const okCwdRes = await tools.teamwork_lemma_verify.execute({ sessionId: RUN, lemmaId: "root", round: 1, cwd: "lean-sub" }) assert.strictEqual(okCwdRes.report?.status, "PASS", `valid subdir cwd must succeed: ${okCwdRes.content}`) + // PR #72 remediation: mutateLemmaNode with non-string declaration (null) must not throw TypeError + const nullDeclRes = mutateLemmaNode(join(rootSec, ".opencode", "teamwork", RUN), { + action: "update", + lemmaId: "root", + declaration: null, + }) + assert.strictEqual(nullDeclRes.error, undefined, `null declaration update must not fail: ${JSON.stringify(nullDeclRes)}`) + assert.strictEqual(nullDeclRes.node.declaration, "t", "null declaration must leave existing declaration unchanged") + console.log("✓ 9.5 security containment (LEMMA_ID, symlink, sanitization) verified") } @@ -10180,6 +10198,8 @@ process.stdout.write(JSON.stringify({ receipt: "fixture-receipt:" + request.runI assert(!authRefused(res), `team/worker must update its task: ${res.content}`) res = await call("task_update", { sessionId: runId, taskId: "A1", status: "worker_done" }, verifier) assert(!authRefused(res), `team/verifier must be able to update the lifecycle: ${res.content}`) + res = await call("task_update", { sessionId: runId, taskId: "A1", status: "constructor" }, worker) + assert(res.content.startsWith('Error: Invalid status "constructor"'), `prototype key status must be refused without leakage: ${res.content}`) // security_audit: only a descendant team/security-auditor. res = await call("security_audit", { sessionId: runId, status: "PASS", findings: [] }, worker) @@ -10201,6 +10221,10 @@ process.stdout.write(JSON.stringify({ receipt: "fixture-receipt:" + request.runI res = await call("pitfall", { sessionId: runId, pitfall: "unknown" }, unknown) assert(authRefused(res), `an unresolved identity must not log a pitfall: ${res.content}`) + // evidence: restricted to worker/verifier/auditor/sentinel roles; team/scout is denied. + res = await call("evidence", { sessionId: runId, name: "scout.txt", content: "survey" }, "ses_fixture_scout") + assert(authRefused(res), `team/scout must not write evidence: ${res.content}`) + // document_triage / document_record: sentinel vs reviewer/synthesizer split. res = await call("document_triage", { sessionId: "20261123-000030-authz-doc-denied", document: { content: "# A\n\nx\n\n# B\n\ny" }, skipInterview: true }, worker) assert(authRefused(res), `team/worker must not triage a document: ${res.content}`) diff --git a/scripts/test-subagent-hooks.mjs b/scripts/test-subagent-hooks.mjs index 87be1af..26b29a1 100644 --- a/scripts/test-subagent-hooks.mjs +++ b/scripts/test-subagent-hooks.mjs @@ -306,6 +306,128 @@ try { await mock.emitIdle({ sessionID: "ses-worker-6", background: [] }) assert.equal(mock.syntheticCalls.length, 1 + MAX_IDLE_NUDGES) }) + + await runCase("does not nudge team/scout or other non-handoff roles on idle and does not mark them stalled", async () => { + const runPath = join(tmp, "run-scout") + mkdirSync(runPath, { recursive: true }) + writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) + + const nonHandoffRoles = [ + "team/scout", + "team/crafter", + "team/formalization-reviewer", + "team/proposer", + "team/referee", + ] + const sessionAgents = { "ses-sentinel": "team/sentinel" } + for (const [idx, role] of nonHandoffRoles.entries()) { + sessionAgents[`ses-nonhandoff-${idx}`] = role + } + + const mock = createMockCtx(sessionAgents) + const { trackedSubagents } = await registerSubagentAndIdleHooks(mock.ctx, tmp, { + runForSession: async () => runPath, + }) + + for (const [idx, role] of nonHandoffRoles.entries()) { + const childID = `ses-nonhandoff-${idx}` + await mock.emitToolBefore({ + tool: "subagent", + id: `call-nh-${idx}`, + sessionID: "ses-sentinel", + agent: "team/sentinel", + input: { agent: role, description: `Survey (${role})`, prompt: "Inspect workspace" }, + }) + await mock.emitToolAfter({ + tool: "subagent", + id: `call-nh-${idx}`, + sessionID: "ses-sentinel", + agent: "team/sentinel", + status: "completed", + input: { agent: role, description: `Survey (${role})` }, + result: { metadata: { sessionID: childID, status: "completed" } }, + }) + + for (let i = 0; i < MAX_IDLE_NUDGES + 2; i += 1) { + await mock.emitIdle({ sessionID: childID, background: [] }) + } + assert.equal(trackedSubagents.get(childID).stalled, false, `${role} must not be marked stalled`) + } + + // Sentinel going idle after non-handoff children finish must not receive a stalled-child nudge. + await mock.emitIdle({ sessionID: "ses-sentinel", background: [] }) + assert.equal(mock.syntheticCalls.length, 0) + }) + + await runCase("still nudges all handoff-eligible child roles (worker, verifier, falsifier, security-auditor, victory-auditor)", async () => { + const runPath = join(tmp, "run-guarded") + mkdirSync(runPath, { recursive: true }) + writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) + + const guardedRoles = [ + "team/worker", + "team/verifier", + "team/falsifier", + "team/security-auditor", + "team/victory-auditor", + ] + const sessionAgents = { "ses-sentinel": "team/sentinel" } + for (const [idx, role] of guardedRoles.entries()) { + sessionAgents[`ses-guarded-${idx}`] = role + } + + const mock = createMockCtx(sessionAgents) + await registerSubagentAndIdleHooks(mock.ctx, tmp, { + runForSession: async () => runPath, + }) + + for (const [idx, role] of guardedRoles.entries()) { + const childID = `ses-guarded-${idx}` + await mock.emitToolAfter({ + tool: "subagent", + id: `call-g-${idx}`, + sessionID: "ses-sentinel", + agent: "team/sentinel", + status: "completed", + input: { agent: role, description: `Task for ${role}` }, + result: { metadata: { sessionID: childID } }, + }) + await mock.emitIdle({ sessionID: childID, background: [] }) + } + + assert.equal(mock.syntheticCalls.length, guardedRoles.length) + for (const [idx, role] of guardedRoles.entries()) { + assert.equal(mock.syntheticCalls[idx].sessionID, `ses-guarded-${idx}`, `expected nudge for ${role}`) + assert.match(mock.syntheticCalls[idx].text, /teamwork_handoff/) + } + }) + + await runCase("does not treat a subagent-tracked team/sentinel as a handoff-required child", async () => { + const runPath = join(tmp, "run-sentinel-child") + mkdirSync(runPath, { recursive: true }) + writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) + + const mock = createMockCtx({ "ses-root": "team/orchestrator", "ses-sentinel-child": "team/sentinel" }) + const { trackedSubagents } = await registerSubagentAndIdleHooks(mock.ctx, tmp, { + runForSession: async () => runPath, + }) + + await mock.emitToolAfter({ + tool: "subagent", + id: "call-sent", + sessionID: "ses-root", + agent: "team/orchestrator", + status: "completed", + input: { agent: "team/sentinel", description: "Coordinate wave" }, + result: { metadata: { sessionID: "ses-sentinel-child" } }, + }) + + for (let i = 0; i < MAX_IDLE_NUDGES + 1; i += 1) { + await mock.emitIdle({ sessionID: "ses-sentinel-child", background: [] }) + } + assert.equal(trackedSubagents.get("ses-sentinel-child").stalled, false) + assert.equal(mock.syntheticCalls.length, 0) + }) } finally { rmSync(tmp, { recursive: true, force: true }) } diff --git a/tests/runtime/spec/k-subagent-idle.test.ts b/tests/runtime/spec/k-subagent-idle.test.ts index 50e93ab..ffee21a 100644 --- a/tests/runtime/spec/k-subagent-idle.test.ts +++ b/tests/runtime/spec/k-subagent-idle.test.ts @@ -95,3 +95,41 @@ test("K1 subagent hooks + experimental.idle guard inside OpenCode 2.4.4 runtime" expect(await syntheticTexts(loaded, buildSession.id)).toHaveLength(0) }) }) + +test("K2 team/scout is exempt from the experimental.idle handoff guard inside OpenCode 2.4.4 runtime", async () => { + await withHost("k2-scout-idle", async ({ project, loaded, root }) => { + const tools = await openLocationTools(loaded, project.root) + const runId = "20261204-000002-k2" + await planRun(loaded, root, { + sessionId: runId, + topology: "small-focused", + request: "Survey codebase", + tasks: [{ id: "t1", agent: "team/worker", dependsOn: [], maxRounds: 2 }], + }) + const sentinelID = root.id + + const subRes = await runtimeExecute( + tools, + "subagent", + { + agent: "team/scout", + description: "Survey module boundaries", + prompt: `Teamwork run ${runId}. Survey the repository and write scout-report.md.`, + }, + { sessionID: sentinelID, agent: "team/sentinel", id: "call_subagent_k2" }, + ) + const scoutID = subRes?.metadata?.sessionID + expect(typeof scoutID).toBe("string") + expect(scoutID.length).toBeGreaterThan(0) + + // Scout goes idle repeatedly without teamwork_handoff -> 0 nudges. + await triggerIdle(loaded, project.root, scoutID, []) + await triggerIdle(loaded, project.root, scoutID, []) + await triggerIdle(loaded, project.root, scoutID, []) + expect(await syntheticTexts(loaded, scoutID)).toHaveLength(0) + + // Sentinel going idle afterward receives 0 stalled-child nudges. + await triggerIdle(loaded, project.root, sentinelID, []) + expect(await syntheticTexts(loaded, sentinelID)).toHaveLength(0) + }) +}) From 039d1e49bfc7b8a2c6c0163a5f7bfbea9a0dfb8e Mon Sep 17 00:00:00 2001 From: John Smith Date: Fri, 4 Dec 2026 12:08:20 -0500 Subject: [PATCH 2/2] fix: update runtime-l1 expected pass count to 121 and address PR #74 review/duplication Signed-off-by: John Smith --- .github/workflows/ci.yml | 6 +- scripts/test-engine.mjs | 12 +++- scripts/test-subagent-hooks.mjs | 97 ++++++++++++++++----------------- 3 files changed, 62 insertions(+), 53 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f6139f..2f67b90 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,7 @@ jobs: exit 1 fi echo "OPENCODE_BIN=$bin" >> "$GITHUB_ENV" - echo "$(dirname "$bin")" >> "$GITHUB_PATH" + dirname "$bin" >> "$GITHUB_PATH" version="$("$bin" --version | head -n 1)" echo "opencode --version: $version" case "$version" in @@ -82,7 +82,7 @@ jobs: skip="$(grep -E '^[[:space:]]+[0-9]+ skip$' "$log" | tail -n 1 | awk '{print $1}')" fail="$(grep -E '^[[:space:]]+[0-9]+ fail$' "$log" | tail -n 1 | awk '{print $1}')" echo "runtime summary: pass=${pass:-?} skip=${skip:-?} fail=${fail:-?}" - test "$pass" = "120" || { echo "::error::expected 120 passing runtime specs, got ${pass:-none}"; exit 1; } + test "$pass" = "121" || { echo "::error::expected 121 passing runtime specs, got ${pass:-none}"; exit 1; } test "$skip" = "1" || { echo "::error::expected exactly 1 skip (L4 live), got ${skip:-none}"; exit 1; } test "$fail" = "0" || { echo "::error::runtime specs failed"; exit 1; } if grep -q '2 skip' "$log"; then @@ -200,7 +200,7 @@ jobs: const miss = need.filter((n) => !paths.includes(n)); const pkg = JSON.parse(fs.readFileSync("package.json", "utf8")); const deps = Object.keys(pkg.dependencies ?? {}); - console.log(`packed files: ${paths.length}`); + console.log("packed files: " + paths.length); if (bad.length) console.error("forbidden docs/re or tests paths:\n" + bad.join("\n")); if (miss.length) console.error("missing required paths:\n" + miss.join("\n")); if (deps.length) console.error("root dependencies must stay empty:\n" + deps.join("\n")); diff --git a/scripts/test-engine.mjs b/scripts/test-engine.mjs index 3088eec..861859b 100644 --- a/scripts/test-engine.mjs +++ b/scripts/test-engine.mjs @@ -5979,8 +5979,11 @@ try { assert(!/[\u0085\u2028\u2029]/.test(cleanRep) && !cleanRep.includes("\x1b"), "Control chars must be stripped from DOCUMENT_REVIEW_REPORT.md") // PR #72 remediation: resolveAndReadDocument must return strict ok: false on combo and fd-open errors - const comboRefusal = await resolveAndReadDocument(docRoot, { path: "doc.md", url: "https://example.com" }) + const existingDoc = join(docRoot, "existing-doc.md") + writeFileSync(existingDoc, "# Existing\n\nBody.\n") + const comboRefusal = await resolveAndReadDocument(docRoot, { path: "existing-doc.md", url: "https://example.com" }) assert.strictEqual(comboRefusal.ok, false, "source-combo refusal must set ok: false") + assert(comboRefusal.error.includes("cannot be combined"), `expected combo error, got: ${comboRefusal.error}`) const missingRefusal = await resolveAndReadDocument(docRoot, { path: "nonexistent-doc.md" }) assert.strictEqual(missingRefusal.ok, false, "openBoundedDocumentFd refusal must set ok: false") @@ -10200,6 +10203,13 @@ process.stdout.write(JSON.stringify({ receipt: "fixture-receipt:" + request.runI assert(!authRefused(res), `team/verifier must be able to update the lifecycle: ${res.content}`) res = await call("task_update", { sessionId: runId, taskId: "A1", status: "constructor" }, worker) assert(res.content.startsWith('Error: Invalid status "constructor"'), `prototype key status must be refused without leakage: ${res.content}`) + // Also verify canonicalTaskStatus does not resolve an existing stored "constructor" status via Object.prototype + const authzStatePath = join(authzRoot, ".opencode", "teamwork", runId, "state.json") + const authzState = JSON.parse(readFileSync(authzStatePath, "utf8")) + authzState.tasks.A1.status = "constructor" + writeFileSync(authzStatePath, JSON.stringify(authzState, null, 2)) + res = await call("task_update", { sessionId: runId, taskId: "A1", status: "blocked" }, worker) + assert(!authRefused(res) && !res.content.startsWith("Error:"), `stored "constructor" status must fall back to pending and allow transition to blocked: ${res.content}`) // security_audit: only a descendant team/security-auditor. res = await call("security_audit", { sessionId: runId, status: "PASS", findings: [] }, worker) diff --git a/scripts/test-subagent-hooks.mjs b/scripts/test-subagent-hooks.mjs index 26b29a1..c7d91f1 100644 --- a/scripts/test-subagent-hooks.mjs +++ b/scripts/test-subagent-hooks.mjs @@ -307,11 +307,24 @@ try { assert.equal(mock.syntheticCalls.length, 1 + MAX_IDLE_NUDGES) }) - await runCase("does not nudge team/scout or other non-handoff roles on idle and does not mark them stalled", async () => { - const runPath = join(tmp, "run-scout") + async function setupRunWithRoles(runName, parentRole, roles, prefix) { + const runPath = join(tmp, runName) mkdirSync(runPath, { recursive: true }) writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) + const sessionAgents = { "ses-root": parentRole } + const children = roles.map((role, idx) => { + const childID = `${prefix}-${idx}` + sessionAgents[childID] = role + return { role, childID } + }) + const mock = createMockCtx(sessionAgents) + const { trackedSubagents } = await registerSubagentAndIdleHooks(mock.ctx, tmp, { + runForSession: async () => runPath, + }) + return { mock, trackedSubagents, children } + } + await runCase("does not nudge team/scout or other non-handoff roles on idle and does not mark them stalled", async () => { const nonHandoffRoles = [ "team/scout", "team/crafter", @@ -319,35 +332,30 @@ try { "team/proposer", "team/referee", ] - const sessionAgents = { "ses-sentinel": "team/sentinel" } - for (const [idx, role] of nonHandoffRoles.entries()) { - sessionAgents[`ses-nonhandoff-${idx}`] = role - } - - const mock = createMockCtx(sessionAgents) - const { trackedSubagents } = await registerSubagentAndIdleHooks(mock.ctx, tmp, { - runForSession: async () => runPath, - }) + const { mock, trackedSubagents, children } = await setupRunWithRoles( + "run-scout", + "team/sentinel", + nonHandoffRoles, + "ses-nonhandoff", + ) - for (const [idx, role] of nonHandoffRoles.entries()) { - const childID = `ses-nonhandoff-${idx}` + for (const { role, childID } of children) { await mock.emitToolBefore({ tool: "subagent", - id: `call-nh-${idx}`, - sessionID: "ses-sentinel", + id: `call-${childID}`, + sessionID: "ses-root", agent: "team/sentinel", input: { agent: role, description: `Survey (${role})`, prompt: "Inspect workspace" }, }) await mock.emitToolAfter({ tool: "subagent", - id: `call-nh-${idx}`, - sessionID: "ses-sentinel", + id: `call-${childID}`, + sessionID: "ses-root", agent: "team/sentinel", status: "completed", input: { agent: role, description: `Survey (${role})` }, result: { metadata: { sessionID: childID, status: "completed" } }, }) - for (let i = 0; i < MAX_IDLE_NUDGES + 2; i += 1) { await mock.emitIdle({ sessionID: childID, background: [] }) } @@ -355,15 +363,11 @@ try { } // Sentinel going idle after non-handoff children finish must not receive a stalled-child nudge. - await mock.emitIdle({ sessionID: "ses-sentinel", background: [] }) + await mock.emitIdle({ sessionID: "ses-root", background: [] }) assert.equal(mock.syntheticCalls.length, 0) }) await runCase("still nudges all handoff-eligible child roles (worker, verifier, falsifier, security-auditor, victory-auditor)", async () => { - const runPath = join(tmp, "run-guarded") - mkdirSync(runPath, { recursive: true }) - writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) - const guardedRoles = [ "team/worker", "team/verifier", @@ -371,22 +375,18 @@ try { "team/security-auditor", "team/victory-auditor", ] - const sessionAgents = { "ses-sentinel": "team/sentinel" } - for (const [idx, role] of guardedRoles.entries()) { - sessionAgents[`ses-guarded-${idx}`] = role - } - - const mock = createMockCtx(sessionAgents) - await registerSubagentAndIdleHooks(mock.ctx, tmp, { - runForSession: async () => runPath, - }) + const { mock, children } = await setupRunWithRoles( + "run-guarded", + "team/sentinel", + guardedRoles, + "ses-guarded", + ) - for (const [idx, role] of guardedRoles.entries()) { - const childID = `ses-guarded-${idx}` + for (const { role, childID } of children) { await mock.emitToolAfter({ tool: "subagent", - id: `call-g-${idx}`, - sessionID: "ses-sentinel", + id: `call-${childID}`, + sessionID: "ses-root", agent: "team/sentinel", status: "completed", input: { agent: role, description: `Task for ${role}` }, @@ -396,21 +396,20 @@ try { } assert.equal(mock.syntheticCalls.length, guardedRoles.length) - for (const [idx, role] of guardedRoles.entries()) { - assert.equal(mock.syntheticCalls[idx].sessionID, `ses-guarded-${idx}`, `expected nudge for ${role}`) + for (const [idx, { role, childID }] of children.entries()) { + assert.equal(mock.syntheticCalls[idx].sessionID, childID, `expected nudge for ${role}`) assert.match(mock.syntheticCalls[idx].text, /teamwork_handoff/) } }) await runCase("does not treat a subagent-tracked team/sentinel as a handoff-required child", async () => { - const runPath = join(tmp, "run-sentinel-child") - mkdirSync(runPath, { recursive: true }) - writeFileSync(join(runPath, "state.json"), JSON.stringify({ phase: "DISPATCH", tasks: {} })) - - const mock = createMockCtx({ "ses-root": "team/orchestrator", "ses-sentinel-child": "team/sentinel" }) - const { trackedSubagents } = await registerSubagentAndIdleHooks(mock.ctx, tmp, { - runForSession: async () => runPath, - }) + const { mock, trackedSubagents, children } = await setupRunWithRoles( + "run-sentinel-child", + "team/orchestrator", + ["team/sentinel"], + "ses-sentinel-child", + ) + const [{ childID }] = children await mock.emitToolAfter({ tool: "subagent", @@ -419,13 +418,13 @@ try { agent: "team/orchestrator", status: "completed", input: { agent: "team/sentinel", description: "Coordinate wave" }, - result: { metadata: { sessionID: "ses-sentinel-child" } }, + result: { metadata: { sessionID: childID } }, }) for (let i = 0; i < MAX_IDLE_NUDGES + 1; i += 1) { - await mock.emitIdle({ sessionID: "ses-sentinel-child", background: [] }) + await mock.emitIdle({ sessionID: childID, background: [] }) } - assert.equal(trackedSubagents.get("ses-sentinel-child").stalled, false) + assert.equal(trackedSubagents.get(childID).stalled, false) assert.equal(mock.syntheticCalls.length, 0) }) } finally {