Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"));
Expand Down
40 changes: 40 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion agents/team/scout.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ every downstream agent is wrong.

## Output

Write to `.opencode/teamwork/<session-id>/scout-report.md`. Structure:
Write to `.opencode/teamwork/<session-id>/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
Expand Down
6 changes: 5 additions & 1 deletion docs/ARTIFACTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<taskId>-security-auditor.md` / `handoffs/_run-security-auditor.md` |
| `team/victory-auditor`, `team/sentinel`, `team/orchestrator` | run-level only (`taskId` omitted or `_run`) | `<run>/handoffs/_run-<role>.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:

Expand Down Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
15 changes: 3 additions & 12 deletions plugins/opencode-teamwork/authorize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -121,18 +123,7 @@ const RULES: Record<string, RoleSpec> = {
},
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,
},
Expand Down
18 changes: 9 additions & 9 deletions plugins/opencode-teamwork/document-review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
13 changes: 12 additions & 1 deletion plugins/opencode-teamwork/handoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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() : ""
Expand Down
2 changes: 1 addition & 1 deletion plugins/opencode-teamwork/lemma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
2 changes: 1 addition & 1 deletion plugins/opencode-teamwork/package.json
Original file line number Diff line number Diff line change
@@ -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).",
Expand Down
12 changes: 9 additions & 3 deletions plugins/opencode-teamwork/subagent-hooks.ts
Original file line number Diff line number Diff line change
@@ -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"

/**
Expand All @@ -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)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
}

type TrackedSubagent = {
childSessionID: string
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
18 changes: 10 additions & 8 deletions plugins/opencode-teamwork/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -750,15 +750,16 @@ function normalizeTournamentTask(t: any): {
}

/** Canonical task statuses for legacy short aliases (`pass`/`fail`/`running`). */
const CANONICAL_STATUS_BY_SHORT: Record<string, string> = {
pass: "verified_pass",
fail: "verified_fail",
running: "worker_active",
}
const CANONICAL_STATUS_BY_SHORT = new Map<string, string>([
["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>): 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"
}

Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 ?? {}),
Expand Down
Loading
Loading