diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index f128577d2e..dd1d0a6368 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -125,7 +125,11 @@ bun scripts/ci-timings.ts record --event tmp/work-event.json --out tmp/ci-timing ``` The command supplies version, UUID, current timestamp and repository. Explicit -ID/time permit attributed historical observations. IDs cannot be overwritten +ID/time permit attributed historical observations. Optional `orchestrator` IDs +use the same opaque syntax as worker/task IDs. `preempted` records a preemption +without claiming a pass or failure; it requires worker/task IDs. Explicit +[publication](ci-timings.md#publish-local-coordination-events) appends these +local events to the durable measurement ref. IDs cannot be overwritten with different content. Pairs are `work-started`/`work-finished` and `wait-started`/`wait-finished`; waits require `reason` set to `reservation`, `ci`, `review`, `conflict` or `other`. Each pair shares worker/task/reason. diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index a77c375939..6c59997057 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -244,3 +244,50 @@ runner and runtime inputs, retaining the existing proof assertions and gates. See [testing](testing.md#required-proof-for-a-pr), [proof-domain reconciliation](proof-domains.md#resource-and-scheduling-reconciliation) and [the CI measurement policy](../decisions/ci-utility.md#measuring-the-critical-path). + +## Publish local coordination events + +From a trusted repository checkout with Git push access to `origin`, publish +locally recorded work, wait and preemption events explicitly: + +```sh +bun scripts/ci-timings.ts publish --repo odysseus/chronicle --out tmp/ci-events +``` + +Use the repository's own `owner/name` in place of the example. This internal +measurement script prints JSON with `added`, `existing` and `head`; it is not +the supported `brain --json` contract. Collection and report modes remain +read-only. Publication grants no proof, selection or merge authority. + +The input directory holds `event-.json` files from `record`. Each event +uses schema version 1, an immutable ID, repository and UTC ISO timestamp. +Allowed kinds are `work-started`, `work-finished`, `wait-started`, +`wait-finished` and `preempted`. Worker/task IDs are required; `orchestrator` +is optional. IDs contain only ASCII letters, digits, underscores and hyphens, +up to 100 characters. Use opaque generated identifiers, never people's names +or machine identifiers. Optional `pr` is a positive integer; optional `reason` +is `reservation`, `ci`, `review`, `conflict` or `other` and is required for wait +boundaries. Preemption remains neither pass nor failure. Event emission is the +orchestrator's responsibility; this command does not read the host ledger. + +Each invocation accepts at most 100 events, 8 KiB per file and 256 KiB total. +For a larger backlog, select smaller input directories while retaining each +original event's ID and bytes. Non-event files are ignored; selected symlinks, +unknown versions, arbitrary fields, hostname/path-like IDs and personal-string +leakage are refused before contacting the remote. Incident/classification +annotations are outside this publisher's local-event schema: select a directory +containing only work, wait and preemption events. + +The publisher appends immutable `events/.json` files to +`refs/heads/brain-ci-metrics`, preserving the inspected tree's other files. +These are the dedicated published-event inputs for daily compaction (#2955), +which owns the monthly normalized archive. This command enables neither +compaction nor scheduled report delivery. Repeating a batch is a no-op; +an existing ID with different content is refused. Unknown event versions are +refused rather than rewritten. + +Every commit is parented by the inspected remote head and pushed with exact +`--force-with-lease`. A competing update causes a fresh read and merge, up to +five attempts. Persistent contention or access failure exits nonzero, retaining +all local inputs for a retry. Errors appear on stderr; preserve that diagnostic +with the command exit status. No input is deleted, including after success. diff --git a/scripts/ci-event-publish.ts b/scripts/ci-event-publish.ts new file mode 100644 index 0000000000..aee9555b69 --- /dev/null +++ b/scripts/ci-event-publish.ts @@ -0,0 +1,107 @@ +/** Publish local coordination evidence; never an input to integration policy. */ +import { mkdtemp, readdir, lstat, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { scanText } from "./check-leakage"; +import { validateWorkEvent, type WorkEvent } from "./ci-throughput"; + +export const EVENT_REF = "refs/heads/brain-ci-metrics"; +const MAX_EVENTS = 100, MAX_BYTES = 256 * 1024, MAX_EVENT_BYTES = 8192; +const opaque = (value: unknown) => typeof value === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(value); + +/** Strict local-event schema plus the same personal-string screen as the tree. */ +export function screenPublishedEvent(value: unknown, repository: string): WorkEvent { + const e = validateWorkEvent(value); + if (e.repository !== repository) throw new Error("Event repository differs from --repo"); + if (!["work-started", "work-finished", "wait-started", "wait-finished", "preempted"].includes(e.kind) || + Object.keys(e).some(k => !["version", "id", "repository", "kind", "at", "worker", "task", "orchestrator", "reason", "pr"].includes(k)) || + ![e.id, e.worker, e.task].every(opaque) || (e.orchestrator !== undefined && !opaque(e.orchestrator)) || + (e.reason !== undefined && !["reservation", "ci", "review", "conflict", "other"].includes(e.reason)) || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(e.at)) throw new Error("Unsafe local event fields"); + if (scanText("event", JSON.stringify(e)).length) throw new Error("Event refused by leakage screen"); + return e; +} + +/** Git plumbing uses an isolated index; the caller's files and index never move. */ +export class GitEventStore { + constructor(readonly root: string, readonly remote = "origin") {} + async git(args: string[], input?: string, index?: string): Promise { + const p = Bun.spawn(["git", ...args], { cwd: this.root, stdout: "pipe", stderr: "pipe", + stdin: input === undefined ? "ignore" : new TextEncoder().encode(input), env: { ...process.env, + ...(index ? { GIT_INDEX_FILE: index } : {}), + GIT_AUTHOR_NAME: "brain-kit metrics", GIT_AUTHOR_EMAIL: "metrics@example.invalid", + GIT_COMMITTER_NAME: "brain-kit metrics", GIT_COMMITTER_EMAIL: "metrics@example.invalid" } }); + const [code, out, err] = await Promise.all([p.exited, new Response(p.stdout).text(), new Response(p.stderr).text()]); + // Git's raw stderr may include a private remote URL or filesystem path. + if (code !== 0) throw new Error(`Event archive git ${args[0]} failed (${code}); check remote access`); + void err; + return out.trim(); + } + async remoteOid(): Promise { + const output = await this.git(["ls-remote", "--refs", this.remote, EVENT_REF]); + if (!output) return null; + const [oid, ref, ...extra] = output.split(/\s+/); + if (!/^[a-f0-9]{40}$/.test(oid!) || ref !== EVENT_REF || extra.length) throw new Error("Invalid event archive ref"); + return oid!; + } + async read(): Promise { + const oid = await this.remoteOid(); + if (oid) await this.git(["fetch", "--no-tags", this.remote, oid]); + return oid; + } + async publish(parent: string | null, events: WorkEvent[], repository: string): Promise<{ head: string; added: number } | null> { + const pending: WorkEvent[] = []; + for (const event of events) { + const path = `events/${event.id}.json`; + const entry = parent ? await this.git(["ls-tree", parent, "--", path]) : ""; + if (entry) { + if (!/^100644 blob [a-f0-9]{40}\t/.test(entry)) throw new Error("Invalid archived event entry"); + const previous = screenPublishedEvent(JSON.parse(await this.git(["show", `${parent}:${path}`])), repository); + if (JSON.stringify(previous) !== JSON.stringify(event)) throw new Error("Event ID already exists with different content"); + } else pending.push(event); + } + if (!pending.length && parent) return { head: parent, added: 0 }; + const temporary = await mkdtemp(join(tmpdir(), "brain-event-index-")), index = join(temporary, "index"); + try { + await this.git(["read-tree", ...(parent ? [parent] : ["--empty"])], undefined, index); + for (const event of pending) { + const blob = await this.git(["hash-object", "-w", "--stdin"], JSON.stringify(event) + "\n"); + await this.git(["update-index", "--add", "--cacheinfo", `100644,${blob},events/${event.id}.json`], undefined, index); + } + const tree = await this.git(["write-tree"], undefined, index); + const head = await this.git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", "ci: append coordination events"]); + try { + await this.git(["push", "--porcelain", `--force-with-lease=${EVENT_REF}:${parent ?? ""}`, this.remote, `${head}:${EVENT_REF}`]); + return { head, added: pending.length }; + } catch (error) { + if (await this.remoteOid() !== parent) return null; + throw error; + } + } finally { await rm(temporary, { recursive: true, force: true }); } + } +} + +export async function publishEvents(options: { root: string; dir: string; repository: string; store?: GitEventStore }): Promise<{ added: number; existing: number; head: string | null }> { + const { root, dir, repository } = options; + if (!/^[\w-]+\/[\w-]+$/.test(repository)) throw new Error("Invalid publication repository"); + const names = (await readdir(dir)).filter(name => /^event-[\w-]+\.json$/.test(name)).sort(); + if (names.length > MAX_EVENTS) throw new Error(`Event batch exceeds ${MAX_EVENTS}; select a smaller input directory`); + const events: WorkEvent[] = [], ids = new Set(); let bytes = 0; + for (const name of names) { + const path = join(dir, name), stat = await lstat(path); + bytes += stat.size; + if (!stat.isFile() || stat.size > MAX_EVENT_BYTES || bytes > MAX_BYTES) throw new Error("Event batch exceeds size bounds or contains a non-file"); + const event = screenPublishedEvent(JSON.parse(await readFile(path, "utf8")), repository); + if (ids.has(event.id)) throw new Error("Duplicate event ID in batch"); + ids.add(event.id); events.push(event); + } + if (!events.length) return { added: 0, existing: 0, head: null }; + // All local input is screened before any network operation. A lost CAS is + // retried against the new tree, preserving unrelated archive/compaction work. + const store = options.store ?? new GitEventStore(root); + for (let attempt = 0; attempt < 5; attempt++) { + const parent = await store.read(), result = await store.publish(parent, events, repository); + if (result) return { ...result, existing: events.length - result.added }; + } + throw new Error("Event publication contention exceeded five attempts; local events retained, retry publish"); +} diff --git a/scripts/ci-throughput.ts b/scripts/ci-throughput.ts index 0dd8c96de3..dc59c712cb 100644 --- a/scripts/ci-throughput.ts +++ b/scripts/ci-throughput.ts @@ -12,8 +12,8 @@ export interface PullObservation { mergeObject?: { sha: string; tree: string; parents: string[] }; } export interface WorkEvent { - version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "failure-classified" | "incident" | "revert" | "expedited-fix"; - at: string; worker?: string; task?: string; reason?: "reservation" | "ci" | "review" | "conflict" | "other"; + version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "preempted" | "failure-classified" | "incident" | "revert" | "expedited-fix"; + at: string; worker?: string; task?: string; orchestrator?: string; reason?: "reservation" | "ci" | "review" | "conflict" | "other"; pr?: number; run?: number; attempt?: number; job?: number; relatedPR?: number; classification?: "product" | "test" | "infrastructure" | "stale-candidate" | "intentional-feedback"; evidence?: string; @@ -38,12 +38,13 @@ function green(s: TimingSnapshot): boolean { /** Only public operational references and opaque coordination IDs are retained. */ export function validateWorkEvent(value: unknown): WorkEvent { const e = value as WorkEvent; - const allowed = new Set(["version", "id", "repository", "kind", "at", "worker", "task", "reason", "pr", "run", "attempt", "job", "relatedPR", "classification", "evidence"]); + const allowed = new Set(["version", "id", "repository", "kind", "at", "worker", "task", "orchestrator", "reason", "pr", "run", "attempt", "job", "relatedPR", "classification", "evidence"]); if (!e || typeof e !== "object" || Object.keys(e).some(k => !allowed.has(k)) || e.version !== 1 || typeof e.id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(e.id) || !/^[\w.-]+\/[\w.-]+$/.test(e.repository) || !stamp(e.at) || - !["work-started", "work-finished", "wait-started", "wait-finished", "failure-classified", "incident", "revert", "expedited-fix"].includes(e.kind)) throw new Error("Invalid coordination event"); + !["work-started", "work-finished", "wait-started", "wait-finished", "preempted", "failure-classified", "incident", "revert", "expedited-fix"].includes(e.kind)) throw new Error("Invalid coordination event"); + if (e.orchestrator !== undefined && (typeof e.orchestrator !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(e.orchestrator))) throw new Error("Opaque orchestrator ID required"); for (const field of ["pr", "run", "attempt", "job", "relatedPR"] as const) if (e[field] !== undefined && !number(e[field])) throw new Error(`Invalid event ${field}`); - if (/^(work|wait)-/.test(e.kind)) { + if (/^(work|wait)-/.test(e.kind) || e.kind === "preempted") { if (![e.worker, e.task].every(x => typeof x === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(x))) throw new Error("Opaque worker/task IDs required"); if (e.kind.startsWith("wait-") && !["reservation", "ci", "review", "conflict", "other"].includes(e.reason ?? "")) throw new Error("Wait reason required"); } else { diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index c0af36a5c3..e2566a6bc2 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -1,4 +1,5 @@ -/** Read-only CI timing archive. Logs are data; no candidate code is executed. */ +/** CI timing collection and explicit local-event publication. Logs are data; no candidate code is executed. */ +import { publishEvents } from "./ci-event-publish"; import { mkdir, readdir, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { percentage, seconds, stats } from "./ci-timing-stats"; @@ -555,6 +556,7 @@ if (import.meta.main) { if (!["--repo", "--since", "--until", "--run", "--out", "--event", "--scenario", "--seed", "--request-budget", "--reserve", "--history"].includes(flag) || !args.length || options.has(flag)) throw new Error("Invalid timing option"); options.set(flag, args.shift()!); } + if (mode === "publish" && (resources || reservations || redMain || [...options.keys()].some(flag => !["--repo", "--out"].includes(flag)))) throw new Error("Publish accepts only --repo and --out"); const dir = resolve(options.get("--out") ?? "tmp/ci-timings"); // Proof-policy epochs read this ref's first-parent history from the local checkout. const history = options.get("--history") ?? "origin/main"; @@ -580,7 +582,9 @@ if (import.meta.main) { } if (options.has("--scenario")) await Bun.write(join(dir, "scenario.json"), JSON.stringify(await Bun.file(options.get("--scenario")!).json(), null, 2)); if (options.has("--since") && options.has("--until")) await Bun.write(join(dir, "analysis-window.json"), JSON.stringify({ since: options.get("--since"), until: options.get("--until"), source: "explicit analysis interval" })); - if (mode === "record") { + if (mode === "publish") { + console.log(JSON.stringify(await publishEvents({ root: process.cwd(), dir, repository }))); + } else if (mode === "record") { if (!options.has("--event")) throw new Error("Record requires --event JSON-file"); const input = await Bun.file(options.get("--event")!).json(); if (input.repository && input.repository !== repository) throw new Error("Event repository differs from --repo"); @@ -697,6 +701,6 @@ if (import.meta.main) { if (errors.some(e => !budgetProblem(e.error)) || enrichmentErrors.some(e => !budgetProblem(e.problem)) || (await readSnapshots(dir)).some(s => s.problems.some(p => !budgetProblem(p))) || !api.budget.stopped && report.collectionCoverage.missingAttempts.length) process.exitCode = 1; - } else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--reservations] [--red-main] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]"); + } else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record|publish [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--reservations] [--red-main] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]"); } catch (error) { console.error(error); process.exitCode = 1; } } diff --git a/tests/ci-event-publish.test.ts b/tests/ci-event-publish.test.ts new file mode 100644 index 0000000000..5d74195be0 --- /dev/null +++ b/tests/ci-event-publish.test.ts @@ -0,0 +1,125 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { publishEvents } from "../scripts/ci-event-publish"; + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const repository = "odysseus/chronicle", ref = "refs/heads/brain-ci-metrics"; +const event = (id = "event-1") => ({ version: 1, id, repository, kind: "work-started", at: "2026-07-12T00:00:00Z", worker: "worker-1", task: "task-1" }); +function git(root: string, ...args: string[]) { + const p = Bun.spawnSync(["git", ...args], { cwd: root, stdout: "pipe", stderr: "pipe" }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return new TextDecoder().decode(p.stdout).trim(); +} +function setup() { + const root = mkdtempSync(join(tmpdir(), "odysseus-events-")); dirs.push(root); + const remote = join(root, "remote.git"); git(root, "init", "--bare", remote); + const clones = ["one", "two"].map(name => { + const clone = join(root, name); mkdirSync(clone); git(clone, "init"); git(clone, "remote", "add", "origin", remote); + const dir = join(clone, "events"); mkdirSync(dir); return { root: clone, dir, repository }; + }); + return { root, remote, one: clones[0]!, two: clones[1]! }; +} +function record(dir: string, value: object) { writeFileSync(join(dir, `event-${(value as { id: string }).id}.json`), JSON.stringify(value)); } + +test("publishing the same batch twice adds nothing and conflicting IDs cannot rewrite history", async () => { + const { one, remote } = setup(); record(one.dir, event()); + const first = await publishEvents(one); + expect(first.added, "FIRST_BATCH_PUBLISHED").toBe(1); + expect(await publishEvents(one)).toEqual({ added: 0, existing: 1, head: first.head }); + expect(JSON.parse(git(remote, "show", `${ref}:events/event-1.json`))).toEqual(event()); + record(one.dir, { ...event(), task: "task-2" }); + await expect(publishEvents(one)).rejects.toThrow("different content"); + expect(git(remote, "rev-parse", ref)).toBe(first.head!); +}); + +test("unsafe hostnames, outside paths and names are refused before any push", async () => { + const { one, remote } = setup(); + for (const extra of [{ worker: "ithaca.example.invalid" }, { task: "/outside/crew" }, { orchestrator: "ithaca.example.invalid" }, { worker: "al" + "ain" }, { evidence: "/outside/crew" }]) { + record(one.dir, { ...event(), ...extra }); + await expect(publishEvents(one), "UNSAFE_EVENT_REFUSED").rejects.toThrow(); + expect(git(remote, "for-each-ref", "--format=%(refname)"), "NOTHING_PUSHED").toBe(""); + } +}); + +test("two machines pushing concurrently both land their immutable events", async () => { + const { root, one, two, remote } = setup(); record(one.dir, event("one")); record(two.dir, event("two")); + const script = join(root, "contender.ts"), source = resolve(import.meta.dir, "../scripts/ci-event-publish.ts"); + // Both processes inspect the same missing remote before either may push. + writeFileSync(script, `import {existsSync,writeFileSync} from "node:fs"; + import {publishEvents, GitEventStore} from ${JSON.stringify(source)}; + const [root,dir,id,barrier]=process.argv.slice(2); + const store=new GitEventStore(root), read=store.read.bind(store); let first=true; + store.read=async()=>{ const snapshot=await read(); if(first){first=false;writeFileSync(barrier+id,"ready"); + const deadline=Date.now()+10000;while(!existsSync(barrier+"1")||!existsSync(barrier+"2")){if(Date.now()>deadline)throw Error("barrier timeout");await Bun.sleep(5);}} + return snapshot; }; + console.log(JSON.stringify(await publishEvents({root,dir,repository:${JSON.stringify(repository)},store})));`); + const children = [one, two].map((options, i) => Bun.spawn([process.execPath, script, options.root, options.dir, String(i + 1), join(root, "barrier-")], { stdout: "pipe", stderr: "pipe" })); + const results = await Promise.all(children.map(async child => { + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); return JSON.parse(out); + })); + expect(results.map(r => r.added)).toEqual([1, 1]); + expect(git(remote, "ls-tree", "-r", "--name-only", ref).split("\n")).toEqual(["events/one.json", "events/two.json"]); + expect(git(remote, "rev-list", "--count", ref)).toBe("2"); +}); + +test("publication preserves unrelated monthly archive content and the caller index", async () => { + const { one, remote } = setup(); + git(one.root, "config", "user.name", "Odysseus"); git(one.root, "config", "user.email", "odysseus@example.invalid"); + mkdirSync(join(one.root, "2026-07")); writeFileSync(join(one.root, "2026-07", "runs.json"), "[]\n"); + git(one.root, "add", "2026-07/runs.json"); git(one.root, "commit", "-m", "archive seed"); + git(one.root, "push", "origin", `HEAD:${ref}`); + const parent = git(one.root, "rev-parse", "HEAD"), before = git(one.root, "ls-files", "--stage"); + record(one.dir, event()); const result = await publishEvents(one); + expect(git(remote, "show", `${ref}:2026-07/runs.json`)).toBe("[]"); + expect(git(remote, "rev-parse", `${result.head}^`)).toBe(parent); + expect(git(one.root, "ls-files", "--stage")).toBe(before); + expect(git(one.root, "rev-parse", "HEAD")).toBe(parent); +}); + +test("an unsafe batch leaves another input directory usable and bounded batches retain local files", async () => { + const { one, two, remote } = setup(); + record(one.dir, { ...event(), task: "/outside/crew" }); + await expect(publishEvents(one)).rejects.toThrow(); + record(two.dir, { ...event("safe"), kind: "preempted", orchestrator: "orchestrator-1", reason: "other" }); + expect((await publishEvents(two)).added).toBe(1); + for (let i = 0; i < 101; i++) record(two.dir, event(`bounded-${i}`)); + const head = git(remote, "rev-parse", ref); + await expect(publishEvents(two)).rejects.toThrow("batch exceeds 100"); + expect(git(remote, "rev-parse", ref)).toBe(head); + expect(await Bun.file(join(two.dir, "event-bounded-100.json")).exists()).toBe(true); +}); + +test("the CLI records and publishes preemption and admission waits with stable IDs", async () => { + const { one, remote } = setup(), script = resolve(import.meta.dir, "../scripts/ci-timings.ts"); + async function cli(...args: string[]) { + const child = Bun.spawn([process.execPath, script, ...args, "--repo", repository, "--out", one.dir], { cwd: one.root, stdout: "pipe", stderr: "pipe" }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); return out; + } + const input = join(one.root, "input.json"); + writeFileSync(input, JSON.stringify({ ...event("preempted-1"), kind: "preempted", orchestrator: "orchestrator-1" })); + await cli("record", "--event", input); + for (const kind of ["wait-started", "wait-finished"]) { + writeFileSync(input, JSON.stringify({ ...event(kind), kind, task: "admission-slot-1", reason: "other" })); + await cli("record", "--event", input); + } + expect(JSON.parse(await cli("publish"))).toMatchObject({ added: 3, existing: 0 }); + expect(JSON.parse(await cli("publish"))).toMatchObject({ added: 0, existing: 3 }); + expect(JSON.parse(git(remote, "show", `${ref}:events/preempted-1.json`)).orchestrator).toBe("orchestrator-1"); +}); + +test("unknown versions, duplicate IDs and oversized records fail before remote publication", async () => { + const { one, remote } = setup(); + record(one.dir, { ...event(), version: 2 }); + await expect(publishEvents(one)).rejects.toThrow("Invalid coordination event"); + record(one.dir, event()); writeFileSync(join(one.dir, "event-alias.json"), JSON.stringify(event())); + await expect(publishEvents(one)).rejects.toThrow("Duplicate event ID"); + rmSync(join(one.dir, "event-alias.json")); + writeFileSync(join(one.dir, "event-event-1.json"), " ".repeat(8193)); + await expect(publishEvents(one)).rejects.toThrow("size bounds"); + expect(git(remote, "for-each-ref", "--format=%(refname)")).toBe(""); +});