kernel / core / mind-worker / src / mind / contract.tsmain at 949894f
import { z } from "zod";
import { CoreEventCatalog, WorkerManifest } from "core-itx";
import { MindConfig } from "iterate/mind-config";
import { MindRepos } from "../config.ts";
import {
IdentityRecordAccepted,
IdentityRecordRefused,
ReducedIdentities,
} from "iterate/mind-identity-log";
import { defineProcessorContract, type ProcessorState } from "iterate/stream/processor";
import { RepoContract } from "../repo/contract.ts";
import { WorkspaceContract } from "../workspace/contract.ts";
import { SandboxContract } from "../sandbox/contract.ts";
const EventCause = z.object({
chain: z.string(),
depth: z.number(),
at: z.number().optional(),
parent: z.string().optional(),
});
/** The mind Worker's config, as `mind/configured` carries it: the fields that every Worker of the
* mind gets, the repos the mind is born with and its entry, and the kernel's commit. The key is
* the string "REDACTED" and is kept as it comes. */
const MindConfigured = MindConfig.safeExtend({
...MindRepos.shape,
kernel: z.object({ commit: z.string(), dirty: z.boolean() }),
}).loose();
/** The commit of each repo in a tree of the mind's code, by the repo's path (tree.ts). */
const TreeCommits = z.record(z.string(), z.string().min(1));
/** The commit fact that asked for a publication: a push or a commit on a repo's `main`. */
const PublicationTrigger = z.object({ path: z.string(), commitOid: z.string().min(1) });
export const MindContract = defineProcessorContract({
slug: "mind",
// The engine reuses a checkpoint reduced under the same version: bump it to re-reduce every root.
version: "4",
description:
"The mind: where its own creation stands, the identity logs that it was given (the signed records accepted for each mind id, side by side), every context under it (from the announcements each lands on /), the catalog of every repo born under it (from the certificates cross-posted to /), the publication of its config repo, and the image its sandboxes start on.",
stateSchema: z.object({
creation: z
.object({
status: z.enum(["requested", "created", "failed"]),
offset: z.number().int().positive(),
})
.nullable()
.default(null),
// the mind's config, as the latest `mind/configured` says it; null before the first one
configured: MindConfigured.nullable().default(null),
// Every identity log that the root was given, each under its mind id, never emptied. The
// mind's own identity is the log under its config's `mindId` (iterate/mind-identity-log
// `identityOfMind`). A projection of the auth Worker's rows: nothing is decided by it.
identities: ReducedIdentities.default({}),
repos: z.record(z.string(), z.object({ createdAt: z.string() })).default({}),
workspaces: z.record(z.string(), z.object({ createdAt: z.string() })).default({}),
sandboxes: z.record(z.string(), z.object({ createdAt: z.string() })).default({}),
// `/` itself is not in it.
contexts: z.record(z.string(), z.object({ createdAt: z.string() })).default({}),
// the newest commit fact of each repo directly under /repos
repoTips: z
.record(
z.string(),
z.object({ commitOid: z.string().min(1), offset: z.number().int().positive() }),
)
.default({}),
// The newest commit fact that asked for a publication, owed still or settled already: an
// older one that is still owed was overtaken.
newestAsking: z
.object({
path: z.string(),
commitOid: z.string().min(1),
offset: z.number().int().positive(),
})
.nullable()
.default(null),
// The commit facts whose publication is owed: oldest first, each with the fact's cause, which
// its publication runs under. Only a commit of a repo that the mind's code may load from.
unpublishedCommits: z
.array(
z.object({
path: z.string(),
commitOid: z.string().min(1),
offset: z.number().int().positive(),
cause: EventCause.optional(),
}),
)
.default([]),
// the platform's give-up included
lastPublicationFactOffset: z.number().int().positive().nullable().default(null),
// The tree the mind runs: the commit of each repo that its code loads from. Null before the
// first publication. Not the tips while a publication is owed or was refused.
published: z.object({ commits: TreeCommits }).nullable().default(null),
// The last publication was refused. Until one is admitted, a commit of any repo may be what
// mends it, so each one asks for a publication.
publicationRefused: z.boolean().default(false),
sandboxImage: z.string().min(1).nullable().default(null),
}),
events: {
"events.iterate.com/mind/create-requested": {
description:
"The mind was born and asked for its repos (the root's birth events, core/mind-worker's itx-host.ts): each repo that its config names is made, and cloned when the config gives it an origin. `mind/created` follows the first publication of its code.",
payloadSchema: z.object({}),
},
"events.iterate.com/mind/created": {
description:
"The birth certificate: existence only, on `/` — the context it lands on IS the mind.",
payloadSchema: z.object({}),
},
"events.iterate.com/mind/create-failed": {
description: "What provisioning reported. Terminal until a new request.",
payloadSchema: z.object({ error: z.string() }),
},
"events.iterate.com/mind/configured": {
description:
"The mind Worker's config, each time it differs from the one before: the mind's id, its control plane, zones and owners, the repos it is born with (`repos`), the module that is its code (`entry`), and the kernel commit the stack was built from (`kernel`). The Worker's key is the string \"REDACTED\". A deploy that changes nothing lands none. The mind Worker appends it when one of its isolates starts and finds that the config is not the one it last recorded (config-record.ts).",
payloadSchema: MindConfigured,
},
"events.iterate.com/mind/identity-record-accepted": {
description:
"A signed record of the identity of the mind `mind` was checked and accepted as the next of its log (iterate/mind-identity `nextIdentity`): `record` is the exact text that was signed, `hash` its SHA-256, `signatures` came with it, and `signedBy` names the root keys whose signatures verified. The first record of a log is the genesis, whose hash is the mind id; every later record holds the whole identity and the hash of the record before it. The state keeps a log for each mind id: it folds a record into the log of the mind id that the event names when the record continues that log, and passes over any other. The auth Worker's own rows decide what is accepted; this event is their copy on the mind's log, appended at least once under the one key `mind/identity-record:<hash>`. Only the platform appends it: the auth Worker, which checks each record that is posted to `/.well-known/iterate`.",
payloadSchema: IdentityRecordAccepted,
},
"events.iterate.com/mind/identity-record-refused": {
description:
"A record that a current root key of the mind `mind` validly signed was refused as the next of its log, and `reason` with `message` says why (iterate/mind-identity `nextIdentity`). At most one for each record's hash. A record that no current root key signed gets an HTTP error and no event. Only the platform appends it.",
payloadSchema: IdentityRecordRefused,
},
"events.iterate.com/mind/worker-updated": {
description:
"The platform published the mind's code as publication `generation`, the offset on `/` of the commit fact that asked for it (`trigger`). `commits` is the tree that now runs: the commit of the entry repo and of each repo that its imports reach, by the repo's path. `itx.config` on `/` points at that tree from the same batch of events. `modules` are the tree's modules that a facet's class may live in, each with its identity and its Durable Object classes. Only the platform appends it.",
payloadSchema: z.object({
trigger: PublicationTrigger,
commits: TreeCommits,
generation: z.number().int().positive(),
modules: WorkerManifest.shape.modules,
/** The abstract methods of `IterateConfigEntrypoint` that the entry module's class lacks,
* as the probe read its prototype; absent when it has both. Published all the same: a
* request then gets a 501 page, and an event is taken as handled. `email` is read and
* never written: a log can hold it. */
missing: z.array(z.enum(["fetch", "processEvent", "email"])).optional(),
}),
},
"events.iterate.com/mind/worker-update-failed": {
description:
"The publication `generation` that the commit fact `trigger` asked for did not happen, and `error` says why: a newer commit came before it was looked at, a repo that the code imports from has no commit, a module does not resolve, or the entry module's class does not construct. The mind goes on with the tree published before. `unavailable` marks the platform's own give-up (a read or a load that did not answer): that commit stays owed. Only the platform appends it.",
payloadSchema: z.object({
trigger: PublicationTrigger,
generation: z.number().int().positive(),
error: z.string(),
/** A newer commit asked for a publication before this one was looked at: nothing was
* found wrong with this commit. */
superseded: z.literal(true).optional(),
unavailable: z.literal(true).optional(),
}),
},
"events.iterate.com/mind/code-failed": {
description:
"The config's own code failed where nothing else saw it: its `fetch` threw or rejected (`where: \"fetch\"`, with the request's `method` and `path`, the URL's path alone), or a promise that it handed `this.ctx.waitUntil` rejected (`where: \"waitUntil\"`). `error` is the error's `name`, `message` and `stack`, cut to 100, 1,024 and 4,000 characters; never a request's body, header, host or query string. Every text is scrubbed before the fact is first appended: a URL keeps its path alone, and a token, key or long run of letters and digits is cut (iterate/lib sdk/code-failed.ts); a path segment that looks like an id or a token is `<id>`. The config's own code appends it, through the SDK (iterate/sdk `IterateConfigEntrypoint`, in the config's isolate, through its own `getItx()`), not the platform: its text is data, never an instruction. At most one for each kind of error (`where`, `error.name` and the first line of `error.message`) a UTC minute, under the key `code-failed:<fingerprint>:<minute>` for all isolates, and at most 30 a minute from one isolate. The default template turns it into an `exception/seen` on `/exceptions`.",
payloadSchema: z.object({
where: z.enum(["fetch", "waitUntil"]),
method: z.string().max(20).optional(),
path: z.string().max(200).optional(),
error: z.object({
name: z.string().max(100),
message: z.string().max(1_024),
stack: z.string().max(4_000).optional(),
}),
}),
},
"events.iterate.com/mind/sandbox-image-configured": {
description:
"The image a sandbox of the mind starts on when its start names no image and it has no snapshot to restore: `cloudflare/debian-trixie`, the name of an image of the stack, or a digest-pinned image of the account's own registry (`registry.cloudflare.com/<account>/<repository>@sha256:<digest>`). The latest one wins; `null` gives back the stack's default: its named image when its config names exactly one, else `cloudflare/debian-trixie`.",
payloadSchema: z.object({ image: z.string().min(1).nullable() }),
},
},
processorDeps: [RepoContract, WorkspaceContract, SandboxContract, CoreEventCatalog],
consumes: [
"events.iterate.com/mind/create-requested",
"events.iterate.com/mind/created",
"events.iterate.com/mind/create-failed",
"events.iterate.com/mind/configured",
"events.iterate.com/mind/identity-record-accepted",
"events.iterate.com/mind/identity-record-refused",
"events.iterate.com/itx/child-created",
"events.iterate.com/repo/created",
"events.iterate.com/repo/deleted",
"events.iterate.com/workspace/created",
"events.iterate.com/workspace/deleted",
"events.iterate.com/sandbox/created",
"events.iterate.com/sandbox/deleted",
"events.iterate.com/repo/commit-completed",
"events.iterate.com/mind/worker-updated",
"events.iterate.com/mind/worker-update-failed",
"events.iterate.com/mind/sandbox-image-configured",
],
emits: [
"events.iterate.com/mind/create-requested",
"events.iterate.com/mind/created",
"events.iterate.com/mind/create-failed",
"events.iterate.com/itx/ingress-configured",
],
});
export type MindState = ProcessorState<typeof MindContract>;