Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: steadier run records in the app

ogsamrat2c420f5864fc
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 2274ddea..cba439df 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -216,6 +216,7 @@ export class CaptureHost {
onLateWrites: (late) => this.recordLateWrites(late),
// What became of each session's base: recorded in its uploads, so no missing base goes unexplained.
onProjectArchive: (sessionId, outcome) => this.sessionUploader.recordProjectArchive(sessionId, outcome),
+ onTurnArchive: (sessionId, result) => this.sessionUploader.archiveTurnChecked(sessionId, result),
...(baseIdleMs !== undefined ? { baseIdleMs } : {}),
...(baseMaxDeferMs !== undefined ? { baseMaxDeferMs } : {}),
});
diff --git a/apps/server/src/context/PARITY.sha256 b/apps/server/src/context/PARITY.sha256
index e054688c..b2e5fd1a 100644
--- a/apps/server/src/context/PARITY.sha256
+++ b/apps/server/src/context/PARITY.sha256
@@ -1,9 +1,11 @@
# The capture-context modules are the same files in omnirush-cli (assets/extensions/omnirush/capture/context/)
# and omnirush-gui (apps/server/src/context/). A change to one must be ported to the other and this list updated in both.
+9e4e14b658182753f54ab2176ec95555c3b5ef3ec2cb458976b56d0254f7155b capture-gaps.ts
b7d4fad94c133cb4303db934a5bb8e84dcb09dcc6720dc9cc7245d7c8205fa11 commands.ts
e13f86577014b52affc4c2336630eedcac277b974939c6741119a62b7fda439b ephemeral.ts
+1bd9abb65af931b6f32d0334c97fbfedba7ab70c9a86351dfbc92ef208ec1f33 exec-witness.ts
5f89ff17f225ac47700d31f34c358591c8fbde794a45c156d607e5a675a2ba73 exec.ts
-6a0aef5537b449d31aff2751cf45d844f978cd5d37197998dfb029a10483709c index.ts
+373951bb0c97e39426db12354a9d28df026f73abe64ea905ebe51f86fe91ce10 index.ts
57c97292c7ca65cb1a024e0206af27ae6d3fbdf06c2973dfbfd3760183d02892 install-log-assets.ts
d204176a44609f7c3da5bcedfada71fdd79703d0c854e3c9632b94e9be007a6f install-log.ts
a9474cc5087b39e56f79bcd7e4cdfa9fcb748f26505bf6ad0f891c17393407ac network.ts
diff --git a/apps/server/src/context/capture-gaps.ts b/apps/server/src/context/capture-gaps.ts
new file mode 100644
index 00000000..ddbd7e5e
--- /dev/null
+++ b/apps/server/src/context/capture-gaps.ts
@@ -0,0 +1,147 @@
+// Durable capture-gap log (`context.capture_gaps`): what could not be
+// captured for a session and why, kept on disk per session so a crash or a
+// restart does not lose it. Each note is one JSON line in
+// <dir>/<session>.jsonl; the session's whole list (open and resolved) is
+// sent again at every session start, resume and recovery included, and at
+// each turn end that noted something. Identical in the CLI and the desktop app.
+
+import { existsSync } from "node:fs";
+import { appendFile, mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+export const CAPTURE_GAPS_SCHEMA = "omnirush.capture-gaps.v1";
+/** Logs untouched this long are removed (the session is long over). */
+export const CAPTURE_GAPS_MAX_AGE_MS = 14 * 24 * 60 * 60_000;
+/** Distinct gaps kept per session (by `what`); later ones only count. */
+const MAX_GAPS = 200;
+const SESSION_ID = /^[A-Za-z0-9._:-]{8,128}$/;
+
+export type CaptureGap = {
+ /** What is missing: a section, an event kind, an upload. */
+ what: string;
+ /** Why: timeout, failed, refused, spooled, ... */
+ why: string;
+ turn: number | null;
+ first_at: string;
+ last_at: string;
+ count: number;
+ /** What brings it back, when anything does (spool_retry, chain_reopen_next_prompt, ...). */
+ recovery?: string | null;
+ detail?: string | null;
+ resolved_at?: string | null;
+};
+
+type Line = { at: string; what: string; why?: string; turn?: number | null; recovery?: string | null; detail?: string | null; resolved?: boolean };
+
+/** The session's gaps from its log lines, by `what` (a resolve line closes the open one). */
+export function foldGaps(lines: Line[]): CaptureGap[] {
+ const gaps = new Map<string, CaptureGap>();
+ for (const line of lines) {
+ if (!line || typeof line.what !== "string" || typeof line.at !== "string") continue;
+ const known = gaps.get(line.what);
+ if (line.resolved) {
+ if (known && !known.resolved_at) known.resolved_at = line.at;
+ continue;
+ }
+ if (known && !known.resolved_at) {
+ known.last_at = line.at;
+ known.count += 1;
+ known.why = line.why ?? known.why;
+ if (line.detail) known.detail = line.detail;
+ continue;
+ }
+ if (!known && gaps.size >= MAX_GAPS) continue;
+ gaps.set(line.what, { what: line.what, why: line.why ?? "unknown", turn: line.turn ?? null, first_at: line.at, last_at: line.at, count: 1, recovery: line.recovery ?? null, detail: line.detail ?? null, resolved_at: null });
+ }
+ return [...gaps.values()];
+}
+
+export class CaptureGapLog {
+ private readonly written = new Map<string, Promise<void>>();
+ /** Sessions with a note since their gaps were last sent. */
+ private readonly dirty = new Set<string>();
+ /** Open gaps (by `what`) per session this process noted or read back. */
+ private readonly open = new Map<string, Set<string>>();
+
+ constructor(private readonly dir: string | null, private readonly now: () => number = Date.now) {}
+
+ private file(sessionId: string): string | null {
+ return this.dir && SESSION_ID.test(sessionId) ? join(this.dir, `${sessionId}.jsonl`) : null;
+ }
+
+ private append(sessionId: string, line: Line): Promise<void> {
+ this.dirty.add(sessionId);
+ const file = this.file(sessionId);
+ const previous = this.written.get(sessionId) ?? Promise.resolve();
+ // One write after another per session: lines never interleave.
+ const next = previous.then(async () => {
+ if (!file || !this.dir) return;
+ await mkdir(this.dir, { recursive: true });
+ await appendFile(file, `${JSON.stringify(line)}\n`, "utf8");
+ }).catch(() => undefined);
+ this.written.set(sessionId, next);
+ return next;
+ }
+
+ note(sessionId: string, gap: { what: string; why: string; turn?: number | null; recovery?: string | null; detail?: string | null }): Promise<void> {
+ const open = this.open.get(sessionId) ?? new Set<string>();
+ open.add(gap.what);
+ this.open.set(sessionId, open);
+ return this.append(sessionId, { at: new Date(this.now()).toISOString(), ...gap, detail: gap.detail ? String(gap.detail).slice(0, 300) : null });
+ }
+
+ /** Closes an open gap; nothing is written when the session has none of that name (the common case). */
+ resolve(sessionId: string, what: string): Promise<void> {
+ const open = this.open.get(sessionId);
+ if (open ? !open.delete(what) : !(this.file(sessionId) && existsSync(this.file(sessionId)!))) return Promise.resolve();
+ return this.append(sessionId, { at: new Date(this.now()).toISOString(), what, resolved: true });
+ }
+
+ /** How many gaps of the session are open whose name starts with `prefix` (this process's view). */
+ openCount(sessionId: string, prefix = ""): number {
+ return [...(this.open.get(sessionId) ?? [])].filter((what) => what.startsWith(prefix)).length;
+ }
+
+ /** Whether the session noted something since `taken` last ran for it. */
+ pending(sessionId: string): boolean {
+ return this.dirty.has(sessionId);
+ }
+
+ /** The session's gaps (all of them, from disk), marking them sent. */
+ async take(sessionId: string): Promise<CaptureGap[]> {
+ this.dirty.delete(sessionId);
+ await this.written.get(sessionId);
+ const file = this.file(sessionId);
+ if (!file) return [];
+ let text = "";
+ try {
+ text = await readFile(file, "utf8");
+ } catch {
+ return [];
+ }
+ const lines: Line[] = [];
+ for (const raw of text.split("\n")) {
+ if (!raw.trim()) continue;
+ try {
+ lines.push(JSON.parse(raw));
+ } catch {
+ // A line cut by a crash.
+ }
+ }
+ const gaps = foldGaps(lines);
+ this.open.set(sessionId, new Set(gaps.filter((gap) => !gap.resolved_at).map((gap) => gap.what)));
+ return gaps;
+ }
+
+ /** Removes logs untouched for CAPTURE_GAPS_MAX_AGE_MS. Never throws. */
+ async prune(maxAgeMs = CAPTURE_GAPS_MAX_AGE_MS): Promise<void> {
+ if (!this.dir) return;
+ const names = await readdir(this.dir).catch(() => [] as string[]);
+ for (const name of names) {
+ if (!name.endsWith(".jsonl")) continue;
+ const file = join(this.dir, name);
+ const info = await stat(file).catch(() => null);
+ if (info && this.now() - info.mtimeMs > maxAgeMs) await rm(file, { force: true }).catch(() => undefined);
+ }
+ }
+}
diff --git a/apps/server/src/context/exec-witness.ts b/apps/server/src/context/exec-witness.ts
new file mode 100644
index 00000000..e31c2b57
--- /dev/null
+++ b/apps/server/src/context/exec-witness.ts
@@ -0,0 +1,78 @@
+// Execution witness of one shell tool call (`context.exec`): the shell the
+// engine runs it with, the argv it spawns, the folder it runs in, the
+// program the command starts and the machine (OS, architecture, version).
+// The engine never reports its shell, so it is chosen here by the engine's
+// own rule (core/src/shell.ts `acceptable()`, tool/shell.ts `cmd()`), and
+// `shell.how` says which branch of that rule picked it. Identical in the CLI
+// and the desktop app.
+
+import nodePath from "node:path";
+import { existsSync } from "node:fs";
+
+import { resolveCommand } from "../command-guard.js";
+
+export const EXEC_SCHEMA = "omnirush.exec.v1";
+
+/** Shells the engine refuses from $SHELL (core/src/shell.ts META deny). */
+const DENIED = new Set(["fish", "nu"]);
+const POWERSHELL = new Set(["powershell", "pwsh"]);
+
+export type ShellChoice = { path: string; name: string; how: "config" | "env_shell" | "pwsh" | "powershell" | "git_bash" | "comspec" | "zsh_default" | "bash_on_path" | "sh_fallback" | "box" };
+
+type Lookup = (command: string) => string | null;
+
+function shellName(file: string, platform: NodeJS.Platform): string {
+ const parse = platform === "win32" ? nodePath.win32.parse : nodePath.posix.parse;
+ return (platform === "win32" ? parse(file).name : nodePath.posix.basename(file)).toLowerCase();
+}
+
+/** The engine's shell for a tool call (`configShell`: the config's `shell`, set for a box run). */
+export function engineShell(input: { platform: NodeJS.Platform; env: NodeJS.ProcessEnv; configShell?: string | null; which?: Lookup; exists?: (file: string) => boolean }): ShellChoice | null {
+ const { platform, env } = input;
+ const pathEnv = platform === "win32" ? (env.Path ?? env.PATH) : env.PATH;
+ const which: Lookup = input.which ?? ((command) => resolveCommand(command, { platform, pathEnv: pathEnv ?? "" }));
+ const exists = input.exists ?? existsSync;
+ const isAbs = platform === "win32" ? nodePath.win32.isAbsolute : nodePath.posix.isAbsolute;
+ const resolve = (file: string): string | null => (isAbs(file) ? (exists(file) ? file : null) : which(file));
+ const pick = (file: string | null | undefined, how: ShellChoice["how"]): ShellChoice | null => {
+ if (!file || DENIED.has(shellName(file, platform))) return null;
+ const found = resolve(file);
+ return found ? { path: found, name: shellName(found, platform), how } : null;
+ };
+ // A config shell replaces $SHELL (the engine never falls back from one to the other).
+ const chosen = input.configShell ? pick(input.configShell, "config") : pick(env.SHELL, "env_shell");
+ if (chosen) return chosen;
+ if (platform === "win32") {
+ const pwsh = which("pwsh");
+ if (pwsh) return { path: pwsh, name: "pwsh", how: "pwsh" };
+ const powershell = which("powershell");
+ if (powershell) return { path: powershell, name: "powershell", how: "powershell" };
+ const git = env.OPENCODE_GIT_BASH_PATH || (() => {
+ const found = which("git");
+ return found ? nodePath.win32.join(found, "..", "..", "bin", "bash.exe") : null;
+ })();
+ if (git && exists(git)) return { path: git, name: "bash", how: "git_bash" };
+ const comspec = env.ComSpec || env.COMSPEC || "cmd.exe";
+ return { path: comspec, name: shellName(comspec, platform), how: "comspec" };
+ }
+ if (platform === "darwin") return { path: "/bin/zsh", name: "zsh", how: "zsh_default" };
+ const bash = which("bash");
+ return bash ? { path: bash, name: "bash", how: "bash_on_path" } : { path: "/bin/sh", name: "sh", how: "sh_fallback" };
+}
+
+/** The argv the engine spawns for `command` with `shell` (tool/shell.ts cmd(), Node's `shell` option). */
+export function shellArgv(shell: ShellChoice, command: string, platform: NodeJS.Platform): string[] {
+ if (platform === "win32" && POWERSHELL.has(shell.name)) return [shell.path, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command];
+ if (platform === "win32" && shell.name === "cmd") return [shell.path, "/d", "/s", "/c", `"${command}"`];
+ return [shell.path, "-c", command];
+}
+
+/** The program a command line starts: its first word, resolved on PATH when it is not a path (null for builtins and shell syntax). */
+export function commandProgram(command: string, platform: NodeJS.Platform, which: Lookup): { word: string; path: string | null } | null {
+ const word = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*("([^"]+)"|'([^']+)'|&\s*"([^"]+)"|[^\s;|&()<>]+)/.exec(command);
+ const raw = word ? (word[2] ?? word[3] ?? word[4] ?? word[1]) : null;
+ if (!raw) return null;
+ const isPath = /[\\/]/.test(raw);
+ const bare = platform === "win32" ? raw.replace(/\.(?:exe|cmd|bat|com)$/i, "") : raw;
+ return { word: raw, path: isPath ? raw : which(bare) };
+}
diff --git a/apps/server/src/context/index.ts b/apps/server/src/context/index.ts
index 78504a4d..d3613a80 100644
--- a/apps/server/src/context/index.ts
+++ b/apps/server/src/context/index.ts
@@ -60,6 +60,10 @@ import { collectShellAliases } from "./shell-aliases.js";
import { systemPackages } from "./system-packages.js";
import { runCommand, type Runner } from "./exec.js";
import { arch as osArch, release as osRelease } from "node:os";
+import nodePath, { join } from "node:path";
+import { CAPTURE_GAPS_SCHEMA, CaptureGapLog } from "./capture-gaps.js";
+import { commandProgram, engineShell, EXEC_SCHEMA, shellArgv } from "./exec-witness.js";
+import { resolveCommand } from "../command-guard.js";
export const CONTEXT_SCHEMA = 1;
const SECTION_TIMEOUT_MS = 30_000;
@@ -77,7 +81,9 @@ export type ContextEventType =
| "context.outside_file"
| "context.install"
| "context.env_turn"
- | "context.outside_files";
+ | "context.outside_files"
+ | "context.exec"
+ | "context.capture_gaps";
/** Whether capture context is on: OMNIRUSH_CAPTURE_CONTEXT=0 (or false/off/no) turns it off. */
export function captureContextEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
@@ -225,6 +231,9 @@ export class ContextCapture {
private readonly installReader: InstallLogReader | null;
private installGate: InstallLogGate = INSTALL_LOG_OFF;
private installDrainTimer: ReturnType<typeof setTimeout> | null = null;
+ /** What could not be captured, per session, on disk (capture-gaps.ts). */
+ readonly gaps: CaptureGapLog;
+ private gapsPruned = false;
constructor(private readonly options: ContextOptions) {
this.env = options.env ?? process.env;
@@ -233,6 +242,62 @@ export class ContextCapture {
this.privacy = options.privacy ?? currentPrivacy();
this.platform = options.platform ?? process.platform;
this.installReader = this.enabled && options.installLog ? new InstallLogReader(options.installLog.raw) : null;
+ this.gaps = new CaptureGapLog(this.enabled && options.cacheDir ? join(options.cacheDir, "gaps") : null);
+ }
+
+ /** Something of the session could not be captured: kept on disk, sent with the session's next gap list. */
+ noteGap(sessionId: string, gap: { what: string; why: string; recovery?: string | null; detail?: string | null }): void {
+ if (!this.enabled) return;
+ void this.gaps.note(sessionId, { ...gap, turn: this.sessions.get(sessionId)?.turn ?? null });
+ }
+
+ /** A gap noted earlier is closed (the upload went through after all, the chain moved on). */
+ resolveGap(sessionId: string, what: string): void {
+ if (this.enabled) void this.gaps.resolve(sessionId, what);
+ }
+
+ /** The session's whole gap list (`restored`: read back at a start), when it has any. */
+ private sendGaps(state: SessionContext, restored: boolean): Promise<void> {
+ return this.gaps.take(state.id).then((gaps) => {
+ if (gaps.length > 0) this.emit(state.id, "context.capture_gaps", { schema: CAPTURE_GAPS_SCHEMA, turn: state.turn, restored, open: gaps.filter((gap) => !gap.resolved_at).length, gaps });
+ });
+ }
+
+ /** `context.exec` for a shell call the engine just started (exec-witness.ts). */
+ private emitExec(state: SessionContext, event: ToolEvent, at: number): void {
+ const command = typeof event.command === "string" ? event.command : null;
+ if (!command) return;
+ const boxed = this.boxOf(state) !== null;
+ const workdir = typeof event.workdir === "string" && event.workdir.trim() ? event.workdir.trim() : null;
+ const path = this.platform === "win32" ? nodePath.win32 : nodePath.posix;
+ const cwd = workdir ? (path.isAbsolute(workdir) ? workdir : path.resolve(state.root, workdir)) : state.root;
+ const pathEnv = this.platform === "win32" ? (this.env.Path ?? this.env.PATH) : this.env.PATH;
+ const which = (name: string) => resolveCommand(name, { platform: this.platform, pathEnv: pathEnv ?? "" });
+ const shell = boxed ? { path: "boxsh", name: "boxsh", how: "box" as const } : engineShell({ platform: this.platform, env: this.env, which });
+ const program = boxed ? null : commandProgram(command, this.platform, which);
+ const tilde = (text: string | null) => (text === null ? null : tildeText(text, this.privacy));
+ this.emit(state.id, "context.exec", {
+ schema: EXEC_SCHEMA,
+ turn: state.turn,
+ call: event.callId,
+ tool: event.tool,
+ at: new Date(at).toISOString(),
+ box: boxed,
+ shell: shell ? { path: tilde(shell.path), name: shell.name, how: shell.how } : null,
+ argv: shell ? shellArgv(shell, command, this.platform).map((arg, index) => (index === 0 ? tilde(arg) : arg)) : null,
+ cwd: tilde(cwd),
+ cwd_rel: relativeTo(state.root, cwd, this.platform),
+ program: program ? { word: program.word, path: tilde(program.path) } : null,
+ os: this.platform,
+ arch: osArch(),
+ os_version: (() => {
+ try {
+ return osRelease();
+ } catch {
+ return null;
+ }
+ })(),
+ });
}
/** The session's processes: the app's process tree, and processes working in the project or its outside folders. */
@@ -253,6 +318,7 @@ export class ContextCapture {
this.options.record(sessionId, type, this.options.scrub.json(data));
} catch (error) {
this.options.log?.("warn", "capture context: event dropped", { type, error: error instanceof Error ? error.message : String(error) });
+ if (type !== "context.capture_gaps") this.noteGap(sessionId, { what: type, why: "dropped", detail: error instanceof Error ? error.message : String(error) });
}
}
@@ -305,6 +371,12 @@ export class ContextCapture {
}
this.sessions.set(sessionId, state);
this.refreshInstallGate(state);
+ // What an earlier run of this session could not capture goes out again (a crash, a restart, a resume).
+ this.track(state, this.sendGaps(state, true));
+ if (!this.gapsPruned) {
+ this.gapsPruned = true;
+ void this.gaps.prune();
+ }
this.track(state, (async () => {
if (after) await withTimeout(after, SECTION_TIMEOUT_MS);
await this.collectSessionStart(state);
@@ -591,6 +663,7 @@ export class ContextCapture {
timings[name] = Math.round(performance.now() - at);
if ("value" in result) return result.value;
errors[name] = "timeout" in result ? "timeout" : "failed";
+ this.noteGap(state.id, { what: `context.environment.${name}`, why: errors[name]! });
return undefined;
};
const { privacy } = this;
@@ -735,6 +808,8 @@ export class ContextCapture {
state.liveCalls.set(event.callId, { callId: event.callId, tool: event.tool, input: {}, status: "running", start: at, end: null, command, cwd: workdir ? workdir : state.root });
state.observer?.boost();
if (this.platform === "linux" && state.observer && command) state.socketsAtStart.set(event.callId, socketPairs().catch(() => new Map()));
+ // After the network observer's first sample: the PATH lookups never delay it.
+ this.emitExec(state, event, at);
return;
}
if (!known) return;
@@ -797,6 +872,7 @@ export class ContextCapture {
if (found && !found.ended) {
this.installTurnEnded(found);
this.outsideFilesTurnEnded(found);
+ if (this.gaps.pending(sessionId)) this.track(found, this.sendGaps(found, false));
}
runningTurns.delete(sessionId);
const state = found;
diff --git a/apps/server/src/session-archive/lifecycle.ts b/apps/server/src/session-archive/lifecycle.ts
index c2384420..36461ac3 100644
--- a/apps/server/src/session-archive/lifecycle.ts
+++ b/apps/server/src/session-archive/lifecycle.ts
@@ -73,6 +73,8 @@ export type ProjectArchiveLifecycleOptions = {
* records it in the session's upload, so no missing base goes unexplained.
*/
onProjectArchive?: (sessionId: string, outcome: ProjectArchiveOutcome) => void;
+ /** Each turn's delta as it was captured (queued, or skipped with the reason): the post-turn chain check. */
+ onTurnArchive?: (sessionId: string, result: CaptureResult) => void;
};
export type ProjectArchiveOutcome = {
@@ -217,6 +219,7 @@ export class ProjectArchiveLifecycle {
private readonly now: () => number;
private readonly onLateWrites: ((late: LateWrites) => void) | undefined;
private readonly onProjectArchive: ((sessionId: string, outcome: ProjectArchiveOutcome) => void) | undefined;
+ private readonly onTurnArchive: ((sessionId: string, result: CaptureResult) => void) | undefined;
private readonly enabled: boolean;
private readonly accountMissing: boolean;
private signedOut = false;
@@ -258,6 +261,7 @@ export class ProjectArchiveLifecycle {
this.now = options.now ?? Date.now;
this.onLateWrites = options.onLateWrites;
this.onProjectArchive = options.onProjectArchive;
+ this.onTurnArchive = options.onTurnArchive;
}
private reportArchive(sessionId: string, outcome: ProjectArchiveOutcome | null): void {
@@ -728,6 +732,11 @@ export class ProjectArchiveLifecycle {
let result: CaptureResult | null = null;
if (!finalWithoutCount) {
result = await this.archiver.captureDelta(sessionId, record.root, turns, before !== undefined ? { before } : {});
+ try {
+ this.onTurnArchive?.(sessionId, result);
+ } catch (error) {
+ this.warn("report", error);
+ }
if (result.status === "skipped" && result.reason === "stopped") record.root = null;
this.settle(result);
}
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 0baa1455..ffb95d84 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -4830,6 +4830,30 @@ export class SessionUploader {
this.permissionModeNow = mode;
}
+ /**
+ * Post-turn check of an upload (context/capture-gaps.ts): an envelope that
+ * went to the spool or was refused is a gap until it is delivered. The same
+ * names as the CLI's (workspace-sync.ts envelopeGap).
+ */
+ private envelopeGap(sessionId: string, type: string, sequence: number, outcome: "sent" | "spooled" | "refused", reason?: string): void {
+ const what = `upload.${type}.${sequence}`;
+ const context = this.contextOf(sessionId);
+ if (outcome === "sent") context?.resolveGap(sessionId, what);
+ else context?.noteGap(sessionId, { what, why: outcome, recovery: outcome === "spooled" ? "spool_retry" : null, detail: reason ?? null });
+ }
+
+ /**
+ * Post-turn check of the project archive chain (lifecycle onTurnArchive):
+ * a turn's delta that could not join the chain is a gap until one does.
+ */
+ archiveTurnChecked(sessionId: string, result: { status: string; reason?: string; detail?: string }): void {
+ const context = this.contextOf(sessionId);
+ if (result.status === "queued") context?.resolveGap(sessionId, "archive.chain");
+ else if (result.status === "skipped" && ["stopped", "failed", "unavailable", "no_base"].includes(result.reason ?? "")) {
+ context?.noteGap(sessionId, { what: "archive.chain", why: result.reason!, recovery: result.reason === "stopped" ? "chain_reopen_next_prompt" : "next_turn", detail: result.detail ?? null });
+ }
+ }
+
/** Capture context wired to this uploader: its trace, its scrub, the project archive and the archive's exclusions. */
/** The capture context a chat's events go to (a box chat's own, else this machine's). */
contextOf(sessionId: string): ContextCapture | null {
@@ -6022,6 +6046,8 @@ export class SessionUploader {
state.turnWrittenPaths.clear();
// After the turn's artifact baseline (set just below) is listed.
this.contextOf(sessionId)?.turnStarted(sessionId, Promise.resolve().then(() => state.artifactBaseline));
+ // Preflight: uploads of earlier turns still waiting go out now, before this turn adds more.
+ if ((this.contextOf(sessionId)?.gaps.openCount(sessionId, "upload.") ?? 0) > 0) void this.drainSpool().catch(() => undefined);
} else {
this.contextOf(sessionId)?.turnEnded(sessionId);
}
@@ -7208,6 +7234,7 @@ export class SessionUploader {
state.failureCount += 1;
state.lastFailureAt = new Date().toISOString();
await this.persistSession(state).catch(() => undefined);
+ this.envelopeGap(state.id, snapshotType, sequence, "spooled");
this.log("warn", "OmniRush session upload artifact spooled for retry", {
sessionId: state.id,
snapshotType,
@@ -7245,6 +7272,7 @@ export class SessionUploader {
if ((!outcome.retryable || !this.spoolDir) && !account.aborted) {
// Refused for good: the gap the server will show at this sequence is explained.
if (!outcome.retryable) state.refused = [...state.refused, `${state.segment}:${sequence}`].slice(-MAX_REFUSED_SEQUENCES);
+ this.envelopeGap(state.id, snapshotType, sequence, "refused", outcome.reason);
await this.recordLedgerOutcome(state.id, "failure").catch(() => undefined);
throw new Error(outcome.reason);
}
@@ -7252,6 +7280,7 @@ export class SessionUploader {
}
state.sentBytes += bytes;
state.lastSuccessAt = new Date().toISOString();
+ this.envelopeGap(state.id, snapshotType, sequence, "sent");
// The sequence is already on disk; this only records the outcome (stop() waits for it).
void this.persistSession(state).catch((error: unknown) => {
this.log("warn", "OmniRush session ledger update failed", {
@@ -8013,6 +8042,7 @@ export class SessionUploader {
if (outcome.ok) {
this.ownSpoolEntries.delete(entry.id);
await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
+ this.envelopeGap(entry.session_id, entry.snapshot_type, entry.sequence, "sent");
await this.recordLedgerOutcome(entry.session_id, "success").catch(() => undefined);
this.retryFailures = 0;
delivered += 1;
@@ -8032,6 +8062,7 @@ export class SessionUploader {
if (!outcome.retryable) {
await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
pending -= 1;
+ this.envelopeGap(entry.session_id, entry.snapshot_type, entry.sequence, "refused", outcome.reason);
this.log("warn", "OmniRush session upload artifact dropped from spool", {
sessionId: entry.session_id,
snapshotType: entry.snapshot_type,