iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / mind / processor.test.tsmain at 949894f

// The mind's processor: how a mind is born from the repos its config names, and how a commit of
// one of them publishes the mind's code. The processor runs here with repos and a publisher that
// record what they are asked.
import type { ItxExpression } from "iterate/expression";
import { identityHashOf, type SignedRecord } from "iterate/mind-identity";
import { sha256Hex } from "core-itx";
import { ProcessorEngine, type StreamEvent, type StreamEventInput } from "iterate/stream/processor";
import { memoryStorage, memoryStream } from "iterate/stream/test-support";
import { expect, test, vi } from "vitest";
import { newIdentityLog } from "../../../lib/src/test-support/identity-log.ts";
import { MindContract, type MindState } from "./contract.ts";
import { MindProcessor } from "./processor.ts";
import type { MindPublisher } from "./publication.ts";

test("a commit of a repo that the mind's code imports from publishes the newest commit of every repo of the tree, and names them", async () => {
  const mind = mindOf({
    owes: false,
    probed: aConfig,
    repos: {
      "/repos/config": {
        "worker.ts": `import { init } from "@repos/stdlib/init.ts"; export default class { ready = init(); }`,
      },
      "/repos/stdlib": { "init.ts": "export const init = () => true;" },
      // nothing imports from it: a publication never reads it
      "/repos/kernel": { "README.md": "what only a deploy can change" },
    },
  });
  // a push to stdlib: its commit's fact asks for a publication
  const pushed = { path: "/repos/stdlib", commitOid: "stdlib@1", offset: 9 };
  mind.deliver({ ...mind.state, newestAsking: pushed, unpublishedCommits: [pushed] });
  await mind.settled();

  expect(mind.published).toEqual([
    "files /repos/config",
    "files /repos/stdlib",
    "identity stdlib/init.ts",
    "identity config/worker.ts",
    "probe",
    "keep config/worker.ts",
    "append",
  ]);
  const [modules, pointer, updated] = mind.platformFacts;
  const commits = { "/repos/config": "seed", "/repos/stdlib": "stdlib@1" };
  expect(updated).toMatchObject({
    type: "events.iterate.com/mind/worker-updated",
    payload: { trigger: { path: "/repos/stdlib", commitOid: "stdlib@1" }, commits, generation: 9 },
  });
  // the pointer names the tree by its commits, so a load reads the same files every time
  expect(modules).toMatchObject({ payload: { match: "itx.config.modules" } });
  expect(pointer).toMatchObject({
    payload: {
      match: "itx.config",
      target: [
        "itx",
        "builtins",
        "workers",
        [
          "get",
          {
            source: [
              "itx",
              "config",
              ["modules", { commits, entry: { repo: "/repos/config", module: "worker.ts" } }],
            ],
            mainModule: "config/worker.ts",
          },
        ],
      ],
    },
  });
  expect(mind.current).toMatchObject({ published: { commits }, unpublishedCommits: [] });
});

test("a commit asks for a publication when its repo is part of what the mind runs; any repo's commit does before the first publication and after a refused one", async () => {
  const root = memoryStream("/");
  const committed = (path: string, commitOid: string) => ({
    type: "events.iterate.com/repo/commit-completed",
    payload: { path, commitOid, message: "a commit", changedPaths: [] },
  });
  // A new engine on new storage reduces the whole log, through the contract's own `consumes`.
  // It answers the commits whose publication is owed, each by the offset of its fact.
  const owedAfter = async (...events: StreamEventInput[]) => {
    root.stream.append(...events);
    const engine = new ProcessorEngine(reducingProcessor(), {
      stream: root.stream,
      storage: memoryStorage(),
    });
    const { unpublishedCommits } = (await engine.snapshot()).state;
    return Object.fromEntries(
      unpublishedCommits.map(({ path, commitOid, offset }) => [`${path} ${commitOid}`, offset]),
    );
  };
  /** The outcome of the publication that the commit fact at offset `generation` asked for. */
  const outcome = (type: string, generation: number, payload: object) => ({
    type: `events.iterate.com/mind/${type}`,
    payload: { trigger: { path: "/repos/config", commitOid: "c1" }, generation, ...payload },
  });

  // nothing runs yet: every repo's commit may be what makes the first publication possible
  const first = await owedAfter(
    configuredEvent({}),
    committed("/repos/stdlib", "s1"),
    committed("/repos/config", "c1"),
  );
  expect(Object.keys(first)).toEqual(["/repos/stdlib s1", "/repos/config c1"]);

  // the publication that the config's commit asked for runs config and stdlib
  const published = outcome("worker-updated", first["/repos/config c1"]!, {
    commits: { "/repos/config": "c1", "/repos/stdlib": "s1" },
    modules: {},
  });
  // The kernel's repo is not part of what runs, and a repo deeper than /repos/<name> never is:
  // their commits ask for nothing. Stdlib's does.
  const running = await owedAfter(
    published,
    committed("/repos/kernel", "k1"),
    committed("/repos/github.com/iterate/core", "g1"),
    committed("/repos/stdlib", "s2"),
  );
  expect(Object.keys(running)).toEqual(["/repos/stdlib s1", "/repos/stdlib s2"]);

  // after a refused publication, a commit of a repo outside the tree may be what mends it
  const refused = outcome("worker-update-failed", running["/repos/stdlib s2"]!, {
    error: "config/worker.ts imports from /repos/words, which has no commit on main",
  });
  expect(Object.keys(await owedAfter(refused, committed("/repos/words", "w1")))).toEqual([
    "/repos/stdlib s1",
    "/repos/words w1",
  ]);
});

test("a mind is born by making the repos that its config names and cloning the ones with an origin, once; its first publication is what creates it", async () => {
  const mind = mindOf({ owes: false });
  const unborn: MindState = {
    ...mind.state,
    creation: { status: "requested", offset: 2 },
    configured: configuredEvent({
      repos: [
        { path: "/repos/config", origin: null },
        { path: "/repos/stdlib", origin: "https://git.example.org/repos/stdlib" },
      ],
    }).payload as MindState["configured"],
    repos: {},
    repoTips: {},
    newestAsking: null,
    published: null,
    lastPublicationFactOffset: null,
  };
  mind.deliver(unborn);
  await mind.settled();
  // a second pass of the same incarnation, before the repos' facts reached the state
  mind.deliver(unborn);
  await mind.settled();

  expect(mind.root.did).toEqual([
    "create /repos/config",
    "create /repos/stdlib",
    "setOrigin /repos/stdlib https://git.example.org/repos/stdlib",
    'pull /repos/stdlib {"remote":"https://git.example.org/repos/stdlib"}',
  ]);
  // its repos are there and nothing runs yet: the mind is not created
  expect(mind.facts).toEqual([]);

  // the first publication landed: the next pass creates the mind
  mind.deliver({
    ...unborn,
    published: { commits: { "/repos/config": "seed" } },
    lastPublicationFactOffset: 7,
  });
  await mind.settled();
  expect(mind.facts.map((fact) => fact.type)).toEqual([
    "events.iterate.com/itx/ingress-configured",
    "events.iterate.com/mind/created",
  ]);
});

test("a birth that failed is asked for again after bounded waits in one incarnation, and its next try clones the repo whose clone failed", async () => {
  vi.useFakeTimers();
  try {
    const mind = mindOf({ owes: false });
    const unborn: MindState = {
      ...mind.state,
      creation: { status: "requested", offset: 2 },
      configured: configuredEvent({
        repos: [{ path: "/repos/config", origin: "https://git.example.org/repos/config-template" }],
      }).payload as MindState["configured"],
      repos: {},
      repoTips: {},
      newestAsking: null,
      published: null,
      lastPublicationFactOffset: null,
    };
    const failed: MindState = { ...unborn, creation: { status: "failed", offset: 3 } };
    const typesOf = () => mind.facts.map((fact) => fact.type.split("/").slice(1).join("/"));
    // a new mind's stack is still being deployed at its first request: the repo cannot be made
    mind.root.refusals.push(
      "create: Alchemy worker is being deployed",
      "create: Alchemy worker is being deployed",
    );
    mind.deliver(unborn);
    await mind.settled();
    expect(mind.facts.at(-1)).toMatchObject({
      type: "events.iterate.com/mind/create-failed",
      payload: { error: "Alchemy worker is being deployed" },
    });
    // the first ask comes at once, and it fails the same way
    mind.deliver(failed);
    await mind.settled();
    mind.deliver(unborn);
    await mind.settled();
    expect(typesOf()).toEqual(["mind/create-failed", "mind/create-requested", "mind/create-failed"]);
    // the second ask waits 5 s, and a pass in between asks for nothing more
    mind.deliver(failed);
    mind.deliver(failed);
    await vi.advanceTimersByTimeAsync(4_900);
    expect(typesOf()).toHaveLength(3);
    await vi.advanceTimersByTimeAsync(100);
    await mind.settled();
    expect(typesOf().at(-1)).toBe("mind/create-requested");
    // this try makes the repo, and its clone fails: the birth fails, and the try after it clones again
    mind.root.refusals.push("pull: the origin did not answer");
    mind.deliver(unborn);
    await mind.settled();
    expect(mind.facts.at(-1)).toMatchObject({ payload: { error: "the origin did not answer" } });
    mind.deliver(failed);
    await vi.advanceTimersByTimeAsync(15_000);
    await mind.settled();
    mind.deliver(unborn);
    await mind.settled();
    expect(mind.root.did).toEqual([
      "create /repos/config",
      "setOrigin /repos/config https://git.example.org/repos/config-template",
      "setOrigin /repos/config https://git.example.org/repos/config-template",
      'pull /repos/config {"remote":"https://git.example.org/repos/config-template"}',
    ]);
    // THE ROW OF WAITS ENDS: three more asks (30 s, 60 s, 120 s), then none in this incarnation
    const asks = () => typesOf().filter((type) => type === "mind/create-requested").length;
    expect(asks()).toBe(3);
    for (const wait of [30_000, 60_000, 120_000]) {
      mind.deliver(failed);
      await vi.advanceTimersByTimeAsync(wait);
      await mind.settled();
    }
    expect(asks()).toBe(6);
    mind.deliver(failed);
    await vi.advanceTimersByTimeAsync(600_000);
    await mind.settled();
    expect(asks()).toBe(6);
    // a new incarnation starts the row again
    mind.restart();
    mind.deliver(failed);
    await mind.settled();
    expect(asks()).toBe(7);
  } finally {
    vi.useRealTimers();
  }
});

test("a birth also makes the repos that the entry repo's package.json names, each cloned from beside where the entry repo came from", async () => {
  const mind = mindOf({
    owes: false,
    repos: {
      "/repos/config": {
        "package.json": JSON.stringify({
          main: "worker.ts",
          dependencies: { yjs: "13.6.33", "@repos/stdlib": "../stdlib", "@repos/dash": "../dash" },
        }),
      },
    },
  });
  const unborn: MindState = {
    ...mind.state,
    creation: { status: "requested", offset: 2 },
    // what a deploy names: the kernel's repo and the entry repo, each with where it comes from
    configured: configuredEvent({
      repos: [
        { path: "/repos/kernel", origin: "https://git.example.org/repos/kernel" },
        { path: "/repos/config", origin: "https://git.example.org/repos/config-template" },
      ],
    }).payload as MindState["configured"],
    repos: {},
    repoTips: {},
    newestAsking: null,
    published: null,
    lastPublicationFactOffset: null,
  };
  mind.deliver(unborn);
  await mind.settled();

  expect(mind.root.did).toEqual([
    "create /repos/kernel",
    "setOrigin /repos/kernel https://git.example.org/repos/kernel",
    'pull /repos/kernel {"remote":"https://git.example.org/repos/kernel"}',
    "create /repos/config",
    "setOrigin /repos/config https://git.example.org/repos/config-template",
    'pull /repos/config {"remote":"https://git.example.org/repos/config-template"}',
    "create /repos/stdlib",
    "setOrigin /repos/stdlib https://git.example.org/repos/stdlib",
    'pull /repos/stdlib {"remote":"https://git.example.org/repos/stdlib"}',
    "create /repos/dash",
    "setOrigin /repos/dash https://git.example.org/repos/dash",
    'pull /repos/dash {"remote":"https://git.example.org/repos/dash"}',
  ]);
});

test("an entry repo that was cloned from nowhere has its named repos made empty, and a mind that is created fetches nothing for a new name", async () => {
  const named = {
    "/repos/config": {
      "package.json": JSON.stringify({ dependencies: { "@repos/stdlib": "../stdlib" } }),
    },
  };
  const empty = mindOf({ owes: false, repos: named });
  empty.deliver({
    ...empty.state,
    creation: { status: "requested", offset: 2 },
    configured: configuredEvent({
      repos: [{ path: "/repos/config", origin: null }],
    }).payload as MindState["configured"],
    repos: {},
    repoTips: {},
    newestAsking: null,
    published: null,
    lastPublicationFactOffset: null,
  });
  await empty.settled();
  expect(empty.root.did).toEqual(["create /repos/config", "create /repos/stdlib"]);

  // after birth a name the mind has no repo for is nobody's to fetch: the publication says so
  const alive = mindOf({ owes: false, repos: named });
  alive.deliver(alive.state);
  await alive.settled();
  expect(alive.root.did.filter((did) => /^(create|setOrigin|pull) /.test(did))).toEqual([]);
});

test("a publication keeps the entry module's files after its probe passed and before it appends the pointer", async () => {
  const mind = mindOf({ owes: true, head: "seed", probed: aConfig });
  mind.deliver(mind.state);
  await mind.settled();
  expect({
    published: mind.published,
    facts: mind.platformFacts.map((fact) => fact.type),
  }).toEqual({
    published: [
      "files /repos/config",
      "identity config/worker.ts",
      "probe",
      "keep config/worker.ts",
      "append",
    ],
    facts: [
      "events.iterate.com/itx/rewrite-rule-configured",
      "events.iterate.com/itx/rewrite-rule-configured",
      "events.iterate.com/mind/worker-updated",
    ],
  });
});

test("a commit whose class lacks an abstract method is published, and its worker-updated names what it lacks, once for the commit; a commit with all three names nothing", async () => {
  const lacking = mindOf({
    owes: true,
    head: "seed",
    probed: { ...aConfig, missing: ["fetch", "processEvent"] },
  });
  lacking.deliver(lacking.state);
  await lacking.settled();
  expect(lacking.platformFacts.at(-1)).toMatchObject({
    type: "events.iterate.com/mind/worker-updated",
    idempotencyKey: "mind/publication:5",
    payload: {
      trigger: { path: "/repos/config", commitOid: "seed" },
      commits: { "/repos/config": "seed" },
      missing: ["fetch", "processEvent"],
    },
  });
  const whole = mindOf({ owes: true, head: "seed", probed: aConfig });
  whole.deliver(whole.state);
  await whole.settled();
  expect(whole.platformFacts.at(-1)).toMatchObject({
    type: "events.iterate.com/mind/worker-updated",
  });
  expect(whole.platformFacts.at(-1)!.payload).not.toHaveProperty("missing");
});

test("a publication whose probe is refused keeps nothing", async () => {
  const mind = mindOf({
    owes: true,
    head: "seed",
    probed: { ...aConfig, configEntrypoint: false },
  });
  mind.deliver(mind.state);
  await mind.settled();
  expect(mind).toMatchObject({
    published: ["files /repos/config", "identity config/worker.ts", "probe", "append"],
    platformFacts: [{ type: "events.iterate.com/mind/worker-update-failed" }],
  });
});

test("a head read behind the commit's own fact, its parent, is read again, and the commit publishes", async () => {
  vi.useFakeTimers();
  try {
    const mind = mindOf({ owes: true, head: ["parent", "seed"], probed: aConfig });
    mind.deliver(mind.state);
    await vi.advanceTimersByTimeAsync(6_000);
    await mind.settled();
    expect({
      headReads: mind.headReads,
      facts: mind.platformFacts.map((fact) => fact.type),
    }).toEqual({
      headReads: 2,
      facts: [
        "events.iterate.com/itx/rewrite-rule-configured",
        "events.iterate.com/itx/rewrite-rule-configured",
        "events.iterate.com/mind/worker-updated",
      ],
    });
  } finally {
    vi.useRealTimers();
  }
});

test("a commit whose newer commit's fact came is still a supersession, with its words, and its head is not read", async () => {
  const mind = mindOf({ owes: false, head: "newer", probed: aConfig });
  mind.deliver(mind.owing("seed", 5, { commitOid: "newer", offset: 8 }));
  await mind.settled();
  expect({
    headReads: mind.headReads,
    facts: mind.platformFacts.map((fact) => fact.type),
    first: mind.platformFacts[0],
  }).toEqual({
    // the newer commit's own publication reads it once
    headReads: 1,
    facts: [
      "events.iterate.com/mind/worker-update-failed",
      "events.iterate.com/itx/rewrite-rule-configured",
      "events.iterate.com/itx/rewrite-rule-configured",
      "events.iterate.com/mind/worker-updated",
    ],
    first: superseded("seed", 5, "newer"),
  });
});

test("a commit left owed by its bounded give-up, and overtaken by a newer commit that published, is settled at the next incarnation with one event and no read", async () => {
  vi.useFakeTimers();
  try {
    // nine reads behind the seed's fact, then main at the newer commit
    const heads = [...Array.from({ length: 9 }, () => "parent"), "newer"];
    const mind = mindOf({ owes: true, head: heads, probed: aConfig });
    mind.deliver(mind.state);
    await vi.advanceTimersByTimeAsync(10 * 60_000);
    await mind.settled();
    expect(mind.current).toMatchObject({ unpublishedCommits: [{ commitOid: "seed", offset: 5 }] });
    // the newer commit's fact, in the same incarnation: it publishes, and the seed stays owed
    const newer = { path: "/repos/config", commitOid: "newer", offset: 8 };
    mind.deliver({
      ...mind.current,
      repoTips: { "/repos/config": { commitOid: "newer", offset: 8 } },
      newestAsking: newer,
      unpublishedCommits: [...mind.current.unpublishedCommits, newer],
    });
    await vi.advanceTimersByTimeAsync(1_000);
    await mind.settled();
    expect(mind.current).toMatchObject({
      published: { commits: { "/repos/config": "newer" } },
      unpublishedCommits: [{ commitOid: "seed", offset: 5 }],
    });
    const before = { reads: mind.headReads, facts: mind.platformFacts.length };
    mind.restart();
    mind.deliver(mind.current);
    await vi.advanceTimersByTimeAsync(1_000);
    await mind.settled();
    expect({
      reads: mind.headReads - before.reads,
      facts: mind.platformFacts.slice(before.facts),
      owed: mind.current.unpublishedCommits,
    }).toEqual({ reads: 0, facts: [superseded("seed", 5, "newer")], owed: [] });
  } finally {
    vi.useRealTimers();
  }
});

test("a checkpoint of the older build that holds an owed commit a newer one overtook settles it at its first wake, with one event and no read", async () => {
  const mind = mindOf({ owes: false, head: "newer", probed: aConfig });
  // a state that owes the seed (offset 5) while a newer commit (offset 8) is the tip and published
  const checkpoint: MindState = {
    ...mind.state,
    repoTips: { "/repos/config": { commitOid: "newer", offset: 8 } },
    newestAsking: { path: "/repos/config", commitOid: "newer", offset: 8 },
    unpublishedCommits: [{ path: "/repos/config", commitOid: "seed", offset: 5 }],
    published: { commits: { "/repos/config": "newer" } },
  };
  mind.deliver(checkpoint);
  await mind.settled();
  expect({
    reads: mind.headReads,
    facts: mind.platformFacts,
    owed: mind.current.unpublishedCommits,
  }).toEqual({ reads: 0, facts: [superseded("seed", 5, "newer")], owed: [] });
});

test("a head that stays behind is read on the publication's bounded waits, each give-up is said as unavailable, and the commit stays owed", async () => {
  vi.useFakeTimers();
  try {
    const mind = mindOf({ owes: true, head: "parent", probed: aConfig });
    mind.deliver(mind.state);
    // three runs of three reads (0, 5 and 30 s), 30 s apart: 165 s
    await vi.advanceTimersByTimeAsync(10 * 60_000);
    await mind.settled();
    const failed = {
      type: "events.iterate.com/mind/worker-update-failed",
      payload: {
        trigger: { path: "/repos/config", commitOid: "seed" },
        generation: 5,
        error: "main of /repos/config read parent, not seed, and no newer commit of it is known",
        unavailable: true,
      },
    };
    expect({ headReads: mind.headReads, facts: mind.platformFacts }).toEqual({
      headReads: 9,
      facts: [failed, failed, failed],
    });
  } finally {
    vi.useRealTimers();
  }
});

test("the first wake of an incarnation gives the root what refreshes the persons' grants once a day, and a second pass does not again", async () => {
  const mind = mindOf({ owes: false });
  mind.deliver(mind.state);
  mind.deliver(mind.state);
  await mind.settled();
  expect(mind).toMatchObject({
    root: {
      did: [
        // the row fans out: a day whose refresh fails holds no later day
        "row grant-refresh for events.iterate.com/secret/grants-refresh-due, ordered false: itx.builtins.secrets.refreshGrants",
        "schedule grant-refresh every 24 h: events.iterate.com/secret/grants-refresh-due",
      ],
    },
  });
});

test.for([
  ["a schedule of the mind's own under the key is left as it is", { schedule: true }, "row"],
  ["a row that is there is not written again", { row: true }, "schedule"],
] as const)("%s", async ([, there, written]) => {
  const mind = mindOf({ owes: false, there });
  mind.deliver(mind.state);
  await mind.settled();
  expect(mind.root.did.map((done) => done.split(" ")[0])).toEqual([written]);
});

test("a schedule under the key whose fire failed fires no more, so it is set again as it is defined, with the mind's own period", async () => {
  const mind = mindOf({ owes: false, there: { schedule: "failed", row: true } });
  mind.deliver(mind.state);
  await mind.settled();
  expect(mind).toMatchObject({
    root: {
      did: ["schedule grant-refresh every 6 h: events.iterate.com/secret/grants-refresh-due"],
    },
  });
});

test("a root that stays awake looks again an hour after its last look: a schedule that was cancelled since is set again, and within the hour nothing is asked", async () => {
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // a mind's own schedule under the key (a hold) and the row: the first look writes nothing
    const mind = mindOf({ owes: false, there: { schedule: true, row: true } });
    mind.deliver(mind.state);
    await mind.settled();
    // the hold is cancelled, and the root's object does not start anew: its bridges keep it awake
    mind.root.schedule = undefined;
    vi.setSystemTime(Date.now() + 59 * 60_000);
    mind.deliver(mind.state);
    await mind.settled();
    const withinTheHour = [...mind.root.did];
    vi.setSystemTime(Date.now() + 2 * 60_000);
    mind.deliver(mind.state);
    await mind.settled();

    expect({ withinTheHour, afterIt: mind.root.did }).toEqual({
      withinTheHour: [],
      afterIt: ["schedule grant-refresh every 24 h: events.iterate.com/secret/grants-refresh-due"],
    });
  } finally {
    vi.useRealTimers();
  }
});

test("the state keeps the mind's config as the latest `mind/configured` says it: its repos, its entry and the kernel's commit", async () => {
  // a new engine on new storage reduces the whole log, through the contract's own `consumes`
  const root = memoryStream("/");
  const configuredAfter = async (events: StreamEventInput[]) => {
    root.stream.append(...events);
    const engine = new ProcessorEngine(reducingProcessor(), {
      stream: root.stream,
      storage: memoryStorage(),
    });
    return (await engine.snapshot()).state.configured;
  };
  expect(await configuredAfter([])).toBeNull();
  expect(await configuredAfter([configuredEvent({})])).toMatchObject({
    zones: ["example.com"],
    signingKey: "REDACTED",
    repos: [{ path: "/repos/config", origin: null }],
    entry: { repo: "/repos/config", module: "worker.ts" },
    kernel: { commit: "a".repeat(40), dirty: false },
  });
  // a deploy from a newer kernel commit: the state says the newer one
  const newer = { commit: "b".repeat(40), dirty: true };
  expect(await configuredAfter([configuredEvent({ kernel: newer })])).toMatchObject({
    kernel: newer,
  });
});

test("the root keeps a log for each mind id and never empties one: after one id's genesis, another id's genesis and a further record of the first, it holds both logs, whatever the deploys named", async () => {
  const [first, other] = [await newIdentityLog(), await newIdentityLog()];
  const second = await first.next(first.genesis, { alsoKnownAs: ["did:example:ada"] });
  const third = await first.next(second, { alsoKnownAs: [] });
  const deployed = (mindId: string, _versionId: string) => [configuredEvent({ mindId })];
  const accepted = async (signed: SignedRecord, mind: string) => ({
    type: "events.iterate.com/mind/identity-record-accepted",
    // as the append boundary stamps the platform's own append
    source: { platform: true as const },
    payload: {
      mind,
      hash: await identityHashOf(signed.record),
      record: signed.record,
      signatures: signed.signatures,
      signedBy: [],
    },
  });
  const root = memoryStream("/");
  // a new engine on new storage reduces the whole log, through the contract's own `consumes`
  const identitiesAfter = async (...events: StreamEventInput[]) => {
    root.stream.append(...events);
    const processor = reducingProcessor();
    const engine = new ProcessorEngine(processor, {
      stream: root.stream,
      storage: memoryStorage(),
    });
    return (await engine.snapshot()).state.identities;
  };
  const born = {
    head: first.mind,
    position: 1,
    current: JSON.parse(first.genesis.record),
    refused: null,
  };
  // a record folds into the log of its own mind id, with no deploy before it
  expect(await identitiesAfter(await accepted(first.genesis, first.mind))).toEqual({
    [first.mind]: born,
  });
  // A deploy names the first id, then the other id, then the first again by the Worker's first
  // version, whose record the log holds already. None of that touches a log.
  const otherBorn = {
    head: other.mind,
    position: 1,
    current: JSON.parse(other.genesis.record),
    refused: null,
  };
  expect(
    await identitiesAfter(
      ...deployed(first.mind, "version-1"),
      ...deployed(other.mind, "version-2"),
      await accepted(other.genesis, other.mind),
      ...deployed(first.mind, "version-1"),
    ),
  ).toEqual({ [first.mind]: born, [other.mind]: otherBorn });
  // the third record before the second is not the next: it stays in the log, and is not folded
  expect(await identitiesAfter(await accepted(third, first.mind))).toMatchObject({
    [first.mind]: { position: 1 },
  });
  const grown = {
    head: await identityHashOf(second.record),
    position: 2,
    current: JSON.parse(second.record),
    refused: null,
  };
  expect(await identitiesAfter(await accepted(second, first.mind))).toEqual({
    [first.mind]: grown,
    [other.mind]: otherBorn,
  });
  // an event of either type that the platform did not write is passed over
  const { source: _stamp, ...unstamped } = await accepted(third, first.mind);
  expect(
    await identitiesAfter(unstamped, {
      type: "events.iterate.com/mind/identity-record-refused",
      payload: { mind: first.mind, reason: "forged", message: "a sentence" },
    }),
  ).toEqual({ [first.mind]: grown, [other.mind]: otherBorn });
  const [refusedEvent] = await root.stream.append({
    type: "events.iterate.com/mind/identity-record-refused",
    source: { platform: true },
    payload: { mind: first.mind, reason: "not-next", message: "a sentence" },
  });
  expect(await identitiesAfter()).toEqual({
    [first.mind]: { ...grown, refused: { offset: refusedEvent!.offset, reason: "not-next" } },
    [other.mind]: otherBorn,
  });
  // the same record again, as an append that was not said to be stored: nothing changes
  expect(await identitiesAfter(await accepted(second, first.mind))).toMatchObject({
    [first.mind]: { position: 2 },
  });
});

test("a root born before the identity events gets them: at its first wake its own row takes the contract's types, so an identity event is in the batch that its span of the log is delivered as", async () => {
  const log = await newIdentityLog();
  const deployed = [configuredEvent({ mindId: log.mind })];
  // THE ROOT AS A BUILD BEFORE THE IDENTITY EVENTS LEFT IT: its own row with the event types of
  // its birth, and a checkpoint of contract version 1, whose state has no `identities`.
  const { root, storage, row, pushed } = rootWithRow([
    ...MindContract.consumes.filter(
      (type) =>
        type !== "events.iterate.com/mind/identity-record-accepted" &&
        type !== "events.iterate.com/mind/identity-record-refused",
    ),
    "events.iterate.com/itx/woken",
  ]);
  const before = (await root.stream.append({
    type: "events.iterate.com/mind/sandbox-image-configured",
    payload: { image: null },
  })) as StreamEvent[];
  const { identities: _absent, ...stateOfVersion1 } = MindContract.stateSchema.parse({});
  storage.write(
    "mind",
    { reducerVersion: "1", reducedThroughOffset: before.at(-1)!.offset },
    stateOfVersion1,
    true,
  );
  let incarnation = incarnationOf({ root, storage, row });

  // THE DEPLOY OF THIS CODE: the root wakes, and its row is written once
  await pushed(incarnation, [{ type: "events.iterate.com/itx/woken", payload: {} }, ...deployed]);
  await incarnation.settled();
  expect(row).toMatchObject({
    did: ["processors.enable mind"],
    written: 1,
    consumes: [...MindContract.consumes, "events.iterate.com/itx/woken"],
  });

  // THE GENESIS, THEN AN ORDINARY EVENT, in one span of the log, as a row delivers them. With
  // the row of the root's birth the genesis would not be in the batch, and the checkpoint
  // would pass it.
  await pushed(incarnation, [
    {
      type: "events.iterate.com/mind/identity-record-accepted",
      source: { platform: true },
      payload: {
        mind: log.mind,
        hash: log.mind,
        record: log.genesis.record,
        signatures: log.genesis.signatures,
        signedBy: [],
      },
    },
    { type: "events.iterate.com/mind/sandbox-image-configured", payload: { image: null } },
  ]);
  expect((await incarnation.engine.snapshot()).state.identities).toMatchObject({
    [log.mind]: { head: log.mind, position: 1 },
  });
  // a restart: the checkpoint holds it, and the row is right, so it is not written again
  incarnation = incarnationOf({ root, storage, row });
  await pushed(incarnation, [{ type: "events.iterate.com/itx/woken", payload: {} }]);
  await incarnation.settled();
  expect((await incarnation.engine.snapshot()).state.identities).toMatchObject({
    [log.mind]: { head: log.mind, position: 1 },
  });
  expect(row).toMatchObject({ did: Array(2).fill("processors.enable mind"), written: 1 });
});

test("a root that could not look at its own row looks again at its next pass, and then no more in that incarnation", async () => {
  const { root, storage, row, pushed } = rootWithRow([
    ...MindContract.consumes,
    "events.iterate.com/itx/woken",
  ]);
  row.down = true;
  const incarnation = incarnationOf({ root, storage, row });
  const pass = {
    type: "events.iterate.com/mind/sandbox-image-configured",
    payload: { image: null },
  };
  await pushed(incarnation, [pass]);
  await incarnation.settled();
  expect(row).toMatchObject({ did: [] });
  row.down = false;
  await pushed(incarnation, [pass]);
  await incarnation.settled();
  await pushed(incarnation, [pass]);
  await incarnation.settled();
  expect(row).toMatchObject({ did: ["processors.enable mind"], written: 0 });
});

test("the latest `mind/sandbox-image-configured` on `/` names the image the mind's sandboxes start on, and null gives the stack's own back", async () => {
  const root = memoryStream("/");
  const configured = (image: string | null) => ({
    type: "events.iterate.com/mind/sandbox-image-configured",
    payload: { image },
  });
  // a new engine on new storage reduces the whole log, through the contract's own `consumes`
  const imageAfter = async (event: StreamEventInput) => {
    root.stream.append(event);
    const processor = reducingProcessor();
    const engine = new ProcessorEngine(processor, {
      stream: root.stream,
      storage: memoryStorage(),
    });
    return (await engine.snapshot()).state.sandboxImage;
  };
  expect({
    first: await imageAfter(configured("registry.cloudflare.com/account/first@sha256:digest")),
    latest: await imageAfter(configured("registry.cloudflare.com/account/latest@sha256:digest")),
    cleared: await imageAfter(configured(null)),
  }).toEqual({
    first: "registry.cloudflare.com/account/first@sha256:digest",
    latest: "registry.cloudflare.com/account/latest@sha256:digest",
    cleared: null,
  });
});

test("a mind that is not created yet gets no schedule", async () => {
  const mind = mindOf({ owes: false });
  mind.deliver({ ...mind.state, creation: { status: "failed", offset: 2 } });
  await mind.settled();
  expect(mind).toMatchObject({ root: { did: [] } });
});

/** A ROOT WITH ITS OWN SUBSCRIPTION ROW, as the kernel delivers through one: a span of the log
 *  goes to the processor as the events of the span whose types the row names, with the span's
 *  whole range, so the processor's cursor passes an event that the row left out. `row.did` is
 *  what was asked of the row, and `row.written` how often it was written; `row.down`: the root
 *  cannot be asked. */
function rootWithRow(consumes: string[]) {
  const row = { consumes, did: [] as string[], written: 0, down: false };
  const root = memoryStream("/");
  const storage = memoryStorage();
  /** Appends `events` as one span and delivers it through the row. */
  const pushed = async (
    { engine }: Pick<Incarnation, "engine">,
    events: StreamEventInput[],
  ): Promise<void> => {
    const committed = (await root.stream.append(...events)) as StreamEvent[];
    await engine.processEventBatch(
      committed.filter(({ type }) => row.consumes.includes(type)),
      { after: committed[0]!.offset - 1, through: committed.at(-1)!.offset },
    );
  };
  return { root, storage, row, pushed };
}

type Incarnation = { engine: ProcessorEngine<MindState>; settled: () => Promise<void> };

/** ONE INCARNATION OF THE ROOT'S MIND PROCESSOR on the root's log and checkpoint: a new
 *  processor and a new engine, as after a restart. `settled` waits for the work it started in
 *  the background. */
function incarnationOf({
  root,
  storage,
  row,
}: Pick<ReturnType<typeof rootWithRow>, "root" | "storage" | "row">): Incarnation {
  const invoke = async (expression: ItxExpression) => {
    const [registry, last] = [expression[2], expression.at(-1)];
    const [verb, name] = Array.isArray(last) ? last : [];
    if (registry !== "processors" || verb !== "enable" || name !== "mind")
      throw new Error(`the test's root has no ${JSON.stringify(expression)}`);
    if (row.down) throw new Error("the root was not reached");
    row.did.push("processors.enable mind");
    // as the kernel's `processors.enable` does: the row is written when its types are not the
    // contract's (core/itx src/context/built-ins.ts)
    const consumes = [...MindContract.consumes, "events.iterate.com/itx/woken"];
    if (JSON.stringify(row.consumes) === JSON.stringify(consumes)) return { name };
    row.consumes = consumes;
    row.written += 1;
    return { name };
  };
  return {
    engine: new ProcessorEngine(
      new MindProcessor(
        () => ({ invoke, [Symbol.dispose]() {} }) as unknown as ReturnType<ItxScope>,
        () => ({}) as MindPublisher,
      ),
      { stream: root.stream, storage, fedByPushes: true },
    ),
    // the engine's own background work
    settled: () => new Promise((resolve) => setTimeout(resolve, 20)),
  };
}

function mindOf({
  owes,
  head = "seed",
  there = {},
  probed = {},
  repos = { "/repos/config": { "worker.ts": "export default class {}\n" } },
}: {
  owes: boolean;
  /** The files of each repo of the mind. A repo but `/repos/config` has one commit,
   *  `<name>@1`. A publication reads these for their imports; what loads them is the
   *  publisher's own, given here. */
  repos?: Record<string, Record<string, string>>;
  /** What each read of main's head answers, in turn; the last answer stays. */
  head?: string | string[];
  /** What the publication's probe answers: by default nothing of a config, so it is refused. */
  probed?: unknown;
  /** What the root holds already under the daily refresh's key and name. The schedule is the
   *  mind's own, every six hours; `failed`: its last fire failed, so it is parked. */
  there?: { schedule?: true | "failed"; row?: true };
}) {
  const asked: string[] = [];
  /** What the publication asked of its publisher, in order. */
  const published: string[] = [];
  const facts: StreamEventInput[] = [];
  const platformFacts: StreamEventInput[] = [];
  const background: Promise<unknown>[] = [];
  let headReads = 0;
  const state: MindState = MindContract.stateSchema.parse({
    creation: { status: "created", offset: 2 },
    configured: configuredEvent({}).payload,
    repos: Object.fromEntries(
      Object.keys(repos).map((path) => [path, { createdAt: "2026-11-24T00:00:00.000Z" }]),
    ),
    repoTips: { "/repos/config": { commitOid: "seed", offset: 5 } },
    newestAsking: SEED,
    unpublishedCommits: owes ? [SEED] : [],
    lastPublicationFactOffset: owes ? null : 6,
    published: owes ? null : { commits: { "/repos/config": "seed" } },
  });
  // The root's own schedules and rows, as the daily refresh of the grants asks for them: what it
  // read and what it wrote, in order.
  // `refusals`: what the next call of a repo's `create` or `pull` throws, as "<verb>: <error>"
  const root = {
    schedule: there.schedule,
    row: there.row,
    did: [] as string[],
    refusals: [] as string[],
  };
  const ofTheRoot = (expression: ItxExpression): { answer: unknown } | undefined => {
    const [registry, last] = [expression[2], expression.at(-1)];
    const [verb, argument] = Array.isArray(last) ? last : [];
    // the root's own row, which every incarnation compares with the contract once
    if (registry === "processors" && verb === "enable") return { answer: { name: argument } };
    if (registry === "subscriptions" && verb === "get") return { answer: root.row ? {} : null };
    if (registry === "schedules" && verb === "get")
      return {
        answer: root.schedule
          ? {
              key: "grant-refresh",
              when: { everyMs: 6 * 3_600_000 },
              events: [{ type: "events.iterate.com/secret/grants-refresh-due", payload: {} }],
              ...(root.schedule === "failed" && {
                failure: { error: "the append was refused", offset: 9 },
              }),
            }
          : null,
      };
    if (registry === "schedules" && verb === "set") {
      const { key, when, events } = argument as {
        key: string;
        when: { everyMs: number };
        events: { type: string }[];
      };
      root.did.push(`schedule ${key} every ${when.everyMs / 3_600_000} h: ${events[0]?.type}`);
      return { answer: { key } };
    }
    if (verb === "append") {
      const { payload } = argument as {
        payload: { name: string; consumes: string[]; ordered: boolean; target: string[] };
      };
      root.did.push(
        `row ${payload.name} for ${payload.consumes.join(",")}, ordered ${payload.ordered}: ${payload.target.join(".")}`,
      );
      return { answer: [] };
    }
    return undefined;
  };
  // The processor asks the root for its own row and schedules alone: a publication reads the
  // repos through its publisher.
  const invoke = async (expression: ItxExpression) => {
    // A repo is made, and cloned, through the mind's collection (`itx.builtins.repos`): a pull
    // goes out through its caller's egress, which the collection hands the repo. A pull asked of
    // the repo's own facet (`cd(path).facets.get("repo")`) is one that a real repo refuses.
    const [verb, ...args] = expression.at(-1) as [string, ...unknown[]];
    const at = expression[2];
    if (at === "repos" && root.refusals[0]?.startsWith(`${verb}: `))
      throw new Error(root.refusals.shift()!.slice(verb.length + 2));
    if (at === "repos" && verb === "create") {
      root.did.push(`create ${args[0]}`);
      return { path: args[0] };
    }
    const got = expression[3];
    if (at === "repos" && Array.isArray(got) && got[0] === "get" && verb === "readFile")
      return repos[String(got[1])]?.[String(args[0])] || null;
    if (at === "repos" && Array.isArray(got) && got[0] === "get") {
      root.did.push(
        [verb, got[1], ...args.map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg)))].join(" "),
      );
      return {};
    }
    if (Array.isArray(at) && at[0] === "cd" && String(at[1]).startsWith("/repos/") && verb === "pull")
      throw new Error(`repo ${at[1]}: a pull or push goes through its caller's egress`);
    const rootsOwn = ofTheRoot(expression);
    if (rootsOwn) return rootsOwn.answer;
    throw new Error(`the test's root has no ${JSON.stringify(expression)}`);
  };
  // the state last delivered, which the platform's facts reduce onto, each at the next offset
  let current = state;
  let nextOffset = 100;
  const deliver = (delivered: MindState) =>
    (current = delivered) &&
    processor.processEvent({
      state: delivered,
      delivery: { caughtUp: true },
      append: async (...events: StreamEventInput[]) => {
        facts.push(...events);
      },
      runInBackground: (work: () => Promise<unknown>) => void background.push(work()),
    } as unknown as Parameters<MindProcessor["processEvent"]>[0]);
  const publisher: MindPublisher = {
    // A commit that main is at does not load here unless `probed` says so: by default the probe
    // answers nothing of a config, and the publication is refused, an outcome like any other.
    head: async (repoPath) => {
      if (repoPath !== "/repos/config") return `${repoPath.slice("/repos/".length)}@1`;
      headReads += 1;
      return typeof head === "string" ? head : head[Math.min(headReads, head.length) - 1]!;
    },
    files: async (repoPath) => {
      published.push(`files ${repoPath}`);
      return repos[repoPath]!;
    },
    identityOf: async (_files, mainModule) => {
      published.push(`identity ${mainModule}`);
      return "identity";
    },
    probe: async () => {
      published.push("probe");
      return probed;
    },
    keepModules: async (_files, mainModule) => void published.push(`keep ${mainModule}`),
    // The platform's fact lands on `/` and is delivered to this processor before the publication's
    // own work returns: the order a root's log gives.
    appendAsPlatform: async (...events: StreamEventInput[]) => {
      published.push("append");
      platformFacts.push(...events);
      asked.push("publication:outcome delivered while it runs");
      let reduced = current;
      for (const event of events)
        reduced =
          processor.reduce({
            event: { ...event, offset: nextOffset++ } as unknown as Parameters<
              MindProcessor["reduce"]
            >[0]["event"],
            state: reduced,
          } as Parameters<MindProcessor["reduce"]>[0]) || reduced;
      deliver(reduced);
    },
  };
  const incarnation = () =>
    new MindProcessor(
      () => ({ invoke, [Symbol.dispose]() {} }) as unknown as ReturnType<ItxScope>,
      () => publisher,
    );
  let processor = incarnation();
  return {
    state,
    asked,
    published,
    facts,
    platformFacts,
    root,
    deliver,
    /** The state once the fact of commit `commitOid` arrived at `offset`: its publication is owed.
     *  `newer`: the fact of a commit after it arrived too. */
    owing: (
      commitOid: string,
      offset: number,
      newer?: { commitOid: string; offset: number },
    ): MindState => {
      const [first, ...later] = [{ commitOid, offset }, ...(newer ? [newer] : [])].map(
        (commit) => ({ path: "/repos/config", ...commit }),
      );
      const newest = later.at(-1) || first!;
      return {
        ...state,
        repoTips: { "/repos/config": { commitOid: newest.commitOid, offset: newest.offset } },
        newestAsking: newest,
        unpublishedCommits: [first!, ...later],
      };
    },
    /** The state last delivered, with the platform's facts reduced onto it. */
    get current() {
      return current;
    },
    /** A new incarnation of the root: a new processor over the same repo, publisher and storage. */
    restart() {
      processor = incarnation();
    },
    /** How many times a publication read main's head. */
    get headReads() {
      return headReads;
    },
    /** Every piece of background work the processor started has ended, with what it started. */
    async settled() {
      for (let seen = 0; seen < background.length; seen = background.length)
        await Promise.all(background);
    },
  };
}

type ItxScope = ConstructorParameters<typeof MindProcessor>[0];

// what the probe answers of a config whose entry is an IterateConfigEntrypoint that constructs
const aConfig = { configEntrypoint: true, constructError: null, classes: {} };

// the refusal of a commit that a newer commit superseded
const superseded = (commitOid: string, generation: number, by: string) => ({
  type: "events.iterate.com/mind/worker-update-failed",
  idempotencyKey: `mind/publication:${generation}`,
  payload: {
    trigger: { path: "/repos/config", commitOid },
    generation,
    error: `/repos/config moved on to ${by} before this commit was published`,
    superseded: true,
  },
});

/** The config repo's commit that every mind of `mindOf` starts with, and the fact that asked for
 *  its publication. */
const SEED = { path: "/repos/config", commitOid: "seed", offset: 5 };

/** `mind/configured`, as the mind Worker appends it: one repo that is the mind's code, unless
 *  `changed` says otherwise. */
function configuredEvent(changed: object) {
  return {
    type: "events.iterate.com/mind/configured",
    payload: {
      mindId: "a".repeat(64),
      controlPlaneHostname: "iterate.example.com",
      zones: ["example.com"],
      ownerEmails: ["ada@elsewhere.example"],
      topology: "full-cloudflare",
      signingKey: "REDACTED",
      repos: [{ path: "/repos/config", origin: null }],
      entry: { repo: "/repos/config", module: "worker.ts" },
      kernel: { commit: "a".repeat(40), dirty: false },
      ...changed,
    },
  };
}

/** A processor that only reduces: it reaches no context and no publisher. */
const reducingProcessor = () =>
  new MindProcessor(
    () => {
      throw new Error("the reduce reaches no context");
    },
    () => ({}) as MindPublisher,
  );