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

32.1 KB
Raw Blame
/**
 * The runtime is where #7456's claim is either true or not: a controller a
 * mind installed has to keep running while that mind is not running.
 *
 * The HELD-OUT test the issue asks for is `still ticks with no mind, no tool
 * call, and no author in the process` below. It installs a controller and then
 * touches nothing a mind touches — no tool dispatch, no wake, no further
 * install — and drives only the supervisor's own clock. Time is injected
 * rather than slept through, so the contract is about cadence and not about
 * how long the suite is willing to wait.
 *
 * The rest of these pin the boundaries a higher-level test could not phrase
 * usefully: that an id is the only thing an install may say about behavior,
 * that arming is reconciled at every gate move rather than only at boot, that
 * a laptop that slept does not wake to a replayed backlog, and that a broken
 * controller stops and says why instead of failing on a schedule forever.
 */

import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { rmSync } from 'node:fs';
import { join } from 'node:path';
import { z } from 'zod';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
import { eidoverseControllerRecordSchema, summarizeControllerInstall } from '../lib/eidoverseControllers.js';

vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
  dataRoot: () => lazyTempDataRoot('portos-eidoverse-controllers-'),
}));

const { atomicWrite, readJSONFile } = await import('../lib/fileUtils.js');

// `deliverControllerEffects()` (the default `deliver` the runtime uses when a
// test does not inject its own) lazily imports this module, so mocking it is
// what lets a test drive a REAL world refusal through the REAL delivery path
// instead of only through an injected `deliver` stand-in (#7628).
const { augmentEidoverseWorldMock, sayInEidoverseWorldMock } = vi.hoisted(() => ({
  augmentEidoverseWorldMock: vi.fn(),
  sayInEidoverseWorldMock: vi.fn(),
}));
vi.mock('./eidoverseWorld.js', () => ({
  augmentEidoverseWorld: augmentEidoverseWorldMock,
  sayInEidoverseWorld: sayInEidoverseWorldMock,
}));

const {
  __resetEidoverseControllerRuntimeForTests,
  getEidoverseControllerInstall,
  installEidoverseController,
  isEidoverseControllerSupervisorRegistered,
  listEidoverseControllers,
  retireEidoverseController,
  setEidoverseControllerArmed,
  tickEidoverseControllers,
  updateEidoverseControllerConfig,
} = await import('./eidoverseControllerRuntime.js');

/** The raw store file this module owns, for tests that need to inspect or
 * hand-edit what actually landed on disk (a `schemaVersion` newer than this
 * build's own constant, for instance — nothing this module's own API can
 * produce). */
const storeFile = () => join(lazyTempDataRoot('portos-eidoverse-controllers-'), 'eidoverse', 'controllers.json');

const MINUTE = 60_000;
const START = Date.parse('2026-03-04T00:00:00.000Z');
const at = (msFromStart) => new Date(START + msFromStart).toISOString();

const install = (overrides = {}, options = {}) => installEidoverseController({
  id: 'plaza-beacon',
  controllerId: 'ambient-beacon',
  tickIntervalMs: 5 * MINUTE,
  config: { label: 'plaza', pulseEveryTicks: 2 },
  ...overrides,
}, { installedBy: 'mind', now: at(0), ...options });

/**
 * Advance the supervisor's clock past `passes` wake-ups, exactly as the
 * scheduled interval would. Nothing else in the process runs.
 */
async function runSupervisorPasses(passes, { fromMs = 0, everyMs = MINUTE, ...options } = {}) {
  const results = [];
  for (let pass = 1; pass <= passes; pass += 1) {
    results.push(await tickEidoverseControllers({ now: at(fromMs + pass * everyMs), ...options }));
  }
  return results;
}

beforeEach(() => {
  rmSync(lazyTempDataRoot('portos-eidoverse-controllers-'), { recursive: true, force: true });
  __resetEidoverseControllerRuntimeForTests();
  augmentEidoverseWorldMock.mockReset();
  sayInEidoverseWorldMock.mockReset();
});

afterEach(() => __resetEidoverseControllerRuntimeForTests());
afterAll(cleanupTempDataRoots);

describe('installing a controller', () => {
  it('resolves behavior by id against the fixed registry and refuses anything else', async () => {
    const refused = await install({ controllerId: 'ambient-beacon/../../../etc/passwd' });
    expect(refused.outcome).toBe('refused');

    // An id-shaped string that is simply not registered is refused the same
    // way — there is no path, no import, and no fallback that could run it.
    const unknown = await install({ controllerId: 'attacker-supplied' });
    expect(unknown.outcome).toBe('refused');
    expect(unknown.reasons[0]).toMatch(/never by a module path/);

    expect((await listEidoverseControllers()).installs).toEqual([]);
  });

  it('validates the config against the controller\'s own schema at install time', async () => {
    const refused = await install({ config: { label: 'plaza', pulseEveryTicks: 0 } });
    expect(refused.outcome).toBe('refused');
    expect(refused.reasons[0]).toMatch(/^config\.pulseEveryTicks/);
  });

  it('arms the supervisor on install and stands it down again on retire', async () => {
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);

    await install();
    expect(isEidoverseControllerSupervisorRegistered()).toBe(true);

    await retireEidoverseController('plaza-beacon');
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);
  });

  it('reconciles arming when a controller is disarmed and re-armed, not only at boot', async () => {
    await install();

    await setEidoverseControllerArmed('plaza-beacon', false, { now: at(MINUTE) });
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);

    await setEidoverseControllerArmed('plaza-beacon', true, { now: at(2 * MINUTE) });
    expect(isEidoverseControllerSupervisorRegistered()).toBe(true);
  });

  it('never fires on install — the first tick is one interval away', async () => {
    const installed = await install();

    expect(installed.install.tick).toBe(0);
    expect(installed.install.nextTickAt).toBe(at(5 * MINUTE));
    expect((await runSupervisorPasses(4))[3]).toMatchObject({ ticked: 0 });
  });
});

describe('the supervised tick path', () => {
  it('still ticks with no mind, no tool call, and no author in the process', async () => {
    await install({ deliverEffects: false });

    // From here on nothing a mind does happens: no tool dispatch, no wake, no
    // second install. Only the supervisor's own clock moves.
    await runSupervisorPasses(30);

    const record = await getEidoverseControllerInstall('plaza-beacon');
    // Six five-minute cadences fit in thirty one-minute supervisor passes.
    expect(record.tick).toBe(6);
    expect(record.state).toMatchObject({ label: 'plaza', ticks: 6, pulses: 3 });
    expect(record.lastOutcome).toMatchObject({ ok: true, reason: null });
    // Every second tick pulsed, and each pulse was recorded where the author
    // can read it back on their next wake.
    expect(record.recentEffects.map((effect) => effect.summary))
      .toEqual(['plaza pulse 3', 'plaza pulse 2', 'plaza pulse 1']);
  });

  it('survives a restart of the process that installed it', async () => {
    await install();
    await runSupervisorPasses(10);
    expect((await getEidoverseControllerInstall('plaza-beacon')).tick).toBe(2);

    // A restart: every in-memory handle in this module is dropped and the
    // runtime is re-imported fresh. Only what reached disk comes back.
    __resetEidoverseControllerRuntimeForTests();
    vi.resetModules();
    const restarted = await import('./eidoverseControllerRuntime.js');

    await restarted.startEidoverseControllerSupervisor();
    expect(restarted.isEidoverseControllerSupervisorRegistered()).toBe(true);

    await restarted.tickEidoverseControllers({ now: at(20 * MINUTE) });
    const record = await restarted.getEidoverseControllerInstall('plaza-beacon');
    expect(record.tick).toBe(3);
    expect(record.state.ticks).toBe(3);

    restarted.__resetEidoverseControllerRuntimeForTests();
  });

  it('wakes a slept machine to ONE tick, not to a replayed backlog', async () => {
    await install();

    // Three days later, in a single pass.
    const [pass] = await runSupervisorPasses(1, { everyMs: 3 * 24 * 60 * MINUTE });

    expect(pass).toMatchObject({ ticked: 1, due: 1 });
    expect((await getEidoverseControllerInstall('plaza-beacon')).tick).toBe(1);
  });

  it('keeps effects out of the world until the install explicitly delivers them', async () => {
    const deliver = vi.fn(async () => ({ delivered: 1, error: null }));
    await install({ config: { label: 'plaza', pulseEveryTicks: 1 }, deliverEffects: false });

    await runSupervisorPasses(5, { deliver });
    expect(deliver).not.toHaveBeenCalled();

    await install({ id: 'lamp-keeper', controllerId: 'lantern-keeper', deliverEffects: true, tickIntervalMs: 5 * MINUTE,
      config: { relightEveryTicks: 1, lanterns: [{ id: 'plaza-lantern', pos: [0, 2, 0] }] } }, { now: at(5 * MINUTE) });

    await runSupervisorPasses(5, { fromMs: 5 * MINUTE, deliver });
    expect(deliver).toHaveBeenCalledTimes(1);
    expect(deliver.mock.calls[0][0]).toEqual([{
      kind: 'augment',
      operations: [{ verb: 'light', args: { id: 'plaza-lantern', pos: [0, 2, 0], color: 0xFFD27F, intensity: 16, range: 10 } }],
    }]);
  });

  it('counts the step and records the failure when the world cannot be reached', async () => {
    const deliver = vi.fn(async () => { throw new Error('world host is down'); });
    await install({ config: { label: 'plaza', pulseEveryTicks: 1, announce: true }, deliverEffects: true });

    await runSupervisorPasses(5, { deliver });

    const record = await getEidoverseControllerInstall('plaza-beacon');
    // The controller's own state advanced — re-running it to retry a world
    // write would double-count everything it did.
    expect(record.state.pulses).toBe(1);
    expect(record.lastOutcome).toMatchObject({ ok: true, delivered: 0, deliveryError: 'world host is down' });
  });

  // #7628: `augmentEidoverseWorld()` never throws on a world refusal — the
  // verdict is its return value. This drives that refusal through the REAL
  // `deliverControllerEffects()` (no `deliver` override), the seam the old
  // fixture skipped by mocking a throw instead, and follows it all the way to
  // the projection a mind or the panel actually reads.
  it('reads a world refusal instead of counting it as delivered, and disarms after enough of them', async () => {
    augmentEidoverseWorldMock.mockResolvedValue({
      success: false,
      applied: 0,
      operations: [{ verb: 'light', id: 'missing-lantern', outcome: 'refused', proposed: null, committed: null, reason: 'unknown entity id' }],
    });
    await install({
      id: 'lamp-keeper', controllerId: 'lantern-keeper', deliverEffects: true, tickIntervalMs: MINUTE,
      config: { relightEveryTicks: 1, lanterns: [{ id: 'missing-lantern', pos: [0, 2, 0] }] },
    });

    await runSupervisorPasses(3);

    expect(augmentEidoverseWorldMock).toHaveBeenCalledTimes(3);
    const record = await getEidoverseControllerInstall('lamp-keeper');
    // The step succeeded every tick — #7628's whole point is that this alone
    // used to be reported as "ok" with no trace of the refusal anywhere.
    expect(record.lastOutcome.ok).toBe(true);
    expect(record.lastOutcome).toMatchObject({ delivered: 0, deliveryError: 'unknown entity id' });
    expect(record.consecutiveDeliveryFailures).toBe(3);
    // A run of refused deliveries disarms exactly like a run of failed steps.
    expect(record.armed).toBe(false);
    expect(record.disarmedReason).toMatch(/3 consecutive delivery failures: unknown entity id/);
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);

    // The projection every reader (route, mind tool, panel) actually consumes
    // carries the refusal as its own verdict, separate from the tick.
    const summary = summarizeControllerInstall(record);
    expect(summary.lastTickOk).toBe(true);
    expect(summary.lastDelivery).toEqual({ ok: false, delivered: 0, reason: 'unknown entity id' });
    expect(summary.lastCompletedDelivery).toEqual({ at: at(3 * MINUTE), tick: 3, ok: false, delivered: 0, reason: 'unknown entity id' });
  });

  it('does not disarm on a rewritten delivery — the world landed different args, not nothing', async () => {
    augmentEidoverseWorldMock.mockResolvedValue({
      success: true,
      applied: 1,
      operations: [{ verb: 'light', id: 'plaza-lantern', outcome: 'rewritten', proposed: { id: 'plaza-lantern' }, committed: { id: 'plaza-lantern', pos: [0, 1, 0] } }],
    });
    await install({
      id: 'lamp-keeper', controllerId: 'lantern-keeper', deliverEffects: true, tickIntervalMs: MINUTE,
      config: { relightEveryTicks: 1, lanterns: [{ id: 'plaza-lantern', pos: [0, 2, 0] }] },
    });

    await runSupervisorPasses(3);

    const record = await getEidoverseControllerInstall('lamp-keeper');
    expect(record.lastOutcome).toMatchObject({ ok: true, delivered: 1, deliveryError: null });
    expect(record.consecutiveDeliveryFailures).toBe(0);
    expect(record.armed).toBe(true);
    expect(summarizeControllerInstall(record).lastDelivery).toEqual({ ok: true, delivered: 1, reason: null });
  });
});

describe('a controller that goes wrong', () => {
  const brokenController = {
    id: 'broken-probe',
    configSchema: { safeParse: (config) => ({ success: true, data: config }) },
    createState: () => ({}),
    step: () => { throw new Error('boom'); },
  };
  const resolveBroken = async (id) => (id === 'broken-probe' ? brokenController : null);

  it('disarms after repeated failures instead of failing on a schedule forever', async () => {
    await install({ controllerId: 'broken-probe', tickIntervalMs: MINUTE }, { resolveDefinition: resolveBroken });

    await runSupervisorPasses(3, { resolveDefinition: resolveBroken });

    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.armed).toBe(false);
    expect(record.consecutiveFailures).toBe(3);
    expect(record.disarmedReason).toMatch(/3 consecutive failed ticks: step\(\) threw: boom/);

    // And a further pass does nothing at all, rather than continuing to throw.
    expect(await tickEidoverseControllers({ now: at(10 * MINUTE), resolveDefinition: resolveBroken }))
      .toMatchObject({ ticked: 0, due: 0 });
    // Disarming the last armed install moves the gate as surely as a retire
    // does, so the supervisor stands itself down instead of waking every
    // minute to find nothing to do until the next restart.
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);
  });

  it('disarms an install whose controller id this version no longer ships', async () => {
    await install({ controllerId: 'broken-probe', tickIntervalMs: MINUTE }, { resolveDefinition: resolveBroken });

    // The real registry, which has never heard of `broken-probe`.
    await runSupervisorPasses(1);

    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.armed).toBe(false);
    expect(record.disarmedReason).toMatch(/no controller is registered under "broken-probe" any more/);
  });
});

describe('the install store', () => {
  it('reads as empty on an install that has never installed one', async () => {
    const listed = await listEidoverseControllers();
    expect(listed.installs).toEqual([]);
    expect(listed.counts).toEqual({ total: 0, armed: 0, delivering: 0 });
  });

  it('rebuilds state on re-install, because state is shaped by the config that produced it', async () => {
    await install();
    await runSupervisorPasses(10);
    expect((await getEidoverseControllerInstall('plaza-beacon')).state.ticks).toBe(2);

    const reinstalled = await install({ config: { label: 'quay', pulseEveryTicks: 4 } }, { now: at(20 * MINUTE) });
    expect(reinstalled.install.state).toMatchObject({ label: 'quay', ticks: 0, pulses: 0 });
    // The tick ordinal is the supervisor's own count of attempts and survives.
    expect(reinstalled.install.tick).toBe(2);
    expect(reinstalled.install.installedAt).toBe(at(0));
  });

  it('does not silently re-arm a controller somebody deliberately quieted', async () => {
    await install();
    await setEidoverseControllerArmed('plaza-beacon', false, { now: at(MINUTE) });

    // `armed` defaults to true in the schema, so a re-install that never
    // mentions it must not read as a request to turn the controller back on.
    const quiet = await install({ config: { label: 'quay', pulseEveryTicks: 4 } }, { now: at(2 * MINUTE) });
    expect(quiet.install.armed).toBe(false);
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);

    const loud = await install({ armed: true, config: { label: 'quay', pulseEveryTicks: 4 } }, { now: at(3 * MINUTE) });
    expect(loud.install.armed).toBe(true);
    expect(isEidoverseControllerSupervisorRegistered()).toBe(true);
  });

  it('keeps accumulated state across a disarm and re-arm', async () => {
    await install();
    await runSupervisorPasses(10);

    await setEidoverseControllerArmed('plaza-beacon', false, { now: at(11 * MINUTE) });
    await runSupervisorPasses(10, { fromMs: 11 * MINUTE });
    expect((await getEidoverseControllerInstall('plaza-beacon')).state.ticks).toBe(2);

    await setEidoverseControllerArmed('plaza-beacon', true, { now: at(22 * MINUTE) });
    await runSupervisorPasses(10, { fromMs: 22 * MINUTE });
    expect((await getEidoverseControllerInstall('plaza-beacon')).state.ticks).toBe(4);
  });

  it('retires an install outright rather than parking it forever', async () => {
    await install();
    expect((await retireEidoverseController('plaza-beacon')).outcome).toBe('retired');
    expect(await getEidoverseControllerInstall('plaza-beacon')).toBeNull();
    expect((await retireEidoverseController('plaza-beacon')).outcome).toBe('unknown-install');
  });
});

// #7629: nothing read an install's config back, and a stored install was
// never revalidated against the definition it runs — the store's version
// stamp went unread, a config that stopped parsing kept stepping, and a mind
// had no way to change an inherited controller's config without destroying
// its accumulated state.
describe('revalidating a stored install against its definition (#7629)', () => {
  it('disarms rather than steps when the stored config no longer parses against its definition', async () => {
    // The install-time schema accepts `label`; a later "shipped schema
    // tightened" is simulated by resolving to a STRICTER schema at tick time
    // that the already-stored config fails.
    const loose = {
      id: 'drifted', configSchema: z.object({ label: z.string() }).strict(),
      createState: () => ({}), step: (state) => ({ state }),
    };
    const strict = {
      ...loose,
      configSchema: z.object({ label: z.string().max(3) }).strict(),
    };
    const resolveLoose = async (id) => (id === 'drifted' ? loose : null);
    const resolveStrict = async (id) => (id === 'drifted' ? strict : null);

    await install({ controllerId: 'drifted', tickIntervalMs: MINUTE, config: { label: 'too-long-now' } }, { resolveDefinition: resolveLoose });
    await runSupervisorPasses(1, { resolveDefinition: resolveStrict });

    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.armed).toBe(false);
    expect(record.tick).toBe(0);
    expect(record.disarmedReason).toMatch(/stored config no longer parses/);
    expect(record.config).toEqual({ label: 'too-long-now' });
  });

  it('applies and persists a newly-added configSchema default exactly once on an existing install\'s next tick', async () => {
    const v1 = {
      id: 'evolving', configSchema: z.object({ label: z.string() }).strict(),
      createState: () => ({ ticks: 0 }), step: (state) => ({ state: { ticks: state.ticks + 1 } }),
    };
    // v2 adds `boost` with a default — the shape a shipped-controller upgrade
    // takes per root AGENTS.md: installs upgrade on their own schedule.
    const v2 = {
      ...v1,
      configSchema: z.object({ label: z.string(), boost: z.number().int().default(3) }).strict(),
    };
    const resolveV1 = async (id) => (id === 'evolving' ? v1 : null);
    const resolveV2 = async (id) => (id === 'evolving' ? v2 : null);

    await install({ controllerId: 'evolving', tickIntervalMs: MINUTE, config: { label: 'plaza' } }, { resolveDefinition: resolveV1 });
    expect((await getEidoverseControllerInstall('plaza-beacon')).config).toEqual({ label: 'plaza' });

    await runSupervisorPasses(1, { resolveDefinition: resolveV2 });
    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.config).toEqual({ label: 'plaza', boost: 3 });
    expect(record.lastOutcome).toMatchObject({ ok: true });
  });

  it('fails the step and counts toward maxConsecutiveFailures when live state violates the definition\'s invariants', async () => {
    const guarded = {
      id: 'guarded', configSchema: z.object({}).strict(),
      createState: () => ({ count: 0 }),
      step: (state) => ({ state: { count: state.count + 1 } }),
      // Violates on every tick from the first one, so three passes accumulate
      // three consecutive failures rather than succeeding a while first.
      invariants: [function countNeverExceedsZero(state) { return state.count <= 0; }],
    };
    const resolveGuarded = async (id) => (id === 'guarded' ? guarded : null);

    await install({ controllerId: 'guarded', tickIntervalMs: MINUTE, config: {} }, { resolveDefinition: resolveGuarded });
    await runSupervisorPasses(3, { resolveDefinition: resolveGuarded });

    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.consecutiveFailures).toBe(3);
    expect(record.armed).toBe(false);
    expect(record.lastOutcome).toMatchObject({ ok: false });
    expect(record.lastOutcome.reason).toMatch(/invariant/);
    expect(record.disarmedReason).toMatch(/consecutive failed ticks/);
  });

  it('disarms rather than steps a store stamped with a schemaVersion newer than this build, and reports the file\'s own stamp', async () => {
    await install({ tickIntervalMs: MINUTE });

    const raw = await readJSONFile(storeFile(), null, { allowArray: false, strict: true });
    await atomicWrite(storeFile(), { ...raw, schemaVersion: raw.schemaVersion + 1 });

    expect((await listEidoverseControllers()).schemaVersion).toBe(raw.schemaVersion + 1);

    await runSupervisorPasses(1);
    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.armed).toBe(false);
    expect(record.tick).toBe(0);
    expect(record.disarmedReason).toMatch(/newer than this build/);
  });

  it("never downgrades a newer stamp when it writes, so the guard survives the disarm that fires it", async () => {
    await install({ tickIntervalMs: MINUTE });
    const raw = await readJSONFile(storeFile(), null, { allowArray: false, strict: true });
    const newer = raw.schemaVersion + 1;
    await atomicWrite(storeFile(), { ...raw, schemaVersion: newer });

    // The disarming pass persists the record, and that write must not re-stamp
    // the file with THIS build’s older constant — doing so would erase the only
    // signal the guard reads, leaving it a one-shot.
    await runSupervisorPasses(1);
    expect((await readJSONFile(storeFile(), null, { allowArray: false, strict: true })).schemaVersion).toBe(newer);

    // So a re-arm (another write path) still lands on a newer-stamped store,
    // and the next pass refuses again instead of stepping under this build’s rules.
    await setEidoverseControllerArmed("plaza-beacon", true, { now: at(MINUTE) });
    expect((await readJSONFile(storeFile(), null, { allowArray: false, strict: true })).schemaVersion).toBe(newer);

    await runSupervisorPasses(1, { fromMs: 2 * MINUTE });
    const record = await getEidoverseControllerInstall("plaza-beacon");
    expect(record.armed).toBe(false);
    expect(record.tick).toBe(0);
    expect(record.disarmedReason).toMatch(/newer than this build/);
  });
});

describe('updateEidoverseControllerConfig (#7629)', () => {
  it('changes config while the accumulated state survives — the "inherit and modify" verb, not a rebuild', async () => {
    await install();
    await runSupervisorPasses(10);
    const before = await getEidoverseControllerInstall('plaza-beacon');
    expect(before.state.ticks).toBe(2);

    const result = await updateEidoverseControllerConfig('plaza-beacon', { label: 'quay', pulseEveryTicks: 4 });
    expect(result.outcome).toBe('updated');
    expect(result.install.config).toEqual({ label: 'quay', pulseEveryTicks: 4, announce: false });
    // Unlike a re-install, state is untouched.
    expect(result.install.state).toEqual(before.state);
  });

  it('refuses a config the definition\'s schema rejects, leaving the install unchanged', async () => {
    await install();
    const result = await updateEidoverseControllerConfig('plaza-beacon', { label: 'plaza', pulseEveryTicks: 0 });
    expect(result.outcome).toBe('refused');
    expect(result.reasons[0]).toMatch(/^config\.pulseEveryTicks/);
    expect((await getEidoverseControllerInstall('plaza-beacon')).config).toMatchObject({ pulseEveryTicks: 2 });
  });

  it('reports unknown-install for an id nothing has installed', async () => {
    expect((await updateEidoverseControllerConfig('nope', {})).outcome).toBe('unknown-install');
  });
});

// #10818: proposals and latest-tick health cannot stand in for retained,
// completed outbound evidence. Drive persistence and projections together.
describe('completed outbound delivery evidence', () => {
  it('survives multiple quiet/failed ticks and restart, preserves arming/config edits, and resets on reinstall', async () => {
    await install({ tickIntervalMs: MINUTE, config: { label: 'plaza', pulseEveryTicks: 2, announce: true }, deliverEffects: true });
    const deliver = vi.fn(async () => ({ delivered: 1, error: null }));
    await runSupervisorPasses(3, { deliver });
    const completed = { at: at(2 * MINUTE), tick: 2, ok: true, delivered: 1, reason: null };
    expect(deliver).toHaveBeenCalledTimes(1);
    const quiet = summarizeControllerInstall(await getEidoverseControllerInstall('plaza-beacon'));
    expect(quiet.lastDelivery).toEqual({ ok: null, delivered: 0, reason: null });
    expect(quiet.lastCompletedDelivery).toEqual(completed);
    await updateEidoverseControllerConfig('plaza-beacon', { label: 'plaza', pulseEveryTicks: 100, announce: true }, { now: at(3 * MINUTE) });
    await runSupervisorPasses(2, { fromMs: 3 * MINUTE, deliver });
    const broken = { configSchema: z.record(z.unknown()), step: () => { throw new Error('example step failure'); } };
    await runSupervisorPasses(1, { fromMs: 5 * MINUTE, resolveDefinition: () => broken, deliver });
    expect((await getEidoverseControllerInstall('plaza-beacon')).lastCompletedDelivery).toEqual(completed);
    await setEidoverseControllerArmed('plaza-beacon', false, { now: at(6 * MINUTE) });
    await setEidoverseControllerArmed('plaza-beacon', true, { now: at(6 * MINUTE) });
    __resetEidoverseControllerRuntimeForTests();
    vi.resetModules();
    const restarted = await import('./eidoverseControllerRuntime.js');
    const record = await restarted.getEidoverseControllerInstall('plaza-beacon');
    expect(record.lastCompletedDelivery).toEqual(completed);
    expect(eidoverseControllerRecordSchema.safeParse(record).success).toBe(true);
    const listed = (await restarted.listEidoverseControllers()).installs[0];
    for (const projection of [summarizeControllerInstall(listed), summarizeControllerInstall(record, { includeState: true })]) {
      expect(projection.lastCompletedDelivery).toEqual(completed);
      expect(projection.lastDelivery).toEqual({ ok: null, delivered: 0, reason: null });
    }
    expect((await readJSONFile(storeFile(), null)).installs['plaza-beacon'].lastCompletedDelivery).toEqual(completed);
    const reinstalled = await restarted.installEidoverseController({ id: 'plaza-beacon', controllerId: 'ambient-beacon', config: {} }, { now: at(7 * MINUTE) });
    expect(reinstalled.install.lastCompletedDelivery).toBeNull();
    restarted.__resetEidoverseControllerRuntimeForTests();
  });

  it('never creates completed outbound evidence from local notes or disabled delivery', async () => {
    const deliver = vi.fn(async () => ({ delivered: 1, error: null }));
    await install({ tickIntervalMs: MINUTE, config: { pulseEveryTicks: 1, announce: false }, deliverEffects: true });
    await install({ id: 'disabled-beacon', tickIntervalMs: MINUTE, config: { pulseEveryTicks: 1, announce: true }, deliverEffects: false });
    await runSupervisorPasses(2, { deliver });
    expect(deliver).not.toHaveBeenCalled();
    for (const record of (await listEidoverseControllers()).installs) {
      expect(record.state.pulses).toBe(2);
      expect(record.recentEffects).toHaveLength(2);
      expect(record.lastCompletedDelivery).toBeNull();
    }
  });

  it('replaces success with partial refusal and then thrown failure while retaining acknowledged counts', async () => {
    const definition = { id: 'example-outbound', configSchema: z.object({}).strict(), createState: () => ({}), step: (state) => ({ state, effects: [
      { kind: 'say', text: 'example acknowledgement' },
      { kind: 'augment', operations: [{ verb: 'light', args: { id: 'example-lamp' } }] },
    ] }) };
    await install({ controllerId: definition.id, tickIntervalMs: MINUTE, config: {}, deliverEffects: true }, { resolveDefinition: () => definition });
    sayInEidoverseWorldMock.mockResolvedValue(undefined);
    augmentEidoverseWorldMock.mockResolvedValueOnce({ success: true, applied: 1, operations: [] })
      .mockResolvedValueOnce({ success: false, applied: 1, operations: [{ outcome: 'refused', reason: 'example partial refusal' }] })
      .mockRejectedValue(new Error('example transport failure'));
    await runSupervisorPasses(1, { resolveDefinition: () => definition });
    expect((await getEidoverseControllerInstall('plaza-beacon')).lastCompletedDelivery).toEqual({ at: at(MINUTE), tick: 1, ok: true, delivered: 2, reason: null });
    await runSupervisorPasses(1, { fromMs: MINUTE, resolveDefinition: () => definition });
    expect((await getEidoverseControllerInstall('plaza-beacon')).lastCompletedDelivery).toEqual({ at: at(2 * MINUTE), tick: 2, ok: false, delivered: 2, reason: 'example partial refusal' });
    await runSupervisorPasses(2, { fromMs: 2 * MINUTE, resolveDefinition: () => definition });
    const record = await getEidoverseControllerInstall('plaza-beacon');
    expect(record.lastCompletedDelivery).toEqual({ at: at(4 * MINUTE), tick: 4, ok: false, delivered: 1, reason: 'example transport failure' });
    expect(record.consecutiveDeliveryFailures).toBe(3);
    expect(record.armed).toBe(false);
    expect(isEidoverseControllerSupervisorRegistered()).toBe(false);
  });

  it('keeps in-flight history unchanged and rejects completion after reinstall or a different outcome with the same tick', async () => {
    await install({ tickIntervalMs: MINUTE, config: { pulseEveryTicks: 1, announce: true }, deliverEffects: true });
    await runSupervisorPasses(1, { deliver: async () => ({ delivered: 1, error: null }) });
    const completed = (await getEidoverseControllerInstall('plaza-beacon')).lastCompletedDelivery;
    for (const replace of ['different-outcome', 'reinstall']) {
      let finish;
      let started;
      const entered = new Promise((resolve) => { started = resolve; });
      const pending = tickEidoverseControllers({ now: at(replace === 'reinstall' ? 3 * MINUTE : 2 * MINUTE), deliver: () => {
        started();
        return new Promise((resolve) => { finish = resolve; });
      } });
      await entered;
      expect((await getEidoverseControllerInstall('plaza-beacon')).lastCompletedDelivery).toEqual(completed);
      if (replace === 'reinstall') {
        await install({ tickIntervalMs: MINUTE, deliverEffects: true }, { now: at(3 * MINUTE) });
      } else {
        const raw = await readJSONFile(storeFile(), null);
        raw.installs['plaza-beacon'].lastOutcome.at = at(2 * MINUTE + 1);
        await atomicWrite(storeFile(), raw);
      }
      finish({ delivered: 2, error: null });
      await pending;
      const record = await getEidoverseControllerInstall('plaza-beacon');
      expect(record.lastCompletedDelivery).toEqual(replace === 'reinstall' ? null : completed);
      expect(record.lastOutcome?.delivered ?? 0).toBe(0);
    }
  });
});