A desktop coding agent with free access to frontier models.
TypeScript
feat: buildathon reproducibility mode
Samrat Talukdar2d5c608cb44b
diff --git a/apps/app/src/app/lib/buildathon.ts b/apps/app/src/app/lib/buildathon.tsindex e9a81d51..06ddc6fb 100644--- a/apps/app/src/app/lib/buildathon.ts+++ b/apps/app/src/app/lib/buildathon.ts@@ -169,28 +169,85 @@ export function projectKey(path: string | null | undefined): string | null {return trimmed || null;}-export function readProjectTracks(storage: KeyValueStore | null = defaultStorage()): Record<string, string> {+/**+ * A folder's answer: its track, or null when it was skipped ("No track");+ * `first`: when it was first answered. (CLI: the folder tracks file, the same+ * fields.) Older entries were the track alone.+ */+export type ProjectEntry = { track: string | null; first: string | null; at: string | null };++export function readProjectEntries(storage: KeyValueStore | null = defaultStorage()): Record<string, ProjectEntry> {const value = readJson<Record<string, unknown>>(BUILDATHON_TRACKS_STORAGE_KEY, {}, storage);- const tracks: Record<string, string> = {};- for (const [path, track] of Object.entries(value)) {- if (typeof track === "string" && track) tracks[path] = track;+ const entries: Record<string, ProjectEntry> = {};+ for (const [path, entry] of Object.entries(value)) {+ if (typeof entry === "string" && entry) entries[path] = { track: entry, first: null, at: null };+ else if (entry && typeof entry === "object" && !Array.isArray(entry)) {+ const raw = entry as Record<string, unknown>;+ const iso = (v: unknown) => (typeof v === "string" && Number.isFinite(Date.parse(v)) ? v : null);+ entries[path] = { track: typeof raw.track === "string" && raw.track ? raw.track : null, first: iso(raw.first), at: iso(raw.at) };+ }}+ return entries;+}++/** Folder -> track, for folders that have one. */+export function readProjectTracks(storage: KeyValueStore | null = defaultStorage()): Record<string, string> {+ const tracks: Record<string, string> = {};+ for (const [path, entry] of Object.entries(readProjectEntries(storage))) if (entry.track) tracks[path] = entry.track;return tracks;}export function readProjectTrack(path: string | null | undefined, storage: KeyValueStore | null = defaultStorage()): string | null {const key = projectKey(path);- return key ? readProjectTracks(storage)[key] ?? null : null;+ return key ? readProjectEntries(storage)[key]?.track ?? null : null;+}++/** Whether the folder was answered (a track or a skip). */+export function projectAnswered(path: string | null | undefined, storage: KeyValueStore | null = defaultStorage()): boolean {+ const key = projectKey(path);+ return Boolean(key && readProjectEntries(storage)[key]);}-/** Saves (or, with null, clears) a folder's track. */-export function writeProjectTrack(path: string | null | undefined, track: string | null, storage: KeyValueStore | null = defaultStorage()): void {+/** Saves a folder's track, or (null) its skip; the first answer's time is kept. */+export function writeProjectTrack(path: string | null | undefined, track: string | null, storage: KeyValueStore | null = defaultStorage(), now = Date.now()): void {const key = projectKey(path);if (!key) return;- const tracks = readProjectTracks(storage);- if (track) tracks[key] = track;- else delete tracks[key];- writeJson(BUILDATHON_TRACKS_STORAGE_KEY, tracks, storage);+ const entries = readProjectEntries(storage);+ const at = new Date(now).toISOString();+ entries[key] = { track, first: entries[key]?.first ?? entries[key]?.at ?? at, at };+ // A bounded list: the most recent 500 folders.+ const kept = Object.entries(entries).sort((a, b) => String(a[1].at).localeCompare(String(b[1].at))).slice(-500);+ writeJson(BUILDATHON_TRACKS_STORAGE_KEY, Object.fromEntries(kept), storage);+}++/**+ * The buildathon projects (contract "Reproducibility mode"): folders with a+ * track, and folders skipped whose first answer fell inside the event. The+ * server leaves out generic folders (home, temp, a root).+ */+export function buildathonProjectPaths(event: BuildathonEvent, entries: Record<string, ProjectEntry>): string[] {+ const starts = event.startsAt ? Date.parse(event.startsAt) : Number.NEGATIVE_INFINITY;+ const deadline = Date.parse(event.deadlineAt);+ const known = new Set(event.tracks.map((track) => track.id));+ const out: string[] = [];+ for (const [path, entry] of Object.entries(entries)) {+ if (entry.track && known.has(entry.track)) out.push(path);+ else if (!entry.track && entry.first) {+ const first = Date.parse(entry.first);+ if (first >= starts && first <= deadline) out.push(path);+ }+ }+ return out.sort();+}++/** The server's body for PUT /runtime-config/buildathon (null without an event). */+export function buildathonServerBody(status: BuildathonStatus | null, entries: Record<string, ProjectEntry>) {+ if (!status) return null;+ return {+ repro: { box: status.repro.box, agent_rules: status.repro.agentRules },+ projects: buildathonProjectPaths(status.event, entries),+ deadline_at: status.event.deadlineAt,+ };}export function readTaggedSessions(storage: KeyValueStore | null = defaultStorage()): Record<string, string> {@@ -266,6 +323,8 @@ type BuildathonStore = {offsetMs: number;panelOpen: boolean;projects: BuildathonProject[];+ /** The project open in the app (the panel's checklist is about it). */+ selectedProjectId: string | null;/** Projects created in this run, waiting for the one-time track question. */newProjects: Array<{ path: string; name: string }>;/** Bumped on every track change so pickers re-read storage. */@@ -273,7 +332,7 @@ type BuildathonStore = {setStatus: (status: BuildathonStatus | null, receivedAtMs?: number) => void;openPanel: () => void;closePanel: () => void;- setProjects: (projects: BuildathonProject[]) => void;+ setProjects: (projects: BuildathonProject[], selectedProjectId?: string | null) => void;noteNewProject: (project: { path: string; name: string }) => void;dropNewProject: (path: string) => void;bumpTracks: () => void;@@ -284,6 +343,7 @@ export const useBuildathonStore = create<BuildathonStore>((set) => ({offsetMs: 0,panelOpen: false,projects: [],+ selectedProjectId: null,newProjects: [],tracksVersion: 0,setStatus: (status, receivedAtMs = Date.now()) =>@@ -294,7 +354,7 @@ export const useBuildathonStore = create<BuildathonStore>((set) => ({})),openPanel: () => set({ panelOpen: true }),closePanel: () => set({ panelOpen: false }),- setProjects: (projects) => set({ projects }),+ setProjects: (projects, selectedProjectId = null) => set({ projects, selectedProjectId }),noteNewProject: (project) =>set((state) => {const key = projectKey(project.path);@@ -382,3 +442,32 @@ export function buildathonProjects(groups: SessionGroupLike[]): BuildathonProjec})),}));}++let lastSent: string | null = null;++/**+ * Tells the local server the buildathon projects and the event's `repro`+ * block when they changed since the last answer it took. Never throws; a+ * failure is tried again on the next call.+ */+export async function syncBuildathonServer(+ status: BuildathonStatus | null,+ send: (body: NonNullable<ReturnType<typeof buildathonServerBody>>) => Promise<unknown>,+ entries: Record<string, ProjectEntry> = readProjectEntries(),+): Promise<"sent" | "unchanged" | "skipped" | "failed"> {+ const body = buildathonServerBody(status, entries);+ if (!body) return "skipped";+ const key = JSON.stringify(body);+ if (key === lastSent) return "unchanged";+ try {+ await send(body);+ lastSent = key;+ return "sent";+ } catch {+ return "failed";+ }+}++export function resetBuildathonServerSync(): void {+ lastSent = null;+}diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.tsindex fd0072d9..690740db 100644--- a/apps/app/src/app/lib/desktop.ts+++ b/apps/app/src/app/lib/desktop.ts@@ -790,6 +790,7 @@ const {omnirushBuildathonSessions,omnirushBuildathonLink,omnirushBuildathonTagSession,+ omnirushBuildathonChecklist,omnirushAccountConnect,omnirushAccountSignOut,omnirushServerRestart,@@ -860,6 +861,7 @@ export {omnirushBuildathonSessions,omnirushBuildathonLink,omnirushBuildathonTagSession,+ omnirushBuildathonChecklist,omnirushAccountConnect,omnirushAccountSignOut,omnirushServerRestart,diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 9413adf1..9f1f3a7f 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -436,7 +436,7 @@ export type OmniRushWorkspaceBox = {serverDefault: "off" | "offer" | "on";on: boolean;/** "host-builds": the server's default would put it in the sandbox, but the folder has this computer's builds. */- source: "env" | "project" | "server" | "default" | "host-builds";+ source: "env" | "project" | "server" | "default" | "host-builds" | "buildathon";offer: boolean;state: "off" | "unavailable" | "downloading" | "starting" | "ready" | "failed";runtime: { ok: boolean; name: string | null; flavor: string | null; version: string | null; reason: string | null } | null;@@ -2001,6 +2001,11 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: srequestJson<{ removed: boolean }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/box/reset`, {token, hostToken, method: "POST", body: {}, timeoutMs: 90_000,}),+ /** Buildathon projects (folders) and the event's `repro` block: their chats get its rules and box. */+ setBuildathon: (body: { repro: { box: string; agent_rules: string } | null; projects: string[]; deadline_at: string | null }) =>+ requestJson<{ ok: boolean; projects: number; box: string }>(baseUrl, "/runtime-config/buildathon", {+ token, hostToken, method: "PUT", body, timeoutMs: ENGINE_RELOAD_TIMEOUT_MS,+ }),getBestPractices: () =>requestJson<OmniRushBestPractices>(baseUrl, "/runtime-config/best-practices", { token, hostToken, timeoutMs: timeouts.config }),setBestPractices: (enabled: boolean) =>diff --git a/apps/app/src/react-app/domains/buildathon/buildathon.tsx b/apps/app/src/react-app/domains/buildathon/buildathon.tsxindex f1474d82..c11fa928 100644--- a/apps/app/src/react-app/domains/buildathon/buildathon.tsx+++ b/apps/app/src/react-app/domains/buildathon/buildathon.tsx@@ -1,6 +1,6 @@/** @jsxImportSource react */import { useCallback, useEffect, useMemo, useState } from "react";-import { Copy, ExternalLink, Trophy, X } from "lucide-react";+import { Check, Copy, ExternalLink, Trophy, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";@@ -10,11 +10,14 @@ import { cn } from "@/lib/utils";import {desktopNotificationShow,omnirushBuildathon,+ omnirushBuildathonChecklist,omnirushBuildathonLink,omnirushBuildathonSessions,omnirushBuildathonTagSession,openDesktopUrl,} from "../../../app/lib/desktop";+import { createOmniRushServerClient } from "../../../app/lib/omnirush-server";+import { resolveOmniRushConnection } from "../../shell/omnirush-connection";import {BUILDATHON_REFRESH_MS,buildathonChipText,@@ -22,6 +25,10 @@ import {compactTokens,formatEventTime,formatRemaining,+ buildathonProjectPaths,+ projectAnswered,+ projectKey,+ readProjectEntries,readProjectTrack,readProjectTracks,readShownReminders,@@ -33,9 +40,11 @@ import {sessionStatusLabel,sessionsToTag,setProjectTrack,+ syncBuildathonServer,tagSessions,useBuildathonStore,type BuildathonCountdown,+ type BuildathonProject,type BuildathonSession,type BuildathonStatus,type BuildathonTrack,@@ -100,7 +109,7 @@ function TrackSelect(props: { tracks: BuildathonTrack[]; value: string | null; odata-testid={props.testId}aria-label="Buildathon track">- <option value="">Not part of the buildathon</option>+ <option value="">No track</option>{props.tracks.map((track) => (<option key={track.id} value={track.id}>{track.label}</option>))}@@ -154,11 +163,11 @@ function NewProjectPrompt(props: { status: BuildathonStatus; project: { path: st<div className="flex items-center gap-1.5 font-medium"><Trophy className="size-3.5" /> Building for the buildathon?</div><div className="mt-0.5 text-xs text-muted-foreground">Pick a track for “{props.project.name}”. You can change it later in Settings.</div></div>- <Button variant="ghost" size="icon-xs" aria-label="Not now" onClick={props.onDone}><X /></Button>+ <Button variant="ghost" size="icon-xs" aria-label="Not now" onClick={() => { setProjectTrack(props.project.path, null); props.onDone(); }}><X /></Button></div><TrackSelect tracks={trackOptions(props.status)} value={track} onChange={setTrack} testId="buildathon-prompt-select" /><div className="flex justify-end gap-2">- <Button variant="ghost" size="xs" onClick={props.onDone}>Not now</Button>+ <Button variant="ghost" size="xs" onClick={() => { setProjectTrack(props.project.path, null); props.onDone(); }}>Not now</Button><Buttonsize="xs"disabled={!track}@@ -274,6 +283,63 @@ function Section(props: { title: string; children: React.ReactNode; testId?: str);}+/** The buildathon project the checklist is about: the open one when it is one, else the first. */+function checklistProject(status: BuildathonStatus, projects: BuildathonProject[], selectedId: string | null): BuildathonProject | null {+ const listed = new Set(buildathonProjectPaths(status.event, readProjectEntries()));+ const candidates = projects.filter((project) => project.local && listed.has(projectKey(project.path) ?? ""));+ return candidates.find((project) => project.id === selectedId) ?? candidates[0] ?? null;+}++/** The rebuild checklist of a buildathon project, checked in its folder (cheap file checks). */+function ChecklistSection(props: { status: BuildathonStatus }) {+ const projects = useBuildathonStore((store) => store.projects);+ const selectedId = useBuildathonStore((store) => store.selectedProjectId);+ const tracksVersion = useBuildathonStore((store) => store.tracksVersion);+ const project = useMemo(() => checklistProject(props.status, projects, selectedId), [props.status, projects, selectedId, tracksVersion]);+ const [checks, setChecks] = useState<Array<{ id: string; text: string; ok: boolean | null }> | null | undefined>(undefined);+ const checklist = props.status.repro.checklist;+ const path = project?.path ?? null;+ useEffect(() => {+ if (!path) return;+ let live = true;+ setChecks(undefined);+ void omnirushBuildathonChecklist({ path, checklist }).catch(() => null).then((result) => {+ if (live) setChecks(result ?? null);+ });+ return () => {+ live = false;+ };+ }, [path, checklist]);+ if (!project) {+ return (+ <Section title="Rebuild checklist" testId="buildathon-checklist">+ <div className="text-xs text-muted-foreground">Pick a track for your project (Settings, or the prompt on a new project) to check it here.</div>+ </Section>+ );+ }+ const known = checks ? checks.filter((check) => check.ok !== null) : [];+ const passed = known.filter((check) => check.ok).length;+ return (+ <Section title={`Rebuild checklist · ${project.name}${checks ? ` · ${passed}/${known.length}` : ""}`} testId="buildathon-checklist">+ {checks === undefined ? <div className="text-xs text-muted-foreground">Checking…</div>+ : checks === null ? <div className="text-xs text-muted-foreground">The folder could not be checked.</div>+ : (+ <ul className="grid grid-cols-1 gap-1 text-xs sm:grid-cols-2">+ {checks.map((check) => (+ <li key={check.id} className="flex items-start gap-1.5" data-check={check.id} data-ok={String(check.ok)}>+ {check.ok === true ? <Check className="mt-0.5 size-3.5 shrink-0 text-emerald-600" />+ : check.ok === false ? <X className="mt-0.5 size-3.5 shrink-0 text-red-600 dark:text-red-400" />+ : <span className="mt-0.5 w-3.5 shrink-0 text-center text-muted-foreground">?</span>}+ <span className={check.ok === false ? "text-foreground" : "text-muted-foreground"}>{check.text}</span>+ </li>+ ))}+ </ul>+ )}+ <div className="text-[11px] text-muted-foreground">Chats in this project follow the event's rebuild rules and run in the Linux sandbox when it is on.</div>+ </Section>+ );+}+/** "My Buildathon": countdown, tokens, rules, sessions, submission, link code. */export function BuildathonPanel(props: { status: BuildathonStatus; onClose: () => void }) {const { event, participant, submission } = props.status;@@ -362,6 +428,8 @@ export function BuildathonPanel(props: { status: BuildathonStatus; onClose: () =) : null}</Section>+ <ChecklistSection status={props.status} />+<Section title="Rules" testId="buildathon-rules"><ul className="space-y-1 text-xs">{rules.map((rule, index) => (@@ -432,9 +500,33 @@ export function BuildathonLayer() {void tagSessions(pending, (input) => omnirushBuildathonTagSession(input));}, [status, projects, tracksVersion]);+ // The local server gets the buildathon projects and the event's `repro` block: their chats get+ // the event's rules (engine plugin) and, with `box: "on"`, the Linux sandbox. Retried on failure.+ const [syncRetry, setSyncRetry] = useState(0);+ useEffect(() => {+ if (!status) return;+ let live = true;+ let timer: number | undefined;+ void syncBuildathonServer(status, async (body) => {+ const connection = await resolveOmniRushConnection();+ if (!connection.normalizedBaseUrl || !(connection.resolvedToken || connection.resolvedHostToken)) throw new Error("server not ready");+ await createOmniRushServerClient({+ baseUrl: connection.normalizedBaseUrl,+ token: connection.resolvedToken || undefined,+ hostToken: connection.resolvedHostToken || undefined,+ }).setBuildathon(body);+ }).then((outcome) => {+ if (live && outcome === "failed") timer = window.setTimeout(() => setSyncRetry((value) => value + 1), 30_000);+ });+ return () => {+ live = false;+ if (timer) window.clearTimeout(timer);+ };+ }, [status, tracksVersion, syncRetry]);+const closePrompt = useCallback((path: string) => useBuildathonStore.getState().dropNewProject(path), []);const prompt = status && status.event && buildathonCountdown(status.event, now).kind !== "closed"- ? newProjects.find((project) => !readProjectTrack(project.path)) ?? null+ ? newProjects.find((project) => !projectAnswered(project.path)) ?? null: null;if (!status) return null;diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsxindex 71ccd484..55ecb8d4 100644--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx@@ -1158,8 +1158,8 @@ export function AppSidebar(props: AppSidebarProps) {// The buildathon layer files event sessions under their project's track.React.useEffect(() => {- useBuildathonStore.getState().setProjects(buildathonProjects(props.workspaceSessionGroups));- }, [props.workspaceSessionGroups]);+ useBuildathonStore.getState().setProjects(buildathonProjects(props.workspaceSessionGroups), props.selectedWorkspaceId || null);+ }, [props.workspaceSessionGroups, props.selectedWorkspaceId]);// Green unread dots: agent finished while the user was on another session.React.useEffect(() => {diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox.ts b/apps/app/src/react-app/domains/settings/linux-sandbox.tsindex 1345a5f1..24ee9c93 100644--- a/apps/app/src/react-app/domains/settings/linux-sandbox.ts+++ b/apps/app/src/react-app/domains/settings/linux-sandbox.ts@@ -105,6 +105,8 @@ export function linuxSandboxView(box: OmniRushWorkspaceBox, pending: LinuxSandboif (!box.on) {if (box.source === "env") return { ...base, tone: "off", title: "Off for this app", detail: "Set by OMNIRUSH_BOX where the app is launched." };if (box.hostBuilds?.native) return { ...base, tone: "attention", title: "Off for this project", detail: box.hostBuilds.notice };+ // A buildathon project: turned off here (less reproducible), or the event offers the sandbox.+ if (box.notice) return { ...base, tone: "attention", title: box.source === "project" ? "Off for this project" : "Off", detail: box.notice };return { ...base, tone: "off", title: "Off", detail: "Commands run on this computer." };}const using = runtimeLabel(box);diff --git a/apps/app/tests/buildathon.test.ts b/apps/app/tests/buildathon.test.tsindex 7058c913..b1861e78 100644--- a/apps/app/tests/buildathon.test.ts+++ b/apps/app/tests/buildathon.test.ts@@ -3,7 +3,13 @@ import { describe, expect, test } from "bun:test";import {buildathonChipText,buildathonCountdown,+ buildathonProjectPaths,buildathonProjects,+ buildathonServerBody,+ projectAnswered,+ readProjectEntries,+ resetBuildathonServerSync,+ syncBuildathonServer,clockOffsetMs,formatEventTime,formatRemaining,@@ -162,7 +168,7 @@ test("the only-tool rule comes first", () => {});describe("refresh", () => {- const status: BuildathonStatus = { enrolled: true, serverTime: null, event: EVENT, participant: null, submission: null };+ const status: BuildathonStatus = { enrolled: true, serverTime: null, event: EVENT, participant: null, submission: null, repro: { box: "on", agentRules: "", checklist: [] } };test("enrolled shows, anything else hides", async () => {await refreshBuildathon(async () => status);@@ -176,3 +182,48 @@ describe("refresh", () => {expect(useBuildathonStore.getState().status).toBeNull();});});++describe("reproducibility mode: buildathon projects", () => {+ const inside = Date.parse("2026-10-15T00:00:00Z");+ const before = Date.parse("2026-10-01T00:00:00Z");++ test("a track, or a skip first answered inside the event; the first answer's time is kept", () => {+ const storage = memoryStorage();+ writeProjectTrack("/p/tracked", "agents", storage, before);+ writeProjectTrack("/p/skipped", null, storage, inside);+ writeProjectTrack("/p/early-skip", null, storage, before);+ writeProjectTrack("/p/unknown-track", "nope", storage, inside);+ expect(projectAnswered("/p/skipped", storage)).toBe(true);+ expect(projectAnswered("/p/never", storage)).toBe(false);+ expect(buildathonProjectPaths(EVENT, readProjectEntries(storage))).toEqual(["/p/skipped", "/p/tracked"]);+ // A later track keeps the first answer's time; a later skip of an early folder does not make it one.+ writeProjectTrack("/p/early-skip", null, storage, inside);+ expect(readProjectEntries(storage)["/p/early-skip"]!.first).toBe(new Date(before).toISOString());+ expect(buildathonProjectPaths(EVENT, readProjectEntries(storage))).not.toContain("/p/early-skip");+ });++ test("older entries (the track alone) still read", () => {+ const storage = memoryStorage({ "omnirush.buildathon.tracks.v1": JSON.stringify({ "/p/old": "agents" }) });+ expect(readProjectTrack("/p/old", storage)).toBe("agents");+ expect(buildathonProjectPaths(EVENT, readProjectEntries(storage))).toEqual(["/p/old"]);+ });++ test("the server's body, sent only when it changed; a failure is sent again", async () => {+ resetBuildathonServerSync();+ const status: BuildathonStatus = {+ enrolled: true, serverTime: null, event: EVENT, participant: null, submission: null,+ repro: { box: "on", agentRules: "Rules.", checklist: [] },+ };+ const storage = memoryStorage();+ writeProjectTrack("/p/app", "agents", storage, inside);+ const entries = readProjectEntries(storage);+ expect(buildathonServerBody(status, entries)).toEqual({ repro: { box: "on", agent_rules: "Rules." }, projects: ["/p/app"], deadline_at: EVENT.deadlineAt });+ expect(buildathonServerBody(null, entries)).toBeNull();+ const sent: unknown[] = [];+ expect(await syncBuildathonServer(status, async () => { throw new Error("down"); }, entries)).toBe("failed");+ expect(await syncBuildathonServer(status, async (body) => void sent.push(body), entries)).toBe("sent");+ expect(await syncBuildathonServer(status, async (body) => void sent.push(body), entries)).toBe("unchanged");+ expect(await syncBuildathonServer(null, async (body) => void sent.push(body), entries)).toBe("skipped");+ expect(sent.length).toBe(1);+ });+});diff --git a/apps/app/tests/linux-sandbox-card.test.tsx b/apps/app/tests/linux-sandbox-card.test.tsxindex 0c5b23ea..6485ea3a 100644--- a/apps/app/tests/linux-sandbox-card.test.tsx+++ b/apps/app/tests/linux-sandbox-card.test.tsx@@ -156,6 +156,14 @@ describe("Linux sandbox card", () => {expect(linuxSandboxView(box({ ...on, state: "unavailable", notice: "Sandbox off for now: the sandbox did not start in time." }))).toMatchObject({ title: "The sandbox is not running", action: { kind: "retry" }, errorDetail: "the sandbox did not start in time" });});+ test("a buildathon project turned off here says it is less reproducible; the event's offer says so too", () => {+ const less = "This buildathon project runs on this computer (sandbox off here), so it is less reproducible. Turn the Linux sandbox on to run it in the box.";+ expect(linuxSandboxView(box({ on: false, mode: "off", source: "project", state: "off", notice: less }))).toMatchObject({ tone: "attention", title: "Off for this project", detail: less });+ const offer = "This buildathon project rebuilds more reliably in the Linux sandbox. Turn it on to run its chats there.";+ expect(linuxSandboxView(box({ on: false, source: "buildathon", offer: true, state: "off", notice: offer }))).toMatchObject({ tone: "attention", title: "Off", detail: offer });+ expect(linuxSandboxView(box({ on: false, source: "default", state: "off", notice: null }))).toMatchObject({ tone: "off", title: "Off", detail: "Commands run on this computer." });+ });+test("macOS / Windows: a project kept off for its host builds says why (switch off, one click on); on by choice it warns; a box says it is Linux", () => {const kept = "This folder has Mac builds (node_modules, .venv) that won't run in the Linux sandbox, so its chats run on this Mac. Turn the sandbox on for this project to use it anyway.";const off = box({ on: false, source: "host-builds", state: "off", notice: kept, hostBuilds: { native: true, things: "node_modules, .venv", notice: kept } });diff --git a/apps/desktop/electron/buildathon-checklist.mjs b/apps/desktop/electron/buildathon-checklist.mjsnew file mode 100644index 00000000..7a947436--- /dev/null+++ b/apps/desktop/electron/buildathon-checklist.mjs@@ -0,0 +1,190 @@+// The buildathon rebuild checklist, checked in the project folder with cheap+// file checks (contract "Reproducibility mode"). Ported word for word from the+// CLI (omnirush-cli assets/extensions/omnirush/buildathon-lib.js, "the+// checklist, checked here"); keep the two in step.++import fs from "node:fs";+import os from "node:os";+import path from "node:path";++export const DEFAULT_CHECKLIST = Object.freeze([+ { id: "git", text: "A git repository with commits" },+ { id: "lockfile", text: "A dependency lockfile" },+ { id: "runtime_pin", text: "The runtime version pinned" },+ { id: "dockerfile", text: "A Dockerfile that builds and runs it" },+ { id: "test_cmd", text: "One test command" },+ { id: "readme", text: "A README with setup, run and test steps" },+ { id: "env_example", text: "Settings in .env.example, no secrets in files" },+ { id: "no_abs_paths", text: "No absolute paths from this machine" },+]);+++const SKIP_DIRS = new Set([".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "target", ".next", ".cache", "vendor", ".omnirush", ".opencode"]);+const TEXT_EXT = /\.(js|mjs|cjs|ts|tsx|jsx|py|go|rs|rb|java|kt|php|sh|bash|zsh|ps1|json|ya?ml|toml|ini|cfg|conf|env|md|txt|html|css|scss|sql|dockerfile|mk)$|(^|\/)(Dockerfile|Makefile|Containerfile|Procfile|justfile)$/i;++function exists(root, name) {+ try {+ return fs.statSync(path.join(root, name));+ } catch {+ return null;+ }+}++function readSmall(root, name, max = 256 * 1024) {+ try {+ const st = fs.statSync(path.join(root, name));+ if (!st.isFile() || st.size > max) return null;+ return fs.readFileSync(path.join(root, name), "utf8");+ } catch {+ return null;+ }+}++function anyOf(root, names) {+ return names.some((n) => exists(root, n));+}++/** The project's text files (bounded walk, build/dependency folders left out). */+function projectFiles(root, { maxFiles = 3000, maxDepth = 6 } = {}) {+ const out = [];+ const walk = (rel, depth) => {+ if (out.length >= maxFiles || depth > maxDepth) return;+ let entries = [];+ try {+ entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ if (out.length >= maxFiles) return;+ const child = rel ? `${rel}/${e.name}` : e.name;+ if (e.isDirectory()) {+ if (!SKIP_DIRS.has(e.name)) walk(child, depth + 1);+ } else if (e.isFile() && TEXT_EXT.test(child)) out.push(child);+ }+ };+ walk("", 0);+ return out;+}++const CHECKS = {+ git: (root) => {+ const git = exists(root, ".git");+ if (!git) return false;+ if (git.isFile()) return true; // a worktree+ try {+ return fs.readdirSync(path.join(root, ".git", "refs", "heads")).length > 0 || Boolean(exists(root, ".git/packed-refs"));+ } catch {+ return false;+ }+ },+ lockfile: (root) => anyOf(root, ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb", "npm-shrinkwrap.json", "poetry.lock", "uv.lock", "Pipfile.lock", "pdm.lock", "requirements.lock", "Cargo.lock", "go.sum", "Gemfile.lock", "composer.lock", "mix.lock", "pubspec.lock", "packages.lock.json", "gradle.lockfile", "flake.lock"])+ || /^[A-Za-z0-9_.\-\[\]]+==\S+/m.test(readSmall(root, "requirements.txt") || ""),+ runtime_pin: (root) => {+ if (anyOf(root, [".nvmrc", ".node-version", ".python-version", ".tool-versions", "rust-toolchain", "rust-toolchain.toml", ".ruby-version", ".java-version", "runtime.txt", "mise.toml", ".mise.toml", ".sdkmanrc", ".bun-version"])) return true;+ if (/^(toolchain|go)\s+\S+/m.test(readSmall(root, "go.mod") || "")) return true;+ try {+ const pkg = JSON.parse(readSmall(root, "package.json") || "{}");+ if (pkg?.engines?.node || pkg?.volta?.node || pkg?.packageManager) return true;+ } catch {+ /* not JSON */+ }+ return /requires-python\s*=/.test(readSmall(root, "pyproject.toml") || "");+ },+ dockerfile: (root) => anyOf(root, ["Dockerfile", "Containerfile", "docker/Dockerfile", ".devcontainer/Dockerfile"]),+ test_cmd: (root) => {+ if (/^test\s*:/m.test(readSmall(root, "Makefile") || "") || /^test\b/m.test(readSmall(root, "justfile") || "")) return true;+ try {+ const test = JSON.parse(readSmall(root, "package.json") || "{}")?.scripts?.test;+ if (typeof test === "string" && test.trim() && !/no test specified/.test(test)) return true;+ } catch {+ /* not JSON */+ }+ if (/\[tool\.pytest|pytest/.test(readSmall(root, "pyproject.toml") || "") || anyOf(root, ["pytest.ini", "tox.ini", "noxfile.py"])) return true;+ return anyOf(root, ["Cargo.toml", "go.mod"]);+ },+ readme: (root) => {+ try {+ return fs.readdirSync(root).some((n) => /^readme(\.|$)/i.test(n) && (exists(root, n)?.size ?? 0) > 0);+ } catch {+ return false;+ }+ },+ env_example: (root) => {+ if (anyOf(root, [".env.example", ".env.sample", ".env.template", ".env.dist", "env.example"])) return true;+ try {+ return !fs.readdirSync(root).some((n) => /^\.env(\.|$)/.test(n));+ } catch {+ return false;+ }+ },+ no_abs_paths: (root, { home }) => {+ const user = String(home || "").split(/[\\/]/).filter(Boolean).pop() || "";+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const needles = [home, root].filter((p) => p && p.length > 4).map((p) => new RegExp(`${escape(p)}(?![\\w.-])`));+ // /Users/<me>, /home/<me>, C:\Users\<me> (also with the backslashes escaped in source).+ const generic = user ? new RegExp(`(/Users/|/home/|[A-Za-z]:(?:\\\\){1,2}Users(?:\\\\){1,2})${user.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([/\\\\]|\\b)`, "i") : null;+ for (const rel of projectFiles(root)) {+ const text = readSmall(root, rel);+ if (!text) continue;+ if (needles.some((n) => n.test(text)) || (generic && generic.test(text))) return false;+ }+ return true;+ },+};++/**+ * The checklist against the project folder: [{ id, text, ok }], ok null for+ * an id this version does not know.+ */+export function evaluateChecklist(root, checklist = DEFAULT_CHECKLIST, { home = os.homedir() } = {}) {+ return checklist.map((item) => {+ const check = CHECKS[item.id];+ let ok = null;+ if (check) {+ try {+ ok = Boolean(check(root, { home }));+ } catch {+ ok = false;+ }+ }+ return { id: item.id, text: item.text, ok };+ });+}+++function str(value) {+ return typeof value === "string" ? value.trim() : "";+}++/** The `repro.checklist` list; missing or empty: the default list (CLI parseRepro, the same rule). */+export function parseChecklist(value) {+ const checklist = Array.isArray(value)+ ? value.filter((c) => c && typeof c === "object" && str(c.id)).map((c) => ({ id: c.id.trim(), text: str(c.text) || DEFAULT_CHECKLIST.find((d) => d.id === c.id.trim())?.text || c.id.trim() }))+ : [];+ return checklist.length ? checklist.slice(0, 30) : DEFAULT_CHECKLIST.map((c) => ({ ...c }));+}++/** A drive or file-system root, the home folder or the temp folder: never a project of its own. */+export function genericFolder(dir, { home = os.homedir() } = {}) {+ const key = path.resolve(dir);+ if (path.dirname(key) === key) return true;+ return [home, os.tmpdir()].filter(Boolean).map((d) => path.resolve(d)).includes(key);+}++/**+ * The checklist for one project folder (the app's IPC): null for anything+ * but an existing absolute folder that is a real project.+ * @param {{ path?: unknown, checklist?: unknown }} [input]+ * @returns {Array<{ id: string, text: string, ok: boolean | null }> | null}+ */+export function projectChecklist(input = {}, { home = os.homedir() } = {}) {+ const dir = typeof input.path === "string" ? input.path.trim() : "";+ if (!dir || !path.isAbsolute(dir) || genericFolder(dir, { home })) return null;+ try {+ if (!fs.statSync(dir).isDirectory()) return null;+ } catch {+ return null;+ }+ return evaluateChecklist(dir, parseChecklist(input.checklist), { home });+}diff --git a/apps/desktop/electron/buildathon.mjs b/apps/desktop/electron/buildathon.mjsindex 28a164ee..36352ae9 100644--- a/apps/desktop/electron/buildathon.mjs+++ b/apps/desktop/electron/buildathon.mjs@@ -7,6 +7,11 @@* shows nothing.*/+import { parseChecklist } from "./buildathon-checklist.mjs";++/** The server's default rules, word for word (the CLI and the server embed the same). */+export const DEFAULT_AGENT_RULES = "This project is part of the OmniRush Buildathon and must rebuild from scratch on a clean Linux machine. Keep every file the project needs inside this folder and use git, committing after each working step. Pin the runtime version (.nvmrc / .python-version / go.mod toolchain / rust-toolchain.toml) and always keep a lockfile; install dependencies only into the project (no global installs, no sudo outside the Dockerfile). Maintain a Dockerfile that installs every system package and dependency and can build and run the project, a single test command (e.g. `make test`) that works offline, and a README with exact setup, run, test and deploy steps. Never hard-code absolute paths from this machine or put secrets in files (use .env.example). After each change, run the tests.";+export const BUILDATHON_TRACKS = /** @type {const} */ ([{ id: "agents", label: "Agents & Automation" },{ id: "devtools", label: "Developer Tools & Open Source" },@@ -150,6 +155,23 @@ export function parseBuildathonSubmission(value) {};}+const REPRO_BOX = ["on", "offer", "off"];++/**+ * The `repro` block (contract "Reproducibility mode"); a missing or partial+ * one falls back to the defaults: box on, the default rules and checklist.+ * @returns {import("@omnirush/types/desktop-ipc").OmniRushBuildathonRepro}+ */+export function parseBuildathonRepro(value) {+ const block = value && typeof value === "object" && !Array.isArray(value) ? value : {};+ const rules = text(block.agent_rules);+ return {+ box: REPRO_BOX.includes(block.box) ? block.box : "on",+ agentRules: rules && rules.length <= 8_000 ? rules : DEFAULT_AGENT_RULES,+ checklist: parseChecklist(block.checklist),+ };+}+/*** GET /me/buildathon (or the link answer): null unless the account is* enrolled and the event names a deadline.@@ -165,6 +187,7 @@ export function parseBuildathonStatus(value) {event,participant: parseParticipant(value.participant),submission: parseBuildathonSubmission(value.submission),+ repro: parseBuildathonRepro(value.repro),};}diff --git a/apps/desktop/electron/buildathon.test.mjs b/apps/desktop/electron/buildathon.test.mjsindex f12c54f6..78e71eea 100644--- a/apps/desktop/electron/buildathon.test.mjs+++ b/apps/desktop/electron/buildathon.test.mjs@@ -1,17 +1,21 @@import assert from "node:assert/strict";-import { mkdtemp } from "node:fs/promises";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtemp, readFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import test from "node:test";import {BUILDATHON_TRACKS,+ DEFAULT_AGENT_RULES,buildathonLinkCode,buildathonTrackId,+ parseBuildathonRepro,parseBuildathonSessions,parseBuildathonStatus,parseBuildathonSubmission,} from "./buildathon.mjs";+import { DEFAULT_CHECKLIST, evaluateChecklist, projectChecklist } from "./buildathon-checklist.mjs";import { createDesktopOmniRushAccountStore } from "./omnirush-account.mjs";const GATEWAY = "http://localhost:8090/omnirush/v1";@@ -210,3 +214,63 @@ test("buildathon store: link code", async () => {const offline = await signedInStore(async () => { throw new TypeError("fetch failed"); });assert.equal((await offline.buildathonLink({ code: "FB-0000-00" })).ok, false);});++test("repro block: the server's values, else the contract's defaults (box on)", () => {+ const none = parseBuildathonRepro(undefined);+ assert.equal(none.box, "on");+ assert.equal(none.agentRules, DEFAULT_AGENT_RULES);+ assert.deepEqual(none.checklist.map((c) => c.id), ["git", "lockfile", "runtime_pin", "dockerfile", "test_cmd", "readme", "env_example", "no_abs_paths"]);+ const server = parseBuildathonRepro({ box: "offer", agent_rules: "Use make.", checklist: [{ id: "git" }, { id: "custom", text: "Custom" }, { bad: 1 }] });+ assert.equal(server.box, "offer");+ assert.equal(server.agentRules, "Use make.");+ assert.deepEqual(server.checklist, [{ id: "git", text: DEFAULT_CHECKLIST[0].text }, { id: "custom", text: "Custom" }]);+ assert.equal(parseBuildathonRepro({ box: "maybe" }).box, "on");+ assert.equal(parseBuildathonStatus(ENROLLED).repro.box, "on", "parsed with the rest of the answer");+});++test("repro: the default rules are the contract's text, word for word", async () => {+ const contract = "This project is part of the OmniRush Buildathon and must rebuild from scratch on a clean Linux machine. Keep every file the project needs inside this folder and use git, committing after each working step. Pin the runtime version (.nvmrc / .python-version / go.mod toolchain / rust-toolchain.toml) and always keep a lockfile; install dependencies only into the project (no global installs, no sudo outside the Dockerfile). Maintain a Dockerfile that installs every system package and dependency and can build and run the project, a single test command (e.g. `make test`) that works offline, and a README with exact setup, run, test and deploy steps. Never hard-code absolute paths from this machine or put secrets in files (use .env.example). After each change, run the tests.";+ assert.equal(DEFAULT_AGENT_RULES, contract);+ const server = await readFile(new URL("../../server/src/buildathon-repro.ts", import.meta.url), "utf8");+ assert.ok(server.includes(JSON.stringify(contract)), "the server embeds the same text");+});++function project(prefix = "omnirush-bt-proj-") {+ return mkdtempSync(path.join(os.tmpdir(), prefix));+}++test("checklist: cheap checks in the folder, pass and fail", () => {+ const bare = project();+ const results = evaluateChecklist(bare, DEFAULT_CHECKLIST, { home: "/home/nobody" });+ const ok = Object.fromEntries(results.map((r) => [r.id, r.ok]));+ assert.deepEqual(ok, { git: false, lockfile: false, runtime_pin: false, dockerfile: false, test_cmd: false, readme: false, env_example: true, no_abs_paths: true });++ const good = project();+ mkdirSync(path.join(good, ".git", "refs", "heads"), { recursive: true });+ mkdirSync(path.join(good, "src"));+ writeFileSync(path.join(good, ".git", "refs", "heads", "main"), "abc\n");+ writeFileSync(path.join(good, "package.json"), JSON.stringify({ engines: { node: "22" }, scripts: { test: "node --test" } }));+ writeFileSync(path.join(good, "package-lock.json"), "{}");+ writeFileSync(path.join(good, "Dockerfile"), "FROM node:22\n");+ writeFileSync(path.join(good, "README.md"), "# app\n");+ writeFileSync(path.join(good, ".env"), "KEY=1\n");+ writeFileSync(path.join(good, ".env.example"), "KEY=\n");+ writeFileSync(path.join(good, "src", "a.js"), "export const p = './data';\n");+ const all = evaluateChecklist(good, [...DEFAULT_CHECKLIST, { id: "future", text: "Future" }], { home: "/home/alice" });+ assert.deepEqual(all.map((r) => r.ok), [true, true, true, true, true, true, true, true, null]);++ writeFileSync(path.join(good, "src", "b.py"), 'DATA = "/home/alice/datasets/x.csv"\n');+ assert.equal(evaluateChecklist(good, [{ id: "no_abs_paths", text: "x" }], { home: "/home/alice" })[0].ok, false);+ rmSync(path.join(good, ".env.example"));+ assert.equal(evaluateChecklist(good, [{ id: "env_example", text: "x" }], { home: "/home/alice" })[0].ok, false, ".env without an example");+});++test("checklist IPC: an existing project folder only, never home, a root or a relative path", () => {+ const dir = project();+ assert.equal(projectChecklist({ path: dir, checklist: [] }).length, 8, "the default list when none is sent");+ assert.equal(projectChecklist({ path: os.homedir() }), null);+ assert.equal(projectChecklist({ path: "/" }), null);+ assert.equal(projectChecklist({ path: "relative/dir" }), null);+ assert.equal(projectChecklist({ path: path.join(dir, "missing") }), null);+ assert.equal(projectChecklist({}), null);+});diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjsindex 15da5f2a..e5dafedf 100644--- a/apps/desktop/electron/main.mjs+++ b/apps/desktop/electron/main.mjs@@ -95,6 +95,7 @@ import {import { installStdioErrorHandlers } from "./stdio-errors.mjs";import { createTurnGuard } from "./turn-guard.mjs";import { KEEP_AWAKE_FILE, createKeepAwake } from "./keep-awake.mjs";+import { projectChecklist } from "./buildathon-checklist.mjs";import {createRendererCrashRecovery,installSocketTypeOfServiceGuard,@@ -2207,6 +2208,11 @@ const desktopCommandHandlers = {const input = args[0] && typeof args[0] === "object" ? args[0] : {};return omnirushAccountStore.buildathonLink({ code: input.code });},+ // The rebuild checklist of one buildathon project, checked in its folder (cheap file checks).+ "omnirushBuildathonChecklist": async (event, ...args) => {+ const input = args[0] && typeof args[0] === "object" ? args[0] : {};+ return projectChecklist({ path: input.path, checklist: input.checklist });+ },"omnirushBuildathonTagSession": async (event, ...args) => {const input = args[0] && typeof args[0] === "object" ? args[0] : {};return omnirushAccountStore.buildathonTagSession({ sessionId: input.sessionId, track: input.track, project: input.project });diff --git a/apps/server/package.json b/apps/server/package.jsonindex ac4272d1..9a7f48b5 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.tsindex e8a4d511..7f8b3db1 100644--- a/apps/server/src/box/launch.ts+++ b/apps/server/src/box/launch.ts@@ -140,14 +140,20 @@ export function askedBackend({ env = process.env, stateDir }: { env?: NodeJS.Pro/*** On or off for a project, and why: OMNIRUSH_BOX=1|0 (every project), then- * the project's setting, then the server's default ("on"; "offer" shows a- * one-line offer until the project was offered it once; "off").+ * the project's setting, then (a buildathon project, buildathon-repro.ts) the+ * event's `repro.box`, then the server's default ("on"; "offer" shows a+ * one-line offer until the project was offered it once; "off"). A buildathon+ * project kept off by OMNIRUSH_BOX=0 or its own switch says so (`lessRepro`).+ * CLI: src/box/launch.js resolveMode, the same order.*/-export function resolveMode({ env = process.env, project, server, offered = false }: { env?: NodeJS.ProcessEnv; project: ProjectBoxMode; server: ServerBoxDefault; offered?: boolean }): { on: boolean; source: "env" | "project" | "server" | "default"; offer: boolean } {+export function resolveMode({ env = process.env, project, server, offered = false, buildathon = null }: { env?: NodeJS.ProcessEnv; project: ProjectBoxMode; server: ServerBoxDefault; offered?: boolean; buildathon?: "on" | "offer" | "off" | null }): { on: boolean; source: "env" | "project" | "server" | "default" | "buildathon"; offer: boolean; lessRepro?: true } {+ const lessRepro = buildathon === "on" || buildathon === "offer" ? { lessRepro: true as const } : {};const asked = String(env.OMNIRUSH_BOX ?? "").trim().toLowerCase();if (["1", "on", "true"].includes(asked)) return { on: true, source: "env", offer: false };- if (["0", "off", "false"].includes(asked)) return { on: false, source: "env", offer: false };- if (project === "on" || project === "off") return { on: project === "on", source: "project", offer: false };+ if (["0", "off", "false"].includes(asked)) return { on: false, source: "env", offer: false, ...lessRepro };+ if (project === "on" || project === "off") return { on: project === "on", source: "project", offer: false, ...(project === "off" ? lessRepro : {}) };+ if (buildathon === "on") return { on: true, source: "buildathon", offer: false };+ if (buildathon === "offer" && server !== "on") return { on: false, source: "buildathon", offer: !offered };if (server === "on") return { on: true, source: "server", offer: false };return { on: false, source: server === "offer" ? "server" : "default", offer: server === "offer" && !offered };}diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex f8711dd9..e3906840 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -33,6 +33,7 @@ import { detectStack, imageFor } from "./images.js";import { askedBackend, boxRun, planBox, pullLog, pullMarker, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";import type { BoxInstallLogPaths } from "./install-log.js";import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";+import { BUILDATHON_OFFER_NOTICE, buildathonBoxFor, buildathonProjectsFile, LESS_REPRO_NOTICE } from "../buildathon-repro.js";import { layerSizes, pullProgress, type PullProgress } from "./pull-progress.js";import { detectRuntime, type BackendAlternative, type DetectOptions, type RuntimeResult } from "./runtime.js";@@ -62,7 +63,7 @@ export type BoxStatus = {/** Whether the project's chats should run in its box. */on: boolean;/** "host-builds": the server's default would put it in the box, but its folder has this computer's builds (macOS, Windows). */- source: "env" | "project" | "server" | "default" | "host-builds";+ source: "env" | "project" | "server" | "default" | "host-builds" | "buildathon";/** The server offers the box and this project was not offered it yet. */offer: boolean;state: "off" | "unavailable" | "downloading" | "starting" | "ready" | "failed";@@ -262,7 +263,9 @@ export class BoxService {private async mode(workspace: BoxWorkspace) {const settings = await this.options.readSettings(workspace.id).catch(() => ({ mode: null, offered: false }));const server = this.serverDefault();- const resolved = resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered });+ // A buildathon project (the app lists them): the event's `repro.box` comes before the server's default.+ const buildathon = workspace.workspaceType === "local" ? this.buildathonBox(boxRoot(workspace)) : null;+ const resolved = resolveMode({ env: this.env, project: settings.mode, server, offered: settings.offered, buildathon });const gate = workspace.workspaceType === "local" ? this.hostGate(boxRoot(workspace), resolved) : null;// A box already running for the project keeps its chats (builds made since do not move them out).const running = this.projects.get(boxKey(boxRoot(workspace)))?.run;@@ -278,6 +281,14 @@ export class BoxService {* Null on Linux, with the box off, or when the folder has none.* OMNIRUSH_BOX_KEEP_NATIVE=off or OMNIRUSH_BOX_HOST_BUILDS=off skips it.*/+ private buildathonBox(root: string): "on" | "offer" | "off" | null {+ try {+ return buildathonBoxFor(root, buildathonProjectsFile(this.home));+ } catch {+ return null;+ }+ }+private hostGate(root: string, mode: { on: boolean; source: string }): { native: boolean; things: string; notice: string } | null {if (!mode.on || !hostRules(this.platform)) return null;if (String(this.env.OMNIRUSH_BOX_KEEP_NATIVE ?? "").trim().toLowerCase() === "off") return null;@@ -289,7 +300,8 @@ export class BoxService {return null;}if (!found.found) return null;- const native = mode.source === "server";+ // Only a default (the server's, or the buildathon's) keeps the folder here; the user's own choice does not.+ const native = mode.source === "server" || mode.source === "buildathon";return { native, things: hostBuildThings(found), notice: hostBuildsNotice(native ? "native" : "explicit", { platform: this.platform, result: found }) };}@@ -425,7 +437,7 @@ export class BoxService {}async status(workspace: BoxWorkspace, { fresh = false }: { fresh?: boolean } = {}): Promise<BoxStatus> {- const { settings, server, on, source, offer, hostBuilds: gate } = await this.mode(workspace);+ const { settings, server, on, source, offer, hostBuilds: gate, lessRepro } = await this.mode(workspace);// The server's "offer": shown once per folder (CLI: the tip, once per folder).if (offer && workspace.workspaceType === "local") await this.options.writeSettings(workspace.id, { offered: true }).catch(() => undefined);const root = boxRoot(workspace);@@ -495,7 +507,11 @@ export class BoxService {progress,container,platform: this.platform,- notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`) : gate?.native ? gate.notice : null,+ notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`)+ : gate?.native ? gate.notice+ : lessRepro ? LESS_REPRO_NOTICE+ : offer && source === "buildathon" ? BUILDATHON_OFFER_NOTICE+ : null,error: run?.box?.error ?? (record?.state === "off" || record?.state === "failed" ? record.error || null : null),boxNotice: on && hostRules(this.platform) ? hostBuildsNotice("box", { platform: this.platform }) : null,};@@ -572,7 +588,7 @@ export class BoxService {// A chat with turns but no checkpoint ran on this machine (reopened, or started in this run before the// server's default reached the app, or while the image downloaded): when only the server's default// turned the box on, it goes on here (new chats get the box); a project turned on by its user moves it.- if (capture && turnsSoFar > 0 && !this.nativeChats.has(sessionId) && !this.boxedChats.has(sessionId) && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && (await this.mode(workspace)).source === "server") {+ if (capture && turnsSoFar > 0 && !this.nativeChats.has(sessionId) && !this.boxedChats.has(sessionId) && !this.turns.has(sessionId) && savedTurns(this.snapshotDir(sessionId)) === 0 && ["server", "buildathon"].includes((await this.mode(workspace)).source)) {this.nativeChats.set(sessionId, run.key);await this.writeProjects();this.log("info", "box: a chat that ran on this machine stays there", { sessionId, turnsBefore });diff --git a/apps/server/src/buildathon-repro.test.ts b/apps/server/src/buildathon-repro.test.tsnew file mode 100644index 00000000..3f017df2--- /dev/null+++ b/apps/server/src/buildathon-repro.test.ts@@ -0,0 +1,180 @@+// Buildathon reproducibility mode (contract "Reproducibility mode"; the CLI's+// test/buildathon.test.js covers the same cases): the app's buildathon+// projects get the event's rules in the engine's instructions and, with+// `repro.box` on, the Linux sandbox; the project's own switch and the+// macOS / Windows host-builds rule still win.+import { afterEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";++import { rememberServerDefault, resolveMode } from "./box/launch.js";+import { BoxService, type BoxWorkspace } from "./box/service.js";+import {+ AGENT_RULES_HEADING,+ BUILDATHON_OFFER_NOTICE,+ BUILDATHON_PROJECTS_FILE,+ DEFAULT_AGENT_RULES,+ LESS_REPRO_NOTICE,+ agentRulesFor,+ buildathonBoxFor,+ parseReproBlock,+ readReproState,+ reproStateFromBody,+ writeReproState,+} from "./buildathon-repro.js";+import { OmniRushBuildathon } from "./opencode-plugins/omnirush-buildathon.js";++const MACHO = Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00, 0x00, 0x01, 0, 0, 0, 0, 2, 0, 0, 0]);+const savedBoxHome = process.env.OMNIRUSH_BOX_HOME;++afterEach(() => {+ if (savedBoxHome === undefined) delete process.env.OMNIRUSH_BOX_HOME;+ else process.env.OMNIRUSH_BOX_HOME = savedBoxHome;+});++function tmp(prefix = "omnirush-bt-"): string {+ return mkdtempSync(path.join(os.tmpdir(), prefix));+}++function put(root: string, rel: string, content: Buffer | string, mode = 0o644): void {+ const file = path.join(root, rel);+ mkdirSync(path.dirname(file), { recursive: true });+ writeFileSync(file, content, { mode });+}++const later = new Date(Date.now() + 5 * 86_400_000).toISOString();++async function listProjects(home: string, projects: unknown[], repro: unknown = undefined, deadline = later): Promise<void> {+ await writeReproState(reproStateFromBody({ repro, projects, deadline_at: deadline }), path.join(home, BUILDATHON_PROJECTS_FILE));+}++describe("buildathon repro: state", () => {+ test("the repro block: the server's values, else the contract's defaults (box on)", () => {+ expect(parseReproBlock(undefined)).toEqual({ box: "on", agentRules: DEFAULT_AGENT_RULES });+ expect(parseReproBlock({ box: "offer", agent_rules: "Use make." })).toEqual({ box: "offer", agentRules: "Use make." });+ expect(parseReproBlock({ box: "maybe", agent_rules: "" }).box).toBe("on");+ });++ test("projects: absolute folders, never home, temp or a root; past the deadline nothing applies", async () => {+ const home = tmp("boxhome-");+ const project = tmp();+ await listProjects(home, [project, os.homedir(), os.tmpdir(), "/", "relative/x", 7], { box: "on" });+ const file = path.join(home, BUILDATHON_PROJECTS_FILE);+ expect(readReproState(file)!.keys.length).toBe(1);+ expect(buildathonBoxFor(project, file)).toBe("on");+ expect(buildathonBoxFor(path.join(project, "..", path.basename(project)), file)).toBe("on");+ expect(buildathonBoxFor(tmp(), file)).toBeNull();+ expect(buildathonBoxFor(project, file, Date.now() + 6 * 86_400_000)).toBeNull();+ // An empty list removes the file.+ await listProjects(home, []);+ expect(readReproState(file)).toBeNull();+ });++ test("the rules for a chat: in a listed project only, under the heading, the server's text or the default", async () => {+ const home = tmp("boxhome-");+ const project = tmp();+ const file = path.join(home, BUILDATHON_PROJECTS_FILE);+ await listProjects(home, [project]);+ expect(agentRulesFor(project, file)).toBe(`${AGENT_RULES_HEADING}\n\n${DEFAULT_AGENT_RULES}`);+ expect(agentRulesFor(tmp(), file)).toBeNull();+ await listProjects(home, [project], { agent_rules: "Keep a Makefile." });+ expect(agentRulesFor(project, file)).toBe(`${AGENT_RULES_HEADING}\n\nKeep a Makefile.`);+ });+});++describe("buildathon repro: the engine plugin", () => {+ test("adds the rules to a listed project's system prompt once; other folders are left alone", async () => {+ const home = tmp("boxhome-");+ process.env.OMNIRUSH_BOX_HOME = home;+ const project = tmp();+ await listProjects(home, [project]);+ const hooks = await OmniRushBuildathon({ directory: project });+ const output = { system: ["You are the agent."] };+ await hooks["experimental.chat.system.transform"]({}, output);+ await hooks["experimental.chat.system.transform"]({}, output);+ expect(output.system).toEqual(["You are the agent.", `${AGENT_RULES_HEADING}\n\n${DEFAULT_AGENT_RULES}`]);++ const other = { system: ["You are the agent."] };+ await (await OmniRushBuildathon({ directory: tmp() }))["experimental.chat.system.transform"]({}, other);+ expect(other.system).toEqual(["You are the agent."]);+ });+});++describe("buildathon repro: the box", () => {+ test("resolveMode: the env flag, then the project's switch (off: less reproducible), then repro.box, then the server", () => {+ expect(resolveMode({ env: {}, project: null, server: "off", buildathon: "on" })).toEqual({ on: true, source: "buildathon", offer: false });+ expect(resolveMode({ env: {}, project: null, server: "offer", buildathon: "on" })).toEqual({ on: true, source: "buildathon", offer: false });+ expect(resolveMode({ env: {}, project: "off", server: "on", buildathon: "on" })).toEqual({ on: false, source: "project", offer: false, lessRepro: true });+ expect(resolveMode({ env: { OMNIRUSH_BOX: "0" }, project: null, server: "on", buildathon: "on" })).toEqual({ on: false, source: "env", offer: false, lessRepro: true });+ expect(resolveMode({ env: {}, project: null, server: "off", buildathon: "offer" })).toEqual({ on: false, source: "buildathon", offer: true });+ expect(resolveMode({ env: {}, project: null, server: "on", buildathon: "offer" })).toEqual({ on: true, source: "server", offer: false });+ expect(resolveMode({ env: {}, project: null, server: "off", buildathon: "off" })).toEqual({ on: false, source: "default", offer: false });+ expect(resolveMode({ env: {}, project: null, server: "off", buildathon: null })).toEqual({ on: false, source: "default", offer: false });+ });++ type Settings = Map<string, { mode: "on" | "off" | null; offered: boolean }>;+ function service(stateDir: string, home: string, workspace: BoxWorkspace, settings: Settings, platform: NodeJS.Platform) {+ return new BoxService({+ stateDir,+ readSettings: async (id) => settings.get(id) ?? { mode: null, offered: false },+ writeSettings: async (id, update) => {+ const current = settings.get(id) ?? { mode: null, offered: false };+ settings.set(id, { mode: update.mode === undefined ? current.mode : update.mode, offered: update.offered ?? current.offered });+ },+ workspaces: () => [workspace],+ pluginPath: () => "/plugins/omnirush-box.js",+ env: { OMNIRUSH_BOX_HOME: home, PATH: "", OMNIRUSH_BOX_RUNTIME: "/nonexistent/docker" },+ platform,+ });+ }++ test("a buildathon project's chats go in the box over the server's off; its own switch keeps them here with one line", async () => {+ const stateDir = tmp("state-");+ const home = tmp("boxhome-");+ const root = tmp();+ put(root, "README.md", "# x\n");+ rememberServerDefault(stateDir, { local_box: { default: "off" } });+ const workspace: BoxWorkspace = { id: "ws_bt", path: root, workspaceType: "local" };+ const settings: Settings = new Map();+ expect(await service(stateDir, home, workspace, settings, "linux").status(workspace)).toMatchObject({ on: false, source: "default" });+ await listProjects(home, [root], { box: "on" });+ const boxes = service(stateDir, home, workspace, settings, "linux");+ expect(await boxes.status(workspace)).toMatchObject({ on: true, source: "buildathon", hostBuilds: null });+ const off = await boxes.setMode(workspace, "off");+ expect(off).toMatchObject({ mode: "off", on: false, source: "project", notice: LESS_REPRO_NOTICE });+ // Back to the default: the box again.+ expect(await boxes.setMode(workspace, null)).toMatchObject({ on: true, source: "buildathon" });+ });++ test("repro.box offer: the offer with its own line; off: the server's default as before", async () => {+ const stateDir = tmp("state-");+ const home = tmp("boxhome-");+ const root = tmp();+ rememberServerDefault(stateDir, { local_box: { default: "off" } });+ const workspace: BoxWorkspace = { id: "ws_offer", path: root, workspaceType: "local" };+ await listProjects(home, [root], { box: "offer" });+ expect(await service(stateDir, home, workspace, new Map(), "linux").status(workspace)).toMatchObject({ on: false, source: "buildathon", offer: true, notice: BUILDATHON_OFFER_NOTICE });+ await listProjects(home, [root], { box: "off" });+ expect(await service(stateDir, home, workspace, new Map(), "linux").status(workspace)).toMatchObject({ on: false, source: "default", offer: false, notice: null });+ });++ test("host builds still win on macOS: a Mac-built buildathon project stays on this Mac", async () => {+ const stateDir = tmp("state-");+ const home = tmp("boxhome-");+ const root = tmp();+ put(root, "package.json", "{}");+ put(root, "node_modules/esbuild/bin/esbuild", MACHO, 0o755);+ put(root, "node_modules/@esbuild/darwin-arm64/bin/esbuild", MACHO, 0o755);+ put(root, "node_modules/@img/sharp-darwin-arm64/lib/sharp-darwin-arm64.node", MACHO);+ put(root, "node_modules/better-sqlite3/build/Release/better_sqlite3.node", MACHO);+ mkdirSync(path.join(root, "node_modules/.bin"), { recursive: true });+ symlinkSync("../esbuild/bin/esbuild", path.join(root, "node_modules/.bin/esbuild"));+ rememberServerDefault(stateDir, { local_box: { default: "off" } });+ await listProjects(home, [root], { box: "on" });+ const workspace: BoxWorkspace = { id: "ws_macbt", path: root, workspaceType: "local" };+ const status = await service(stateDir, home, workspace, new Map(), "darwin").status(workspace);+ expect(status).toMatchObject({ on: false, source: "host-builds", hostBuilds: { native: true } });+ expect(status.notice).toBe(status.hostBuilds!.notice);+ });+});diff --git a/apps/server/src/buildathon-repro.ts b/apps/server/src/buildathon-repro.tsnew file mode 100644index 00000000..365a4559--- /dev/null+++ b/apps/server/src/buildathon-repro.ts@@ -0,0 +1,145 @@+// Buildathon reproducibility mode (contract "Reproducibility mode"; CLI:+// assets/extensions/omnirush/buildathon-lib.js, keep the two in step).+//+// The app sends the event's `repro` block and its buildathon projects (a+// folder with a track, or one skipped inside the event) to the server,+// which keeps them in one file next to the box's projects file. Two readers:+// the box service (the project's chats run in its box when `box` is "on")+// and the engine plugin (opencode-plugins/omnirush-buildathon.ts, which adds+// the agent rules to the chat's instructions). Nothing is written into the+// user's project.+//+// Kept small and free of server imports: the engine plugin bundles it.++import { readFileSync, statSync } from "node:fs";+import { mkdir, rename, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { boxHome, keyOf } from "./box/plugin-lib.js";++/** The server's default rules, word for word (clients embed the same as the fallback). */+export const DEFAULT_AGENT_RULES = "This project is part of the OmniRush Buildathon and must rebuild from scratch on a clean Linux machine. Keep every file the project needs inside this folder and use git, committing after each working step. Pin the runtime version (.nvmrc / .python-version / go.mod toolchain / rust-toolchain.toml) and always keep a lockfile; install dependencies only into the project (no global installs, no sudo outside the Dockerfile). Maintain a Dockerfile that installs every system package and dependency and can build and run the project, a single test command (e.g. `make test`) that works offline, and a README with exact setup, run, test and deploy steps. Never hard-code absolute paths from this machine or put secrets in files (use .env.example). After each change, run the tests.";++/** The heading the rules go under (the CLI's rules file starts the same way). */+export const AGENT_RULES_HEADING = "# OmniRush Buildathon: reproducibility";++export const BUILDATHON_PROJECTS_FILE = "buildathon-projects.json";++/** One line on a buildathon project whose sandbox its user turned off. */+export const LESS_REPRO_NOTICE = "This buildathon project runs on this computer (sandbox off here), so it is less reproducible. Turn the Linux sandbox on to run it in the box.";+/** The "offer" for a buildathon project. */+export const BUILDATHON_OFFER_NOTICE = "This buildathon project rebuilds more reliably in the Linux sandbox. Turn it on to run its chats there.";++export type ReproBox = "on" | "offer" | "off";+export type BuildathonReproState = {+ box: ReproBox;+ agentRules: string;+ /** Box keys (box/common.ts boxKey) of the buildathon projects. */+ keys: string[];+ /** After this (the event's deadline) the state no longer applies. */+ until: number | null;+ updated: number;+};++const BOX_MODES = new Set(["on", "offer", "off"]);+const MAX_RULES = 8_000;+const MAX_PROJECTS = 200;++function text(value: unknown): string | null {+ return typeof value === "string" && value.trim() ? value.trim() : null;+}++export function buildathonProjectsFile(home: string = boxHome()): string {+ return path.join(home, BUILDATHON_PROJECTS_FILE);+}++/** The `repro` block's box and rules; a missing or partial block falls back to the defaults (box on). */+export function parseReproBlock(block: unknown): { box: ReproBox; agentRules: string } {+ const value = block && typeof block === "object" && !Array.isArray(block) ? block as Record<string, unknown> : {};+ const rules = text(value.agent_rules ?? value.agentRules);+ return {+ box: BOX_MODES.has(value.box as string) ? value.box as ReproBox : "on",+ agentRules: rules && rules.length <= MAX_RULES ? rules : DEFAULT_AGENT_RULES,+ };+}++/** A folder that is never a project of its own: a drive or file-system root, the home folder, the temp folder. */+export function genericFolder(dir: string, { home = os.homedir() }: { home?: string } = {}): boolean {+ const key = path.resolve(dir);+ if (path.dirname(key) === key) return true;+ return [home, os.tmpdir()].filter(Boolean).map((d) => path.resolve(d)).includes(key);+}++/**+ * The app's PUT body ({ repro, projects: [folder paths], deadline_at }) as the+ * state to keep; projects: absolute folders, generic ones left out.+ */+export function reproStateFromBody(body: Record<string, unknown>, { now = Date.now(), home = os.homedir() }: { now?: number; home?: string } = {}): BuildathonReproState {+ const { box, agentRules } = parseReproBlock(body.repro);+ const folders = Array.isArray(body.projects) ? body.projects : [];+ const keys = new Set<string>();+ for (const folder of folders.slice(0, MAX_PROJECTS)) {+ const dir = text(folder);+ if (!dir || !path.isAbsolute(dir) || genericFolder(dir, { home })) continue;+ keys.add(keyOf(dir));+ }+ const until = typeof body.deadline_at === "string" && Number.isFinite(Date.parse(body.deadline_at)) ? Date.parse(body.deadline_at) : null;+ return { box, agentRules, keys: [...keys].sort(), until, updated: now };+}++/** Saves the state (an empty project list removes the file). */+export async function writeReproState(state: BuildathonReproState, file = buildathonProjectsFile()): Promise<void> {+ if (!state.keys.length) {+ await rm(file, { force: true });+ cache = null;+ return;+ }+ await mkdir(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ await writeFile(tmp, `${JSON.stringify({ box: state.box, agent_rules: state.agentRules, keys: state.keys, until: state.until, updated: state.updated })}\n`, { mode: 0o600 });+ await rename(tmp, file);+ cache = null;+}++let cache: { file: string; mtime: number; state: BuildathonReproState | null } | null = null;++/** The kept state, re-read when the file changes; null when there is none or it is past the deadline. */+export function readReproState(file = buildathonProjectsFile(), now = Date.now()): BuildathonReproState | null {+ let mtime = 0;+ try {+ mtime = statSync(file).mtimeMs;+ } catch {+ cache = null;+ return null;+ }+ if (!cache || cache.file !== file || cache.mtime !== mtime) {+ let state: BuildathonReproState | null = null;+ try {+ const value = JSON.parse(readFileSync(file, "utf8"));+ const { box, agentRules } = parseReproBlock(value);+ const keys = Array.isArray(value?.keys) ? value.keys.filter((key: unknown): key is string => typeof key === "string") : [];+ state = { box, agentRules, keys, until: typeof value?.until === "number" ? value.until : null, updated: Number(value?.updated) || 0 };+ } catch {+ state = null;+ }+ cache = { file, mtime, state };+ }+ const state = cache.state;+ if (!state || (state.until !== null && now > state.until)) return null;+ return state;+}++/** The buildathon project a folder belongs to: its `box` setting, or null when it is not one. */+export function buildathonBoxFor(root: string, file = buildathonProjectsFile(), now = Date.now()): ReproBox | null {+ const state = readReproState(file, now);+ if (!state) return null;+ return state.keys.includes(keyOf(root)) ? state.box : null;+}++/** The rules for a chat in `dir` (with their heading), or null outside a buildathon project. */+export function agentRulesFor(dir: string, file = buildathonProjectsFile(), now = Date.now()): string | null {+ const state = readReproState(file, now);+ if (!state || !state.keys.includes(keyOf(dir))) return null;+ return `${AGENT_RULES_HEADING}\n\n${state.agentRules}`;+}diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.tsindex f81d4622..12d6c0a7 100644--- a/apps/server/src/omnirush-extensions-plugin-path.ts+++ b/apps/server/src/omnirush-extensions-plugin-path.ts@@ -44,3 +44,4 @@ export const omnirushReasoningEffortPluginPath = () => omnirushPluginPath("omnirexport const omnirushSwarmPluginPath = () => omnirushPluginPath("omnirush-swarm");export const omnirushMcpPolicyPluginPath = () => omnirushPluginPath("omnirush-mcp-policy");export const omnirushBudgetWrapPluginPath = () => omnirushPluginPath("omnirush-budget-wrap");+export const omnirushBuildathonPluginPath = () => omnirushPluginPath("omnirush-buildathon");diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.tsindex f953b6a0..b52e6110 100644--- a/apps/server/src/omnirush-runtime-config.ts+++ b/apps/server/src/omnirush-runtime-config.ts@@ -29,6 +29,7 @@ import {omnirushBudgetWrapPluginPath,omnirushOfficeAttachmentsPluginPath,omnirushSpreadsheetsPluginPath,+ omnirushBuildathonPluginPath,omnirushChromeDevtoolsPluginPath,omnirushPdfAttachmentsPluginPath,} from "./omnirush-extensions-plugin-path.js";@@ -272,6 +273,8 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(omnirushReasoningEffortPluginPath(),omnirushTitleRecoveryPluginPath(),omnirushSwarmPluginPath(),+ // Buildathon projects only (the app lists them): the event's reproducibility rules.+ omnirushBuildathonPluginPath(),...runtimePluginList(runtimeConfig),// This must be last: user/runtime plugins may not reintroduce MCP// configuration or replace the deny rules.diff --git a/apps/server/src/opencode-plugins/omnirush-buildathon.ts b/apps/server/src/opencode-plugins/omnirush-buildathon.tsnew file mode 100644index 00000000..128f3a29--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-buildathon.ts@@ -0,0 +1,26 @@+// Engine plugin: in a buildathon project (buildathon-repro.ts; the app lists+// them), the event's reproducibility rules join the chat's instructions.+// The CLI adds the same text as an engine instructions file in its own state+// folder; neither ever writes into the project. Other folders are left alone.+// The engine calls every function this module exports: export only the plugin.++import path from "node:path";++import { agentRulesFor } from "../buildathon-repro.js";++export const OmniRushBuildathon = async ({ directory }: { directory?: string }) => {+ const root = path.resolve(directory || process.cwd());+ return {+ "experimental.chat.system.transform": async (_input: unknown, output: { system?: unknown }) => {+ if (!Array.isArray(output.system)) return;+ let rules: string | null = null;+ try {+ rules = agentRulesFor(root);+ } catch {+ rules = null;+ }+ // In place: the engine keeps its own reference to this array.+ if (rules && !output.system.includes(rules)) output.system.push(rules);+ },+ };+};diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 2f9fafb1..02c2334c 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -176,6 +176,8 @@ import {writeOmniRushWorkspaceConfig,} from "./omnirush-workspace-config-store.js";import { boxServiceFor } from "./box/desktop.js";+import { boxHome } from "./box/common.js";+import { buildathonProjectsFile, reproStateFromBody, writeReproState } from "./buildathon-repro.js";import { prepareBoxInstallLog } from "./box/install-log.js";import { rememberServerDefault, watchServerDefault } from "./box/launch.js";import { normalizeBackend } from "./box/backends/index.js";@@ -3897,6 +3899,26 @@ function createRoutes(return jsonResponse({ ...status, engine });});+ // Buildathon projects (buildathon-repro.ts): the app sends the event's `repro` block and the+ // folders that are buildathon projects; their chats get the event's rules and, with `box: "on"`,+ // the sandbox. `{ "projects": [] }` clears it.+ addRoute(routes, "PUT", "/runtime-config/buildathon", "client", async (ctx) => {+ ensureWritable(config);+ requireClientScope(ctx, "collaborator");+ const body = await readJsonBody(ctx.request);+ if (!Array.isArray(body.projects) || Object.keys(body).some((key) => !["repro", "projects", "deadline_at"].includes(key))) {+ throw new ApiError(400, "invalid_payload", "projects must be a list of folders; repro and deadline_at are optional");+ }+ const boxes = boxServiceFor(config);+ const before = JSON.stringify(await boxes.engineBits());+ const state = reproStateFromBody(body);+ await writeReproState(state, buildathonProjectsFile(boxHome()));+ // New chats of a buildathon project start in its box: planned now, in the background (a missing image downloads).+ void boxes.ensureAll();+ const engine = JSON.stringify(await boxes.engineBits()) === before ? { status: "unchanged" as const } : await applyBoxEngineConfig(config, "local_box");+ return jsonResponse({ ok: true, projects: state.keys.length, box: state.box, engine });+ });+// Try again now: a box that failed to start (or a project that went on without it) is planned again.addRoute(routes, "POST", "/workspace/:id/box/retry", "client", async (ctx) => {ensureWritable(config);diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex efa246e3..1ecb9125 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -324,12 +324,20 @@ export type OmniRushBuildathonSubmission = {checks: Array<{ id: string; ok: boolean; text: string }>;locked: boolean;};+/** The event's reproducibility settings (defaults when the server sends none). */+export type OmniRushBuildathonRepro = {+ box: "on" | "offer" | "off";+ agentRules: string;+ checklist: Array<{ id: string; text: string }>;+};+export type OmniRushBuildathonCheck = { id: string; text: string; ok: boolean | null };export type OmniRushBuildathonStatus = {enrolled: true;serverTime: string | null;event: OmniRushBuildathonEvent;participant: OmniRushBuildathonParticipant | null;submission: OmniRushBuildathonSubmission | null;+ repro: OmniRushBuildathonRepro;};export type OmniRushBuildathonSession = {sessionId: string;@@ -901,6 +909,10 @@ export type DesktopCommandMap = {omnirushBuildathon: { args: []; result: OmniRushBuildathonStatus | null };omnirushBuildathonSessions: { args: []; result: OmniRushBuildathonSession[] | null };omnirushBuildathonLink: { args: [input: { code: string }]; result: OmniRushBuildathonLinkResult };+ omnirushBuildathonChecklist: {+ args: [input: { path: string; checklist: Array<{ id: string; text: string }> }];+ result: OmniRushBuildathonCheck[] | null;+ };omnirushBuildathonTagSession: {args: [input: { sessionId: string; track: string; project?: string | null }];result: OmniRushBuildathonTagResult;