# Commodore watchdog implementation plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Ship an opt-in `armada-watchdog.js` plugin that detects when a dispatched subagent has not returned past a configured threshold (default 5 min) and nudges the orchestrator with one terse message.

**Architecture:** New opt-in plugin auto-loaded by opencode from `.opencode/plugins/armada-watchdog.js` when `armada.yaml` has `project.supervision.watchdog: true` (or `armada init --watchdog`). Mirrors the existing `armada-supervision.js` (`src/generator.js:559`) and `armada-fleet.js` (`src/generator.js:654`) plugins. In-memory state only; inherits opencode session lifecycle events and the `client.session.promptAsync` nudge primitive.

**Tech Stack:** Node >= 20, ESM, opencode plugin API, vitest-style `node --test`. No new runtime dependencies.

**Spec:** `docs/superpowers/specs/2026-08-04-commodore-watchdog-design.md`

## Global Constraints

- ESM, imports use explicit `.js` extensions. Node >= 20.
- Generated plugin source must be valid JS loadable by opencode (same shape as `renderArmadaFleetPlugin` at `src/generator.js:654`).
- No new runtime dependencies; `yaml` is the only allowed one and we don't need it here.
- The watchdog flag follows the existing `supervision.{plugin,fleet}` pattern at `src/manifest.js:163-165` — defaults to `{ plugin: false, fleet: false, watchdog: false }`. If a future user wants a per-project `timeoutMs`, they can set `project.supervision.watchdog: { enabled: true, timeoutMs: 600_000 }`; for the initial ship, the field is a boolean (mirror `plugin`/`fleet`) and the timeout is the constant `300_000` baked into the rendered plugin source. Per-project timeout is a follow-up.
- All tests use `node --test 'tests/*.test.js'` (existing convention).
- No emojis in code, comments, print statements or logging.
- Small modules; no defensive programming; no overengineering.

**Execution context:** This plan runs inside a feature lane worktree (per AGENTS.md "Feature work must run through armada"). Set up the lane with `git worktree add -b feat/commodore-watchdog sandbox/commodore-watchdog` from the repo root, then `cd sandbox/commodore-watchdog` and execute from there.

---

## File structure

**Created:**
- `tests/watchdog.test.js` — unit tests for the rendered plugin (event handling, threshold, recursion guard, completion clearing).

**Modified (production):**
- `src/manifest.js` — accept `project.supervision.watchdog` (boolean); default false. (Lines 122-130 + 178-180.)
- `src/generator.js` — add `renderArmadaWatchdogPlugin()` (sibling of `renderArmadaFleetPlugin` at line 654). Exports a new public function.
- `src/scaffold.js` — write `.opencode/plugins/armada-watchdog.js` when `manifest.project.supervision.watchdog === true` (sibling of lines 357-363 and 423-424).
- `src/cli.js` — accept `--watchdog` flag, set `manifest.project.supervision.watchdog = true`; add to help text (sibling of lines 297-303, 54-55).
- `src/doctor.js` — add `watchdog plugin` check (sibling of lines 119-136).
- `AGENTS.md` — one paragraph under the opt-in supervision section (around line 108).
- `TODO.md` — one line under the watchdog heading if present, or near the supervision section.

**Modified (tests):**
- `tests/manifest.test.js` — three new tests (parse with `watchdog: true` alongside `plugin: false`; reject non-boolean; default to false when missing).
- `tests/generator.test.js` — one new test for `renderArmadaWatchdogPlugin` (valid JS, exports `ArmadaWatchdog`, contains all four event handlers, embeds `300_000`).
- `tests/scaffold.test.js` — two new tests (written when flag set; removed on uninstall).
- `tests/cli.test.js` — one new test for `--watchdog` flag → manifest field.
- `tests/doctor.test.js` — one new test for the watchdog check (only when enabled, missing-file reported, present-file reported).

**Phases 1 and 2 are independent and write disjoint files (production code vs. the new test file).** Phase 3 depends on Phase 1 (it adds a CLI flag that calls into the same generator + manifest code).

---

## Phase 1: Production code

### Task 1.1: Extend manifest schema for `project.supervision.watchdog`

**Files:**
- Modify: `src/manifest.js:122-130` (add watchdog field validation).
- Modify: `src/manifest.js:178-180` (extend the default object in the returned manifest).
- Test: `tests/manifest.test.js` (add three tests after line 312).

**Interfaces:**
- Consumes: `raw.project.supervision` from YAML.
- Produces: `parsed.project.supervision.watchdog` (boolean, default `false`).

- [ ] **Step 1: Write failing test** in `tests/manifest.test.js` (after the "defaults both to false" test at line 300):

```js
// -- Phase 5: supervision.watchdog --
test("parses supervision.watchdog: true alongside plugin: false", () => {
  const yaml = [
    "project:",
    "  name: x",
    "  supervision:",
    "    plugin: false",
    "    watchdog: true",
    "team:",
    "  - role: orchestrator",
    "    model: opencode-go/hy3",
    "    permissions:",
    "      edit:",
    "        \"*\": deny",
    "      bash:",
    "        \"*\": deny",
    "      webfetch: deny",
    "  - role: backend-dev",
    "    model: opencode/deepseek-v4-flash-free",
    "    permissions:",
    "      edit:",
    "        \"*\": allow",
    "      bash:",
    "        \"*\": allow",
    "      webfetch: allow",
  ].join("\n")
  const parsed = parseManifestYaml(yaml)
  assert.strictEqual(parsed.project.supervision.plugin, false)
  assert.strictEqual(parsed.project.supervision.watchdog, true)
})

test("rejects supervision.watchdog non-boolean", () => {
  const yaml = [
    "project:",
    "  name: x",
    "  supervision:",
    "    watchdog: \"yes\"",
    "team:",
    "  - role: orchestrator",
    "    model: opencode-go/hy3",
    "    permissions:",
    "      edit:",
    "        \"*\": deny",
    "      bash:",
    "        \"*\": deny",
    "      webfetch: deny",
    "  - role: backend-dev",
    "    model: opencode/deepseek-v4-flash-free",
    "    permissions:",
    "      edit:",
    "        \"*\": allow",
    "      bash:",
    "        \"*\": allow",
    "      webfetch: allow",
  ].join("\n")
  assert.throws(() => parseManifestYaml(yaml), /supervision\.watchdog.*boolean/)
})

test("parses missing supervision.watchdog defaults to false", () => {
  const yaml = [
    "project:",
    "  name: x",
    "  supervision:",
    "    plugin: true",
    "team:",
    "  - role: orchestrator",
    "    model: opencode-go/hy3",
    "    permissions:",
    "      edit:",
    "        \"*\": deny",
    "      bash:",
    "        \"*\": deny",
    "      webfetch: deny",
    "  - role: backend-dev",
    "    model: opencode/deepseek-v4-flash-free",
    "    permissions:",
    "      edit:",
    "        \"*\": allow",
    "      bash:",
    "        \"*\": allow",
    "      webfetch: allow",
  ].join("\n")
  const parsed = parseManifestYaml(yaml)
  assert.strictEqual(parsed.project.supervision.watchdog, false)
})
```

- [ ] **Step 2: Run tests; expect them to fail** with "supervision.watchdog" or "undefined" errors. Run: `node --test tests/manifest.test.js 2>&1 | tail -20`. Expect 3 failures.

- [ ] **Step 3: Extend manifest schema validation** in `src/manifest.js`:

After line 129 (the existing `supervision.fleet` check), add:

```js
  if (p.supervision?.watchdog !== undefined && typeof p.supervision.watchdog !== "boolean") {
    throw new Error("armada.yaml: schema violation: project.supervision.watchdog must be a boolean")
  }
```

- [ ] **Step 4: Extend the default supervision object** at line 178-180:

Change:

```js
      supervision: {
        plugin: p.supervision?.plugin ?? false,
        fleet: p.supervision?.fleet ?? false,
      },
```

to:

```js
      supervision: {
        plugin: p.supervision?.plugin ?? false,
        fleet: p.supervision?.fleet ?? false,
        watchdog: p.supervision?.watchdog ?? false,
      },
```

- [ ] **Step 5: Re-run tests; expect 3 new tests to pass.** Run: `node --test tests/manifest.test.js 2>&1 | tail -5`. Expect green.

- [ ] **Step 6: Run full suite; expect green.** Run: `node --test 'tests/*.test.js' 2>&1 | tail -10`. Existing tests should still pass; the `presets/*.yaml` round-trip tests in `tests/preset.test.js` should pick up the new field automatically.

- [ ] **Step 7: Commit.** `git add src/manifest.js tests/manifest.test.js && git commit -m "feat(manifest): support project.supervision.watchdog boolean"`

### Task 1.2: Add `renderArmadaWatchdogPlugin()` to `src/generator.js`

**Files:**
- Modify: `src/generator.js` — add a new exported function after `renderArmadaFleetPlugin()` (which ends at line 736). Also update the manifest round-trip test at line 289-299 to include the new field.
- Test: `tests/generator.test.js` — add tests after line 295 (the existing `supervision.plugin round-trips` test).

**Interfaces:**
- Produces: `renderArmadaWatchdogPlugin()` → string. The string is a complete opencode plugin module that exports `ArmadaWatchdog`. Bakes in `TIMEOUT_MS = 300_000`.

- [ ] **Step 1: Write failing test** in `tests/generator.test.js` (add an import and a new test block after line 295):

Update the existing import at line 8 to include the new function:

```js
import { deepMerge, buildTeam, renderAgentFile, renderOpenCodeJson, renderAgentsMd, renderRequirementsMd, renderManifestYaml, renderArmadaSupervisionPlugin, renderArmadaFleetPlugin, renderArmadaWatchdogPlugin } from "../src/generator.js"
```

After the existing "supervision.plugin round-trips" test (around line 299), add:

```js
test("supervision.watchdog round-trips through manifest", () => {
  const m = { project: { name: "x", supervision: { watchdog: true } } }
  const yaml = renderManifestYaml(m, buildTeam({}))
  assert.match(yaml, /supervision:\n    watchdog: true/)
  const reparsed = parseManifestYaml(yaml)
  assert.strictEqual(reparsed.project.supervision.watchdog, true)

  const dflt = renderManifestYaml({ project: { name: "x" } }, buildTeam({}))
  assert.match(dflt, /watchdog: false/)
})

test("renderArmadaWatchdogPlugin emits valid JS with watchdog handlers", async () => {
  const src = renderArmadaWatchdogPlugin()
  // Should be importable as JS without throwing
  const { writeFile, unlink } = await import("node:fs/promises")
  const { tmpdir } = await import("node:os")
  const { join } = await import("node:path")
  const dir = tmpdir()
  const file = join(dir, `armada-watchdog-${Date.now()}.mjs`)
  await writeFile(file, src, "utf8")
  try {
    const mod = await import(file)
    assert.strictEqual(typeof mod.ArmadaWatchdog, "function", "exports ArmadaWatchdog")
  } finally {
    await unlink(file).catch(() => {})
  }
})

test("renderArmadaWatchdogPlugin contains four event handlers and embeds 300_000", () => {
  const src = renderArmadaWatchdogPlugin()
  assert.match(src, /session\.created/, "handles session.created")
  assert.match(src, /session\.completed/, "handles session.completed")
  assert.match(src, /session\.closed/, "handles session.closed")
  assert.match(src, /session\.deleted/, "handles session.deleted")
  assert.match(src, /session\.idle/, "handles session.idle")
  assert.match(src, /300_000/, "bakes in 5-min default threshold")
  assert.match(src, /client\.session\.promptAsync/, "uses promptAsync to nudge")
  assert.match(src, /skipNextIdle|nudgedSessions/, "has recursion guard")
})

test("renderArmadaWatchdogPlugin is deterministic for same input", () => {
  const a = renderArmadaWatchdogPlugin()
  const b = renderArmadaWatchdogPlugin()
  assert.strictEqual(a, b)
})
```

You'll also need to add the import for `parseManifestYaml` to the test file if not present (check the existing imports; if it imports `renderManifestYaml` it likely also imports `parseManifestYaml` — verify and add if missing).

- [ ] **Step 2: Run the new tests; expect 3 of 4 to fail** (the round-trip test will fail first; the render tests will fail because the function does not exist). Run: `node --test tests/generator.test.js 2>&1 | tail -20`.

- [ ] **Step 3: Implement `renderArmadaWatchdogPlugin()`** in `src/generator.js`, immediately after `renderArmadaFleetPlugin` (after line 736):

```js
// Build the opt-in `.opencode/plugins/armada-watchdog.js` subagent watchdog plugin.
// Single file, auto-loaded by opencode from the project plugin directory (no
// install). Handlers:
//   - session.created   -> identify the orchestrator session (first event whose
//                          title matches the lane's tmux session name); record
//                          any child session under its parent's tracking map
//                          with a startedAt timestamp.
//   - session.completed -> drop the child from the tracking map.
//   - session.closed    -> drop the child from the tracking map.
//   - session.deleted   -> drop the child from the tracking map.
//   - session.idle      -> if a tracked child has been waiting longer than
//                          TIMEOUT_MS and no completion event has fired, inject
//                          a one-line nudge into the orchestrator's session.
//
// TIMEOUT_MS is the dead-subagent threshold (default 5 min). The recursion
// guard (skipNextIdle + nudgedSessions) mirrors the supervision plugin so
// the nudge itself does not loop. State is in-memory only.
export function renderArmadaWatchdogPlugin() {
  return `// opencode-armada watchdog plugin (opt-in). Generated by armada init
// --watchdog (or armada.yaml project.supervision.watchdog: true).
// Auto-loaded by opencode from .opencode/plugins/ — no install required.

const TIMEOUT_MS = 300_000

// In-memory tracking. Map<parentSessionId, Map<childSessionId, startedAt>>
const tracking = new Map()

// Recursion guard (mirrors armada-supervision.js). skipNextIdle prevents
// the nudge we just injected from re-triggering the idle handler.
// nudgedSessions ensures we only nudge a given orchestrator session once
// per outstanding child batch.
let skipNextIdle = false
const nudgedParents = new Set()

// First session.created whose title matches the lane tmux session name is
// treated as the orchestrator. We capture its id once and reuse it.
let orchestratorId = null
let orchestratorTitle = null

function getTmuxSessionName() {
  // TMUX env var is "<socket>,<pid>,<session>" — last comma-separated field.
  const t = process.env.TMUX ?? ""
  const parts = t.split(",")
  return parts[parts.length - 1] || null
}

function isOrchestratorEvent(props) {
  if (!orchestratorId) {
    const title = props?.info?.title ?? props?.sessionID ?? null
    const tmux = getTmuxSessionName()
    if (title && tmux && title === tmux) {
      orchestratorId = props.sessionID ?? null
      orchestratorTitle = title
      return true
    }
    return false
  }
  return (props?.sessionID ?? null) === orchestratorId
}

function getOrCreate(parentId) {
  let m = tracking.get(parentId)
  if (!m) { m = new Map(); tracking.set(parentId, m) }
  return m
}

export const ArmadaWatchdog = async ({ client }) => {
  return {
    event: async ({ event }) => {
      const type = event.type
      const props = event.properties ?? {}
      const sessionID = props.sessionID ?? null

      if (type === "session.created") {
        if (orchestratorId === null) {
          // Try to claim the orchestrator role for this session.
          isOrchestratorEvent(props)
        }
        if (sessionID && sessionID !== orchestratorId) {
          // Track as a potential child. We don't have a confirmed parent
          // link in the event payload, so we conservatively treat any
          // non-orchestrator session as a child of the orchestrator.
          const m = getOrCreate(orchestratorId ?? "_unassigned_")
          if (!m.has(sessionID)) m.set(sessionID, Date.now())
        }
        return
      }

      if (type === "session.completed" || type === "session.closed" || type === "session.deleted") {
        if (sessionID) {
          for (const m of tracking.values()) m.delete(sessionID)
        }
        return
      }

      if (type === "session.idle") {
        if (skipNextIdle) { skipNextIdle = false; return }
        if (!isOrchestratorEvent(props)) return
        if (!orchestratorId) return

        const children = tracking.get(orchestratorId)
        if (!children || children.size === 0) return

        const now = Date.now()
        const overdue = []
        for (const [id, startedAt] of children) {
          if (now - startedAt > TIMEOUT_MS) overdue.push(id)
        }
        if (overdue.length === 0) return

        const batchKey = orchestratorId + ":" + overdue.slice().sort().join(",")
        if (nudgedParents.has(batchKey)) return
        nudgedParents.add(batchKey)

        try {
          await client.session.promptAsync({
            path: { id: orchestratorId },
            body: { parts: [{ type: "text", text: \`armada-watchdog: \${overdue.length} dispatched subagent(s) past \${TIMEOUT_MS}ms without return: \${overdue.join(", ")}. Likely dead. Re-dispatch or abort.\` }] },
          })
          skipNextIdle = true
        } catch (err) {
          await client.app.log({ body: { service: "armada-watchdog", level: "warn", message: String(err?.message ?? err) } })
        }
      }
    },
  }
}
`
}
```

- [ ] **Step 4: Re-run tests; expect all four new tests to pass.** Run: `node --test tests/generator.test.js 2>&1 | tail -5`.

- [ ] **Step 5: Run full suite; expect green.** Run: `node --test 'tests/*.test.js' 2>&1 | tail -5`. The round-trip test added in step 1 will start passing only after `renderManifestYaml` learns to emit the new field — see step 6.

- [ ] **Step 6: Update `renderManifestYaml` to include the watchdog field** in `src/generator.js`. At line 838-839, change:

```js
    plugin: ${manifest.project.supervision?.plugin ?? false}
    fleet: ${manifest.project.supervision?.fleet ?? false}
```

to:

```js
    plugin: ${manifest.project.supervision?.plugin ?? false}
    fleet: ${manifest.project.supervision?.fleet ?? false}
    watchdog: ${manifest.project.supervision?.watchdog ?? false}
```

Re-run: `node --test tests/generator.test.js tests/preset.test.js 2>&1 | tail -5`. Expect green.

- [ ] **Step 7: Commit.** `git add src/generator.js tests/generator.test.js && git commit -m "feat(generator): add renderArmadaWatchdogPlugin()"`

### Task 1.3: Extend `src/scaffold.js` to write the plugin when enabled

**Files:**
- Modify: `src/scaffold.js:357-363` (add a third `if` block for the watchdog).
- Modify: `src/scaffold.js:423-424` (extend the uninstall `removeFile` block).
- Test: `tests/scaffold.test.js` (add two tests after line 449).

- [ ] **Step 1: Write failing test** in `tests/scaffold.test.js` (after the "fleet plugin written" test at line 449). Mirror the structure of the existing `fleet plugin written when supervision.fleet is true` test (lines 430-446):

```js
test("watchdog plugin written when supervision.watchdog is true", () => {
  const dir = makeEmptyDir()
  // Default state: no watchdog plugin written
  const before = buildScaffold({ project: { name: "x" } })
  applyScaffold(before, dir)
  assert.ok(!existsSync(join(dir, ".opencode/plugins/armada-watchdog.js")), "no plugin by default")

  // When supervision.watchdog is true, the file appears with rendered content
  const manifest = buildScaffold({ project: { name: "x", supervision: { watchdog: true } } })
  applyScaffold(manifest, dir)
  const plugin = join(dir, ".opencode/plugins/armada-watchdog.js")
  assert.ok(existsSync(plugin), "watchdog plugin written")
  const src = readFileSync(plugin, "utf8")
  assert.strictEqual(src, renderArmadaWatchdogPlugin(), "content matches generator output")
})
```

For uninstall, mirror the supervision-plugin test (lines 205-222):

```js
test("watchdog plugin removed on uninstall when supervision.watchdog is true", () => {
  const dir = makeEmptyDir()
  const manifest = buildScaffold({ project: { name: "x", supervision: { watchdog: true } } })
  applyScaffold(manifest, dir)
  assert.ok(existsSync(join(dir, ".opencode/plugins/armada-watchdog.js")))
  const removed = runUninstall({ project: { supervision: { watchdog: true } } }, dir)
  assert.ok(removed.includes(".opencode/plugins/armada-watchdog.js"))
})
```

(Adapt the helper names — `makeEmptyDir`, `buildScaffold`, `applyScaffold`, `runUninstall` — to whatever the existing tests in this file already use; they're the established helpers in the file.)

- [ ] **Step 2: Run the new tests; expect them to fail.** Run: `node --test tests/scaffold.test.js 2>&1 | tail -10`.

- [ ] **Step 3: Extend scaffold.js to write the plugin.** After the existing `supervision.fleet` block at line 363, add:

```js
  // 7c. Opt-in thin watchdog plugin.
  if (manifest.project.supervision?.watchdog) {
    write(".opencode/plugins/armada-watchdog.js", renderArmadaWatchdogPlugin())
  }
```

- [ ] **Step 4: Extend the uninstall path.** At line 423-424, add the watchdog file to the removal list (inside the same `if (manifest.project.supervision?.plugin || manifest.project.supervision?.fleet)` block, OR as a separate `if` for symmetry):

```js
  if (manifest.project.supervision?.watchdog) {
    removeFile(".opencode/plugins/armada-watchdog.js")
  }
```

- [ ] **Step 5: Re-run scaffold tests; expect green.** Run: `node --test tests/scaffold.test.js 2>&1 | tail -5`.

- [ ] **Step 6: Commit.** `git add src/scaffold.js tests/scaffold.test.js && git commit -m "feat(scaffold): write armada-watchdog.js when supervision.watchdog enabled"`

### Task 1.4: Add `--watchdog` flag to `src/cli.js`

**Files:**
- Modify: `src/cli.js:54-55` (add to help text).
- Modify: `src/cli.js:297-303` (add `--watchdog` flag handling).
- Test: `tests/cli.test.js` (add a test for the flag).

- [ ] **Step 1: Add help text line** in `src/cli.js` (after line 55):

```js
  armada init --watchdog                    opt-in subagent watchdog plugin (.opencode/plugins/)
```

- [ ] **Step 2: Add flag handling** in `src/cli.js` (after line 303):

```js
  if (args.includes("--watchdog")) {
    manifest.project.supervision = manifest.project.supervision ?? { plugin: false, fleet: false, watchdog: false }
    manifest.project.supervision.watchdog = true
  }
```

- [ ] **Step 2b: Update the default supervision object** in `src/cli.js` at line 381. Change:

```js
      supervision: { plugin: false, fleet: false },
```

to:

```js
      supervision: { plugin: false, fleet: false, watchdog: false },
```

- [ ] **Step 3: Add CLI test** in `tests/cli.test.js`. Mirror the structure of the existing `--fleet-tracker` test (search for `fleet-tracker` in this file — it sets up a fake `armada init` and asserts the manifest output). The new test:

```js
test("armada init --watchdog sets supervision.watchdog to true", () => {
  // Use the same helpers as the --fleet-tracker test (likely a fake opencode bin
  // + runCli). Invoke `armada init --watchdog` in a temp dir. Read the
  // generated armada.yaml. Assert it contains `watchdog: true` under
  // `supervision:`.
})
```

(Adapt the helper names and assertions to the file's established pattern.)

- [ ] **Step 4: Run tests; expect green.** Run: `node --test tests/cli.test.js 2>&1 | tail -5`.

- [ ] **Step 5: Commit.** `git add src/cli.js tests/cli.test.js && git commit -m "feat(cli): armada init --watchdog"`

### Task 1.5: Add watchdog check to `src/doctor.js`

**Files:**
- Modify: `src/doctor.js:119-136` (add a third `if` block for the watchdog).
- Test: `tests/doctor.test.js` (add a test after line 105).

- [ ] **Step 1: Add doctor check** in `src/doctor.js` (after the fleet block at line 136):

```js
  if (opts.project?.supervision?.watchdog) {
    const pluginPath = join(opts.targetDir ?? ".", ".opencode/plugins/armada-watchdog.js")
    checks.push({
      name: "watchdog plugin",
      ok: existsSync(pluginPath),
      message: existsSync(pluginPath)
        ? ".opencode/plugins/armada-watchdog.js present"
        : "supervision.watchdog is true but .opencode/plugins/armada-watchdog.js missing — re-run armada init",
    })
  }
```

- [ ] **Step 2: Add doctor test** in `tests/doctor.test.js` (mirror the existing `supervision plugin check` at line 72-92 and `fleet tracker check` at line 95-108). Three assertions:

```js
test("watchdog plugin check only when enabled", async () => {
  let checks = await runDoctor({ env: envWith(binDir), project: { supervision: { watchdog: false } }, targetDir: dir })
  assert.ok(!checks.some((c) => c.name === "watchdog plugin"), "no check when disabled")

  checks = await runDoctor({ env: envWith(binDir), project: { supervision: { watchdog: true } }, targetDir: dir })
  const missing = checks.find((c) => c.name === "watchdog plugin")
  assert.ok(missing, "check present when enabled")
  assert.strictEqual(missing.ok, false, "ok=false when file missing")

  writeFileSync(join(dir, ".opencode/plugins/armada-watchdog.js"), "// plugin")
  checks = await runDoctor({ env: envWith(binDir), project: { supervision: { watchdog: true } }, targetDir: dir })
  const present = checks.find((c) => c.name === "watchdog plugin")
  assert.ok(present && present.ok === true, "ok=true when file present")
})
```

- [ ] **Step 3: Run tests; expect green.** Run: `node --test tests/doctor.test.js 2>&1 | tail -5`.

- [ ] **Step 4: Commit.** `git add src/doctor.js tests/doctor.test.js && git commit -m "feat(doctor): verify armada-watchdog.js presence when supervision.watchdog enabled"`

---

## Phase 2: Plugin unit tests

### Task 2.1: Add `tests/watchdog.test.js`

**Files:**
- Create: `tests/watchdog.test.js` (sibling of `tests/fleet-plugin.test.js`).

- [ ] **Step 1: Write the file.** Use the `renderArmadaFleetPlugin` test pattern from `tests/fleet-plugin.test.js:1-60` as a template. The new file imports `renderArmadaWatchdogPlugin` and exercises the rendered source by writing it to a temp file, importing it under a mock `client`, and firing synthetic events.

```js
import { test } from "node:test"
import assert from "node:assert/strict"
import { writeFile, unlink, mkdtemp } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { renderArmadaWatchdogPlugin } from "../src/generator.js"

// Mock opencode client that records promptAsync calls.
function makeMockClient() {
  const calls = { promptAsync: [], appLog: [] }
  return {
    calls,
    session: {
      promptAsync: async (req) => {
        calls.promptAsync.push(req)
        return { ok: true }
      },
    },
    app: {
      log: async (req) => {
        calls.appLog.push(req)
        return { ok: true }
      },
    },
  }
}

// Render the plugin, write to a unique temp file, import it.
async function loadWatchdog(client, env = {}) {
  const src = renderArmadaWatchdogPlugin()
  const dir = await mkdtemp(join(tmpdir(), "armada-watchdog-test-"))
  const file = join(dir, "armada-watchdog.mjs")
  await writeFile(file, src, "utf8")
  const savedTmux = process.env.TMUX
  process.env.TMUX = env.tmux ?? ",,"  // default empty session name
  try {
    const mod = await import(`${file}?t=${Date.now()}`)
    const watchdog = mod.ArmadaWatchdog({ client })
    return { watchdog, dir, file }
  } finally {
    // restore
    if (savedTmux === undefined) delete process.env.TMUX
    else process.env.TMUX = savedTmux
  }
}

test("watchdog: session.created for orchestrator is recognized when title matches tmux", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({
    event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } },
  })
  // No nudge should fire on session.created.
  assert.strictEqual(client.calls.promptAsync.length, 0)
})

test("watchdog: session.created for child is tracked", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({
    event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } },
  })
  await watchdog.event({
    event: { type: "session.created", properties: { sessionID: "child-1", info: { title: "subagent-1" } } },
  })
  // Idle before threshold: no nudge.
  await watchdog.event({
    event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } },
  })
  assert.strictEqual(client.calls.promptAsync.length, 0, "no nudge before threshold")
})

test("watchdog: session.idle past threshold nudges orchestrator", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-1", info: { title: "subagent-1" } } } })

  // Advance fake time: the plugin uses Date.now() internally. Override it.
  const realNow = Date.now
  const realStart = realNow()
  Date.now = () => realStart + 600_000  // 10 min later, past the 5-min threshold
  try {
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  } finally {
    Date.now = realNow
  }

  assert.strictEqual(client.calls.promptAsync.length, 1, "exactly one nudge")
  const text = client.calls.promptAsync[0].body.parts[0].text
  assert.match(text, /armada-watchdog:/)
  assert.match(text, /child-1/)
  assert.match(text, /300_000/)
})

test("watchdog: session.completed clears the child so next idle does not nudge", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-1", info: { title: "subagent-1" } } } })
  await watchdog.event({ event: { type: "session.completed", properties: { sessionID: "child-1" } } })

  const realNow = Date.now
  const realStart = realNow()
  Date.now = () => realStart + 600_000
  try {
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  } finally {
    Date.now = realNow
  }

  assert.strictEqual(client.calls.promptAsync.length, 0, "no nudge after completion")
})

test("watchdog: session.closed and session.deleted also clear the child", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-closed", info: { title: "s" } } } })
  await watchdog.event({ event: { type: "session.closed", properties: { sessionID: "child-closed" } } })

  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-deleted", info: { title: "s" } } } })
  await watchdog.event({ event: { type: "session.deleted", properties: { sessionID: "child-deleted" } } })

  const realNow = Date.now
  const realStart = realNow()
  Date.now = () => realStart + 600_000
  try {
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  } finally {
    Date.now = realNow
  }

  assert.strictEqual(client.calls.promptAsync.length, 0)
})

test("watchdog: skipNextIdle recursion guard prevents nudge re-entry", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-1", info: { title: "s" } } } })

  const realNow = Date.now
  const realStart = realNow()
  Date.now = () => realStart + 600_000
  try {
    // First idle: nudges and sets skipNextIdle.
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
    // Second idle (caused by the nudge being processed): must NOT nudge again.
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  } finally {
    Date.now = realNow
  }

  assert.strictEqual(client.calls.promptAsync.length, 1, "exactly one nudge, recursion guarded")
})

test("watchdog: non-orchestrator session.idle is ignored", async () => {
  const client = makeMockClient()
  const { watchdog } = await loadWatchdog(client, { tmux: ",,orch-lane" })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "orch-1", info: { title: "orch-lane" } } } })
  await watchdog.event({ event: { type: "session.created", properties: { sessionID: "child-1", info: { title: "s" } } } })

  const realNow = Date.now
  const realStart = realNow()
  Date.now = () => realStart + 600_000
  try {
    // idle on a non-orchestrator session id
    await watchdog.event({ event: { type: "session.idle", properties: { sessionID: "child-1", info: { title: "s" } } } })
  } finally {
    Date.now = realNow
  }

  assert.strictEqual(client.calls.promptAsync.length, 0, "non-orchestrator idle ignored")
})
```

- [ ] **Step 2: Run the test file; expect all seven tests to pass.** Run: `node --test tests/watchdog.test.js 2>&1 | tail -20`. If a test fails because the plugin's date-override trick doesn't take effect (the plugin was rendered with `Date.now` referenced lexically), the test will still work because `Date.now = ...` is a global mutation; the plugin reads `Date.now()` at call time, so the override applies. (If the plugin is rendered with `const TIMEOUT_MS = 300_000` and `Date.now()` inline — both are runtime-resolved — the override is fine.)

- [ ] **Step 3: Run full suite; expect green.** Run: `node --test 'tests/*.test.js' 2>&1 | tail -5`.

- [ ] **Step 4: Commit.** `git add tests/watchdog.test.js && git commit -m "test(watchdog): cover dispatch, threshold, completion, recursion"`

---

## Phase 3: Docs + PR

### Task 3.1: Update `AGENTS.md` and `TODO.md`

**Files:**
- Modify: `AGENTS.md` — extend the bullet list under the opt-in supervision section near line 108-110. Add a new bullet:

```md
- **Opt-in supervision:** `armada init --supervision-plugin` (or `armada.yaml` `supervision.plugin: true`) emits one `.opencode/plugins/armada-supervision.js` file (session.created resume nudge, session.idle no-blind-stop, tool.execute.before shell-redirect guard). `armada init --fleet-tracker` (`supervision.fleet: true`) emits `.opencode/plugins/armada-fleet.js` (per-session heartbeat so the dashboard shows ACTIVE vs STALLED). `armada init --watchdog` (`supervision.watchdog: true`) emits `.opencode/plugins/armada-watchdog.js` which detects dispatched subagents that have not returned within 5 minutes and nudges the orchestrator. Default init stays plugin-free.
```

- Modify: `TODO.md` — find the watchdog heading (if present) or the supervision section. Add one line:

```md
- [x] **Subagent watchdog.** `armada init --watchdog` emits `.opencode/plugins/armada-watchdog.js` — thin layer over opencode's session lifecycle that nudges the orchestrator when a dispatched subagent has not returned past 5 min (default). Opt-in via `armada.yaml project.supervision.watchdog: true`.
```

- [ ] **Step 1: Apply both edits.** Use `edit` on each file (Read first, then Edit).

- [ ] **Step 2: Run the docs-grep guard tests** to ensure no terminology regressions. Run: `node --test tests/terminology-grep.test.js tests/agents-md.test.js tests/docs-no-hand-edit.test.js 2>&1 | tail -5`. Expect green.

- [ ] **Step 3: Commit.** `git add AGENTS.md TODO.md && git commit -m "docs: cover opt-in subagent watchdog plugin"`

### Task 3.2: Final verification

- [ ] **Step 1: Run the full test suite from the lane worktree.** Run: `node --test 'tests/*.test.js' 2>&1 | tail -10`. Expect green; report the pass count.

- [ ] **Step 2: Run the CLI smoke** to confirm help text + flag still work. Run: `node src/cli.js help 2>&1 | grep -- --watchdog`. Expect one line. Run: `node src/cli.js init --help 2>&1 | grep -- --watchdog`. (Adjust if `--help` isn't a subcommand — at minimum confirm the flag is listed in `node src/cli.js help`.)

- [ ] **Step 3: Run `armada doctor` against the lane directory** to confirm the new check fires (and is absent by default). Run: `node src/cli.js doctor --target .`. Expect a check named `watchdog plugin` if `armada.yaml` has `supervision.watchdog: true`; otherwise no such check.

- [ ] **Step 4: Sanity-check the generated plugin source** by rendering it and visually scanning. Run: `node -e "import('./src/generator.js').then(m => process.stdout.write(m.renderArmadaWatchdogPlugin()))" | head -30`. Confirm: header comment, `TIMEOUT_MS = 300_000`, all four event handlers, promptAsync usage, recursion guard.

- [ ] **Step 5: Commit any remaining edits** (e.g., if step 3 surfaced a fix). `git status` and `git diff` first; only stage and commit if there are real changes.

### Task 3.3: Open the PR

- [ ] **Step 1: Push the branch.** `git push -u origin feat/commodore-watchdog`.

- [ ] **Step 2: Open the PR.** `gh pr create --base master --title "feat: opt-in subagent watchdog (armada-watchdog.js)" --body "..."`. Body should reference the spec at `docs/superpowers/specs/2026-08-04-commodore-watchdog-design.md` and summarize: opt-in plugin, in-memory state, 5-min default, one nudge per overdue batch, recursion guard, zero token cost on the happy path.

- [ ] **Step 3: Report the PR URL back to the user.** Do not merge locally; wait for the user to review and merge.

---

## Self-review

- **Spec coverage:** Problem, goal, non-goals, architecture, components, data flow, error handling, testing, documentation — all covered by the tasks above. ✅
- **Placeholder scan:** No "TBD" / "TODO" / "implement later" / "similar to Task N" placeholders. All step code is concrete. ✅
- **Type consistency:** `renderArmadaWatchdogPlugin()` is consistently referenced as a no-arg function returning a string across all tasks. `TIMEOUT_MS = 300_000` is consistently used. The mock client shape (`session.promptAsync`, `app.log`) matches what the plugin source actually calls. ✅
- **Independent phases:** Phase 1 (production) and Phase 2 (new test file) write disjoint files. Phase 3 depends on both. ✅
