Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

54.5 KB
Raw Blame
/**
 * Tests for the agent-lifecycle concurrency guards.
 *
 * The two guard primitives that gate every spawn + completion were extracted
 * into agentGuards.js (issue #2548) precisely so these tests drive the REAL
 * code path instead of a hand-copied replica of spawnAgentForTask /
 * handleAgentCompletion:
 *
 *   - withSpawnDedupGuard — the `spawningTasks` dedup guard that
 *     `spawnAgentForTask` wraps `runAgentSpawn` in. Acquires the guard
 *     synchronously before the first await, holds it across the ENTIRE spawn
 *     body (including the runner-enqueue handoff), and releases it in a
 *     finally. That is what closes the late-delete race where a concurrent
 *     `task:ready` re-emit spawned a SECOND agent for the same task id.
 *   - withMapEntryCleanup — the `runnerAgents` cleanup that
 *     `handleAgentCompletion` wraps its body in, so a throw from any
 *     completion step (completeAgent / updateTask / processAgentCompletion /
 *     finalizeAgent) can't strand the in-memory agent record.
 *
 * A thin set of source-level assertions at the bottom pins the remaining
 * non-negotiable orderings that live inside the ~470-LOC orchestrators and
 * have no behavioral seam — the handedOff pre-spawn/post-handoff split, the
 * federation claim/register ordering (#1563), the #989 app-review marker
 * release, the runner env merge (#2243) — plus the wiring invariant that the
 * orchestrators actually delegate to the extracted guards.
 */

import { describe, it, expect, beforeEach } from 'vitest';
import { readFileSync, readdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { spawningTasks, runnerAgents } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
import { PROVIDER_CONFIG_BLOCKED_CATEGORY, PAUSED_BLOCKED_CATEGORIES, USER_DECISION_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';

const __dirname = dirname(fileURLToPath(import.meta.url));
const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');
const AGENT_SPAWN_PREPARATION_SRC = readFileSync(join(__dirname, 'agentSpawnPreparation.js'), 'utf-8');
const AGENT_SPAWN_DISPATCH_SRC = readFileSync(join(__dirname, 'agentSpawnDispatch.js'), 'utf-8');
const AGENT_SPAWN_OWNER_SRC = `${AGENT_SPAWN_PREPARATION_SRC}\n${AGENT_SPAWN_DISPATCH_SRC}`;
// finalizeAgent + stampLiExecutionVerdict moved to their own module (issue #2837)
// so both spawners can import them without cycling back through the lifecycle
// orchestrator. The source-level assertions below follow them there.
const AGENT_FINALIZATION_SRC = readFileSync(join(__dirname, 'agentFinalization.js'), 'utf-8');
// The four public-review spawn preconditions moved out of the orchestrator
// (#6617) once their block-and-bail epilogues collapsed into one helper. The
// wiring assertions below follow them there.
const PUBLIC_REVIEW_SPAWN_GATE_SRC = readFileSync(join(__dirname, '../lib/publicReviewSpawnGate.js'), 'utf-8');
// The registerAgent projection — agent.metadata is a hand-picked map of
// task.metadata — moved out of the orchestrator with the same change (#6617).
// The projection-CONTENT guards below follow it; the ORDERING guards (claim
// before register, identity before register) stay on the orchestrator.
const AGENT_REGISTRATION_SRC = readFileSync(join(__dirname, '../lib/agentRegistrationRecord.js'), 'utf-8');

function deferred() {
  let resolve;
  const promise = new Promise((r) => { resolve = r; });
  return { promise, resolve };
}

beforeEach(() => {
  spawningTasks.clear();
  runnerAgents.clear();
});

// ─── withSpawnDedupGuard — the real spawn dedup guard ───────────────────────

describe('withSpawnDedupGuard — spawn dedup guard', () => {
  it('holds the guard for the duration of fn and releases it on success', async () => {
    const task = { id: 'task-ok' };
    let heldDuringFn = false;
    const result = await withSpawnDedupGuard(spawningTasks, task.id, async () => {
      heldDuringFn = spawningTasks.has(task.id);
      return 'agent-1';
    });
    expect(heldDuringFn).toBe(true);
    expect(result).toBe('agent-1');
    expect(spawningTasks.has(task.id)).toBe(false);
  });

  it('releases the guard even when fn throws (no leak on setup failure)', async () => {
    // The pre-widening bug: a throw from buildAgentPrompt / writeFile /
    // createAgentRun / registerAgent leaked spawningTasks forever, permanently
    // blocking every future spawn of that task id.
    await expect(
      withSpawnDedupGuard(spawningTasks, 'task-throw', async () => {
        throw new Error('buildAgentPrompt failed (ENOSPC)');
      })
    ).rejects.toThrow('buildAgentPrompt failed');
    expect(spawningTasks.has('task-throw')).toBe(false);
  });

  it('releases the guard on an early return null (detected-error path)', async () => {
    // Every detected-error early return inside runAgentSpawn (no provider,
    // claim yielded, max-spawns, lane-acquire, updateTask failure) returns null;
    // the guard must be released for each of them.
    const result = await withSpawnDedupGuard(spawningTasks, 'task-null', async () => null);
    expect(result).toBeNull();
    expect(spawningTasks.has('task-null')).toBe(false);
  });

  it('returns SPAWN_DEDUP_SKIP and does not touch the set when already held', async () => {
    spawningTasks.add('task-inflight'); // an earlier spawn is mid-flight
    let fnRan = false;
    const result = await withSpawnDedupGuard(spawningTasks, 'task-inflight', async () => {
      fnRan = true;
      return 'agent-2';
    });
    expect(result).toBe(SPAWN_DEDUP_SKIP);
    expect(fnRan).toBe(false); // the guarded body never ran
    expect(spawningTasks.has('task-inflight')).toBe(true); // pre-existing guard untouched
  });

  it('acquires the guard synchronously before the first await inside fn', async () => {
    // A `task:ready` re-emit can land while the first spawn is suspended at an
    // await (ensureInstanceId / getTaskById). The guard must be taken
    // synchronously — before fn yields — or the racer slips past the has()
    // check. Prove it: a second call issued with NO await between the two must
    // already see the guard held.
    const gate = deferred();
    const first = withSpawnDedupGuard(spawningTasks, 'task-sync', async () => {
      await gate.promise;
      return 'agent-first';
    });
    const second = await withSpawnDedupGuard(spawningTasks, 'task-sync', async () => 'agent-second');
    expect(second).toBe(SPAWN_DEDUP_SKIP);
    gate.resolve();
    expect(await first).toBe('agent-first');
  });
});

// ─── withUpdateInProgressGuard — the self-update spawn hold (issue #4124) ───

describe('withUpdateInProgressGuard — self-update spawn hold', () => {
  it('runs the spawn body when no update is in progress', async () => {
    let ran = false;
    const result = await withUpdateInProgressGuard(() => false, async () => {
      ran = true;
      return 'agent-1';
    });
    expect(ran).toBe(true);
    expect(result).toBe('agent-1');
  });

  it('returns SPAWN_UPDATE_SKIP without running the body while an update is in progress', async () => {
    let ran = false;
    const result = await withUpdateInProgressGuard(() => true, async () => {
      ran = true;
      return 'agent-2';
    });
    // The whole point: no agent process is created inside the window where
    // update.sh is about to pm2-delete this server. The task record is never
    // touched, so it stays `pending` and runs after the restart.
    expect(ran).toBe(false);
    expect(result).toBe(SPAWN_UPDATE_SKIP);
  });

  it('reads the flag on EVERY call, so the hold releases when the update settles', async () => {
    let updating = true;
    const isUpdating = () => updating;
    expect(await withUpdateInProgressGuard(isUpdating, async () => 'spawned')).toBe(SPAWN_UPDATE_SKIP);
    updating = false;
    expect(await withUpdateInProgressGuard(isUpdating, async () => 'spawned')).toBe('spawned');
  });

  it('uses a sentinel distinct from the dedup skip, so the two holds stay distinguishable', () => {
    expect(SPAWN_UPDATE_SKIP).not.toBe(SPAWN_DEDUP_SKIP);
  });

  it('checks the flag OUTSIDE the dedup guard, so a held task leaves no stranded guard entry', async () => {
    // Mirrors how spawnAgentForTask composes them. If the update check sat
    // inside withSpawnDedupGuard the task id would be added and removed for a
    // spawn that never happened — harmless today, but it would also mean the
    // dedup set churned once per held dispatch during the whole update window.
    const outcome = await withUpdateInProgressGuard(() => true, () =>
      withSpawnDedupGuard(spawningTasks, 'task-held', async () => 'agent-3'));
    expect(outcome).toBe(SPAWN_UPDATE_SKIP);
    expect(spawningTasks.has('task-held')).toBe(false);
  });
});

// ─── The reported late-delete race, driven by the real guard ────────────────

describe('spawnAgentForTask dedup — late-delete race (issue #2548 / #1563)', () => {
  it('a concurrent spawn landing during the handoff window is deduped (only ONE agent)', async () => {
    // Reproduce the reported race with the REAL guard. Call A holds the guard
    // across its whole body — including the runner-enqueue handoff, modelled
    // here by an awaited gate. Call B arrives DURING that handoff window: the
    // exact boundary (after the in_progress flip, before the runner accepted
    // the agent) where the pre-fix code had already released the guard and let
    // a second agent spawn. Because withSpawnDedupGuard holds the guard until
    // A's fn settles, B is deduped instead of spawning a duplicate.
    const taskId = 'task-race';
    const spawned = [];
    const handoffGate = deferred();
    let secondCall;

    const first = withSpawnDedupGuard(spawningTasks, taskId, async () => {
      // Inject the racer mid-handoff, while the guard is (correctly) still held.
      secondCall = withSpawnDedupGuard(spawningTasks, taskId, async () => {
        spawned.push('agent-second');
        return 'agent-second';
      });
      await handoffGate.promise; // runner-enqueue completing
      spawned.push('agent-first');
      return 'agent-first';
    });

    // Drain microtasks so A reaches the injection point + B runs its dedup path.
    await new Promise((r) => setImmediate(r));
    const secondResult = await secondCall;

    handoffGate.resolve();
    const firstResult = await first;

    expect(secondResult).toBe(SPAWN_DEDUP_SKIP); // racer deduped, no second agent
    expect(spawned).toEqual(['agent-first']);    // exactly ONE agent spawned
    expect(firstResult).toBe('agent-first');
    expect(spawningTasks.has(taskId)).toBe(false); // released once A settled
  });

  it('the guard is per-attempt, not sticky — a later spawn for the same id proceeds', async () => {
    // Sanity: after A completes and releases, a subsequent spawn for the same
    // task id (e.g. a retry) must not be permanently blocked.
    const taskId = 'task-seq';
    const a = await withSpawnDedupGuard(spawningTasks, taskId, async () => 'agent-a');
    const b = await withSpawnDedupGuard(spawningTasks, taskId, async () => 'agent-b');
    expect(a).toBe('agent-a');
    expect(b).toBe('agent-b');
    expect(spawningTasks.has(taskId)).toBe(false);
  });
});

// ─── withMapEntryCleanup — the real runnerAgents completion cleanup ──────────

describe('withMapEntryCleanup — runnerAgents completion cleanup', () => {
  it('runs the completion steps then deletes the map entry (happy path)', async () => {
    runnerAgents.set('agent-A', { taskId: 'task-A' });
    const steps = [];
    await withMapEntryCleanup(runnerAgents, 'agent-A', async () => {
      steps.push('completeAgent');
      steps.push('updateTask');
      steps.push('processAgentCompletion');
    });
    expect(steps).toEqual(['completeAgent', 'updateTask', 'processAgentCompletion']);
    expect(runnerAgents.has('agent-A')).toBe(false);
  });

  it('deletes the map entry even when an inner completion step throws', async () => {
    // A throw from completeAgent / updateTask / processAgentCompletion /
    // finalizeAgent must never leak the in-memory record — memory grows
    // unboundedly and a stale entry can re-trigger/misroute completion.
    runnerAgents.set('agent-B', { taskId: 'task-B' });
    await expect(
      withMapEntryCleanup(runnerAgents, 'agent-B', async () => {
        throw new Error('completeAgent failed: state save error');
      })
    ).rejects.toThrow('completeAgent failed');
    expect(runnerAgents.has('agent-B')).toBe(false);
  });

  it('propagates the inner error after cleanup (finally does not swallow it)', async () => {
    runnerAgents.set('agent-C', { taskId: 'task-C' });
    let caught;
    try {
      await withMapEntryCleanup(runnerAgents, 'agent-C', async () => {
        throw new Error('updateTask failed');
      });
    } catch (err) {
      caught = err;
    }
    expect(caught?.message).toBe('updateTask failed');
    expect(runnerAgents.has('agent-C')).toBe(false);
  });

  it('is safe when the entry was already removed (double-delete no-op)', async () => {
    // handleAgentCompletion's early-return branches (paused / unknown agent)
    // delete the entry before the guarded body; the finally delete must be a
    // harmless no-op if the key is already gone.
    const result = await withMapEntryCleanup(runnerAgents, 'agent-missing', async () => 'ok');
    expect(result).toBe('ok');
    expect(runnerAgents.has('agent-missing')).toBe(false);
  });
});

// ─── Wiring invariants: the orchestrators delegate to the guards ────────────
//
// The behavioral tests above cover the guards themselves; these two source
// checks pin that spawnAgentForTask / handleAgentCompletion actually route
// their guard/cleanup through the extracted helpers, so a refactor that
// re-inlines a hand-rolled try/finally (and re-opens the race) fails loudly.

describe('agentLifecycle — guard wiring', () => {
  it('spawnAgentForTask delegates the dedup guard to withSpawnDedupGuard(runAgentSpawn)', () => {
    const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
    expect(idx, 'spawnAgentForTask must exist').toBeGreaterThan(-1);
    const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1200);
    expect(body).toMatch(
      /withSpawnDedupGuard\(\s*spawningTasks\s*,\s*task\.id\s*,\s*\(\)\s*=>\s*runAgentSpawn\(task\)\s*\)/
    );
    // The dedup-skip sentinel is honored (returns null to the caller).
    expect(body).toMatch(/SPAWN_DEDUP_SKIP/);
  });

  // Issue #4124: `/api/update/execute` refuses to start while an agent is live,
  // but `update.sh` then runs git pull / submodule update / npm install for
  // seconds before `pm2 delete`. This is the last-line gate for a spawn landing
  // in THAT window.
  it('spawnAgentForTask wraps the spawn in withUpdateInProgressGuard(isUpdateInProgress)', () => {
    const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
    expect(idx, 'spawnAgentForTask must exist').toBeGreaterThan(-1);
    const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1200);
    expect(body).toMatch(/withUpdateInProgressGuard\(\s*isUpdateInProgress\s*,/);
    expect(body).toMatch(/SPAWN_UPDATE_SKIP/);
    // The synchronous mirror, not a re-implemented disk read.
    expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);
  });

  // The four gates themselves moved to `lib/publicReviewSpawnGate.js`, and
  // WHAT each one decides is now behavior-tested at the spawn boundary
  // (agentLifecycle.blockAndBail.test.js) rather than grepped for here. What
  // stays greppable is the wiring: that the orchestrator delegates to the gate
  // instead of growing a second copy beside it.
  it('delegates every public-review spawn precondition to the extracted gate', () => {
    expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(
      /import \{ checkPublicReviewSpawnPreconditions \} from '\.\.\/lib\/publicReviewSpawnGate\.js'/
    );
    expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(
      /const publicReviewBlock = await checkPublicReviewSpawnPreconditions\(\{[\s\S]{0,400}?validateModel: validatePublicReviewModel,/
    );
    // One bail, through the shared epilogue — not a hand-rolled block write.
    expect(AGENT_SPAWN_DISPATCH_SRC).toContain('if (publicReviewBlock) return context.blockAndBail(publicReviewBlock);');
    // A second, inline copy of any gate here is the drift this extraction
    // exists to prevent.
    expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewScanBlock\(/);
    expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewEligibilityBlock\(/);
    expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewProviderBlock\(/);
  });

  // #5830 collapsed the two per-stage provider gates into one and dropped the
  // `publicReview &&` guard with them, so an ORDINARY task — posture `null`,
  // which no vendor declares a recipe for — was blocked at spawn with
  // "has no enforced null public-content review mode". The decision lives in
  // `publicReviewProviderBlock` (unit-tested in
  // providerVendors.publicReview.test.js), which returns null for a task that
  // requested no posture. Pin the call at its new home so neither the gate nor
  // the caller can re-derive it from a boolean support check and reintroduce
  // the same collapse.
  it('asks the posture helper for the provider gate rather than re-deriving it', () => {
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture);');
    // The helper owns the reason and the blocked category, so the gate cannot
    // pick its own — building either here means it decided for itself whether
    // the posture was supported.
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (postureBlock) return { ...postureBlock, emit: 'agent:error' };");
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toContain('public-content review mode');
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toMatch(/supportsPublicReviewPosture\(/);
    expect(AGENT_LIFECYCLE_SRC).not.toContain('public-content review mode');
    expect(AGENT_LIFECYCLE_SRC).not.toMatch(/supportsPublicReviewPosture\(/);
  });

  // The two CONTENT gates fail closed, which is not an agent failure: raising
  // an investigator for one could retry the same unvalidated input. That
  // distinction is a one-word `emit` field now, so it is easy to "tidy" away —
  // pin it beside the categories it applies to.
  it('withholds public review with a warn log, never an agent:error', () => {
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-security-scan-incomplete');
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-no-cleared-prs');
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-eligibility-incomplete');
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (scanBlock) return { ...scanBlock, emit: 'warn-log' };");
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (eligibilityBlock) return { ...eligibilityBlock, emit: 'warn-log' };");
    // The gate returns a verdict; it never announces one itself.
    expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toContain('cosEvents');
  });
});

// ─── Coverage guard for the self-update spawn gate (issue #4124) ────────────
//
// The gate is argued to cover EVERY path that can start an agent because those
// paths funnel through exactly two chokepoints: `task:ready` → subAgentSpawner's
// listener → `spawnAgentForTask` → one of the three low-level spawn helpers.
// Gating fewer files than "every spawn engine" is only sound while that funnel
// holds, so pin it: a new direct caller of `spawnAgentForTask` or of a spawn
// helper would bypass the gate and must fail here rather than in production.

describe('self-update spawn gate — funnel coverage (#4124)', () => {
  const SERVICES_DIR = __dirname;

  /** Every non-test .js under server/services (recursively), with its source. */
  const serviceSources = () => {
    const out = [];
    const walk = (dir) => {
      for (const entry of readdirSync(dir, { withFileTypes: true })) {
        const full = join(dir, entry.name);
        if (entry.isDirectory()) { walk(full); continue; }
        if (!entry.name.endsWith('.js') || entry.name.includes('.test.')) continue;
        out.push({ path: full, src: readFileSync(full, 'utf-8') });
      }
    };
    walk(SERVICES_DIR);
    return out;
  };

  /**
   * Files whose source invokes `name(` somewhere other than its own
   * declaration, relative to server/services and sorted. Listing the DEFINING
   * file too keeps the assertions non-vacuous: a regex that silently stopped
   * matching would drop that file and fail, instead of passing as an empty set.
   */
  const invokersOf = (name) => serviceSources()
    .filter(({ src }) => new RegExp(`(?<!function )\\b${name}\\(`).test(src))
    .map(({ path }) => path.slice(SERVICES_DIR.length + 1))
    .sort();

  it('spawnAgentForTask is invoked from exactly one place — the gated task:ready listener', () => {
    expect(
      invokersOf('spawnAgentForTask'),
      'a new caller of spawnAgentForTask must also carry the self-update hold (see subAgentSpawner.js)'
    ).toEqual(['subAgentSpawner.js']);
  });

  it('the three low-level spawn helpers are invoked only from the gated dispatch', () => {
    // If any other module called these directly it would create an agent
    // process without passing spawnAgentForTask's update guard at all.
    for (const helper of ['spawnTuiAgent', 'spawnViaRunner', 'spawnDirectly']) {
      expect(
        invokersOf(helper),
        `${helper} must stay reachable only through spawnAgentForTask`
      ).toEqual(['agentSpawnDispatch.js']);
    }
  });

  it('subAgentSpawner holds the dispatch on the synchronous update flag', () => {
    const src = readFileSync(join(SERVICES_DIR, 'subAgentSpawner.js'), 'utf-8');
    expect(src).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);
    // The dispatch body lives in `handleTaskReady`, the named function the
    // `task:ready` registration wraps in a `.catch` (a plain EventEmitter would
    // otherwise leak an async listener's rejection).
    const idx = src.indexOf('async function handleTaskReady');
    expect(idx, 'the task:ready dispatch must exist').toBeGreaterThan(-1);
    const spawnIdx = src.indexOf('await spawnAgentForTask(task)', idx);
    expect(spawnIdx).toBeGreaterThan(idx);
    // The hold is BEFORE the spawn, and before the (awaited) runner probe — a
    // synchronous check can't be raced by anything in between.
    const preamble = src.slice(idx, spawnIdx);
    expect(preamble).toMatch(/if \(isUpdateInProgress\(\)\) \{\s*return holdTask\(task,/);
    expect(preamble.indexOf('isUpdateInProgress()')).toBeLessThan(preamble.indexOf('isRunnerReachable()'));
  });

  it('handleAgentCompletion delegates runnerAgents cleanup to withMapEntryCleanup', () => {
    const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
    expect(idx, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
    const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 60_000);
    expect(body).toMatch(/withMapEntryCleanup\(\s*runnerAgents\s*,\s*agentId\s*,/);
  });

  // A tracked agent can already be terminal by the time its completion event
  // lands: a runner-backed TUI is finalized by spawnTuiAgent's `finish()`, which
  // then kills the session — and the runner reports THAT as an exit-143
  // completion. Without this guard the event ran a second finalizeAgent that
  // overwrote a sentinel-signalled success with a `startup-failure` verdict.
  it('handleAgentCompletion bails on a duplicate completion for an already-terminal record', () => {
    const body = trackedCompletionPreamble();
    // Reads the PERSISTED record — the in-memory maps say nothing about whether
    // another owner already wrote the terminal record.
    expect(body).toMatch(/await getAgentRecord\(agentId\)/);
    expect(body).toMatch(/persistedAgent && persistedAgent\.status !== 'running'/);
  });

  // The record backs BOTH the terminal-status guard and the PR-ownership check,
  // and `getAgent` (the transcript-hydrating reader) would line-split a completed
  // run's whole output.txt — megabytes on the very path the guard exists to catch,
  // plus a possible metadata.json rewrite via repairCodexTaskSummary.
  it('handleAgentCompletion reads the record once, via the transcript-free reader', () => {
    const body = trackedCompletionPreamble();
    expect(body).toMatch(/const persistedAgent = await getAgentRecord\(agentId\)/);
    // Imported unaliased, so `getAgent` can't be smuggled back in under this name.
    expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{[^}]*\bgetAgentRecord\b[^}]*\} from '\.\/cosAgentLifecycle\.js'/);
    expect(AGENT_LIFECYCLE_SRC).not.toMatch(/getAgent as getAgentRecord/);
    // Exactly one read for the whole tracked path.
    const reads = AGENT_LIFECYCLE_SRC.match(/await getAgentRecord\(agentId\)/g) || [];
    expect(reads).toHaveLength(1);
  });

  it('stampLiExecutionVerdict builds the verdict from the task liProposal marker via the shared builder (#2779)', () => {
    const idx = AGENT_FINALIZATION_SRC.indexOf('async function stampLiExecutionVerdict');
    expect(idx, 'stampLiExecutionVerdict must exist').toBeGreaterThan(-1);
    const body = AGENT_FINALIZATION_SRC.slice(idx, idx + 1500);
    // Derived from the persisted task's liProposal marker via the shared builder (parity
    // with the local #2765 write) and merged into taskUpdate.metadata under the verdict key.
    expect(body).toMatch(/task\?\.metadata\?\.liProposal/);
    expect(body).toMatch(/buildLiExecutionVerdict\(/);
    expect(body).toMatch(/\[LI_EXECUTION_VERDICT_KEY\]:\s*verdict/);
  });

  it('the post-restart recovery completion path also stamps the LI verdict on direct success (#2779, codex P2)', () => {
    // A hand-off that finished while the server was down completes via this bypass, not
    // finalizeAgent — it must still stamp so the outcome federates to the originating peer.
    // End-anchored on the statement that follows the branch rather than a fixed
    // char count: a fixed window silently shrinks its coverage every time the
    // branch grows, and a later addition pushed the assertions below out of it.
    const body = recoveryBranchSource();
    // The direct-success completion doesn't route through handleOrphanedTask, so it
    // stamps its own clean-completion verdict here.
    expect(body).toMatch(/await stampLiExecutionVerdict\(\{ status: 'completed', metadata: \{ \.\.\.task\.metadata, taskOutcome: taskOutcome \|\| null \} \}, task, \{ success: retiredSuccess \}\)/);
  });

  // The failure-path re-stamp used to live here too (re-reading the task after
  // `handleOrphanedTask` settled it `blocked`) — moved INTO `handleOrphanedTask`
  // itself (#8440), so every terminal settlement it makes is stamped, on every
  // caller (the orphan sweep, `resetOrphanedTasks`, and this post-restart path),
  // not just this one. See `agentManagement.test.js`'s
  // "stamps the LI execution verdict" coverage for the new location.
  it('no longer re-reads the task after handleOrphanedTask to re-stamp a failure verdict', () => {
    const body = recoveryBranchSource();
    expect(body).not.toMatch(/settled\.status === 'blocked'/);
    expect(body).not.toMatch(/await stampLiExecutionVerdict\(\{\}, settled/);
  });

  // This bypass never runs worktree cleanup, so the dead run's tree is still on
  // disk when the task is requeued. Without the dead agent's metadata,
  // handleOrphanedTask can't tell the retry what to resume, and it builds a fresh
  // worktree off the default branch and redoes work sitting right there.
  //
  // `startedAt` rides along for the same class of reason (#3637): it is the window
  // the orphan path's commit probe needs, and without it the probe is skipped and a
  // run that DID commit before dying is requeued as if it had produced nothing.
  it('the post-restart recovery path hands the dead agent’s metadata to the retry handler', () => {
    const body = recoveryBranchSource();
    expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata,\s*agentStartedAt: cosAgent\.startedAt,[\s\S]*?\}\)/);
  });
});

/**
 * Source of the post-restart recovery path. It was an inline `if (!agent)`
 * branch of handleAgentCompletion until #3872 split it into its own function;
 * the slice follows it there rather than re-anchoring on a neighbouring
 * statement inside the router, so the window is the whole function body and
 * cannot silently shrink as the path grows.
 */
function recoveryBranchSource() {
  const start = AGENT_LIFECYCLE_SRC.indexOf('async function completeUntrackedAgentFromCosState');
  expect(start, 'post-restart recovery path must exist').toBeGreaterThan(-1);
  const end = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion', start);
  expect(end, 'end anchor (the router that dispatches into it) must exist').toBeGreaterThan(start);
  return AGENT_LIFECYCLE_SRC.slice(start, end);
}

/**
 * Source of the TRACKED completion preamble in handleAgentCompletion — from
 * entering the withMapEntryCleanup body to the first real work it does. Both
 * anchors are real statements, so the window can't silently widen to swallow the
 * rest of the completion body as the function grows.
 */
function trackedCompletionPreamble() {
  const start = AGENT_LIFECYCLE_SRC.indexOf('withMapEntryCleanup(runnerAgents, agentId,');
  expect(start, 'withMapEntryCleanup wrapper must exist').toBeGreaterThan(-1);
  const end = AGENT_LIFECYCLE_SRC.indexOf("Normalize the agent's task shape", start);
  expect(end, 'end anchor (task-shape normalization) must exist').toBeGreaterThan(start);
  return AGENT_LIFECYCLE_SRC.slice(start, end);
}

// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────
//
// These pin control-flow orderings that live inside the ~470-LOC guarded spawn
// body and can't be reached without mocking its 40+ imports. Anchored on
// `runAgentSpawn` (the guarded body extracted from spawnAgentForTask, #2548).

const _RUN_SPAWN_START = AGENT_SPAWN_OWNER_SRC.indexOf('export async function prepareAgentSpawn');
const RUN_SPAWN_BODY = AGENT_SPAWN_OWNER_SRC;

describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', () => {
  it('uses a mutable handedOff flag to distinguish the two failure modes', () => {
    expect(AGENT_SPAWN_PREPARATION_SRC).toMatch(/handedOff:\s*false/);
    expect(AGENT_LIFECYCLE_SRC).toMatch(/context\.handedOff/);
    expect(AGENT_LIFECYCLE_SRC).toMatch(/if\s*\(!context\.setupCatchArmed\s*\|\|\s*context\.handedOff\)\s*throw\s+err\s*;/);
    expect(AGENT_LIFECYCLE_SRC).toMatch(
      /await context\.blockAndBail\(\{[\s\S]{0,300}?reason: setupError,[\s\S]{0,200}?category: 'private-security-setup-failed',/
    );
    expect(AGENT_LIFECYCLE_SRC).toMatch(/job:spawn-failed/);
    expect(AGENT_LIFECYCLE_SRC).toMatch(/task\.metadata\??\.jobId/);
  });

  it('sets handedOff = true BEFORE the first spawn helper invocation', () => {
    const flipIdx = AGENT_SPAWN_DISPATCH_SRC.indexOf('context.handedOff = true');
    expect(flipIdx, '`context.handedOff = true` must exist in dispatchAgentRun').toBeGreaterThan(-1);
    for (const helper of ['spawnTuiAgent(', 'spawnViaRunner(', 'spawnDirectly(']) {
      const idx = AGENT_SPAWN_DISPATCH_SRC.indexOf(helper);
      expect(idx, `${helper} must appear AFTER \`context.handedOff = true\``).toBeGreaterThan(flipIdx);
    }
  });
});

describe('runAgentSpawn source — durable TUI ownership (#3202)', () => {
  it('routes TUI providers through the runner when it is available', () => {
    expect(RUN_SPAWN_BODY).toMatch(
      /const executionMode = resolveExecutionMode\(\{ spawnHeadless, useRunner: dispatchUseRunner \}\);/
    );
    // The four modes themselves, at their new home.
    expect(AGENT_REGISTRATION_SRC).toMatch(/if \(spawnHeadless\) return useRunner \? 'runner' : 'direct';/);
    expect(AGENT_REGISTRATION_SRC).toMatch(/return useRunner \? 'runner-tui' : 'tui';/);
    expect(RUN_SPAWN_BODY).toMatch(/spawnTuiAgent\(\{[\s\S]{0,1000}?useDurableRunner:\s*dispatchUseRunner/);
    expect(RUN_SPAWN_BODY).not.toMatch(/useRunner:\s*isTui\s*\?\s*false\s*:\s*useRunner/);
  });
});

// Source-level assertion (issue #989): the synthetic app-review marker bound by
// `bindAppReviewAgent` before this spawn MUST be released on every
// pre-completion `return null` path, or the app reads "in review" until the next
// daemon restart. `cleanupOnError` is the SINGLE owner of that release now
// (#6617) — it is defined before the first gate, so the two earliest returns
// (max-spawns block, lane-acquire failure) route through it too instead of
// hand-rolling their own release, which is how two of the eight copies came to
// omit it. What each gate actually releases is behavior-tested in
// agentLifecycle.blockAndBail.test.js; these pin the structure that keeps a
// NEW gate from re-opening the hole.
describe('agent spawn preparation — app-review marker release (issue #989)', () => {
  it('releases the synthetic app-review marker from the shared cleanup owner', () => {
    const start = AGENT_SPAWN_PREPARATION_SRC.indexOf('context.cleanupOnError =');
    expect(start, 'cleanup owner must exist').toBeGreaterThan(-1);
    const body = AGENT_SPAWN_PREPARATION_SRC.slice(start, start + 1400);
    expect(body).toMatch(/releaseAppReviewMarker\(context\.task\.metadata\?\.app\)/);
  });

  it('awaits every cleanup call before returning null', () => {
    const bareCalls = AGENT_SPAWN_OWNER_SRC.match(/(?<!await )(?<!const )context\.cleanupOnError\(/g) || [];
    expect(bareCalls, 'all cleanup calls must be awaited').toEqual([]);
  });

  it('keeps one marker release site in preparation', () => {
    const releases = AGENT_SPAWN_PREPARATION_SRC.match(/releaseAppReviewMarker\(/g) || [];
    expect(releases).toHaveLength(1);
  });

  it('guards each release on the acquired resource', () => {
    const body = AGENT_SPAWN_PREPARATION_SRC;
    expect(body).toMatch(/if \(context\.laneAcquired\) release\(context\.agentId\);/);
    expect(body).toMatch(/if \(context\.toolExecution\) \{[\s\S]{0,200}?errorExecution\(context\.toolExecution\.id/);
    expect(body).toMatch(/if \(context\.claimAcquired\) \{/);
    expect(body).toMatch(/context\.laneAcquired = true;/);
  });
});

// ─── runAgentSpawn — the ONE block-and-bail epilogue (issue #6617) ───────────
//
// Nine gates used to each carry their own copy of "persist blocked, clean up,
// announce, return null". They drifted — two announced with a warn log and two
// skipped the app-review-marker release — and the suite could not see it,
// because it grepped for `status: 'blocked'`. Collapsing them into one
// parameterized helper is what makes each gate's behavior assertable, so pin
// that the collapse holds: a tenth gate must reuse the helper, not paste a
// tenth copy.
describe('agent spawn preparation — one block-and-bail epilogue', () => {
  it('writes the blocked status in exactly one place', () => {
    const blockWrites = AGENT_SPAWN_OWNER_SRC.match(/status: 'blocked'/g) || [];
    expect(blockWrites).toHaveLength(1);
    expect(AGENT_SPAWN_PREPARATION_SRC).toContain('context.blockAndBail = async');
  });

  it('persists the block before releasing the lease', () => {
    const body = AGENT_SPAWN_PREPARATION_SRC;
    const persistIdx = body.indexOf("status: 'blocked'");
    const cleanupIdx = body.indexOf('await context.cleanupOnError(reason)');
    expect(persistIdx).toBeGreaterThan(-1);
    expect(cleanupIdx).toBeGreaterThan(-1);
    expect(persistIdx).toBeLessThan(cleanupIdx);
    expect(body.indexOf("cosEvents.emit('agent:error'")).toBeGreaterThan(cleanupIdx);
  });

  it('supports the three announcement modes the gates differ on', () => {
    const body = AGENT_SPAWN_PREPARATION_SRC;
    expect(body).toMatch(/if \(emit === 'agent:error'\)/);
    expect(body).toMatch(/\} else if \(emit === 'warn-log'\)/);
    expect(body).toMatch(/emitLog\('warn', `Public review withheld for task \$\{context\.task\.id\}: \$\{category\}`/);
    expect(body).toMatch(/category: 'max-spawns',\s*emit: 'none',/);
  });
});

// ─── runAgentSpawn — permanent provider-config failure blocks the task ───────
//
// A resolution failure marked `permanent` (an api-only provider pinned to an
// agent task, which has no file-writing harness) fails identically on every
// re-dispatch. Without a block, the task stays pending and silently re-fails
// forever. Pin that the permanent branch flips the task to blocked BEFORE the
// lease is released, so a federated peer can't be clobbered.
describe('runAgentSpawn source — permanent provider-config failure blocks the task', () => {
  it('the resolution-failure path blocks a permanent failure with a provider-config reason', () => {
    const idx = AGENT_SPAWN_DISPATCH_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
    expect(idx, 'resolution call must exist').toBeGreaterThan(-1);
    const body = AGENT_SPAWN_DISPATCH_SRC.slice(idx, idx + 2000);
    // `persist` carries what used to be an `if (resolution.permanent)` wrapper
    // around a hand-copied block write: a transient failure stays pending, a
    // permanent one is blocked. Same decision, one line, one epilogue.
    expect(body, 'gates the block on resolution.permanent').toMatch(/persist:\s*resolution\.permanent,/);
    expect(body, 'routes through the shared epilogue').toMatch(/return context\.blockAndBail\(\{/);
    // The category is the SHARED constant, not a hand-written literal: the pause
    // and reaper-exemption sets in lib/taskBlockCategories.js key on the same
    // value, and a stamp-site literal is exactly how those three drift apart.
    expect(body, 'tags the block category from the shared constant').toMatch(/category:\s*PROVIDER_CONFIG_BLOCKED_CATEGORY,/);
    expect(body, 'does not re-hardcode the literal').not.toMatch(/'provider-config'/);
    expect(AGENT_SPAWN_DISPATCH_SRC, 'imports the shared constant').toMatch(/import \{[^}]*PROVIDER_CONFIG_BLOCKED_CATEGORY[^}]*\} from '\.\.\/lib\/taskBlockCategories\.js'/);
    // The provider identity rides the agent:error event, so the investigator
    // names which provider failed rather than only the message.
    expect(body).toMatch(/emitPayload: \{[\s\S]{0,300}?resolution\.providerId[\s\S]{0,200}?resolution\.providerStatus/);
  });

  // The block only does its job if the vocabulary module agrees it is a config
  // PAUSE (keeps the resume pointer) and a user DECISION (exempt from the 14-day
  // auto-expiry). Pin both memberships here, at the stamp site, so removing one
  // fails beside the code that depends on it.
  it('the stamped category is a config pause the reaper leaves alone', () => {
    expect(PROVIDER_CONFIG_BLOCKED_CATEGORY).toBe('provider-config');
    expect(PAUSED_BLOCKED_CATEGORIES.has(PROVIDER_CONFIG_BLOCKED_CATEGORY), 'keeps its resume pointer').toBe(true);
    expect(USER_DECISION_BLOCKED_CATEGORIES.has(PROVIDER_CONFIG_BLOCKED_CATEGORY), 'never auto-expired to completed').toBe(true);
  });

  // The ordering this used to assert at this one call site is now a property of
  // `blockAndBail`, which every gate shares — pinned once, in
  // "one block-and-bail epilogue" above. What is left to pin here is that this
  // path still goes through it rather than re-inlining its own write.
  it('blocks through the shared epilogue, which persists before releasing the lease', () => {
    const idx = AGENT_SPAWN_DISPATCH_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
    const body = AGENT_SPAWN_DISPATCH_SRC.slice(idx, idx + 2000);
    expect(body, 'no hand-rolled block write on this path').not.toMatch(/status:\s*'blocked'/);
    expect(body, 'no hand-rolled lease release on this path').not.toMatch(/await cleanupOnError\(/);
    expect(body).toMatch(/if \(!resolution\.ok\) \{[\s\S]{0,1200}?return context\.blockAndBail\(\{/);
  });
});

// ─── Instance provenance stamping + claim ordering (issue #1563) ─────────────
//
// Every spawned agent records the producing machine's federation identity, and
// the cross-instance claim must be acquired (and re-checked against the fresh
// record) BEFORE the agent is registered — otherwise two peers spawn for the
// same task. These orderings live inside runAgentSpawn with no behavioral seam.
describe('runAgentSpawn source — instance provenance + claim ordering (#1563)', () => {
  it('imports the identity resolver from the instance identity leaf', () => {
    expect(AGENT_SPAWN_PREPARATION_SRC).toMatch(
      /import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instanceIdentity\.js';/
    );
  });

  it('resolves instanceId via ensureInstanceId() before registering the agent', () => {
    const resolveIdx = RUN_SPAWN_BODY.indexOf('await ensureInstanceId()');
    const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');
    expect(resolveIdx, '`await ensureInstanceId()` must exist inside runAgentSpawn').toBeGreaterThan(-1);
    expect(registerIdx, '`registerAgent(...)` must exist inside runAgentSpawn').toBeGreaterThan(-1);
    expect(resolveIdx, 'instanceId must be resolved BEFORE registerAgent is called').toBeLessThan(registerIdx);
  });

  it("refuses to spawn a task under another instance's live lease (claim guard)", () => {
    const guardIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');
    const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');
    expect(guardIdx, 'must gate the spawn on isClaimableBy').toBeGreaterThan(-1);
    expect(guardIdx, 'the claim guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
  });

  // #4520: a task pinned to a specific federated instance runs ONLY there. The
  // pin is a standing decision, so it gates the spawn ahead of the opportunistic
  // lease check — and is re-checked against the fresh record, because a
  // reassignment can sync in between the dequeue and the claim.
  it('refuses to spawn a task pinned to another instance, before the lease check', () => {
    const targetIdx = RUN_SPAWN_BODY.indexOf('isTargetedElsewhere(task.metadata, instanceId)');
    const leaseIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');
    const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');
    expect(targetIdx, 'must gate the spawn on isTargetedElsewhere').toBeGreaterThan(-1);
    expect(targetIdx, 'the pin guard must run BEFORE the lease guard').toBeLessThan(leaseIdx);
    expect(targetIdx, 'the pin guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
  });

  it('re-checks the pin against the freshest task, before claiming it', () => {
    const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
    const recheckIdx = RUN_SPAWN_BODY.indexOf('isTargetedElsewhere(freshTask.metadata, instanceId)');
    const acquireIdx = RUN_SPAWN_BODY.indexOf('metadata: buildClaim(instanceId)');
    expect(recheckIdx, 'must re-check the pin against the fresh metadata').toBeGreaterThan(rereadIdx);
    expect(recheckIdx, 'the fresh pin re-check must precede taking the claim').toBeLessThan(acquireIdx);
  });

  it('stamps the federation claim into the in_progress task update', () => {
    expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);
  });

  it('acquires the claim (updateTask with buildClaim) BEFORE registering the agent', () => {
    const acquireIdx = RUN_SPAWN_BODY.indexOf('metadata: buildClaim(instanceId)');
    const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');
    expect(acquireIdx, 'must acquire the claim via updateTask(buildClaim) up front').toBeGreaterThan(-1);
    expect(acquireIdx, 'claim must be acquired BEFORE registerAgent').toBeLessThan(registerIdx);
  });

  it('re-reads the freshest task and yields if claimed during dispatch', () => {
    const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
    const recheckIdx = RUN_SPAWN_BODY.indexOf('!isClaimableBy(freshTask.metadata, instanceId)');
    expect(rereadIdx, 'must re-read the freshest persisted task before claiming').toBeGreaterThan(-1);
    expect(recheckIdx, 'must re-check claimability against the fresh metadata').toBeGreaterThan(rereadIdx);
  });

  // The hold keeps this instance's OWN lease (updateTask only releases it when a
  // status other than in_progress is written), so the claim re-check above passes
  // for a held task. A `task:ready` emitted before the failure — or a stale
  // generator snapshot — would otherwise spawn the retry while the pointer naming
  // its predecessor's branch is still being resolved (#3373).
  it('refuses to spawn a task whose retry is held for its resume pointer', () => {
    const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
    const holdIdx = RUN_SPAWN_BODY.indexOf('isRetryHeld(freshTask.metadata)');
    const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');
    expect(holdIdx, 'must check the retry hold on the fresh metadata').toBeGreaterThan(rereadIdx);
    expect(holdIdx, 'the hold guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
  });

  it('releases the claim on a failed-setup early exit (cleanupOnError)', () => {
    const fnStart = AGENT_SPAWN_PREPARATION_SRC.indexOf('context.cleanupOnError = async');
    const fnBody = AGENT_SPAWN_PREPARATION_SRC.slice(fnStart, fnStart + 1200);
    expect(fnBody.indexOf('context.claimAcquired'), 'cleanup owner must gate on claimAcquired').toBeGreaterThan(-1);
    expect(fnBody.indexOf('buildRelease()'), 'cleanup owner must release the claim via buildRelease').toBeGreaterThan(-1);
  });

  it('stamps instanceId into the registerAgent metadata', () => {
    expect(AGENT_REGISTRATION_SRC).toMatch(/\binstanceId,/);
    expect(AGENT_REGISTRATION_SRC.indexOf('instanceId,')).toBeLessThan(AGENT_REGISTRATION_SRC.indexOf('workspacePath,'));
  });

  it('records claimFlow separately from CoS-managed PR/worktree flags', () => {
    expect(AGENT_REGISTRATION_SRC).toContain('configOpenPR: isTruthyMeta(task.metadata?.openPR)');
    // Derived from \`isClaimFlowTask\`, not re-implemented inline: the predicate also
    // recognises a claim run by its \`analysisType\`, which an inline
    // \`isTruthyMeta(task.metadata?.claimFlow)\` would silently drop. Hoisted to one
    // const because \`configCodingOnMain\` reads the same fact.
    expect(AGENT_SPAWN_DISPATCH_SRC).toContain('const claimFlowTask = isClaimFlowTask(task);');
    expect(AGENT_REGISTRATION_SRC).toContain('configClaimFlow: claimFlowTask');
    expect(AGENT_REGISTRATION_SRC.indexOf('configClaimFlow')).toBeGreaterThan(AGENT_REGISTRATION_SRC.indexOf('configOpenPR'));
  });

  it('projects the public-review posture so the UI can explain the missing shell link', () => {
    // `spawnHeadless` forces a public-review stage headless even on a TUI
    // provider — unless it is the sandboxed-actions stage on a vendor with an
    // attachable recipe (#6062) — so its card usually gets no "Open Shell"
    // link. Without this projection the card cannot tell that apart from a PTY
    // that failed to attach, and the run reads as wedged.
    expect(AGENT_REGISTRATION_SRC).toMatch(/^\s*publicReviewPosture,$/m);
    // …and the orchestrator still hands it over, so the key cannot go stale.
    expect(RUN_SPAWN_BODY).toMatch(/^\s*publicReviewPosture,$/m);
  });
});

// These used to be three source-regex assertions pinning a hand-spread env
// literal (`...forgeTokenEnv, ...provider.envVars, ...opencodeEnv`) inside
// spawnViaRunner. The layering now lives in `lib/cliChildEnv.js#composeProviderEnv`,
// where `cliChildEnv.test.js` asserts the ORDER against the real function instead
// of against source text — which is the point of #3194: a grep-shaped guard was
// what let this exact site miss the #2243/#2190 sweep in the first place.
//
// What is still worth pinning HERE is the wiring: that spawnViaRunner routes
// through the shared composer and feeds it the right inputs.
describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () => {
  // Bounded by the NEXT top-level declaration rather than a character count: a
  // fixed window silently shrinks as the function grows a comment, and the
  // assertions below then fail on text that is still there (and would keep
  // passing on a line that had drifted into the following function).
  const runnerBody = () => {
    const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');
    expect(fnStart, 'spawnViaRunner must exist').toBeGreaterThan(-1);
    const nextExport = AGENT_LIFECYCLE_SRC.indexOf('\nexport ', fnStart + 1);
    return AGENT_LIFECYCLE_SRC.slice(fnStart, nextExport > -1 ? nextExport : undefined);
  };

  it('source: composes the runner envVars through the shared composeProviderEnv', () => {
    expect(AGENT_LIFECYCLE_SRC).toMatch(
      /import\s*\{\s*composeProviderEnv\s*\}\s*from\s*'\.\.\/lib\/cliChildEnv\.js';/
    );
    // The payload must BE the composed env — not a literal that re-spreads it,
    // which is how the layer order drifted from the other spawn sites before.
    expect(runnerBody()).toMatch(/envVars:\s*composeProviderEnv\(\{/);
  });

  it('source: feeds the composer the provider + per-call model so --model ollama/<id> is accepted', () => {
    const fnBody = runnerBody();
    const call = fnBody.slice(fnBody.indexOf('composeProviderEnv({'), fnBody.indexOf('composeProviderEnv({') + 300);
    expect(call, 'the OpenCode declared-models map is built from provider+model').toContain('provider,');
    expect(call).toContain('model,');
  });

  it("source: pins GH_TOKEN via resolveForgeTokenEnv so the runner-spawned agent's `gh` uses the repo-owner account", () => {
    const fnBody = runnerBody();
    expect(fnBody).toContain('resolveForgeTokenEnv(workspacePath)');
    // `before` is the slot that sits UNDER provider.envVars, so an explicit
    // provider GH_TOKEN still wins — passing it as `extra` would invert that.
    expect(fnBody).toMatch(/before:\s*\{[^}]*\.\.\.forgeTokenEnv[^}]*\}/);
  });
});

describe('runAgentSpawn source — claim-miss guard (issue #2633)', () => {
  it('only a null in_progress result is fatal — an { error } miss must NOT block the spawn', () => {
    // A truthy `{ error }` is EXPECTED for legitimately-unpersisted autonomous
    // emits (Priority 3 idle-review tasks carry taskType:'internal' but are
    // never written to COS-TASKS.md). Blocking on it would silently kill every
    // idle-review spawn — the pre-#2633 behavior spawned them anyway, so the
    // fatal guard must remain `!updateResult` only.
    const fatalIdx = RUN_SPAWN_BODY.indexOf('if (!updateResult) {');
    expect(fatalIdx, 'the fatal guard must be `!updateResult` alone — the { error } shape must not be fatal').toBeGreaterThan(-1);
    expect(RUN_SPAWN_BODY, 'the { error } shape must not be part of the fatal guard (it would block unpersisted idle-review spawns)')
      .not.toContain('if (!updateResult || updateResult.error)');
  });

  it('warn-logs when the in_progress claim returns an { error } object so silent misses are visible', () => {
    const warnIdx = RUN_SPAWN_BODY.indexOf('if (updateResult?.error) {');
    expect(warnIdx, 'a silent { error } miss must be surfaced via a warn log').toBeGreaterThan(-1);
    const body = RUN_SPAWN_BODY.slice(warnIdx, warnIdx + 400);
    expect(body).toMatch(/emitLog\('warn'/);
    expect(body).toContain('updateResult.error');
  });
});

// #6117: a public-review Stage 3 dispatch inlines the whole screened envelope —
// ~100K tokens — and a model server on this box spends minutes prefilling it
// before the child emits a line. Nothing compared the assembled prompt against
// the endpoint it was aimed at, so the run's duration estimate carried none of
// that cost and the card was indistinguishable from a wedged run. The budget has
// no behavioral seam inside runAgentSpawn, so pin the two orderings that make it
// correct.
describe('runAgentSpawn source — local prompt/prefill budget (#6117)', () => {
  it('measures the FULLY assembled prompt, after the public-review envelope is appended', () => {
    // Measuring `basePrompt` would miss the envelope, which IS the ~100K tokens.
    const promptIdx = RUN_SPAWN_BODY.indexOf('formatPublicReviewInputPrompt(publicReviewPromptData)');
    const planIdx = RUN_SPAWN_BODY.indexOf('planLocalPromptBudget({');
    expect(promptIdx, 'the public-review envelope must still be appended to the prompt').toBeGreaterThan(-1);
    expect(planIdx, '`planLocalPromptBudget({` must exist inside runAgentSpawn').toBeGreaterThan(-1);
    expect(promptIdx, 'the budget must be planned AFTER the envelope is appended').toBeLessThan(planIdx);
  });

  it('only asks the question for an endpoint on this machine, and never refuses the dispatch', () => {
    // A cloud provider prefills in seconds and must take no async hop; and the
    // decision on this issue was explicitly to RAISE the estimate rather than
    // block a provider the user deliberately configured.
    expect(RUN_SPAWN_BODY).toMatch(/const\s+localEndpoint\s*=\s*localEndpointOfProvider\(provider\)\s*;/);
    expect(RUN_SPAWN_BODY).toMatch(/localEndpoint\s*\r?\n?\s*\?\s*planLocalPromptBudget\(\{/);
    expect(RUN_SPAWN_BODY, 'the budget must never turn into a blocked task')
      .not.toMatch(/localPromptBudget[\s\S]{0,200}blockedReason/);
  });

  it('stamps the budget onto the agent record so the card can explain the silence', () => {
    expect(AGENT_REGISTRATION_SRC).toMatch(/\blocalPromptBudget,/);
    expect(RUN_SPAWN_BODY).toMatch(/\blocalPromptBudget,/);
  });
});

// Source-level assertion (#6406): agent.metadata is a hand-picked projection of
// task.metadata, so a provenance key the projection forgets is a field that
// reaches disk and never reaches the runner's completion continuation or the
// denial ledger — exactly what happened to `quotaBurnStepId`. The projection has
// to derive from the one block definition in lib/quotaBurnOrigin.js (whose own
// test pins that the block covers every persisted field), which means naming a
// `taskQuotaBurn*` key by hand here is the regression.
describe('runAgentSpawn source — quota-burn provenance projection (#6406)', () => {
  it('spreads the shared provenance block instead of naming its keys', () => {
    expect(AGENT_REGISTRATION_SRC).toMatch(/\.\.\.quotaBurnAgentMetadata\(task\.metadata\)/);
    expect(AGENT_REGISTRATION_SRC.match(/^\s*taskQuotaBurn\w*\s*:/gm) || []).toEqual([]);
    expect(AGENT_LIFECYCLE_SRC.match(/^\s*taskQuotaBurn\w*\s*:/gm) || []).toEqual([]);
  });
});

// Archive classification must survive the task-to-agent metadata projection.
it('preserves the machine-local privacy marker in spawned agent metadata', () => {
  expect(AGENT_REGISTRATION_SRC).toContain('machineLocal: isTruthyMeta(task.metadata?.machineLocal)');
});