iterate.com / kernel

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

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

// The probe admits a tree of the mind's repos (tree.ts): its entry module's default export is an
// `IterateConfigEntrypoint` that constructs. Only the platform writes the pointer, `itx.config`
// (caller.ts `refuseNonPlatformWrites`).
import type { ItxExpression } from "iterate/expression";
import { failureKind, isPlatformFailureKind } from "iterate/platform-retry";
import type { StreamEventInput } from "iterate/stream/processor";
import { z } from "zod";
import type { WorkerManifest } from "core-itx";
import type { MindRepos } from "../config.ts";
import { readPackage } from "../context/module-resolution.ts";
import type { TreeCommits } from "./tree.ts";

// Files by path: text, or `{ base64 }` for a file that is not text. One repo's at a commit, or
// the tree of several repos.
type RepoFiles = Record<string, string | { base64: string }>;

export type MindPublisher = {
  /** The newest commit of the repo's `main`, or null when it has none. */
  head(repoPath: string): Promise<string | null>;
  files(repoPath: string, commitOid: string): Promise<RepoFiles>;
  // throws when it does not resolve
  identityOf(files: RepoFiles, mainModule: string): Promise<string>;
  probe(files: RepoFiles, mainModule: string): Promise<unknown>;
  // keeps the module's files where a load under its identity reads them; a failed write is logged
  keepModules(files: RepoFiles, mainModule: string): Promise<void>;
  appendAsPlatform(...events: StreamEventInput[]): Promise<unknown>;
};

// A platform failure on the way (a module lock, the probe's load) throws as itself: the follower
// meets it again.
export async function probedConfig(
  files: RepoFiles,
  publisher: Pick<MindPublisher, "identityOf" | "probe" | "keepModules">,
): Promise<{
  mainModule: string;
  modules: WorkerManifest["modules"];
  missing: ConfigMethod[];
}> {
  const { entry } = readPackage(files, "the mind's code");
  if (Object.hasOwn(files, PROBE_MODULE))
    throw new Error(`${PROBE_MODULE} is the platform's publication probe: rename that file`);
  // The entry must load. Any other file at a repo's root is one of the mind's modules only when
  // it loads as a Worker's module: a script for a laptop that sits there is left out, and no
  // facet's class can live in it.
  const others = await Promise.all(
    publishedModules(files)
      .filter((module) => module !== entry)
      .map(async (module) => {
        try {
          return [module, await publisher.identityOf(files, module)] as const;
        } catch (error) {
          if (isPlatformFailureKind(failureKind(error))) throw error;
          console.info({
            event: "mind.file-is-no-module",
            namespace: "mind",
            message: "a file at a repo's root does not load as a Worker's module, so it is not one of the mind's modules",
            module,
            error: error instanceof Error ? error.message : String(error),
          });
          return undefined;
        }
      }),
  );
  const identities = [
    [entry, await publisher.identityOf(files, entry)] as const,
    ...others.filter((identified) => identified !== undefined),
  ];
  const modules = identities.map(([module]) => module);
  const probeSource = { ...files, [PROBE_MODULE]: probeModule(entry, modules) };
  const answer = ProbeAnswer.parse(await publisher.probe(probeSource, PROBE_MODULE));
  if (!answer.configEntrypoint)
    throw new Error(
      `${entry}'s default export is not an IterateConfigEntrypoint (iterate/sdk): every context's events are delivered to its deliverEvent`,
    );
  if (answer.constructError)
    throw new Error(
      `${entry}'s default export does not construct: ${answer.constructError} — every delivery and every request constructs it`,
    );
  // Before the pointer is appended, so the isolates that load the new config read the files from KV
  // and do not each ask the repo for the commit. A commit the probe refused keeps nothing.
  await publisher.keepModules(files, entry);
  return {
    mainModule: entry,
    missing: answer.missing,
    modules: Object.fromEntries(
      identities.map(([module, identity]) => [
        module,
        { identity, classes: answer.classes[module] ?? [] },
      ]),
    ),
  };
}

// At the fixed point: through `itx.repos` a hop reads `/`'s rule table first, and a read in the
// SNAPSHOT_TTL_MS before a publication's commit would hold that commit's answer as long.
export const repoCall = (repoPath: string, verb: string, ...args: unknown[]): ItxExpression => [
  "itx",
  "builtins",
  ["cd", repoPath],
  "builtins",
  "facets",
  ["get", "repo"],
  [verb, ...args],
];

/** The mind facet's `tree`, at the fixed point: the files of a set of commits as one tree. */
const TREE_OF_COMMITS: ItxExpression = [
  "itx",
  "builtins",
  ["cd", "/"],
  "builtins",
  "facets",
  ["get", "mind"],
  "tree",
];

// `itx.config.modules` names the mind facet at the fixed point, and a row on `itx.config…` is the
// platform's alone, so no rule anyone appends re-points what loads under the published identity.
export function configPointer(
  tree: { commits: TreeCommits; key: string; entry: MindRepos["entry"] },
  mainModule: string,
  manifest: WorkerManifest,
): StreamEventInput[] {
  const rule = (match: string, key: string, target: unknown, description: string) => ({
    type: "events.iterate.com/itx/rewrite-rule-configured",
    idempotencyKey: `mind/${key}:${manifest.generation}`,
    payload: { match, target, description },
  });
  return [
    rule(
      "itx.config.modules",
      "config-modules",
      TREE_OF_COMMITS,
      "the files of the mind's repos at a set of commits, as one tree, as the published code's producer reads them",
    ),
    rule(
      "itx.config",
      "config-pointer",
      [
        "itx",
        "builtins",
        "workers",
        [
          "get",
          {
            source: ["itx", "config", ["modules", { commits: tree.commits, entry: tree.entry }]],
            cacheKey: tree.key,
            mainModule,
            manifest,
          },
        ],
      ],
      `the mind's published code: ${Object.entries(tree.commits)
        .map(([repoPath, commitOid]) => `${repoPath} at ${commitOid.slice(0, 12)}`)
        .join(", ")}, publication ${manifest.generation}`,
    ),
  ];
}

const PROBE_MODULE = ".iterate-publication-probe.js";

/** The abstract methods of `IterateConfigEntrypoint` (iterate/sdk). The loader never type-checks,
 *  so a commit may lack one: it is published, and `mind/worker-updated` names what it lacks, once
 *  for the commit. */
const ConfigMethod = z.enum(["fetch", "processEvent"]);
type ConfigMethod = z.infer<typeof ConfigMethod>;

const ProbeAnswer = z.object({
  configEntrypoint: z.boolean(),
  constructError: z.string().nullable(),
  classes: z.record(z.string(), z.array(z.string())),
  missing: z.array(ConfigMethod).default([]),
});

// The modules a facet's class may live in: those at the root of each repo of the tree
// (`stdlib/agents.ts`), and each app's backend inside a repo (`config/apps/<name>/backend.ts`). Not
// every file: the probe loads each one, and a page's script is not a Worker's module. A test is
// not one either: it imports what a Worker has not got.
function publishedModules(files: RepoFiles): string[] {
  return Object.keys(files)
    .filter((path) => /\.(ts|mts|js|mjs)$/.test(path) && !path.endsWith(".d.ts"))
    .filter((path) => !/\.test\.[a-z]+$/.test(path))
    .filter((path) => /^[^/]+\/([^/]+|apps\/[^/]+\/backend\.[a-z]+)$/.test(path))
    .sort();
}

function probeModule(entry: string, modules: string[]): string {
  const others = modules.filter((module) => module !== entry);
  const guarded = others.map(
    (module) =>
      `  try { classes[${JSON.stringify(module)}] = classesOf(await import(${JSON.stringify(`./${module}`)})); } catch {}`,
  );
  return [
    `import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";`,
    `import { IterateConfigEntrypoint } from "iterate/sdk";`,
    `import * as main from ${JSON.stringify(`./${entry}`)};`,
    `const classesOf = (module) => Object.keys(module).filter((key) => typeof module[key] === "function" && module[key].prototype instanceof DurableObject);`,
    `const messageOf = (error) => (error instanceof Error ? error.message : String(error));`,
    `export default class extends WorkerEntrypoint {`,
    `  async probe() {`,
    `    const Entry = main.default;`,
    `    const configEntrypoint = typeof Entry === "function" && Entry.prototype instanceof IterateConfigEntrypoint;`,
    `    let constructError = null;`,
    `    if (configEntrypoint) try { new Entry(this.ctx, this.env); } catch (error) { constructError = messageOf(error); }`,
    `    const classes = { ${JSON.stringify(entry)}: classesOf(main) };`,
    // On the prototype, as Workers RPC and `deliverEvent` reach a method: an arrow field is none.
    `    const missing = configEntrypoint ? ${JSON.stringify(ConfigMethod.options)}.filter((name) => typeof Entry.prototype[name] !== "function") : [];`,
    ...guarded,
    `    return { configEntrypoint, constructError, classes, missing };`,
    `  }`,
    `}`,
    ``,
  ].join("\n");
}